opencode-model-router 1.13.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.
@@ -6,11 +6,12 @@ import {
6
6
  renameSync,
7
7
  writeFileSync,
8
8
  } from "node:fs";
9
- import { homedir } from "node:os";
9
+ import { availableParallelism, homedir } from "node:os";
10
10
  import { dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { parseJsonc } from "./jsonc";
13
13
  import type { DelegateInstructionsPolicy } from "./instructions";
14
+ import type { PluginLogger } from "./logger";
14
15
 
15
16
  /**
16
17
  * Filename of the optional user overrides file (global and project copies share
@@ -128,14 +129,44 @@ export interface EnforcementConfig {
128
129
  delegateTimeoutMs?: number;
129
130
  /** Reject unavailable verification. Default false; never escalates it. */
130
131
  strictUnverifiable?: boolean;
131
- /** Capture/cache conservative dispatch-time test baselines. Default true. */
132
+ /** Deprecated: `false` maps to `failureRecheck: false` (explicit `failureRecheck` wins). No default. */
132
133
  testBaseline?: boolean;
133
- /** Independent capture ceiling, including fingerprinting. Default 60000 ms. */
134
+ /** Bounds the whole git-only reference capture, in ms. Default 15000. */
134
135
  baselineTimeoutMs?: number;
135
136
  /** Override tier ceilings: fast 60000 / medium 180000 / heavy 600000 ms. */
136
137
  graderTimeoutMs?: number;
137
- /** Ceiling for the whole acceptance gate, in ms. Default 90000. */
138
- gateBudgetMs?: number };
138
+ /** Deadline for every synchronous verification, in ms. Default 90000. */
139
+ gateBudgetMs?: number;
140
+ /** Which tests a verification runs. Default "affected". */
141
+ testScope?: "affected" | "full";
142
+ /** Worker cap passed to runners that support one (integer >= 1). Default 2. */
143
+ maxWorkers?: number;
144
+ /** Run verification commands at below-normal priority. Default true. */
145
+ lowPriority?: boolean;
146
+ /** Machine-wide verification slots (integer >= 1). Default max(1, floor(cores / 8)). */
147
+ maxConcurrentVerifications?: number;
148
+ /** Mode for dispatches without a `VERIFY:` directive. Default "deferred". */
149
+ defaultVerify?: "deferred" | "required";
150
+ /** Longest wait for the reference capture before the producer starts, in ms (0 = never wait). Default 5000. */
151
+ captureWaitMs?: number;
152
+ /** Also run deferred verifications in the background. Default false. */
153
+ background?: boolean;
154
+ /** How long an unverified delegation stays verifiable, in ms (integer >= 1). Default 3600000. */
155
+ pendingTtlMs?: number;
156
+ /**
157
+ * Maximum wait for a verification slot, in ms (0 = no wait). Default 60000.
158
+ *
159
+ * Residual (QA-1.4-21): a lock whose owner is not provably dead is reclaimed
160
+ * only by a caller that waits or stays alive through ~8 s of observation, so
161
+ * a very short wait may give up on a slot that a longer one would reclaim.
162
+ */
163
+ slotWaitMs?: number;
164
+ /** Coalescing window, in ms (0 = no batching). Default 2000. */
165
+ batchWindowMs?: number;
166
+ /** Capture a reference and recheck scoped failures against it. Default true. */
167
+ failureRecheck?: boolean;
168
+ /** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
169
+ recheckTimeoutMs?: number };
139
170
  escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
140
171
  proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
141
172
  }
@@ -673,6 +704,12 @@ function validateTaskPatterns(obj: Record<string, unknown>): void {
673
704
  }
674
705
  }
675
706
 
707
+ /**
708
+ * Largest delay `setTimeout` honours (2^31 - 1 ms). Node and bun clamp any
709
+ * larger delay to 1 ms, turning a "huge" budget into an immediate timeout.
710
+ */
711
+ const MAX_TIMER_MS = 2_147_483_647;
712
+
676
713
  function validateEnforcement(obj: Record<string, unknown>): void {
677
714
  // Validate enforcement if present (optional — absent means no enforcement)
678
715
  if (obj.enforcement !== undefined) {
@@ -694,12 +731,20 @@ function validateEnforcement(obj: Record<string, unknown>): void {
694
731
  );
695
732
  }
696
733
  }
