Merge build/407-verdict-notes-on-the-fork: after every verdict, the answerer can read it with plain git
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents f3ca852, af7e52c · Browse files · 4 files·+1131 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+1131 added−17 removed
- tests:+804 added−4 removed
- other:+327 added−13 removed
Provenance
- Commit
cc390dd- Tree
063a2e2- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
f3ca852- Parent 2
af7e52c
4 files changed+1131 added−17 removed
modified:apps/platform/src/workflows/answer/program.ts+110 added-13 removed
18 unmodified lines19 * then. A busy repo during a land is retried by the land step's own20 * retries first. It also stops when a port step finds nothing to do (the21 * answer no longer waits on that call), as W2's in-process run does:22 * whatever moved the answer on carries it, and a run that went on from the23- * state it found could ask for the same call forever.23+ * state it found could ask for the same call forever. Wherever it stops,24+ * its last step writes the verdict, as it stands then, as the note on the25+ * answer's head in its fork (`notes`).26 */27+import { HostBusy } from "@repo/artifacts/repo-host";28+import type { RepoHost } from "@repo/artifacts/repo-host";29 import type { CheckRunner } from "@repo/checks/check-runner";30 import type { EvidenceStore } from "@repo/checks/evidence-store";31 import {32 AnswerReport,10 unmodified lines43 outcomeOf,44 } from "@repo/project/landing";45 import { Projects } from "@repo/project/projects";46 import { LaneOutcome } from "@repo/protocol/domain/answer";47+import type { Verdict } from "@repo/protocol/domain/answer";48 import type { Outcome } from "@repo/protocol/domain/outcome";49+import { CommitSha } from "@repo/protocol/ids";50 import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";45-import { Array, Data, Effect, Match, Option, Schema } from "effect";51+import {52+ Array,53+ Cause,54+ Data,55+ Effect,56+ Match,57+ Option,58+ Schedule,59+ Schema,60+} from "effect";61 62 import type { AnswerParams } from "../../answer-runs.ts";63+import { writeVerdictNote } from "../notes.ts";64 import { StepRunner } from "../step.ts";65 import type { StepRetry } from "../step.ts";66 import {67 laneOnMain,9 unmodified lines77 | CheckRunner78 | EvidenceStore79 | Lander80 | Projects81+ | RepoHost82 | StepRunner;83 84 /** A run was started for a request its project does not hold: the project never does that. */85 export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{258 unmodified lines344 } satisfies Steps;345 });346 347 /**331- * Where the verdict note on the answer's head, in its fork, is written after332- * a step that judged it (W4 407: `writeVerdictNote` in its own step). Empty333- * until then; the canonical note is written by `Lander.land` with the334- * verdict.348+ * What writing an answer's verdict note came to, kept as the step's value:349+ * a replay reads it back, and a note that could not be written never fails350+ * the run, in this run or a replay (W3 313 #5).351 */336-const notes = (_params: AnswerParams, _judged: Steps): Effect.Effect<void> =>337- Effect.void;352+const Noted = Schema.TaggedUnion({353+ /** The answer has no verdict to note: no tree of it was checked. */354+ Unjudged: {},355+ /** The note could not be written, for this reason; the verdict stands in the project. */356+ Unwritten: { reason: Schema.String },357+ Written: { changed: Schema.Boolean, notesTip: CommitSha },358+});359 360+/** How often a busy fork is asked again for the note before it is given up. */361+const noteRetry = {362+ schedule: Schedule.exponential("250 millis"),363+ times: 2,364+ while: Schema.is(HostBusy),365+};366+367+/** The verdict as `verdict` shows it: the one the checks gave, with where the answer stands now. */368+const shownVerdict = (run: AnswerRun) =>369+ Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({370+ ...made,371+ outcome: outcomeOf(run.state),372+ }));373+374+/** The answer's verdict, as it stands, written as the note on its head in its fork. */375+const noteVerdict = (params: AnswerParams) =>376+ Effect.gen(function* () {377+ const run = yield* load(params);378+379+ const judged = Option.flatMap(run, (found) =>380+ Option.map(shownVerdict(found), (verdict) => ({381+ fork: found.state.request.fork,382+ verdict,383+ }))384+ );385+386+ if (Option.isNone(judged)) {387+ return Noted.cases.Unjudged.make({});388+ }389+390+ const { fork, verdict } = judged.value;391+392+ const written = yield* writeVerdictNote({393+ fork,394+ head: verdict.head,395+ verdict,396+ }).pipe(Effect.retry(noteRetry));397+398+ return Noted.cases.Written.make(written);399+ }).pipe(400+ // Anything but an interruption is recorded: the note is bookkeeping, and401+ // a fork its answerer filled with refs of their own may break it.402+ Effect.catchCause((cause) =>403+ Cause.hasInterruptsOnly(cause)404+ ? Effect.interrupt405+ : Effect.as(406+ Effect.logWarning(407+ "an answer's verdict note was not written",408+ cause409+ ),410+ Noted.cases.Unwritten.make({411+ reason: Option.match(Cause.findErrorOption(cause), {412+ onNone: () => "defect",413+ onSome: ({ _tag }) => _tag,414+ }),415+ })416+ )417+ )418+ );419+420+/**421+ * Once the run stops, the verdict note on the answer's head in its fork422+ * (spec D22, W4 407): the verdict as `verdict` shows it, so an answerer423+ * reads where the answer stands with plain git, refused, waiting or424+ * landed. Its own step, named for the outcome the run stopped at, so a425+ * replay reads the record and a restarted run writes the same note again,426+ * which changes nothing. The canonical note is `Lander.land`'s.427+ */428+const notes = (429+ params: AnswerParams,430+ outcome: Outcome431+): Effect.Effect<void, never, AnswerPorts> =>432+ Effect.flatMap(StepRunner, ({ step }) =>433+ Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))434+ );435+436 /** The port call a step runs, under its name. */437 const portStep = (438 params: AnswerParams,439 call: Call<"Land" | "Merge" | "RunChecks">,58 unmodified lines498 if (Option.isNone(given)) {499 return next.outcome;500 }501 405- if (NextStep.guards.RunChecks(call)) {406- yield* notes(params, next);407- }408-502 return yield* carry(params, next, { ...attempts, [call._tag]: attempt });503 });504 505 /**12 unmodified lines518 if (Option.isNone(run)) {519 return yield* Effect.die(new UnknownRequest(params));520 }521 429- return yield* carry(522+ const outcome = yield* carry(523 params,524 {525 effects: callsOf(nextSteps(run.value)),526 outcome: outcomeOf(run.value.state),527 },528 { Land: 0, Merge: 0, RunChecks: 0 }529 );530+531+ yield* notes(params, outcome);532+533+ return outcome;534 });added:apps/platform/src/workflows/notes.ts+217 added
1+/**2+ * Verdict notes on an answer's fork (spec D22, §5 steps 7 and 10): after the3+ * platform judges an answer, its answerer reads the verdict with plain git,4+ *5+ * git fetch origin refs/notes/<slug>:refs/notes/<slug>6+ * git notes --ref=<slug> show <head>7+ *8+ * in a clone of their fork. One JSON note per head, the public `Verdict`9+ * encoding and nothing more (D17); a newer verdict on the same head10+ * replaces its note, and the notes on the fork's other heads stay.11+ *12+ * Everything goes through `RepoHost` (principle 6): the notes ref's tip from13+ * the ref listing (the binding resolves no custom ref, S1 #20), the earlier14+ * notes through reads, and the new note as one compare-and-swap push of the15+ * notes ref alone, never beside a branch (no atomic multi-ref push, S1 #6),16+ * never forced. Each new notes commit has the earlier one as its parent, so17+ * the same fetch, without `+`, brings the newer note to a clone that has the18+ * older. The canonical notes on landings are the Lander's (W2 212).19+ */20+import { HostBusy, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";21+import type {22+ ObjectId,23+ RepoName,24+ RepoNotFound,25+ TreeEntry,26+} from "@repo/artifacts/repo-host";27+import { noteCommit, notesRef } from "@repo/git/notes";28+import type { ScratchSource } from "@repo/git/notes";29+import { Verdict } from "@repo/protocol/domain/answer";30+import type { CommitSha } from "@repo/protocol/ids";31+import { DateTime, Effect, Option, Schema } from "effect";32+33+export { notesRef } from "@repo/git/notes";34+35+/** What writing a note came to: the notes ref's tip, and whether the write moved it. */36+export interface NoteWritten {37+ readonly notesTip: CommitSha;38+ readonly changed: boolean;39+}40+41+const encoder = new TextEncoder();42+43+const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));44+45+/** The note's bytes as `noteCommit` writes them: the verdict's JSON and a newline. */46+const noteBytes = (verdict: Verdict) =>47+ Effect.map(Effect.orDie(encodeVerdict(verdict)), (json) =>48+ encoder.encode(`${json}\n`)49+ );50+51+/** A blob holding `bytes` as git frames it: its header, then its content. */52+const framed = (bytes: Uint8Array) => {53+ const header = encoder.encode(`blob ${bytes.byteLength}\0`);54+ const raw = new Uint8Array(header.byteLength + bytes.byteLength);55+56+ raw.set(header);57+ raw.set(bytes, header.byteLength);58+59+ return raw;60+};61+62+/** The id git gives a blob holding `bytes`. */63+const blobId = (bytes: Uint8Array) =>64+ Effect.map(65+ Effect.promise(() => crypto.subtle.digest("SHA-1", framed(bytes))),66+ (digest) =>67+ [...new Uint8Array(digest)]68+ .map((byte) => byte.toString(16).padStart(2, "0"))69+ .join("")70+ );71+72+/** git's zlib stream, as a loose object holds it. */73+const deflate = (bytes: Uint8Array) =>74+ Effect.map(75+ Effect.promise(() =>76+ new Response(77+ new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))78+ ).arrayBuffer()79+ ),80+ (buffer) => new Uint8Array(buffer)81+ );82+83+/**84+ * The earlier note `blob` in the fork, put in `source` as a loose object.85+ * A push over git smart HTTP (`/binding`'s) sends every object the new86+ * notes tree names that it cannot tell the remote has, and the source87+ * holds no earlier notes commit to tell it by, so it must hold their blobs.88+ */89+const keepEarlierNote = (90+ fork: RepoName,91+ source: ScratchSource,92+ blob: ObjectId93+) =>94+ Effect.gen(function* () {95+ const bytes = yield* RepoHost.use((host) => host.readBlob(fork, blob)).pipe(96+ Effect.flatMap(97+ Option.match({98+ onNone: () => Effect.die(`${fork} has no note blob ${blob}`),99+ onSome: Effect.succeed,100+ })101+ )102+ );103+104+ const dir = `${source.gitdir}/objects/${blob.slice(0, 2)}`;105+106+ const loose = yield* deflate(framed(bytes));107+108+ // Another note's blob may have made the folder already.109+ yield* Effect.ignore(110+ Effect.tryPromise(() => source.fs.promises.mkdir(dir))111+ );112+ yield* Effect.promise(() =>113+ source.fs.promises.writeFile(`${dir}/${blob.slice(2)}`, loose)114+ );115+ });116+117+/** The notes tree's entries at `tip`, read through the port; none before the first note. */118+const notesAt = (fork: RepoName, tip: Option.Option<CommitSha>) =>119+ Option.match(tip, {120+ onNone: () => Effect.succeed<readonly TreeEntry[]>([]),121+ onSome: (sha) =>122+ Effect.gen(function* () {123+ const host = yield* RepoHost;124+ const commit = yield* host.readCommit(fork, sha);125+126+ if (Option.isNone(commit)) {127+ return yield* Effect.die(`${fork} has no notes commit ${sha}`);128+ }129+130+ const tree = yield* host.readTree(fork, commit.value.tree);131+132+ if (Option.isNone(tree)) {133+ return yield* Effect.die(`${fork} has no tree ${commit.value.tree}`);134+ }135+136+ return tree.value;137+ }),138+ });139+140+interface NoteInput {141+ readonly fork: RepoName;142+ readonly head: CommitSha;143+ readonly verdict: Verdict;144+}145+146+/**147+ * One try: the note on top of the notes ref as listed now, pushed with a148+ * compare-and-swap on that ref alone. `None` when the ref moved under it.149+ */150+const once = (input: NoteInput) =>151+ Effect.gen(function* () {152+ const host = yield* RepoHost;153+154+ const tip = Option.fromNullishOr(155+ (yield* host.refs(input.fork)).get(notesRef)156+ );157+158+ const earlier = yield* notesAt(input.fork, tip);159+ const note = yield* blobId(yield* noteBytes(input.verdict));160+161+ if (162+ Option.isSome(tip) &&163+ earlier.some(({ name, sha }) => name === input.head && sha === note)164+ ) {165+ return Option.some<NoteWritten>({ changed: false, notesTip: tip.value });166+ }167+168+ const { commit, source } = yield* noteCommit({169+ notesParent: tip,170+ now: yield* DateTime.now,171+ repo: input.fork,172+ target: input.head,173+ verdict: input.verdict,174+ });175+176+ yield* Effect.forEach(177+ earlier.filter(178+ ({ name, type }) => name !== input.head && type === "blob"179+ ),180+ ({ sha }) => keepEarlierNote(input.fork, source, sha),181+ { discard: true }182+ );183+184+ const [outcome] = yield* host.push(input.fork, source, [185+ { from: tip, ref: notesRef, to: commit },186+ ]);187+188+ return outcome !== undefined && RefOutcome.$is("Updated")(outcome)189+ ? Option.some<NoteWritten>({ changed: true, notesTip: commit })190+ : Option.none();191+ });192+193+/**194+ * `verdict` as the note on `head` in `fork`. The same verdict already there195+ * changes nothing (`changed: false`, no push). A notes ref that moved196+ * between the listing and the push is listed again and the note written on197+ * top of the move, once; one that moved under that too is `HostBusy`, for198+ * the caller to retry.199+ */200+export const writeVerdictNote = (201+ input: NoteInput202+): Effect.Effect<NoteWritten, RepoNotFound | HostBusy, RepoHost> =>203+ Effect.gen(function* () {204+ const first = yield* once(input);205+206+ if (Option.isSome(first)) {207+ return first.value;208+ }209+210+ const second = yield* once(input);211+212+ if (Option.isSome(second)) {213+ return second.value;214+ }215+216+ return yield* new HostBusy({ name: input.fork });217+ });modified:apps/platform/test/workflows/answer.test.ts+14 added-4 removed
207 unmodified lines208 const tip = yield* mainTip;209 210 expect(outcome).toStrictEqual(landedAt(tip));211 expect(yield* parentsOf(tip)).toStrictEqual([answer.opened]);212- expect(yield* namesOf(steps)).toStrictEqual(["load", ...pass(1)]);212+ expect(yield* namesOf(steps)).toStrictEqual([213+ "load",214+ ...pass(1),215+ "notes:Landed",216+ ]);217 expect(yield* landsOf(answer)).toHaveLength(1);218 }).pipe(Effect.provide(world))219 );220 293 unmodified lines514 expect(yield* namesOf(steps)).toStrictEqual([515 "load",516 ...pass(1),517 ...pass(2),518+ "notes:Landed",519 ]);520 expect(521 Option.map(yield* verdictOf(answer.api), ({ tree }) => tree)522 ).toStrictEqual(Option.some(shaOf(remerged)));87 unmodified lines610 611 expect(Exit.getSuccess(exit)).toStrictEqual(612 Option.some(Outcome.cases.Checking.make({ stage: "human" }))613 );609- expect(yield* namesOf(steps)).toStrictEqual(["load", ...pass(1)]);614+ expect(yield* namesOf(steps)).toStrictEqual([615+ "load",616+ ...pass(1),617+ "notes:Checking",618+ ]);619 expect(yield* landsOf(answer)).toHaveLength(0);620 }).pipe(Effect.provide(world))621 );622 13 unmodified lines636 "record:merge#1",637 "cheap#1",638 "checks#1",639 "record:checks#1",640+ "notes:AwaitingFinish",641 ]);642 expect(yield* landsOf(answer)).toHaveLength(0);643 }).pipe(Effect.provide(worldWith(finishRequired)))644 );245 unmodified lines890 });891 892 /** The world's ports, as the Workflow's run takes them. */893 const portsOfWorld = Effect.map(884- Effect.context<CheckRunner | EvidenceStore | Lander | Projects>(),894+ Effect.context<CheckRunner | EvidenceStore | Lander | Projects | RepoHost>(),895 Layer.succeedContext896 );897 898 describe(runWorkflow, () => {13 unmodified lines912 const tip = yield* mainTip;913 914 const recorded = yield* engine.record("record:land#1");915 906- expect(engine.ran).toStrictEqual(["load", ...pass(1)]);916+ expect(engine.ran).toStrictEqual(["load", ...pass(1), "notes:Landed"]);917 expect(isJson(outcome)).toBeTruthy();918 expect(yield* Schema.decodeEffect(OutcomeJson)(outcome)).toStrictEqual(919 landedAt(tip)920 );75 unmodified linesadded:apps/platform/test/notes.test.ts+790 added
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import {4+ HostBusy,5+ ObjectId,6+ RefName,7+ RepoHost,8+ RepoName,9+ RepoNotFound,10+} from "@repo/artifacts/repo-host";11+import type { RefUpdate } from "@repo/artifacts/repo-host";12+import { RepoHostLocal } from "@repo/artifacts/repo-host/local";13+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14+import { pushRefs } from "@repo/artifacts/repo-host/smart-http";15+import { Brand } from "@repo/brand";16+import { CheckAt } from "@repo/checks/check-runner";17+import { Verdict } from "@repo/protocol/domain/answer";18+import { Outcome } from "@repo/protocol/domain/outcome";19+import {20+ AskId,21+ CheckVersion,22+ CommitSha,23+ LandedSha,24+ LaneName,25+ PatchId,26+ ProjectName,27+ TreeSha,28+} from "@repo/protocol/ids";29+import { ChecksFailed } from "@repo/protocol/refusal";30+import { git, gitOk } from "@repo/testkit/git";31+import { gitClient } from "@repo/testkit/git-client";32+import { httpBackend } from "@repo/testkit/http-backend";33+import {34+ Context,35+ DateTime,36+ Effect,37+ Exit,38+ FileSystem,39+ Layer,40+ Option,41+ Redacted,42+ Ref,43+ Schema,44+} from "effect";45+import type { Scope } from "effect";46+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";47+import { TestClock } from "effect/testing";48+49+import { WorkerFetch } from "../src/adapters/fetch.ts";50+import { runAnswer } from "../src/workflows/answer/program.ts";51+import { notesRef, writeVerdictNote } from "../src/workflows/notes.ts";52+import { memoSteps } from "../src/workflows/step.ts";53+import type { StepRunner } from "../src/workflows/step.ts";54+import {55+ admitted,56+ askLane,57+ bobFork,58+ Checker,59+ logged,60+ mainTip,61+ parsePath,62+ project,63+ scriptProjectLanes,64+ StepLog,65+ verdictOf,66+ world,67+} from "./workflows/answer.fixtures.ts";68+import type { Admitted } from "./workflows/answer.fixtures.ts";69+70+const fork = RepoName.make("datekit--fix-week--alice");71+72+const main = RefName.make("refs/heads/main");73+74+const unit = LaneName.make("unit");75+76+/** The verdict the checks gave on `head`: refused, its `unit` lane red. */77+const refusedOn = (head: CommitSha) =>78+ Verdict.make({79+ ask: AskId.make("fix-week"),80+ at: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),81+ base: CommitSha.make("1".repeat(40)),82+ checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),83+ head,84+ heldBack: [],85+ lanes: [86+ {87+ command: "bun run test",88+ durationMs: 1200,89+ lane: unit,90+ result: "failed",91+ },92+ ],93+ outcome: Outcome.cases.Refused.make({94+ refusals: [95+ new ChecksFailed({96+ lane: unit,97+ logRef: `datekit/push-${head}-alice/unit#1`,98+ next: "bun run test",99+ }),100+ ],101+ }),102+ patchId: PatchId.make("2".repeat(64)),103+ project: ProjectName.make("datekit"),104+ stage: "checks",105+ tree: TreeSha.make("3".repeat(40)),106+ verifier: "platform",107+ });108+109+/** A later verdict on `head`: its checks passed, and it landed. */110+const landedOn = (head: CommitSha) =>111+ Verdict.make({112+ ...refusedOn(head),113+ at: DateTime.makeUnsafe("2026-10-07T12:20:00Z"),114+ lanes: [115+ {116+ command: "bun run test",117+ durationMs: 900,118+ lane: unit,119+ result: "passed",120+ },121+ ],122+ outcome: Outcome.cases.Landed.make({123+ sha: LandedSha.make("4".repeat(40)),124+ }),125+ stage: "human",126+ });127+128+const encoded = Schema.encodeEffect(Verdict);129+130+/** A note's text read back as a verdict, encoded again, to compare with what was written. */131+const asVerdict = (note: Option.Option<string>) =>132+ Effect.option(133+ Schema.decodeEffect(Schema.fromJsonString(Verdict))(134+ Option.getOrElse(note, () => "")135+ ).pipe(Effect.flatMap(encoded))136+ );137+138+/** Real `git http-backend` over the bare repos in `root`, on a local port: its origin. */139+const served = (root: string) =>140+ Effect.gen(function* () {141+ const node = yield* Effect.context<NodeServices.NodeServices>();142+143+ const app = Effect.gen(function* () {144+ const request = yield* HttpServerRequest.toWeb(145+ yield* HttpServerRequest.HttpServerRequest146+ );147+148+ return HttpServerResponse.fromWeb(149+ yield* Effect.scoped(httpBackend(root)(request)).pipe(150+ Effect.provideContext(node)151+ )152+ );153+ }).pipe(Effect.orDie);154+155+ const server = yield* Layer.build(156+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))157+ ).pipe(Effect.orDie);158+159+ const { address } = Context.get(server, HttpServer.HttpServer);160+161+ return "port" in address162+ ? `http://127.0.0.1:${address.port}`163+ : yield* Effect.die("the test server listens on a socket, not a port");164+ });165+166+/** What a test of the notes works with: the store, and a folder for clones. */167+interface DiskWorld {168+ readonly host: RepoHost["Service"];169+ readonly work: string;170+}171+172+/**173+ * Bare repos on local disk (`RepoHost` `/local`), served by real `git174+ * http-backend`, as the W3 world serves them: what the platform writes175+ * through the port, git reads from the remote.176+ */177+const diskWorld: Effect.Effect<178+ DiskWorld,179+ never,180+ NodeServices.NodeServices | Scope.Scope181+> = Effect.gen(function* () {182+ const fs = yield* FileSystem.FileSystem;183+ const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);184+ const work = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);185+186+ const hosts = yield* Layer.build(187+ RepoHostLocal.layer({ remoteBase: yield* served(root), root }).pipe(188+ Layer.provide(WorkerFetch)189+ )190+ );191+192+ return { host: Context.get(hosts, RepoHost), work };193+});194+195+/**196+ * The fork, made with two commits on its main, each an answer's head: the197+ * answerer pushed `first`, then `second` on top of it.198+ */199+const forkWithTwoHeads = (host: RepoHost["Service"]) =>200+ Effect.gen(function* () {201+ const client = yield* gitClient(memoryFs());202+203+ yield* host.create(fork).pipe(Effect.orDie);204+205+ const first = yield* client.commit("Work", [206+ ["src/week.ts", "export const week = 1;\n"],207+ ]);208+209+ const second = yield* client.commit(210+ "Work",211+ [["src/week.ts", "export const week = 2;\n"]],212+ [first]213+ );214+215+ yield* host216+ .push(fork, client.source, [217+ { from: Option.none(), ref: main, to: second },218+ ])219+ .pipe(Effect.orDie);220+221+ return { first, second };222+ });223+224+/** `verdict` written as the note on `head` in the fork, through the disk's store. */225+const write = (disk: DiskWorld, head: CommitSha, verdict: Verdict) =>226+ writeVerdictNote({ fork, head, verdict }).pipe(227+ Effect.provideService(RepoHost, disk.host)228+ );229+230+/**231+ * The disk's store, whose first `stale` listings of a repo's refs show no232+ * notes ref, as a listing made just before another write moved it would;233+ * every push it takes is counted.234+ */235+const movedUnder = (disk: DiskWorld, stale: number) =>236+ Effect.gen(function* () {237+ const listings = yield* Ref.make(0);238+ const pushes = yield* Ref.make(0);239+240+ const host = RepoHost.of({241+ ...disk.host,242+ push: (name, source, updates) =>243+ Effect.andThen(244+ Ref.update(pushes, (n) => n + 1),245+ disk.host.push(name, source, updates)246+ ),247+ refs: (name) =>248+ Effect.gen(function* () {249+ const listed = yield* Ref.getAndUpdate(listings, (n) => n + 1);250+ const refs = yield* disk.host.refs(name);251+252+ return listed < stale253+ ? new Map([...refs].filter(([ref]) => ref !== notesRef))254+ : refs;255+ }),256+ });257+258+ return { host, pushes: Ref.get(pushes) };259+ });260+261+/**262+ * The disk's store, whose pushes go over git smart HTTP to the repo's263+ * remote, as `RepoHost` `/binding` pushes to Artifacts: the push sends264+ * every object its source holds that the remote's refs do not reach.265+ */266+const overSmartHttp = (disk: DiskWorld) =>267+ RepoHost.of({268+ ...disk.host,269+ push: (name, source, updates) =>270+ Effect.flatMap(disk.host.remote(name), (remote) =>271+ pushRefs({272+ remote,273+ source,274+ token: Redacted.make("a-write-token"),275+ updates,276+ }).pipe(Effect.provide(WorkerFetch))277+ ),278+ });279+280+/** The disk's store, keeping the updates of every push it takes, in order. */281+const recordingPushes = (disk: DiskWorld) =>282+ Effect.map(Ref.make<readonly (readonly RefUpdate[])[]>([]), (pushed) => ({283+ host: RepoHost.of({284+ ...disk.host,285+ push: (name, source, updates) =>286+ Effect.andThen(287+ Ref.update(pushed, (all) => [...all, updates]),288+ disk.host.push(name, source, updates)289+ ),290+ }),291+ pushed: Ref.get(pushed),292+ }));293+294+/** Where the fork's notes ref stands, through the port. */295+const notesTip = (host: RepoHost["Service"]) =>296+ Effect.map(host.refs(fork).pipe(Effect.orDie), (refs) =>297+ Option.fromNullishOr(refs.get(notesRef))298+ );299+300+/**301+ * A clone of the fork in `work/<name>`, made the first time, then the302+ * answerer's read with nothing but git: fetch the notes ref and show the303+ * note on `head`. `None` when git shows none.304+ */305+const noteInClone = (disk: DiskWorld, name: string, head: CommitSha) =>306+ Effect.gen(function* () {307+ const fs = yield* FileSystem.FileSystem;308+ const clone = `${disk.work}/${name}`;309+310+ if (!(yield* fs.exists(clone).pipe(Effect.orDie))) {311+ const remote = yield* disk.host.remote(fork).pipe(Effect.orDie);312+313+ yield* gitOk(disk.work, "clone", "--quiet", remote, name);314+ }315+316+ const ref = `refs/notes/${Brand.slug}`;317+318+ yield* git(clone, "fetch", "--quiet", "origin", `${ref}:${ref}`);319+320+ const shown = yield* git(321+ clone,322+ "notes",323+ `--ref=${Brand.slug}`,324+ "show",325+ head326+ );327+328+ return shown.exitCode === 0 ? Option.some(shown.stdout) : Option.none();329+ });330+331+describe(writeVerdictNote, () => {332+ it.live(333+ "puts the verdict on the head in the fork, where a fresh clone reads it with plain git",334+ () =>335+ Effect.gen(function* () {336+ const disk = yield* diskWorld;337+338+ const { first: head } = yield* forkWithTwoHeads(disk.host);339+340+ const verdict = refusedOn(head);341+ const written = yield* write(disk, head, verdict);342+ const note = yield* noteInClone(disk, "fresh", head);343+344+ expect(yield* asVerdict(note)).toStrictEqual(345+ Option.some(yield* encoded(verdict))346+ );347+ expect(348+ note.pipe(Option.map((text) => text.endsWith("}\n")))349+ ).toStrictEqual(Option.some(true));350+ expect(written).toStrictEqual({351+ changed: true,352+ notesTip: Option.getOrThrow(yield* notesTip(disk.host)),353+ });354+ }).pipe(Effect.provide(NodeServices.layer)),355+ 30_000356+ );357+358+ it.live(359+ "writing the same verdict again leaves the notes ref's tip where it was",360+ () =>361+ Effect.gen(function* () {362+ const disk = yield* diskWorld;363+364+ const { first: head } = yield* forkWithTwoHeads(disk.host);365+366+ const first = yield* write(disk, head, refusedOn(head));367+ const again = yield* write(disk, head, refusedOn(head));368+369+ expect(again).toStrictEqual({370+ changed: false,371+ notesTip: first.notesTip,372+ });373+ expect(yield* notesTip(disk.host)).toStrictEqual(374+ Option.some(first.notesTip)375+ );376+ }).pipe(Effect.provide(NodeServices.layer)),377+ 30_000378+ );379+380+ it.live(381+ "a newer verdict on the same head replaces its note, the notes on other heads stay, and the same fetch brings it",382+ () =>383+ Effect.gen(function* () {384+ const disk = yield* diskWorld;385+386+ const { first, second } = yield* forkWithTwoHeads(disk.host);387+388+ yield* write(disk, first, refusedOn(first));389+ yield* write(disk, second, refusedOn(second));390+391+ const before = yield* noteInClone(disk, "answerer", first);392+ const replaced = yield* write(disk, first, landedOn(first));393+394+ expect(yield* asVerdict(before)).toStrictEqual(395+ Option.some(yield* encoded(refusedOn(first)))396+ );397+ expect(replaced.changed).toBeTruthy();398+ expect(399+ yield* asVerdict(yield* noteInClone(disk, "answerer", first))400+ ).toStrictEqual(Option.some(yield* encoded(landedOn(first))));401+ expect(402+ yield* asVerdict(yield* noteInClone(disk, "answerer", second))403+ ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));404+ }).pipe(Effect.provide(NodeServices.layer)),405+ 30_000406+ );407+408+ it.live(409+ "pushes the notes ref alone, never forced: a compare-and-swap from the tip it listed",410+ () =>411+ Effect.gen(function* () {412+ const disk = yield* diskWorld;413+414+ const { first, second } = yield* forkWithTwoHeads(disk.host);415+416+ const recording = yield* recordingPushes(disk);417+418+ const noted = (head: CommitSha) =>419+ writeVerdictNote({ fork, head, verdict: refusedOn(head) }).pipe(420+ Effect.provideService(RepoHost, recording.host)421+ );422+423+ const one = yield* noted(first);424+ const two = yield* noted(second);425+426+ expect(yield* recording.pushed).toStrictEqual([427+ [{ from: Option.none(), ref: notesRef, to: one.notesTip }],428+ [429+ {430+ from: Option.some(one.notesTip),431+ ref: notesRef,432+ to: two.notesTip,433+ },434+ ],435+ ]);436+ }).pipe(Effect.provide(NodeServices.layer)),437+ 30_000438+ );439+440+ it.live(441+ "a notes ref that moved under the write is read again, and the note goes on top of the move",442+ () =>443+ Effect.gen(function* () {444+ const disk = yield* diskWorld;445+446+ const { first, second } = yield* forkWithTwoHeads(disk.host);447+448+ const moved = yield* write(disk, first, refusedOn(first));449+ const racing = yield* movedUnder(disk, 1);450+451+ const written = yield* writeVerdictNote({452+ fork,453+ head: second,454+ verdict: refusedOn(second),455+ }).pipe(Effect.provideService(RepoHost, racing.host));456+457+ const tip = yield* notesTip(disk.host);458+459+ expect(written).toStrictEqual({460+ changed: true,461+ notesTip: Option.getOrThrow(tip),462+ });463+ expect(yield* racing.pushes).toBe(2);464+ expect(465+ Option.map(466+ yield* disk.host467+ .readCommit(fork, Option.getOrThrow(tip))468+ .pipe(Effect.orDie),469+ ({ parents }) => parents470+ )471+ ).toStrictEqual(Option.some([moved.notesTip]));472+ expect(473+ yield* asVerdict(yield* noteInClone(disk, "answerer", first))474+ ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));475+ expect(476+ yield* asVerdict(yield* noteInClone(disk, "answerer", second))477+ ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));478+ }).pipe(Effect.provide(NodeServices.layer)),479+ 30_000480+ );481+482+ it.live(483+ "a notes ref that moves under the write twice is busy, and stays where the last move put it",484+ () =>485+ Effect.gen(function* () {486+ const disk = yield* diskWorld;487+488+ const { first, second } = yield* forkWithTwoHeads(disk.host);489+490+ const moved = yield* write(disk, first, refusedOn(first));491+ const racing = yield* movedUnder(disk, Number.POSITIVE_INFINITY);492+493+ const exit = yield* Effect.exit(494+ writeVerdictNote({495+ fork,496+ head: second,497+ verdict: refusedOn(second),498+ }).pipe(Effect.provideService(RepoHost, racing.host))499+ );500+501+ expect(exit).toStrictEqual(Exit.fail(new HostBusy({ name: fork })));502+ expect(yield* racing.pushes).toBe(2);503+ expect(yield* notesTip(disk.host)).toStrictEqual(504+ Option.some(moved.notesTip)505+ );506+ }).pipe(Effect.provide(NodeServices.layer)),507+ 30_000508+ );509+510+ it.live(511+ "pushes over git smart HTTP as the binding does, the notes on other heads included",512+ () =>513+ Effect.gen(function* () {514+ const disk = yield* diskWorld;515+516+ const { first, second } = yield* forkWithTwoHeads(disk.host);517+518+ const written = yield* Effect.exit(519+ Effect.andThen(520+ writeVerdictNote({ fork, head: first, verdict: refusedOn(first) }),521+ writeVerdictNote({ fork, head: second, verdict: refusedOn(second) })522+ ).pipe(Effect.provideService(RepoHost, overSmartHttp(disk)))523+ );524+525+ expect(Exit.isSuccess(written)).toBeTruthy();526+ expect(527+ yield* asVerdict(yield* noteInClone(disk, "answerer", first))528+ ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));529+ expect(530+ yield* asVerdict(yield* noteInClone(disk, "answerer", second))531+ ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));532+ }).pipe(Effect.provide(NodeServices.layer)),533+ 30_000534+ );535+});536+537+/**538+ * The note on `head` in bob's fork, read through the port as plain git539+ * finds it: the notes ref's tip, that commit's parents, and the note's text.540+ */541+const noteOnBobsFork = (head: CommitSha) =>542+ Effect.gen(function* () {543+ const host = yield* RepoHost;544+ const tip = (yield* host.refs(bobFork).pipe(Effect.orDie)).get(notesRef);545+546+ if (tip === undefined) {547+ return Option.none();548+ }549+550+ const commit = Option.getOrThrow(551+ yield* host.readCommit(bobFork, tip).pipe(Effect.orDie)552+ );553+554+ const entries = Option.getOrThrow(555+ yield* host.readTree(bobFork, commit.tree).pipe(Effect.orDie)556+ );557+558+ const entry = entries.find(({ name }) => name === head);559+560+ const blob =561+ entry === undefined562+ ? Option.none()563+ : yield* host564+ .readBlob(bobFork, ObjectId.make(entry.sha))565+ .pipe(Effect.orDie);566+567+ return Option.some({568+ note: Option.map(blob, (bytes) => new TextDecoder().decode(bytes)),569+ parents: commit.parents,570+ tip,571+ });572+ });573+574+/**575+ * The world's store, each push to the fork's notes ref counted; with576+ * `refuse`, every such push fails as a store that lost the fork would; with577+ * `busy`, that many first ones find the fork busy with another push.578+ */579+const countingNotes = (580+ options: { readonly busy?: number; readonly refuse?: boolean } = {}581+) =>582+ Effect.gen(function* () {583+ const host = yield* RepoHost;584+ const pushes = yield* Ref.make(0);585+586+ const counted = RepoHost.of({587+ ...host,588+ push: (name, source, updates) =>589+ name === bobFork && updates.some(({ ref }) => ref === notesRef)590+ ? Effect.flatMap(591+ Ref.getAndUpdate(pushes, (n) => n + 1),592+ (before): ReturnType<typeof host.push> => {593+ if (options.refuse === true) {594+ return Effect.fail(new RepoNotFound({ name }));595+ }596+597+ return before < (options.busy ?? 0)598+ ? Effect.fail(new HostBusy({ name }))599+ : host.push(name, source, updates);600+ }601+ )602+ : host.push(name, source, updates),603+ });604+605+ return { counted, pushes: Ref.get(pushes) };606+ });607+608+/** Steps over a fresh in-memory record, as a new run of the Workflow instance has. */609+const freshSteps = Effect.flatMap(memoSteps(), (memo) =>610+ Layer.build(logged(memo))611+);612+613+/** Every lane on the merged tree green but `unit`, which fails in the file the answer changed. */614+const unitFails = (answer: Admitted) =>615+ Effect.gen(function* () {616+ yield* scriptProjectLanes(answer.merged, { result: "passed" });617+ yield* Checker.use((script) =>618+ Effect.all([619+ script.script(answer.merged, askLane, [{ result: "passed" }]),620+ script.script(answer.merged, unit, [621+ {622+ result: "failed",623+ signature: `parses ISO weeks: AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,624+ },625+ ]),626+ script.script(627+ CheckAt.cases.Commit.make({ commit: answer.opened }),628+ unit,629+ [{ result: "passed" }]630+ ),631+ ])632+ );633+ });634+635+/** Every lane on the merged tree green. */636+const allGreen = (answer: Admitted) =>637+ Effect.andThen(638+ scriptProjectLanes(answer.merged, { result: "passed" }),639+ Checker.use((script) =>640+ script.script(answer.merged, askLane, [{ result: "passed" }])641+ )642+ );643+644+/** The answer's run, over `steps`, its store `host`. */645+const runOver = (646+ answer: Admitted,647+ steps: Context.Context<StepRunner | StepLog>,648+ host: RepoHost["Service"]649+) =>650+ runAnswer({ project, requestId: answer.requestId }).pipe(651+ Effect.provide(steps),652+ Effect.provideService(RepoHost, host)653+ );654+655+/** The note `noted` holds, as a verdict encoded again. */656+const noteIn = (657+ noted: Option.Option<{ readonly note: Option.Option<string> }>658+) => asVerdict(Option.flatMap(noted, ({ note }) => note));659+660+describe(runAnswer, () => {661+ it.effect(662+ "a run its checks refuse leaves its verdict, as `verdict` shows it, as the note on the head in the fork",663+ () =>664+ Effect.gen(function* () {665+ const answer = yield* admitted();666+667+ yield* unitFails(answer);668+669+ const { counted, pushes } = yield* countingNotes();670+ const outcome = yield* runOver(answer, yield* freshSteps, counted);671+ const noted = yield* noteOnBobsFork(answer.head);672+ const verdict = Option.getOrThrow(yield* verdictOf(answer.api));673+674+ expect(Outcome.guards.Refused(outcome)).toBeTruthy();675+ expect(verdict.outcome).toStrictEqual(outcome);676+ expect(yield* noteIn(noted)).toStrictEqual(677+ Option.some(yield* encoded(verdict))678+ );679+ expect(Option.map(noted, ({ parents }) => parents)).toStrictEqual(680+ Option.some([])681+ );682+ expect(yield* pushes).toBe(1);683+ }).pipe(Effect.provide(world))684+ );685+686+ it.effect(687+ "a replay of the run writes no second notes commit, and a restarted run writes the same note, which changes nothing",688+ () =>689+ Effect.gen(function* () {690+ const answer = yield* admitted();691+692+ yield* unitFails(answer);693+694+ const { counted, pushes } = yield* countingNotes();695+ const steps = yield* freshSteps;696+ const outcome = yield* runOver(answer, steps, counted);697+ const noted = yield* noteOnBobsFork(answer.head);698+699+ // The engine replays the run from its records, the note's step too.700+ expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);701+ expect(yield* pushes).toBe(1);702+ expect(703+ (yield* StepLog.use(({ names }) => names).pipe(704+ Effect.provide(steps)705+ )).filter((name) => name.startsWith("notes:"))706+ ).toStrictEqual(["notes:Refused", "notes:Refused"]);707+708+ // A restarted run starts over a fresh record of steps.709+ const restarted = yield* runOver(answer, yield* freshSteps, counted);710+711+ expect({712+ noted: yield* noteOnBobsFork(answer.head),713+ outcome: restarted,714+ pushes: yield* pushes,715+ }).toStrictEqual({ noted, outcome, pushes: 1 });716+ }).pipe(Effect.provide(world))717+ );718+719+ it.effect("a run that lands leaves the note saying where it landed", () =>720+ Effect.gen(function* () {721+ const answer = yield* admitted();722+723+ yield* allGreen(answer);724+725+ const { counted } = yield* countingNotes();726+ const outcome = yield* runOver(answer, yield* freshSteps, counted);727+ const tip = yield* mainTip;728+ const noted = yield* noteOnBobsFork(answer.head);729+730+ expect(outcome).toStrictEqual(Outcome.cases.Landed.make({ sha: tip }));731+ expect(yield* noteIn(noted)).toStrictEqual(732+ Option.some(733+ yield* encoded(Option.getOrThrow(yield* verdictOf(answer.api)))734+ )735+ );736+ expect(737+ Option.map(yield* verdictOf(answer.api), (verdict) => verdict.outcome)738+ ).toStrictEqual(Option.some(outcome));739+ }).pipe(Effect.provide(world))740+ );741+742+ it.effect(743+ "a fork busy with another push is asked again, and the note is written",744+ () =>745+ Effect.gen(function* () {746+ const answer = yield* admitted();747+748+ yield* unitFails(answer);749+750+ const { counted, pushes } = yield* countingNotes({ busy: 1 });751+752+ // The step waits out its backoff on the TestClock: move the clock753+ // on for as long as the run goes.754+ const outcome = yield* Effect.race(755+ runOver(answer, yield* freshSteps, counted),756+ Effect.forever(TestClock.adjust("250 millis"))757+ );758+759+ const noted = yield* noteOnBobsFork(answer.head);760+761+ expect(Outcome.guards.Refused(outcome)).toBeTruthy();762+ expect(yield* pushes).toBe(2);763+ expect(yield* noteIn(noted)).toStrictEqual(764+ Option.some(765+ yield* encoded(Option.getOrThrow(yield* verdictOf(answer.api)))766+ )767+ );768+ }).pipe(Effect.provide(world))769+ );770+771+ it.effect(772+ "a note the fork refuses leaves the run's outcome as it was, in the run and in its replay",773+ () =>774+ Effect.gen(function* () {775+ const answer = yield* admitted();776+777+ yield* unitFails(answer);778+779+ const { counted, pushes } = yield* countingNotes({ refuse: true });780+ const steps = yield* freshSteps;781+ const outcome = yield* runOver(answer, steps, counted);782+783+ expect(Outcome.guards.Refused(outcome)).toBeTruthy();784+ expect(yield* pushes).toBe(1);785+ expect(yield* noteOnBobsFork(answer.head)).toStrictEqual(Option.none());786+ expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);787+ expect(yield* pushes).toBe(1);788+ }).pipe(Effect.provide(world))789+ );790+});