opencode-model-router 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,209 @@
1
1
  // Impure, bounded Git fingerprint adapter. Never interpolates paths into a shell.
2
- import { execFile } from "node:child_process";
2
+ import { execFile, spawn, type ChildProcess } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
4
  import { lstat, readFile, readlink, realpath } from "node:fs/promises";
5
- import { resolve } from "node:path";
6
- import type { TreeSnapshot, ChangedFile } from "./dispatch";
5
+ import { constants as osConstants, setPriority } from "node:os";
6
+ import { join, resolve } from "node:path";
7
+ import { ABSENT_DIGEST, FILE_DIGEST_PREFIX, LINK_DIGEST_PREFIX, type TreeSnapshot, type ChangedFile } from "./dispatch";
7
8
 
8
- export async function snapshotTree(cwd: string, signal: AbortSignal): Promise<TreeSnapshot | undefined> {
9
+ /** Each git process of a snapshot. */
10
+ export const SNAPSHOT_GIT_TIMEOUT_MS = 10_000;
11
+ /** Each git process's stdout, in bytes (execFile's maxBuffer). */
12
+ export const SNAPSHOT_GIT_MAX_BUFFER = 32 * 1024 * 1024;
13
+
14
+ /** What one git process of a snapshot is spawned with. */
15
+ export interface SnapshotGitOptions {
16
+ readonly cwd: string;
17
+ readonly signal: AbortSignal;
18
+ readonly timeoutMs: number;
19
+ readonly maxBuffer: number;
20
+ /** QA-3.1-8: below-normal OS priority (VerifyBudget.lowPriority), like every other verification process. */
21
+ readonly lowPriority: boolean;
22
+ }
23
+
24
+ /**
25
+ * One git process of a snapshot: `git` with `args`, never a shell. Resolves its stdout; rejects on a
26
+ * non-zero exit, a timeout, an abort or a spawn error.
27
+ */
28
+ export type SnapshotGit = (args: readonly string[], opts: SnapshotGitOptions) => Promise<string>;
29
+
30
+ /** Windows: lowers a spawned child's priority class; false when it could not (the child may have exited). */
31
+ function lowerPriority(pid: number): boolean {
32
+ try {
33
+ setPriority(pid, osConstants.priority.PRIORITY_BELOW_NORMAL);
34
+ return true;
35
+ } catch {
36
+ return false; // The run itself is unaffected, as in exec.ts.
37
+ }
38
+ }
39
+
40
+ const isWin = process.platform === "win32";
41
+ /** exec.ts's rule: Windows tools by absolute path, never looked up in the (project) cwd. */
42
+ const TASKKILL = process.env.SystemRoot ? join(process.env.SystemRoot, "System32", "taskkill.exe") : "taskkill.exe";
43
+ const TASKKILL_TIMEOUT_MS = 5000;
44
+
45
+ /**
46
+ * QA-G-6: end git and everything it spawned (fsmonitor hooks, filters such as git-lfs), the same
47
+ * way exec.ts kills a verification tree: `taskkill /T /F` on Windows, the process group on POSIX
48
+ * (git is spawned detached, so it leads its own group). execFile's own abort/timeout ends git only.
49
+ * Kept here rather than imported from exec.ts: several tests mock exec.ts while calling this module.
50
+ */
51
+ function killGitTree(child: ChildProcess): void {
52
+ const pid = child.pid;
53
+ if (pid === undefined) return; // Never started; its `error` rejects the call.
54
+ if (isWin) {
55
+ execFile(TASKKILL, ["/pid", String(pid), "/T", "/F"], { windowsHide: true, timeout: TASKKILL_TIMEOUT_MS }, (err) => {
56
+ if (err) child.kill();
57
+ });
58
+ return;
59
+ }
60
+ try {
61
+ process.kill(-pid, "SIGKILL");
62
+ } catch {
63
+ child.kill("SIGKILL");
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The default SnapshotGit. QA-3.1-8: `lowPriority` applies exec.ts's rule: on POSIX
69
+ * `nice -n 10 -- git …` (inherited from birth), on Windows PRIORITY_BELOW_NORMAL set on the child
70
+ * right after the spawn (its descendants inherit the class). QA-G-6: an abort, the timeout or a
71
+ * stdout past `maxBuffer` rejects at once and kills git's whole tree (`killGitTree`).
72
+ */
73
+ export const execGit: SnapshotGit = (args, opts) => new Promise<string>((ok, fail) => {
74
+ if (opts.signal.aborted) {
75
+ fail(new Error("git aborted before it started"));
76
+ return;
77
+ }
78
+ const nice = opts.lowPriority && !isWin;
79
+ let child: ChildProcess;
80
+ try {
81
+ child = spawn(nice ? "nice" : "git", nice ? ["-n", "10", "--", "git", ...args] : [...args], {
82
+ cwd: opts.cwd, windowsHide: true, detached: !isWin, stdio: ["ignore", "pipe", "ignore"],
83
+ });
84
+ } catch (e) {
85
+ fail(e);
86
+ return;
87
+ }
88
+ if (opts.lowPriority && isWin && child.pid !== undefined) lowerPriority(child.pid);
89
+ const chunks: Buffer[] = [];
90
+ let bytes = 0;
91
+ let settled = false;
92
+ const settle = (error?: unknown, stdout?: string) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ clearTimeout(timer);
96
+ opts.signal.removeEventListener("abort", onAbort);
97
+ if (error === undefined) ok(stdout ?? "");
98
+ else fail(error);
99
+ };
100
+ const stop = (why: string) => {
101
+ if (settled) return;
102
+ killGitTree(child);
103
+ settle(new Error(`git ${why}`));
104
+ };
105
+ const onAbort = () => stop("aborted");
106
+ const timer = setTimeout(() => stop(`timed out after ${opts.timeoutMs} ms`), opts.timeoutMs);
107
+ opts.signal.addEventListener("abort", onAbort, { once: true });
108
+ child.stdout?.on("data", (chunk: Buffer) => {
109
+ bytes += chunk.length;
110
+ if (bytes > opts.maxBuffer) stop(`stdout exceeded ${opts.maxBuffer} bytes`);
111
+ else chunks.push(chunk);
112
+ });
113
+ child.on("error", (e) => settle(e));
114
+ child.on("close", (code, signal) => {
115
+ if (code === 0) settle(undefined, Buffer.concat(chunks).toString("utf8"));
116
+ else settle(new Error(`git exited with ${code === null ? signal : `code ${code}`}`));
117
+ });
118
+ });
119
+
120
+ /**
121
+ * QA-2.1-2: above this many paths to digest, a snapshot's per-file digests are "unavailable".
122
+ * QA-2.1-14: the change set then widens to every dispatch-listed path (delta), so this bounds the
123
+ * gate's reads, not attribution.
124
+ */
125
+ export const MAX_DIGEST_FILES = 500;
126
+ /** QA-2.1-2: above this many bytes of regular files to digest, per-file digests are "unavailable". */
127
+ export const MAX_DIGEST_BYTES = 64 * 1024 * 1024;
128
+
129
+ export interface SnapshotOptions {
130
+ /**
131
+ * The absolute paths to digest. Default: the snapshot's own listed (dirty or untracked) paths,
132
+ * as at dispatch. A gate passes the dispatch snapshot's paths.
133
+ */
134
+ digestPaths?: readonly string[];
135
+ /** Default MAX_DIGEST_FILES. */
136
+ maxDigestFiles?: number;
137
+ /** Default MAX_DIGEST_BYTES. */
138
+ maxDigestBytes?: number;
139
+ /**
140
+ * QA-3.1-8: run the snapshot's git processes at below-normal priority. The wiring passes
141
+ * VerifyBudget.lowPriority (default true). Default false.
142
+ */
143
+ lowPriority?: boolean;
144
+ /** The git process seam (tests). Default execGit. */
145
+ git?: SnapshotGit;
146
+ }
147
+
148
+ function errorCode(err: unknown): unknown {
149
+ return err && typeof err === "object" && "code" in err ? (err as { code: unknown }).code : undefined;
150
+ }
151
+
152
+ /**
153
+ * QA-2.1-2: one content identity per path, bounded by count and bytes (sizes are summed from lstat
154
+ * before anything is read). Reads only files, spawns nothing, and honours `signal`. Anything it
155
+ * cannot prove (a directory, an unreadable path, the bounds) makes the whole map "unavailable".
156
+ */
157
+ async function digestPaths(
158
+ paths: readonly string[],
159
+ signal: AbortSignal,
160
+ maxFiles: number,
161
+ maxBytes: number,
162
+ ): Promise<ReadonlyMap<string, string> | "unavailable"> {
163
+ if (paths.length > maxFiles) return "unavailable";
164
+ try {
165
+ const kinds: [string, "absent" | "link" | "file"][] = [];
166
+ let bytes = 0;
167
+ for (const path of paths) {
168
+ let stat;
169
+ try {
170
+ stat = await lstat(path);
171
+ } catch (err) {
172
+ const code = errorCode(err);
173
+ if (code !== "ENOENT" && code !== "ENOTDIR") return "unavailable";
174
+ kinds.push([path, "absent"]);
175
+ continue;
176
+ }
177
+ if (stat.isSymbolicLink()) {
178
+ kinds.push([path, "link"]);
179
+ } else if (stat.isFile()) {
180
+ bytes += stat.size;
181
+ if (bytes > maxBytes) return "unavailable";
182
+ kinds.push([path, "file"]);
183
+ } else {
184
+ return "unavailable"; // A directory (nested repository) has no content identity here.
185
+ }
186
+ }
187
+ const digests = new Map<string, string>();
188
+ for (const [path, kind] of kinds) {
189
+ if (signal.aborted) return "unavailable";
190
+ if (kind === "absent") digests.set(path, ABSENT_DIGEST);
191
+ else if (kind === "link") digests.set(path, LINK_DIGEST_PREFIX + await readlink(path));
192
+ else digests.set(path, FILE_DIGEST_PREFIX + createHash("sha256").update(await readFile(path, { signal })).digest("hex"));
193
+ }
194
+ return digests;
195
+ } catch {
196
+ // Deleted or replaced between lstat and read, unreadable, or aborted: no per-file proof.
197
+ return "unavailable";
198
+ }
199
+ }
200
+
201
+ export async function snapshotTree(cwd: string, signal: AbortSignal, options: SnapshotOptions = {}): Promise<TreeSnapshot | undefined> {
9
202
  let gitCwd = cwd;
10
- const git = (args: string[]) => new Promise<string>((ok, fail) => {
11
- execFile("git", ["--no-pager", ...args], {
12
- cwd: gitCwd, signal, timeout: 10000, maxBuffer: 32 * 1024 * 1024, windowsHide: true,
13
- }, (error, stdout) => error ? fail(error) : ok(stdout));
203
+ const run = options.git ?? execGit;
204
+ const lowPriority = options.lowPriority === true;
205
+ const git = (args: string[]) => run(["--no-pager", ...args], {
206
+ cwd: gitCwd, signal, timeoutMs: SNAPSHOT_GIT_TIMEOUT_MS, maxBuffer: SNAPSHOT_GIT_MAX_BUFFER, lowPriority,
14
207
  });
15
208
  try {
16
209
  const root = (await git(["rev-parse", "--show-toplevel"])).trim();
@@ -24,8 +217,13 @@ export async function snapshotTree(cwd: string, signal: AbortSignal): Promise<Tr
24
217
  for (let i = 0; i < records.length; i++) {
25
218
  const record = records[i];
26
219
  if (!record) continue;
27
- files.push({ path: resolve(root, record.slice(3)), status: record.slice(0, 2) });
28
- if (/[RC]/.test(record.slice(0, 2))) i++; // -z rename destination precedes source.
220
+ const file: ChangedFile = { path: resolve(root, record.slice(3)), status: record.slice(0, 2) };
221
+ // -z emits a rename/copy as `XY dest\0source\0`; keep the source.
222
+ if (/[RC]/.test(file.status)) {
223
+ const source = records[++i];
224
+ if (source) file.previousPath = resolve(root, source);
225
+ }
226
+ files.push(file);
29
227
  }
30
228
  const hash = createHash("sha256").update(status);
31
229
  hash.update(await git(["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"]));
@@ -43,8 +241,14 @@ export async function snapshotTree(cwd: string, signal: AbortSignal): Promise<Tr
43
241
  else if (stat.isFile()) hash.update(await readFile(absolute, { signal }));
44
242
  else return undefined;
45
243
  }
244
+ const digests = await digestPaths(
245
+ options.digestPaths ?? files.map(f => f.path),
246
+ signal,
247
+ options.maxDigestFiles ?? MAX_DIGEST_FILES,
248
+ options.maxDigestBytes ?? MAX_DIGEST_BYTES,
249
+ );
46
250
  if (signal.aborted) return undefined;
47
- return { cwd: await realpath(cwd), head, fingerprint: hash.digest("hex"), dirty: files.length > 0, files };
251
+ return { cwd: await realpath(cwd), root: await realpath(root), head, fingerprint: hash.digest("hex"), dirty: files.length > 0, files, digests };
48
252
  } catch {
49
253
  // Not a Git checkout, unreadable file, timeout or concurrent deletion: no baseline.
50
254
  return undefined;
@@ -1,6 +1,11 @@
1
1
  // src/verify/types.ts
2
2
  // Pure types for the deterministic verifier. No runtime code.
3
3
 
4
+ // Type-only: runner.ts and reference.ts import their seam types from this module, and a type cycle
5
+ // has no runtime effect.
6
+ import type { ChangedPath, RunResult, S6Code, ScopedSpec } from "./runner";
7
+ import type { DispatchReference, InexactReason } from "./reference";
8
+
4
9
  export type VerifyMethod = "deterministic" | "checker" | "none";
5
10
 
6
11
  export interface Verdict {
@@ -16,6 +21,11 @@ export interface Verdict {
16
21
  evidence?: string;
17
22
  /** true when nothing was actually verified (SKIPPED != PASS) */
18
23
  skipped?: boolean;
24
+ /**
25
+ * testsPass attribution (deterministic.ts header, T5): the ids every exact-recheck judgement of
26
+ * this verdict classified, concatenated across testsPass checks. Absent when no check classified.
27
+ */
28
+ failures?: FailureClassification;
19
29
  }
20
30
 
21
31
  export interface ExecResult {
@@ -25,8 +35,25 @@ export interface ExecResult {
25
35
  timedOut?: boolean;
26
36
  }
27
37
 
38
+ /** Options shared by every verification process seam (shell string or argv). */
39
+ export interface ExecOptions {
40
+ cwd?: string;
41
+ timeoutMs?: number;
42
+ /** Aborting kills the whole process tree; an already-aborted signal never spawns. */
43
+ signal?: AbortSignal;
44
+ /** Run the process (and its descendants) at below-normal OS priority. */
45
+ lowPriority?: boolean;
46
+ /** Merged over process.env; never replaces it. */
47
+ env?: Record<string, string>;
48
+ }
49
+
28
50
  export interface ExecSeam {
29
- (command: string, opts?: { cwd?: string; timeoutMs?: number }): Promise<ExecResult>;
51
+ (command: string, opts?: ExecOptions): Promise<ExecResult>;
52
+ }
53
+
54
+ /** Spawn `file` with `args` and no shell: arguments reach the child byte-for-byte. */
55
+ export interface ArgvSeam {
56
+ (file: string, args: readonly string[], opts?: ExecOptions): Promise<ExecResult>;
30
57
  }
31
58
 
32
59
  export interface FsSeam {
@@ -39,12 +66,39 @@ export interface MutexRegistry {
39
66
  }
40
67
 
41
68
  export interface DeterministicDeps {
42
- /** Bound to the original dispatch, not looked up using the after-state diff. */
43
- testBaseline?: (command: string) => Promise<import("./baseline").TestBaseline | undefined>;
69
+ /**
70
+ * S5 (deterministic.ts header, T2 P2-P7): plans, runs and rechecks one testsPass request. Called
71
+ * outside `mutex`. Absent -> testsPass is unverifiable, never a run (G5).
72
+ */
73
+ testsPass?: TestsPassHook;
74
+ /** S3/S4 per-check scopes (T8): one slot hold per check, low priority, deadline-bound. */
75
+ openScope?: import("./deterministic").OpenCheckScope;
76
+ /** Shell-free process seam (git searches, scoped specs). */
77
+ argv?: ArgvSeam;
78
+ /**
79
+ * The producer's changed files with tree-snapshot statuses and rename sources, or "unavailable"
80
+ * without a change baseline (section 1.5-6). Default "unavailable".
81
+ */
82
+ changedFiles?: readonly ChangedPath[] | "unavailable";
83
+ /**
84
+ * The settled dispatch reference (T2 P0). Default: "disabled" when `budget.failureRecheck` is
85
+ * off, else none ("the dispatch was not tracked").
86
+ */
87
+ reference?: ReferenceState;
88
+ /** The validated budget (resolveVerifyBudget). Absent: testScope "affected", failureRecheck on. */
89
+ budget?: import("../router/config").VerifyBudget;
90
+ /** lintClean scoping (T8); default planScopedLint. Used only with `openScope`. */
91
+ planLint?: typeof import("./runner").planScopedLint;
92
+ /**
93
+ * The gate's deadline (T3). Absent: each testsPass check runs under its own deadline of
94
+ * `budget.gateBudgetMs` (else `timeoutMs`), disposed when the check ends.
95
+ */
96
+ deadline?: Deadline;
44
97
  /** Preserve completed failures if an outer gate budget expires later. */
45
98
  onFailure?: (reason: string) => void;
46
99
  exec: ExecSeam;
47
- fs: FsSeam;
100
+ /** Any FsSeam; lintClean scoping also uses the optional PlannerFs members when present. */
101
+ fs: import("./runner").PlannerFs;
48
102
  cwd: string;
49
103
  mutex?: MutexRegistry;
50
104
  /** per-check timeout in ms; default 120000 */
@@ -57,3 +111,246 @@ export interface DeterministicDeps {
57
111
  lintCommand?: string;
58
112
  };
59
113
  }
114
+
115
+ // ---------------------------------------------------------------------------------------------
116
+ // testsPass pipeline contract (plan Phase 2.1, task 2.1.1)
117
+ //
118
+ // The pipeline, the verdict algebra and its truth table are specified in the header of the
119
+ // "testsPass pipeline" section of src/verify/deterministic.ts. Phase 2.2 (batch.ts) and Phase 2.4
120
+ // (pending.ts) code against these types only, never against 2.1's internals.
121
+ // ---------------------------------------------------------------------------------------------
122
+
123
+ /**
124
+ * One deadline per synchronous verification (plan section 1.5-13): a `VERIFY:required` gate in
125
+ * either call path (`delegate` tool, native `task`), or one `router_verify` call. The owner creates
126
+ * it with `gateBudgetMs` next to the AbortController it aborts when its `withTimeout` rejects. Every
127
+ * wait and command inside the verification (slot wait, test search, scoped run, GC, materialize,
128
+ * recheck run, batch wait) is bounded by `bound(itsOwnBudget)` and receives `signal`.
129
+ */
130
+ export interface Deadline {
131
+ /** The budget the deadline was created with (gateBudgetMs). For messages only. */
132
+ readonly budgetMs: number;
133
+ /** Milliseconds left, clamped to >= 0. 0 once the deadline passed or `signal` aborted. */
134
+ remaining(): number;
135
+ /** min(ownBudgetMs, remaining()): the bound of one step. `ownBudgetMs` may be Infinity. */
136
+ bound(ownBudgetMs: number): number;
137
+ /**
138
+ * Aborts when the deadline passes or the owner aborts the verification. Every slot wait, spawn,
139
+ * materialize and GC receives it, so an abort kills the running process tree and nothing is
140
+ * spawned afterwards (an already-aborted signal never spawns: ExecOptions.signal).
141
+ */
142
+ readonly signal: AbortSignal;
143
+ }
144
+
145
+ /**
146
+ * The dispatch reference as the gate sees it (S2, plan sections 1.5-7 and 1.5-14). Produced by
147
+ * `prepareVerification` (2.1.3) and stored by the pending registry (2.4.1) as a promise.
148
+ */
149
+ export type ReferenceState =
150
+ /** A git-only capture that resolved with no overlapping edit observed while it was in flight. */
151
+ | { readonly kind: "captured"; readonly reference: DispatchReference }
152
+ /** `failureRecheck: false` (or the deprecated `testBaseline: false`): nothing was captured. */
153
+ | { readonly kind: "disabled" }
154
+ /**
155
+ * No usable capture: not a git repository, capture failed or exceeded `baselineTimeoutMs`, an
156
+ * edit was observed in an overlapping directory before it resolved, or the dispatch was not
157
+ * tracked. `reason` is a short stable phrase for the verdict text.
158
+ */
159
+ | { readonly kind: "none"; readonly reason: string };
160
+
161
+ /**
162
+ * What the scoped test run of ONE request produced (S1, S3, S4, S6), as judgeScoped consumes it.
163
+ * `no-affected` and `unverifiable` come from planning (planScopedRun, detectRunner); every other
164
+ * kind comes from a ScopedExecutor. A batch (2.2) returns one per request.
165
+ */
166
+ export type ScopedOutcome =
167
+ /** planScopedRun returned NoAffected (section 1.5-6, runner.ts M.2): nothing spawned, pass with the note. */
168
+ | { readonly kind: "no-affected"; readonly note: string }
169
+ /** S6: scoping is impossible. Nothing spawned; the router never falls back to a full suite. */
170
+ | { readonly kind: "unverifiable"; readonly code: S6Code; readonly reason: string }
171
+ /**
172
+ * The slot (S3) was not obtained within min(slotWaitMs, remaining). Nothing spawned.
173
+ * `deadlineCut`: the wait ended because the deadline passed or aborted, not at slotWaitMs.
174
+ */
175
+ | { readonly kind: "slot-busy"; readonly waitedMs: number; readonly deadlineCut: boolean }
176
+ /**
177
+ * The command exited on its own before its bound; `result` is readResult's parse (or, for
178
+ * testScope "full", the observeTests-derived result; source "text").
179
+ */
180
+ | {
181
+ readonly kind: "ran";
182
+ readonly result: RunResult;
183
+ readonly exitCode: number;
184
+ /** The spec that ran; undefined for testScope "full" (a resolved shell command, not a spec). */
185
+ readonly spec?: ScopedSpec;
186
+ /** Planner notes, slot notes (e.g. "slot reclaimed during the run") and readResult's note. */
187
+ readonly notes: readonly string[];
188
+ }
189
+ /**
190
+ * The command hit its own bound min(timeoutMs, remaining) and its process tree was killed.
191
+ * `result` is readResult's parse of what was written (always called: it deletes the report).
192
+ */
193
+ | { readonly kind: "timed-out"; readonly boundMs: number; readonly result?: RunResult }
194
+ /**
195
+ * The deadline passed or the owner aborted: the tree was killed, or nothing was spawned.
196
+ * `reason` is a stable phrase such as "gate budget exhausted during the scoped run".
197
+ */
198
+ | { readonly kind: "aborted"; readonly reason: string }
199
+ /** The executor itself failed (spawn threw, slot I/O error). Fail-closed: never a pass. */
200
+ | { readonly kind: "error"; readonly reason: string };
201
+
202
+ /** Why a recheck at the dispatch reference cannot be compared (never "pre-existing"). */
203
+ export type RecheckUnusableCause =
204
+ /** ReferenceState "none": "no reference: pre-existing failures cannot be told apart" (1.5-14). */
205
+ | "no-reference"
206
+ /** materialize returned ok:false (aborted, worktree-add-failed, unsafe-path, error). */
207
+ | "materialize-failed"
208
+ /** The stash commit is gone (commit-missing) or the worktree vanished during the rerun (QA-1.5-4). */
209
+ | "reference-vanished"
210
+ /** unreproduced holds an ignored input outside the inert allowlist, e.g. .env (QA-1.5-7). */
211
+ | "unreproduced-inputs"
212
+ /** planRerun or detectRunner returned S6 (node-not-found, tmpdir-in-repo, argv-too-long, ...). */
213
+ | "rerun-unplannable"
214
+ /** The rerun reported complete === false (QA-1.3-17). */
215
+ | "incomplete"
216
+ /** The rerun reported collectionError === true: setup/collection failure at the reference (1.5-8). */
217
+ | "collection-error"
218
+ /** The rerun ran no tests: total === 0 (QA-1.3-17). */
219
+ | "no-tests"
220
+ /** The runner cannot pin sources to the reference (pytest: editable installs import the live tree). */
221
+ | "runner-unsupported"
222
+ /** The rerun's executor failed (spawn threw, I/O error). */
223
+ | "error";
224
+
225
+ /**
226
+ * The S2 failure-only recheck at the dispatch reference, as judgeScoped consumes it. It carries
227
+ * reference-side FACTS only; judgeScoped classifies each failing id (FailureClassification), so one
228
+ * recheck can be shared by several requests of a batch (2.2) with the same reference.
229
+ *
230
+ * File keys below are id-space keys: the file part of a RunResult id (cwd-relative, "/"
231
+ * separators; the part before " > " or "::", or the whole bare-file id). The rerun spec's cwd is
232
+ * the live spec's cwd mapped into the reference worktree, so both runs share one key space.
233
+ */
234
+ export type RecheckOutcome =
235
+ /** An exact reference with inert `unreproduced`, rerun comparably where anything was rerun. */
236
+ | {
237
+ readonly kind: "exact";
238
+ /**
239
+ * The rerun at the reference: complete, no collection error, total > 0 (otherwise the
240
+ * outcome is "unusable"). undefined when every failing file is in `absentFiles`.
241
+ */
242
+ readonly result: RunResult | undefined;
243
+ /** File keys of the failing files that ran at the reference. */
244
+ readonly ranFiles: readonly string[];
245
+ /** File keys of failing files that do not exist at the exact reference: added since dispatch. */
246
+ readonly absentFiles: readonly string[];
247
+ readonly notes: readonly string[];
248
+ }
249
+ /** The reference cannot be rebuilt exactly (1.5-7, reference.ts section 2). Never excuses, never proves. */
250
+ | { readonly kind: "approximate"; readonly inexactReasons: readonly InexactReason[] }
251
+ /** The reference exists or was expected, but its run cannot be compared. Never excuses, never proves. */
252
+ | { readonly kind: "unusable"; readonly cause: RecheckUnusableCause; readonly reason: string }
253
+ /** `failureRecheck: false`: no reference, no recheck; any scoped failure is unverifiable (section 1.4). */
254
+ | { readonly kind: "disabled" }
255
+ /** The rerun hit min(recheckTimeoutMs, remaining) and its tree was killed. */
256
+ | { readonly kind: "timed-out"; readonly boundMs: number }
257
+ /** Less than the recheck threshold remained: nothing materialized or spawned (section 1.5-13). */
258
+ | { readonly kind: "skipped-deadline"; readonly remainingMs: number };
259
+
260
+ /** judgeScoped's per-id attribution of the scoped failures (ids as in RunResult.failingIds). */
261
+ export interface FailureClassification {
262
+ /** Proven introduced: failing now, and passing, collecting or absent at the exact reference. */
263
+ readonly introduced: readonly string[];
264
+ /** Proven pre-existing: the same id fails at the exact reference. */
265
+ readonly preexisting: readonly string[];
266
+ /** Neither could be proven (file not rerun, text ids that cannot be compared). */
267
+ readonly unknown: readonly string[];
268
+ }
269
+
270
+ /**
271
+ * The result of one testsPass check. Structurally a deterministic.ts CheckResult:
272
+ * ok -> pass; !ok && unverifiable -> caveat (rejected only under strictUnverifiable, by gate.ts);
273
+ * !ok && !unverifiable -> fail (onFailure, escalation).
274
+ */
275
+ export interface TestsPassJudgement {
276
+ readonly ok: boolean;
277
+ readonly unverifiable: boolean;
278
+ /** Set when !ok: the rejection reason, or the caveat text of an unverifiable result. */
279
+ readonly reason?: string;
280
+ /** Set on a pass that must not read as a green suite, or with informative context. */
281
+ readonly note?: string;
282
+ readonly evidence?: string;
283
+ /** Set whenever an exact recheck was used to classify failures. */
284
+ readonly failures?: FailureClassification;
285
+ }
286
+
287
+ /**
288
+ * S3 + S4 + run + readResult for one spec: waits for the slot (bounded by
289
+ * deadline.bound(slotWaitMs)), spawns spec.file/spec.args through the ArgvSeam (never a shell) at
290
+ * low priority with deadline.signal and timeoutMs = deadline.bound(check timeout), and ALWAYS calls
291
+ * readResult (even after a timeout, an abort or a failed spawn). Never rejects.
292
+ */
293
+ export type ScopedExecutor = (spec: ScopedSpec, deadline: Deadline) => Promise<ScopedOutcome>;
294
+
295
+ /**
296
+ * S2 for the failing files of one scoped run (absolute live paths, RunResult.failingFiles):
297
+ * skip below the deadline threshold, GC stale references, materialize INSIDE the slot hold, check
298
+ * exactness and `unreproduced`, rerun only the failing files that exist at the reference
299
+ * (planRerun, same entry as the live tree), readResult, dispose. Never rejects.
300
+ */
301
+ export type Rechecker = (
302
+ reference: DispatchReference,
303
+ failingFiles: readonly string[],
304
+ deadline: Deadline,
305
+ ) => Promise<RecheckOutcome>;
306
+
307
+ /**
308
+ * One S3 slot hold for one gate check or one batch (QA-1.4-18: acquire once, hold it across the
309
+ * recheck, never acquire a nested slot in the same process). The hold is taken by the first
310
+ * `execute` that needs to spawn; if that attempt is busy, every later call reports the same
311
+ * outcome without waiting again. References are materialized and disposed inside the hold.
312
+ */
313
+ export interface VerificationScope {
314
+ readonly execute: ScopedExecutor;
315
+ /** A Rechecker for one check command and live cwd (it needs detectRunner(command, cwd)), sharing this hold. */
316
+ rechecker(command: string, cwd: string): Rechecker;
317
+ /** Waits for pending reference disposals, then releases the hold. Idempotent; never rejects. */
318
+ close(): Promise<void>;
319
+ }
320
+
321
+ /** Opens a VerificationScope. `meta` is written into the slot's lock file (slot.ts SlotMeta). */
322
+ export type OpenVerificationScope = (meta: { readonly cwd: string; readonly command: string }) => VerificationScope;
323
+
324
+ /** One testsPass verification request: everything the S5 hook needs to plan, run and recheck it. */
325
+ export interface TestsPassRequest {
326
+ /** resolveRepoCommand's result; it already passed isCommandAllowed. */
327
+ readonly command: string;
328
+ /** Absolute check cwd. */
329
+ readonly cwd: string;
330
+ /** "full" runs the resolved command as written (runShell), still under S2-S5 (section 1.4). */
331
+ readonly testScope: "affected" | "full";
332
+ /** The producer's changed files with tree-snapshot statuses and rename sources; "unavailable" without attribution. */
333
+ readonly changedFiles: readonly ChangedPath[] | "unavailable";
334
+ readonly reference: ReferenceState;
335
+ readonly deadline: Deadline;
336
+ }
337
+
338
+ /** What the S5 hook returns for one request; judgeScoped turns it into the check result. */
339
+ export interface TestsPassRun {
340
+ readonly scoped: ScopedOutcome;
341
+ /** undefined when no recheck was attempted (green, planning outcomes, slot busy, timeout, abort, error). */
342
+ readonly recheck: RecheckOutcome | undefined;
343
+ }
344
+
345
+ /**
346
+ * The S5 seam. 2.1.2 implements it as a direct call (plan, scope, execute, recheck); 2.2.3 swaps in
347
+ * the batch coordinator behind this exact type. Never rejects.
348
+ */
349
+ export type TestsPassHook = (request: TestsPassRequest) => Promise<TestsPassRun>;
350
+
351
+ /**
352
+ * The verdict algebra (deterministic.ts, "testsPass pipeline" header, truth table). Pure and total:
353
+ * every (scoped, recheck) pair maps to exactly one judgement, and no path yields ok for a failure
354
+ * that is not proven pre-existing at an exact reference with a complete scoped inventory.
355
+ */
356
+ export type JudgeScoped = (scoped: ScopedOutcome, recheck: RecheckOutcome | undefined) => TestsPassJudgement;