Skip to content
Myr

notes.test.ts

This file

Path

apps/platform/test/notes.test.ts

742 lines · 22.4 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–69why, one step back
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 type { RefUpdate } from "@repo/artifacts/repo-host";12import { RepoHostLocal } from "@repo/artifacts/repo-host/local";13import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14import { pushRefs } from "@repo/artifacts/repo-host/smart-http";15import { Brand } from "@repo/brand";16import { CheckAt } from "@repo/checks/check-runner";17import { Verdict } from "@repo/protocol/domain/answer";18import { Outcome } from "@repo/protocol/domain/outcome";19import {20 AskId,21 CheckVersion,22 CommitSha,23 LandedSha,24 LaneName,25 PatchId,26 ProjectName,27 TreeSha,28} from "@repo/protocol/ids";29import { ChecksFailed } from "@repo/protocol/refusal";30import { git, gitOk } from "@repo/testkit/git";31import { gitClient } from "@repo/testkit/git-client";32import { httpBackend } from "@repo/testkit/http-backend";33import {34 Context,35 DateTime,36 Effect,37 Exit,38 FileSystem,39 Layer,40 Option,41 Redacted,42 Ref,43 Schema,44} from "effect";45import type { Scope } from "effect";46import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";47import { TestClock } from "effect/testing";4849import { WorkerFetch } from "../src/adapters/fetch.ts";50import { runAnswer } from "../src/workflows/answer/program.ts";51import { notesRef, writeVerdictNote } from "../src/workflows/notes.ts";52import { memoSteps } from "../src/workflows/step.ts";53import type { StepRunner } from "../src/workflows/step.ts";54import {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";68import type { Admitted } from "./workflows/answer.fixtures.ts";69

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 70why, one step back
70const fork = RepoName.make("alice__datekit--fix-week--alice");

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 71–101why, one step back
71
72const main = RefName.make("refs/heads/main");7374const unit = LaneName.make("unit");7576const refusedOn = (head: CommitSha) =>77 Verdict.make({78 ask: AskId.make("fix-week"),79 at: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),80 base: CommitSha.make("1".repeat(40)),81 checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),82 head,83 heldBack: [],84 lanes: [85 {86 command: "bun run test",87 durationMs: 1200,88 lane: unit,89 result: "failed",90 },91 ],92 outcome: Outcome.cases.Refused.make({93 refusals: [94 new ChecksFailed({95 lane: unit,96 logRef: `datekit/push-${head}-alice/unit#1`,97 next: "bun run test",98 }),99 ],100 }),101 patchId: PatchId.make("2".repeat(64)),

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 102why, one step back
102 project: ProjectName.make("alice/datekit"),

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 103–742why, one step back
103 stage: "checks",
104 tree: TreeSha.make("3".repeat(40)),105 verifier: "platform",106 });107108const 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);127128const asVerdict = (note: Option.Option<string>) =>129 Effect.option(130 Schema.decodeEffect(Schema.fromJsonString(Verdict))(131 Option.getOrElse(note, () => "")132 ).pipe(Effect.flatMap(encoded))133 );134135const served = (root: string) =>136 Effect.gen(function* () {137 const node = yield* Effect.context<NodeServices.NodeServices>();138139 const app = Effect.gen(function* () {140 const request = yield* HttpServerRequest.toWeb(141 yield* HttpServerRequest.HttpServerRequest142 );143144 return HttpServerResponse.fromWeb(145 yield* Effect.scoped(httpBackend(root)(request)).pipe(146 Effect.provideContext(node)147 )148 );149 }).pipe(Effect.orDie);150151 const server = yield* Layer.build(152 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))153 ).pipe(Effect.orDie);154155 const { address } = Context.get(server, HttpServer.HttpServer);156157 return "port" in address158 ? `http://127.0.0.1:${address.port}`159 : yield* Effect.die("the test server listens on a socket, not a port");160 });161162interface DiskWorld {163 readonly host: RepoHost["Service"];164 readonly work: string;165}166167const diskWorld: Effect.Effect<168 DiskWorld,169 never,170 NodeServices.NodeServices | Scope.Scope171> = Effect.gen(function* () {172 const fs = yield* FileSystem.FileSystem;173 const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);174 const work = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);175176 const hosts = yield* Layer.build(177 RepoHostLocal.layer({ remoteBase: yield* served(root), root }).pipe(178 Layer.provide(WorkerFetch)179 )180 );181182 return { host: Context.get(hosts, RepoHost), work };183});184185const forkWithTwoHeads = (host: RepoHost["Service"]) =>186 Effect.gen(function* () {187 const client = yield* gitClient(memoryFs());188189 yield* host.create(fork).pipe(Effect.orDie);190191 const first = yield* client.commit("Work", [192 ["src/week.ts", "export const week = 1;\n"],193 ]);194195 const second = yield* client.commit(196 "Work",197 [["src/week.ts", "export const week = 2;\n"]],198 [first]199 );200201 yield* host202 .push(fork, client.source, [203 { from: Option.none(), ref: main, to: second },204 ])205 .pipe(Effect.orDie);206207 return { first, second };208 });209210const write = (disk: DiskWorld, head: CommitSha, verdict: Verdict) =>211 writeVerdictNote({ fork, head, verdict }).pipe(212 Effect.provideService(RepoHost, disk.host)213 );214215const movedUnder = (disk: DiskWorld, stale: number) =>216 Effect.gen(function* () {217 const listings = yield* Ref.make(0);218 const pushes = yield* Ref.make(0);219220 const host = RepoHost.of({221 ...disk.host,222 push: (name, source, updates) =>223 Effect.andThen(224 Ref.update(pushes, (n) => n + 1),225 disk.host.push(name, source, updates)226 ),227 refs: (name) =>228 Effect.gen(function* () {229 const listed = yield* Ref.getAndUpdate(listings, (n) => n + 1);230 const refs = yield* disk.host.refs(name);231232 return listed < stale233 ? new Map([...refs].filter(([ref]) => ref !== notesRef))234 : refs;235 }),236 });237238 return { host, pushes: Ref.get(pushes) };239 });240241const overSmartHttp = (disk: DiskWorld) =>242 RepoHost.of({243 ...disk.host,244 push: (name, source, updates) =>245 Effect.flatMap(disk.host.remote(name), (remote) =>246 pushRefs({247 remote,248 source,249 token: Redacted.make("a-write-token"),250 updates,251 }).pipe(Effect.provide(WorkerFetch))252 ),253 });254255const recordingPushes = (disk: DiskWorld) =>256 Effect.map(Ref.make<readonly (readonly RefUpdate[])[]>([]), (pushed) => ({257 host: RepoHost.of({258 ...disk.host,259 push: (name, source, updates) =>260 Effect.andThen(261 Ref.update(pushed, (all) => [...all, updates]),262 disk.host.push(name, source, updates)263 ),264 }),265 pushed: Ref.get(pushed),266 }));267268const notesTip = (host: RepoHost["Service"]) =>269 Effect.map(host.refs(fork).pipe(Effect.orDie), (refs) =>270 Option.fromNullishOr(refs.get(notesRef))271 );272273const noteInClone = (disk: DiskWorld, name: string, head: CommitSha) =>274 Effect.gen(function* () {275 const fs = yield* FileSystem.FileSystem;276 const clone = `${disk.work}/${name}`;277278 if (!(yield* fs.exists(clone).pipe(Effect.orDie))) {279 const remote = yield* disk.host.remote(fork).pipe(Effect.orDie);280281 yield* gitOk(disk.work, "clone", "--quiet", remote, name);282 }283284 const ref = `refs/notes/${Brand.slug}`;285286 yield* git(clone, "fetch", "--quiet", "origin", `${ref}:${ref}`);287288 const shown = yield* git(289 clone,290 "notes",291 `--ref=${Brand.slug}`,292 "show",293 head294 );295296 return shown.exitCode === 0 ? Option.some(shown.stdout) : Option.none();297 });298299describe(writeVerdictNote, () => {300 it.live(301 "puts the verdict on the head in the fork, where a fresh clone reads it with plain git",302 () =>303 Effect.gen(function* () {304 const disk = yield* diskWorld;305306 const { first: head } = yield* forkWithTwoHeads(disk.host);307308 const verdict = refusedOn(head);309 const written = yield* write(disk, head, verdict);310 const note = yield* noteInClone(disk, "fresh", head);311312 expect(yield* asVerdict(note)).toStrictEqual(313 Option.some(yield* encoded(verdict))314 );315 expect(316 note.pipe(Option.map((text) => text.endsWith("}\n")))317 ).toStrictEqual(Option.some(true));318 expect(written).toStrictEqual({319 changed: true,320 notesTip: Option.getOrThrow(yield* notesTip(disk.host)),321 });322 }).pipe(Effect.provide(NodeServices.layer)),323 30_000324 );325326 it.live(327 "writing the same verdict again leaves the notes ref's tip where it was",328 () =>329 Effect.gen(function* () {330 const disk = yield* diskWorld;331332 const { first: head } = yield* forkWithTwoHeads(disk.host);333334 const first = yield* write(disk, head, refusedOn(head));335 const again = yield* write(disk, head, refusedOn(head));336337 expect(again).toStrictEqual({338 changed: false,339 notesTip: first.notesTip,340 });341 expect(yield* notesTip(disk.host)).toStrictEqual(342 Option.some(first.notesTip)343 );344 }).pipe(Effect.provide(NodeServices.layer)),345 30_000346 );347348 it.live(349 "a newer verdict on the same head replaces its note, the notes on other heads stay, and the same fetch brings it",350 () =>351 Effect.gen(function* () {352 const disk = yield* diskWorld;353354 const { first, second } = yield* forkWithTwoHeads(disk.host);355356 yield* write(disk, first, refusedOn(first));357 yield* write(disk, second, refusedOn(second));358359 const before = yield* noteInClone(disk, "answerer", first);360 const replaced = yield* write(disk, first, landedOn(first));361362 expect(yield* asVerdict(before)).toStrictEqual(363 Option.some(yield* encoded(refusedOn(first)))364 );365 expect(replaced.changed).toBeTruthy();366 expect(367 yield* asVerdict(yield* noteInClone(disk, "answerer", first))368 ).toStrictEqual(Option.some(yield* encoded(landedOn(first))));369 expect(370 yield* asVerdict(yield* noteInClone(disk, "answerer", second))371 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));372 }).pipe(Effect.provide(NodeServices.layer)),373 30_000374 );375376 it.live(377 "pushes the notes ref alone, never forced: a compare-and-swap from the tip it listed",378 () =>379 Effect.gen(function* () {380 const disk = yield* diskWorld;381382 const { first, second } = yield* forkWithTwoHeads(disk.host);383384 const recording = yield* recordingPushes(disk);385386 const noted = (head: CommitSha) =>387 writeVerdictNote({ fork, head, verdict: refusedOn(head) }).pipe(388 Effect.provideService(RepoHost, recording.host)389 );390391 const one = yield* noted(first);392 const two = yield* noted(second);393394 expect(yield* recording.pushed).toStrictEqual([395 [{ from: Option.none(), ref: notesRef, to: one.notesTip }],396 [397 {398 from: Option.some(one.notesTip),399 ref: notesRef,400 to: two.notesTip,401 },402 ],403 ]);404 }).pipe(Effect.provide(NodeServices.layer)),405 30_000406 );407408 it.live(409 "a notes ref that moved under the write is read again, and the note goes on top of the move",410 () =>411 Effect.gen(function* () {412 const disk = yield* diskWorld;413414 const { first, second } = yield* forkWithTwoHeads(disk.host);415416 const moved = yield* write(disk, first, refusedOn(first));417 const racing = yield* movedUnder(disk, 1);418419 const written = yield* writeVerdictNote({420 fork,421 head: second,422 verdict: refusedOn(second),423 }).pipe(Effect.provideService(RepoHost, racing.host));424425 const tip = yield* notesTip(disk.host);426427 expect(written).toStrictEqual({428 changed: true,429 notesTip: Option.getOrThrow(tip),430 });431 expect(yield* racing.pushes).toBe(2);432 expect(433 Option.map(434 yield* disk.host435 .readCommit(fork, Option.getOrThrow(tip))436 .pipe(Effect.orDie),437 ({ parents }) => parents438 )439 ).toStrictEqual(Option.some([moved.notesTip]));440 expect(441 yield* asVerdict(yield* noteInClone(disk, "answerer", first))442 ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));443 expect(444 yield* asVerdict(yield* noteInClone(disk, "answerer", second))445 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));446 }).pipe(Effect.provide(NodeServices.layer)),447 30_000448 );449450 it.live(451 "a notes ref that moves under the write twice is busy, and stays where the last move put it",452 () =>453 Effect.gen(function* () {454 const disk = yield* diskWorld;455456 const { first, second } = yield* forkWithTwoHeads(disk.host);457458 const moved = yield* write(disk, first, refusedOn(first));459 const racing = yield* movedUnder(disk, Number.POSITIVE_INFINITY);460461 const exit = yield* Effect.exit(462 writeVerdictNote({463 fork,464 head: second,465 verdict: refusedOn(second),466 }).pipe(Effect.provideService(RepoHost, racing.host))467 );468469 expect(exit).toStrictEqual(Exit.fail(new HostBusy({ name: fork })));470 expect(yield* racing.pushes).toBe(2);471 expect(yield* notesTip(disk.host)).toStrictEqual(472 Option.some(moved.notesTip)473 );474 }).pipe(Effect.provide(NodeServices.layer)),475 30_000476 );477478 it.live(479 "pushes over git smart HTTP as the binding does, the notes on other heads included",480 () =>481 Effect.gen(function* () {482 const disk = yield* diskWorld;483484 const { first, second } = yield* forkWithTwoHeads(disk.host);485486 const written = yield* Effect.exit(487 Effect.andThen(488 writeVerdictNote({ fork, head: first, verdict: refusedOn(first) }),489 writeVerdictNote({ fork, head: second, verdict: refusedOn(second) })490 ).pipe(Effect.provideService(RepoHost, overSmartHttp(disk)))491 );492493 expect(Exit.isSuccess(written)).toBeTruthy();494 expect(495 yield* asVerdict(yield* noteInClone(disk, "answerer", first))496 ).toStrictEqual(Option.some(yield* encoded(refusedOn(first))));497 expect(498 yield* asVerdict(yield* noteInClone(disk, "answerer", second))499 ).toStrictEqual(Option.some(yield* encoded(refusedOn(second))));500 }).pipe(Effect.provide(NodeServices.layer)),501 30_000502 );503});504505const noteOnBobsFork = (head: CommitSha) =>506 Effect.gen(function* () {507 const host = yield* RepoHost;508 const tip = (yield* host.refs(bobFork).pipe(Effect.orDie)).get(notesRef);509510 if (tip === undefined) {511 return Option.none();512 }513514 const commit = Option.getOrThrow(515 yield* host.readCommit(bobFork, tip).pipe(Effect.orDie)516 );517518 const entries = Option.getOrThrow(519 yield* host.readTree(bobFork, commit.tree).pipe(Effect.orDie)520 );521522 const entry = entries.find(({ name }) => name === head);523524 const blob =525 entry === undefined526 ? Option.none()527 : yield* host528 .readBlob(bobFork, ObjectId.make(entry.sha))529 .pipe(Effect.orDie);530531 return Option.some({532 note: Option.map(blob, (bytes) => new TextDecoder().decode(bytes)),533 parents: commit.parents,534 tip,535 });536 });537538const countingNotes = (539 options: { readonly busy?: number; readonly refuse?: boolean } = {}540) =>541 Effect.gen(function* () {542 const host = yield* RepoHost;543 const pushes = yield* Ref.make(0);544545 const counted = RepoHost.of({546 ...host,547 push: (name, source, updates) =>548 name === bobFork && updates.some(({ ref }) => ref === notesRef)549 ? Effect.flatMap(550 Ref.getAndUpdate(pushes, (n) => n + 1),551 (before): ReturnType<typeof host.push> => {552 if (options.refuse === true) {553 return Effect.fail(new RepoNotFound({ name }));554 }555556 return before < (options.busy ?? 0)557 ? Effect.fail(new HostBusy({ name }))558 : host.push(name, source, updates);559 }560 )561 : host.push(name, source, updates),562 });563564 return { counted, pushes: Ref.get(pushes) };565 });566567const freshSteps = Effect.flatMap(memoSteps(), (memo) =>568 Layer.build(logged(memo))569);570571const unitFails = (answer: Admitted) =>572 Effect.gen(function* () {573 yield* scriptProjectLanes(answer.merged, { result: "passed" });574 yield* Checker.use((script) =>575 Effect.all([576 script.script(answer.merged, askLane, [{ result: "passed" }]),577 script.script(answer.merged, unit, [578 {579 result: "failed",580 signature: `parses ISO weeks: AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,581 },582 ]),583 script.script(584 CheckAt.cases.Commit.make({ commit: answer.opened }),585 unit,586 [{ result: "passed" }]587 ),588 ])589 );590 });591592const allGreen = (answer: Admitted) =>593 Effect.andThen(594 scriptProjectLanes(answer.merged, { result: "passed" }),595 Checker.use((script) =>596 script.script(answer.merged, askLane, [{ result: "passed" }])597 )598 );599600const runOver = (601 answer: Admitted,602 steps: Context.Context<StepRunner | StepLog>,603 host: RepoHost["Service"]604) =>605 runAnswer({ project, requestId: answer.requestId }).pipe(606 Effect.provide(steps),607 Effect.provideService(RepoHost, host)608 );609610const noteIn = (611 noted: Option.Option<{ readonly note: Option.Option<string> }>612) => asVerdict(Option.flatMap(noted, ({ note }) => note));613614describe(runAnswer, () => {615 it.effect(616 "a run its checks refuse leaves its verdict, as `verdict` shows it, as the note on the head in the fork",617 () =>618 Effect.gen(function* () {619 const answer = yield* admitted();620621 yield* unitFails(answer);622623 const { counted, pushes } = yield* countingNotes();624 const outcome = yield* runOver(answer, yield* freshSteps, counted);625 const noted = yield* noteOnBobsFork(answer.head);626 const verdict = Option.getOrThrow(yield* verdictOf(answer.api));627628 expect(Outcome.guards.Refused(outcome)).toBeTruthy();629 expect(verdict.outcome).toStrictEqual(outcome);630 expect(yield* noteIn(noted)).toStrictEqual(631 Option.some(yield* encoded(verdict))632 );633 expect(Option.map(noted, ({ parents }) => parents)).toStrictEqual(634 Option.some([])635 );636 expect(yield* pushes).toBe(1);637 }).pipe(Effect.provide(world))638 );639640 it.effect(641 "a replay of the run writes no second notes commit, and a restarted run writes the same note, which changes nothing",642 () =>643 Effect.gen(function* () {644 const answer = yield* admitted();645646 yield* unitFails(answer);647648 const { counted, pushes } = yield* countingNotes();649 const steps = yield* freshSteps;650 const outcome = yield* runOver(answer, steps, counted);651 const noted = yield* noteOnBobsFork(answer.head);652653 expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);654 expect(yield* pushes).toBe(1);655 expect(656 (yield* StepLog.use(({ names }) => names).pipe(657 Effect.provide(steps)658 )).filter((name) => name.startsWith("notes:"))659 ).toStrictEqual(["notes:Refused", "notes:Refused"]);660661 const restarted = yield* runOver(answer, yield* freshSteps, counted);662663 expect({664 noted: yield* noteOnBobsFork(answer.head),665 outcome: restarted,666 pushes: yield* pushes,667 }).toStrictEqual({ noted, outcome, pushes: 1 });668 }).pipe(Effect.provide(world))669 );670671 it.effect("a run that lands leaves the note saying where it landed", () =>672 Effect.gen(function* () {673 const answer = yield* admitted();674675 yield* allGreen(answer);676677 const { counted } = yield* countingNotes();678 const outcome = yield* runOver(answer, yield* freshSteps, counted);679 const tip = yield* mainTip;680 const noted = yield* noteOnBobsFork(answer.head);681682 expect(outcome).toStrictEqual(Outcome.cases.Landed.make({ sha: tip }));683 expect(yield* noteIn(noted)).toStrictEqual(684 Option.some(685 yield* encoded(Option.getOrThrow(yield* verdictOf(answer.api)))686 )687 );688 expect(689 Option.map(yield* verdictOf(answer.api), (verdict) => verdict.outcome)690 ).toStrictEqual(Option.some(outcome));691 }).pipe(Effect.provide(world))692 );693694 it.effect(695 "a fork busy with another push is asked again, and the note is written",696 () =>697 Effect.gen(function* () {698 const answer = yield* admitted();699700 yield* unitFails(answer);701702 const { counted, pushes } = yield* countingNotes({ busy: 1 });703704 // The step waits out its backoff on the TestClock: move the clock705 // on for as long as the run goes.706 const outcome = yield* Effect.race(707 runOver(answer, yield* freshSteps, counted),708 Effect.forever(TestClock.adjust("250 millis"))709 );710711 const noted = yield* noteOnBobsFork(answer.head);712713 expect(Outcome.guards.Refused(outcome)).toBeTruthy();714 expect(yield* pushes).toBe(2);715 expect(yield* noteIn(noted)).toStrictEqual(716 Option.some(717 yield* encoded(Option.getOrThrow(yield* verdictOf(answer.api)))718 )719 );720 }).pipe(Effect.provide(world))721 );722723 it.effect(724 "a note the fork refuses leaves the run's outcome as it was, in the run and in its replay",725 () =>726 Effect.gen(function* () {727 const answer = yield* admitted();728729 yield* unitFails(answer);730731 const { counted, pushes } = yield* countingNotes({ refuse: true });732 const steps = yield* freshSteps;733 const outcome = yield* runOver(answer, steps, counted);734735 expect(Outcome.guards.Refused(outcome)).toBeTruthy();736 expect(yield* pushes).toBe(1);737 expect(yield* noteOnBobsFork(answer.head)).toStrictEqual(Option.none());738 expect(yield* runOver(answer, steps, counted)).toStrictEqual(outcome);739 expect(yield* pushes).toBe(1);740 }).pipe(Effect.provide(world))741 );742});