Skip to content
Myr

Leave each answer's verdict as a git note on its head in the fork, so the answerer reads it with plain git

Before adoption: this commit came in with the history the project adopted, so no landing records it.

W4 407. When an Answer run stops, the answerer can see the verdict with plain git: `git fetch origin refs/notes/<slug>:refs/notes/<slug> && git notes --ref=<slug> show <head>` in their fork prints it as JSON. - apps/platform/src/workflows/notes.ts: `writeVerdictNote({fork, head, verdict})` returns `{notesTip, changed}`. It reads the fork's notes tip from `RepoHost.refs`, because the binding resolves no custom ref (S1 #20). It builds the note with @repo/git's `noteCommit`, and pushes a compare-and-swap of the notes ref alone. The push is never forced and never shares a push with a branch (S1 #6). If the same verdict is already the note on that head (its git blob id matches), it changes nothing and pushes nothing. A newer verdict replaces the note on its head and keeps the notes on other heads. Each notes commit's parent is the previous one, so the same fetch without `+` fast-forwards. If the notes ref moves under the push, it lists the ref again and writes once more; if it moves again, the result is HostBusy. `notesRef` is re-exported from @repo/git/notes, so the ref has one home. - Found while testing: a notes push over git smart HTTP, as /binding pushes, sends every blob the new notes tree names. The scratch source has no earlier notes commit to prove the remote already holds them. So once a fork has notes on two heads, isomorphic-git fails with NotFoundError, and the test showed it. Fix: notes.ts copies each earlier note blob, read through RepoHost, into the scratch source as a loose object before the push. - answer/program.ts: the run's last step is `notes:<outcome tag>`. It writes the verdict as the `verdict` contract shows it, which is the checks' verdict with the outcome as it stands when the run stops (Refused, AwaitingFinish, Checking, Landed{sha}). This replaces the empty `notes` slot after each record:checks#n. Reason: every run end is a verdict the answerer should see, and a note written just before a land would be replaced moments later. The step name comes from recorded values, so a replay reads the step's record. A restarted run writes the same blob again, which changes nothing (principle 8). - The notes step never fails the run. Its value is `Unjudged | Written | Unwritten{reason}`, kept as a value because a spent step would kill every replay (W3 313 #5). A busy fork is retried twice with backoff. Any other failure or defect is logged and recorded. Interruptions are re-raised. `AnswerPorts` gains RepoHost, which `workerPorts` already provides. - ASSUMPTION / departure: writeVerdictNote needs only RepoHost, not `RepoHost | Fetch`. The adapters take Fetch at layer build, and /binding's push mints and revokes a write token on the fork for that one call. - Outside the territory, for verify: apps/platform/test/workflows/answer.test.ts adds the new last step to five exact step-name lists and RepoHost to `portsOfWorld`. Nothing else in that file changed (recorded in the issue's Comments). - Tests, each red by assertion first, in apps/platform/test/notes.test.ts: - over RepoHost /local behind real `git http-backend`: a fresh clone reads the note, which decodes with Verdict and equals what was written; the same verdict twice leaves the tip where it was; a Landed verdict replaces the note, the other head's note stays, and the answerer's existing clone takes it with the same fetch; a stale tip is listed again and the note is written on top of the move, while a ref that keeps moving gives HostBusy after two pushes; pushes over smart HTTP (pushRefs) work with notes on two heads. - through runAnswer over the W3 memory world: a run refused by its checks leaves the project's verdict as a single notes commit with no parent; a replay pushes nothing more, and a restarted run changes nothing; a landed run's note says Landed at the landing; a note the fork refuses leaves the outcome as it was, in the run and in its replay. - Open, in the issue's Comments: a first-merge conflict has no Verdict (no tree), so it gets no note; an outcome changed outside a run updates the note only when a later run stops; noteCommit could take over the earlier-blob copy; this has not been checked live, so 499 should read a note from a dev-stage fork. - bun run fix && bun run verify green: platform 255 tests; bytes platform 1,516,238 of 1,665,000.

authored by oscabriel · committed by oscabriel · parent 650cb35 · Browse files · 4 files+1047 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+1047 added−17 removed

  • tests:+718 added−4 removed
  • other:+329 added−13 removed

4 files+1047 added−17 removed

modified:apps/platform/src/workflows/answer/program.ts+110 added-13 removed
18 unmodified lines
19 * 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 */27import { HostBusy } from "@repo/artifacts/repo-host";28import type { RepoHost } from "@repo/artifacts/repo-host";29import type { CheckRunner } from "@repo/checks/check-runner";30import type { EvidenceStore } from "@repo/checks/evidence-store";31import {32 AnswerReport,
10 unmodified lines
43 outcomeOf,44} from "@repo/project/landing";45import { Projects } from "@repo/project/projects";46import { LaneOutcome } from "@repo/protocol/domain/answer";47import type { Verdict } from "@repo/protocol/domain/answer";48import type { Outcome } from "@repo/protocol/domain/outcome";49import { CommitSha } from "@repo/protocol/ids";50import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";45import { Array, Data, Effect, Match, Option, Schema } from "effect";51import {52 Array,53 Cause,54 Data,55 Effect,56 Match,57 Option,58 Schedule,59 Schema,60} from "effect";6162import type { AnswerParams } from "../../answer-runs.ts";63import { writeVerdictNote } from "../notes.ts";64import { StepRunner } from "../step.ts";65import type { StepRetry } from "../step.ts";66import {67 laneOnMain,
9 unmodified lines
77 | CheckRunner78 | EvidenceStore79 | Lander80 | Projects81 | RepoHost82 | StepRunner;8384/** A run was started for a request its project does not hold: the project never does that. */85export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{
258 unmodified lines
344 } satisfies Steps;345 });346347/**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 */336const notes = (_params: AnswerParams, _judged: Steps): Effect.Effect<void> =>337 Effect.void;352const 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});359360/** How often a busy fork is asked again for the note before it is given up. */361const noteRetry = {362 schedule: Schedule.exponential("250 millis"),363 times: 2,364 while: Schema.is(HostBusy),365};366367/** The verdict as `verdict` shows it: the one the checks gave, with where the answer stands now. */368const shownVerdict = (run: AnswerRun) =>369 Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({370 ...made,371 outcome: outcomeOf(run.state),372 }));373374/** The answer's verdict, as it stands, written as the note on its head in its fork. */375const noteVerdict = (params: AnswerParams) =>376 Effect.gen(function* () {377 const run = yield* load(params);378379 const judged = Option.flatMap(run, (found) =>380 Option.map(shownVerdict(found), (verdict) => ({381 fork: found.state.request.fork,382 verdict,383 }))384 );385386 if (Option.isNone(judged)) {387 return Noted.cases.Unjudged.make({});388 }389390 const { fork, verdict } = judged.value;391392 const written = yield* writeVerdictNote({393 fork,394 head: verdict.head,395 verdict,396 }).pipe(Effect.retry(noteRetry));397398 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 );419420/**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 */428const 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 );435436/** The port call a step runs, under its name. */437const portStep = (438 params: AnswerParams,439 call: Call<"Land" | "Merge" | "RunChecks">,
58 unmodified lines
498 if (Option.isNone(given)) {499 return next.outcome;500 }501405 if (NextStep.guards.RunChecks(call)) {406 yield* notes(params, next);407 }408502 return yield* carry(params, next, { ...attempts, [call._tag]: attempt });503 });504505/**
12 unmodified lines
518 if (Option.isNone(run)) {519 return yield* Effect.die(new UnknownRequest(params));520 }521429 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 );530531 yield* notes(params, outcome);532533 return outcome;534 });
added:apps/platform/src/workflows/notes.ts+219 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 */20import { HostBusy, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";21import type {22 ObjectId,23 RepoName,24 RepoNotFound,25 TreeEntry,26} from "@repo/artifacts/repo-host";27import { noteCommit, notesRef } from "@repo/git/notes";28import type { ScratchSource } from "@repo/git/notes";29import { Verdict } from "@repo/protocol/domain/answer";30import type { CommitSha } from "@repo/protocol/ids";31import { DateTime, Effect, Option, Schema } from "effect";3233export { notesRef } from "@repo/git/notes";3435/** What writing a note came to: the notes ref's tip, and whether the write moved it. */36export interface NoteWritten {37 readonly notesTip: CommitSha;38 readonly changed: boolean;39}4041const encoder = new TextEncoder();4243const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));4445/** The note's bytes as `noteCommit` writes them: the verdict's JSON and a newline. */46const noteBytes = (verdict: Verdict) =>47 Effect.map(Effect.orDie(encodeVerdict(verdict)), (json) =>48 encoder.encode(`${json}\n`)49 );5051/** The id git gives a blob holding `bytes`. */52const blobId = (bytes: Uint8Array) =>53 Effect.map(54 Effect.promise(() =>55 crypto.subtle.digest(56 "SHA-1",57 Uint8Array.from([58 ...encoder.encode(`blob ${bytes.byteLength}\0`),59 ...bytes,60 ])61 )62 ),63 (digest) =>64 [...new Uint8Array(digest)]65 .map((byte) => byte.toString(16).padStart(2, "0"))66 .join("")67 );6869/** git's zlib stream, as a loose object holds it. */70const deflate = (bytes: Uint8Array) =>71 Effect.map(72 Effect.promise(() =>73 new Response(74 new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))75 ).arrayBuffer()76 ),77 (buffer) => new Uint8Array(buffer)78 );7980/**81 * The earlier note `blob` in the fork, put in `source` as a loose object.82 * A push over git smart HTTP (`/binding`'s) sends every object the new83 * notes tree names that it cannot tell the remote has, and the source84 * holds no earlier notes commit to tell it by, so it must hold their blobs.85 */86const keepEarlierNote = (87 fork: RepoName,88 source: ScratchSource,89 blob: ObjectId90) =>91 Effect.gen(function* () {92 const bytes = yield* RepoHost.use((host) => host.readBlob(fork, blob)).pipe(93 Effect.flatMap(94 Option.match({95 onNone: () => Effect.die(`${fork} has no note blob ${blob}`),96 onSome: Effect.succeed,97 })98 )99 );100101 const dir = `${source.gitdir}/objects/${blob.slice(0, 2)}`;102103 const loose = yield* deflate(104 Uint8Array.from([105 ...encoder.encode(`blob ${bytes.byteLength}\0`),106 ...bytes,107 ])108 );109110 // Another note's blob may have made the folder already.111 yield* Effect.ignore(112 Effect.tryPromise(() => source.fs.promises.mkdir(dir))113 );114 yield* Effect.promise(() =>115 source.fs.promises.writeFile(`${dir}/${blob.slice(2)}`, loose)116 );117 });118119/** The notes tree's entries at `tip`, read through the port; none before the first note. */120const notesAt = (fork: RepoName, tip: Option.Option<CommitSha>) =>121 Option.match(tip, {122 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),123 onSome: (sha) =>124 Effect.gen(function* () {125 const host = yield* RepoHost;126 const commit = yield* host.readCommit(fork, sha);127128 if (Option.isNone(commit)) {129 return yield* Effect.die(`${fork} has no notes commit ${sha}`);130 }131132 const tree = yield* host.readTree(fork, commit.value.tree);133134 if (Option.isNone(tree)) {135 return yield* Effect.die(`${fork} has no tree ${commit.value.tree}`);136 }137138 return tree.value;139 }),140 });141142interface NoteInput {143 readonly fork: RepoName;144 readonly head: CommitSha;145 readonly verdict: Verdict;146}147148/**149 * One try: the note on top of the notes ref as listed now, pushed with a150 * compare-and-swap on that ref alone. `None` when the ref moved under it.151 */152const once = (input: NoteInput) =>153 Effect.gen(function* () {154 const host = yield* RepoHost;155156 const tip = Option.fromNullishOr(157 (yield* host.refs(input.fork)).get(notesRef)158 );159160 const earlier = yield* notesAt(input.fork, tip);161 const note = yield* blobId(yield* noteBytes(input.verdict));162163 if (164 Option.isSome(tip) &&165 earlier.some(({ name, sha }) => name === input.head && sha === note)166 ) {167 return Option.some<NoteWritten>({ changed: false, notesTip: tip.value });168 }169170 const { commit, source } = yield* noteCommit({171 notesParent: tip,172 now: yield* DateTime.now,173 repo: input.fork,174 target: input.head,175 verdict: input.verdict,176 });177178 yield* Effect.forEach(179 earlier.filter(180 ({ name, type }) => name !== input.head && type === "blob"181 ),182 ({ sha }) => keepEarlierNote(input.fork, source, sha),183 { discard: true }184 );185186 const [outcome] = yield* host.push(input.fork, source, [187 { from: tip, ref: notesRef, to: commit },188 ]);189190 return outcome !== undefined && RefOutcome.$is("Updated")(outcome)191 ? Option.some<NoteWritten>({ changed: true, notesTip: commit })192 : Option.none();193 });194195/**196 * `verdict` as the note on `head` in `fork`. The same verdict already there197 * changes nothing (`changed: false`, no push). A notes ref that moved198 * between the listing and the push is listed again and the note written on199 * top of the move, once; one that moved under that too is `HostBusy`, for200 * the caller to retry.201 */202export const writeVerdictNote = (203 input: NoteInput204): Effect.Effect<NoteWritten, RepoNotFound | HostBusy, RepoHost> =>205 Effect.gen(function* () {206 const first = yield* once(input);207208 if (Option.isSome(first)) {209 return first.value;210 }211212 const second = yield* once(input);213214 if (Option.isSome(second)) {215 return second.value;216 }217218 return yield* new HostBusy({ name: input.fork });219 });
modified:apps/platform/test/workflows/answer.test.ts+14 added-4 removed
207 unmodified lines
208 const tip = yield* mainTip;209210 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 lines
514 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 lines
610611 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 lines
636 "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 lines
890});891892/** The world's ports, as the Workflow's run takes them. */893const portsOfWorld = Effect.map(884 Effect.context<CheckRunner | EvidenceStore | Lander | Projects>(),894 Effect.context<CheckRunner | EvidenceStore | Lander | Projects | RepoHost>(),895 Layer.succeedContext896);897898describe(runWorkflow, () => {
13 unmodified lines
912 const tip = yield* mainTip;913914 const recorded = yield* engine.record("record:land#1");915906 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 lines
added:apps/platform/test/notes.test.ts+704 added
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 HostBusy,5 ObjectId,6 RefName,7 RepoHost,8 RepoName,9 RepoNotFound,10} from "@repo/artifacts/repo-host";11import { RepoHostLocal } from "@repo/artifacts/repo-host/local";12import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13import { pushRefs } from "@repo/artifacts/repo-host/smart-http";14import { Brand } from "@repo/brand";15import { CheckAt } from "@repo/checks/check-runner";16import { Verdict } from "@repo/protocol/domain/answer";17import { Outcome } from "@repo/protocol/domain/outcome";18import {19 AskId,20 CheckVersion,21 CommitSha,22 LandedSha,23 LaneName,24 PatchId,25 ProjectName,26 TreeSha,27} from "@repo/protocol/ids";28import { ChecksFailed } from "@repo/protocol/refusal";29import { git, gitOk } from "@repo/testkit/git";30import { gitClient } from "@repo/testkit/git-client";31import { httpBackend } from "@repo/testkit/http-backend";32import {33 Context,34 DateTime,35 Effect,36 Exit,37 FileSystem,38 Layer,39 Option,40 Redacted,41 Ref,42 Schema,43} from "effect";44import type { Scope } from "effect";45import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";4647import { WorkerFetch } from "../src/adapters/fetch.ts";48import { runAnswer } from "../src/workflows/answer/program.ts";49import { notesRef, writeVerdictNote } from "../src/workflows/notes.ts";50import { memoSteps } from "../src/workflows/step.ts";51import type { StepRunner } from "../src/workflows/step.ts";52import {53 admitted,54 askLane,55 bobFork,56 Checker,57 logged,58 mainTip,59 parsePath,60 project,61 scriptProjectLanes,62 StepLog,63 verdictOf,64 world,65} from "./workflows/answer.fixtures.ts";66import type { Admitted } from "./workflows/answer.fixtures.ts";6768const fork = RepoName.make("datekit--fix-week--alice");6970const main = RefName.make("refs/heads/main");7172const unit = LaneName.make("unit");7374/** The verdict the checks gave on `head`: refused, its `unit` lane red. */75const refusedOn = (head: CommitSha) =>76 Verdict.make({77 ask: AskId.make("fix-week"),78 at: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),79 base: CommitSha.make("1".repeat(40)),80 checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),81 head,82 heldBack: [],83 lanes: [84 {85 command: "bun run test",86 durationMs: 1200,87 lane: unit,88 result: "failed",89 },90 ],91 outcome: Outcome.cases.Refused.make({92 refusals: [93 new ChecksFailed({94 lane: unit,95 logRef: `datekit/push-${head}-alice/unit#1`,96 next: "bun run test",97 }),98 ],99 }),100 patchId: PatchId.make("2".repeat(64)),101 project: ProjectName.make("datekit"),102 stage: "checks",103 tree: TreeSha.make("3".repeat(40)),104 verifier: "platform",105 });106107/** A later verdict on `head`: its checks passed, and it landed. */108const landedOn = (head: CommitSha) =>109 Verdict.make({110 ...refusedOn(head),111 at: DateTime.makeUnsafe("2026-10-07T12:20:00Z"),112 lanes: [113 {114 command: "bun run test",115 durationMs: 900,116 lane: unit,117 result: "passed",118 },119 ],120 outcome: Outcome.cases.Landed.make({121 sha: LandedSha.make("4".repeat(40)),122 }),123 stage: "human",124 });125126const encoded = Schema.encodeEffect(Verdict);127128/** A note's text read back as a verdict, encoded again, to compare with what was written. */129const asVerdict = (note: Option.Option<string>) =>130 Effect.option(131 Schema.decodeEffect(Schema.fromJsonString(Verdict))(132 Option.getOrElse(note, () => "")133 ).pipe(Effect.flatMap(encoded))134 );135136/** Real `git http-backend` over the bare repos in `root`, on a local port: its origin. */137const served = (root: string) =>138 Effect.gen(function* () {139 const node = yield* Effect.context<NodeServices.NodeServices>();140141 const app = Effect.gen(function* () {142 const request = yield* HttpServerRequest.toWeb(143 yield* HttpServerRequest.HttpServerRequest144 );145146 return HttpServerResponse.fromWeb(147 yield* Effect.scoped(httpBackend(root)(request)).pipe(148 Effect.provideContext(node)149 )150 );151 }).pipe(Effect.orDie);152153 const server = yield* Layer.build(154 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))155 ).pipe(Effect.orDie);156157 const { address } = Context.get(server, HttpServer.HttpServer);158159 return "port" in address160 ? `http://127.0.0.1:${address.port}`161 : yield* Effect.die("the test server listens on a socket, not a port");162 });163164/** What a test of the notes works with: the store, and a folder for clones. */165interface DiskWorld {166 readonly host: RepoHost["Service"];167 readonly work: string;168}169170/**171 * Bare repos on local disk (`RepoHost` `/local`), served by real `git172 * http-backend`, as the W3 world serves them: what the platform writes173 * through the port, git reads from the remote.174 */175const diskWorld: Effect.Effect<176 DiskWorld,177 never,178 NodeServices.NodeServices | Scope.Scope179> = Effect.gen(function* () {180 const fs = yield* FileSystem.FileSystem;181 const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);182 const work = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);183184 const hosts = yield* Layer.build(185 RepoHostLocal.layer({ remoteBase: yield* served(root), root }).pipe(186 Layer.provide(WorkerFetch)187 )188 );189190 return { host: Context.get(hosts, RepoHost), work };191});192193/**194 * The fork, made with two commits on its main, each an answer's head: the195 * answerer pushed `first`, then `second` on top of it.196 */197const forkWithTwoHeads = (host: RepoHost["Service"]) =>198 Effect.gen(function* () {199 const client = yield* gitClient(memoryFs());200201 yield* host.create(fork).pipe(Effect.orDie);202203 const first = yield* client.commit("Work", [204 ["src/week.ts", "export const week = 1;\n"],205 ]);206207 const second = yield* client.commit(208 "Work",209 [["src/week.ts", "export const week = 2;\n"]],210 [first]211 );212213 yield* host214 .push(fork, client.source, [215 { from: Option.none(), ref: main, to: second },216 ])217 .pipe(Effect.orDie);218219 return { first, second };220 });221222/** `verdict` written as the note on `head` in the fork, through the disk's store. */223const write = (disk: DiskWorld, head: CommitSha, verdict: Verdict) =>224 writeVerdictNote({ fork, head, verdict }).pipe(225 Effect.provideService(RepoHost, disk.host)226 );227228/**229 * The disk's store, whose first `stale` listings of a repo's refs show no230 * notes ref, as a listing made just before another write moved it would;231 * every push it takes is counted.232 */233const movedUnder = (disk: DiskWorld, stale: number) =>234 Effect.gen(function* () {235 const listings = yield* Ref.make(0);236 const pushes = yield* Ref.make(0);237238 const host = RepoHost.of({239 ...disk.host,240 push: (name, source, updates) =>241 Effect.andThen(242 Ref.update(pushes, (n) => n + 1),243 disk.host.push(name, source, updates)244 ),245 refs: (name) =>246 Effect.gen(function* () {247 const listed = yield* Ref.getAndUpdate(listings, (n) => n + 1);248 const refs = yield* disk.host.refs(name);249250 return listed < stale251 ? new Map([...refs].filter(([ref]) => ref !== notesRef))252 : refs;253 }),254 });255256 return { host, pushes: Ref.get(pushes) };257 });258259/**260 * The disk's store, whose pushes go over git smart HTTP to the repo's261 * remote, as `RepoHost` `/binding` pushes to Artifacts: the push sends262 * every object its source holds that the remote's refs do not reach.263 */264const overSmartHttp = (disk: DiskWorld) =>265 RepoHost.of({266 ...disk.host,267 push: (name, source, updates) =>268 Effect.flatMap(disk.host.remote(name), (remote) =>269 pushRefs({270 remote,271 source,272 token: Redacted.make("a-write-token"),273 updates,274 }).pipe(Effect.provide(WorkerFetch))275 ),276 });277278/** Where the fork's notes ref stands, through the port. */279const notesTip = (host: RepoHost["Service"]) =>280 Effect.map(host.refs(fork).pipe(Effect.orDie), (refs) =>281 Option.fromNullishOr(refs.get(notesRef))282 );283284/**285 * A clone of the fork in `work/<name>`, made the first time, then the286 * answerer's read with nothing but git: fetch the notes ref and show the287 * note on `head`. `None` when git shows none.288 */289const noteInClone = (disk: DiskWorld, name: string, head: CommitSha) =>290 Effect.gen(function* () {291 const fs = yield* FileSystem.FileSystem;292 const clone = `${disk.work}/${name}`;293294 if (!(yield* fs.exists(clone).pipe(Effect.orDie))) {295 const remote = yield* disk.host.remote(fork).pipe(Effect.orDie);296297 yield* gitOk(disk.work, "clone", "--quiet", remote, name);298 }299300 const ref = `refs/notes/${Brand.slug}`;301302 yield* git(clone, "fetch", "--quiet", "origin", `${ref}:${ref}`);303304 const shown = yield* git(305 clone,306 "notes",307 `--ref=${Brand.slug}`,308 "show",309 head310 );311312 return shown.exitCode === 0 ? Option.some(shown.stdout) : Option.none();313 });314315describe(writeVerdictNote, () => {316 it.live(317 "puts the verdict on the head in the fork, where a fresh clone reads it with plain git",318 () =>319 Effect.gen(function* () {320 const disk = yield* diskWorld;321322 const { first: head } = yield* forkWithTwoHeads(disk.host);323324 const verdict = refusedOn(head);325 const written = yield* write(disk, head, verdict);326 const note = yield* noteInClone(disk, "fresh", head);327328 expect(yield* asVerdict(note)).toStrictEqual(329 Option.some(yield* encoded(verdict))330 );331 expect(332 note.pipe(Option.map((text) => text.endsWith("}\n")))333 ).toStrictEqual(Option.some(true));334 expect(written).toStrictEqual({335 changed: true,336 notesTip: Option.getOrThrow(yield* notesTip(disk.host)),337 });338 }).pipe(Effect.provide(NodeServices.layer)),339 30_000340 );341342 it.live(343 "writing the same verdict again leaves the notes ref's tip where it was",344 () =>345 Effect.gen(function* () {346 const disk = yield* diskWorld;347348 const { first: head } = yield* forkWithTwoHeads(disk.host);349350 const first = yield* write(disk, head, refusedOn(head));351 const again = yield* write(disk, head, refusedOn(head));352353 expect(again).toStrictEqual({354 changed: false,355 notesTip: first.notesTip,356 });357 expect(yield* notesTip(disk.host)).toStrictEqual(358 Option.some(first.notesTip)359 );360 }).pipe(Effect.provide(NodeServices.layer)),361 30_000362 );363364 it.live(365 "a newer verdict on the same head replaces its note, the notes on other heads stay, and the same fetch brings it",366 () =>367 Effect.gen(function* () {368 const disk = yield* diskWorld;369370 const { first, second } = yield* forkWithTwoHeads(disk.host);371372 yield* write(disk, first, refusedOn(first));373 yield* write(disk, second, refusedOn(second));374375 const before = yield* noteInClone(disk, "answerer", first);376 const replaced = yield* write(disk, first, landedOn(first));377378 expect(yield* asVerdict(before)).toStrictEqual(379 Option.some(yield* encoded(refusedOn(first)))380 );381 expect(replaced.changed).toBeTruthy();382 expect(383 yield* asVerdict(yield* noteInClone(disk, "answerer", first))384 ).toStrictEqual(Option.some(yield* encoded(landedOn(first))));385 expect(386 yield* asVerdict(yield* noteInClone(disk, "answerer", second))387 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));388 }).pipe(Effect.provide(NodeServices.layer)),389 30_000390 );391392 it.live(393 "a notes ref that moved under the write is read again, and the note goes on top of the move",394 () =>395 Effect.gen(function* () {396 const disk = yield* diskWorld;397398 const { first, second } = yield* forkWithTwoHeads(disk.host);399400 const moved = yield* write(disk, first, refusedOn(first));401 const racing = yield* movedUnder(disk, 1);402403 const written = yield* writeVerdictNote({404 fork,405 head: second,406 verdict: refusedOn(second),407 }).pipe(Effect.provideService(RepoHost, racing.host));408409 const tip = yield* notesTip(disk.host);410411 expect(written).toStrictEqual({412 changed: true,413 notesTip: Option.getOrThrow(tip),414 });415 expect(yield* racing.pushes).toBe(2);416 expect(417 Option.map(418 yield* disk.host419 .readCommit(fork, Option.getOrThrow(tip))420 .pipe(Effect.orDie),421 ({ parents }) => parents422 )423 ).toStrictEqual(Option.some([moved.notesTip]));424 expect(425 yield* asVerdict(yield* noteInClone(disk, "answerer", first))426 ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));427 expect(428 yield* asVerdict(yield* noteInClone(disk, "answerer", second))429 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));430 }).pipe(Effect.provide(NodeServices.layer)),431 30_000432 );433434 it.live(435 "a notes ref that moves under the write twice is busy, and stays where the last move put it",436 () =>437 Effect.gen(function* () {438 const disk = yield* diskWorld;439440 const { first, second } = yield* forkWithTwoHeads(disk.host);441442 const moved = yield* write(disk, first, refusedOn(first));443 const racing = yield* movedUnder(disk, Number.POSITIVE_INFINITY);444445 const exit = yield* Effect.exit(446 writeVerdictNote({447 fork,448 head: second,449 verdict: refusedOn(second),450 }).pipe(Effect.provideService(RepoHost, racing.host))451 );452453 expect(exit).toStrictEqual(Exit.fail(new HostBusy({ name: fork })));454 expect(yield* racing.pushes).toBe(2);455 expect(yield* notesTip(disk.host)).toStrictEqual(456 Option.some(moved.notesTip)457 );458 }).pipe(Effect.provide(NodeServices.layer)),459 30_000460 );461462 it.live(463 "pushes over git smart HTTP as the binding does, the notes on other heads included",464 () =>465 Effect.gen(function* () {466 const disk = yield* diskWorld;467468 const { first, second } = yield* forkWithTwoHeads(disk.host);469470 const written = yield* Effect.exit(471 Effect.andThen(472 writeVerdictNote({ fork, head: first, verdict: refusedOn(first) }),473 writeVerdictNote({ fork, head: second, verdict: refusedOn(second) })474 ).pipe(Effect.provideService(RepoHost, overSmartHttp(disk)))475 );476477 expect(Exit.isSuccess(written)).toBeTruthy();478 expect(479 yield* asVerdict(yield* noteInClone(disk, "answerer", first))480 ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));481 expect(482 yield* asVerdict(yield* noteInClone(disk, "answerer", second))483 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));484 }).pipe(Effect.provide(NodeServices.layer)),485 30_000486 );487});488489/**490 * The note on `head` in bob's fork, read through the port as plain git491 * finds it: the notes ref's tip, that commit's parents, and the note's text.492 */493const noteOnBobsFork = (head: CommitSha) =>494 Effect.gen(function* () {495 const host = yield* RepoHost;496 const tip = (yield* host.refs(bobFork).pipe(Effect.orDie)).get(notesRef);497498 if (tip === undefined) {499 return Option.none();500 }501502 const commit = Option.getOrThrow(503 yield* host.readCommit(bobFork, tip).pipe(Effect.orDie)504 );505506 const entries = Option.getOrThrow(507 yield* host.readTree(bobFork, commit.tree).pipe(Effect.orDie)508 );509510 const entry = entries.find(({ name }) => name === head);511512 const blob =513 entry === undefined514 ? Option.none()515 : yield* host516 .readBlob(bobFork, ObjectId.make(entry.sha))517 .pipe(Effect.orDie);518519 return Option.some({520 note: Option.map(blob, (bytes) => new TextDecoder().decode(bytes)),521 parents: commit.parents,522 tip,523 });524 });525526/**527 * The world's store, each push to the fork's notes ref counted; with528 * `refuse`, every such push fails as a store that lost the fork would.529 */530const countingNotes = (options: { readonly refuse?: boolean } = {}) =>531 Effect.gen(function* () {532 const host = yield* RepoHost;533 const pushes = yield* Ref.make(0);534535 const counted = RepoHost.of({536 ...host,537 push: (name, source, updates) =>538 name === bobFork && updates.some(({ ref }) => ref === notesRef)539 ? Effect.andThen(540 Ref.update(pushes, (n) => n + 1),541 options.refuse === true542 ? Effect.fail(new RepoNotFound({ name }))543 : host.push(name, source, updates)544 )545 : host.push(name, source, updates),546 });547548 return { counted, pushes: Ref.get(pushes) };549 });550551/** Steps over a fresh in-memory record, as a new run of the Workflow instance has. */552const freshSteps = Effect.flatMap(memoSteps(), (memo) =>553 Layer.build(logged(memo))554);555556/** Every lane on the merged tree green but `unit`, which fails in the file the answer changed. */557const unitFails = (answer: Admitted) =>558 Effect.gen(function* () {559 yield* scriptProjectLanes(answer.merged, { result: "passed" });560 yield* Checker.use((script) =>561 Effect.all([562 script.script(answer.merged, askLane, [{ result: "passed" }]),563 script.script(answer.merged, unit, [564 {565 result: "failed",566 signature: `parses ISO weeks: AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,567 },568 ]),569 script.script(570 CheckAt.cases.Commit.make({ commit: answer.opened }),571 unit,572 [{ result: "passed" }]573 ),574 ])575 );576 });577578/** Every lane on the merged tree green. */579const allGreen = (answer: Admitted) =>580 Effect.andThen(581 scriptProjectLanes(answer.merged, { result: "passed" }),582 Checker.use((script) =>583 script.script(answer.merged, askLane, [{ result: "passed" }])584 )585 );586587/** The answer's run, over `steps`, its store `host`. */588const runOver = (589 answer: Admitted,590 steps: Context.Context<StepRunner | StepLog>,591 host: RepoHost["Service"]592) =>593 runAnswer({ project, requestId: answer.requestId }).pipe(594 Effect.provide(steps),595 Effect.provideService(RepoHost, host)596 );597598/** The note `noted` holds, as a verdict encoded again. */599const noteIn = (600 noted: Option.Option<{ readonly note: Option.Option<string> }>601) => asVerdict(Option.flatMap(noted, ({ note }) => note));602603describe(runAnswer, () => {604 it.effect(605 "a run its checks refuse leaves its verdict, as `verdict` shows it, as the note on the head in the fork",606 () =>607 Effect.gen(function* () {608 const answer = yield* admitted();609610 yield* unitFails(answer);611612 const { counted, pushes } = yield* countingNotes();613 const outcome = yield* runOver(answer, yield* freshSteps, counted);614 const noted = yield* noteOnBobsFork(answer.head);615 const verdict = Option.getOrThrow(yield* verdictOf(answer.api));616617 expect(Outcome.guards.Refused(outcome)).toBeTruthy();618 expect(verdict.outcome).toStrictEqual(outcome);619 expect(yield* noteIn(noted)).toStrictEqual(620 Option.some(yield* encoded(verdict))621 );622 expect(Option.map(noted, ({ parents }) => parents)).toStrictEqual(623 Option.some([])624 );625 expect(yield* pushes).toBe(1);626 }).pipe(Effect.provide(world))627 );628629 it.effect(630 "a replay of the run writes no second notes commit, and a restarted run writes the same note, which changes nothing",631 () =>632 Effect.gen(function* () {633 const answer = yield* admitted();634635 yield* unitFails(answer);636637 const { counted, pushes } = yield* countingNotes();638 const steps = yield* freshSteps;639 const outcome = yield* runOver(answer, steps, counted);640 const noted = yield* noteOnBobsFork(answer.head);641642 // The engine replays the run from its records, the note's step too.643 expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);644 expect(yield* pushes).toBe(1);645 expect(646 (yield* StepLog.use(({ names }) => names).pipe(647 Effect.provide(steps)648 )).filter((name) => name.startsWith("notes:"))649 ).toStrictEqual(["notes:Refused", "notes:Refused"]);650651 // A restarted run starts over a fresh record of steps.652 const restarted = yield* runOver(answer, yield* freshSteps, counted);653654 expect({655 noted: yield* noteOnBobsFork(answer.head),656 outcome: restarted,657 pushes: yield* pushes,658 }).toStrictEqual({ noted, outcome, pushes: 1 });659 }).pipe(Effect.provide(world))660 );661662 it.effect("a run that lands leaves the note saying where it landed", () =>663 Effect.gen(function* () {664 const answer = yield* admitted();665666 yield* allGreen(answer);667668 const { counted } = yield* countingNotes();669 const outcome = yield* runOver(answer, yield* freshSteps, counted);670 const tip = yield* mainTip;671 const noted = yield* noteOnBobsFork(answer.head);672673 expect(outcome).toStrictEqual(Outcome.cases.Landed.make({ sha: tip }));674 expect(yield* noteIn(noted)).toStrictEqual(675 Option.some(676 yield* encoded(Option.getOrThrow(yield* verdictOf(answer.api)))677 )678 );679 expect(680 Option.map(yield* verdictOf(answer.api), (verdict) => verdict.outcome)681 ).toStrictEqual(Option.some(outcome));682 }).pipe(Effect.provide(world))683 );684685 it.effect(686 "a note the fork refuses leaves the run's outcome as it was, in the run and in its replay",687 () =>688 Effect.gen(function* () {689 const answer = yield* admitted();690691 yield* unitFails(answer);692693 const { counted, pushes } = yield* countingNotes({ refuse: true });694 const steps = yield* freshSteps;695 const outcome = yield* runOver(answer, steps, counted);696697 expect(Outcome.guards.Refused(outcome)).toBeTruthy();698 expect(yield* pushes).toBe(1);699 expect(yield* noteOnBobsFork(answer.head)).toStrictEqual(Option.none());700 expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);701 expect(yield* pushes).toBe(1);702 }).pipe(Effect.provide(world))703 );704});