Skip to content
Myr

ratchet-loop.test.ts

This file

Path

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

832 lines · 23.9 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { CheckAt } from "@repo/checks/check-runner";4import { Verdict } from "@repo/protocol/domain/answer";5import { DecisionSubject } from "@repo/protocol/domain/decision";6import type { Choice } from "@repo/protocol/domain/decision";7import { Outcome } from "@repo/protocol/domain/outcome";8import {9  AskId,10  LaneName,11  ProjectName,12  RatchetName,13  RepoPath,14  TreeSha,15} from "@repo/protocol/ids";16import type { CommitSha } from "@repo/protocol/ids";17import { Weakened } from "@repo/protocol/refusal";18import { Array, Effect, Order, Schema } from "effect";1920import { pushRequestId } from "../src/adapters/custody.ts";21import { coreLoopWorld } from "./world.ts";22import type { CoreLoopWorld, GitClient, Someone } from "./world.ts";2324const project = ProjectName.make("dora/burrow");2526const noAnyInParser = AskId.make("no-any-in-parser");2728const formatIso = AskId.make("format-iso");2930const decodeRaw = AskId.make("decode-raw");3132const ratchet = RatchetName.make("no-explicit-any");3334const ratchetLane = LaneName.make(ratchet);3536const lintToZero = LaneName.make("lintToZero");3738const redThenGreen = LaneName.make("redThenGreen");3940const lint = "oxlint --format json";4142const rule = "typescript/no-explicit-any";4344const sdk = `${Brand.cliPackage}/rules`;4546const parsePath = "packages/parser/src/parse.ts";4748const formatPath = "packages/format/src/format.ts";4950const codecPath = "packages/parser/src/codec.ts";5152const anyParse =53  "export const parse = (s: any): any => ({ year: Number(s as any) });\n";5455const anyFormat = "export const format = (d: any, f: any) => String(d);\n";5657const start = {58  [`${Brand.configDir}/project.ts`]: [59    `import { check, kinds, project } from "${sdk}";`,60    ``,61    `export default project({`,62    `  kinds: [kinds.fix, kinds.lintToZero],`,63    `  ratchets: {`,64    `    "${ratchet}": check.ratchet.count("${lint}", { rule: "${rule}" }),`,65    `  },`,66    `  run: { checks: {}, test: "bun test {path}" },`,67    `});`,68    ``,69  ].join("\n"),70  [`${Brand.configDir}/vouched.td`]: "alice\nbob\n",71  "package.json":72    '{ "name": "burrow", "private": true, "workspaces": ["packages/*"] }\n',73  "packages/format/package.json": '{ "name": "format" }\n',74  "packages/parser/package.json": '{ "name": "parser" }\n',75  [formatPath]: anyFormat,76  [parsePath]: anyParse,77};7879const lintFiles = Array.make({80  content: [81    `import { kinds, territory } from "${sdk}";`,82    ``,83    `export default kinds.lintToZero.ask({`,84    `  command: "${lint}",`,85    `  rule: "${rule}",`,86    `  territory: territory.package("parser"),`,87    `  want: "parser types every value it reads",`,88    `});`,89    ``,90  ].join("\n"),91  path: RepoPath.make(`${Brand.configDir}/asks/${noAnyInParser}.ask.ts`),92});9394const fixFiles = (95  ask: AskId,96  module: string,97  want: string,98  subject: {99    readonly file: string;100    readonly name: string;101    readonly call: string;102    readonly is: string;103  }104) =>105  Array.make(106    {107      content: [108        `import { kinds, territory } from "${sdk}";`,109        ``,110        `export default kinds.fix.ask({`,111        `  path: "packages/${module}/test/${ask}.test.ts",`,112        `  territory: territory.package("${module}"),`,113        `  want: "${want}",`,114        `});`,115        ``,116      ].join("\n"),117      path: RepoPath.make(`${Brand.configDir}/asks/${ask}.ask.ts`),118    },119    {120      content: [121        `import { expect, it } from "bun:test";`,122        `import { ${subject.name} } from "../src/${subject.file}";`,123        ``,124        `it("${want}", () => {`,125        `  expect(${subject.call}).toBe(${subject.is});`,126        `});`,127        ``,128      ].join("\n"),129      path: RepoPath.make(`packages/${module}/test/${ask}.test.ts`),130    }131  );132133const isoFiles = fixFiles(formatIso, "format", "format writes ISO dates", {134  call: "format(new Date(0))",135  file: "format.ts",136  is: '"1970-01-01"',137  name: "format",138});139140const rawFiles = fixFiles(decodeRaw, "parser", "parser decodes raw input", {141  call: 'decode("2026")',142  file: "codec.ts",143  is: '"2026"',144  name: "decode",145});146147const anyAt = (filename: string, line: number) => ({148  code: "typescript(no-explicit-any)",149  filename,150  help: "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.",151  labels: [{ span: { column: 1, length: 3, line, offset: 0 } }],152  message: "Unexpected `any`. Specify a different type.",153  severity: "error",154  url: "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html",155});156157const oxlintReport = (158  findings: readonly (readonly [path: string, line: number])[]159) =>160  JSON.stringify({161    diagnostics: findings.map(([path, line]) => anyAt(path, line)),162    number_of_files: 4,163    number_of_rules: 1,164    start_time: 0.01,165    threads_count: 4,166  });167168const mainFindings = [169  [formatPath, 1],170  [formatPath, 1],171  [parsePath, 1],172  [parsePath, 1],173  [parsePath, 1],174] as const;175176const formatOnly = [177  [formatPath, 1],178  [formatPath, 1],179] as const;180181const remoteLines = (stderr: string) =>182  stderr183    .split("\n")184    .filter((line) => line.startsWith("remote: "))185    .map((line) => line.trimEnd());186187const credited = (handle: string) =>188  `${handle} <${handle}@users.${Brand.domain}>`;189190type Baseline = readonly [ratchet: string, territory: string, count: number];191192const baselines = (world: CoreLoopWorld) =>193  Effect.map(world.ratchets(project), (rows) =>194    Array.sort(195      rows.map(({ count, ratchet: name, territory }): Baseline => [196        name,197        territory,198        count,199      ]),200      Order.mapInput(Order.String, ([name, territory]: Baseline) =>201        [name, territory].join(" ")202      )203    )204  );205206const treeOf = (git: GitClient, work: string, head: CommitSha) =>207  Effect.map(git.ok(work, "rev-parse", `${head}^{tree}`), (tree) =>208    CheckAt.cases.Tree.make({ tree: TreeSha.make(tree) })209  );210211const noteOn = (git: GitClient, work: string, head: CommitSha) =>212  Effect.gen(function* () {213    const ref = `refs/notes/${Brand.slug}`;214215    yield* git.ok(work, "fetch", "--quiet", "origin", `${ref}:${ref}`);216217    const shown = yield* git.ok(218      work,219      "notes",220      `--ref=${Brand.slug}`,221      "show",222      head223    );224225    return yield* Schema.decodeEffect(Schema.fromJsonString(Verdict))(226      shown227    ).pipe(Effect.orDie);228  });229230const answer = (231  world: CoreLoopWorld,232  as: Someone,233  git: GitClient,234  input: {235    readonly ask: AskId;236    readonly files: Readonly<Record<string, string>>;237  }238) =>239  Effect.gen(function* () {240    const { claim } = yield* world.rpc(as).claim({ ask: input.ask, project });241    const work = yield* git.clone(claim.remote);242    const head = yield* git.commit(work, `Answer ${input.ask}`, input.files);243    const pushed = yield* git.push(work);244    const tree = yield* treeOf(git, work, head);245246    return { claim, head, pushed, tree, work };247  });248249const scriptAnswer = (250  world: CoreLoopWorld,251  tree: CheckAt,252  input: {253    readonly askLane: LaneName;254    readonly askResult: "passed" | "failed";255    readonly findings: readonly (readonly [string, number])[];256  }257) =>258  Effect.gen(function* () {259    const report = oxlintReport(input.findings);260    const linted = input.findings.length === 0 ? "passed" : "failed";261262    yield* world.script(tree, ratchetLane, [linted]);263    yield* world.print(tree, ratchetLane, report);264    yield* world.script(tree, input.askLane, [input.askResult]);265    yield* world.print(tree, input.askLane, report);266  });267268const ratchetStory = (world: CoreLoopWorld) =>269  Effect.gen(function* () {270    const dora = world.rpc("dora");271    const doraGit = world.git("dora");272273    yield* dora.initProject({ project });274275    const home = yield* doraGit.clone(`${world.origin}/${project}.git`);276277    yield* doraGit.commit(home, "Start burrow", start);278    yield* doraGit.push(home);279280    const composedLint = CheckAt.cases.Commit.make({281      commit: yield* world.composed(project, lintFiles),282    });283284    yield* world.script(composedLint, lintToZero, ["failed", "failed"]);285    yield* world.print(composedLint, lintToZero, oxlintReport(mainFindings));286287    const opened = yield* dora.openAsk({288      ask: noAnyInParser,289      files: lintFiles,290      project,291    });292293    const afterOpening = yield* baselines(world);294295    for (const [ask, files] of [296      [formatIso, isoFiles],297      [decodeRaw, rawFiles],298    ] as const) {299      yield* world.script(300        CheckAt.cases.Commit.make({301          commit: yield* world.composed(project, files),302        }),303        redThenGreen,304        ["failed", "failed"]305      );306      yield* dora.openAsk({ ask, files, project });307    }308309    const harnessGit = yield* world.gitWithUsername(310      "alice",311      "audit;harness=pi&model=kimi-k3"312    );313314    const typed = yield* answer(world, "alice", harnessGit, {315      ask: noAnyInParser,316      files: {317        [parsePath]:318          "export const parse = (s: string) => ({ year: Number(s) });\n",319      },320    });321322    yield* scriptAnswer(world, typed.tree, {323      askLane: lintToZero,324      askResult: "failed",325      findings: formatOnly,326    });327    yield* world.settle();328329    const landed = (yield* world.rpc("alice").status({ project })).answers;330    const afterLanding = yield* baselines(world);331332    const pushLog = (yield* world.logged).filter(({ annotations }) =>333      annotations.has("harness")334    );335336    const bobGit = world.git("bob");337338    const widened = yield* answer(world, "bob", bobGit, {339      ask: formatIso,340      files: { [formatPath]: "export const format = (d: any, f: any) => d;\n" },341    });342343    yield* scriptAnswer(world, widened.tree, {344      askLane: redThenGreen,345      askResult: "passed",346      findings: [...formatOnly, [parsePath, 1]],347    });348    yield* world.settle();349350    const bob = world.rpc("bob");351352    return {353      afterLanding,354      afterOpening,355      bobsAnswers: (yield* bob.status({ project })).answers,356      bobsNote: yield* noteOn(bobGit, widened.work, widened.head),357      bobsVerdict: (yield* bob.verdict({ ask: formatIso, project })).verdict,358      home,359      landed,360      opened,361      pushLog,362      typed,363      widened,364    };365  });366367const escapeStory = (world: CoreLoopWorld, choice: Choice) =>368  Effect.gen(function* () {369    const aliceGit = world.git("alice");370371    const escaped = yield* answer(world, "alice", aliceGit, {372      ask: decodeRaw,373      files: {374        [codecPath]: [375          "// oxlint-disable-next-line no-explicit-any -- the codec boundary erases types",376          "export const decode = (raw: any) => raw;",377          "",378        ].join("\n"),379      },380    });381382    yield* scriptAnswer(world, escaped.tree, {383      askLane: redThenGreen,384      askResult: "passed",385      findings: formatOnly,386    });387    yield* world.settle();388389    const dora = world.rpc("dora");390    const alice = world.rpc("alice");391    const waiting = (yield* alice.status({ project })).answers;392    const today = yield* dora.today({ project });393    const before = yield* baselines(world);394395    const [waiver] = today.decisions;396397    if (waiver === undefined) {398      return { before, today, waiting };399    }400401    yield* dora.decide({ choice, decision: waiver.id, project });402    yield* world.settle();403404    return {405      after: yield* baselines(world),406      afterDecision: (yield* alice.status({ project })).answers,407      before,408      claims: (yield* alice.status({ project })).claims,409      escaped,410      today,411      waiting,412      waiver,413    };414  });415416const raiseStory = (world: CoreLoopWorld) =>417  Effect.gen(function* () {418    const raised = yield* answer(world, "alice", world.git("alice"), {419      ask: decodeRaw,420      files: {421        [codecPath]: [422          "// @ts-expect-error -- the codec boundary erases types",423          "export const decode = (raw: any) => raw;",424          "",425        ].join("\n"),426      },427    });428429    yield* scriptAnswer(world, raised.tree, {430      askLane: redThenGreen,431      askResult: "passed",432      findings: [...formatOnly, [codecPath, 2]],433    });434    yield* world.settle();435436    const dora = world.rpc("dora");437    const today = yield* dora.today({ project });438    const before = yield* baselines(world);439440    for (const { id } of today.decisions) {441      yield* dora.decide({ choice: "accept", decision: id, project });442    }443444    yield* world.settle();445446    return {447      after: yield* baselines(world),448      answers: (yield* world.rpc("alice").status({ project })).answers,449      before,450      subjects: today.decisions.map(({ subject }) => subject),451    };452  });453454const againStory = (world: CoreLoopWorld) =>455  Effect.gen(function* () {456    const aliceGit = world.git("alice");457    const escape = "// @ts-expect-error -- the codec boundary erases types";458459    const first = yield* answer(world, "alice", aliceGit, {460      ask: decodeRaw,461      files: {462        [codecPath]: [463          escape,464          "export const decode = (raw: any) => raw;",465          "",466        ].join("\n"),467      },468    });469470    yield* scriptAnswer(world, first.tree, {471      askLane: redThenGreen,472      askResult: "passed",473      findings: [...formatOnly, [codecPath, 2]],474    });475    yield* world.settle();476477    const dora = world.rpc("dora");478479    for (const { id, subject } of (yield* dora.today({ project })).decisions) {480      yield* dora.decide({481        choice: DecisionSubject.guards.Waiver(subject) ? "accept" : "decline",482        decision: id,483        project,484      });485    }486487    yield* world.settle();488489    const head = yield* aliceGit.commit(first.work, "Type decode", {490      [codecPath]: [491        escape,492        "export const decode = (raw: unknown) => raw;",493        "",494      ].join("\n"),495    });496497    yield* aliceGit.push(first.work);498499    yield* scriptAnswer(world, yield* treeOf(aliceGit, first.work, head), {500      askLane: redThenGreen,501      askResult: "passed",502      findings: formatOnly,503    });504    yield* world.settle();505506    return {507      answers: (yield* world.rpc("alice").status({ project })).answers,508      baselines: yield* baselines(world),509      today: (yield* dora.today({ project })).decisions,510    };511  });512513const movedStory = (world: CoreLoopWorld, widened: { readonly work: string }) =>514  Effect.gen(function* () {515    const aliceGit = world.git("alice");516    const bobGit = world.git("bob");517518    const escaped = yield* answer(world, "alice", aliceGit, {519      ask: decodeRaw,520      files: {521        [codecPath]: [522          "// oxlint-disable-next-line no-explicit-any -- the codec boundary erases types",523          "export const decode = (raw: any) => raw;",524          "",525        ].join("\n"),526      },527    });528529    yield* scriptAnswer(world, escaped.tree, {530      askLane: redThenGreen,531      askResult: "passed",532      findings: formatOnly,533    });534    yield* world.settle();535536    const typed = yield* bobGit.commit(widened.work, "Type format", {537      [formatPath]:538        "export const format = (d: Date) => d.toISOString().slice(0, 10);\n",539    });540541    yield* bobGit.push(widened.work);542    yield* scriptAnswer(world, yield* treeOf(bobGit, widened.work, typed), {543      askLane: redThenGreen,544      askResult: "passed",545      findings: [],546    });547    yield* world.settle();548549    yield* aliceGit.ok(550      escaped.work,551      "fetch",552      "--quiet",553      `${world.origin}/${project}.git`,554      "main"555    );556557    const remerged = CheckAt.cases.Tree.make({558      tree: TreeSha.make(559        yield* aliceGit.ok(560          escaped.work,561          "merge-tree",562          "--write-tree",563          "FETCH_HEAD",564          escaped.head565        )566      ),567    });568569    yield* scriptAnswer(world, remerged, {570      askLane: redThenGreen,571      askResult: "passed",572      findings: [],573    });574575    const dora = world.rpc("dora");576    const asked = (yield* dora.today({ project })).decisions;577578    for (const { id } of asked) {579      yield* dora.decide({ choice: "accept", decision: id, project });580    }581582    yield* world.settle();583584    return {585      answers: (yield* world.rpc("alice").status({ project })).answers,586      asked: asked.map(({ subject }) => subject._tag),587      baselines: yield* baselines(world),588      today: (yield* dora.today({ project })).decisions,589    };590  });591592const parserZero: Baseline = [ratchet, "parser", 0];593594const formatTwo: Baseline = [ratchet, "format", 2];595596describe("ratchets and lint-to-zero asks, through the platform's fetch handler with real git", () => {597  it.live(598    "a lint-to-zero ask opens red first by its count, its answer lowers the baseline, and an answer that raises a count is refused Weakened",599    () =>600      Effect.gen(function* () {601        const world = yield* coreLoopWorld();602        const seen = yield* ratchetStory(world);603        const { typed, widened } = seen;604605        const weakened = new Weakened({606          weakening: { after: 1, before: 0, ratchet, territory: "parser" },607        });608609        expect({610          afterLanding: seen.afterLanding,611          afterOpening: seen.afterOpening,612          bobsNote: seen.bobsNote.outcome,613          bobsOutcomes: seen.bobsAnswers.map(({ outcome }) => outcome),614          bobsPush: {615            exitCode: widened.pushed.exitCode,616            remote: remoteLines(widened.pushed.stderr),617          },618          bobsVerdict: seen.bobsVerdict?.outcome,619          landed: seen.landed.map(({ outcome }) => outcome._tag),620          opened: seen.opened.ask.check._tag,621        }).toStrictEqual({622          afterLanding: [formatTwo, parserZero],623          afterOpening: [formatTwo, [ratchet, "parser", 3]],624          bobsNote: Outcome.cases.Refused.make({ refusals: [weakened] }),625          bobsOutcomes: [Outcome.cases.Refused.make({ refusals: [weakened] })],626          bobsPush: {627            exitCode: 0,628            remote: [629              `remote: checking ${formatIso} at ${widened.head.slice(0, 7)}; follow with ${Brand.cli} status`,630            ],631          },632          bobsVerdict: Outcome.cases.Refused.make({ refusals: [weakened] }),633          landed: ["Landed"],634          opened: "LintToZero",635        });636637        expect(638          seen.pushLog.map(({ annotations }) => ({639            harness: annotations.get("harness"),640            model: annotations.get("model"),641            pusher: annotations.get("pusher"),642          }))643        ).toContainEqual({ harness: "pi", model: "kimi-k3", pusher: "alice" });644        expect(seen.landed.map(({ requestId }) => requestId)).toStrictEqual([645          pushRequestId(typed.claim.claimant, typed.head),646        ]);647      }),648    60_000649  );650651  it.live(652    "a reasoned escape waits on one Waiver, and accepting it lands the answer and raises its territory's escapes by one",653    () =>654      Effect.gen(function* () {655        const world = yield* coreLoopWorld();656        const { home } = yield* ratchetStory(world);657        const seen = yield* escapeStory(world, "accept");658        const doraGit = world.git("dora");659660        yield* doraGit.ok(home, "fetch", "--quiet", "origin");661662        const landed = yield* doraGit.ok(home, "rev-parse", "origin/main");663664        expect({665          after: seen.after,666          afterDecision: seen.afterDecision?.map(({ outcome }) => outcome._tag),667          before: seen.before,668          decidedBy: yield* doraGit.ok(669            home,670            "log",671            "-1",672            "--format=%(trailers:key=Decided-by,valueonly)",673            landed674          ),675          subjects: seen.today.decisions.map(({ subject }) => subject),676          waiting: seen.waiting.map(({ outcome }) => outcome._tag),677        }).toStrictEqual({678          after: [679            [RatchetName.make("escapes-parser"), "parser", 1],680            formatTwo,681            parserZero,682          ],683          afterDecision: ["Landed", "Landed"],684          before: [formatTwo, parserZero],685          decidedBy: credited("dora"),686          subjects: [687            DecisionSubject.cases.Waiver.make({688              ask: decodeRaw,689              at: { line: 1, path: RepoPath.make(codecPath) },690              marker: "oxlint-disable",691              reason: "the codec boundary erases types",692            }),693          ],694          waiting: ["Landed", "AwaitingDecision"],695        });696      }),697    60_000698  );699700  it.live(701    "declining the Waiver leaves the answer unlanded, the claim live, and the escapes where they were",702    () =>703      Effect.gen(function* () {704        const world = yield* coreLoopWorld();705        const { landed } = yield* ratchetStory(world);706        const seen = yield* escapeStory(world, "decline");707708        expect({709          after: seen.after,710          afterDecision: seen.afterDecision?.map(({ outcome }) => outcome),711          claims: seen.claims?.map(({ ask, state }) => [ask, state]),712        }).toStrictEqual({713          after: [formatTwo, parserZero],714          afterDecision: [715            ...landed.map(({ outcome }) => outcome),716            Outcome.cases.Refused.make({717              refusals: [718                new Weakened({719                  at: { line: 1, path: RepoPath.make(codecPath) },720                  weakening: {721                    marker: "oxlint-disable",722                    reason: "the codec boundary erases types",723                  },724                }),725              ],726            }),727          ],728          claims: [729            [noAnyInParser, "answered"],730            [decodeRaw, "live"],731          ],732        });733      }),734    60_000735  );736737  it.live(738    "a raise explained by a reasoned escape in its territory waits on RaiseRatchet beside the Waiver, and accepting both raises both baselines",739    () =>740      Effect.gen(function* () {741        const world = yield* coreLoopWorld();742        yield* ratchetStory(world);743        const seen = yield* raiseStory(world);744745        expect({746          after: seen.after,747          answers: seen.answers.map(({ outcome }) => outcome._tag),748          before: seen.before,749          subjects: seen.subjects,750        }).toStrictEqual({751          after: [752            [RatchetName.make("escapes-parser"), "parser", 1],753            formatTwo,754            [ratchet, "parser", 1],755          ],756          answers: ["Landed", "Landed"],757          before: [formatTwo, parserZero],758          subjects: [759            DecisionSubject.cases.Waiver.make({760              ask: decodeRaw,761              at: { line: 1, path: RepoPath.make(codecPath) },762              marker: "@ts-expect-error",763              reason: "the codec boundary erases types",764            }),765            DecisionSubject.cases.RaiseRatchet.make({766              after: 1,767              ask: decodeRaw,768              before: 0,769              ratchet,770              territory: "parser",771            }),772          ],773        });774      }),775    60_000776  );777778  it.live(779    "a Waiver accepted for one answer is asked again of the next answer to the same ask",780    () =>781      Effect.gen(function* () {782        const world = yield* coreLoopWorld();783        yield* ratchetStory(world);784        const seen = yield* againStory(world);785786        expect({787          answers: seen.answers.map(({ outcome }) => outcome._tag),788          baselines: seen.baselines,789          today: seen.today.map(({ subject }) => subject),790        }).toStrictEqual({791          answers: ["Landed", "Refused", "AwaitingDecision"],792          baselines: [formatTwo, parserZero],793          today: [794            DecisionSubject.cases.Waiver.make({795              ask: decodeRaw,796              at: { line: 1, path: RepoPath.make(codecPath) },797              marker: "@ts-expect-error",798              reason: "the codec boundary erases types",799            }),800          ],801        });802      }),803    60_000804  );805806  it.live(807    "an accepted Waiver is not asked again when its answer is checked again after main moved",808    () =>809      Effect.gen(function* () {810        const world = yield* coreLoopWorld();811        const { widened } = yield* ratchetStory(world);812        const seen = yield* movedStory(world, widened);813814        expect({815          answers: seen.answers.map(({ outcome }) => outcome._tag),816          asked: seen.asked,817          baselines: seen.baselines,818          today: seen.today,819        }).toStrictEqual({820          answers: ["Landed", "Landed"],821          asked: ["Waiver"],822          baselines: [823            [RatchetName.make("escapes-parser"), "parser", 1],824            [ratchet, "format", 0],825            parserZero,826          ],827          today: [],828        });829      }),830    60_000831  );832});