Skip to content
Myr

core-loop.test.ts

This file

Path

apps/platform/test/core-loop.test.ts

599 lines · 18.2 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import type { RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { CheckAt } from "@repo/checks/check-runner";5import { draftRunsInline } from "@repo/drafting/draft-runs/inline";6import type { InlinePorts } from "@repo/drafting/draft-runs/inline";7import type { DraftedAsk } from "@repo/drafting/drafted";8import { DrafterMemory } from "@repo/drafting/drafter/memory";9import { draftedFiles } from "@repo/drafting/render";10import type { Projects } from "@repo/project/projects";11import { DecisionSubject } from "@repo/protocol/domain/decision";12import { Outcome } from "@repo/protocol/domain/outcome";13import {14  AskId,15  Handle,16  LandedSha,17  LaneName,18  ProjectName,19  RepoPath,20  RequestId,21  TreeSha,22} from "@repo/protocol/ids";23import {24  AskFull,25  DirectPush,26  OutOfScope,27  StaleBase,28} from "@repo/protocol/refusal";29import { explain } from "@repo/protocol/render";30import { Array, Context, Deferred, Effect, Layer } from "effect";3132import { pushRequestId } from "../src/adapters/custody.ts";33import { coreLoopWorld } from "./world.ts";3435const project = ProjectName.make("dora/datekit");3637const parseIso = AskId.make("parse-iso");3839const parseMonth = AskId.make("parse-month");4041const redThenGreen = LaneName.make("redThenGreen");4243const mainRef = "refs/heads/main";4445const sdk = `${Brand.cliPackage}/rules`;4647const readme = "datekit: dates, parsed\n";4849const start = {50  [`${Brand.configDir}/project.ts`]: [51    `import { kinds, project } from "${sdk}";`,52    ``,53    `export default project({`,54    `  kinds: [kinds.fix],`,55    `  run: { checks: {}, test: "bun test {path}" },`,56    `});`,57    ``,58  ].join("\n"),59  [`${Brand.configDir}/vouched.td`]: "alice\nbob\n",60  "README.md": readme,61  "package.json": '{ "name": "dora/datekit", "private": true }\n',62  "src/parse.ts":63    "export const parse = (iso: string) => ({ month: 0, year: 0 });\n",64};6566const askFiles = (ask: AskId, want: string, assertion: string) =>67  Array.make(68    {69      content: [70        `import { kinds, territory } from "${sdk}";`,71        ``,72        `export default kinds.fix.ask({`,73        `  path: "test/${ask}.test.ts",`,74        `  territory: territory.paths("src/parse.ts"),`,75        `  want: "${want}",`,76        `});`,77        ``,78      ].join("\n"),79      path: RepoPath.make(`${Brand.configDir}/asks/${ask}.ask.ts`),80    },81    {82      content: [83        `import { expect, it } from "bun:test";`,84        `import { parse } from "../src/parse.ts";`,85        ``,86        `it("${want}", () => {`,87        `  ${assertion}`,88        `});`,89        ``,90      ].join("\n"),91      path: RepoPath.make(`test/${ask}.test.ts`),92    }93  );9495const isoFiles = askFiles(96  parseIso,97  "parse reads the year of an ISO date",98  'expect(parse("2026-10-07").year).toBe(2026);'99);100101const monthFiles = askFiles(102  parseMonth,103  "parse reads the month of an ISO date",104  'expect(parse("2026-10-07").month).toBe(10);'105);106107const yearRead =108  "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4)) });\n";109110const monthRead =111  "export const parse = (iso: string) => ({ month: Number(iso.slice(5, 7)), year: 0 });\n";112113const remoteLines = (stderr: string) =>114  stderr115    .split("\n")116    .filter((line) => line.startsWith("remote: "))117    .map((line) => line.trimEnd());118119const rendered = (refusals: Parameters<typeof explain>[0]) =>120  explain(refusals).map((line) => `remote: ${line}`);121122const credited = (handle: string) =>123  `${handle} <${handle}@users.${Brand.domain}>`;124125describe("the core loop, through the platform's fetch handler with real git", () => {126  it.live(127    "an ask opens red first, an out-of-scope answer is refused, the fixed answer lands with its credit, a stale one is refused, and a replay lands nothing",128    () =>129      Effect.gen(function* () {130        const world = yield* coreLoopWorld();131        const dora = world.rpc("dora");132        const alice = world.rpc("alice");133        const bob = world.rpc("bob");134        const doraGit = world.git("dora");135        const aliceGit = world.git("alice");136        const bobGit = world.git("bob");137138        const made = yield* dora.initProject({ project });139        const home = yield* doraGit.clone(made.remote);140        const first = yield* doraGit.commit(home, "Start datekit", start);141        const firstPush = yield* doraGit.push(home);142143        const afterFirst = yield* doraGit.ok(144          home,145          "ls-remote",146          "origin",147          mainRef148        );149150        yield* doraGit.commit(home, "Straight to main", {151          "README.md": "datekit, pushed around the gate\n",152        });153154        const direct = yield* doraGit.push(home);155156        expect({157          afterDirect: yield* doraGit.ok(home, "ls-remote", "origin", mainRef),158          afterFirst,159          direct: {160            exitCode: direct.exitCode,161            rejected: direct.stderr.includes("HEAD -> main (DirectPush)"),162            remote: remoteLines(direct.stderr),163          },164          first: {165            exitCode: firstPush.exitCode,166            remote: remoteLines(firstPush.stderr),167          },168          remote: made.remote,169        }).toStrictEqual({170          afterDirect: `${first}\t${mainRef}`,171          afterFirst: `${first}\t${mainRef}`,172          direct: {173            exitCode: 1,174            rejected: true,175            remote: rendered([new DirectPush({ ref: mainRef })]),176          },177          first: { exitCode: 0, remote: [] },178          remote: `${world.origin}/${project}.git`,179        });180181        yield* world.script(182          CheckAt.cases.Commit.make({183            commit: yield* world.composed(project, isoFiles),184          }),185          redThenGreen,186          ["failed", "failed"]187        );188189        const iso = yield* dora.openAsk({190          ask: parseIso,191          files: isoFiles,192          project,193        });194195        yield* world.script(196          CheckAt.cases.Commit.make({197            commit: yield* world.composed(project, monthFiles),198          }),199          redThenGreen,200          ["failed", "failed"]201        );202203        const month = yield* dora.openAsk({204          ask: parseMonth,205          files: monthFiles,206          project,207        });208209        yield* doraGit.ok(home, "fetch", "--quiet", "origin");210211        expect({212          askedBy: iso.ask.askedBy,213          files: yield* doraGit.ok(214            home,215            "show",216            "--format=",217            "--name-only",218            iso.landed219          ),220          main: yield* doraGit.ok(home, "rev-parse", "origin/main"),221          parents: yield* doraGit.ok(222            home,223            "log",224            "-2",225            "--format=%P",226            month.landed227          ),228          trailer: yield* doraGit.ok(229            home,230            "log",231            "-1",232            "--format=%(trailers:key=Asked-by,valueonly)",233            iso.landed234          ),235        }).toStrictEqual({236          askedBy: "dora",237          files: isoFiles.map(({ path }) => path).join("\n"),238          main: month.landed,239          parents: [iso.landed, first].join("\n"),240          trailer: credited("dora"),241        });242243        const { claim } = yield* alice.claim({ ask: parseIso, project });244        const full = yield* Effect.flip(bob.claim({ ask: parseIso, project }));245        const { claim: bobs } = yield* bob.claim({ ask: parseMonth, project });246247        const work = yield* aliceGit.clone(claim.remote);248249        const wide = yield* aliceGit.commit(work, "Read the year, and say so", {250          "README.md": "datekit: dates, parsed, years first\n",251          "src/parse.ts": yearRead,252        });253254        const refused = yield* aliceGit.push(work);255256        expect({257          base: claim.base,258          checkCommand: claim.checkCommand,259          fork: yield* aliceGit.ok(work, "ls-remote", "origin", mainRef),260          full,261          refused: {262            exitCode: refused.exitCode,263            rejected: refused.stderr.includes("HEAD -> main (OutOfScope)"),264            remote: remoteLines(refused.stderr),265          },266          remote: claim.remote,267        }).toStrictEqual({268          base: month.landed,269          checkCommand: `bun test test/${parseIso}.test.ts`,270          fork: `${wide}\t${mainRef}`,271          full: new AskFull({ ask: parseIso }),272          refused: {273            exitCode: 1,274            rejected: true,275            remote: rendered([276              new OutOfScope({ paths: [RepoPath.make("README.md")] }),277            ]),278          },279          remote: `${world.origin}/${project}--parse-iso--alice.git`,280        });281282        const fix = yield* aliceGit.commit(work, "Leave the readme alone", {283          "README.md": readme,284        });285286        const harnessGit = yield* world.gitWithUsername(287          "alice",288          "audit;harness=claude-code&model=haiku"289        );290291        const offered = yield* harnessGit.push(work);292        const tree = yield* aliceGit.ok(work, "rev-parse", `${fix}^{tree}`);293294        yield* world.script(295          CheckAt.cases.Tree.make({ tree: TreeSha.make(tree) }),296          redThenGreen,297          ["passed"]298        );299300        yield* world.settle();301        yield* doraGit.ok(home, "fetch", "--quiet", "origin");302303        const landed = LandedSha.make(304          yield* doraGit.ok(home, "rev-parse", "origin/main")305        );306307        const status = yield* alice.status({ project });308        const { verdict } = yield* alice.verdict({ ask: parseIso, project });309310        const { landing } = yield* world311          .rpc("anonymous")312          .landing({ project, sha: landed });313314        expect({315          assisted: yield* doraGit.ok(316            home,317            "log",318            "-1",319            "--format=%(trailers:key=Assisted-by)",320            landed321          ),322          commit: yield* doraGit.ok(323            home,324            "log",325            "-1",326            "--format=%P%n%T%n%an%n%cn",327            landed328          ),329          landing: {330            ask: landing.ask,331            assisted: landing.assisted,332            author: landing.author,333            credits: landing.credits,334            parent: landing.parent,335          },336          mirror: yield* doraGit.ok(337            home,338            "ls-remote",339            "origin",340            `${Brand.refsPrefix}landed`341          ),342          offered: {343            exitCode: offered.exitCode,344            remote: remoteLines(offered.stderr),345          },346          status: {347            answers: status.answers.map(({ head, outcome, requestId }) => [348              requestId,349              head,350              outcome,351            ]),352            claims: status.claims.map(({ ask, state }) => [ask, state]),353          },354          trailers: yield* doraGit.ok(355            home,356            "log",357            "-1",358            "--format=%(trailers:key=Asked-by,valueonly)%(trailers:key=Signed-off-by,valueonly)",359            landed360          ),361          verdict: verdict?.lanes.map(({ lane, result }) => [lane, result]),362        }).toStrictEqual({363          assisted: "Assisted-by: claude-code:haiku (claimed)",364          commit: [month.landed, tree, "alice", Brand.name].join("\n"),365          landing: {366            ask: parseIso,367            assisted: [368              { harness: "claude-code", model: "haiku", verified: false },369            ],370            author: "alice",371            credits: [372              { handle: "dora", role: "Asked-by" },373              { handle: "alice", role: "Signed-off-by" },374            ],375            parent: month.landed,376          },377          mirror: `${landed}\t${Brand.refsPrefix}landed`,378          offered: {379            exitCode: 0,380            remote: [381              `remote: checking ${parseIso} at ${fix.slice(0, 7)}; follow with ${Brand.cli} status`,382            ],383          },384          status: {385            answers: [386              [387                pushRequestId(claim.claimant, fix),388                fix,389                Outcome.cases.Landed.make({ sha: landed }),390              ],391            ],392            claims: [[parseIso, "answered"]],393          },394          trailers: `${credited("dora")}\n${credited("alice")}`,395          verdict: [[redThenGreen, "passed"]],396        });397398        const bobsWork = yield* bobGit.clone(bobs.remote);399400        const stale = yield* bobGit.commit(bobsWork, "Read the month", {401          "src/parse.ts": monthRead,402        });403404        const racing = yield* bobGit.push(bobsWork);405406        yield* world.settle();407408        const bobsAnswers = (yield* bob.status({ project })).answers;409410        const receipt = { ask: parseIso, base: claim.base, head: fix, project };411412        const replayed = yield* alice.submitAnswer({413          ...receipt,414          requestId: RequestId.make(`push-${fix}`),415        });416417        const again = yield* alice.submitAnswer({418          ...receipt,419          requestId: pushRequestId(claim.claimant, fix),420        });421422        yield* world.settle();423424        expect({425          again,426          answers: (yield* alice.status({ project })).answers.length,427          bob: bobsAnswers.map(({ head, outcome }) => [head, outcome]),428          main: yield* doraGit.ok(home, "ls-remote", "origin", mainRef),429          racing: racing.exitCode,430          replayed,431        }).toStrictEqual({432          again: replayed,433          answers: 1,434          bob: [435            [436              stale,437              Outcome.cases.Refused.make({438                refusals: [439                  new StaleBase({440                    base: bobs.base,441                    conflicts: [RepoPath.make("src/parse.ts")],442                    main: landed,443                    movedBy: [444                      {445                        ask: parseIso,446                        author: Handle.make("alice"),447                        landing: landed,448                        path: RepoPath.make("src/parse.ts"),449                      },450                    ],451                  }),452                ],453              }),454            ],455          ],456          main: `${landed}\t${mainRef}`,457          racing: 0,458          replayed: {459            ...receipt,460            outcome: Outcome.cases.Checking.make({ stage: "merge" }),461            requestId: pushRequestId(claim.claimant, fix),462          },463        });464      }),465    60_000466  );467468  it.live(469    "a want proposed with a draft runs in process, goes to the maintainer with its red-first evidence, and opens on accept with Assisted-by beside the people's credits",470    () =>471      Effect.gen(function* () {472        const drafted: DraftedAsk = {473          id: AskId.make("parse-day"),474          kind: "fix",475          rationale: "parse reads no day, so the test fails by its assertion",476          territory: [RepoPath.make("src/parse.ts")],477          test: {478            path: RepoPath.make("test/parse-day.test.ts"),479            source: [480              'import { expect, it } from "bun:test";',481              'import { parse } from "../src/parse.ts";',482              "",483              'it("parse reads the day of an ISO date", () => {',484              '  expect(Reflect.get(parse("2026-10-07"), "day")).toBe(7);',485              "});",486              "",487            ].join("\n"),488          },489          want: "parse reads the day of an ISO date",490        };491492        const ready = yield* Deferred.make<Context.Context<InlinePorts>>();493        const drafter = yield* Layer.build(DrafterMemory([drafted]));494495        const world = yield* coreLoopWorld({496          plugIn: () => ({497            project: draftRunsInline(Deferred.await(ready)),498            worker: Layer.effectDiscard(499              Effect.gen(function* () {500                const ports = yield* Effect.context<Projects | RepoHost>();501502                yield* Deferred.succeed(ready, Context.merge(ports, drafter));503              })504            ),505          }),506        });507508        const dora = world.rpc("dora");509        const alice = world.rpc("alice");510        const doraGit = world.git("dora");511512        const made = yield* dora.initProject({ project });513        const home = yield* doraGit.clone(made.remote);514515        yield* doraGit.commit(home, "Start datekit", start);516        yield* doraGit.push(home);517518        yield* world.script(519          CheckAt.cases.Commit.make({520            commit: yield* world.composed(project, draftedFiles(drafted)),521          }),522          redThenGreen,523          ["failed", "failed"]524        );525526        const proposed = yield* alice.proposeAsk({527          draft: true,528          project,529          want: drafted.want,530        });531532        const { decisions } = yield* dora.today({ project });533534        const decision = yield* Effect.fromOption(535          Array.findFirst(536            decisions,537            ({ subject }) =>538              DecisionSubject.guards.OpenProposal(subject) &&539              subject.proposal === proposed.proposal.id540          )541        );542543        const shown = yield* alice.showProposal({544          project,545          proposal: proposed.proposal.id,546        });547548        yield* dora.decide({549          choice: "accept",550          decision: decision.id,551          project,552        });553554        const { asks } = yield* alice.listAsks({ project });555556        yield* doraGit.ok(home, "fetch", "--quiet", "origin");557558        expect({559          asks: asks.map(({ ask, claimed }) => ({ ask, claimed })),560          draft: shown.proposal.draft?._tag,561          files: yield* doraGit.ok(562            home,563            "show",564            "--format=",565            "--name-only",566            "origin/main"567          ),568          proposed: proposed.proposal.draft?._tag,569          redFirst: decision.evidence.some(570            ({ label, value }) =>571              label === "red first" && value.startsWith(`${redThenGreen}: `)572          ),573          trailers: (yield* doraGit.ok(574            home,575            "log",576            "-1",577            "--format=%(trailers:only)",578            "origin/main"579          ))580            .split("\n")581            .filter((line) => /^[A-Za-z-]+-by: /u.test(line)),582        }).toStrictEqual({583          asks: [{ ask: drafted.id, claimed: false }],584          draft: "Ready",585          files: draftedFiles(drafted)586            .map(({ path }) => path)587            .join("\n"),588          proposed: "Drafting",589          redFirst: true,590          trailers: [591            `Asked-by: ${credited("alice")}`,592            `Decided-by: ${credited("dora")}`,593            `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,594          ],595        });596      }),597    60_000598  );599});