697
- if (
698
- enforcement.verify !== undefined &&
699
- typeof enforcement.verify === "object" &&
700
- enforcement.verify !== null
701
- ) {
734
+ if (enforcement.verify !== undefined) {
735
+ // A non-object (including `null`) would skip every check below, and an
736
+ // override `verify: null` would erase the whole bundled block on merge.
737
+ if (!isPlainObject(enforcement.verify)) {
738
+ throw new Error("tiers.json: enforcement.verify must be an object");
739
+ }
702
740
  const verify = enforcement.verify as Record<string, unknown>;
741
+ // An own `__proto__`/`constructor`/`prototype` key is never read, but a
742
+ // later `Object.assign` copy would reparent through it; reject it here.
743
+ for (const key of ["__proto__", "constructor", "prototype"] as const) {
744
+ if (Object.prototype.hasOwnProperty.call(verify, key)) {
745
+ throw new Error(`tiers.json: enforcement.verify must not contain the key "${key}"`);
746
+ }
747
+ }
703
748
  if (verify.testBaseline !== undefined && typeof verify.testBaseline !== "boolean") {
704
749
  throw new Error("tiers.json: enforcement.verify.testBaseline must be a boolean");
705
750
  }
@@ -744,16 +789,66 @@ function validateEnforcement(obj: Record<string, unknown>): void {
744
789
  "graderTimeoutMs",
745
790
  "gateBudgetMs",
746
791
  "baselineTimeoutMs",
792
+ "pendingTtlMs",
793
+ "recheckTimeoutMs",
747
794
  ] as const) {
748
795
  const value = verify[key];
749
796
  if (value !== undefined) {
750
- if (!Number.isInteger(value) || (value as number) < 1) {
797
+ if (
798
+ !Number.isInteger(value) ||
799
+ (value as number) < 1 ||
800
+ (value as number) > MAX_TIMER_MS
801
+ ) {
751
802
  throw new Error(
752
- `tiers.json: enforcement.verify.${key} must be an integer >= 1 (milliseconds)`,
803
+ `tiers.json: enforcement.verify.${key} must be an integer >= 1 and <= ${MAX_TIMER_MS} (milliseconds)`,
753
804
  );
754
805
  }
755
806
  }
756
807
  }
808
+ // Waits/windows where 0 is meaningful ("no wait", "no batching").
809
+ for (const key of ["captureWaitMs", "slotWaitMs", "batchWindowMs"] as const) {
810
+ const value = verify[key];
811
+ if (
812
+ value !== undefined &&
813
+ (!Number.isInteger(value) || (value as number) < 0 || (value as number) > MAX_TIMER_MS)
814
+ ) {
815
+ throw new Error(
816
+ `tiers.json: enforcement.verify.${key} must be an integer >= 0 and <= ${MAX_TIMER_MS} (milliseconds)`,
817
+ );
818
+ }
819
+ }
820
+ // Safe integers only: `1e21` passes `Number.isInteger` but stringifies to
821
+ // `1e+21`, which no test runner parses as a worker count.
822
+ for (const key of ["maxWorkers", "maxConcurrentVerifications"] as const) {
823
+ const value = verify[key];
824
+ if (value !== undefined && (!Number.isSafeInteger(value) || (value as number) < 1)) {
825
+ throw new Error(`tiers.json: enforcement.verify.${key} must be an integer >= 1`);
826
+ }
827
+ }
828
+ for (const key of ["lowPriority", "background", "failureRecheck"] as const) {
829
+ const value = verify[key];
830
+ if (value !== undefined && typeof value !== "boolean") {
831
+ throw new Error(`tiers.json: enforcement.verify.${key} must be a boolean`);
832
+ }
833
+ }
834
+ if (
835
+ verify.testScope !== undefined &&
836
+ verify.testScope !== "affected" &&
837
+ verify.testScope !== "full"
838
+ ) {
839
+ throw new Error(
840
+ 'tiers.json: enforcement.verify.testScope must be "affected" or "full"',
841
+ );
842
+ }
843
+ if (
844
+ verify.defaultVerify !== undefined &&
845
+ verify.defaultVerify !== "deferred" &&
846
+ verify.defaultVerify !== "required"
847
+ ) {
848
+ throw new Error(
849
+ 'tiers.json: enforcement.verify.defaultVerify must be "deferred" or "required"',
850
+ );
851
+ }
757
852
  if (
758
853
  verify.requireExplicitDoD !== undefined &&
759
854
  typeof verify.requireExplicitDoD !== "boolean"
@@ -1169,3 +1264,107 @@ export function normalizeEnforcement(
1169
1264
  ): { mode: "off" | "advisory" | "enforced" } {
1170
1265
  return { mode: e?.mode ?? "advisory" };
1171
1266
  }
1267
+
1268
+ /** Fully defaulted verification budget (§1.4). */
1269
+ export interface VerifyBudget {
1270
+ testScope: "affected" | "full";
1271
+ maxWorkers: number;
1272
+ lowPriority: boolean;
1273
+ maxConcurrentVerifications: number;
1274
+ defaultVerify: "deferred" | "required";
1275
+ captureWaitMs: number;
1276
+ background: boolean;
1277
+ pendingTtlMs: number;
1278
+ slotWaitMs: number;
1279
+ batchWindowMs: number;
1280
+ failureRecheck: boolean;
1281
+ recheckTimeoutMs: number;
1282
+ baselineTimeoutMs: number;
1283
+ gateBudgetMs: number;
1284
+ }
1285
+
1286
+ export interface ResolveVerifyBudgetOptions {
1287
+ /** Core count; defaults to `os.availableParallelism()`. Injected by tests. */
1288
+ cores?: number;
1289
+ }
1290
+
1291
+ let warnedTestBaselineDeprecated = false;
1292
+
1293
+ /** Test-only: re-arm the once-per-process `testBaseline` deprecation warning. */
1294
+ export function resetVerifyBudgetWarnings(): void {
1295
+ warnedTestBaselineDeprecated = false;
1296
+ }
1297
+
1298
+ /**
1299
+ * Logs the once-per-process deprecation warning for `enforcement.verify.testBaseline`
1300
+ * (any value) through the plugin logger. Call once after every `loadConfig()`.
1301
+ * Kept apart from `resolveVerifyBudget` so that function stays pure.
1302
+ */
1303
+ export function warnDeprecatedVerifyKeys(
1304
+ cfg: RouterConfig | undefined,
1305
+ logger: PluginLogger,
1306
+ ): void {
1307
+ const v = cfg?.enforcement?.verify;
1308
+ if (
1309
+ warnedTestBaselineDeprecated ||
1310
+ !isPlainObject(v) ||
1311
+ !Object.prototype.hasOwnProperty.call(v, "testBaseline") ||
1312
+ v.testBaseline === undefined
1313
+ ) {
1314
+ return;
1315
+ }
1316
+ warnedTestBaselineDeprecated = true;
1317
+ logger.warn(
1318
+ "enforcement.verify.testBaseline is deprecated; use enforcement.verify.failureRecheck",
1319
+ { key: "testBaseline" },
1320
+ );
1321
+ }
1322
+
1323
+ /**
1324
+ * The single place verification-budget defaults are applied. Pure and
1325
+ * synchronous: no module state, no logging (see `warnDeprecatedVerifyKeys`).
1326
+ * Reads own properties only, so a value inherited through a prototype is never
1327
+ * applied. A non-finite or `< 1` core count (including `Infinity`) counts as 1.
1328
+ */
1329
+ export function resolveVerifyBudget(
1330
+ cfg: RouterConfig | undefined,
1331
+ opts: ResolveVerifyBudgetOptions = {},
1332
+ ): VerifyBudget {
1333
+ const raw = cfg?.enforcement?.verify;
1334
+ const v: Record<string, unknown> = isPlainObject(raw) ? raw : {};
1335
+ const own = <T>(key: string): T | undefined =>
1336
+ Object.prototype.hasOwnProperty.call(v, key) && v[key] !== undefined
1337
+ ? (v[key] as T)
1338
+ : undefined;
1339
+
1340
+ const testBaseline = own<boolean>("testBaseline");
1341
+
1342
+ const failureRecheck =
1343
+ own<boolean>("failureRecheck") ?? (testBaseline === false ? false : true);
1344
+
1345
+ const cores = opts.cores ?? availableParallelism();
1346
+ const coreCount = Number.isFinite(cores) && cores >= 1 ? Math.floor(cores) : 1;
1347
+
1348
+ // QA-1.6-8: waiting for the reference capture longer than the capture itself
1349
+ // may take is pointless, so the wait never exceeds baselineTimeoutMs.
1350
+ const baselineTimeoutMs = own<number>("baselineTimeoutMs") ?? 15_000;
1351
+ const captureWaitMs = Math.min(own<number>("captureWaitMs") ?? 5000, baselineTimeoutMs);
1352
+
1353
+ return {
1354
+ testScope: own<"affected" | "full">("testScope") ?? "affected",
1355
+ maxWorkers: own<number>("maxWorkers") ?? 2,
1356
+ lowPriority: own<boolean>("lowPriority") ?? true,
1357
+ maxConcurrentVerifications:
1358
+ own<number>("maxConcurrentVerifications") ?? Math.max(1, Math.floor(coreCount / 8)),
1359
+ defaultVerify: own<"deferred" | "required">("defaultVerify") ?? "deferred",
1360
+ captureWaitMs,
1361
+ background: own<boolean>("background") ?? false,
1362
+ pendingTtlMs: own<number>("pendingTtlMs") ?? 3_600_000,
1363
+ slotWaitMs: own<number>("slotWaitMs") ?? 60_000,
1364
+ batchWindowMs: own<number>("batchWindowMs") ?? 2000,
1365
+ failureRecheck,
1366
+ recheckTimeoutMs: own<number>("recheckTimeoutMs") ?? 60_000,
1367
+ baselineTimeoutMs,
1368
+ gateBudgetMs: own<number>("gateBudgetMs") ?? 90_000,
1369
+ };
1370
+ }
@@ -264,6 +264,13 @@ export const CLAUDE_ANTI_NARRATION = [
264
264
  // Assembled system prompt (pure — no side effects)
265
265
  // ---------------------------------------------------------------------------
266
266
 
267
+ /**
268
+ * Description of the `delegate` tool. It is not parsed as dispatch text, so it shows the literal,
269
+ * working `VERIFY:required` form (QA-2.3-3).
270
+ */
271
+ export const DELEGATE_TOOL_DESCRIPTION =
272
+ "Delegate a task to a tier subagent (fast | medium | heavy). Required-mode delegations and DoDs without testsPass are verified independently (deterministic checks, or a grader at >= the producer tier in a fresh session) before return: an accepted result on PASS, an honest 'unmet' status on FAIL. A DoD containing testsPass is deferred by default as a whole (its build, lint, run and criteria checks too) and returns UNVERIFIED with a `[router] unverified \u00b7 vrf_\u2026` footer, a risk level and a handle; verify it with router_verify, or put `VERIFY:required` in the task for a synchronous gate. Optionally pass an [acceptance]...[/acceptance] block to define the Definition of Done.";
273
+
267
274
  /**
268
275
  * Builds the DoD / Acceptance block protocol section shown when enforcement is ON.
269
276
  * Pure: no side-effects, no I/O.
@@ -275,7 +282,7 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
275
282
  : "If you omit the block, a minimal DoD is auto-inferred from the task type.";
276
283
  return [
277
284
  "### Acceptance / Definition of Done (enforcement is ON)",
278
- "Non-trivial delegations are independently verified before their result is accepted (producer \u2260 grader; grader \u2265 producer tier). Attach an acceptance block to your dispatch so the gate knows what \"done\" means:",
285
+ "Non-trivial delegations are verified independently (producer \u2260 grader; grader \u2265 producer tier). Required-mode delegations and DoDs without testsPass are gated before return; a DoD containing testsPass defers by default as a whole (its build, lint, run and criteria checks too) and returns unverified with a `[router] unverified \u00b7 vrf_\u2026` footer, a risk level and a handle. Attach an acceptance block to your dispatch so the gate knows what \"done\" means:",
279
286
  "",
280
287
  "[acceptance]",
281
288
  "check: testsPass",
@@ -287,7 +294,9 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
287
294
  "[/acceptance]",
288
295
  "",
289
296
  "- check kinds: testsPass | buildPasses | lintClean | fileExists path=\u2026 | schemaMatch path=\u2026 schema=\u2026 | run command=\"\u2026\" expect=\u2026",
290
- "- Command allowlist (first-token basename): npm, npx, pnpm, yarn, bun, node, tsc, tsx, vitest, jest, eslint, prettier. No shell chaining, redirection, substitution or newlines; interpreter inline-eval/print flags are forbidden. buildPasses probes a build script, then root tsconfig.json (npx tsc --noEmit). Unavailable checks produce acceptance caveats, not producer escalation; strictUnverifiable restores rejection.",
297
+ "- testsPass runs only the tests affected by the producer's changes (the full suite is CI's job); prefer it over a hand-written full-suite run command. A failure that also fails at the dispatch-time reference is excused as pre-existing.",
298
+ "- Per dispatch you may add `VERIFY:<mode>` as one token, <mode> being `required` or `deferred` (default deferred: returns at once with a handle and a risk level) and `VERIFY_WAIT:<n>s`. Pick required when later work depends on this delegation, or call router_verify before building on a medium/high-risk deferred result; unverified delegations stay listed in the prompt until verified or expired (1 h, or a restart); absent from the list does not mean verified.",
299
+ "- Command allowlist (first-token basename): npm, npx, pnpm, yarn, bun, node, tsc, tsx, vitest, jest, eslint, prettier, pytest (plus exactly `uv run pytest`). No shell chaining, redirection, substitution or newlines; interpreter inline-eval/print flags are forbidden. buildPasses probes a build script, then root tsconfig.json (npx tsc --noEmit). Unavailable checks produce acceptance caveats, not producer escalation; strictUnverifiable restores rejection.",
291
300
  "- " + omitLine,
292
301
  "- A failing DoD causes the result to be rejected and retried/escalated, not silently accepted.",
293
302
  ].join("\n");
@@ -1,5 +1,9 @@
1
1
  // Runner-independent comparison with opportunistic text/JSON adapters.
2
- import type { ExecResult } from "./types";
2
+ import type {
3
+ ExecResult, FailureClassification, JudgeScoped, RecheckOutcome, ScopedOutcome, TestsPassJudgement,
4
+ } from "./types";
5
+ import type { RunResult } from "./runner";
6
+ import { scrubText } from "../guard/scrub";
3
7
 
4
8
  export interface TestObservation {
5
9
  code: number;
@@ -8,10 +12,18 @@ export interface TestObservation {
8
12
  complete: boolean;
9
13
  }
10
14
 
11
- export interface TestBaseline {
12
- observation: TestObservation;
13
- dirty: boolean;
14
- }
15
+ /**
16
+ * T7 u4: the stable ReferenceState "none" reasons. The store (dispatch.ts) produces all but
17
+ * `untracked`, which is also runDeterministic's default when a gate carries no reference.
18
+ */
19
+ export const REFERENCE_NONE = {
20
+ failed: "the dispatch-time capture failed or timed out",
21
+ contaminated: "an edit was observed in an overlapping directory before the capture resolved",
22
+ untracked: "the dispatch was not tracked",
23
+ gateBudget: "the capture had not resolved within the gate budget",
24
+ /** The dispatch's DoD had no allowlisted testsPass check (or verify.require was "never"). */
25
+ notRequested: "no testsPass check was declared at dispatch",
26
+ } as const;
15
27
 
16
28
  export function observeTests(result: ExecResult): TestObservation {
17
29
  const text = (result.stdout + "\n" + result.stderr).replace(/\x1b\[[0-9;]*m/g, "");
@@ -54,25 +66,131 @@ export function observeTests(result: ExecResult): TestObservation {
54
66
  };
55
67
  }
56
68
 
57
- export function compareTests(after: TestObservation, baseline?: TestBaseline): {
58
- ok: boolean; unverifiable?: boolean; reason?: string; evidence?: string; note?: string;
59
- } {
60
- const observed = `observed failures: ${after.failures.join(", ") || "(identities unavailable)"}; count=${after.count ?? "unknown"}; exit=${after.code}`;
61
- const unavailable = (why: string) => ({ ok: false, unverifiable: true, reason: `testsPass: ${why}; ${observed}` });
62
- if (!baseline) return unavailable("no usable dispatch-time baseline");
63
- const before = baseline.observation;
64
- if (after.code === 0) return { ok: true, evidence: "testsPass: suite is green (exit 0)" };
65
- const added = after.failures.filter(id => !before.failures.includes(id));
66
- if (before.code === 0 || (before.complete && added.length > 0) ||
67
- (before.count !== undefined && after.count !== undefined && after.count > before.count)) {
68
- const named = before.code === 0 || before.complete ? added : [];
69
- return { ok: false, reason: `testsPass: introduced failures: ${named.join(", ") || `failure count ${before.count ?? 0} -> ${after.count ?? "unknown"}, exit ${after.code}`}` };
70
- }
71
- if (before.complete && after.complete && added.length === 0) {
72
- const note = `testsPass: no worse than before; pre-existing failures: ${after.failures.join(", ")}; suite is NOT green; baseline tree was ${baseline.dirty ? "dirty" : "clean"}`;
73
- return { ok: true, evidence: note, note };
69
+ /**
70
+ * The id-space file key of a RunResult id (deterministic.ts header, T5): the part before the
71
+ * earliest " > " or "::" separator, else the whole (bare-file) id; "/" separators. The earliest
72
+ * wins so a pytest parametrisation such as `t.py::test[1 > 0]` keys to `t.py`, and a vitest name
73
+ * containing "::" keys to its file.
74
+ */
75
+ export function fileKeyOfId(id: string): string {
76
+ const cuts = [id.indexOf(" > "), id.indexOf("::")].filter(i => i >= 0);
77
+ const file = cuts.length > 0 ? id.slice(0, Math.min(...cuts)) : id;
78
+ return file.replace(/\\/g, "/");
79
+ }
80
+
81
+ /** T7 <ids>: at most 10 ids, then " (+<k> more)". */
82
+ export function formatIds(ids: readonly string[]): string {
83
+ if (ids.length === 0) return "(none)";
84
+ const shown = ids.slice(0, 10).join(", ");
85
+ return ids.length > 10 ? `${shown} (+${ids.length - 10} more)` : shown;
86
+ }
87
+
88
+ const unverifiable = (reason: string, failures?: FailureClassification): TestsPassJudgement =>
89
+ failures ? { ok: false, unverifiable: true, reason, failures } : { ok: false, unverifiable: true, reason };
90
+
91
+ /** T5.5: classify each scoped failing id against an exact recheck. */
92
+ function classify(c: RunResult, recheck: Extract<RecheckOutcome, { kind: "exact" }>): FailureClassification {
93
+ const r = recheck.result;
94
+ const ran = new Set(recheck.ranFiles);
95
+ const absent = new Set(recheck.absentFiles);
96
+ const refFailing = new Set(r?.failingIds ?? []);
97
+ const refFileKeys = new Set((r?.failingIds ?? []).map(fileKeyOfId));
98
+ const introduced: string[] = [];
99
+ const preexisting: string[] = [];
100
+ const unknown: string[] = [];
101
+ for (const x of c.failingIds) {
102
+ const f = fileKeyOfId(x);
103
+ const bare = f === x.replace(/\\/g, "/");
104
+ if (absent.has(f)) introduced.push(x);
105
+ else if (!ran.has(f)) unknown.push(x);
106
+ // A bare-file id (collection error now) is never pre-existing; its file ran, so it is introduced.
107
+ else if (bare) introduced.push(x);
108
+ else if (refFailing.has(x)) preexisting.push(x);
109
+ else if (c.source === "report") introduced.push(x);
110
+ else if (!refFileKeys.has(f)) introduced.push(x);
111
+ else unknown.push(x);
74
112
  }
75
- // Equal counts or equal non-zero exits cannot prove that the identities are
76
- // unchanged. Under-excuse rather than silently replace an old failure by a new one.
77
- return unavailable(`baseline exit=${before.code}, count=${before.count ?? "unknown"}; cannot prove failures predate dispatch`);
113
+ return { introduced, preexisting, unknown };
78
114
  }
115
+
116
+ /**
117
+ * The verdict algebra (deterministic.ts header, T5-T7). Pure and total: a failure passes only when
118
+ * proven pre-existing at an exact reference with a complete scoped inventory (G1), and fails only
119
+ * when at least one id is proven introduced (G2).
120
+ */
121
+ export const judgeScoped: JudgeScoped = (scoped: ScopedOutcome, recheck: RecheckOutcome | undefined): TestsPassJudgement => {
122
+ switch (scoped.kind) {
123
+ case "no-affected":
124
+ return { ok: true, unverifiable: false, note: scoped.note };
125
+ case "unverifiable":
126
+ return unverifiable(`testsPass: scoping impossible (${scoped.code}): ${scoped.reason}`);
127
+ case "slot-busy":
128
+ return unverifiable(scoped.deadlineCut
129
+ ? "gate budget exhausted waiting for the verification slot"
130
+ : `verification slot busy (waited ${scoped.waitedMs}ms)`);
131
+ case "timed-out":
132
+ return unverifiable(`testsPass timed out after ${scoped.boundMs}ms`);
133
+ case "aborted":
134
+ return unverifiable(`testsPass: ${scoped.reason}`);
135
+ case "error":
136
+ return unverifiable(`testsPass check errored: ${scrubText(scoped.reason)}`);
137
+ case "ran":
138
+ break;
139
+ }
140
+ const c = scoped.result;
141
+ const note = c.note ?? "no details";
142
+ if (c.complete && !c.collectionError && c.failingIds.length === 0) {
143
+ const runner = scoped.spec?.runner ?? "full";
144
+ const total = c.total ?? "unknown";
145
+ const evidence = `testsPass: affected tests passed (${runner}, ${total} tests)`;
146
+ return c.total === 0
147
+ ? { ok: true, unverifiable: false, evidence, note: "testsPass: no affected tests ran" }
148
+ : { ok: true, unverifiable: false, evidence };
149
+ }
150
+ const observed = `; observed failures: ${formatIds(c.failingIds)}`;
151
+ if (c.failingIds.length === 0) {
152
+ return c.collectionError
153
+ ? unverifiable(`testsPass: collection error without failing test files: ${note}${observed}`)
154
+ : unverifiable(`testsPass: the scoped result is incomplete: ${note} (exit ${scoped.exitCode})`);
155
+ }
156
+ if (recheck === undefined) {
157
+ return unverifiable(c.collectionError
158
+ ? `testsPass: collection error without failing test files: ${note}${observed}`
159
+ : `testsPass: cannot attribute failures: no failing test file identified, recheck not attempted${observed}`);
160
+ }
161
+ switch (recheck.kind) {
162
+ case "approximate": {
163
+ const causes = recheck.inexactReasons.map(r => (r.path ? `${r.cause} ${r.path}` : r.cause));
164
+ return unverifiable(`testsPass: cannot attribute failures: the dispatch reference is approximate (${formatIds(causes)})${observed}`);
165
+ }
166
+ case "unusable":
167
+ return unverifiable(recheck.cause === "no-reference"
168
+ ? `testsPass: no reference: pre-existing failures cannot be told apart (${recheck.reason})${observed}`
169
+ : `testsPass: cannot attribute failures: reference unusable (${recheck.cause}): ${recheck.reason}${observed}`);
170
+ case "disabled":
171
+ return unverifiable(`testsPass: cannot attribute failures: failureRecheck is off, pre-existing failures cannot be told apart${observed}`);
172
+ case "timed-out":
173
+ return unverifiable(`testsPass: cannot attribute failures: the reference rerun timed out after ${recheck.boundMs}ms${observed}`);
174
+ case "skipped-deadline":
175
+ return unverifiable(`testsPass: gate budget exhausted before recheck${observed}`);
176
+ case "exact":
177
+ break;
178
+ }
179
+ const failures = classify(c, recheck);
180
+ if (failures.introduced.length > 0) {
181
+ const reason = `testsPass: introduced failures: ${formatIds(failures.introduced)}${observed}`;
182
+ return failures.preexisting.length > 0
183
+ ? { ok: false, unverifiable: false, reason, note: `testsPass: also failing at the dispatch reference: ${formatIds(failures.preexisting)}`, failures }
184
+ : { ok: false, unverifiable: false, reason, failures };
185
+ }
186
+ if (failures.unknown.length === 0 && c.complete && !c.collectionError) {
187
+ return {
188
+ ok: true, unverifiable: false, failures,
189
+ note: `testsPass: no worse than before; pre-existing failures: ${formatIds(failures.preexisting)}; suite is NOT green (affected tests checked against the exact dispatch reference)`,
190
+ };
191
+ }
192
+ if (failures.unknown.length > 0) {
193
+ return unverifiable(`testsPass: cannot prove failures predate dispatch: ${formatIds(failures.unknown)}${observed}`, failures);
194
+ }
195
+ return unverifiable(`testsPass: the scoped failure inventory is incomplete (${c.note ?? "collection error"}); known failures predate dispatch, others may not${observed}`, failures);
196
+ };