Skip to content
Myr

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

15 files+2179 added−89 removed

modified:apps/platform/src/adapters/custody.ts+53 added-3 removed
24 unmodified lines
25 * 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 */35import type { RepoName } from "@repo/artifacts/repo-host";36import { Custody } from "@repo/git/custody";37import type { Command } from "@repo/git/custody";38import type { ProjectApi } from "@repo/project/project";39import { Projects } from "@repo/project/projects";40import type { HarnessAudit } from "@repo/protocol/audit";41import { RequestId, sameHandle } from "@repo/protocol/ids";42import type { AskId, CommitSha, Handle, ProjectName } from "@repo/protocol/ids";43import { Principal } from "@repo/protocol/principal";44import type { Person } from "@repo/protocol/principal";
223 unmodified lines
268 )269 );270 });271272/** What a push's log lines and span carry: who pushes, to which kind of repo, through which harness. */273type PushAnnotations = HarnessAudit & {274 readonly pusher: string;275 readonly target: RepoKind["_tag"];276};277278const 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});287288/**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 */293const 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 });305306/** Custody that takes every push as it comes: a person's own working fork. */307const takeAll = custodyOf(308 () => [],309 () => Effect.succeed([])
6 unmodified lines
316317/**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 */324export 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 }334335 const projects = yield* Projects;336 const annotations = annotationsOf(pusher, kind, audit);337338 yield* Effect.logInfo("a push reached custody").pipe(339 Effect.annotateLogs(annotations)340 );341294 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 });351352 return annotated(custody, annotations);353 });
modified:apps/platform/src/workflows/answer/lanes.ts+185 added-13 removed
8 unmodified lines
9 *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 */14import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";19import {20 CheckAt,21 CheckLane,22 CheckRunner,23 outputOf,24} from "@repo/checks/check-runner";25import type { CheckRun, LaneEvidence } from "@repo/checks/check-runner";26import { EvidenceStore } from "@repo/checks/evidence-store";27import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";28import { measure } from "@repo/checks/kinds/ratchet";29import { classifyFailure } from "@repo/gate/classify";18import { runBlockOf } from "@repo/project/answer-runs";30import { MeasuredCount, runBlockOf } from "@repo/project/answer-runs";31import type { AnswerRun } from "@repo/project/answer-runs";32import { LandingState } from "@repo/project/landing";33import {34 HeldBackResult,35 LaneOutcome,36 LaneResult,37} from "@repo/protocol/domain/answer";38import { CheckSpec } from "@repo/protocol/domain/check";39import { AskKind } from "@repo/protocol/domain/kind";40import { RunBlock } from "@repo/protocol/domain/run";41import {42 CommitSha,43 LandedSha,44 LaneName,45 ProjectName,46 RatchetName,47 RepoName,48 RepoPath,49 RequestId,50 TreeSha,
3 unmodified lines
54 Flake,55 StaleBase,56 VerifierBlocked,57} from "@repo/protocol/refusal";44import { Array, Effect, Option, Order, Schema } from "effect";58import { Array, Effect, Option, Order, Result, Schema } from "effect";5960/**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 */65export const cheapLanes = ["format", "lint", "types"] as const;6667/** Which of the answer's lanes a stage runs. */
58 unmodified lines
126 /** 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});138139export type StageRun = typeof StageRun.Type;
160 unmodified lines
300 run.run === undefined ? asked : { ...asked, run: run.run }301 );302};303304/** A job's run with one lane's result, and its evidence, put in place of what it was. */305const 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});317318/**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 */325const countedAskLane = (326 run: AnswerRun,327 ran: CheckRun328): Effect.Effect<CheckRun> => {329 const { ask, askLane } = run;330331 const result = ran.lanes.find(({ lane }) => lane === askLane);332333 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 }342343 const { check } = ask;344345 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};375376/** What the cheap stage counted: each ratchet per territory, or the one whose count it could not read. */377interface Counted {378 readonly counts: readonly MeasuredCount[];379 readonly uncounted: Option.Option<RatchetName>;380}381382/**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 */387const 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 ?? [];393394 if (!Array.isReadonlyArrayNonEmpty(specs)) {395 return { counts: [], uncounted: Option.none() };396 }397398 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 );404405 const ran = yield* job(lanes);406407 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 );417418 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);425426 return Result.match(counts, {427 onFailure: (name) => ({ counts: [], uncounted: Option.some(name) }),428 onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),429 });430 });431432/** What a stage run says of the counts: them, and the ratchet whose count it could not read. */433const 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 });438439/**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 */446export const runStage = (447 run: AnswerRun,448 tree: TreeSha,
10 unmodified lines
459 const remerges = LandingState.guards.Checking(run.state)460 ? run.state.remerges461 : 0;462463 const counting = stage === "cheap" && run.counts !== undefined;464309 if (!Array.isReadonlyArrayNonEmpty(lanes)) {465 if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {466 return StageRun.cases.Ran.make({ checked, heldBack: [], lanes: [] });467 }468469 const block = yield* runBlockOf(checked);470471 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)));483484 const counts = counting485 ? countFields(yield* countRatchets(run, job))486 : {};487488 if (!Array.isReadonlyArrayNonEmpty(lanes)) {489 return StageRun.cases.Ran.make({490 checked,491 heldBack: [],492 lanes: [],493 ...counts,494 });495 }496497 const firstRun = yield* job(lanes);498 const first = byLane(firstRun);499
28 unmodified lines
528 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 lines
modified:apps/platform/src/workflows/answer/program.ts+36 added-6 removed
46 unmodified lines
47import type { Verdict } from "@repo/protocol/domain/answer";48import type { Outcome } from "@repo/protocol/domain/outcome";49import { CommitSha } from "@repo/protocol/ids";50import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";51import { VerifierBlocked } from "@repo/protocol/refusal";52import {53 Array,54 Cause,55 Data,
206 unmodified lines
262 };263 });264265/**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 */270const 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([]);279280/**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 */288const 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);295277 // 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 };300301 const judged =302 StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0303 ? yield* stage(params, call.tree, "checks", attempt)304 : undefined;305306 const last = judged ?? cheap;307308 const counts = StageRun.guards.Ran(cheap.ran)309 ? Option.fromUndefinedOr(cheap.ran.counts)310 : Option.none();311312 return StageRun.match(last.ran, {313 Blocked: ({ attempt: at }) =>314 reported(LandingCommand.Blocked({ attempt: at })),315 Moved: () => Option.none(),
12 unmodified lines
328 ? 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 lines
modified:apps/platform/src/credential.ts+23 added-9 removed
modified:apps/platform/src/git.ts+6 added-3 removed
21 unmodified lines
22import { Anonymous, Principal } from "@repo/protocol/principal";23import { Effect, Option, Ref } from "effect";2425import { custodyFor, refuseAll } from "./adapters/custody.ts";26import { credentialOf } from "./credential.ts";26import { auditOf, credentialOf } from "./credential.ts";27import { repoKind, RepoKind } from "./repo-names.ts";28import { Sessions } from "./sessions.ts";2930/** What serving git needs: who is calling, their projects, and the git server behind. */
107 unmodified lines
138139 // 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;149150 const response = yield* gateway(request).pipe(
18 unmodified lines
added: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 */14import { describe, expect, it } from "@effect/vitest";15import { Brand } from "@repo/brand";16import { CheckAt } from "@repo/checks/check-runner";17import { Verdict } from "@repo/protocol/domain/answer";18import { DecisionSubject } from "@repo/protocol/domain/decision";19import type { Choice } from "@repo/protocol/domain/decision";20import { Outcome } from "@repo/protocol/domain/outcome";21import {22 AskId,23 LaneName,24 ProjectName,25 RatchetName,26 RepoPath,27 TreeSha,28} from "@repo/protocol/ids";29import type { CommitSha } from "@repo/protocol/ids";30import { Weakened } from "@repo/protocol/refusal";31import { Array, Effect, Order, Schema } from "effect";3233import { pushRequestId } from "../src/adapters/custody.ts";34import { coreLoopWorld } from "./world.ts";35import type { CoreLoopWorld, GitClient, Someone } from "./world.ts";3637const project = ProjectName.make("burrow");3839const noAnyInParser = AskId.make("no-any-in-parser");4041const formatIso = AskId.make("format-iso");4243const decodeRaw = AskId.make("decode-raw");4445const ratchet = RatchetName.make("no-explicit-any");4647/** The lane the ratchet's count runs in, named for the ratchet. */48const ratchetLane = LaneName.make(ratchet);4950/** The lane a `lintToZero` ask's check runs in. */51const lintToZero = LaneName.make("lintToZero");5253/** The lane a `redThenGreen` ask's check runs in. */54const redThenGreen = LaneName.make("redThenGreen");5556/** The project's lint, which prints JSON. */57const lint = "oxlint --format json";5859const rule = "typescript/no-explicit-any";6061/** Where the config folder's sdk is imported from, as a maintainer writes it. */62const sdk = `${Brand.cliPackage}/rules`;6364const parsePath = "packages/parser/src/parse.ts";6566const formatPath = "packages/format/src/format.ts";6768const codecPath = "packages/parser/src/codec.ts";6970/** Three explicit `any`s in parser, two in format: what main starts with. */71const anyParse =72 "export const parse = (s: any): any => ({ year: Number(s as any) });\n";7374const anyFormat = "export const format = (d: any, f: any) => String(d);\n";7576/** The project as dora first pushes it: two packages, the config folder, the vouches. */77const 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};9899/** The lint-to-zero ask's one file: no explicit `any` left in parser. */100const 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});114115/** A `fix` ask's files in `module`: its file, and its check, which asserts on `subject`. */116const 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 );154155const 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});161162const rawFiles = fixFiles(decodeRaw, "parser", "parser decodes raw input", {163 call: 'decode("2026")',164 file: "codec.ts",165 is: '"2026"',166 name: "decode",167});168169/** One `typescript/no-explicit-any` finding, as oxlint 1.87 prints it. */170const 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});179180/** What `oxlint --format json` prints for these findings. */181const 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 });191192const mainFindings = [193 [formatPath, 1],194 [formatPath, 1],195 [parsePath, 1],196 [parsePath, 1],197 [parsePath, 1],198] as const;199200const formatOnly = [201 [formatPath, 1],202 [formatPath, 1],203] as const;204205/** The lines git printed from the server's side band, less git's padding. */206const remoteLines = (stderr: string) =>207 stderr208 .split("\n")209 .filter((line) => line.startsWith("remote: "))210 .map((line) => line.trimEnd());211212/** A person in a trailer: their handle and the address the platform gives them. */213const credited = (handle: string) =>214 `${handle} <${handle}@users.${Brand.domain}>`;215216/** A baseline as the tests read it: `[ratchet, territory, count]`. */217type Baseline = readonly [ratchet: string, territory: string, count: number];218219/** Each baseline, in name order. */220const 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 );233234/** The tree of `head` in a work tree: where an answer whose base is main is checked. */235const 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 );239240/** The verdict note on `head` in the clone at `work`, read with plain git. */241const noteOn = (git: GitClient, work: string, head: CommitSha) =>242 Effect.gen(function* () {243 const ref = `refs/notes/${Brand.slug}`;244245 yield* git.ok(work, "fetch", "--quiet", "origin", `${ref}:${ref}`);246247 const shown = yield* git.ok(248 work,249 "notes",250 `--ref=${Brand.slug}`,251 "show",252 head253 );254255 return yield* Schema.decodeEffect(Schema.fromJsonString(Verdict))(256 shown257 ).pipe(Effect.orDie);258 });259260/** `as`'s answer, pushed: it claims `ask`, clones its fork and commits `files`. */261const 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);276277 return { claim, head, pushed, tree, work };278 });279280/** The merged tree's lanes, scripted: the ratchet's count, and the ask's own check. */281const 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";293294 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 });299300/**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 */305const ratchetStory = (world: CoreLoopWorld) =>306 Effect.gen(function* () {307 const dora = world.rpc("dora");308 const doraGit = world.git("dora");309310 // dora makes the project and pushes its first tree.311 yield* dora.initProject({ project });312313 const home = yield* doraGit.clone(`${world.origin}/${project}.git`);314315 yield* doraGit.commit(home, "Start burrow", start);316 yield* doraGit.push(home);317318 // 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 });322323 yield* world.script(composedLint, lintToZero, ["failed", "failed"]);324 yield* world.print(composedLint, lintToZero, oxlintReport(mainFindings));325326 const opened = yield* dora.openAsk({327 ask: noAnyInParser,328 files: lintFiles,329 project,330 });331332 const afterOpening = yield* baselines(world);333334 // 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 }348349 // 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 );356357 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 });364365 yield* scriptAnswer(world, typed.tree, {366 askLane: lintToZero,367 askResult: "failed",368 findings: formatOnly,369 });370 yield* world.settle();371372 const landed = (yield* world.rpc("alice").status({ project })).answers;373 const afterLanding = yield* baselines(world);374375 const pushLog = (yield* world.logged).filter(({ annotations }) =>376 annotations.has("harness")377 );378379 // 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");382383 const widened = yield* answer(world, "bob", bobGit, {384 ask: formatIso,385 files: { [formatPath]: "export const format = (d: any, f: any) => d;\n" },386 });387388 yield* scriptAnswer(world, widened.tree, {389 askLane: redThenGreen,390 askResult: "passed",391 findings: [...formatOnly, [parsePath, 1]],392 });393 yield* world.settle();394395 const bob = world.rpc("bob");396397 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 });411412/**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 */417const escapeStory = (world: CoreLoopWorld, choice: Choice) =>418 Effect.gen(function* () {419 const aliceGit = world.git("alice");420421 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 });431432 yield* scriptAnswer(world, escaped.tree, {433 askLane: redThenGreen,434 askResult: "passed",435 findings: formatOnly,436 });437 yield* world.settle();438439 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);444445 const [waiver] = today.decisions;446447 if (waiver === undefined) {448 return { before, today, waiting };449 }450451 yield* dora.decide({ choice, decision: waiver.id, project });452 yield* world.settle();453454 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 });465466/**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 */471const 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 });483484 yield* scriptAnswer(world, raised.tree, {485 askLane: redThenGreen,486 askResult: "passed",487 findings: [...formatOnly, [codecPath, 2]],488 });489 yield* world.settle();490491 const dora = world.rpc("dora");492 const today = yield* dora.today({ project });493 const before = yield* baselines(world);494495 for (const { id } of today.decisions) {496 yield* dora.decide({ choice: "accept", decision: id, project });497 }498499 yield* world.settle();500501 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 });508509/**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 */515const againStory = (world: CoreLoopWorld) =>516 Effect.gen(function* () {517 const aliceGit = world.git("alice");518 const escape = "// @ts-expect-error -- the codec boundary erases types";519520 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 });530531 yield* scriptAnswer(world, first.tree, {532 askLane: redThenGreen,533 askResult: "passed",534 findings: [...formatOnly, [codecPath, 2]],535 });536 yield* world.settle();537538 const dora = world.rpc("dora");539540 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 }547548 yield* world.settle();549550 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 });557558 yield* aliceGit.push(first.work);559560 yield* scriptAnswer(world, yield* treeOf(aliceGit, first.work, head), {561 askLane: redThenGreen,562 askResult: "passed",563 findings: formatOnly,564 });565 yield* world.settle();566567 return {568 answers: (yield* world.rpc("alice").status({ project })).answers,569 baselines: yield* baselines(world),570 today: (yield* dora.today({ project })).decisions,571 };572 });573574/**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 */579const movedStory = (world: CoreLoopWorld, widened: { readonly work: string }) =>580 Effect.gen(function* () {581 const aliceGit = world.git("alice");582 const bobGit = world.git("bob");583584 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 });594595 yield* scriptAnswer(world, escaped.tree, {596 askLane: redThenGreen,597 askResult: "passed",598 findings: formatOnly,599 });600 yield* world.settle();601602 // 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 });607608 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();615616 // 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 );624625 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 });636637 yield* scriptAnswer(world, remerged, {638 askLane: redThenGreen,639 askResult: "passed",640 findings: [],641 });642643 const dora = world.rpc("dora");644 const asked = (yield* dora.today({ project })).decisions;645646 for (const { id } of asked) {647 yield* dora.decide({ choice: "accept", decision: id, project });648 }649650 yield* world.settle();651652 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 });659660const parserZero: Baseline = [ratchet, "parser", 0];661662const formatTwo: Baseline = [ratchet, "format", 2];663664describe("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;672673 const weakened = new Weakened({674 weakening: { after: 1, before: 0, ratchet, territory: "parser" },675 });676677 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 });704705 // 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 );720721 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");729730 yield* doraGit.ok(home, "fetch", "--quiet", "origin");731732 const landed = yield* doraGit.ok(home, "rev-parse", "origin/main");733734 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 );769770 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");777778 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 );806807 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);814815 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 );847848 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);855856 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 );875876 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);883884 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 lines
22 * 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 */31import { NodeHttpServer, NodeServices } from "@effect/platform-node";32import { SqliteClient } from "@effect/sql-sqlite-node";33import { RefName, RepoHost } from "@repo/artifacts/repo-host";
8 unmodified lines
42import { FrontPageMemory } from "@repo/project/front-page/memory";43import { Lander } from "@repo/project/lander";44import { LanderIsogit } from "@repo/project/lander/isogit";45import { FinishersFromChecks } from "@repo/project/project";46import { ProjectStore } from "@repo/project/project-store";47import type { RatchetRow } from "@repo/project/project-store/rows";48import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";49import { ProjectionMemory } from "@repo/project/projection/memory";50import { Contracts } from "@repo/protocol/contracts";51import type { Client } from "@repo/protocol/contracts";52import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";
4 unmodified lines
57import { git, gitOk } from "@repo/testkit/git";58import type { Ran } from "@repo/testkit/git";59import { httpBackend } from "@repo/testkit/http-backend";60import type { Scope } from "effect";54import { Array, Context, Effect, FileSystem, Layer, Option, Ref } from "effect";61import {62 Array,63 Context,64 Effect,65 FileSystem,66 Layer,67 Logger,68 Option,69 Ref,70 References,71} from "effect";72import {73 FetchHttpClient,74 HttpClient,75 HttpClientRequest,76 HttpServer,77 HttpServerRequest,78 HttpServerResponse,79} from "effect/http";80import { RpcClient, RpcSerialization } from "effect/rpc";81import type { SqlClient } from "effect/sql/SqlClient";8283import { DoProjects } from "../src/adapters/do-projects.ts";84import { WorkerFetch } from "../src/adapters/fetch.ts";85import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";
36 unmodified lines
122 files: Readonly<Record<string, string>>123 ) => Effect.Effect<CommitSha>;124}125126/** One line the Worker's handler logged, with its annotations as text. */127export interface Logged {128 readonly message: string;129 readonly annotations: ReadonlyMap<string, string>;130}131132/** The world a core-loop test drives. */133export 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 lines
160 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 lines
210 });211212/**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 */171const helperScript = (as: Someone) =>217const 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 lines
247 );248249 // 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[] = [];255256 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 });266267 // 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 lines
301 ),302 })303 );304305 // Each DO's database, kept so a test can read its rows back.306 const databases = new Map<string, Context.Context<SqlClient>>();307308 // 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 );316317 databases.set(name, sql);318249 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 );330331 const ports = base.pipe(332 Context.merge(yield* Layer.build(DoProjects(namespace)))333 );334335 // Every request the handler serves logs through the keeper too.336 const logging = yield* Layer.build(337 Logger.layer([keeper], { mergeWithExisting: true })338 );339340 // 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 lines
355356 yield* Effect.addFinalizer(() => Effect.promise(dispose));357358 const origin = yield* listen((request) =>283 Effect.promise(() => handler(request))359 Effect.promise(() => handler(request, logging))360 );361362 // One client per person, over HTTP to the served origin.363 const clientOf = (token: Option.Option<string>) =>
24 unmodified lines
388 const helpers = `${root}/helpers`;389390 yield* fs.makeDirectory(helpers, { recursive: true }).pipe(Effect.orDie);391316 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}`;400401 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 lines
511 });512513 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 lines
modified:packages/checks/src/check-runner/memory.ts+23 added-6 removed
modified:packages/checks/src/kinds/lint-to-zero.ts+50 added-1 removed
modified:packages/checks/src/check-runner.ts+29 added-2 removed
41 unmodified lines
42 Commit: ({ commit }): string => commit,43 Tree: ({ tree }): string => tree,44 });4546/** 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 */52export 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 lines
115 NoTests: () => ({ lane, weakness: "no assertion" as const }),116 Passed: () => ({ lane }),117 });118119/** What a count lane printed: the stdout its count is read from. */120export const LaneOutput = Schema.Struct({121 lane: LaneName,122 stdout: Schema.String,123});124125export type LaneOutput = typeof LaneOutput.Type;126127/**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 */134export 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});141142export type CheckRun = typeof CheckRun.Type;143144/** What a count lane of `run` printed; none when the lane did not ask for it, or did not run. */145export 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 );153154/**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 lines
modified:packages/gate/src/escapes.ts+3 added-3 removed
5 unmodified lines
6 * 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 */13import type { Ask } from "@repo/protocol/domain/ask";14import { DecisionSubject } from "@repo/protocol/domain/decision";15import type { Policy } from "@repo/protocol/domain/policy";
45 unmodified lines
61 * 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 */65const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>65export const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>66 policy.modules.find((module) => matchAny(module.paths, path))?.module ??67 ask.territory.module;6869/**
39 unmodified lines
modified:packages/project/src/answer-runs.ts+26 added-1 removed
15 unmodified lines
16 LaneResult,17 Verdict,18} from "@repo/protocol/domain/answer";19import { Ask } from "@repo/protocol/domain/ask";20import { RatchetSpec } from "@repo/protocol/domain/check";21import { Choice } from "@repo/protocol/domain/decision";22import { AskKind } from "@repo/protocol/domain/kind";23import { Outcome } from "@repo/protocol/domain/outcome";24import { RunBlock } from "@repo/protocol/domain/run";25import { Territory } from "@repo/protocol/domain/territory";26import {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 lines
85 effects: Schema.Array(NextStep),86 outcome: Outcome,87});8889/** A ratchet's count in one territory, as a check of a tree measured it. */90export const MeasuredCount = Schema.Struct({91 count: Attempt,92 ratchet: RatchetName,93 territory: Schema.NonEmptyString,94});9596export type MeasuredCount = typeof MeasuredCount.Type;9798/**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 lines
106 /** 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 lines
150 );151152/**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 */158export 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});167168export type AnswerReport = typeof AnswerReport.Type;169
52 unmodified lines
modified:packages/project/src/deciders.ts+1 added-1 removed
483 unmodified lines
484/**485 * Who decides on `paths`: their deciders, else the project's own (`**`),486 * else its initializer (spec D20). A decision always has someone.487 */488const decidersOn = (488export const decidersOn = (489 policy: Policy,490 paths: readonly RepoPath[],491 initializer: Handle492): Array.NonEmptyReadonlyArray<Handle> => {
1708 unmodified lines
modified:packages/project/src/project.ts+565 added-19 removed
21 unmodified lines
22} from "@repo/artifacts/repo-host";23import type { RepoNotFound } from "@repo/artifacts/repo-host";24import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";25import { Brand } from "@repo/brand";26import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";26import {27 CheckAt,28 CheckLane,29 CheckRunner,30 outputOf,31} from "@repo/checks/check-runner";32import type { CheckRun } from "@repo/checks/check-runner";33import { EvidenceStore, LogRef, logOfRef } from "@repo/checks/evidence-store";34import { findRunBlock } from "@repo/checks/finder";35import { judgeClosure } from "@repo/checks/judge";36import { checkVersion, commandFor } from "@repo/checks/kinds";37import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";38import type { LintToZeroCheck } from "@repo/checks/kinds/lint-to-zero";39import { measure } from "@repo/checks/kinds/ratchet";40import type { RatchetCount } from "@repo/checks/kinds/ratchet";41import { redFirstOfRuns } from "@repo/checks/red-first";42import { weaknessesOf } from "@repo/checks/weak-shapes";43import {44 escapeDecisions,45 escapeRatchet,46 territoryOf,47} from "@repo/gate/escapes";48import type { Waiver } from "@repo/gate/escapes";49import { PushTarget } from "@repo/gate/facts";50import type { PushFacts } from "@repo/gate/facts";51import { pushStages, runGate } from "@repo/gate/gate";52import { scan } from "@repo/gate/stages/shape";
34 unmodified lines
87import type { Ask, AskListing } from "@repo/protocol/domain/ask";88import { CheckSpec } from "@repo/protocol/domain/check";89import type { ClaimView } from "@repo/protocol/domain/claim";90import { RefNameText } from "@repo/protocol/domain/common";91import type { Evidence } from "@repo/protocol/domain/common";92import type { Credit } from "@repo/protocol/domain/credit";76import type { Decision } from "@repo/protocol/domain/decision";93import { DecisionSubject } from "@repo/protocol/domain/decision";94import type { Choice, Decision } from "@repo/protocol/domain/decision";95import { ProjectEvent } from "@repo/protocol/domain/event";96import type { AskKind } from "@repo/protocol/domain/kind";97import type { LandingView } from "@repo/protocol/domain/landing";98import { Outcome } from "@repo/protocol/domain/outcome";
64 unmodified lines
163 Schema,164 Semaphore,165 Struct,166} from "effect";167import type { Data } from "effect";168import { init } from "isomorphic-git";169170import { Alarms } from "./alarms.ts";171import {172 AnswerReport,173 AnswerRun,174 MeasuredCount,175 ReportedCommand,176 Steps,177} from "./answer-runs.ts";178import type { AnswerQueue, AnswerRuns, RunnableEffect } from "./answer-runs.ts";179import { isStep } from "./answer-runs/steps.ts";180import { openDecision } from "./attention/decisions.ts";181import { recordOf } from "./attention/record.ts";182import { mayClaim, standing } from "./attention/vouch.ts";183import {184 ClaimCommand,
6 unmodified lines
191import type { ClaimStep, Live } from "./claim.ts";192import {193 deciderDeadlines,194 deciders,195 decidersOn,196 decidesOn,197 envSchemaMethod,198 isDecider,199 nextDecisionId,
23 unmodified lines
223 LandingState,224 outcomeOf,225 transition as landingTransition,226} from "./landing.ts";205import type { LandingQueue, Request } from "./landing.ts";227import type { LandingQueue, PendingDecision, Request } from "./landing.ts";228import {229 isDue,230 outboxRow,231 OutboxBody,
9 unmodified lines
241 ClaimRow,242 OutboxRow,243 ProjectRow,244 PushEventRow,245 RatchetRow,246} from "./project-store/rows.ts";247import type { Projection } from "./projection.ts";248import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";249import { afterLanding, decideRaise, judgeRatchets } from "./ratchets.ts";250import type {251 RaiseRatchet,252 RaiseRequest,253 RatchetBaseline,254} from "./ratchets.ts";255256/** Every port one project's service runs on. */257export type ProjectPorts =258 | Alarms
378 unmodified lines
637 },638} as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };639640/**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 */646export const Measured = Schema.Struct({647 declared: Schema.Array(MeasuredCount),648 escapes: Schema.Array(MeasuredCount),649});650651export type Measured = typeof Measured.Type;652653/**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 */660export 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});667668export type AnswerRecord = typeof AnswerRecord.Type;669
99 unmodified lines
769 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}776777/**778 * What one call writes, gathered as it goes and committed at its end. The
12 unmodified lines
791 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}798799const writesOf = (): Writes => ({800 answers: new Map(),
7 unmodified lines
808 project: new Map(),809 proposals: new Map(),810 pushEvents: [],811 queue: new Map(),812 ratchets: new Map(),813});814815const isEmpty = (writes: Writes) =>816 [
8 unmodified lines
825 writes.project.size,826 writes.proposals.size,827 writes.pushEvents.length,828 writes.queue.size,829 writes.ratchets.size,830 ].every((count) => count === 0);831832const claimKey = (ask: AskId, claimant: Handle) =>833 JSON.stringify([ask, claimant.toLowerCase()]);
71 unmodified lines
905/** What a check of `ask` runs, and the lane it reports as. */906const askLaneOf = (policy: Policy, ask: Ask) =>907 commandFor(ask.check, policy.run, policy.ratchets);908909/**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 */913const 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 );919920/** The lanes an answer's checks run: the ask's own check, then every project lane. */921const 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];932933/**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 */938const 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 );961962/** A ratchet row's key in a call's writes: its ratchet and territory. */963const ratchetKey = (row: {964 readonly ratchet: string;965 readonly territory: string;966}) => JSON.stringify([row.ratchet, row.territory]);967968/** A row as `ratchets.ts` reads a baseline. */969const baselineOf = (row: RatchetRow): RatchetBaseline => ({970 count: row.count,971 ratchet: row.ratchet,972 setAt: row.at,973 territory: row.territory,974});975976/**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 */981const isEscapeRow = (row: {982 readonly ratchet: string;983 readonly territory: string;984}) => row.ratchet === escapeRatchet(row.territory);985986/** Whether two `Waiver`s are about one escape: one ask, one marker and reason, one line. */987const 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;993994/** What a decider just decided for an answer waiting on it: the subject, and the choice in its words. */995interface DecidedOn {996 readonly choice: Choice;997 readonly subject: PendingDecision["subject"];998}9991000/** The decision `command` takes, when it is one the answer waiting in `before` waits on. */1001const 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();10141015/** The `Waiver`s a decider accepted for an answer: those it had, and the one just accepted. */1016const 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];10291030/** What a decider weighs for one subject an answer waits on. */1031const 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];10491050/**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 */1056const 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;10651066 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 );10811082 const [first, second] = input.runs;1083 const once = yield* read(first);1084 const again = yield* read(second);10851086 if (once.count === 0 || once.count !== again.count) {1087 return yield* new NotRedFirst({});1088 }10891090 return yield* countedBy(policy, check.command, once.stdout);1091 });10921093/** A section of a brief, when it has lines. */1094const section = (heading: string, lines: readonly string[] | undefined) =>1095 lines === undefined || lines.length === 01096 ? []
273 unmodified lines
1370 policy,1371 project: snapshot.project,1372 proposals: snapshot.proposals,1373 queue: yield* queueOf(snapshot.queue),1374 ratchets: snapshot.ratchets,1375 };1376 });13771378 /** The project row once it is live: it has a landed SHA. */
7 unmodified lines
1386 /** 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));13891390 /** 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 ];14011402 /** 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);14071408 /** 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 );14171418 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 };14251426 const before = held.get(ratchetKey(row));14271428 if (before?.count !== row.count || before.at !== row.at) {1429 writes.ratchets.set(ratchetKey(row), row);1430 }1431 }1432 };14331434 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 lines
1516 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 lines
2078 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 lines
2400 (row) => input.writes.outbox.push(row)2401 );2402 };24032404 /**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 });24322433 if (Option.isNone(known)) {2434 return { command, measured: Option.none<Measured>() };2435 }24362437 const { ask: asked, policy } = known.value;2438 const { initializer } = known.value.row;24392440 const escapeBaselines = new Map(2441 ratchetsNow(h, writes)2442 .filter(isEscapeRow)2443 .map(({ count, ratchet }) => [ratchet, count])2444 );24452446 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 );24692470 const waivers = Result.match(facts, {2471 onFailure: (): readonly Waiver[] => [],2472 onSuccess: (found) =>2473 escapeDecisions({ ...found, ratchetBaselines: escapeBaselines }),2474 });24752476 const unread = Result.isFailure(facts) ? [new VerifierBlocked({})] : [];24772478 const territoryIn = (waiver: Waiver) =>2479 territoryOf(policy, asked, waiver.at.path);24802481 // 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 );24892490 const declared = input.report?.ratchets ?? [];24912492 const judgement = judgeRatchets({2493 ask: asked.id,2494 baselines: baselinesNow(h, writes),2495 measured: declared,2496 raises,2497 });24982499 const escapes = Array.dedupe(waivers.map(territoryIn)).map(2500 (territory): MeasuredCount => {2501 const ratchet = escapeRatchet(territory);25022503 return {2504 count:2505 (escapeBaselines.get(ratchet) ?? 0) +2506 waivers.filter((waiver) => territoryIn(waiver) === territory)2507 .length,2508 ratchet,2509 territory,2510 };2511 }2512 );25132514 const refusals = [2515 ...command.refusals,2516 ...unread,2517 ...judgement.refusals,2518 ];25192520 const asking = Array.isReadonlyArrayEmpty(refusals)2521 ? [2522 ...waivers.filter(2523 (waiver) => !input.waived.some(sameEscape(waiver))2524 ),2525 ...judgement.decisions,2526 ]2527 : [];25282529 const changed = checking.changes.map(({ path }) => path);25302531 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 });25472548 writes.decisions.set(decision.id, decision);25492550 return { id: decision.id, subject };2551 });25522553 return {2554 command: LandingCommand.Checked({2555 ...command,2556 decisions: [...command.decisions, ...pending],2557 refusals,2558 }),2559 measured: Option.some<Measured>({ declared, escapes }),2560 };2561 });25622563 /** 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);25702571 if (Option.isNone(decided) || Option.isNone(live)) {2572 return;2573 }25742575 const { choice, subject } = decided.value;25762577 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 };25902591 /**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 }26062607 const { declared, escapes } = measured.value;26082609 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 };26192620 /** 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 lines
2629 }26302631 const { record, row } = found.value;2632 const before = record.landing;26332634 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>() };26482649 const { command } = counted;2650 const { effects, state } = landingTransition(before, command, now);2651 const { request } = state;26522653 const measured = Option.orElse(counted.measured, () =>2654 Option.fromUndefinedOr(record.measured)2655 );26562657 const decided = decidedOn(before, command);2658 const waived = waivedAfter(record.waived ?? [], decided);26592660 raiseOnDecision(h, writes, decided);26612662 if (2663 LandingState.guards.Landed(state) &&2664 LandingState.guards.Landing(before)2665 ) {2666 ratchetsAtLanding(h, writes, measured, state.sha);2667 }26682669 const ask = Option.flatMap(request.ask, (id) =>2670 askNow(h, writes, id)2671 );2672
56 unmodified lines
2729 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 lines
2929 }),2930 (refusals) => Array.findFirst(refusals, isTouchedJudge)2931 );29322407 /** 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);29412942 if (Option.isNone(lane)) {2943 return yield* new NotRedFirst({});2944 }29452946 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 };29552426 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;29572429 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 }29672968 yield* Effect.fromResult(redFirstOfRuns(runs, lane.value.lane));29692970 return [];2971 });29722973 /** The landing that opens an ask: its files on main, authored by its asker. */2974 const landAsk = (input: {
123 unmodified lines
3098 if (Option.isSome(weak)) {3099 return yield* new WeakCheck({ weakness: weak.value });3100 }31012563 yield* redTwice(policy, ask, composed.commit);3102 const counted = yield* redTwice(policy, ask, composed.commit);31033104 const landed = yield* landAsk({3105 ask,3106 credits: opening.credits,
20 unmodified lines
3127 "row",3128 yield* withPolicyAt({ ...row, landed: landed.sha }, landed.sha, now)3129 );31303131 // 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 );31373138 return { ask: opened, landed: landed.sha };3139 });31403141 const openBody =
851 unmodified lines
modified:packages/project/test/project.test.ts+159 added-3 removed
1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { CheckAt } from "@repo/checks/check-runner";4import { CheckAt, CheckRunner } from "@repo/checks/check-runner";5import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";6import { Verdict } from "@repo/protocol/domain/answer";7import type { Ask } from "@repo/protocol/domain/ask";8import { CheckSpec } from "@repo/protocol/domain/check";9import { ClaimView } from "@repo/protocol/domain/claim";10import { Glob } from "@repo/protocol/domain/common";10import { Command, Glob } from "@repo/protocol/domain/common";11import { Outcome } from "@repo/protocol/domain/outcome";12import {13 AskId,14 LandedSha,
20 unmodified lines
35 UnknownProject,36} from "@repo/protocol/refusal";37import { advanceTo, at as instant } from "@repo/testkit/clock";38import type { Files } from "@repo/testkit/git-client";39import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";39import {40 aProject,41 withAsk,42 withKind,43 withVouches,44} from "@repo/testkit/scenarios";45import {46 Array,47 DateTime,48 Effect,49 Exit,50 Layer,51 Option,52 Ref,53 Result,54 Schema,55} from "effect";56
1222 unmodified lines
1279 }1280 )1281 );1282});12831284/** A `lintToZero` ask over parser, in a project whose kinds list `lintToZero`. */1285const noAny = AskId.make("no-any");12861287const 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);13091310/** What `oxlint --format json` prints with `count` explicit `any`s in parser. */1311const 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 });13291330/**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 */1335const lintPrints = (counts: readonly number[]) =>1336 Layer.effect(1337 CheckRunner,1338 Effect.gen(function* () {1339 const left = yield* Ref.make(counts);13401341 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 ]);13481349 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 );13721373/** alice opens the `lintToZero` ask, its lint counting `counts` on main, run by run. */1374const openingByCount = (counts: readonly number[]) =>1375 Effect.gen(function* () {1376 yield* advanceTo("2026-10-07T12:00:00Z");13771378 const api = yield* projectService(project);13791380 yield* api.initProject(alice, {});13811382 const first = yield* Pusher.use((pusher) =>1383 pusher.push(repo, Option.none(), start, "Start")1384 );13851386 yield* api.recordFirstPush(alice, first);13871388 const { file } = Option.getOrThrow(1389 Array.findFirst(lintScenario.policy.asks, ({ id }) => id === noAny)1390 );13911392 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 );14071408describe("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 );14181419 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 );14241425 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});