Merge build/216-checks-runs-and-runner: a check run says whether it failed for the right reason, and runs locally or scripted
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 6a1eb62, ed08887 · Browse files · 22 files·+2571 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+2571 added−10 removed
- tests:+1335 added−10 removed
- other:+1236 added−0 removed
Provenance
- Commit
a61af0e- Tree
094be48- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
6a1eb62- Parent 2
ed08887
22 files changed+2571 added−10 removed
added:packages/checks/src/check-runner/local.ts+171 added
1+/**2+ * `CheckRunner` as real processes on this machine, for the CLI's `check`:3+ * each job gets a checkout from the caller (the CLI makes a git worktree), and4+ * each lane runs there under `sh -c`, one after another, to its time limit.5+ *6+ * It reaches nothing a lane would not: no network of its own, no git config7+ * from this machine (`GIT_CONFIG_GLOBAL=/dev/null`, as `@repo/testkit/git`8+ * runs git), no repo but the checkout (a hook's `GIT_DIR` is unset), and a9+ * `HOME` in a temp dir it removes after the job. Placeholders10+ * and proxies are the Checker's; here a lane sees the user's own env. A sealed11+ * suite runs only in the Checker, so a job with one is `VerifierBlocked`.12+ */13+import { VerifierBlocked } from "@repo/protocol/refusal";14+import { Duration, Effect, FileSystem, Layer, Option, Stream } from "effect";15+import type { Scope } from "effect";16+import { ChildProcess, ChildProcessSpawner } from "effect/process";17+18+import { CheckRunner, evidenceFrom } from "../check-runner.ts";19+import type { CheckAt, CheckLane } from "../check-runner.ts";20+import { classifyRun } from "../classify.ts";21+import type { RunExit } from "../classify.ts";22+23+export interface LocalOptions {24+ /** Makes the job's tree a directory, removed when the scope closes. */25+ readonly checkout: (26+ at: CheckAt27+ ) => Effect.Effect<string, VerifierBlocked, Scope.Scope>;28+}29+30+/** A lane with no time limit of its own gets ten minutes. */31+const DEFAULT_TIMEOUT = Duration.minutes(10);32+33+/** After the time limit's SIGTERM, how long a lane has before SIGKILL. */34+const FORCE_KILL_AFTER = Duration.seconds(2);35+36+// Fixed identity and dates, English messages, no prompts, no colours, and no37+// git config from this machine. A git hook that runs the CLI exports where38+// its own repo is and any `git -c` config; those are unset (an `undefined`39+// value leaves a variable out), so a lane's git sees only the checkout.40+const fixedEnv = {41+ CI: "1",42+ FORCE_COLOR: "0",43+ GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,44+ GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",45+ GIT_AUTHOR_EMAIL: "answerer@example.com",46+ GIT_AUTHOR_NAME: "Answerer",47+ GIT_COMMITTER_DATE: "2026-10-06T12:00:00Z",48+ GIT_COMMITTER_EMAIL: "answerer@example.com",49+ GIT_COMMITTER_NAME: "Answerer",50+ GIT_COMMON_DIR: undefined,51+ GIT_CONFIG: undefined,52+ GIT_CONFIG_COUNT: undefined,53+ GIT_CONFIG_GLOBAL: "/dev/null",54+ GIT_CONFIG_NOSYSTEM: "1",55+ GIT_CONFIG_PARAMETERS: undefined,56+ GIT_DIR: undefined,57+ GIT_INDEX_FILE: undefined,58+ GIT_NAMESPACE: undefined,59+ GIT_OBJECT_DIRECTORY: undefined,60+ GIT_PREFIX: undefined,61+ GIT_TERMINAL_PROMPT: "0",62+ GIT_WORK_TREE: undefined,63+ LC_ALL: "C",64+ NO_COLOR: "1",65+};66+67+const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>68+ bytes.pipe(Stream.decodeText(), Stream.mkString);69+70+const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };71+72+export const CheckRunnerLocal = {73+ layer: (74+ options: LocalOptions75+ ): Layer.Layer<76+ CheckRunner,77+ never,78+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem79+ > =>80+ Layer.effect(81+ CheckRunner,82+ Effect.gen(function* () {83+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;84+ const fs = yield* FileSystem.FileSystem;85+86+ // One lane to its end or its time limit. A process a signal ended87+ // has no exit code: -1. The scope's close kills its process group.88+ const exitOf = (cwd: string, home: string, lane: CheckLane) =>89+ Effect.scoped(90+ Effect.gen(function* () {91+ const child = yield* spawner.spawn(92+ ChildProcess.make("sh", ["-c", lane.command], {93+ cwd,94+ env: { ...fixedEnv, HOME: home, TMPDIR: home },95+ extendEnv: true,96+ forceKillAfter: FORCE_KILL_AFTER,97+ })98+ );99+100+ const [stdout, stderr, code] = yield* Effect.all(101+ [102+ text(child.stdout),103+ text(child.stderr),104+ child.exitCode.pipe(105+ Effect.map(Number),106+ Effect.orElseSucceed(() => -1)107+ ),108+ ],109+ { concurrency: "unbounded" }110+ );111+112+ return { code, stderr, stdout } satisfies RunExit;113+ })114+ ).pipe(115+ Effect.timeoutOption(116+ lane.timeoutMs === undefined117+ ? DEFAULT_TIMEOUT118+ : Duration.millis(lane.timeoutMs)119+ ),120+ Effect.map(Option.getOrElse(() => timedOut)),121+ Effect.mapError(() => new VerifierBlocked({}))122+ );123+124+ const runLane = (cwd: string, home: string, lane: CheckLane) =>125+ Effect.map(126+ Effect.timed(exitOf(cwd, home, lane)),127+ ([elapsed, exit]) => ({128+ exit,129+ result: {130+ command: lane.command,131+ durationMs: Math.round(Duration.toMillis(elapsed)),132+ lane: lane.lane,133+ result: classifyRun(lane.lane, exit),134+ },135+ })136+ );137+138+ return CheckRunner.of({139+ run: (job) =>140+ Effect.scoped(141+ Effect.gen(function* () {142+ if (job.heldBack !== undefined) {143+ return yield* new VerifierBlocked({});144+ }145+146+ const cwd = yield* options.checkout(job.at);147+148+ const home = yield* fs149+ .makeTempDirectoryScoped({ prefix: "check-home-" })150+ .pipe(Effect.mapError(() => new VerifierBlocked({})));151+152+ const [elapsed, ran] = yield* Effect.timed(153+ Effect.forEach(job.lanes, (lane) => runLane(cwd, home, lane))154+ );155+156+ return {157+ durationMs: Math.round(Duration.toMillis(elapsed)),158+ evidence: ran.flatMap(({ exit, result }) =>159+ result.result === "passed"160+ ? []161+ : [evidenceFrom(result.lane, exit)]162+ ),163+ heldBack: [],164+ lanes: ran.map(({ result }) => result),165+ };166+ })167+ ),168+ });169+ })170+ ),171+};added:packages/checks/src/check-runner/memory.ts+90 added
1+/**2+ * `CheckRunner` from a script, for tests: each `(tree or commit, lane)` gets3+ * its scripted results in order, and the last one again once they run out.4+ * A pair with no script is `VerifierBlocked`, as a Checker that cannot run is.5+ */6+import type { LaneResult } from "@repo/protocol/domain/answer";7+import type { LaneName } from "@repo/protocol/ids";8+import { VerifierBlocked } from "@repo/protocol/refusal";9+import { Array, Effect, Layer, Option, Ref } from "effect";10+11+import { CheckRunner, shaOf } from "../check-runner.ts";12+import type { CheckAt, LaneEvidence } from "../check-runner.ts";13+14+/** Where a lane's script lives in the map: `<tree or commit sha>:<lane>`. */15+export const scriptKey = (at: CheckAt, lane: LaneName) =>16+ `${shaOf(at)}:${lane}`;17+18+/**19+ * A scripted lane has no output to read, so a scripted failure counts as one20+ * assertion failing the same way every time: two of them on main are red21+ * first. Any other result that is not a pass leaves no signature.22+ */23+const evidenceOf = ({ lane, result }: LaneResult): LaneEvidence =>24+ result === "failed"25+ ? { lane, signature: `${lane}: scripted failure` }26+ : { lane };27+28+export const CheckRunnerMemory = {29+ layer: (30+ script: ReadonlyMap<string, readonly LaneResult[]>31+ ): Layer.Layer<CheckRunner> =>32+ Layer.effect(33+ CheckRunner,34+ Effect.gen(function* () {35+ // How many results each key has served.36+ const served = yield* Ref.make<ReadonlyMap<string, number>>(new Map());37+38+ const next = (39+ key: string,40+ results: Array.NonEmptyReadonlyArray<LaneResult>41+ ) =>42+ Ref.modify(served, (counts) => {43+ const count = counts.get(key) ?? 0;44+45+ return [46+ results[Math.min(count, results.length - 1)] ?? results[0],47+ new Map(counts).set(key, count + 1),48+ ] as const;49+ });50+51+ return CheckRunner.of({52+ run: (job) =>53+ Effect.gen(function* () {54+ // Every lane has a script, or none of them advances.55+ const scripted = yield* Effect.forEach(job.lanes, ({ lane }) => {56+ const key = scriptKey(job.at, lane);57+58+ return Option.match(59+ Option.filter(60+ Option.fromNullishOr(script.get(key)),61+ Array.isReadonlyArrayNonEmpty62+ ),63+ {64+ onNone: () => Effect.fail(new VerifierBlocked({})),65+ onSome: (results) => Effect.succeed({ key, results }),66+ }67+ );68+ });69+70+ const lanes = yield* Effect.forEach(71+ scripted,72+ ({ key, results }) => next(key, results)73+ );74+75+ return {76+ durationMs: lanes.reduce(77+ (total, { durationMs }) => total + durationMs,78+ 079+ ),80+ evidence: lanes81+ .filter(({ result }) => result !== "passed")82+ .map(evidenceOf),83+ heldBack: [],84+ lanes,85+ };86+ }),87+ });88+ })89+ ),90+};added:packages/checks/src/check-runner.ts+129 added
1+/**2+ * The `CheckRunner` port (spec §4.2): the one way the platform and the CLI run3+ * a project's lanes on a tree. `CheckJob` and `CheckRun` are schemas because4+ * they cross the sandbox's entrypoint in W3, decoded on both sides.5+ * Adapters: `/memory` (scripted, for tests) and `/local` (real processes in a6+ * checkout, for the CLI's `check`); the Checker's lives in `apps/platform`.7+ */8+import { HeldBackResult, LaneResult } from "@repo/protocol/domain/answer";9+import { EnvItem } from "@repo/protocol/domain/env";10+import {11+ AreaName,12+ CommitSha,13+ EnvKey,14+ LaneName,15+ ProjectName,16+ RepoName,17+ SuiteRoot,18+ TreeSha,19+} from "@repo/protocol/ids";20+import type { VerifierBlocked } from "@repo/protocol/refusal";21+import { Context, Option, Schema } from "effect";22+import type { Effect } from "effect";23+24+import { diagnose, Diagnosis } from "./classify.ts";25+import type { RunExit } from "./classify.ts";26+27+/**28+ * What a job runs on: an exact tree (an answer merged onto main) or a29+ * commit (main itself, when an ask opens).30+ */31+export const CheckAt = Schema.TaggedUnion({32+ Commit: { commit: CommitSha },33+ Tree: { tree: TreeSha },34+});35+36+export type CheckAt = typeof CheckAt.Type;37+38+/** The object id a job runs on, whichever kind it is. */39+export const shaOf = (at: CheckAt): string =>40+ CheckAt.match(at, {41+ Commit: ({ commit }): string => commit,42+ Tree: ({ tree }): string => tree,43+ });44+45+/** One lane to run: its name, the project's command for it, and its time limit. */46+export const CheckLane = Schema.Struct({47+ command: Schema.NonEmptyString,48+ lane: LaneName,49+ timeoutMs: Schema.optionalKey(50+ Schema.Int.pipe(Schema.check(Schema.isGreaterThan(0)))51+ ),52+});53+54+export type CheckLane = typeof CheckLane.Type;55+56+/** A request to run lanes on one tree of one project's repo. */57+export const CheckJob = Schema.Struct({58+ at: CheckAt,59+ /** The sealed suite, from the layer's repo at its pinned commit (W6). */60+ heldBack: Schema.optionalKey(61+ Schema.Struct({62+ areas: Schema.Array(AreaName),63+ at: CommitSha,64+ layerRepo: RepoName,65+ suite: SuiteRoot,66+ })67+ ),68+ lanes: Schema.Array(CheckLane),69+ /** Env items whose values the run sees only as placeholders. */70+ placeholders: Schema.Array(EnvKey),71+ project: ProjectName,72+ /** Env items whose outbound hosts go through the platform's gateway. */73+ proxies: Schema.Array(EnvItem),74+ repo: RepoName,75+});76+77+export type CheckJob = typeof CheckJob.Type;78+79+/**80+ * What a lane that did not pass leaves for comparing runs without logs: its81+ * failure signature when it failed on assertions, and `no assertion` when it82+ * found no tests at all.83+ */84+export const LaneEvidence = Schema.Struct({85+ lane: LaneName,86+ signature: Schema.optionalKey(Schema.NonEmptyString),87+ weakness: Schema.optionalKey(Schema.Literal("no assertion")),88+});89+90+export type LaneEvidence = typeof LaneEvidence.Type;91+92+/** A lane's evidence, read from its exit where the run happened. */93+export const evidenceFrom = (lane: LaneName, exit: RunExit): LaneEvidence =>94+ Diagnosis.$match(diagnose(exit), {95+ Blocked: () => ({ lane }),96+ Failed: ({ signature }) =>97+ Option.match(signature, {98+ onNone: () => ({ lane }),99+ onSome: (text) => ({ lane, signature: text }),100+ }),101+ LoadError: () => ({ lane }),102+ NoTests: () => ({ lane, weakness: "no assertion" as const }),103+ Passed: () => ({ lane }),104+ });105+106+/**107+ * One job's result: each lane, the held-back areas' bits, the whole run's108+ * time, and the evidence of every lane that did not pass. Logs never travel109+ * here; a lane's `logRef` names where the platform keeps its log.110+ */111+export const CheckRun = Schema.Struct({112+ durationMs: Schema.Int,113+ evidence: Schema.Array(LaneEvidence),114+ heldBack: Schema.Array(HeldBackResult),115+ lanes: Schema.Array(LaneResult),116+});117+118+export type CheckRun = typeof CheckRun.Type;119+120+/**121+ * Runs a job's lanes. `VerifierBlocked` means the run could not happen at all122+ * (no checkout, no script for it): the gate's trouble, never the answer's.123+ */124+export class CheckRunner extends Context.Service<125+ CheckRunner,126+ {127+ readonly run: (job: CheckJob) => Effect.Effect<CheckRun, VerifierBlocked>;128+ }129+>()("checks/CheckRunner") {}added:packages/checks/src/classify.ts+269 added
1+/**2+ * Red for the right reason (CAA D): what one run of a lane says happened.3+ * A failure by an assertion is told apart from a run that never got that4+ * far (a load or compile error, or no tests at all), from the runner's JSON5+ * report where there is one and from its output otherwise.6+ */7+import type { LaneOutcome } from "@repo/protocol/domain/answer";8+import type { LaneName } from "@repo/protocol/ids";9+import { Array, Data, Option, Order, pipe, Schema, String } from "effect";10+11+/** How one lane's command ended, as the runner saw it. */12+export interface RunExit {13+ /** The exit code; negative when the process had none (a signal ended it). */14+ readonly code: number;15+ readonly stdout: string;16+ readonly stderr: string;17+ /** The runner's JSON report, when it wrote one (vitest's `--reporter=json`). */18+ readonly report?: unknown;19+ /** The runner was stopped at the lane's time limit. */20+ readonly timedOut?: boolean;21+}22+23+/**24+ * What one run says happened. `Failed` carries the failing tests' signature25+ * when every failure was an assertion's; a test that threw anything else26+ * (`TypeError: parseWeek is not a function`) failed with none.27+ */28+export type Diagnosis =29+ | { readonly _tag: "Blocked" }30+ | { readonly _tag: "Failed"; readonly signature: Option.Option<string> }31+ | { readonly _tag: "LoadError" }32+ | { readonly _tag: "NoTests" }33+ | { readonly _tag: "Passed" };34+35+export const Diagnosis = Data.taggedEnum<Diagnosis>();36+37+// The fields of vitest's JSON report (jest's shape) that tell what happened.38+// A file that failed with a message and collected no tests failed to load.39+const VitestReport = Schema.Struct({40+ numTotalTests: Schema.Finite,41+ testResults: Schema.Array(42+ Schema.Struct({43+ assertionResults: Schema.Array(44+ Schema.Struct({45+ failureMessages: Schema.Array(Schema.String),46+ fullName: Schema.String,47+ status: Schema.String,48+ })49+ ),50+ message: Schema.String,51+ status: Schema.String,52+ })53+ ),54+});55+56+type VitestReport = typeof VitestReport.Type;57+58+const decodeReport = Schema.decodeUnknownOption(VitestReport);59+60+/** A line that reports a failed assertion: chai's, node's, jest's and bun's `expect`, pytest's `assert`. */61+const ASSERTION =62+ /AssertionError|^E\s+assert\b|^(?:error: |Error: )?expect\(|^Snapshot .+ mismatched/u;63+64+/** The details jest and bun print under an `expect(received)` line. */65+const EXPECTATION_DETAIL = /^(?:Expected|Received)\b/u;66+67+/** The output of a run that never reached its tests. */68+const LOAD_ERROR = [69+ /Cannot find (?:module|package)/u,70+ /ERR_MODULE_NOT_FOUND/u,71+ /Failed to load url/u,72+ /\bSyntaxError\b/u,73+ /\b(?:ModuleNotFound|Import)Error\b/u,74+ /Transform failed/u,75+];76+77+/** The output of a run that found no tests: vitest's, bun's or jest's, pytest's, node's. */78+const NO_TESTS = [79+ /No test files found/u,80+ /did not match any test files|No tests found/u,81+ /\bno tests ran\b/u,82+ /^ℹ tests 0$/mu,83+];84+85+/** A line naming a failed test: bun's `(fail)`, pytest's `FAILED`, vitest's `FAIL`. */86+const FAILED_TEST = [87+ /^\(fail\) (?<name>.+)$/u,88+ /^FAILED (?<name>\S+)/u,89+ /^FAIL\s+(?<name>.+)$/u,90+];91+92+const ANSI = new RegExp(93+ `${globalThis.String.fromCharCode(27)}\\[[0-9;]*m`,94+ "gu"95+);96+97+const ADDRESS = /\b0x[0-9a-fA-F]+\b/gu;98+99+// An absolute path of two or more segments, with any `:line:col`, not the100+// tail of a relative one (`test/week.test.ts` stays).101+const ABSOLUTE_PATH = /(?<![\w.])(?:file:\/\/)?(?:\/[\w.@+-]+){2,}(?::\d+)*/gu;102+103+const BRACKETED_DURATION = /\s*[[(]\d+(?:\.\d+)?\s?m?s[\])]/gu;104+105+const DURATION = /\b\d+(?:\.\d+)?\s?m?s\b/gu;106+107+/** Without the parts that change between two runs of the same failure. */108+const normalise = (text: string) =>109+ text110+ .replaceAll(ANSI, "")111+ .replaceAll(ADDRESS, "<address>")112+ .replaceAll(ABSOLUTE_PATH, "<path>")113+ .replaceAll(BRACKETED_DURATION, "")114+ .replaceAll(DURATION, "<duration>")115+ .replaceAll(/\s+/gu, " ")116+ .trim();117+118+const firstLine = (text: string) => text.split("\n", 1)[0] ?? "";119+120+const signatureOf = (entries: readonly string[]) =>121+ Array.dedupe(entries).toSorted(Order.String).join("\n");122+123+/** The first assertion line, with jest's and bun's `Expected:`/`Received:` lines under it. */124+const assertionOf = (lines: readonly string[]) =>125+ Option.map(126+ Array.findFirstIndex(lines, (line) => ASSERTION.test(line)),127+ (at) => {128+ const detail = pipe(129+ lines.slice(at + 1),130+ Array.filter(String.isNonEmpty),131+ Array.takeWhile((line) => EXPECTATION_DETAIL.test(line))132+ );133+134+ return normalise([lines[at] ?? "", ...detail].join(" "));135+ }136+ );137+138+const failedTestsOf = (lines: readonly string[]) =>139+ pipe(140+ lines,141+ Array.flatMap((line) =>142+ Array.getSomes(143+ FAILED_TEST.map((pattern) =>144+ Option.fromNullishOr(pattern.exec(line)?.groups?.name)145+ )146+ )147+ ),148+ Array.map(normalise)149+ );150+151+const fromOutput = (exit: RunExit): Diagnosis => {152+ const output = `${exit.stdout}\n${exit.stderr}`.replaceAll(ANSI, "");153+ const lines = output.split("\n").map(String.trim);154+ const assertion = assertionOf(lines);155+156+ if (Option.isSome(assertion)) {157+ const names = signatureOf(failedTestsOf(lines)).replaceAll("\n", " | ");158+159+ return Diagnosis.Failed({160+ signature: Option.some(161+ names === "" ? assertion.value : `${names}: ${assertion.value}`162+ ),163+ });164+ }165+166+ if (NO_TESTS.some((pattern) => pattern.test(output))) {167+ return Diagnosis.NoTests();168+ }169+170+ if (LOAD_ERROR.some((pattern) => pattern.test(output))) {171+ return Diagnosis.LoadError();172+ }173+174+ return Diagnosis.Failed({ signature: Option.none() });175+};176+177+const fromReport = (report: VitestReport, exit: RunExit): Diagnosis => {178+ const collectFailed = report.testResults.some(179+ (file) =>180+ file.status === "failed" &&181+ file.message !== "" &&182+ file.assertionResults.length === 0183+ );184+185+ if (collectFailed) {186+ return Diagnosis.LoadError();187+ }188+189+ const failures = report.testResults190+ .flatMap((file) => file.assertionResults)191+ .filter((test) => test.status === "failed")192+ .map((test) => ({193+ first: normalise(firstLine(test.failureMessages[0] ?? "")),194+ name: normalise(test.fullName),195+ }));196+197+ if (Array.isReadonlyArrayNonEmpty(failures)) {198+ const byAssertion = failures.every(({ first }) => ASSERTION.test(first));199+200+ return Diagnosis.Failed({201+ signature: byAssertion202+ ? Option.some(203+ signatureOf(failures.map(({ first, name }) => `${name}: ${first}`))204+ )205+ : Option.none(),206+ });207+ }208+209+ if (report.numTotalTests === 0) {210+ return Diagnosis.NoTests();211+ }212+213+ return fromOutput(exit);214+};215+216+// No exit code (a signal), "not executable" (126), "not found" (127), or217+// the shell's 128+n for a process a signal killed.218+const neverRan = (code: number) =>219+ code < 0 || code === 126 || code === 127 || (code > 128 && code < 160);220+221+/**222+ * What one run says happened. A run stopped at its time limit, or one whose223+ * command never ran, is `Blocked`: the verifier's trouble, not the answer's.224+ * Otherwise exit 0 is `Passed` whatever the report says (a run with225+ * `--passWithNoTests` found none and passed), and a failure is read from the226+ * report, or from the output when there is none.227+ */228+export const diagnose = (exit: RunExit): Diagnosis => {229+ if (exit.timedOut === true || neverRan(exit.code)) {230+ return Diagnosis.Blocked();231+ }232+233+ if (exit.code === 0) {234+ return Diagnosis.Passed();235+ }236+237+ return Option.match(decodeReport(exit.report), {238+ onNone: () => fromOutput(exit),239+ onSome: (report) => fromReport(report, exit),240+ });241+};242+243+/**244+ * How one lane's run ended. `failed` is any failure once the tests ran;245+ * `loadError` is a run that never reached them (a load or compile error, or246+ * no tests found). A single run is never `flaked`: that takes a second run.247+ */248+export const classifyRun = (lane: LaneName, exit: RunExit): LaneOutcome =>249+ Diagnosis.$match(diagnose(exit), {250+ Blocked: () => "blocked" as const,251+ Failed: () => "failed" as const,252+ LoadError: () => "loadError" as const,253+ NoTests: () => "loadError" as const,254+ Passed: () => "passed" as const,255+ });256+257+/**258+ * The failing tests' names and the first line of each one's assertion,259+ * normalised (absolute paths, durations and addresses stripped), so two runs260+ * that failed the same way have the same signature. None unless the run261+ * failed on assertions.262+ */263+export const failureSignature = (exit: RunExit): Option.Option<string> => {264+ const diagnosis = diagnose(exit);265+266+ return Diagnosis.$is("Failed")(diagnosis)267+ ? diagnosis.signature268+ : Option.none();269+};added:packages/checks/src/phases.ts+117 added
1+/**2+ * The Checker's phases as data (OSR §5.3). `apps/sandbox` runs the plan; this3+ * module only decides it, so its order can be proved over every input:4+ *5+ * 1. `Setup` installs what the checks need, with egress to the registries and6+ * the run block's `setupEgress` only;7+ * 2. `Snapshot` saves that install, keyed by what it came from. It is the only8+ * snapshot, and it comes before held-back files exist: a snapshot taken9+ * after them would carry them into the next Sandbox;10+ * 3. `EgressOff` cuts the network, leaving only the platform's handlers;11+ * 4. `WriteHeldBack` writes the sealed suite, only when there is one;12+ * 5. `Run` runs the lanes, seeing placeholders, never values;13+ * 6. `Report` sends back lanes and one bit per area, never logs.14+ *15+ * With no setup command there is nothing to install or snapshot, so the plan16+ * starts at `EgressOff`. The checkout itself comes before the plan.17+ */18+import type { RunBlock } from "@repo/protocol/domain/run";19+import type { AreaName, EnvKey, LaneName } from "@repo/protocol/ids";20+import { Data, Hash, Option } from "effect";21+22+/** A lane as the `Run` phase runs it. */23+export interface PlannedLane {24+ readonly lane: LaneName;25+ readonly command: string;26+}27+28+/**29+ * One phase. This is the union `Data.TaggedEnum` would build; it is written30+ * out because the lint refuses the `{}` members `EgressOff` and `Report`31+ * would need there.32+ */33+export type Phase =34+ | {35+ readonly _tag: "Setup";36+ readonly command: string;37+ readonly egress: readonly string[];38+ }39+ | { readonly _tag: "Snapshot"; readonly key: string }40+ | { readonly _tag: "EgressOff" }41+ | { readonly _tag: "WriteHeldBack"; readonly areas: readonly AreaName[] }42+ | {43+ readonly _tag: "Run";44+ readonly lanes: readonly PlannedLane[];45+ readonly placeholders: readonly EnvKey[];46+ }47+ | { readonly _tag: "Report" };48+49+export const Phase = Data.taggedEnum<Phase>();50+51+export interface PlanInput {52+ readonly run: RunBlock;53+ readonly lanes: readonly PlannedLane[];54+ readonly heldBack: Option.Option<{ readonly areas: readonly AreaName[] }>;55+ readonly placeholders: readonly EnvKey[];56+ /** The hash of the project's lockfile at the tree being checked. */57+ readonly lockfileHash: string;58+}59+60+const DEFAULT_IMAGE = "checker:default";61+62+/**63+ * A snapshot holds what setup installed, so it is reused only for the same64+ * image, setup command, setup hosts and lockfile.65+ */66+const snapshotKey = (67+ run: RunBlock,68+ command: string,69+ egress: readonly string[],70+ lockfileHash: string71+) => {72+ const image = run.image ?? DEFAULT_IMAGE;73+74+ // Hash.string is a fixed function of its input (djb2), so the key is too.75+ const setupHash = Math.abs(76+ Hash.string(JSON.stringify([image, command, egress]))77+ ).toString(16);78+79+ return `setup:${lockfileHash}:${setupHash}`;80+};81+82+/** The phases the Checker runs for one job, in order. */83+export const phasePlan = ({84+ heldBack,85+ lanes,86+ lockfileHash,87+ placeholders,88+ run,89+}: PlanInput): readonly Phase[] => {90+ const install: readonly Phase[] =91+ run.setup === undefined92+ ? []93+ : [94+ Phase.Setup({ command: run.setup, egress: run.setupEgress ?? [] }),95+ Phase.Snapshot({96+ key: snapshotKey(97+ run,98+ run.setup,99+ run.setupEgress ?? [],100+ lockfileHash101+ ),102+ }),103+ ];104+105+ const sealed: readonly Phase[] = Option.match(heldBack, {106+ onNone: () => [],107+ onSome: ({ areas }) => [Phase.WriteHeldBack({ areas })],108+ });109+110+ return [111+ ...install,112+ Phase.EgressOff(),113+ ...sealed,114+ Phase.Run({ lanes, placeholders }),115+ Phase.Report(),116+ ];117+};added:packages/checks/src/red-first.ts+99 added
1+/**2+ * Red first, for the right reason (CAA D): an ask opens only when its check3+ * fails on main twice in the same way, by an assertion. A check that fails to4+ * load fails because its subject is missing, and any answer that exports the5+ * subject could pass it; a check that fails two different ways is flaky.6+ */7+import type { LaneName } from "@repo/protocol/ids";8+import { NotRedFirst, WeakCheck } from "@repo/protocol/refusal";9+import { Data, Option, Result } from "effect";10+11+import type { CheckRun } from "./check-runner.ts";12+import { diagnose, Diagnosis } from "./classify.ts";13+import type { RunExit } from "./classify.ts";14+15+/** One run of an ask's check on main. */16+export interface RunEvidence {17+ readonly lane: LaneName;18+ readonly exit: RunExit;19+}20+21+/** How the check fails on main, the same both times. */22+export interface RedSignature {23+ readonly signature: string;24+ readonly lane: LaneName;25+}26+27+/** What one run says about the check, for comparing it with the other. */28+type Reading =29+ | { readonly _tag: "Red"; readonly signature: string }30+ | { readonly _tag: "NoTests" }31+ | { readonly _tag: "NotRed" };32+33+const Reading = Data.taggedEnum<Reading>();34+35+const readExit = (exit: RunExit): Reading =>36+ Diagnosis.$match(diagnose(exit), {37+ Blocked: () => Reading.NotRed(),38+ Failed: ({ signature }) =>39+ Option.match(signature, {40+ onNone: () => Reading.NotRed(),41+ onSome: (text) => Reading.Red({ signature: text }),42+ }),43+ LoadError: () => Reading.NotRed(),44+ NoTests: () => Reading.NoTests(),45+ Passed: () => Reading.NotRed(),46+ });47+48+const readRun = (run: CheckRun, lane: LaneName): Reading => {49+ const result = run.lanes.find((each) => each.lane === lane)?.result;50+ const evidence = run.evidence.find((each) => each.lane === lane);51+52+ if (evidence?.weakness === "no assertion") {53+ return Reading.NoTests();54+ }55+56+ return result === "failed" && evidence?.signature !== undefined57+ ? Reading.Red({ signature: evidence.signature })58+ : Reading.NotRed();59+};60+61+const judge = (62+ lane: LaneName,63+ [first, second]: readonly [Reading, Reading]64+): Result.Result<RedSignature, NotRedFirst | WeakCheck> => {65+ if (Reading.$is("NoTests")(first) || Reading.$is("NoTests")(second)) {66+ return Result.fail(new WeakCheck({ weakness: "no assertion" }));67+ }68+69+ return Reading.$is("Red")(first) &&70+ Reading.$is("Red")(second) &&71+ first.signature === second.signature72+ ? Result.succeed({ lane, signature: first.signature })73+ : Result.fail(new NotRedFirst({}));74+};75+76+/**77+ * Whether two runs of one check, from their exits, failed the same way by an78+ * assertion. A run that found no tests is `WeakCheck{no assertion}`; a pass,79+ * a load error, a time-out, a throw that is not an assertion, two different80+ * failures or two different lanes are `NotRedFirst`.81+ */82+export const redFirst = ([first, second]: readonly [83+ RunEvidence,84+ RunEvidence,85+]): Result.Result<RedSignature, NotRedFirst | WeakCheck> =>86+ first.lane === second.lane87+ ? judge(first.lane, [readExit(first.exit), readExit(second.exit)])88+ : Result.fail(new NotRedFirst({}));89+90+/**91+ * `redFirst` for the platform, which sees two `CheckRun`s and never their92+ * output: the lane must have failed both times with the same evidence93+ * signature.94+ */95+export const redFirstOfRuns = (96+ [first, second]: readonly [CheckRun, CheckRun],97+ lane: LaneName98+): Result.Result<RedSignature, NotRedFirst | WeakCheck> =>99+ judge(lane, [readRun(first, lane), readRun(second, lane)]);added:packages/checks/src/weak-shapes.ts+361 added
1+/**2+ * The static half of "red for the right reason" (CAA D): five shapes of check3+ * that pass whatever the answer does, read from the check file's source4+ * before it ever runs. It reads expect-style checks (vitest, jest, bun); a5+ * file with no `expect(` call (pytest, go test) is outside it and flags6+ * nothing, and the twice-red run still guards it.7+ */8+import { Array, Option, pipe } from "effect";9+10+/**11+ * A shape of check that passes whatever the answer does, as `WeakCheck`'s12+ * `weakness` names it.13+ */14+export type Weakness =15+ | "self-referential"16+ | "constant pin"17+ | "absence-only"18+ | "mock-only"19+ | "fixture-asserts-fixture";20+21+/**22+ * The check file as an ask carries it: its repo path, which places its23+ * relative imports, and its source.24+ */25+export interface CheckFile {26+ readonly path: string;27+ readonly content: string;28+}29+30+/** One `expect(subject).matcher(expected)` in the check, as source text. */31+interface Expectation {32+ readonly subject: string;33+ readonly negated: boolean;34+ readonly matcher: string;35+ readonly expected: string;36+}37+38+/** The check's source twice: without comments, and with string contents blanked too. */39+interface Source {40+ readonly text: string;41+ readonly masked: string;42+}43+44+const QUOTES = new Set(['"', "'", "`"]);45+46+/** The index just past the string literal that opens at `start`. */47+const stringEnd = (source: string, start: number) => {48+ const quote = source[start];49+ let at = start + 1;50+51+ while (at < source.length && source[at] !== quote) {52+ at += source[at] === "\\" ? 2 : 1;53+ }54+55+ return Math.min(at + 1, source.length);56+};57+58+const blank = (text: string) => text.replaceAll(/[^\n]/gu, " ");59+60+/**61+ * Comments become spaces in both copies; a string stays in `text` and keeps62+ * only its quotes in `masked`. Both keep every index, so a position found in63+ * `masked` reads the same span of `text`.64+ */65+const read = (source: string): Source => {66+ const text: string[] = [];67+ const masked: string[] = [];68+ let at = 0;69+70+ while (at < source.length) {71+ const pair = source.slice(at, at + 2);72+ const char = source[at] ?? "";73+74+ if (pair === "//" || pair === "/*") {75+ // A line comment ends before its newline, a block comment after `*/`.76+ const close = pair === "//" ? "\n" : "*/";77+ const found = source.indexOf(close, at + 2);78+ const end = found === -1 ? source.length : found + close.length;79+ const span = blank(source.slice(at, end));80+81+ text.push(span);82+ masked.push(span);83+ at = end;84+ } else if (QUOTES.has(char)) {85+ const end = stringEnd(source, at);86+ const literal = source.slice(at, end);87+88+ text.push(literal);89+ masked.push(`${char}${blank(literal.slice(1, -1))}${literal.slice(-1)}`);90+ at = end;91+ } else {92+ text.push(char);93+ masked.push(char);94+ at += 1;95+ }96+ }97+98+ return { masked: masked.join(""), text: text.join("") };99+};100+101+/** The index of the `)` that closes the `(` at `open`, in masked source. */102+const closing = (masked: string, open: number) => {103+ let depth = 0;104+105+ for (let at = open; at < masked.length; at += 1) {106+ if (masked[at] === "(") {107+ depth += 1;108+ } else if (masked[at] === ")") {109+ depth -= 1;110+111+ if (depth === 0) {112+ return Option.some(at);113+ }114+ }115+ }116+117+ return Option.none();118+};119+120+const expectationAt = (121+ { masked, text }: Source,122+ start: number123+): Option.Option<Expectation> =>124+ Option.gen(function* () {125+ const open = masked.indexOf("(", start);126+ const close = yield* closing(masked, open);127+128+ // `.not`, `.resolves` and `.rejects`, then the matcher's call.129+ const chain =130+ /\s*(?<modifiers>(?:\.\s*(?:not|resolves|rejects)\s*)*)\.\s*(?<matcher>[A-Za-z_$][\w$]*)\s*\(/uy;131+132+ chain.lastIndex = close + 1;133+ const found = yield* Option.fromNullishOr(chain.exec(masked));134+ const matcherOpen = found.index + found[0].length - 1;135+ const matcherClose = yield* closing(masked, matcherOpen);136+137+ return {138+ expected: text.slice(matcherOpen + 1, matcherClose).trim(),139+ matcher: found.groups?.matcher ?? "",140+ negated: /\bnot\b/u.test(found.groups?.modifiers ?? ""),141+ subject: text.slice(open + 1, close).trim(),142+ };143+ });144+145+const expectationsOf = (source: Source) =>146+ Array.getSomes(147+ Array.map(148+ [...source.masked.matchAll(/(?<![\w$.])expect\s*\(/gu)],149+ (match) => expectationAt(source, match.index)150+ )151+ );152+153+const importsOf = ({ masked, text }: Source) =>154+ pipe(155+ [156+ ...text.matchAll(157+ /(?<keyword>\bfrom|\bimport\s*\(?|\brequire\s*\()\s*["'](?<specifier>[^"'\n]+)["']/gu158+ ),159+ ],160+ // A keyword inside a string is blanked in `masked`.161+ Array.filter((match) => masked[match.index] !== " "),162+ Array.map((match) => match.groups?.specifier ?? "")163+ );164+165+const EXTENSION = /\.(?:[cm]?[jt]sx?|json)$/u;166+167+const GLOB = /[*?[{]/u;168+169+const segmentsOf = (path: string) =>170+ path.split("/").filter((segment) => segment !== "" && segment !== ".");171+172+/**173+ * The folder a territory glob covers: its fixed head (`packages/week/**` →174+ * `packages/week`), or, for a glob naming one file, that file's folder, since175+ * a check reaches a file through its folder's index too.176+ */177+const baseOf = (glob: string) => {178+ const segments = segmentsOf(glob);179+ const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));180+181+ const isFile =182+ fixed.length === segments.length && EXTENSION.test(fixed.at(-1) ?? "");183+184+ return isFile ? fixed.slice(0, -1) : fixed;185+};186+187+/** A relative import's repo path, resolved from the check file's folder. */188+const resolve = (checkPath: string, specifier: string) => {189+ const resolved = segmentsOf(checkPath).slice(0, -1);190+191+ for (const segment of segmentsOf(specifier)) {192+ if (segment === "..") {193+ resolved.pop();194+ } else {195+ resolved.push(segment);196+ }197+ }198+199+ return resolved;200+};201+202+const startsWith = (path: readonly string[], head: readonly string[]) =>203+ head.every((segment, index) => path[index] === segment);204+205+/**206+ * Whether an import reaches into a territory's folder: a relative import207+ * that resolves inside it, or to a folder above it (`../src` reaching208+ * `src/week.ts` through `src/index.ts`), or a package import whose unscoped209+ * name is one of its folders (`@datekit/week` for `packages/week/**`).210+ */211+const reaches =212+ (checkPath: string) => (specifier: string, base: readonly string[]) => {213+ if (!specifier.startsWith(".")) {214+ const parts = specifier.split("/");215+ const name = specifier.startsWith("@") ? parts[1] : parts[0];216+217+ return name !== undefined && base.includes(name);218+ }219+220+ const path = resolve(checkPath, specifier);221+222+ return startsWith(path, base) || startsWith(base, path);223+ };224+225+// After strings, numbers and the literal keywords go, a literal has no226+// identifier left but its object keys, and no call or arrow.227+const isLiteral = (text: string) =>228+ text !== "" &&229+ !/[(=]/u.test(text) &&230+ !/[A-Za-z_$]/u.test(231+ text232+ .replaceAll(233+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\$]|\\.)*`/gu,234+ "0"235+ )236+ .replaceAll(237+ /\b(?:0[box][\da-f_]+|\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?n?)\b/giu,238+ "0"239+ )240+ .replaceAll(/\b(?:true|false|null|undefined|NaN|Infinity)\b/gu, "0")241+ .replaceAll(/[A-Za-z_$][\w$]*\s*:/gu, "")242+ );243+244+/** `not.toThrow()`, `toBeUndefined()`, `toBeFalsy()` and their mirrors. */245+const isAbsence = ({ matcher, negated }: Expectation) =>246+ negated247+ ? ["toThrow", "toThrowError", "toBeDefined", "toBeTruthy"].includes(matcher)248+ : ["toBeUndefined", "toBeFalsy"].includes(matcher);249+250+const MOCK_MATCHER =251+ /^to(?:HaveBeen(?:Last|Nth)?Called|BeCalled|Have(?:Last|Nth)?Returned)/u;252+253+const rootOf = (text: string) =>254+ /^(?:await\s+)?(?<root>[A-Za-z_$][\w$]*)/u.exec(text)?.groups?.root;255+256+const mocksOf = ({ text }: Source) =>257+ new Set(258+ Array.map(259+ [260+ ...text.matchAll(261+ /\b(?:const|let|var)\s+(?<name>[A-Za-z_$][\w$]*)\s*=\s*(?:(?:vi|jest)\.(?:fn|spyOn)|mock)\s*\(/gu262+ ),263+ ],264+ (match) => match.groups?.name ?? ""265+ )266+ );267+268+const isOnMock = (mocks: ReadonlySet<string>) => (each: Expectation) =>269+ MOCK_MATCHER.test(each.matcher) ||270+ each.subject.includes(".mock.") ||271+ /\b(?:vi|jest)\.fn\s*\(/u.test(each.subject) ||272+ mocks.has(rootOf(each.subject) ?? "");273+274+/** The names the check binds to a call's result (`const range = weekRange(…)`). */275+const resultsOf = ({ text }: Source) =>276+ new Set(277+ Array.map(278+ [279+ ...text.matchAll(280+ /\b(?:const|let|var)\s+(?<name>[A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[A-Za-z_$][\w$.]*\s*\(/gu281+ ),282+ ],283+ (match) => match.groups?.name ?? ""284+ )285+ );286+287+const squash = (text: string) => text.replaceAll(/\s+/gu, "");288+289+/**290+ * Expected and actual from one source: the same expression twice, or the291+ * subject read straight off the fixture the expected one comes from. A value292+ * the check computed is not a fixture: two of its fields may be compared293+ * (`expect(range.start).toBeLessThan(range.end)`).294+ */295+const isFromOneFixture =296+ (results: ReadonlySet<string>) =>297+ ({ expected, subject }: Expectation) => {298+ const root = rootOf(subject);299+300+ return (301+ !isLiteral(subject) &&302+ (squash(subject) === squash(expected) ||303+ (!subject.includes("(") &&304+ root !== undefined &&305+ !results.has(root) &&306+ root === rootOf(expected)))307+ );308+ };309+310+/** `expect(1).toBe(1)`: a literal held against a literal, or against nothing. */311+const isConstantPin = ({ expected, subject }: Expectation) =>312+ isLiteral(subject) && (expected === "" || isLiteral(expected));313+314+/**315+ * The weak shapes a check file is in, given the territory's paths (globs).316+ * A shape over expectations holds only when every expectation in the file317+ * has it, so one real assertion among weak ones keeps the check:318+ *319+ * - `self-referential`: the check imports nothing from the territory's320+ * folders (its relative imports resolved from its own path);321+ * - `constant pin`: every expectation holds a literal against a literal322+ * (`expect(1).toBe(1)`);323+ * - `absence-only`: every expectation is `not.toThrow`, `toBeUndefined` or324+ * `toBeFalsy` (or a mirror);325+ * - `mock-only`: every expectation is on a `vi.fn()` or a spy;326+ * - `fixture-asserts-fixture`: every expectation takes expected and actual327+ * from the same fixture, or computes both the same way.328+ */329+export const weaknessesOf = (330+ checkFile: CheckFile,331+ territoryPaths: readonly string[]332+): readonly Weakness[] => {333+ const source = read(checkFile.content);334+ const expectations = expectationsOf(source);335+336+ if (!Array.isReadonlyArrayNonEmpty(expectations)) {337+ return [];338+ }339+340+ const bases = territoryPaths.map(baseOf);341+ const intoTerritory = reaches(checkFile.path);342+ const mocks = mocksOf(source);343+344+ const every = (holds: (each: Expectation) => boolean) =>345+ expectations.every(holds);346+347+ const found: readonly [Weakness, boolean][] = [348+ [349+ "self-referential",350+ !importsOf(source).some((specifier) =>351+ bases.some((base) => intoTerritory(specifier, base))352+ ),353+ ],354+ ["constant pin", every(isConstantPin)],355+ ["absence-only", every(isAbsence)],356+ ["mock-only", every(isOnMock(mocks))],357+ ["fixture-asserts-fixture", every(isFromOneFixture(resultsOf(source)))],358+ ];359+360+ return found.flatMap(([weakness, holds]) => (holds ? [weakness] : []));361+};added:packages/checks/test/fixtures/runs/bun-assertion.json+5 added
12345{ "code": 1, "stderr": "\ntest/week.test.ts:\n2 | \n3 | import { weekOf } from \"../src/week.ts\";\n4 | \n5 | describe(\"weekOf\", () => {\n6 | test(\"reads the first week of a year\", () => {\n7 | expect(weekOf(\"2026-W01\")).toBe(1);\n ^\nerror: expect(received).toBe(expected)\n\nExpected: 1\nReceived: 0\n\n at <anonymous> (/work/datekit/test/week.test.ts:7:32)\n(fail) weekOf > reads the first week of a year [2.87ms]\n\n 0 pass\n 1 fail\n 1 expect() calls\nRan 1 test across 1 file. [5.00ms]\n", "stdout": "bun test v1.4.2 (744846f84)\n"}added:packages/checks/test/fixtures/runs/bun-load-error.json+5 added
12345{ "code": 1, "stderr": "\ntest/week.test.ts:\n\n# Unhandled error between tests\n-------------------------------\nerror: Cannot find module '../src/weeks.ts' from '/work/datekit/test/week.test.ts'\n-------------------------------\n\n\n 0 pass\n 1 fail\n 1 error\nRan 1 test across 1 file. [1.00ms]\n", "stdout": "bun test v1.4.2 (744846f84)\n"}added:packages/checks/test/fixtures/runs/bun-no-tests.json+5 added
12345{ "code": 1, "stderr": "The following filters did not match any test files in --cwd=\"/work/datekit\":\n nothing-here\n5 files were searched [1.00ms]\n\nnote: Tests need \".test\", \"_test_\", \".spec\" or \"_spec_\" in the filename (ex: \"MyApp.test.ts\")\n\n", "stdout": "bun test v1.4.2 (744846f84)\n"}added:packages/checks/test/fixtures/runs/node-syntax-error.json+5 added
1+{2+ "code": 1,3+ "stderr": "",4+ "stdout": "file:///work/datekit/test/week.test.mjs:4\n const week = (;\n ^\n\nSyntaxError: Unexpected token ';'\n at compileSourceTextModule (node:internal/modules/esm/utils:355:16)\n at ModuleLoader.moduleStrategy (node:internal/modules/esm/translators:93:18)\n at #translate (node:internal/modules/esm/loader:441:20)\n at afterLoad (node:internal/modules/esm/loader:509:29)\n at ModuleLoader.loadAndTranslate (node:internal/modules/esm/loader:514:12)\n at #getOrCreateModuleJobAfterResolve (node:internal/modules/esm/loader:567:36)\n at afterResolve (node:internal/modules/esm/loader:614:52)\n at ModuleLoader.getOrCreateModuleJob (node:internal/modules/esm/loader:620:12)\n at node:internal/modules/esm/loader:639:32\n at TracingChannel.tracePromise (node:diagnostics_channel:551:22)\n\nNode.js v26.10.0\n✖ test/week.test.mjs (24.399029ms)\nℹ tests 1\nℹ suites 0\nℹ pass 0\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 34.818814\n\n✖ failing tests:\n\ntest at test/week.test.mjs:1:1\n✖ test/week.test.mjs (24.399029ms)\n 'test failed'\n"5+}added:packages/checks/test/fixtures/runs/vitest-assertion-other.json+58 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758{ "code": 1, "report": { "numTotalTestSuites": 2, "numPassedTestSuites": 0, "numFailedTestSuites": 2, "numPendingTestSuites": 0, "numTotalTests": 1, "numPassedTests": 0, "numFailedTests": 1, "numPendingTests": 0, "numTodoTests": 0, "snapshot": { "added": 0, "failure": false, "filesAdded": 0, "filesRemoved": 0, "filesRemovedList": [], "filesUnmatched": 0, "filesUpdated": 0, "matched": 0, "total": 0, "unchecked": 0, "uncheckedKeysByFile": [], "unmatched": 0, "updated": 0, "didUpdate": false }, "startTime": 1791367638442, "success": false, "testResults": [ { "assertionResults": [ { "ancestorTitles": ["parseWeek"], "fullName": "parseWeek reads the first week of a year", "status": "failed", "title": "reads the first week of a year", "duration": 4.0999769999999955, "failureMessages": [ "AssertionError: expected { week: 2, year: 2026 } to strictly equal { week: 1, year: 2026 }\n at /work/datekit/test/week.test.js:5:35\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:1628:35\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:2783:26\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3321:20\n at new Promise (<anonymous>)\n at runWithCancel (file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3316:10)\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3301:20\n at new Promise (<anonymous>)\n at runWithTimeout (file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3259:10)\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3882:64" ], "meta": {}, "tags": [], "benchmarks": [] } ], "startTime": 1791367638532, "endTime": 1791367638536.1, "status": "failed", "message": "", "name": "/work/datekit/test/week.test.js" } ] }, "stderr": "\n⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL test/week.test.js > parseWeek > reads the first week of a year\nAssertionError: expected { week: 2, year: 2026 } to strictly equal { week: 1, year: 2026 }\n\n- Expected\n+ Received\n\n {\n- \"week\": 1,\n+ \"week\": 2,\n \"year\": 2026,\n }\n\n ❯ test/week.test.js:5:35\n 3| describe(\"parseWeek\", () => {\n 4| it(\"reads the first week of a year\", () => {\n 5| expect(parseWeek(\"2026-W01\")).toStrictEqual({ week: 1, year: 2026 …\n | ^\n 6| });\n 7| });\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\n", "stdout": "\n RUN v5.0.3 /work/datekit\n\n ❯ test/week.test.js (1 test | 1 failed) 5ms\n ❯ parseWeek (1)\n × reads the first week of a year 4ms\n\n Test Files 1 failed (1)\n Tests 1 failed (1)\n Start at 03:07:18\n Duration 95ms (transform 45%, import 24%, tests 18%, worker 12%)\n\nJSON report written to /work/datekit/report.json\n"}added:packages/checks/test/fixtures/runs/vitest-assertion.json+58 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758{ "code": 1, "report": { "numTotalTestSuites": 2, "numPassedTestSuites": 0, "numFailedTestSuites": 2, "numPendingTestSuites": 0, "numTotalTests": 1, "numPassedTests": 0, "numFailedTests": 1, "numPendingTests": 0, "numTodoTests": 0, "snapshot": { "added": 0, "failure": false, "filesAdded": 0, "filesRemoved": 0, "filesRemovedList": [], "filesUnmatched": 0, "filesUpdated": 0, "matched": 0, "total": 0, "unchecked": 0, "uncheckedKeysByFile": [], "unmatched": 0, "updated": 0, "didUpdate": false }, "startTime": 1791367629910, "success": false, "testResults": [ { "assertionResults": [ { "ancestorTitles": ["parseWeek"], "fullName": "parseWeek reads the first week of a year", "status": "failed", "title": "reads the first week of a year", "duration": 4.178111000000001, "failureMessages": [ "AssertionError: expected { week: +0, year: 2026 } to strictly equal { week: 1, year: 2026 }\n at /work/datekit/test/week.test.js:5:35\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:1628:35\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:2783:26\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3321:20\n at new Promise (<anonymous>)\n at runWithCancel (file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3316:10)\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3301:20\n at new Promise (<anonymous>)\n at runWithTimeout (file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3259:10)\n at file:///work/datekit/node_modules/vitest/dist/chunks/run.BTlFXlnv.js:3882:64" ], "meta": {}, "tags": [], "benchmarks": [] } ], "startTime": 1791367629997, "endTime": 1791367630001.1782, "status": "failed", "message": "", "name": "/work/datekit/test/week.test.js" } ] }, "stderr": "\n⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL test/week.test.js > parseWeek > reads the first week of a year\nAssertionError: expected { week: +0, year: 2026 } to strictly equal { week: 1, year: 2026 }\n\n- Expected\n+ Received\n\n {\n- \"week\": 1,\n+ \"week\": 0,\n \"year\": 2026,\n }\n\n ❯ test/week.test.js:5:35\n 3| describe(\"parseWeek\", () => {\n 4| it(\"reads the first week of a year\", () => {\n 5| expect(parseWeek(\"2026-W01\")).toStrictEqual({ week: 1, year: 2026 …\n | ^\n 6| });\n 7| });\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\n", "stdout": "\n RUN v5.0.3 /work/datekit\n\n ❯ test/week.test.js (1 test | 1 failed) 5ms\n ❯ parseWeek (1)\n × reads the first week of a year 4ms\n\n Test Files 1 failed (1)\n Tests 1 failed (1)\n Start at 03:07:09\n Duration 92ms (transform 40%, import 25%, tests 20%, worker 14%)\n\nJSON report written to /work/datekit/report.json\n"}added:packages/checks/test/fixtures/runs/vitest-load-error.json+44 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "code": 1, "report": { "numTotalTestSuites": 1, "numPassedTestSuites": 0, "numFailedTestSuites": 1, "numPendingTestSuites": 0, "numTotalTests": 0, "numPassedTests": 0, "numFailedTests": 0, "numPendingTests": 0, "numTodoTests": 0, "snapshot": { "added": 0, "failure": false, "filesAdded": 0, "filesRemoved": 0, "filesRemovedList": [], "filesUnmatched": 0, "filesUpdated": 0, "matched": 0, "total": 0, "unchecked": 0, "uncheckedKeysByFile": [], "unmatched": 0, "updated": 0, "didUpdate": false }, "startTime": 1791367638742, "success": false, "testResults": [ { "assertionResults": [], "startTime": 1791367638742, "endTime": 1791367638742, "status": "failed", "message": "Cannot find module '../src/weeks.js' imported from /work/datekit/test/week.test.js", "name": "/work/datekit/test/week.test.js" } ] }, "stderr": "\n⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL test/week.test.js [ test/week.test.js ]\nError: Cannot find module '../src/weeks.js' imported from /work/datekit/test/week.test.js\n ❯ test/week.test.js:1:1\n 1| import { parseWeek } from \"../src/weeks.js\";\n | ^\n 2|\n 3| describe(\"parseWeek\", () => {\n\n⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯\n\n", "stdout": "\n RUN v5.0.3 /work/datekit\n\n ❯ test/week.test.js (0 test)\n\n Test Files 1 failed (1)\n Tests no tests\n Start at 03:07:18\n Duration 85ms (worker 98%, environment 2%)\n\nJSON report written to /work/datekit/report.json\n"}added:packages/checks/test/fixtures/runs/vitest-no-tests.json+35 added
1234567891011121314151617181920212223242526272829303132333435{ "code": 1, "report": { "numTotalTestSuites": 0, "numPassedTestSuites": 0, "numFailedTestSuites": 0, "numPendingTestSuites": 0, "numTotalTests": 0, "numPassedTests": 0, "numFailedTests": 0, "numPendingTests": 0, "numTodoTests": 0, "snapshot": { "added": 0, "failure": false, "filesAdded": 0, "filesRemoved": 0, "filesRemovedList": [], "filesUnmatched": 0, "filesUpdated": 0, "matched": 0, "total": 0, "unchecked": 0, "uncheckedKeysByFile": [], "unmatched": 0, "updated": 0, "didUpdate": false }, "startTime": 1791367639031, "success": false, "testResults": [] }, "stderr": "No test files found, exiting with code 1\n\nfilter: nothing-matches\ninclude: **/*.{test,spec}.?(c|m)[jt]s?(x)\nexclude: **/node_modules/**, **/.git/**\n\n", "stdout": "\n RUN v5.0.3 /work/datekit\n\nJSON report written to /work/datekit/report.json\n"}added:packages/checks/test/check-runner-local.test.ts+194 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it, vi } from "@effect/vitest";3+import {4+ AreaName,5+ CommitSha,6+ LaneName,7+ ProjectName,8+ RepoName,9+ SuiteRoot,10+} from "@repo/protocol/ids";11+import { VerifierBlocked } from "@repo/protocol/refusal";12+import { gitOk } from "@repo/testkit/git";13+import { Effect, FileSystem } from "effect";14+15+import { CheckAt, CheckRunner } from "../src/check-runner.ts";16+import type { CheckJob } from "../src/check-runner.ts";17+import { CheckRunnerLocal } from "../src/check-runner/local.ts";18+19+const lane = (name: string, command: string) => ({20+ command,21+ lane: LaneName.make(name),22+});23+24+/**25+ * A git repo whose `test` script fails, and a runner whose checkout copies26+ * it into a fresh temp dir for each job.27+ */28+const world = Effect.gen(function* () {29+ const fs = yield* FileSystem.FileSystem;30+ const repo = yield* fs.makeTempDirectoryScoped({ prefix: "datekit-" });31+32+ yield* fs.writeFileString(33+ `${repo}/package.json`,34+ JSON.stringify({35+ name: "datekit",36+ private: true,37+ scripts: { test: `node -e "process.exit(1)"` },38+ })39+ );40+ yield* gitOk(repo, "init", "--quiet", "--initial-branch=main");41+ yield* gitOk(repo, "add", "--all");42+ yield* gitOk(repo, "commit", "--quiet", "--message", "Add datekit");43+44+ const head = CommitSha.make(yield* gitOk(repo, "rev-parse", "HEAD"));45+46+ const checkout = () =>47+ fs.makeTempDirectoryScoped({ prefix: "checkout-" }).pipe(48+ Effect.tap((dir) => fs.copy(repo, dir, { overwrite: true })),49+ Effect.mapError(() => new VerifierBlocked({}))50+ );51+52+ const job = (lanes: CheckJob["lanes"]): CheckJob => ({53+ at: CheckAt.cases.Commit.make({ commit: head }),54+ lanes,55+ placeholders: [],56+ project: ProjectName.make("datekit"),57+ proxies: [],58+ repo: RepoName.make("datekit"),59+ });60+61+ return { checkout, job, repo };62+});63+64+// What git exports to a hook that runs the CLI: its own repo, and the config65+// given with `git -c`. Restored when the test's scope closes.66+const inHook = (repo: string) =>67+ Effect.acquireRelease(68+ Effect.sync(() => {69+ vi.stubEnv("GIT_DIR", `${repo}/.git`);70+ vi.stubEnv("GIT_CONFIG_PARAMETERS", "'user.name'='Hook'");71+ }),72+ () => Effect.sync(() => vi.unstubAllEnvs())73+ );74+75+describe(CheckRunnerLocal.layer, () => {76+ it.live("runs each lane as a process in a checkout, and classifies it", () =>77+ Effect.gen(function* () {78+ const { checkout, job } = yield* world;79+80+ const ran = yield* Effect.flatMap(CheckRunner, (runner) =>81+ runner.run(82+ job([83+ lane("test", "bun run test"),84+ lane("ok", "exit 0"),85+ // The user's git config never reaches a lane.86+ lane(87+ "isolated",88+ `test -z "$(git config --global --get user.name)"`89+ ),90+ ])91+ )92+ ).pipe(Effect.provide(CheckRunnerLocal.layer({ checkout })));93+94+ expect(95+ ran.lanes.map(({ lane: name, result }) => [name, result])96+ ).toStrictEqual([97+ ["test", "failed"],98+ ["ok", "passed"],99+ ["isolated", "passed"],100+ ]);101+ expect(ran.lanes[0]?.durationMs).toBeGreaterThan(0);102+ expect(ran.durationMs).toBeGreaterThanOrEqual(103+ ran.lanes[0]?.durationMs ?? 0104+ );105+ expect(ran.evidence).toStrictEqual([{ lane: LaneName.make("test") }]);106+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))107+ );108+109+ it.live("gives a job a HOME of its own, and removes it after the job", () =>110+ Effect.gen(function* () {111+ const fs = yield* FileSystem.FileSystem;112+ const { checkout, job } = yield* world;113+ const seen = yield* fs.makeTempDirectoryScoped({ prefix: "seen-" });114+115+ const ran = yield* Effect.flatMap(CheckRunner, (runner) =>116+ runner.run(job([lane("home", `printf %s "$HOME" > "${seen}/home"`)]))117+ ).pipe(Effect.provide(CheckRunnerLocal.layer({ checkout })));118+119+ const home = yield* fs.readFileString(`${seen}/home`);120+121+ expect(ran.lanes.map(({ result }) => result)).toStrictEqual(["passed"]);122+ expect(home).toContain("check-home-");123+ expect(yield* fs.exists(home)).toBeFalsy();124+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))125+ );126+127+ it.live(128+ "keeps the repo and git config of a hook that runs it away from a lane's git",129+ () =>130+ Effect.gen(function* () {131+ const { checkout, job, repo } = yield* world;132+133+ yield* inHook(repo);134+135+ const ran = yield* Effect.flatMap(CheckRunner, (runner) =>136+ runner.run(137+ job([138+ lane(139+ "own-repo",140+ `test "$(git rev-parse --absolute-git-dir)" = "$(pwd -P)/.git"`141+ ),142+ lane("no-hook-config", `test -z "$(git config --get user.name)"`),143+ ])144+ )145+ ).pipe(Effect.provide(CheckRunnerLocal.layer({ checkout })));146+147+ expect(148+ ran.lanes.map(({ lane: name, result }) => [name, result])149+ ).toStrictEqual([150+ ["own-repo", "passed"],151+ ["no-hook-config", "passed"],152+ ]);153+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))154+ );155+156+ it.live("stops a lane at its time limit and calls it blocked", () =>157+ Effect.gen(function* () {158+ const { checkout, job } = yield* world;159+160+ const ran = yield* Effect.flatMap(CheckRunner, (runner) =>161+ runner.run(job([{ ...lane("slow", "sleep 5"), timeoutMs: 300 }]))162+ ).pipe(Effect.provide(CheckRunnerLocal.layer({ checkout })));163+164+ expect(ran.lanes[0]?.result).toBe("blocked");165+ expect(ran.lanes[0]?.durationMs).toBeGreaterThanOrEqual(300);166+ expect(ran.lanes[0]?.durationMs).toBeLessThan(4000);167+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))168+ );169+170+ it.live(171+ "is VerifierBlocked for a held-back suite, which only the Checker runs",172+ () =>173+ Effect.gen(function* () {174+ const { checkout, job } = yield* world;175+176+ const blocked = yield* Effect.flatMap(CheckRunner, (runner) =>177+ runner.run({178+ ...job([lane("ok", "exit 0")]),179+ heldBack: {180+ areas: [AreaName.make("parse")],181+ at: CommitSha.make("3".repeat(40)),182+ layerRepo: RepoName.make("datekit--maintainers"),183+ suite: SuiteRoot.make(`sha256:${"4".repeat(64)}`),184+ },185+ })186+ ).pipe(187+ Effect.provide(CheckRunnerLocal.layer({ checkout })),188+ Effect.flip189+ );190+191+ expect(blocked).toStrictEqual(new VerifierBlocked({}));192+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))193+ );194+});added:packages/checks/test/check-runner-memory.test.ts+139 added
1+import { describe, expect, it } from "@effect/vitest";2+import type { LaneResult } from "@repo/protocol/domain/answer";3+import {4+ CommitSha,5+ LaneName,6+ ProjectName,7+ RepoName,8+ TreeSha,9+} from "@repo/protocol/ids";10+import { VerifierBlocked } from "@repo/protocol/refusal";11+import { Effect, Result } from "effect";12+13+import { CheckAt, CheckRunner } from "../src/check-runner.ts";14+import type { CheckJob } from "../src/check-runner.ts";15+import { CheckRunnerMemory } from "../src/check-runner/memory.ts";16+import { redFirstOfRuns } from "../src/red-first.ts";17+18+const tree = TreeSha.make("1".repeat(40));19+20+const main = CommitSha.make("2".repeat(40));21+22+const unit = LaneName.make("unit");23+24+const lint = LaneName.make("lint");25+26+const onTree = CheckAt.cases.Tree.make({ tree });27+28+const onMain = CheckAt.cases.Commit.make({ commit: main });29+30+const job = (at: CheckAt, ...lanes: readonly LaneName[]): CheckJob => ({31+ at,32+ lanes: lanes.map((lane) => ({ command: `bun run ${lane}`, lane })),33+ placeholders: [],34+ project: ProjectName.make("datekit"),35+ proxies: [],36+ repo: RepoName.make("datekit"),37+});38+39+const ran = (40+ lane: LaneName,41+ result: LaneResult["result"],42+ durationMs: number43+): LaneResult => ({ command: `bun run ${lane}`, durationMs, lane, result });44+45+const run = (each: CheckJob) =>46+ Effect.flatMap(CheckRunner, (runner) => runner.run(each));47+48+describe(CheckRunnerMemory.layer, () => {49+ it.effect(50+ "returns the scripted results for a tree and lane in order, then repeats the last",51+ () =>52+ Effect.gen(function* () {53+ const runs = yield* Effect.all(54+ [55+ run(job(onTree, unit)),56+ run(job(onTree, unit)),57+ run(job(onTree, unit)),58+ ],59+ { concurrency: 1 }60+ );61+62+ expect(runs.map(({ lanes }) => lanes)).toStrictEqual([63+ [ran(unit, "failed", 30)],64+ [ran(unit, "passed", 20)],65+ [ran(unit, "passed", 20)],66+ ]);67+ }).pipe(68+ Effect.provide(69+ CheckRunnerMemory.layer(70+ new Map([71+ [72+ `${tree}:${unit}`,73+ [ran(unit, "failed", 30), ran(unit, "passed", 20)],74+ ],75+ ])76+ )77+ )78+ )79+ );80+81+ it.effect(82+ "keeps one script per tree or commit and lane, and totals the run's time",83+ () =>84+ Effect.gen(function* () {85+ const onBoth = yield* run(job(onTree, unit, lint));86+ const onMainAlone = yield* run(job(onMain, unit));87+88+ expect(onBoth).toStrictEqual({89+ durationMs: 40,90+ evidence: [{ lane: lint, signature: "lint: scripted failure" }],91+ heldBack: [],92+ lanes: [ran(unit, "passed", 30), ran(lint, "failed", 10)],93+ });94+ expect(onMainAlone.lanes).toStrictEqual([ran(unit, "loadError", 5)]);95+ expect(onMainAlone.evidence).toStrictEqual([{ lane: unit }]);96+ }).pipe(97+ Effect.provide(98+ CheckRunnerMemory.layer(99+ new Map([100+ [`${tree}:${unit}`, [ran(unit, "passed", 30)]],101+ [`${tree}:${lint}`, [ran(lint, "failed", 10)]],102+ [`${main}:${unit}`, [ran(unit, "loadError", 5)]],103+ ])104+ )105+ )106+ )107+ );108+109+ it.effect("makes two scripted failures on main red first", () =>110+ Effect.gen(function* () {111+ const first = yield* run(job(onMain, unit));112+ const second = yield* run(job(onMain, unit));113+114+ expect(redFirstOfRuns([first, second], unit)).toStrictEqual(115+ Result.succeed({ lane: unit, signature: "unit: scripted failure" })116+ );117+ }).pipe(118+ Effect.provide(119+ CheckRunnerMemory.layer(120+ new Map([[`${main}:${unit}`, [ran(unit, "failed", 30)]]])121+ )122+ )123+ )124+ );125+126+ it.effect("is VerifierBlocked for a tree and lane it has no script for", () =>127+ Effect.gen(function* () {128+ const blocked = yield* Effect.flip(run(job(onTree, unit, lint)));129+130+ expect(blocked).toStrictEqual(new VerifierBlocked({}));131+ }).pipe(132+ Effect.provide(133+ CheckRunnerMemory.layer(134+ new Map([[`${tree}:${unit}`, [ran(unit, "passed", 30)]]])135+ )136+ )137+ )138+ );139+});added:packages/checks/test/classify.test.ts+233 added
1+import { describe, expect, it } from "@effect/vitest";2+import { LaneName } from "@repo/protocol/ids";3+import { Option } from "effect";4+5+import { classifyRun, failureSignature } from "../src/classify.ts";6+import type { RunExit } from "../src/classify.ts";7+import bunAssertion from "./fixtures/runs/bun-assertion.json" with { type: "json" };8+import bunLoadError from "./fixtures/runs/bun-load-error.json" with { type: "json" };9+import bunNoTests from "./fixtures/runs/bun-no-tests.json" with { type: "json" };10+import nodeSyntaxError from "./fixtures/runs/node-syntax-error.json" with { type: "json" };11+import vitestAssertion from "./fixtures/runs/vitest-assertion.json" with { type: "json" };12+import vitestLoadError from "./fixtures/runs/vitest-load-error.json" with { type: "json" };13+import vitestNoTests from "./fixtures/runs/vitest-no-tests.json" with { type: "json" };14+15+const unit = LaneName.make("unit");16+17+// pytest is not installed here, so this run is written out by hand in18+// pytest 8's plain-`assert` failure format, not recorded.19+const pytestAssertion = (path: string, address: string, seconds: string) => ({20+ code: 1,21+ stderr: "",22+ stdout: [23+ "============================= test session starts ==============================",24+ `rootdir: ${path}`,25+ "collected 1 item",26+ "",27+ "test_week.py F [100%]",28+ "",29+ "=================================== FAILURES ===================================",30+ "_______________________________ test_first_week ________________________________",31+ "",32+ " def test_first_week():",33+ '> assert week_of("2026-W01") == 1',34+ `E assert 0 == 1`,35+ `E + where 0 = week_of(<datekit.Week object at ${address}>)`,36+ "",37+ `${path}/test_week.py:5: AssertionError`,38+ "=========================== short test summary info ============================",39+ "FAILED test_week.py::test_first_week - assert 0 == 1",40+ `============================== 1 failed in ${seconds} ===============================`,41+ ].join("\n"),42+});43+44+// vitest before 4 reported a missing import this way; 5 says "Cannot find module".45+const failedToLoadUrl: RunExit = {46+ code: 1,47+ stderr:48+ "Error: Failed to load url ../src/week.ts (resolved id: ../src/week.ts) in /work/datekit/test/week.test.ts. Does the file exist?",49+ stdout: " Test Files 1 failed (1)\n Tests no tests",50+};51+52+// A bun-style failure whose assertion line names a path, a duration and an address.53+const exit = (path: string, ms: string, address: string): RunExit => ({54+ code: 1,55+ stderr: `(fail) parses [${ms}]\nAssertionError: ${path}/week.ts took ${ms} at ${address}`,56+ stdout: "",57+});58+59+// The same run as the /local runner sees it: output only, never a report.60+const withoutReport = ({ code, stderr, stdout }: RunExit): RunExit => ({61+ code,62+ stderr,63+ stdout,64+});65+66+describe(classifyRun, () => {67+ describe("with vitest's JSON report", () => {68+ it("is failed when a test fails on an assertion", () => {69+ expect(classifyRun(unit, vitestAssertion)).toBe("failed");70+ });71+72+ it("is loadError when the test file fails to load", () => {73+ expect(classifyRun(unit, vitestLoadError)).toBe("loadError");74+ });75+76+ it("is loadError when no test file is found", () => {77+ expect(classifyRun(unit, vitestNoTests)).toBe("loadError");78+ });79+80+ it("is passed on exit 0, even when the report found no tests", () => {81+ expect(classifyRun(unit, { ...vitestNoTests, code: 0 })).toBe("passed");82+ });83+ });84+85+ // The /local runner never has a report: vitest's own output decides.86+ describe("from vitest's output, with the report left out", () => {87+ it("is failed on an assertion", () => {88+ expect(classifyRun(unit, withoutReport(vitestAssertion))).toBe("failed");89+ expect(failureSignature(withoutReport(vitestAssertion))).toStrictEqual(90+ Option.some(91+ "test/week.test.js > parseWeek > reads the first week of a year: AssertionError: expected { week: +0, year: 2026 } to strictly equal { week: 1, year: 2026 }"92+ )93+ );94+ });95+96+ it("is loadError when the test file fails to load, or none is found", () => {97+ expect(classifyRun(unit, withoutReport(vitestLoadError))).toBe(98+ "loadError"99+ );100+ expect(classifyRun(unit, withoutReport(vitestNoTests))).toBe("loadError");101+ });102+ });103+104+ describe("from the output, when there is no report", () => {105+ it("is failed on bun's expect(...).toBe failure", () => {106+ expect(classifyRun(unit, bunAssertion)).toBe("failed");107+ });108+109+ it("is failed on pytest's AssertionError", () => {110+ expect(111+ classifyRun(unit, pytestAssertion("/work/datekit", "0x7f3a", "0.02s"))112+ ).toBe("failed");113+ });114+115+ it("is loadError on a SyntaxError", () => {116+ expect(classifyRun(unit, nodeSyntaxError)).toBe("loadError");117+ });118+119+ it("is loadError on Cannot find module", () => {120+ expect(classifyRun(unit, bunLoadError)).toBe("loadError");121+ });122+123+ it("is loadError on Failed to load url", () => {124+ expect(classifyRun(unit, failedToLoadUrl)).toBe("loadError");125+ });126+127+ it("is loadError when bun finds no test files", () => {128+ expect(classifyRun(unit, bunNoTests)).toBe("loadError");129+ });130+131+ it("is failed when a nonzero exit says nothing more", () => {132+ expect(133+ classifyRun(LaneName.make("lint"), {134+ code: 1,135+ stderr: "",136+ stdout: "Found 3 warnings and 2 errors.",137+ })138+ ).toBe("failed");139+ });140+ });141+142+ it("is passed on exit 0", () => {143+ expect(144+ classifyRun(unit, { code: 0, stderr: "", stdout: "1 pass\n0 fail" })145+ ).toBe("passed");146+ });147+148+ it("is blocked when the runner was killed at the time limit", () => {149+ expect(150+ classifyRun(unit, {151+ code: 1,152+ stderr: "",153+ stdout: "AssertionError: expected 0 to be 1",154+ timedOut: true,155+ })156+ ).toBe("blocked");157+ });158+159+ it("is blocked when the lane's command could not start", () => {160+ expect(161+ classifyRun(unit, {162+ code: 127,163+ stderr: "sh: 1: vitest: not found",164+ stdout: "",165+ })166+ ).toBe("blocked");167+ });168+});169+170+describe(failureSignature, () => {171+ it("names the failing test and the first line of its assertion, from the report", () => {172+ expect(failureSignature(vitestAssertion)).toStrictEqual(173+ Option.some(174+ "parseWeek reads the first week of a year: AssertionError: expected { week: +0, year: 2026 } to strictly equal { week: 1, year: 2026 }"175+ )176+ );177+ });178+179+ it("names the failing test and its expectation, from bun's output", () => {180+ expect(failureSignature(bunAssertion)).toStrictEqual(181+ Option.some(182+ "weekOf > reads the first week of a year: error: expect(received).toBe(expected) Expected: 1 Received: 0"183+ )184+ );185+ });186+187+ it("names the failing test and its assertion, from pytest's output", () => {188+ expect(189+ failureSignature(pytestAssertion("/work/datekit", "0x7f3a", "0.02s"))190+ ).toStrictEqual(191+ Option.some("test_week.py::test_first_week: E assert 0 == 1")192+ );193+ });194+195+ it("is the same for two runs that differ only in paths, durations and addresses", () => {196+ const first = failureSignature(197+ pytestAssertion("/home/ci/a", "0x7f3a2c", "0.02s")198+ );199+200+ const second = failureSignature(201+ pytestAssertion("/tmp/run-9/b", "0x55d0e1", "1.31s")202+ );203+204+ expect(first).toStrictEqual(205+ Option.some("test_week.py::test_first_week: E assert 0 == 1")206+ );207+ expect(second).toStrictEqual(first);208+ });209+210+ it("strips durations, absolute paths and addresses from the assertion line", () => {211+ const first = failureSignature(212+ exit("/home/ci/datekit", "12.5ms", "0xdeadbeef")213+ );214+215+ expect(first).toStrictEqual(216+ Option.some("parses: AssertionError: <path> took <duration> at <address>")217+ );218+ expect(219+ failureSignature(exit("/work/datekit", "3ms", "0x7f00aa"))220+ ).toStrictEqual(first);221+ });222+223+ it("is none for a run that failed to load", () => {224+ expect(failureSignature(vitestLoadError)).toStrictEqual(Option.none());225+ expect(failureSignature(bunLoadError)).toStrictEqual(Option.none());226+ });227+228+ it("is none for a run that passed", () => {229+ expect(failureSignature({ code: 0, stderr: "", stdout: "" })).toStrictEqual(230+ Option.none()231+ );232+ });233+});added:packages/checks/test/phases.test.ts+169 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Command, Hostname } from "@repo/protocol/domain/common";3+import type { RunBlock } from "@repo/protocol/domain/run";4+import { AreaName, EnvKey, LaneName } from "@repo/protocol/ids";5+import { Array, Option } from "effect";6+7+import { Phase, phasePlan } from "../src/phases.ts";8+import type { PlanInput } from "../src/phases.ts";9+10+const unit = { command: "bun run test", lane: LaneName.make("unit") };11+12+const lint = { command: "bun run lint", lane: LaneName.make("lint") };13+14+const setup = Command.make("bun install --frozen-lockfile --ignore-scripts");15+16+const registry = Hostname.make("registry.npmjs.org");17+18+const run: RunBlock = {19+ checks: { [unit.lane]: Command.make(unit.command) },20+ setup,21+ setupEgress: [registry],22+ test: Command.make("bun test {path}"),23+};24+25+const parse = AreaName.make("parse");26+27+const token = EnvKey.make("PAYMENTS_KEY");28+29+const input: PlanInput = {30+ heldBack: Option.none(),31+ lanes: [unit],32+ lockfileHash: "sha256:9f86d081",33+ placeholders: [token],34+ run,35+};36+37+const tags = (phases: readonly Phase[]) => phases.map(({ _tag }) => _tag);38+39+const keyOf = (phases: readonly Phase[]) =>40+ phases.flatMap((phase) => (Phase.$is("Snapshot")(phase) ? [phase.key] : []));41+42+// Every input combination: setup or none, extra setup hosts or none,43+// held-back or none, placeholders or none, and zero, one or two lanes.44+const { setup: _setup, setupEgress: _egress, ...bare } = run;45+46+const runBlocks: readonly RunBlock[] = [47+ bare,48+ { ...bare, setup },49+ { ...bare, setupEgress: [registry] },50+ { ...bare, setup, setupEgress: [registry] },51+];52+53+const heldBacks = [Option.none(), Option.some({ areas: [parse] })];54+55+const combinations = Array.flatMap(runBlocks, (runBlock) =>56+ Array.flatMap(heldBacks, (heldBack) =>57+ Array.flatMap([[], [token]], (placeholders) =>58+ Array.map([0, 1, 2], (laneCount): PlanInput => ({59+ heldBack,60+ lanes: [unit, lint].slice(0, laneCount),61+ lockfileHash: "sha256:9f86d081",62+ placeholders,63+ run: runBlock,64+ }))65+ )66+ )67+);68+69+describe(phasePlan, () => {70+ it("is setup, snapshot, egress off, run, report without held-back checks", () => {71+ const phases = phasePlan(input);72+73+ expect(tags(phases)).toStrictEqual([74+ "Setup",75+ "Snapshot",76+ "EgressOff",77+ "Run",78+ "Report",79+ ]);80+ expect(phases[0]).toStrictEqual(81+ Phase.Setup({ command: setup, egress: [registry] })82+ );83+ expect(phases[3]).toStrictEqual(84+ Phase.Run({ lanes: [unit], placeholders: [token] })85+ );86+ });87+88+ it("writes held-back files after egress is off and before the run", () => {89+ const phases = phasePlan({90+ ...input,91+ heldBack: Option.some({ areas: [parse] }),92+ });93+94+ expect(tags(phases)).toStrictEqual([95+ "Setup",96+ "Snapshot",97+ "EgressOff",98+ "WriteHeldBack",99+ "Run",100+ "Report",101+ ]);102+ expect(phases[3]).toStrictEqual(Phase.WriteHeldBack({ areas: [parse] }));103+ });104+105+ it("has no setup and nothing to snapshot when the run block declares no setup", () => {106+ expect(tags(phasePlan({ ...input, run: bare }))).toStrictEqual([107+ "EgressOff",108+ "Run",109+ "Report",110+ ]);111+ });112+113+ it("keys the snapshot by what setup installs from: the lockfile, the command and its hosts", () => {114+ const key = keyOf(phasePlan(input));115+116+ expect(key).toHaveLength(1);117+ expect(keyOf(phasePlan(input))).toStrictEqual(key);118+ expect(119+ keyOf(phasePlan({ ...input, lockfileHash: "sha256:60303ae2" }))120+ ).not.toStrictEqual(key);121+ expect(122+ keyOf(123+ phasePlan({124+ ...input,125+ run: { ...run, setup: Command.make("bun install") },126+ })127+ )128+ ).not.toStrictEqual(key);129+ expect(130+ keyOf(phasePlan({ ...input, run: { ...run, setupEgress: [] } }))131+ ).not.toStrictEqual(key);132+ });133+134+ it("holds the Checker's order over every input combination", () => {135+ expect(combinations).toHaveLength(48);136+137+ for (const each of combinations) {138+ const order = tags(phasePlan(each));139+ const at = (tag: Phase["_tag"]) => order.indexOf(tag);140+141+ // A snapshot taken after held-back files are written would carry them142+ // into the next Sandbox (OSR §5.3 step 3).143+ const afterWrite =144+ at("WriteHeldBack") === -1 ? [] : order.slice(at("WriteHeldBack"));145+146+ expect(afterWrite).not.toContain("Snapshot");147+148+ // Egress is off before the run, and the report comes last.149+ expect(150+ order.filter((tag) => ["EgressOff", "Run", "Report"].includes(tag))151+ ).toStrictEqual(["EgressOff", "Run", "Report"]);152+ expect(order.at(-1)).toBe("Report");153+ expect(at("WriteHeldBack") !== -1).toBe(Option.isSome(each.heldBack));154+ }155+ });156+157+ it("lists placeholders in the run phase only, over every input combination", () => {158+ for (const each of combinations) {159+ const phases = phasePlan(each);160+ const running = phases.filter(Phase.$is("Run"));161+ const others = phases.filter((phase) => !Phase.$is("Run")(phase));162+163+ expect(JSON.stringify(others)).not.toContain(token);164+ expect(running).toStrictEqual([165+ Phase.Run({ lanes: each.lanes, placeholders: each.placeholders }),166+ ]);167+ }168+ });169+});added:packages/checks/test/red-first.test.ts+157 added
1+import { describe, expect, it } from "@effect/vitest";2+import { LaneName } from "@repo/protocol/ids";3+import { NotRedFirst, WeakCheck } from "@repo/protocol/refusal";4+import { Result } from "effect";5+6+import type { CheckRun } from "../src/check-runner.ts";7+import type { RunExit } from "../src/classify.ts";8+import { redFirst, redFirstOfRuns } from "../src/red-first.ts";9+import bunAssertion from "./fixtures/runs/bun-assertion.json" with { type: "json" };10+import vitestAssertionOther from "./fixtures/runs/vitest-assertion-other.json" with { type: "json" };11+import vitestAssertion from "./fixtures/runs/vitest-assertion.json" with { type: "json" };12+import vitestLoadError from "./fixtures/runs/vitest-load-error.json" with { type: "json" };13+import vitestNoTests from "./fixtures/runs/vitest-no-tests.json" with { type: "json" };14+15+const unit = LaneName.make("unit");16+17+const onUnit = (exit: RunExit) => ({ exit, lane: unit });18+19+const passed: RunExit = { code: 0, stderr: "", stdout: " 1 pass\n 0 fail" };20+21+const notRedFirst = Result.fail(new NotRedFirst({}));22+23+// What the platform sees of a run: lanes and evidence, never the output.24+const checkRun = (25+ result: CheckRun["lanes"][number]["result"],26+ evidence: Omit<CheckRun["evidence"][number], "lane">27+): CheckRun => ({28+ durationMs: 40,29+ evidence: result === "passed" ? [] : [{ lane: unit, ...evidence }],30+ heldBack: [],31+ lanes: [{ command: "bun run test", durationMs: 40, lane: unit, result }],32+});33+34+describe(redFirst, () => {35+ it("holds for two runs failing on the same assertion in the same test", () => {36+ expect(37+ redFirst([onUnit(vitestAssertion), onUnit(vitestAssertion)])38+ ).toStrictEqual(39+ Result.succeed({40+ lane: unit,41+ signature:42+ "parseWeek reads the first week of a year: AssertionError: expected { week: +0, year: 2026 } to strictly equal { week: 1, year: 2026 }",43+ })44+ );45+ });46+47+ it("holds from the output alone, with no report", () => {48+ expect(49+ redFirst([onUnit(bunAssertion), onUnit(bunAssertion)])50+ ).toStrictEqual(51+ Result.succeed({52+ lane: unit,53+ signature:54+ "weekOf > reads the first week of a year: error: expect(received).toBe(expected) Expected: 1 Received: 0",55+ })56+ );57+ });58+59+ it("is NotRedFirst for one assertion failure and one load error", () => {60+ expect(61+ redFirst([onUnit(vitestAssertion), onUnit(vitestLoadError)])62+ ).toStrictEqual(notRedFirst);63+ });64+65+ it("is NotRedFirst for two load errors: the check fails before it asserts", () => {66+ expect(67+ redFirst([onUnit(vitestLoadError), onUnit(vitestLoadError)])68+ ).toStrictEqual(notRedFirst);69+ });70+71+ it("is NotRedFirst for two passes", () => {72+ expect(redFirst([onUnit(passed), onUnit(passed)])).toStrictEqual(73+ notRedFirst74+ );75+ });76+77+ it("is NotRedFirst for two failures on different assertions: a flaky check is not red first", () => {78+ expect(79+ redFirst([onUnit(vitestAssertion), onUnit(vitestAssertionOther)])80+ ).toStrictEqual(notRedFirst);81+ });82+83+ it("is NotRedFirst for two failures that threw rather than asserted", () => {84+ const threw: RunExit = {85+ code: 1,86+ stderr:87+ "TypeError: weekOf is not a function\n(fail) weekOf > reads the first week of a year [0.40ms]",88+ stdout: "",89+ };90+91+ expect(redFirst([onUnit(threw), onUnit(threw)])).toStrictEqual(notRedFirst);92+ });93+94+ it("is WeakCheck no assertion when a run found no tests", () => {95+ expect(96+ redFirst([onUnit(vitestNoTests), onUnit(vitestNoTests)])97+ ).toStrictEqual(Result.fail(new WeakCheck({ weakness: "no assertion" })));98+ });99+});100+101+describe(redFirstOfRuns, () => {102+ const signature = "parseWeek reads the first week of a year: expected 0";103+104+ it("holds for two runs whose lane failed with the same signature", () => {105+ expect(106+ redFirstOfRuns(107+ [checkRun("failed", { signature }), checkRun("failed", { signature })],108+ unit109+ )110+ ).toStrictEqual(Result.succeed({ lane: unit, signature }));111+ });112+113+ it("is NotRedFirst when the signatures differ", () => {114+ expect(115+ redFirstOfRuns(116+ [117+ checkRun("failed", { signature }),118+ checkRun("failed", { signature: `${signature} but 2` }),119+ ],120+ unit121+ )122+ ).toStrictEqual(notRedFirst);123+ });124+125+ it("is NotRedFirst when a run failed with no signature, or passed", () => {126+ expect(127+ redFirstOfRuns(128+ [checkRun("failed", { signature }), checkRun("loadError", {})],129+ unit130+ )131+ ).toStrictEqual(notRedFirst);132+ expect(133+ redFirstOfRuns([checkRun("passed", {}), checkRun("passed", {})], unit)134+ ).toStrictEqual(notRedFirst);135+ });136+137+ it("is NotRedFirst when a run has no such lane", () => {138+ expect(139+ redFirstOfRuns(140+ [checkRun("failed", { signature }), checkRun("failed", { signature })],141+ LaneName.make("ask")142+ )143+ ).toStrictEqual(notRedFirst);144+ });145+146+ it("is WeakCheck no assertion when a run found no tests", () => {147+ expect(148+ redFirstOfRuns(149+ [150+ checkRun("loadError", { weakness: "no assertion" }),151+ checkRun("loadError", { weakness: "no assertion" }),152+ ],153+ unit154+ )155+ ).toStrictEqual(Result.fail(new WeakCheck({ weakness: "no assertion" })));156+ });157+});deleted:packages/checks/test/smoke.test.ts-10 removed
1-import { describe, expect, it } from "@effect/vitest";2-3-import manifest from "../package.json" with { type: "json" };4-5-// A skeleton's one test, so vitest finds a file; real tests replace it.6-describe("the package", () => {7- it("is @repo/checks", () => {8- expect(manifest.name).toBe("@repo/checks");9- });10-});added:packages/checks/test/weak-shapes.test.ts+228 added
1+import { describe, expect, it } from "@effect/vitest";2+3+import { weaknessesOf } from "../src/weak-shapes.ts";4+5+// The check files are datekit's, held as text: the lint reads source, never6+// runs it. The territory is what `territory.package` gives a workspace.7+const territory = ["packages/week/**"];8+9+const check = (10+ imports: string,11+ body: string,12+ path = "packages/week/test/week.test.ts"13+) => ({14+ content: `${imports}15+import { describe, expect, it, vi } from "vitest";16+17+describe("parseWeek", () => {18+ it("reads the first week of a year", () => {19+${body}20+ });21+});22+`,23+ path,24+});25+26+const fromTerritory = `import { onWeek, parseWeek } from "../src/week.ts";`;27+28+describe(weaknessesOf, () => {29+ it("passes a real assertion over a territory import", () => {30+ expect(31+ weaknessesOf(32+ check(33+ fromTerritory,34+ `expect(parseWeek("2026-W01")).toStrictEqual({ week: 1, year: 2026 });`35+ ),36+ territory37+ )38+ ).toStrictEqual([]);39+ });40+41+ it("passes a check beside the source it tests, in the same folder", () => {42+ expect(43+ weaknessesOf(44+ check(45+ `import { parseWeek } from "./week.ts";`,46+ `expect(parseWeek("2026-W01").week).toBe(1);`,47+ "packages/week/src/week.test.ts"48+ ),49+ territory50+ )51+ ).toStrictEqual([]);52+ });53+54+ it("passes a check that reaches a one-file territory through its folder's index", () => {55+ expect(56+ weaknessesOf(57+ check(58+ `import { parseISO } from "../../src/index.ts";`,59+ `expect(parseISO("2026-W41-3").getDay()).toBe(3);`,60+ "test/asks/parse-iso-week.test.ts"61+ ),62+ ["src/parse.ts"]63+ )64+ ).toStrictEqual([]);65+ });66+67+ it("passes a territory import by package name", () => {68+ expect(69+ weaknessesOf(70+ check(71+ `import { parseWeek } from "@datekit/week";`,72+ `expect(parseWeek("2026-W01").week).toBe(1);`73+ ),74+ territory75+ )76+ ).toStrictEqual([]);77+ });78+79+ it("passes a check with one real assertion among weak ones", () => {80+ expect(81+ weaknessesOf(82+ check(83+ fromTerritory,84+ `expect(1).toBe(1);85+ expect(() => parseWeek("2026-W01")).not.toThrow();86+ expect(parseWeek("2026-W01").week).toBe(1);`87+ ),88+ territory89+ )90+ ).toStrictEqual([]);91+ });92+93+ it("flags self-referential: the check imports nothing from the territory", () => {94+ expect(95+ weaknessesOf(96+ check(97+ `import { weeksIn } from "../../calendar/src/year.ts";`,98+ `const parseWeek = (text: string) => ({ week: Number(text.slice(6)) });99+ expect(parseWeek("2026-W01")).toStrictEqual({ week: 1 });`100+ ),101+ territory102+ )103+ ).toStrictEqual(["self-referential"]);104+ });105+106+ it("flags constant pin: every expectation is on a literal", () => {107+ expect(108+ weaknessesOf(109+ check(110+ fromTerritory,111+ `parseWeek("2026-W01");112+ expect(1).toBe(1);113+ expect("week").toStrictEqual("week");114+ expect({ week: 1 }).toStrictEqual({ week: 1 });`115+ ),116+ territory117+ )118+ ).toStrictEqual(["constant pin"]);119+ });120+121+ it("passes a literal held against the territory's result", () => {122+ expect(123+ weaknessesOf(124+ check(fromTerritory, `expect(1).toBe(parseWeek("2026-W01").week);`),125+ territory126+ )127+ ).toStrictEqual([]);128+ });129+130+ it("flags absence-only: every expectation is that nothing happened", () => {131+ expect(132+ weaknessesOf(133+ check(134+ fromTerritory,135+ `expect(() => parseWeek("2026-W01")).not.toThrow();136+ expect(parseWeek("")).toBeUndefined();137+ expect(parseWeek("2026-W54")).toBeFalsy();`138+ ),139+ territory140+ )141+ ).toStrictEqual(["absence-only"]);142+ });143+144+ it("flags mock-only: every expectation is on a vi.fn()", () => {145+ expect(146+ weaknessesOf(147+ check(148+ fromTerritory,149+ `const listener = vi.fn();150+ onWeek(listener);151+ expect(listener).toHaveBeenCalled();152+ expect(listener.mock.calls.length).toBe(1);`153+ ),154+ territory155+ )156+ ).toStrictEqual(["mock-only"]);157+ });158+159+ it("flags fixture-asserts-fixture: expected and actual come from the same fixture", () => {160+ expect(161+ weaknessesOf(162+ check(163+ `${fromTerritory}164+import fixture from "./fixtures/first-week.json";`,165+ `parseWeek(fixture.text);166+ expect(fixture.parsed).toStrictEqual(fixture.expected);`167+ ),168+ territory169+ )170+ ).toStrictEqual(["fixture-asserts-fixture"]);171+ });172+173+ it("flags a check that recomputes its expected value the way the code does", () => {174+ expect(175+ weaknessesOf(176+ check(177+ fromTerritory,178+ `expect(parseWeek("2026-W01")).toStrictEqual(parseWeek("2026-W01"));`179+ ),180+ territory181+ )182+ ).toStrictEqual(["fixture-asserts-fixture"]);183+ });184+185+ it("passes two fields of one computed result held against each other", () => {186+ expect(187+ weaknessesOf(188+ check(189+ fromTerritory,190+ `const week = parseWeek("2026-W01");191+ expect(week.start).toBeLessThan(week.end);`192+ ),193+ territory194+ )195+ ).toStrictEqual([]);196+ });197+198+ it("ignores expectations inside comments and strings", () => {199+ expect(200+ weaknessesOf(201+ check(202+ fromTerritory,203+ `// expect(1).toBe(1);204+ /* expect(listener).toHaveBeenCalled(); */205+ const note = "expect(0).toBeFalsy()";206+ expect(parseWeek(note).week).toBe(1);`207+ ),208+ territory209+ )210+ ).toStrictEqual([]);211+ });212+213+ it("flags nothing in a file it cannot read: no expect calls", () => {214+ expect(215+ weaknessesOf(216+ {217+ content: `from datekit.week import parse_week218+219+def test_first_week():220+ assert parse_week("2026-W01") == (2026, 1)221+`,222+ path: "packages/week/test/test_week.py",223+ },224+ territory225+ )226+ ).toStrictEqual([]);227+ });228+});