Merge build/417-wire-ratchets-and-escapes-into-the-platform: lintToZero and ratchet asks land end to end, baselines move down at landing and up only by a decision, and reasoned escapes wait on Today
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents bfd41ab, 02b2450 · Browse files · 15 files·+2179 added−89 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+2179 added−89 removed
- tests:+1179 added−22 removed
- other:+1000 added−67 removed
Provenance
- Commit
80d346c- Tree
a61c489- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
bfd41ab- Parent 2
02b2450
15 files changed+2179 added−89 removed
modified:apps/platform/src/adapters/custody.ts+53 added-3 removed
24 unmodified lines25 * project (`recordPush`: liveness, then stages 0–1, every stage-1 refusal at26 * once); a clean one is offered as the answer (`submitAnswer`, the same path27 * as `<cli> submit`) and the pusher reads that it is being checked. The28 * gate's later stages never run inside the push (spec D5).29+ *30+ * A harness that pushes names itself in the basic-auth username its31+ * credential helper gives (`audit;harness=pi&model=…`, `@repo/protocol/audit`).32+ * Custody logs it with the push, as audit metadata only: who pushes is the33+ * token's person, and the username is never identity, credit or a score.34 */35 import type { RepoName } from "@repo/artifacts/repo-host";36 import { Custody } from "@repo/git/custody";37 import type { Command } from "@repo/git/custody";38 import type { ProjectApi } from "@repo/project/project";39 import { Projects } from "@repo/project/projects";40+import type { HarnessAudit } from "@repo/protocol/audit";41 import { RequestId, sameHandle } from "@repo/protocol/ids";42 import type { AskId, CommitSha, Handle, ProjectName } from "@repo/protocol/ids";43 import { Principal } from "@repo/protocol/principal";44 import type { Person } from "@repo/protocol/principal";223 unmodified lines268 )269 );270 });271 272+/** What a push's log lines and span carry: who pushes, to which kind of repo, through which harness. */273+type PushAnnotations = HarnessAudit & {274+ readonly pusher: string;275+ readonly target: RepoKind["_tag"];276+};277+278+const annotationsOf = (279+ pusher: Person,280+ kind: RepoKind,281+ audit: Option.Option<HarnessAudit>282+): PushAnnotations => ({283+ ...Option.getOrElse(audit, (): HarnessAudit => ({})),284+ pusher: pusher.handle,285+ target: kind._tag,286+});287+288+/**289+ * `custody` with every log line it writes annotated, and its review in a290+ * span with the same attributes. `admit` stays synchronous: the gateway's291+ * body locks the moment the fiber yields.292+ */293+const annotated = (custody: Custody["Service"], annotations: PushAnnotations) =>294+ Custody.of({295+ admit: (repo, commands) =>296+ custody.admit(repo, commands).pipe(Effect.annotateLogs(annotations)),297+ review: (repo, commands) =>298+ custody299+ .review(repo, commands)300+ .pipe(301+ Effect.annotateLogs(annotations),302+ Effect.withSpan("custody.review", { attributes: annotations })303+ ),304+ });305+306 /** Custody that takes every push as it comes: a person's own working fork. */307 const takeAll = custodyOf(308 () => [],309 () => Effect.succeed([])6 unmodified lines316 317 /**318 * Custody of one push by `pusher` to the repo `kind` names. `notice` says a319 * line to the pusher once the push went through: what became of the answer320+ * it offered. `audit` is the harness the push came through (`auditOf` in321+ * `credential.ts`), if its username named one: logged with the push, never280- * it offered. Only a signed-in person pushes anywhere.322+ * who pushes. Only a signed-in person pushes anywhere.323 */324 export const custodyFor = (325 pusher: Principal,326 kind: RepoKind,285- notice: Notice = () => Effect.void327+ notice: Notice = () => Effect.void,328+ audit: Option.Option<HarnessAudit> = Option.none()329 ): Effect.Effect<Custody["Service"], never, Projects> =>330 Effect.gen(function* () {331 if (!Principal.guards.Person(pusher)) {332 return refuseAll;333 }334 335 const projects = yield* Projects;336+ const annotations = annotationsOf(pusher, kind, audit);337 338+ yield* Effect.logInfo("a push reached custody").pipe(339+ Effect.annotateLogs(annotations)340+ );341+294- return yield* RepoKind.$match(kind, {342+ const custody = yield* RepoKind.$match(kind, {343 Canonical: ({ project }) => canonical(projects, project, pusher),344 ClaimFork: (fork) => claimFork(projects, fork, pusher, notice),345 // The platform makes no repo by any other name; nothing pushes there.346 Unknown: () => Effect.succeed(refuseAll),347 // A person's working fork: only its owner pushes; their `land` judges it.348 WorkingFork: ({ handle }) =>349 Effect.succeed(sameHandle(pusher.handle, handle) ? takeAll : refuseAll),350 });351+352+ return annotated(custody, annotations);353 });modified:apps/platform/src/workflows/answer/lanes.ts+185 added-13 removed
8 unmodified lines9 *10 * The merged tree is checked in the answer's fork, where `Lander.merge`11 * keeps it (under `${Brand.refsPrefix}merge/<tree>`), so a merge needs no12 * write token on the canonical repo; main is checked in the canonical repo.13+ *14+ * The cheap stage also counts the policy's ratchets on the merged tree, one15+ * count lane per command (`measure`); the project judges the counts against16+ * its baselines when the checks report. A `lintToZero` ask's own lane is a17+ * count too: green at zero in its territory, whatever its lint exits with.18 */14-import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";19+import {20+ CheckAt,21+ CheckLane,22+ CheckRunner,23+ outputOf,24+} from "@repo/checks/check-runner";25 import type { CheckRun, LaneEvidence } from "@repo/checks/check-runner";26 import { EvidenceStore } from "@repo/checks/evidence-store";27+import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";28+import { measure } from "@repo/checks/kinds/ratchet";29 import { classifyFailure } from "@repo/gate/classify";18-import { runBlockOf } from "@repo/project/answer-runs";30+import { MeasuredCount, runBlockOf } from "@repo/project/answer-runs";31 import type { AnswerRun } from "@repo/project/answer-runs";32 import { LandingState } from "@repo/project/landing";33 import {34 HeldBackResult,35 LaneOutcome,36 LaneResult,37 } from "@repo/protocol/domain/answer";38+import { CheckSpec } from "@repo/protocol/domain/check";39 import { AskKind } from "@repo/protocol/domain/kind";40 import { RunBlock } from "@repo/protocol/domain/run";41 import {42 CommitSha,43 LandedSha,44 LaneName,45 ProjectName,46+ RatchetName,47 RepoName,48 RepoPath,49 RequestId,50 TreeSha,3 unmodified lines54 Flake,55 StaleBase,56 VerifierBlocked,57 } from "@repo/protocol/refusal";44-import { Array, Effect, Option, Order, Schema } from "effect";58+import { Array, Effect, Option, Order, Result, Schema } from "effect";59 60 /**61 * The lanes the cheap stage runs before the costlier checks: the static62 * ones, under the names the run block finder gives them (`checks/finder`).49- * Ratchet counts join them in W4 (417).63+ * The ratchets' counts run beside them (`countRatchets`).64 */65 export const cheapLanes = ["format", "lint", "types"] as const;66 67 /** Which of the answer's lanes a stage runs. */58 unmodified lines126 /** The answer no longer waits on these checks: another run moved it on. */127 Moved: {},128 Ran: {129 checked: Checked,130+ /** The cheap stage's: each ratchet's count on the merged tree, per territory. */131+ counts: Schema.optionalKey(Schema.Array(MeasuredCount)),132 heldBack: Schema.Array(HeldBackResult),133 lanes: Schema.Array(LaneRun),134+ /** The cheap stage's: a ratchet whose command printed no count the platform can read. */135+ uncounted: Schema.optionalKey(RatchetName),136 },137 });138 139 export type StageRun = typeof StageRun.Type;160 unmodified lines300 run.run === undefined ? asked : { ...asked, run: run.run }301 );302 };303 304+/** A job's run with one lane's result, and its evidence, put in place of what it was. */305+const withLane = (306+ ran: CheckRun,307+ result: LaneResult,308+ evidence: Option.Option<LaneEvidence>309+): CheckRun => ({310+ ...ran,311+ evidence: [312+ ...ran.evidence.filter(({ lane }) => lane !== result.lane),313+ ...Option.toArray(evidence),314+ ],315+ lanes: ran.lanes.map((each) => (each.lane === result.lane ? result : each)),316+});317+318 /**319+ * The run with a `lintToZero` ask's lane as its count decides it: passed320+ * at zero in its territory, failed above it (its signature says how many,321+ * so two runs compare), and a load error when its lint printed no count. A322+ * lint the Checker never got going stays as it ran, for its fresh run; its323+ * exit code says nothing, since a lint with findings anywhere exits 1.324+ */325+const countedAskLane = (326+ run: AnswerRun,327+ ran: CheckRun328+): Effect.Effect<CheckRun> => {329+ const { ask, askLane } = run;330+331+ const result = ran.lanes.find(({ lane }) => lane === askLane);332+333+ if (334+ ask === undefined ||335+ askLane === undefined ||336+ !CheckSpec.guards.LintToZero(ask.check) ||337+ result === undefined ||338+ isTrouble(result.result)339+ ) {340+ return Effect.succeed(ran);341+ }342+343+ const { check } = ask;344+345+ return Effect.fromOption(outputOf(ran, askLane)).pipe(346+ Effect.flatMap((stdout) =>347+ lintToZeroCount({348+ asked: ask.territory,349+ check,350+ modules: run.counts?.modules ?? [],351+ stdout,352+ })353+ ),354+ Effect.map((count) =>355+ count === 0356+ ? withLane(ran, { ...result, result: "passed" }, Option.none())357+ : withLane(358+ ran,359+ { ...result, result: "failed" },360+ Option.some({361+ lane: askLane,362+ signature: `${check.rule}: ${count} in ${check.territory ?? ask.territory.module}`,363+ })364+ )365+ ),366+ Effect.orElseSucceed(() =>367+ withLane(368+ ran,369+ { ...result, result: "loadError" },370+ Option.some({ lane: askLane })371+ )372+ )373+ );374+};375+376+/** What the cheap stage counted: each ratchet per territory, or the one whose count it could not read. */377+interface Counted {378+ readonly counts: readonly MeasuredCount[];379+ readonly uncounted: Option.Option<RatchetName>;380+}381+382+/**383+ * The policy's ratchets counted on the merged tree: one count lane per384+ * command (named for the first ratchet that runs it), each output read for385+ * every ratchet it serves and split by the project's modules (`measure`).386+ */387+const countRatchets = <E, R>(388+ run: AnswerRun,389+ job: (lanes: readonly CheckLane[]) => Effect.Effect<CheckRun, E, R>390+): Effect.Effect<Counted, E, R> =>391+ Effect.gen(function* () {392+ const specs = run.counts?.ratchets ?? [];393+394+ if (!Array.isReadonlyArrayNonEmpty(specs)) {395+ return { counts: [], uncounted: Option.none() };396+ }397+398+ const lanes = Array.dedupeWith(399+ specs,400+ (one, other) => one.measure.command === other.measure.command401+ ).map(({ measure: { command }, name }) =>402+ CheckLane.make({ command, lane: LaneName.make(name), output: "stdout" })403+ );404+405+ const ran = yield* job(lanes);406+407+ const printed = (command: string) =>408+ Option.getOrElse(409+ Option.flatMap(410+ Option.fromUndefinedOr(411+ lanes.find((lane) => lane.command === command)412+ ),413+ ({ lane }) => outputOf(ran, lane)414+ ),415+ () => ""416+ );417+418+ const counts = yield* Effect.forEach(specs, (spec) =>419+ measure(420+ spec,421+ (command) => Effect.succeed({ code: 0, stdout: printed(command) }),422+ run.counts?.modules ?? []423+ ).pipe(Effect.mapError(() => spec.name))424+ ).pipe(Effect.result);425+426+ return Result.match(counts, {427+ onFailure: (name) => ({ counts: [], uncounted: Option.some(name) }),428+ onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),429+ });430+ });431+432+/** What a stage run says of the counts: them, and the ratchet whose count it could not read. */433+const countFields = (counted: Counted): Pick<Ran, "counts" | "uncounted"> =>434+ Option.match(counted.uncounted, {435+ onNone: () => ({ counts: counted.counts }),436+ onSome: (uncounted) => ({ counts: counted.counts, uncounted }),437+ });438+439+/**440 * One stage's lanes on the merged tree `tree`: run, a troubled lane run441 * once more, and each lane that did not pass at first logged. The log's442 * name counts the answer's merges (`#1` on its first main), so a replayed443 * step keeps its log under the same name and a re-merge gets a new one.444+ * The cheap stage counts the ratchets too.445 */446 export const runStage = (447 run: AnswerRun,448 tree: TreeSha,10 unmodified lines459 const remerges = LandingState.guards.Checking(run.state)460 ? run.state.remerges461 : 0;462 463+ const counting = stage === "cheap" && run.counts !== undefined;464+309- if (!Array.isReadonlyArrayNonEmpty(lanes)) {465+ if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {466 return StageRun.cases.Ran.make({ checked, heldBack: [], lanes: [] });467 }468 469 const block = yield* runBlockOf(checked);470 471 const job = (each: readonly CheckLane[]) =>472+ runner316- runner.run({317- at: CheckAt.cases.Tree.make({ tree }),318- lanes: each,319- placeholders: [],320- project: checked.project,321- proxies: [],322- repo: checked.fork,323- run: block,473+ .run({474+ at: CheckAt.cases.Tree.make({ tree }),475+ lanes: each,476+ placeholders: [],477+ project: checked.project,478+ proxies: [],479+ repo: checked.fork,480+ run: block,481+ })482+ .pipe(Effect.flatMap((ran) => countedAskLane(run, ran)));483+484+ const counts = counting485+ ? countFields(yield* countRatchets(run, job))486+ : {};487+488+ if (!Array.isReadonlyArrayNonEmpty(lanes)) {489+ return StageRun.cases.Ran.make({490+ checked,491+ heldBack: [],492+ lanes: [],493+ ...counts,494 });495+ }496 497 const firstRun = yield* job(lanes);498 const first = byLane(firstRun);499 28 unmodified lines528 return StageRun.cases.Ran.make({529 checked,530 heldBack: firstRun.heldBack,531 lanes: laneRuns,532+ ...counts,533 });534 }).pipe(535 Effect.catchTag("VerifierBlocked", () =>536 Effect.succeed(78 unmodified linesmodified:apps/platform/src/workflows/answer/program.ts+36 added-6 removed
46 unmodified lines47 import type { Verdict } from "@repo/protocol/domain/answer";48 import type { Outcome } from "@repo/protocol/domain/outcome";49 import { CommitSha } from "@repo/protocol/ids";50 import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";51+import { VerifierBlocked } from "@repo/protocol/refusal";52 import {53 Array,54 Cause,55 Data,206 unmodified lines262 };263 });264 265 /**265- * The checks on the exact merged tree: the cheap stage, then, if it passed,266- * the ask's own check and every other project lane. The first stage that267- * refuses ends them, with its refusals and its lanes.266+ * The refusals of the cheap stage's counts: a ratchet whose command printed267+ * no count the platform can read is the gate's trouble, never the answer's268+ * (`VerifierBlocked`), and the project hears which one in its log.269 */270+const uncountedRefusals = (cheap: StageRun) =>271+ StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined272+ ? Effect.as(273+ Effect.logWarning(274+ `the ratchet ${cheap.uncounted} printed no count on ${cheap.checked.tree}`275+ ),276+ [new VerifierBlocked({})]277+ )278+ : Effect.succeed([]);279+280+/**281+ * The checks on the exact merged tree: the cheap stage (its lanes, and the282+ * ratchets' counts), then, if it passed, the ask's own check and every283+ * other project lane. The first stage that refuses ends them, with its284+ * refusals and its lanes. The counts go to the project with the report,285+ * which judges them against its baselines (spec §5 step 7 (b)) and opens286+ * the decisions a reasoned escape asks for (step 7 (e)).287+ */288 const checks = (289 params: AnswerParams,290 call: Call<"RunChecks">,291 attempt: number292 ): Effect.Effect<Option.Option<Reported>, never, AnswerPorts> =>293 Effect.gen(function* () {275- const cheap = yield* stage(params, call.tree, "cheap", attempt);294+ const ran = yield* stage(params, call.tree, "cheap", attempt);295 277- // W4 417: the cheap stage's ratchet counts, and the decisions a reasoned278- // escape asks for, join here.296+ const cheap = {297+ ...ran,298+ refusals: [...ran.refusals, ...(yield* uncountedRefusals(ran.ran))],299+ };300+301 const judged =302 StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0303 ? yield* stage(params, call.tree, "checks", attempt)304 : undefined;305 306 const last = judged ?? cheap;307 308+ const counts = StageRun.guards.Ran(cheap.ran)309+ ? Option.fromUndefinedOr(cheap.ran.counts)310+ : Option.none();311+312 return StageRun.match(last.ran, {313 Blocked: ({ attempt: at }) =>314 reported(LandingCommand.Blocked({ attempt: at })),315 Moved: () => Option.none(),12 unmodified lines328 ? cheap.ran.lanes329 : []),330 ...lanes,331 ].map(({ result }) => result),332+ ...Option.match(counts, {333+ onNone: () => ({}),334+ onSome: (ratchets) => ({ ratchets }),335+ }),336 }337 ),338 });339 });225 unmodified linesmodified:apps/platform/src/credential.ts+23 added-9 removed
12345678910111213141516171819202122232425262728293031323323242526272829303435363732383940414243444546import { parseAuditUser } from "@repo/protocol/audit";import type { HarnessAudit } from "@repo/protocol/audit";import { bearerToken } from "@repo/protocol/authenticate";import { Option, Schema } from "effect";
const BASIC = /^Basic (?<encoded>\S+)$/u;
const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);
/** The `<user>:<password>` pair of `Authorization: Basic base64(<user>:<password>)`. */const basicPairOf = (headers: Headers): Option.Option<string> => Option.fromNullishOr( BASIC.exec(headers.get("authorization") ?? "")?.groups?.encoded ).pipe(Option.flatMap(fromBase64));
/** The password of `<user>:<password>`; the first colon ends the user name. */const passwordOf = (pair: string) => { const colon = pair.indexOf(":");
return colon === -1 || colon === pair.length - 1 ? Option.none() : Option.some(pair.slice(colon + 1));};
/** The user name of `<user>:<password>`: all before the first colon. */const userOf = (pair: string) => pair.slice(0, Math.max(pair.indexOf(":"), 0));
/** * The platform token a request carries, if it carries one: from * `Authorization: Bearer <token>` (the CLI, MCP clients), or as the password * of `Authorization: Basic base64(<user>:<token>)`, which is how git sends * the token it got from the credential helper. The user name is ignored. */export const credentialOf = (headers: Headers): Option.Option<string> => { const authorization = headers.get("authorization") ?? undefined;
return Option.orElse(bearerToken(authorization), () => Option.fromNullishOr(BASIC.exec(authorization ?? "")?.groups?.encoded).pipe( Option.flatMap(fromBase64), Option.flatMap(passwordOf) )export const credentialOf = (headers: Headers): Option.Option<string> => Option.orElse(bearerToken(headers.get("authorization") ?? undefined), () => Option.flatMap(basicPairOf(headers), passwordOf) );};
/** * The harness a push came through, as its credential helper's basic-auth * user name says (`audit;harness=pi&model=kimi-k3`, `@repo/protocol/audit`); * none for any other user name, or a bearer token. Audit metadata, never * identity: who pushes is the token's person (`credentialOf`). */export const auditOf = (headers: Headers): Option.Option<HarnessAudit> => Option.flatMap(basicPairOf(headers), (pair) => parseAuditUser(userOf(pair)));modified:apps/platform/src/git.ts+6 added-3 removed
21 unmodified lines22 import { Anonymous, Principal } from "@repo/protocol/principal";23 import { Effect, Option, Ref } from "effect";24 25 import { custodyFor, refuseAll } from "./adapters/custody.ts";26-import { credentialOf } from "./credential.ts";26+import { auditOf, credentialOf } from "./credential.ts";27 import { repoKind, RepoKind } from "./repo-names.ts";28 import { Sessions } from "./sessions.ts";29 30 /** What serving git needs: who is calling, their projects, and the git server behind. */107 unmodified lines138 139 // Only a push's own request is judged; reads never reach custody.140 const custody =141 route.endpoint === "git-receive-pack"142- ? yield* custodyFor(principal, kind, (line) =>143- Ref.update(notices, (said) => [...said, line])142+ ? yield* custodyFor(143+ principal,144+ kind,145+ (line) => Ref.update(notices, (said) => [...said, line]),146+ auditOf(request.headers)147 )148 : refuseAll;149 150 const response = yield* gateway(request).pipe(18 unmodified linesadded:apps/platform/test/ratchet-loop.test.ts+902 added
1+/**2+ * Ratchets and lint-to-zero asks as a decider and two contributors live3+ * them, through the platform's own fetch handler with real git (spec §54+ * steps 3, 7 (b), (e) and 8): a project that declares a `no-explicit-any`5+ * ratchet opens a lint-to-zero ask red first by its count, an answer that6+ * drives the count to zero lands and lowers the baseline with no one asked,7+ * an answer elsewhere that raises the count is refused `Weakened`, and a8+ * reasoned escape waits for a decider, who lets it land or not.9+ *10+ * The Checker is scripted: each lane's result, and for a count lane the11+ * linter's JSON it prints, in oxlint's own shape (`oxlintReport`), per12+ * commit or tree.13+ */14+import { describe, expect, it } from "@effect/vitest";15+import { Brand } from "@repo/brand";16+import { CheckAt } from "@repo/checks/check-runner";17+import { Verdict } from "@repo/protocol/domain/answer";18+import { DecisionSubject } from "@repo/protocol/domain/decision";19+import type { Choice } from "@repo/protocol/domain/decision";20+import { Outcome } from "@repo/protocol/domain/outcome";21+import {22+ AskId,23+ LaneName,24+ ProjectName,25+ RatchetName,26+ RepoPath,27+ TreeSha,28+} from "@repo/protocol/ids";29+import type { CommitSha } from "@repo/protocol/ids";30+import { Weakened } from "@repo/protocol/refusal";31+import { Array, Effect, Order, Schema } from "effect";32+33+import { pushRequestId } from "../src/adapters/custody.ts";34+import { coreLoopWorld } from "./world.ts";35+import type { CoreLoopWorld, GitClient, Someone } from "./world.ts";36+37+const project = ProjectName.make("burrow");38+39+const noAnyInParser = AskId.make("no-any-in-parser");40+41+const formatIso = AskId.make("format-iso");42+43+const decodeRaw = AskId.make("decode-raw");44+45+const ratchet = RatchetName.make("no-explicit-any");46+47+/** The lane the ratchet's count runs in, named for the ratchet. */48+const ratchetLane = LaneName.make(ratchet);49+50+/** The lane a `lintToZero` ask's check runs in. */51+const lintToZero = LaneName.make("lintToZero");52+53+/** The lane a `redThenGreen` ask's check runs in. */54+const redThenGreen = LaneName.make("redThenGreen");55+56+/** The project's lint, which prints JSON. */57+const lint = "oxlint --format json";58+59+const rule = "typescript/no-explicit-any";60+61+/** Where the config folder's sdk is imported from, as a maintainer writes it. */62+const sdk = `${Brand.cliPackage}/rules`;63+64+const parsePath = "packages/parser/src/parse.ts";65+66+const formatPath = "packages/format/src/format.ts";67+68+const codecPath = "packages/parser/src/codec.ts";69+70+/** Three explicit `any`s in parser, two in format: what main starts with. */71+const anyParse =72+ "export const parse = (s: any): any => ({ year: Number(s as any) });\n";73+74+const anyFormat = "export const format = (d: any, f: any) => String(d);\n";75+76+/** The project as dora first pushes it: two packages, the config folder, the vouches. */77+const start = {78+ [`${Brand.configDir}/project.ts`]: [79+ `import { check, kinds, project } from "${sdk}";`,80+ ``,81+ `export default project({`,82+ ` kinds: [kinds.fix, kinds.lintToZero],`,83+ ` ratchets: {`,84+ ` "${ratchet}": check.ratchet.count("${lint}", { rule: "${rule}" }),`,85+ ` },`,86+ ` run: { checks: {}, test: "bun test {path}" },`,87+ `});`,88+ ``,89+ ].join("\n"),90+ [`${Brand.configDir}/vouched.td`]: "alice\nbob\n",91+ "package.json":92+ '{ "name": "burrow", "private": true, "workspaces": ["packages/*"] }\n',93+ "packages/format/package.json": '{ "name": "format" }\n',94+ "packages/parser/package.json": '{ "name": "parser" }\n',95+ [formatPath]: anyFormat,96+ [parsePath]: anyParse,97+};98+99+/** The lint-to-zero ask's one file: no explicit `any` left in parser. */100+const lintFiles = Array.make({101+ content: [102+ `import { kinds, territory } from "${sdk}";`,103+ ``,104+ `export default kinds.lintToZero.ask({`,105+ ` command: "${lint}",`,106+ ` rule: "${rule}",`,107+ ` territory: territory.package("parser"),`,108+ ` want: "parser types every value it reads",`,109+ `});`,110+ ``,111+ ].join("\n"),112+ path: RepoPath.make(`${Brand.configDir}/asks/${noAnyInParser}.ask.ts`),113+});114+115+/** A `fix` ask's files in `module`: its file, and its check, which asserts on `subject`. */116+const fixFiles = (117+ ask: AskId,118+ module: string,119+ want: string,120+ subject: {121+ readonly file: string;122+ readonly name: string;123+ readonly call: string;124+ readonly is: string;125+ }126+) =>127+ Array.make(128+ {129+ content: [130+ `import { kinds, territory } from "${sdk}";`,131+ ``,132+ `export default kinds.fix.ask({`,133+ ` path: "packages/${module}/test/${ask}.test.ts",`,134+ ` territory: territory.package("${module}"),`,135+ ` want: "${want}",`,136+ `});`,137+ ``,138+ ].join("\n"),139+ path: RepoPath.make(`${Brand.configDir}/asks/${ask}.ask.ts`),140+ },141+ {142+ content: [143+ `import { expect, it } from "bun:test";`,144+ `import { ${subject.name} } from "../src/${subject.file}";`,145+ ``,146+ `it("${want}", () => {`,147+ ` expect(${subject.call}).toBe(${subject.is});`,148+ `});`,149+ ``,150+ ].join("\n"),151+ path: RepoPath.make(`packages/${module}/test/${ask}.test.ts`),152+ }153+ );154+155+const isoFiles = fixFiles(formatIso, "format", "format writes ISO dates", {156+ call: "format(new Date(0))",157+ file: "format.ts",158+ is: '"1970-01-01"',159+ name: "format",160+});161+162+const rawFiles = fixFiles(decodeRaw, "parser", "parser decodes raw input", {163+ call: 'decode("2026")',164+ file: "codec.ts",165+ is: '"2026"',166+ name: "decode",167+});168+169+/** One `typescript/no-explicit-any` finding, as oxlint 1.87 prints it. */170+const anyAt = (filename: string, line: number) => ({171+ code: "typescript(no-explicit-any)",172+ filename,173+ help: "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.",174+ labels: [{ span: { column: 1, length: 3, line, offset: 0 } }],175+ message: "Unexpected `any`. Specify a different type.",176+ severity: "error",177+ url: "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html",178+});179+180+/** What `oxlint --format json` prints for these findings. */181+const oxlintReport = (182+ findings: readonly (readonly [path: string, line: number])[]183+) =>184+ JSON.stringify({185+ diagnostics: findings.map(([path, line]) => anyAt(path, line)),186+ number_of_files: 4,187+ number_of_rules: 1,188+ start_time: 0.01,189+ threads_count: 4,190+ });191+192+const mainFindings = [193+ [formatPath, 1],194+ [formatPath, 1],195+ [parsePath, 1],196+ [parsePath, 1],197+ [parsePath, 1],198+] as const;199+200+const formatOnly = [201+ [formatPath, 1],202+ [formatPath, 1],203+] as const;204+205+/** The lines git printed from the server's side band, less git's padding. */206+const remoteLines = (stderr: string) =>207+ stderr208+ .split("\n")209+ .filter((line) => line.startsWith("remote: "))210+ .map((line) => line.trimEnd());211+212+/** A person in a trailer: their handle and the address the platform gives them. */213+const credited = (handle: string) =>214+ `${handle} <${handle}@users.${Brand.domain}>`;215+216+/** A baseline as the tests read it: `[ratchet, territory, count]`. */217+type Baseline = readonly [ratchet: string, territory: string, count: number];218+219+/** Each baseline, in name order. */220+const baselines = (world: CoreLoopWorld) =>221+ Effect.map(world.ratchets(project), (rows) =>222+ Array.sort(223+ rows.map(({ count, ratchet: name, territory }): Baseline => [224+ name,225+ territory,226+ count,227+ ]),228+ Order.mapInput(Order.String, ([name, territory]: Baseline) =>229+ [name, territory].join(" ")230+ )231+ )232+ );233+234+/** The tree of `head` in a work tree: where an answer whose base is main is checked. */235+const treeOf = (git: GitClient, work: string, head: CommitSha) =>236+ Effect.map(git.ok(work, "rev-parse", `${head}^{tree}`), (tree) =>237+ CheckAt.cases.Tree.make({ tree: TreeSha.make(tree) })238+ );239+240+/** The verdict note on `head` in the clone at `work`, read with plain git. */241+const noteOn = (git: GitClient, work: string, head: CommitSha) =>242+ Effect.gen(function* () {243+ const ref = `refs/notes/${Brand.slug}`;244+245+ yield* git.ok(work, "fetch", "--quiet", "origin", `${ref}:${ref}`);246+247+ const shown = yield* git.ok(248+ work,249+ "notes",250+ `--ref=${Brand.slug}`,251+ "show",252+ head253+ );254+255+ return yield* Schema.decodeEffect(Schema.fromJsonString(Verdict))(256+ shown257+ ).pipe(Effect.orDie);258+ });259+260+/** `as`'s answer, pushed: it claims `ask`, clones its fork and commits `files`. */261+const answer = (262+ world: CoreLoopWorld,263+ as: Someone,264+ git: GitClient,265+ input: {266+ readonly ask: AskId;267+ readonly files: Readonly<Record<string, string>>;268+ }269+) =>270+ Effect.gen(function* () {271+ const { claim } = yield* world.rpc(as).claim({ ask: input.ask, project });272+ const work = yield* git.clone(claim.remote);273+ const head = yield* git.commit(work, `Answer ${input.ask}`, input.files);274+ const pushed = yield* git.push(work);275+ const tree = yield* treeOf(git, work, head);276+277+ return { claim, head, pushed, tree, work };278+ });279+280+/** The merged tree's lanes, scripted: the ratchet's count, and the ask's own check. */281+const scriptAnswer = (282+ world: CoreLoopWorld,283+ tree: CheckAt,284+ input: {285+ readonly askLane: LaneName;286+ readonly askResult: "passed" | "failed";287+ readonly findings: readonly (readonly [string, number])[];288+ }289+) =>290+ Effect.gen(function* () {291+ const report = oxlintReport(input.findings);292+ const linted = input.findings.length === 0 ? "passed" : "failed";293+294+ yield* world.script(tree, ratchetLane, [linted]);295+ yield* world.print(tree, ratchetLane, report);296+ yield* world.script(tree, input.askLane, [input.askResult]);297+ yield* world.print(tree, input.askLane, report);298+ });299+300+/**301+ * Steps 1 to 3: the project, its asks opened red first, alice's answer to302+ * the lint-to-zero ask landed (pushed with a harness's audit username), and303+ * bob's answer in format refused for what the merged tree counts in parser.304+ */305+const ratchetStory = (world: CoreLoopWorld) =>306+ Effect.gen(function* () {307+ const dora = world.rpc("dora");308+ const doraGit = world.git("dora");309+310+ // dora makes the project and pushes its first tree.311+ yield* dora.initProject({ project });312+313+ const home = yield* doraGit.clone(`${world.origin}/${project}.git`);314+315+ yield* doraGit.commit(home, "Start burrow", start);316+ yield* doraGit.push(home);317+318+ // 1. The lint-to-zero ask: twice on main the rule counts 3 in parser.319+ const composedLint = CheckAt.cases.Commit.make({320+ commit: yield* world.composed(project, lintFiles),321+ });322+323+ yield* world.script(composedLint, lintToZero, ["failed", "failed"]);324+ yield* world.print(composedLint, lintToZero, oxlintReport(mainFindings));325+326+ const opened = yield* dora.openAsk({327+ ask: noAnyInParser,328+ files: lintFiles,329+ project,330+ });331+332+ const afterOpening = yield* baselines(world);333+334+ // Two `fix` asks to answer later, each red first by its check.335+ for (const [ask, files] of [336+ [formatIso, isoFiles],337+ [decodeRaw, rawFiles],338+ ] as const) {339+ yield* world.script(340+ CheckAt.cases.Commit.make({341+ commit: yield* world.composed(project, files),342+ }),343+ redThenGreen,344+ ["failed", "failed"]345+ );346+ yield* dora.openAsk({ ask, files, project });347+ }348+349+ // 2. alice drives the count in parser to zero, through a harness that350+ // names itself in her credential helper's username. format still has351+ // its two, so the lint exits 1; the ask's check is its count in parser.352+ const harnessGit = yield* world.gitWithUsername(353+ "alice",354+ "audit;harness=pi&model=kimi-k3"355+ );356+357+ const typed = yield* answer(world, "alice", harnessGit, {358+ ask: noAnyInParser,359+ files: {360+ [parsePath]:361+ "export const parse = (s: string) => ({ year: Number(s) });\n",362+ },363+ });364+365+ yield* scriptAnswer(world, typed.tree, {366+ askLane: lintToZero,367+ askResult: "failed",368+ findings: formatOnly,369+ });370+ yield* world.settle();371+372+ const landed = (yield* world.rpc("alice").status({ project })).answers;373+ const afterLanding = yield* baselines(world);374+375+ const pushLog = (yield* world.logged).filter(({ annotations }) =>376+ annotations.has("harness")377+ );378+379+ // 3. bob answers format-iso in format; the lint of his merged tree380+ // counts one in parser again, over the baseline of zero.381+ const bobGit = world.git("bob");382+383+ const widened = yield* answer(world, "bob", bobGit, {384+ ask: formatIso,385+ files: { [formatPath]: "export const format = (d: any, f: any) => d;\n" },386+ });387+388+ yield* scriptAnswer(world, widened.tree, {389+ askLane: redThenGreen,390+ askResult: "passed",391+ findings: [...formatOnly, [parsePath, 1]],392+ });393+ yield* world.settle();394+395+ const bob = world.rpc("bob");396+397+ return {398+ afterLanding,399+ afterOpening,400+ bobsAnswers: (yield* bob.status({ project })).answers,401+ bobsNote: yield* noteOn(bobGit, widened.work, widened.head),402+ bobsVerdict: (yield* bob.verdict({ ask: formatIso, project })).verdict,403+ home,404+ landed,405+ opened,406+ pushLog,407+ typed,408+ widened,409+ };410+ });411+412+/**413+ * Step 4: alice answers decode-raw with a reasoned escape in parser, which414+ * hides its `any` from the lint and raises parser's escapes; dora takes415+ * the `Waiver` on Today with `choice`.416+ */417+const escapeStory = (world: CoreLoopWorld, choice: Choice) =>418+ Effect.gen(function* () {419+ const aliceGit = world.git("alice");420+421+ const escaped = yield* answer(world, "alice", aliceGit, {422+ ask: decodeRaw,423+ files: {424+ [codecPath]: [425+ "// oxlint-disable-next-line no-explicit-any -- the codec boundary erases types",426+ "export const decode = (raw: any) => raw;",427+ "",428+ ].join("\n"),429+ },430+ });431+432+ yield* scriptAnswer(world, escaped.tree, {433+ askLane: redThenGreen,434+ askResult: "passed",435+ findings: formatOnly,436+ });437+ yield* world.settle();438+439+ const dora = world.rpc("dora");440+ const alice = world.rpc("alice");441+ const waiting = (yield* alice.status({ project })).answers;442+ const today = yield* dora.today({ project });443+ const before = yield* baselines(world);444+445+ const [waiver] = today.decisions;446+447+ if (waiver === undefined) {448+ return { before, today, waiting };449+ }450+451+ yield* dora.decide({ choice, decision: waiver.id, project });452+ yield* world.settle();453+454+ return {455+ after: yield* baselines(world),456+ afterDecision: (yield* alice.status({ project })).answers,457+ before,458+ claims: (yield* alice.status({ project })).claims,459+ escaped,460+ today,461+ waiting,462+ waiver,463+ };464+ });465+466+/**467+ * alice answers decode-raw with an `any` the lint counts in parser and a468+ * reasoned escape beside it, which explains the raise; dora accepts each469+ * decision on Today, in turn.470+ */471+const raiseStory = (world: CoreLoopWorld) =>472+ Effect.gen(function* () {473+ const raised = yield* answer(world, "alice", world.git("alice"), {474+ ask: decodeRaw,475+ files: {476+ [codecPath]: [477+ "// @ts-expect-error -- the codec boundary erases types",478+ "export const decode = (raw: any) => raw;",479+ "",480+ ].join("\n"),481+ },482+ });483+484+ yield* scriptAnswer(world, raised.tree, {485+ askLane: redThenGreen,486+ askResult: "passed",487+ findings: [...formatOnly, [codecPath, 2]],488+ });489+ yield* world.settle();490+491+ const dora = world.rpc("dora");492+ const today = yield* dora.today({ project });493+ const before = yield* baselines(world);494+495+ for (const { id } of today.decisions) {496+ yield* dora.decide({ choice: "accept", decision: id, project });497+ }498+499+ yield* world.settle();500+501+ return {502+ after: yield* baselines(world),503+ answers: (yield* world.rpc("alice").status({ project })).answers,504+ before,505+ subjects: today.decisions.map(({ subject }) => subject),506+ };507+ });508+509+/**510+ * alice answers decode-raw with a raise and a reasoned escape; dora accepts511+ * the `Waiver` and declines the `RaiseRatchet`, so the answer is refused.512+ * alice pushes again on the same claim: the same escape on the same line,513+ * and no raise.514+ */515+const againStory = (world: CoreLoopWorld) =>516+ Effect.gen(function* () {517+ const aliceGit = world.git("alice");518+ const escape = "// @ts-expect-error -- the codec boundary erases types";519+520+ const first = yield* answer(world, "alice", aliceGit, {521+ ask: decodeRaw,522+ files: {523+ [codecPath]: [524+ escape,525+ "export const decode = (raw: any) => raw;",526+ "",527+ ].join("\n"),528+ },529+ });530+531+ yield* scriptAnswer(world, first.tree, {532+ askLane: redThenGreen,533+ askResult: "passed",534+ findings: [...formatOnly, [codecPath, 2]],535+ });536+ yield* world.settle();537+538+ const dora = world.rpc("dora");539+540+ for (const { id, subject } of (yield* dora.today({ project })).decisions) {541+ yield* dora.decide({542+ choice: DecisionSubject.guards.Waiver(subject) ? "accept" : "decline",543+ decision: id,544+ project,545+ });546+ }547+548+ yield* world.settle();549+550+ const head = yield* aliceGit.commit(first.work, "Type decode", {551+ [codecPath]: [552+ escape,553+ "export const decode = (raw: unknown) => raw;",554+ "",555+ ].join("\n"),556+ });557+558+ yield* aliceGit.push(first.work);559+560+ yield* scriptAnswer(world, yield* treeOf(aliceGit, first.work, head), {561+ askLane: redThenGreen,562+ askResult: "passed",563+ findings: formatOnly,564+ });565+ yield* world.settle();566+567+ return {568+ answers: (yield* world.rpc("alice").status({ project })).answers,569+ baselines: yield* baselines(world),570+ today: (yield* dora.today({ project })).decisions,571+ };572+ });573+574+/**575+ * alice's reasoned escape waits on a `Waiver` while bob's clean answer to576+ * format-iso lands; dora then accepts it, alice's land finds main moved,577+ * and her answer is merged and checked again on the new main.578+ */579+const movedStory = (world: CoreLoopWorld, widened: { readonly work: string }) =>580+ Effect.gen(function* () {581+ const aliceGit = world.git("alice");582+ const bobGit = world.git("bob");583+584+ const escaped = yield* answer(world, "alice", aliceGit, {585+ ask: decodeRaw,586+ files: {587+ [codecPath]: [588+ "// oxlint-disable-next-line no-explicit-any -- the codec boundary erases types",589+ "export const decode = (raw: any) => raw;",590+ "",591+ ].join("\n"),592+ },593+ });594+595+ yield* scriptAnswer(world, escaped.tree, {596+ askLane: redThenGreen,597+ askResult: "passed",598+ findings: formatOnly,599+ });600+ yield* world.settle();601+602+ // bob's answer, typed this time, lands while alice's waits.603+ const typed = yield* bobGit.commit(widened.work, "Type format", {604+ [formatPath]:605+ "export const format = (d: Date) => d.toISOString().slice(0, 10);\n",606+ });607+608+ yield* bobGit.push(widened.work);609+ yield* scriptAnswer(world, yield* treeOf(bobGit, widened.work, typed), {610+ askLane: redThenGreen,611+ askResult: "passed",612+ findings: [],613+ });614+ yield* world.settle();615+616+ // alice's answer merged onto the new main, as the Lander will merge it.617+ yield* aliceGit.ok(618+ escaped.work,619+ "fetch",620+ "--quiet",621+ `${world.origin}/${project}.git`,622+ "main"623+ );624+625+ const remerged = CheckAt.cases.Tree.make({626+ tree: TreeSha.make(627+ yield* aliceGit.ok(628+ escaped.work,629+ "merge-tree",630+ "--write-tree",631+ "FETCH_HEAD",632+ escaped.head633+ )634+ ),635+ });636+637+ yield* scriptAnswer(world, remerged, {638+ askLane: redThenGreen,639+ askResult: "passed",640+ findings: [],641+ });642+643+ const dora = world.rpc("dora");644+ const asked = (yield* dora.today({ project })).decisions;645+646+ for (const { id } of asked) {647+ yield* dora.decide({ choice: "accept", decision: id, project });648+ }649+650+ yield* world.settle();651+652+ return {653+ answers: (yield* world.rpc("alice").status({ project })).answers,654+ asked: asked.map(({ subject }) => subject._tag),655+ baselines: yield* baselines(world),656+ today: (yield* dora.today({ project })).decisions,657+ };658+ });659+660+const parserZero: Baseline = [ratchet, "parser", 0];661+662+const formatTwo: Baseline = [ratchet, "format", 2];663+664+describe("ratchets and lint-to-zero asks, through the platform's fetch handler with real git", () => {665+ it.live(666+ "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",667+ () =>668+ Effect.gen(function* () {669+ const world = yield* coreLoopWorld();670+ const seen = yield* ratchetStory(world);671+ const { typed, widened } = seen;672+673+ const weakened = new Weakened({674+ weakening: { after: 1, before: 0, ratchet, territory: "parser" },675+ });676+677+ expect({678+ afterLanding: seen.afterLanding,679+ afterOpening: seen.afterOpening,680+ bobsNote: seen.bobsNote.outcome,681+ bobsOutcomes: seen.bobsAnswers.map(({ outcome }) => outcome),682+ bobsPush: {683+ exitCode: widened.pushed.exitCode,684+ remote: remoteLines(widened.pushed.stderr),685+ },686+ bobsVerdict: seen.bobsVerdict?.outcome,687+ landed: seen.landed.map(({ outcome }) => outcome._tag),688+ opened: seen.opened.ask.check._tag,689+ }).toStrictEqual({690+ afterLanding: [formatTwo, parserZero],691+ afterOpening: [formatTwo, [ratchet, "parser", 3]],692+ bobsNote: Outcome.cases.Refused.make({ refusals: [weakened] }),693+ bobsOutcomes: [Outcome.cases.Refused.make({ refusals: [weakened] })],694+ bobsPush: {695+ exitCode: 0,696+ remote: [697+ `remote: checking ${formatIso} at ${widened.head.slice(0, 7)}; follow with ${Brand.cli} status`,698+ ],699+ },700+ bobsVerdict: Outcome.cases.Refused.make({ refusals: [weakened] }),701+ landed: ["Landed"],702+ opened: "LintToZero",703+ });704+705+ // 5. The harness's username is logged with the push, as audit706+ // metadata; the push is alice's, by her token.707+ expect(708+ seen.pushLog.map(({ annotations }) => ({709+ harness: annotations.get("harness"),710+ model: annotations.get("model"),711+ pusher: annotations.get("pusher"),712+ }))713+ ).toContainEqual({ harness: "pi", model: "kimi-k3", pusher: "alice" });714+ expect(seen.landed.map(({ requestId }) => requestId)).toStrictEqual([715+ pushRequestId(typed.claim.claimant, typed.head),716+ ]);717+ }),718+ 60_000719+ );720+721+ it.live(722+ "a reasoned escape waits on one Waiver, and accepting it lands the answer and raises its territory's escapes by one",723+ () =>724+ Effect.gen(function* () {725+ const world = yield* coreLoopWorld();726+ const { home } = yield* ratchetStory(world);727+ const seen = yield* escapeStory(world, "accept");728+ const doraGit = world.git("dora");729+730+ yield* doraGit.ok(home, "fetch", "--quiet", "origin");731+732+ const landed = yield* doraGit.ok(home, "rev-parse", "origin/main");733+734+ expect({735+ after: seen.after,736+ afterDecision: seen.afterDecision?.map(({ outcome }) => outcome._tag),737+ before: seen.before,738+ decidedBy: yield* doraGit.ok(739+ home,740+ "log",741+ "-1",742+ "--format=%(trailers:key=Decided-by,valueonly)",743+ landed744+ ),745+ subjects: seen.today.decisions.map(({ subject }) => subject),746+ waiting: seen.waiting.map(({ outcome }) => outcome._tag),747+ }).toStrictEqual({748+ after: [749+ [RatchetName.make("escapes-parser"), "parser", 1],750+ formatTwo,751+ parserZero,752+ ],753+ afterDecision: ["Landed", "Landed"],754+ before: [formatTwo, parserZero],755+ decidedBy: credited("dora"),756+ subjects: [757+ DecisionSubject.cases.Waiver.make({758+ ask: decodeRaw,759+ at: { line: 1, path: RepoPath.make(codecPath) },760+ marker: "oxlint-disable",761+ reason: "the codec boundary erases types",762+ }),763+ ],764+ waiting: ["Landed", "AwaitingDecision"],765+ });766+ }),767+ 60_000768+ );769+770+ it.live(771+ "declining the Waiver leaves the answer unlanded, the claim live, and the escapes where they were",772+ () =>773+ Effect.gen(function* () {774+ const world = yield* coreLoopWorld();775+ const { landed } = yield* ratchetStory(world);776+ const seen = yield* escapeStory(world, "decline");777+778+ expect({779+ after: seen.after,780+ afterDecision: seen.afterDecision?.map(({ outcome }) => outcome),781+ claims: seen.claims?.map(({ ask, state }) => [ask, state]),782+ }).toStrictEqual({783+ after: [formatTwo, parserZero],784+ afterDecision: [785+ ...landed.map(({ outcome }) => outcome),786+ Outcome.cases.Refused.make({787+ refusals: [788+ new Weakened({789+ at: { line: 1, path: RepoPath.make(codecPath) },790+ weakening: {791+ marker: "oxlint-disable",792+ reason: "the codec boundary erases types",793+ },794+ }),795+ ],796+ }),797+ ],798+ claims: [799+ [noAnyInParser, "answered"],800+ [decodeRaw, "live"],801+ ],802+ });803+ }),804+ 60_000805+ );806+807+ it.live(808+ "a raise explained by a reasoned escape in its territory waits on RaiseRatchet beside the Waiver, and accepting both raises both baselines",809+ () =>810+ Effect.gen(function* () {811+ const world = yield* coreLoopWorld();812+ yield* ratchetStory(world);813+ const seen = yield* raiseStory(world);814+815+ expect({816+ after: seen.after,817+ answers: seen.answers.map(({ outcome }) => outcome._tag),818+ before: seen.before,819+ subjects: seen.subjects,820+ }).toStrictEqual({821+ after: [822+ [RatchetName.make("escapes-parser"), "parser", 1],823+ formatTwo,824+ [ratchet, "parser", 1],825+ ],826+ answers: ["Landed", "Landed"],827+ before: [formatTwo, parserZero],828+ subjects: [829+ DecisionSubject.cases.Waiver.make({830+ ask: decodeRaw,831+ at: { line: 1, path: RepoPath.make(codecPath) },832+ marker: "@ts-expect-error",833+ reason: "the codec boundary erases types",834+ }),835+ DecisionSubject.cases.RaiseRatchet.make({836+ after: 1,837+ ask: decodeRaw,838+ before: 0,839+ ratchet,840+ territory: "parser",841+ }),842+ ],843+ });844+ }),845+ 60_000846+ );847+848+ it.live(849+ "a Waiver accepted for one answer is asked again of the next answer to the same ask",850+ () =>851+ Effect.gen(function* () {852+ const world = yield* coreLoopWorld();853+ yield* ratchetStory(world);854+ const seen = yield* againStory(world);855+856+ expect({857+ answers: seen.answers.map(({ outcome }) => outcome._tag),858+ baselines: seen.baselines,859+ today: seen.today.map(({ subject }) => subject),860+ }).toStrictEqual({861+ answers: ["Landed", "Refused", "AwaitingDecision"],862+ baselines: [formatTwo, parserZero],863+ today: [864+ DecisionSubject.cases.Waiver.make({865+ ask: decodeRaw,866+ at: { line: 1, path: RepoPath.make(codecPath) },867+ marker: "@ts-expect-error",868+ reason: "the codec boundary erases types",869+ }),870+ ],871+ });872+ }),873+ 60_000874+ );875+876+ it.live(877+ "an accepted Waiver is not asked again when its answer is checked again after main moved",878+ () =>879+ Effect.gen(function* () {880+ const world = yield* coreLoopWorld();881+ const { widened } = yield* ratchetStory(world);882+ const seen = yield* movedStory(world, widened);883+884+ expect({885+ answers: seen.answers.map(({ outcome }) => outcome._tag),886+ asked: seen.asked,887+ baselines: seen.baselines,888+ today: seen.today,889+ }).toStrictEqual({890+ answers: ["Landed", "Landed"],891+ asked: ["Waiver"],892+ baselines: [893+ [RatchetName.make("escapes-parser"), "parser", 1],894+ [ratchet, "format", 0],895+ parserZero,896+ ],897+ today: [],898+ });899+ }),900+ 60_000901+ );902+});modified:apps/platform/test/world.ts+118 added-19 removed
21 unmodified lines22 * engine's. People are `dora` (who makes the project, so its decider),23 * `alice` and `bob`, each a `SESSION_TOKENS` entry: git sends a person's24 * token as the Basic password its credential helper gives, and the RPC25 * client as a bearer token.26+ *27+ * Every log line the Worker's handler writes is kept beside its usual28+ * printing, with its annotations (`logged`), and each Project DO's SQLite29+ * stays reachable (`ratchets` reads its `ratchets` rows through the store).30 */31 import { NodeHttpServer, NodeServices } from "@effect/platform-node";32 import { SqliteClient } from "@effect/sql-sqlite-node";33 import { RefName, RepoHost } from "@repo/artifacts/repo-host";8 unmodified lines42 import { FrontPageMemory } from "@repo/project/front-page/memory";43 import { Lander } from "@repo/project/lander";44 import { LanderIsogit } from "@repo/project/lander/isogit";45 import { FinishersFromChecks } from "@repo/project/project";46+import { ProjectStore } from "@repo/project/project-store";47+import type { RatchetRow } from "@repo/project/project-store/rows";48+import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";49 import { ProjectionMemory } from "@repo/project/projection/memory";50 import { Contracts } from "@repo/protocol/contracts";51 import type { Client } from "@repo/protocol/contracts";52 import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";4 unmodified lines57 import { git, gitOk } from "@repo/testkit/git";58 import type { Ran } from "@repo/testkit/git";59 import { httpBackend } from "@repo/testkit/http-backend";60 import type { Scope } from "effect";54-import { Array, Context, Effect, FileSystem, Layer, Option, Ref } from "effect";61 import {62+ Array,63+ Context,64+ Effect,65+ FileSystem,66+ Layer,67+ Logger,68+ Option,69+ Ref,70+ References,71+} from "effect";72+import {73 FetchHttpClient,74 HttpClient,75 HttpClientRequest,76 HttpServer,77 HttpServerRequest,78 HttpServerResponse,79 } from "effect/http";80 import { RpcClient, RpcSerialization } from "effect/rpc";81+import type { SqlClient } from "effect/sql/SqlClient";82 83 import { DoProjects } from "../src/adapters/do-projects.ts";84 import { WorkerFetch } from "../src/adapters/fetch.ts";85 import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";36 unmodified lines122 files: Readonly<Record<string, string>>123 ) => Effect.Effect<CommitSha>;124 }125 126+/** One line the Worker's handler logged, with its annotations as text. */127+export interface Logged {128+ readonly message: string;129+ readonly annotations: ReadonlyMap<string, string>;130+}131+132 /** The world a core-loop test drives. */133 export interface CoreLoopWorld {134 /** The platform's fetch handler, composed as the Worker's is. */135 readonly fetch: (request: Request) => Effect.Effect<Response>;136 /** Where the handler is served, on a local port, so git can reach it. */137 readonly origin: string;138 readonly git: (as: Someone) => GitClient;139+ /**140+ * That person's git, whose credential helper gives `username` beside141+ * their token, as the CLI's helper gives a harness's audit username. One142+ * such git per person in a world: its clones share a home.143+ */144+ readonly gitWithUsername: (145+ as: Someone,146+ username: string147+ ) => Effect.Effect<GitClient>;148+ /** Every line the Worker's handler logged so far, in order. */149+ readonly logged: Effect.Effect<readonly Logged[]>;150+ /** A project's ratchet baselines, as its Durable Object's store keeps them. */151+ readonly ratchets: (152+ project: ProjectName153+ ) => Effect.Effect<readonly RatchetRow[]>;154 /** A client of the contracts over HTTP at `/rpc`, as that person (or as anyone). */155 readonly rpc: (as: Someone | "anonymous") => Client["Service"];156 /** Runs every queued answer run to its end, and any run those start. */157 readonly settle: () => Effect.Effect<void>;2 unmodified lines160 at: CheckAt,161 lane: LaneName,162 results: readonly LaneOutcome[]163 ) => Effect.Effect<void>;164+ /** What a count lane prints at a commit or tree: a linter's JSON, as recorded. */165+ readonly print: (166+ at: CheckAt,167+ lane: LaneName,168+ stdout: string169+ ) => Effect.Effect<void>;170 /**171 * The commit the Lander composes from `files` on `project`'s main, which172 * an ask's check runs on, red first, as the ask opens.173 */36 unmodified lines210 });211 212 /**213 * A credential helper as git runs one: asked for a credential, it answers169- * with the person's handle and their platform token as the password.214+ * with a username (the person's handle, unless told another) and their215+ * platform token as the password.216 */171-const helperScript = (as: Someone) =>217+const helperScript = (as: Someone, username: string = as) =>218 [219 "#!/bin/sh",220 'test "$1" = get || exit 0',175- `echo username=${as}`,221+ `echo 'username=${username}'`,222 `echo password=${tokens[as]}`,223 "",224 ].join("\n");225 21 unmodified lines247 );248 249 // The Checker reads its script when it runs, so the test may add to it.250 const script = new Map<string, readonly LaneResult[]>();251+ const printed = new Map<string, string>();252 const queued = yield* Ref.make<readonly AnswerParams[]>([]);253+ // Each line the handler logs, kept with its annotations as it is written.254+ const logs: Logged[] = [];255 256+ const keeper = Logger.make(({ fiber, message }) => {257+ logs.push({258+ annotations: new Map(259+ Object.entries(fiber.getRef(References.CurrentLogAnnotations)).map(260+ ([key, value]) => [key, String(value)]261+ )262+ ),263+ message: String(message),264+ });265+ });266+267 // Every port but `Projects`, built once: the Worker's, its Project DOs'268 // and the answer runs' alike.269 const base = yield* Layer.build(270 Layer.mergeAll(271 UpstreamRepoHost,272 LanderIsogit,213- CheckRunnerMemory.layer(script),273+ CheckRunnerMemory.layer(script, printed),274 RulesEvaluatorBun.pipe(Layer.provide(FinishersFromChecks)),275 options.evidence ?? EvidenceStoreMemory,276 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),277 ProjectionMemory,23 unmodified lines301 ),302 })303 );304 305+ // Each DO's database, kept so a test can read its rows back.306+ const databases = new Map<string, Context.Context<SqlClient>>();307+308 // The `PROJECT` namespace in process: a name is one DO, made on its309 // first call, a shell over a database of its own, living in the world's310 // scope.311 const { namespace } = yield* inProcessNamespace((name) =>312+ Effect.gen(function* () {313+ const sql = yield* Layer.build(314+ SqliteClient.layer({ filename: ":memory:" }).pipe(Layer.orDie)315+ );316+317+ databases.set(name, sql);318+249- projectShell({250- name,251- ports: Layer.mergeAll(252- Layer.succeedContext(base),253- AlarmsMemory,254- runsOf(name)255- ),256- sql: SqliteClient.layer({ filename: ":memory:" }).pipe(Layer.orDie),319+ return yield* projectShell({320+ name,321+ ports: Layer.mergeAll(322+ Layer.succeedContext(base),323+ AlarmsMemory,324+ runsOf(name)325+ ),326+ sql: Layer.succeedContext(sql),327+ });328 })329 );330 331 const ports = base.pipe(332 Context.merge(yield* Layer.build(DoProjects(namespace)))333 );334 335+ // Every request the handler serves logs through the keeper too.336+ const logging = yield* Layer.build(337+ Logger.layer([keeper], { mergeWithExisting: true })338+ );339+340 // The stage's env as the Worker decodes it, with the people's tokens.341 const env = {342 ...fakeEnv(),343 SESSION_TOKENS: JSON.stringify(11 unmodified lines355 356 yield* Effect.addFinalizer(() => Effect.promise(dispose));357 358 const origin = yield* listen((request) =>283- Effect.promise(() => handler(request))359+ Effect.promise(() => handler(request, logging))360 );361 362 // One client per person, over HTTP to the served origin.363 const clientOf = (token: Option.Option<string>) =>24 unmodified lines388 const helpers = `${root}/helpers`;389 390 yield* fs.makeDirectory(helpers, { recursive: true }).pipe(Effect.orDie);391 316- const gitOf = (as: Someone): Effect.Effect<GitClient> =>392+ const gitOf = (393+ as: Someone,394+ username: string = as395+ ): Effect.Effect<GitClient> =>396 Effect.gen(function* () {397+ const named = username === as ? as : `${as}-named`;318- const helper = `${helpers}/${as}`;319- const home = `${root}/people/${as}`;398+ const helper = `${helpers}/${named}`;399+ const home = `${root}/people/${named}`;400 401 yield* Effect.orDie(402 Effect.all([323- fs.writeFileString(helper, helperScript(as)),403+ fs.writeFileString(helper, helperScript(as, username)),404 fs.chmod(helper, 0o700),405 fs.makeDirectory(home, { recursive: true }),406 ])407 );103 unmodified lines511 });512 513 return commit;514 }).pipe(Effect.orDie),435- fetch: (request) => Effect.promise(() => handler(request)),515+ fetch: (request) => Effect.promise(() => handler(request, logging)),516 git: (as) => gits[as],517+ gitWithUsername: gitOf,518+ logged: Effect.sync(() => [...logs]),519 origin,520+ print: (at, lane, stdout) =>521+ Effect.sync(() => {522+ printed.set(scriptKey(at, lane), stdout);523+ }),524+ ratchets: (project) =>525+ Option.match(Option.fromUndefinedOr(databases.get(project)), {526+ onNone: () => Effect.succeed([]),527+ onSome: (sql) =>528+ ProjectStore.use((store) => store.load()).pipe(529+ Effect.map(({ ratchets }) => ratchets),530+ Effect.provide(531+ ProjectStoreSqlite.pipe(532+ Layer.provide(Layer.succeedContext(sql))533+ )534+ )535+ ),536+ }),537 rpc: (as) => clients[as],538 script: (at, lane, results) =>539 Effect.sync(() => {540 script.set(12 unmodified linesmodified:packages/checks/src/check-runner/memory.ts+23 added-6 removed
123456789101112131214151617188 unmodified lines272829303132333435363037383940414216 unmodified lines596061625556636465666768697071726573747576777879808182758384858687888990919293942 unmodified lines979899100101102103104105106107/** * `CheckRunner` from a script, for tests: each `(tree or commit, lane)` gets * its scripted results in order, and the last one again once they run out. * A pair with no script is `VerifierBlocked`, as a Checker that cannot run is. * A count lane (`output: "stdout"`) prints what `outputs` scripts for its * pair, a linter's JSON as it was recorded, and nothing when none is. */import type { LaneResult } from "@repo/protocol/domain/answer";import type { LaneName } from "@repo/protocol/ids";import { VerifierBlocked } from "@repo/protocol/refusal";import { Array, Effect, Layer, Option, Ref } from "effect";
import { CheckRunner, shaOf } from "../check-runner.ts";import type { CheckAt, LaneEvidence } from "../check-runner.ts";import type { CheckAt, LaneEvidence, LaneOutput } from "../check-runner.ts";
/** Where a lane's script lives in the map: `<tree or commit sha>:<lane>`. */export const scriptKey = (at: CheckAt, lane: LaneName) => `${shaOf(at)}:${lane}`;8 unmodified lines ? { lane, signature: `${lane}: scripted failure` } : { lane };
export const CheckRunnerMemory = { /** * `script` holds each pair's results; `outputs`, read when a job runs (so * a test may add to it later), the stdout each count lane prints, by the * same key. */ layer: ( script: ReadonlyMap<string, readonly LaneResult[]> script: ReadonlyMap<string, readonly LaneResult[]>, outputs: ReadonlyMap<string, string> = new Map() ): Layer.Layer<CheckRunner> => Layer.effect( CheckRunner, Effect.gen(function* () {16 unmodified lines return CheckRunner.of({ run: (job) => Effect.gen(function* () { // Every lane has a script, or none of them advances. const scripted = yield* Effect.forEach(job.lanes, ({ lane }) => { const key = scriptKey(job.at, lane); const scripted = yield* Effect.forEach(job.lanes, (lane) => { const key = scriptKey(job.at, lane.lane);
return Option.match( Option.filter( Option.fromNullishOr(script.get(key)), Array.isReadonlyArrayNonEmpty ), { onNone: () => Effect.fail(new VerifierBlocked({})), onSome: (results) => Effect.succeed({ key, results }), onSome: (results) => Effect.succeed({ key, lane, results }), } ); });
const lanes = yield* Effect.forEach( scripted, ({ key, results }) => next(key, results) );
return { const printed = scripted.flatMap( ({ key, lane }): readonly LaneOutput[] => lane.output === "stdout" ? [{ lane: lane.lane, stdout: outputs.get(key) ?? "" }] : [] );
const run = { durationMs: lanes.reduce( (total, { durationMs }) => total + durationMs, 0 ),2 unmodified lines .map(evidenceOf), heldBack: [], lanes, };
return printed.length === 0 ? run : { ...run, outputs: printed }; }), }); }) ),};modified:packages/checks/src/kinds/lint-to-zero.ts+50 added-1 removed
2 unmodified lines3456778910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061622 unmodified lines * test. It is red while the rule reports anything there and green at zero, * so an ask of this kind fails on main by the count itself (CAA E). The count * comes from `countLint`, with the rule and territory already applied. */import type { LintCount } from "./lint-count.ts";import { RatchetMeasure } from "@repo/protocol/domain/check";import type { CheckSpec, RatchetSpec } from "@repo/protocol/domain/check";import type { Territory } from "@repo/protocol/domain/territory";import { RatchetName } from "@repo/protocol/ids";import { Effect } from "effect";
import type { CountUnreadable, LintCount } from "./lint-count.ts";import { measure } from "./ratchet.ts";
/** Red: the rule still reports something in the territory. */export const lintToZeroRed = (count: LintCount): boolean => count.total > 0;
/** Green: the rule reports nothing in the territory. */export const lintToZeroGreen = (count: LintCount): boolean => count.total === 0;
/** A `lintToZero` check. */export type LintToZeroCheck = Extract< CheckSpec, { readonly _tag: "LintToZero" }>;
/** The name a `lintToZero` check's count goes by in `measure`. */const countName = RatchetName.make("lint-to-zero");
/** * What a `lintToZero` check counts in what its lint printed: the rule's * findings in the check's territory (a module by its name, else the name * read as a glob), or in `asked`, the ask's own territory, when the check * names none. Read by `measure`, as a ratchet's count is, so the two never * read a lint differently; the lint's exit code is not read. */export const lintToZeroCount = (input: { readonly asked: Territory; readonly check: LintToZeroCheck; readonly modules: readonly Territory[]; readonly stdout: string;}): Effect.Effect<number, CountUnreadable> => { const { asked, check } = input;
const spec: RatchetSpec = { measure: RatchetMeasure.cases.Count.make({ command: check.command, rule: check.rule, }), name: countName, territory: check.territory ?? asked.module, };
return Effect.map( measure(spec, () => Effect.succeed({ code: 0, stdout: input.stdout }), [ asked, ...input.modules, ]), (counts) => counts.reduce((total, { count }) => total + count, 0) );};modified:packages/checks/src/check-runner.ts+29 added-2 removed
41 unmodified lines42 Commit: ({ commit }): string => commit,43 Tree: ({ tree }): string => tree,44 });45 46-/** One lane to run: its name, the project's command for it, and its time limit. */46+/**47+ * One lane to run: its name, the project's command for it, and its time48+ * limit. A lane with `output: "stdout"` is a count (a lint rule's or a49+ * ratchet's), read from what its command prints: the run hands its stdout50+ * back in `CheckRun.outputs`, to the platform alone, never to an answerer.51+ */52 export const CheckLane = Schema.Struct({53 command: Schema.NonEmptyString,54 lane: LaneName,55+ output: Schema.optionalKey(Schema.Literal("stdout")),56 timeoutMs: Schema.optionalKey(57 Schema.Int.pipe(Schema.check(Schema.isGreaterThan(0)))58 ),59 });55 unmodified lines115 NoTests: () => ({ lane, weakness: "no assertion" as const }),116 Passed: () => ({ lane }),117 });118 119+/** What a count lane printed: the stdout its count is read from. */120+export const LaneOutput = Schema.Struct({121+ lane: LaneName,122+ stdout: Schema.String,123+});124+125+export type LaneOutput = typeof LaneOutput.Type;126+127 /**128 * One job's result: each lane, the held-back areas' bits, the whole run's129 * time, and the evidence of every lane that did not pass. Logs never travel116- * here; a lane's `logRef` names where the platform keeps its log.130+ * here; a lane's `logRef` names where the platform keeps its log. A count131+ * lane's stdout does, in `outputs` (one per lane that asked for it), since132+ * its count is read from it.133 */134 export const CheckRun = Schema.Struct({135 durationMs: Schema.Int,136 evidence: Schema.Array(LaneEvidence),137 heldBack: Schema.Array(HeldBackResult),138 lanes: Schema.Array(LaneResult),139+ outputs: Schema.optionalKey(Schema.Array(LaneOutput)),140 });141 142 export type CheckRun = typeof CheckRun.Type;143 144+/** What a count lane of `run` printed; none when the lane did not ask for it, or did not run. */145+export const outputOf = (146+ run: CheckRun,147+ lane: LaneName148+): Option.Option<string> =>149+ Option.map(150+ Option.fromUndefinedOr(run.outputs?.find((each) => each.lane === lane)),151+ ({ stdout }) => stdout152+ );153+154 /**155 * Runs a job's lanes. `VerifierBlocked` means the run could not happen at all156 * (no checkout, no script for it): the gate's trouble, never the answer's.157 */6 unmodified linesmodified:packages/gate/src/escapes.ts+3 added-3 removed
5 unmodified lines6 * territory past its baseline waits for a decider, one `Waiver` per reasoned7 * marker it adds there, instead of landing or being refused.8 *9 * This is a pure function beside the stages, not a stage: a waiting answer10- * is not refused, so the caller (the Answer workflow, 417) opens the11- * decisions.10+ * is not refused, so the caller (the Project DO, when an answer's checks11+ * report; 417) opens the decisions.12 */13 import type { Ask } from "@repo/protocol/domain/ask";14 import { DecisionSubject } from "@repo/protocol/domain/decision";15 import type { Policy } from "@repo/protocol/domain/policy";45 unmodified lines61 * The territory a path counts against: the first module holding it, or the62 * ask's territory for a path no module holds (a root manifest the ask may63 * change).64 */65-const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>65+export const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>66 policy.modules.find((module) => matchAny(module.paths, path))?.module ??67 ask.territory.module;68 69 /**39 unmodified linesmodified:packages/project/src/answer-runs.ts+26 added-1 removed
15 unmodified lines16 LaneResult,17 Verdict,18 } from "@repo/protocol/domain/answer";19 import { Ask } from "@repo/protocol/domain/ask";20+import { RatchetSpec } from "@repo/protocol/domain/check";21 import { Choice } from "@repo/protocol/domain/decision";22 import { AskKind } from "@repo/protocol/domain/kind";23 import { Outcome } from "@repo/protocol/domain/outcome";24 import { RunBlock } from "@repo/protocol/domain/run";25+import { Territory } from "@repo/protocol/domain/territory";26 import {27 AskId,28 CommitSha,29 DecisionId,30 Handle,31 LandedSha,32 LaneName,33+ RatchetName,34 RepoName,35 RepoPath,36 TreeSha,37 } from "@repo/protocol/ids";47 unmodified lines85 effects: Schema.Array(NextStep),86 outcome: Outcome,87 });88 89+/** A ratchet's count in one territory, as a check of a tree measured it. */90+export const MeasuredCount = Schema.Struct({91+ count: Attempt,92+ ratchet: RatchetName,93+ territory: Schema.NonEmptyString,94+});95+96+export type MeasuredCount = typeof MeasuredCount.Type;97+98 /**99 * One answer request as a run needs it: where it stands, whether it holds100 * the project's one landing slot, and the policy's facts its steps use. It101 * crosses the Project Durable Object's boundary, so it is a schema.4 unmodified lines106 /** The ask it answers; absent for a decider's own landing. */107 ask: Schema.optionalKey(Ask),108 /** The lane the ask's own check reports as, which is red on main by design. */109 askLane: Schema.optionalKey(LaneName),110+ /**111+ * What the cheap stage counts on the merged tree: the policy's ratchets,112+ * and the modules a count is split by. Absent without a policy.113+ */114+ counts: Schema.optionalKey(115+ Schema.Struct({116+ modules: Schema.Array(Territory),117+ ratchets: Schema.Array(RatchetSpec),118+ })119+ ),120 /** Whether a decider must finish it before it lands: the ask kind's `finish`. */121 finish: AskKind.fields.finish,122 /** What the checks run on the merged tree: the ask's check first, then every project lane. */123 lanes: Schema.Array(CheckLane),26 unmodified lines150 );151 152 /**153 * What a step saw beside the command it reports: the lanes and held-back132- * areas a check run judged (the verdict is made from them), and the154+ * areas a check run judged (the verdict is made from them), the ratchets it155+ * counted (the project judges them against its baselines), and the156 * bookkeeping a land left unwritten (the project retries it).157 */158 export const AnswerReport = Schema.Struct({159 heldBack: Schema.optionalKey(Schema.Array(HeldBackResult)),160 lanes: Schema.optionalKey(Schema.Array(LaneResult)),161 pending: Schema.optionalKey(162 Schema.Array(Schema.Literals(["mirror", "notes"]))163 ),164+ /** Each ratchet's count on the checked tree, per territory: the project judges them. */165+ ratchets: Schema.optionalKey(Schema.Array(MeasuredCount)),166 });167 168 export type AnswerReport = typeof AnswerReport.Type;169 52 unmodified linesmodified:packages/project/src/deciders.ts+1 added-1 removed
483 unmodified lines484 /**485 * Who decides on `paths`: their deciders, else the project's own (`**`),486 * else its initializer (spec D20). A decision always has someone.487 */488-const decidersOn = (488+export const decidersOn = (489 policy: Policy,490 paths: readonly RepoPath[],491 initializer: Handle492 ): Array.NonEmptyReadonlyArray<Handle> => {1708 unmodified linesmodified:packages/project/src/project.ts+565 added-19 removed
21 unmodified lines22 } from "@repo/artifacts/repo-host";23 import type { RepoNotFound } from "@repo/artifacts/repo-host";24 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";25 import { Brand } from "@repo/brand";26-import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";26+import {27+ CheckAt,28+ CheckLane,29+ CheckRunner,30+ outputOf,31+} from "@repo/checks/check-runner";32+import type { CheckRun } from "@repo/checks/check-runner";33 import { EvidenceStore, LogRef, logOfRef } from "@repo/checks/evidence-store";34 import { findRunBlock } from "@repo/checks/finder";35 import { judgeClosure } from "@repo/checks/judge";36 import { checkVersion, commandFor } from "@repo/checks/kinds";37+import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";38+import type { LintToZeroCheck } from "@repo/checks/kinds/lint-to-zero";39+import { measure } from "@repo/checks/kinds/ratchet";40+import type { RatchetCount } from "@repo/checks/kinds/ratchet";41 import { redFirstOfRuns } from "@repo/checks/red-first";42 import { weaknessesOf } from "@repo/checks/weak-shapes";43+import {44+ escapeDecisions,45+ escapeRatchet,46+ territoryOf,47+} from "@repo/gate/escapes";48+import type { Waiver } from "@repo/gate/escapes";49 import { PushTarget } from "@repo/gate/facts";50 import type { PushFacts } from "@repo/gate/facts";51 import { pushStages, runGate } from "@repo/gate/gate";52 import { scan } from "@repo/gate/stages/shape";34 unmodified lines87 import type { Ask, AskListing } from "@repo/protocol/domain/ask";88 import { CheckSpec } from "@repo/protocol/domain/check";89 import type { ClaimView } from "@repo/protocol/domain/claim";90 import { RefNameText } from "@repo/protocol/domain/common";91+import type { Evidence } from "@repo/protocol/domain/common";92 import type { Credit } from "@repo/protocol/domain/credit";76-import type { Decision } from "@repo/protocol/domain/decision";93+import { DecisionSubject } from "@repo/protocol/domain/decision";94+import type { Choice, Decision } from "@repo/protocol/domain/decision";95 import { ProjectEvent } from "@repo/protocol/domain/event";96 import type { AskKind } from "@repo/protocol/domain/kind";97 import type { LandingView } from "@repo/protocol/domain/landing";98 import { Outcome } from "@repo/protocol/domain/outcome";64 unmodified lines163 Schema,164 Semaphore,165 Struct,166 } from "effect";167+import type { Data } from "effect";168 import { init } from "isomorphic-git";169 170 import { Alarms } from "./alarms.ts";171 import {172 AnswerReport,173 AnswerRun,174+ MeasuredCount,175 ReportedCommand,176 Steps,177 } from "./answer-runs.ts";178 import type { AnswerQueue, AnswerRuns, RunnableEffect } from "./answer-runs.ts";179 import { isStep } from "./answer-runs/steps.ts";180+import { openDecision } from "./attention/decisions.ts";181 import { recordOf } from "./attention/record.ts";182 import { mayClaim, standing } from "./attention/vouch.ts";183 import {184 ClaimCommand,6 unmodified lines191 import type { ClaimStep, Live } from "./claim.ts";192 import {193 deciderDeadlines,194 deciders,195+ decidersOn,196 decidesOn,197 envSchemaMethod,198 isDecider,199 nextDecisionId,23 unmodified lines223 LandingState,224 outcomeOf,225 transition as landingTransition,226 } from "./landing.ts";205-import type { LandingQueue, Request } from "./landing.ts";227+import type { LandingQueue, PendingDecision, Request } from "./landing.ts";228 import {229 isDue,230 outboxRow,231 OutboxBody,9 unmodified lines241 ClaimRow,242 OutboxRow,243 ProjectRow,244 PushEventRow,245+ RatchetRow,246 } from "./project-store/rows.ts";247 import type { Projection } from "./projection.ts";248 import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";249+import { afterLanding, decideRaise, judgeRatchets } from "./ratchets.ts";250+import type {251+ RaiseRatchet,252+ RaiseRequest,253+ RatchetBaseline,254+} from "./ratchets.ts";255 256 /** Every port one project's service runs on. */257 export type ProjectPorts =258 | Alarms378 unmodified lines637 },638 } as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };639 640 /**641+ * What the checks of an answer's last checked tree counted: each of the642+ * policy's ratchets per territory, and each territory's reasoned escapes643+ * once the answer is in (its count on main, and those the answer adds).644+ * The answer's landing writes them to the project's `ratchets` rows.645+ */646+export const Measured = Schema.Struct({647+ declared: Schema.Array(MeasuredCount),648+ escapes: Schema.Array(MeasuredCount),649+});650+651+export type Measured = typeof Measured.Type;652+653+/**654 * Where one answer stands, as its row keeps it: the landing lifecycle's655 * state, the receipt its request was first given (a replay gets it again),614- * and the verdict on its last checked tree.656+ * the verdict on its last checked tree, what that tree counted, and each657+ * `Waiver` a decider accepted for this answer (checked again after main658+ * moved, it is not asked again; another answer to the ask is).659 */660 export const AnswerRecord = Schema.Struct({661 landing: LandingState,662+ measured: Schema.optionalKey(Measured),663 receipt: AnswerReceipt,664 verdict: Schema.optionalKey(Verdict),665+ waived: Schema.optionalKey(Schema.Array(DecisionSubject.cases.Waiver)),666 });667 668 export type AnswerRecord = typeof AnswerRecord.Type;669 99 unmodified lines769 readonly policy: Option.Option<Policy>;770 readonly project: Option.Option<ProjectRow>;771 readonly proposals: readonly Proposal[];772 readonly queue: LandingQueue;773+ /** Every ratchet's baseline per territory, the escape ratchets' included. */774+ readonly ratchets: readonly RatchetRow[];775 }776 777 /**778 * What one call writes, gathered as it goes and committed at its end. The12 unmodified lines791 readonly project: Map<"row", ProjectRow>;792 readonly proposals: Map<ProposalId, Proposal>;793 readonly pushEvents: PushEventRow[];794 readonly queue: Map<"queue", LandingQueue>;795+ /** Keyed by ratchet and territory (`ratchetKey`). */796+ readonly ratchets: Map<string, RatchetRow>;797 }798 799 const writesOf = (): Writes => ({800 answers: new Map(),7 unmodified lines808 project: new Map(),809 proposals: new Map(),810 pushEvents: [],811 queue: new Map(),812+ ratchets: new Map(),813 });814 815 const isEmpty = (writes: Writes) =>816 [8 unmodified lines825 writes.project.size,826 writes.proposals.size,827 writes.pushEvents.length,828 writes.queue.size,829+ writes.ratchets.size,830 ].every((count) => count === 0);831 832 const claimKey = (ask: AskId, claimant: Handle) =>833 JSON.stringify([ask, claimant.toLowerCase()]);71 unmodified lines905 /** What a check of `ask` runs, and the lane it reports as. */906 const askLaneOf = (policy: Policy, ask: Ask) =>907 commandFor(ask.check, policy.run, policy.ratchets);908 909+/**910+ * The lane an ask's check runs as: a `lintToZero` check is a count, so its911+ * lane hands back what its lint printed.912+ */913+const askCheckLane = (policy: Policy, ask: Ask) =>914+ Option.map(askLaneOf(policy, ask), ({ command, lane }) =>915+ CheckSpec.guards.LintToZero(ask.check)916+ ? CheckLane.make({ command, lane, output: "stdout" })917+ : CheckLane.make({ command, lane })918+ );919+920 /** The lanes an answer's checks run: the ask's own check, then every project lane. */921 const lanesOf = (922 policy: Policy,923 ask: Option.Option<Ask>924 ): readonly CheckLane[] => [925 ...Option.toArray(863- Option.flatMap(ask, (asked) =>864- Option.map(askLaneOf(policy, asked), ({ command, lane }) =>865- CheckLane.make({ command, lane })866- )867- )926+ Option.flatMap(ask, (asked) => askCheckLane(policy, asked))927 ),928 ...Record.toEntries(policy.run.checks).map(([lane, command]) =>929 CheckLane.make({ command, lane })930 ),931 ];932 933+/**934+ * The policy's ratchets that `command` counts, read from what it printed:935+ * one count per ratchet and territory. A ratchet whose count can't be read936+ * there is left out, and its first answer's landing sets its baseline.937+ */938+const countedBy = (policy: Policy, command: string, stdout: string) =>939+ Effect.map(940+ Effect.forEach(941+ policy.ratchets.filter((spec) => spec.measure.command === command),942+ (spec) =>943+ measure(944+ spec,945+ () => Effect.succeed({ code: 0, stdout }),946+ policy.modules947+ ).pipe(948+ Effect.catchTag("CountUnreadable", (unread) =>949+ Effect.as(950+ Effect.logWarning(951+ `the ratchet ${spec.name} has no count in what its command printed`,952+ unread953+ ),954+ []955+ )956+ )957+ )958+ ),959+ (counts): readonly RatchetCount[] => counts.flat()960+ );961+962+/** A ratchet row's key in a call's writes: its ratchet and territory. */963+const ratchetKey = (row: {964+ readonly ratchet: string;965+ readonly territory: string;966+}) => JSON.stringify([row.ratchet, row.territory]);967+968+/** A row as `ratchets.ts` reads a baseline. */969+const baselineOf = (row: RatchetRow): RatchetBaseline => ({970+ count: row.count,971+ ratchet: row.ratchet,972+ setAt: row.at,973+ territory: row.territory,974+});975+976+/**977+ * Whether a row is a territory's escape ratchet's (`escapeRatchet`), which978+ * has no command: its count is the territory's reasoned escapes on main,979+ * moved by those each landing adds.980+ */981+const isEscapeRow = (row: {982+ readonly ratchet: string;983+ readonly territory: string;984+}) => row.ratchet === escapeRatchet(row.territory);985+986+/** Whether two `Waiver`s are about one escape: one ask, one marker and reason, one line. */987+const sameEscape = (one: Waiver) => (other: Waiver) =>988+ other.ask === one.ask &&989+ other.marker === one.marker &&990+ other.reason === one.reason &&991+ other.at.path === one.at.path &&992+ other.at.line === one.at.line;993+994+/** What a decider just decided for an answer waiting on it: the subject, and the choice in its words. */995+interface DecidedOn {996+ readonly choice: Choice;997+ readonly subject: PendingDecision["subject"];998+}999+1000+/** The decision `command` takes, when it is one the answer waiting in `before` waits on. */1001+const decidedOn = (1002+ before: LandingState,1003+ command: LandingCommand1004+): Option.Option<DecidedOn> =>1005+ LandingCommand.$is("Decided")(command) &&1006+ LandingState.guards.AwaitingDecision(before)1007+ ? Option.map(1008+ Option.fromUndefinedOr(1009+ before.decisions.find(({ id }) => id === command.decision)1010+ ),1011+ ({ subject }) => ({ choice: command.choice, subject })1012+ )1013+ : Option.none();1014+1015+/** The `Waiver`s a decider accepted for an answer: those it had, and the one just accepted. */1016+const waivedAfter = (1017+ waived: readonly Waiver[],1018+ decided: Option.Option<DecidedOn>1019+): readonly Waiver[] => [1020+ ...waived,1021+ ...Option.toArray(1022+ Option.flatMap(decided, ({ choice, subject }) =>1023+ choice === "accept" && DecisionSubject.guards.Waiver(subject)1024+ ? Option.some(subject)1025+ : Option.none()1026+ )1027+ ),1028+];1029+1030+/** What a decider weighs for one subject an answer waits on. */1031+const evidenceFor = (1032+ request: Request,1033+ subject: Waiver | RaiseRatchet1034+): readonly Evidence[] => [1035+ {1036+ label: "answer",1037+ value: `${request.answerer} at ${request.head} (${request.requestId})`,1038+ },1039+ DecisionSubject.guards.Waiver(subject)1040+ ? {1041+ label: "escape",1042+ value: `${subject.at.path}:${subject.at.line}: ${subject.marker} -- ${subject.reason}`,1043+ }1044+ : {1045+ label: "ratchet",1046+ value: `${subject.ratchet} in ${subject.territory}: ${subject.before} to ${subject.after}`,1047+ },1048+];1049+1050+/**1051+ * A `lintToZero` check is red first by its count: twice on the composed1052+ * commit its rule reports something in its territory, the same number1053+ * both times (CAA E). Gives what the policy's ratchets count in the same1054+ * lint, for their baselines at the ask's opening.1055+ */1056+const redByCount = (input: {1057+ readonly ask: Ask;1058+ readonly check: LintToZeroCheck;1059+ readonly lane: LaneName;1060+ readonly policy: Policy;1061+ readonly runs: readonly [CheckRun, CheckRun];1062+}) =>1063+ Effect.gen(function* () {1064+ const { ask, check, policy } = input;1065+1066+ const read = (run: CheckRun) =>1067+ Effect.fromOption(outputOf(run, input.lane)).pipe(1068+ Effect.flatMap((stdout) =>1069+ Effect.map(1070+ lintToZeroCount({1071+ asked: ask.territory,1072+ check,1073+ modules: policy.modules,1074+ stdout,1075+ }),1076+ (count) => ({ count, stdout })1077+ )1078+ ),1079+ Effect.mapError(() => new NotRedFirst({}))1080+ );1081+1082+ const [first, second] = input.runs;1083+ const once = yield* read(first);1084+ const again = yield* read(second);1085+1086+ if (once.count === 0 || once.count !== again.count) {1087+ return yield* new NotRedFirst({});1088+ }1089+1090+ return yield* countedBy(policy, check.command, once.stdout);1091+ });1092+1093 /** A section of a brief, when it has lines. */1094 const section = (heading: string, lines: readonly string[] | undefined) =>1095 lines === undefined || lines.length === 01096 ? []273 unmodified lines1370 policy,1371 project: snapshot.project,1372 proposals: snapshot.proposals,1373 queue: yield* queueOf(snapshot.queue),1374+ ratchets: snapshot.ratchets,1375 };1376 });1377 1378 /** The project row once it is live: it has a landed SHA. */7 unmodified lines1386 /** The ask as this call has it: as written so far, or as hydrated. */1387 const askNow = (h: Hydrated, writes: Writes, id: AskId) =>1388 Option.fromUndefinedOr(writes.asks.get(id) ?? h.asks.get(id));1389 1390+ /** The `ratchets` rows as this call has them: written so far, over the hydrated ones. */1391+ const ratchetsNow = (1392+ h: Hydrated,1393+ writes: Writes1394+ ): readonly RatchetRow[] => [1395+ ...h.ratchets.map((row) => writes.ratchets.get(ratchetKey(row)) ?? row),1396+ ...[...writes.ratchets.values()].filter(1397+ (row) =>1398+ !h.ratchets.some((held) => ratchetKey(held) === ratchetKey(row))1399+ ),1400+ ];1401+1402+ /** The baselines of the policy's ratchets, as this call has them; the escape ratchets apart. */1403+ const baselinesNow = (h: Hydrated, writes: Writes) =>1404+ ratchetsNow(h, writes)1405+ .filter((row) => !isEscapeRow(row))1406+ .map(baselineOf);1407+1408+ /** Writes each baseline that differs from the row this call has for it. */1409+ const putRatchets = (1410+ h: Hydrated,1411+ writes: Writes,1412+ baselines: readonly RatchetBaseline[]1413+ ) => {1414+ const held = new Map(1415+ ratchetsNow(h, writes).map((row) => [ratchetKey(row), row])1416+ );1417+1418+ for (const baseline of baselines) {1419+ const row: RatchetRow = {1420+ at: baseline.setAt,1421+ count: baseline.count,1422+ ratchet: baseline.ratchet,1423+ territory: baseline.territory,1424+ };1425+1426+ const before = held.get(ratchetKey(row));1427+1428+ if (before?.count !== row.count || before.at !== row.at) {1429+ writes.ratchets.set(ratchetKey(row), row);1430+ }1431+ }1432+ };1433+1434 const ownClaim = (h: Hydrated, ask: AskId, handle: Handle) =>1435 Option.fromUndefinedOr(1436 h.claims.find(1437 ({ row }) => row.ask === ask && sameHandle(row.claimant, handle)78 unmodified lines1516 landings: writes.landings,1517 outbox,1518 proposals: [...writes.proposals.values()],1519 pushEvents: writes.pushEvents,1520+ ratchets: [...writes.ratchets.values()],1521 ...field(1522 "project",1523 Option.fromUndefinedOr(writes.project.get("row"))1524 ),553 unmodified lines2078 state: landing,2079 ...field("ask", ask),2080 ...field("askLane", askLane),2081 ...field(2082+ "counts",2083+ Option.map(h.policy, ({ modules, ratchets }) => ({2084+ modules,2085+ ratchets,2086+ }))2087+ ),2088+ ...field(2089 "run",2090 Option.map(h.policy, ({ run }) => run)2091 ),2092 ...Option.getOrElse(judgedRun, () => ({})),307 unmodified lines2400 (row) => input.writes.outbox.push(row)2401 );2402 };2403 2404+ /**2405+ * The checks' report on the tree under way, judged against the2406+ * project's ratchets (spec §5 step 7 (b), (e)). Each of the policy's2407+ * ratchets the merged tree counts over its baseline is refused2408+ * `Weakened{ratchet}`, unless a reasoned escape the answer adds in its2409+ * territory asks to raise it (`RaiseRatchet`); each reasoned escape over2410+ * its territory's escape baseline waits on a `Waiver`, unless a decider2411+ * already accepted it for this answer (`waived`: a re-check after main2412+ * moved asks nothing twice). Nothing waits once something refused; the2413+ * decisions open with their subject's default, `decline`. The answer's2414+ * lines unread are the gate's trouble (`VerifierBlocked`): no escape2415+ * lands unweighed. What the tree counted is kept for the answer's2416+ * landing.2417+ */2418+ const ratchetJudged = (input: {2419+ readonly checking: Checking;2420+ readonly command: Data.TaggedEnum.Value<LandingCommand, "Checked">;2421+ readonly h: Hydrated;2422+ readonly now: DateTime.Utc;2423+ readonly report: AnswerReport | undefined;2424+ readonly waived: readonly Waiver[];2425+ readonly writes: Writes;2426+ }) =>2427+ Effect.gen(function* () {2428+ const { checking, command, h, now, writes } = input;2429+ const { request } = checking;2430+ const ask = Option.flatMap(request.ask, (id) => askNow(h, writes, id));2431+ const known = Option.all({ ask, policy: h.policy, row: h.project });2432+2433+ if (Option.isNone(known)) {2434+ return { command, measured: Option.none<Measured>() };2435+ }2436+2437+ const { ask: asked, policy } = known.value;2438+ const { initializer } = known.value.row;2439+2440+ const escapeBaselines = new Map(2441+ ratchetsNow(h, writes)2442+ .filter(isEscapeRow)2443+ .map(({ count, ratchet }) => [ratchet, count])2444+ );2445+2446+ const facts = yield* withPorts(2447+ pushFacts({2448+ ask,2449+ base: request.base,2450+ claim: Option.none(),2451+ claimsHeld: 0,2452+ head: request.head,2453+ landed: checking.main,2454+ policy,2455+ project: name,2456+ pusher: Person.make({ handle: request.answerer }),2457+ ref: mainRef,2458+ repo: request.fork,2459+ })2460+ ).pipe(2461+ Effect.tapError((unread) =>2462+ Effect.logWarning(2463+ `the lines of answer ${request.requestId} could not be read for its escapes`,2464+ unread2465+ )2466+ ),2467+ Effect.result2468+ );2469+2470+ const waivers = Result.match(facts, {2471+ onFailure: (): readonly Waiver[] => [],2472+ onSuccess: (found) =>2473+ escapeDecisions({ ...found, ratchetBaselines: escapeBaselines }),2474+ });2475+2476+ const unread = Result.isFailure(facts) ? [new VerifierBlocked({})] : [];2477+2478+ const territoryIn = (waiver: Waiver) =>2479+ territoryOf(policy, asked, waiver.at.path);2480+2481+ // A reasoned escape in a territory explains a raise there.2482+ const raises = waivers.flatMap((waiver): readonly RaiseRequest[] =>2483+ policy.ratchets.map(({ name: ratchet }) => ({2484+ ratchet,2485+ reason: waiver.reason,2486+ territory: territoryIn(waiver),2487+ }))2488+ );2489+2490+ const declared = input.report?.ratchets ?? [];2491+2492+ const judgement = judgeRatchets({2493+ ask: asked.id,2494+ baselines: baselinesNow(h, writes),2495+ measured: declared,2496+ raises,2497+ });2498+2499+ const escapes = Array.dedupe(waivers.map(territoryIn)).map(2500+ (territory): MeasuredCount => {2501+ const ratchet = escapeRatchet(territory);2502+2503+ return {2504+ count:2505+ (escapeBaselines.get(ratchet) ?? 0) +2506+ waivers.filter((waiver) => territoryIn(waiver) === territory)2507+ .length,2508+ ratchet,2509+ territory,2510+ };2511+ }2512+ );2513+2514+ const refusals = [2515+ ...command.refusals,2516+ ...unread,2517+ ...judgement.refusals,2518+ ];2519+2520+ const asking = Array.isReadonlyArrayEmpty(refusals)2521+ ? [2522+ ...waivers.filter(2523+ (waiver) => !input.waived.some(sameEscape(waiver))2524+ ),2525+ ...judgement.decisions,2526+ ]2527+ : [];2528+2529+ const changed = checking.changes.map(({ path }) => path);2530+2531+ const pending = asking.map((subject): PendingDecision => {2532+ const decision = openDecision({2533+ deciders: decidersOn(2534+ policy,2535+ DecisionSubject.guards.Waiver(subject)2536+ ? [subject.at.path]2537+ : changed,2538+ initializer2539+ ),2540+ evidence: evidenceFor(request, subject),2541+ expireDays: policy.budget.expireDays,2542+ id: nextDecisionId(h.decisions, writes.decisions),2543+ now,2544+ project: name,2545+ subject,2546+ });2547+2548+ writes.decisions.set(decision.id, decision);2549+2550+ return { id: decision.id, subject };2551+ });2552+2553+ return {2554+ command: LandingCommand.Checked({2555+ ...command,2556+ decisions: [...command.decisions, ...pending],2557+ refusals,2558+ }),2559+ measured: Option.some<Measured>({ declared, escapes }),2560+ };2561+ });2562+2563+ /** An accepted `RaiseRatchet` the answer waits on raises its baseline: the one way a baseline rises. */2564+ const raiseOnDecision = (2565+ h: Hydrated,2566+ writes: Writes,2567+ decided: Option.Option<DecidedOn>2568+ ) => {2569+ const live = liveRow(h);2570+2571+ if (Option.isNone(decided) || Option.isNone(live)) {2572+ return;2573+ }2574+2575+ const { choice, subject } = decided.value;2576+2577+ if (DecisionSubject.guards.RaiseRatchet(subject)) {2578+ putRatchets(2579+ h,2580+ writes,2581+ decideRaise(2582+ baselinesNow(h, writes),2583+ subject,2584+ choice,2585+ live.value.landed2586+ )2587+ );2588+ }2589+ };2590+2591+ /**2592+ * A landing's counts become the baselines: each of the policy's2593+ * ratchets lowered where the landed tree counts less (or set, where it2594+ * had none), and each territory's escapes as they stand with the2595+ * answer's in; the gate let no raise land that a decider did not accept.2596+ */2597+ const ratchetsAtLanding = (2598+ h: Hydrated,2599+ writes: Writes,2600+ measured: Option.Option<Measured>,2601+ sha: LandedSha2602+ ) => {2603+ if (Option.isNone(measured)) {2604+ return;2605+ }2606+2607+ const { declared, escapes } = measured.value;2608+2609+ putRatchets(h, writes, [2610+ ...afterLanding(baselinesNow(h, writes), declared, sha).baselines,2611+ ...escapes.map(({ count, ratchet, territory }) => ({2612+ count,2613+ ratchet,2614+ setAt: sha,2615+ territory,2616+ })),2617+ ]);2618+ };2619+2620 /** One reported step of an answer, under the lock: its transition and all it settles. */2621 const advanceBody =2134- (requestId: RequestId, command: LandingCommand, report?: AnswerReport) =>2622+ (requestId: RequestId, reported: LandingCommand, report?: AnswerReport) =>2623 (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2624 Effect.gen(function* () {2625 const found = findAnswer(h, requestId);2626 2 unmodified lines2629 }2630 2631 const { record, row } = found.value;2632 const before = record.landing;2633+2634+ const counted =2635+ LandingCommand.$is("Checked")(reported) &&2636+ LandingState.guards.Checking(before) &&2637+ before.tree === reported.tree2638+ ? yield* ratchetJudged({2639+ checking: before,2640+ command: reported,2641+ h,2642+ now,2643+ report,2644+ waived: record.waived ?? [],2645+ writes,2646+ })2647+ : { command: reported, measured: Option.none<Measured>() };2648+2649+ const { command } = counted;2650 const { effects, state } = landingTransition(before, command, now);2651 const { request } = state;2652 2653+ const measured = Option.orElse(counted.measured, () =>2654+ Option.fromUndefinedOr(record.measured)2655+ );2656+2657+ const decided = decidedOn(before, command);2658+ const waived = waivedAfter(record.waived ?? [], decided);2659+2660+ raiseOnDecision(h, writes, decided);2661+2662+ if (2663+ LandingState.guards.Landed(state) &&2664+ LandingState.guards.Landing(before)2665+ ) {2666+ ratchetsAtLanding(h, writes, measured, state.sha);2667+ }2668+2669 const ask = Option.flatMap(request.ask, (id) =>2670 askNow(h, writes, id)2671 );2672 56 unmodified lines2729 encodeAnswer({2730 ...record,2731 landing: state,2732 ...field("verdict", verdict),2733+ ...field("measured", measured),2734+ ...field(2735+ "waived",2736+ Option.liftPredicate(waived, Array.isReadonlyArrayNonEmpty)2737+ ),2738 })2739 ),2740 updatedAt: now,2741 });187 unmodified lines2929 }),2930 (refusals) => Array.findFirst(refusals, isTouchedJudge)2931 );2932 2407- /** Red first: the ask's check fails twice on the composed commit, the same way. */2933+ /**2934+ * Red first: the ask's check fails twice on the composed commit, the2935+ * same way (a `lintToZero` check, by its count). Gives the counts of the2936+ * policy's ratchets the check's own run read on the way.2937+ */2938 const redTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>2939 Effect.gen(function* () {2410- const lane = askLaneOf(policy, ask);2940+ const lane = askCheckLane(policy, ask);2941 2942 if (Option.isNone(lane)) {2943 return yield* new NotRedFirst({});2944 }2945 2946 const job = {2947 at: CheckAt.cases.Commit.make({ commit: composed }),2418- lanes: [CheckLane.make(lane.value)],2948+ lanes: [lane.value],2949 placeholders: [],2950 project: name,2951 proxies: [],2952 repo,2953 run: policy.run,2954 };2955 2426- const first = yield* runner.run(job);2427- const second = yield* runner.run(job);2956+ const runs = [yield* runner.run(job), yield* runner.run(job)] as const;2957 2429- return yield* Effect.fromResult(2430- redFirstOfRuns([first, second], lane.value.lane)2431- );2958+ if (CheckSpec.guards.LintToZero(ask.check)) {2959+ return yield* redByCount({2960+ ask,2961+ check: ask.check,2962+ lane: lane.value.lane,2963+ policy,2964+ runs,2965+ });2966+ }2967+2968+ yield* Effect.fromResult(redFirstOfRuns(runs, lane.value.lane));2969+2970+ return [];2971 });2972 2973 /** The landing that opens an ask: its files on main, authored by its asker. */2974 const landAsk = (input: {123 unmodified lines3098 if (Option.isSome(weak)) {3099 return yield* new WeakCheck({ weakness: weak.value });3100 }3101 2563- yield* redTwice(policy, ask, composed.commit);3102+ const counted = yield* redTwice(policy, ask, composed.commit);3103 3104 const landed = yield* landAsk({3105 ask,3106 credits: opening.credits,20 unmodified lines3127 "row",3128 yield* withPolicyAt({ ...row, landed: landed.sha }, landed.sha, now)3129 );3130 3131+ // The opening landing records the baselines its check's lint read.3132+ putRatchets(3133+ h,3134+ writes,3135+ afterLanding(baselinesNow(h, writes), counted, landed.sha).baselines3136+ );3137+3138 return { ask: opened, landed: landed.sha };3139 });3140 3141 const openBody =851 unmodified linesmodified:packages/project/test/project.test.ts+159 added-3 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { Brand } from "@repo/brand";4-import { CheckAt } from "@repo/checks/check-runner";4+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";5 import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";6 import { Verdict } from "@repo/protocol/domain/answer";7 import type { Ask } from "@repo/protocol/domain/ask";8 import { CheckSpec } from "@repo/protocol/domain/check";9 import { ClaimView } from "@repo/protocol/domain/claim";10-import { Glob } from "@repo/protocol/domain/common";10+import { Command, Glob } from "@repo/protocol/domain/common";11 import { Outcome } from "@repo/protocol/domain/outcome";12 import {13 AskId,14 LandedSha,20 unmodified lines35 UnknownProject,36 } from "@repo/protocol/refusal";37 import { advanceTo, at as instant } from "@repo/testkit/clock";38 import type { Files } from "@repo/testkit/git-client";39-import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";39 import {40+ aProject,41+ withAsk,42+ withKind,43+ withVouches,44+} from "@repo/testkit/scenarios";45+import {46 Array,47 DateTime,48 Effect,49 Exit,50 Layer,51 Option,52+ Ref,53 Result,54 Schema,55 } from "effect";56 1222 unmodified lines1279 }1280 )1281 );1282 });1283+1284+/** A `lintToZero` ask over parser, in a project whose kinds list `lintToZero`. */1285+const noAny = AskId.make("no-any");1286+1287+const lintScenario = aProject({ people }).pipe(1288+ withVouches(people),1289+ withKind({1290+ checkKind: "lintToZero",1291+ claimers: "vouched",1292+ finish: "never",1293+ name: "lintToZero",1294+ oneWay: false,1295+ race: 1,1296+ requires: ["want", "check", "territory"],1297+ strength: "assertion",1298+ }),1299+ withAsk({1300+ check: CheckSpec.cases.LintToZero.make({1301+ command: Command.make("oxlint --format json"),1302+ rule: "typescript/no-explicit-any",1303+ }),1304+ id: noAny,1305+ kind: "lintToZero",1306+ territory: "packages/parser",1307+ })1308+);1309+1310+/** What `oxlint --format json` prints with `count` explicit `any`s in parser. */1311+const lintPrinting = (count: number) =>1312+ JSON.stringify({1313+ // `Array.makeBy` makes at least one: none is its own case.1314+ diagnostics:1315+ count === 01316+ ? []1317+ : Array.makeBy(count, (line) => ({1318+ code: "typescript(no-explicit-any)",1319+ filename: "packages/parser/src/parse.ts",1320+ labels: [1321+ { span: { column: 1, length: 3, line: line + 1, offset: 0 } },1322+ ],1323+ message: "Unexpected `any`. Specify a different type.",1324+ severity: "error",1325+ })),1326+ number_of_files: 1,1327+ number_of_rules: 1,1328+ });1329+1330+/**1331+ * A Checker whose lint prints `counts` in turn, one run after another: every1332+ * run fails (the lint exits 1 on any finding), so only the count tells two1333+ * runs apart.1334+ */1335+const lintPrints = (counts: readonly number[]) =>1336+ Layer.effect(1337+ CheckRunner,1338+ Effect.gen(function* () {1339+ const left = yield* Ref.make(counts);1340+1341+ return CheckRunner.of({1342+ run: (job) =>1343+ Effect.gen(function* () {1344+ const count = yield* Ref.modify(left, ([next = 0, ...rest]) => [1345+ next,1346+ rest,1347+ ]);1348+1349+ return {1350+ durationMs: 1,1351+ evidence: job.lanes.map(({ lane }) => ({1352+ lane,1353+ signature: `${lane}: lint exited 1`,1354+ })),1355+ heldBack: [],1356+ lanes: job.lanes.map(({ command, lane }) => ({1357+ command,1358+ durationMs: 1,1359+ lane,1360+ result: "failed" as const,1361+ })),1362+ outputs: job.lanes.flatMap(({ lane, output }) =>1363+ output === "stdout"1364+ ? [{ lane, stdout: lintPrinting(count) }]1365+ : []1366+ ),1367+ };1368+ }),1369+ });1370+ })1371+ );1372+1373+/** alice opens the `lintToZero` ask, its lint counting `counts` on main, run by run. */1374+const openingByCount = (counts: readonly number[]) =>1375+ Effect.gen(function* () {1376+ yield* advanceTo("2026-10-07T12:00:00Z");1377+1378+ const api = yield* projectService(project);1379+1380+ yield* api.initProject(alice, {});1381+1382+ const first = yield* Pusher.use((pusher) =>1383+ pusher.push(repo, Option.none(), start, "Start")1384+ );1385+1386+ yield* api.recordFirstPush(alice, first);1387+1388+ const { file } = Option.getOrThrow(1389+ Array.findFirst(lintScenario.policy.asks, ({ id }) => id === noAny)1390+ );1391+1392+ return yield* Effect.result(1393+ api.openAsk(alice, {1394+ ask: noAny,1395+ files: Array.make({1396+ content: `export default "${noAny}";\n`,1397+ path: file,1398+ }),1399+ })1400+ );1401+ }).pipe(1402+ // The world's Checker, in place of the scripted one.1403+ Effect.provide(1404+ Layer.merge(worldOf(lintScenario, "memory"), lintPrints(counts))1405+ )1406+ );1407+1408+describe("opening a lintToZero ask", () => {1409+ it.effect(1410+ "is red first when its rule counts the same, above zero, twice on main",1411+ () =>1412+ Effect.map(openingByCount([3, 3]), (opened) => {1413+ expect(1414+ Result.map(opened, ({ ask }) => [ask.id, ask.check._tag])1415+ ).toStrictEqual(Result.succeed([noAny, "LintToZero"]));1416+ })1417+ );1418+1419+ it.effect("is refused NotRedFirst when its rule counts nothing on main", () =>1420+ Effect.map(openingByCount([0, 0]), (opened) => {1421+ expect(opened).toStrictEqual(Result.fail(new NotRedFirst({})));1422+ })1423+ );1424+1425+ it.effect(1426+ "is refused NotRedFirst when the two runs on main count differently",1427+ () =>1428+ Effect.map(openingByCount([3, 2]), (opened) => {1429+ expect(opened).toStrictEqual(Result.fail(new NotRedFirst({})));1430+ })1431+ );1432+});