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.
@@ -4,11 +4,62 @@
4
4
  // seams. ./paths is pure path math (node:path only) and keeps that contract.
5
5
 
6
6
  import type { Check, DoD } from "./dod";
7
- import type { Verdict, DeterministicDeps, MutexRegistry, ExecResult } from "./types";
7
+ import type {
8
+ Verdict,
9
+ DeterministicDeps,
10
+ MutexRegistry,
11
+ ExecResult,
12
+ Deadline,
13
+ ArgvSeam,
14
+ ExecOptions,
15
+ ExecSeam,
16
+ FailureClassification,
17
+ OpenVerificationScope,
18
+ RecheckOutcome,
19
+ ReferenceState,
20
+ RecheckUnusableCause,
21
+ Rechecker,
22
+ ScopedExecutor,
23
+ ScopedOutcome,
24
+ TestsPassHook,
25
+ TestsPassJudgement,
26
+ TestsPassRequest,
27
+ TestsPassRun,
28
+ VerificationScope,
29
+ } from "./types";
30
+ import type {
31
+ DetectedRunner,
32
+ LintSpec,
33
+ NoAffected,
34
+ Unscoped,
35
+ PlannerFs,
36
+ RunnerFs,
37
+ RunnerHost,
38
+ RunResult,
39
+ TestSearchSeam,
40
+ } from "./runner";
41
+ import type { DispatchReference, MaterializedReference, ReferenceDeps } from "./reference";
42
+ import type { TreeSnapshot } from "./dispatch";
43
+ import type { VerifyBudget } from "../router/config";
44
+ import type { PluginLogger } from "../router/logger";
8
45
  import { scrubText } from "../guard/scrub";
9
46
  import { resolveAgainst } from "./paths";
10
- import { isAbsolute } from "node:path";
11
- import { compareTests, observeTests } from "./baseline";
47
+ import { isAbsolute, posix as pathPosix, win32 as pathWin32 } from "node:path";
48
+ import { judgeScoped, observeTests, REFERENCE_NONE } from "./baseline";
49
+ import {
50
+ detectRunner,
51
+ isNoAffected,
52
+ isUnscoped,
53
+ isUnverifiable,
54
+ planRerun,
55
+ planScopedLint,
56
+ planScopedRun,
57
+ readResult,
58
+ resolveEntry,
59
+ } from "./runner";
60
+ import { fileKeyOfId } from "./baseline";
61
+ import { DEFAULT_MATERIALIZE_TIMEOUT_MS, gcStaleReferences, materialize, nodeReferenceFs } from "./reference";
62
+ import { acquireSlot, type SlotHandle } from "./slot";
12
63
 
13
64
  // ---------------------------------------------------------------------------
14
65
  // MutexRegistry — per-key serialization via promise-chaining
@@ -33,7 +84,7 @@ export function createMutexRegistry(): MutexRegistry {
33
84
 
34
85
  export const DEFAULT_ALLOWLIST = [
35
86
  "npm", "npx", "pnpm", "yarn", "bun", "node",
36
- "tsc", "tsx", "vitest", "jest", "eslint", "prettier",
87
+ "tsc", "tsx", "vitest", "jest", "eslint", "prettier", "pytest",
37
88
  ];
38
89
 
39
90
  // Any shell-chaining / redirection / substitution metacharacter.
@@ -55,6 +106,11 @@ export function isCommandAllowed(command: string, allowlist: string[]): boolean
55
106
  const firstToken = tokens[0];
56
107
  const parts = firstToken.split(/[/\\]/);
57
108
  const basename = parts[parts.length - 1];
109
+ // `uv` is never allowlisted as such: only `uv run pytest ...` passes, and only when pytest is
110
+ // allowed. This runs before the generic check so a user allowlist containing "uv" cannot widen it.
111
+ if (basename.replace(/\.(exe|cmd|bat)$/i, "") === "uv") {
112
+ return allowlist.includes("pytest") && tokens[1] === "run" && tokens[2] === "pytest";
113
+ }
58
114
  if (!allowlist.includes(basename)) return false;
59
115
  // Strip a Windows executable suffix before the interpreter check.
60
116
  const interpreterBase = basename.replace(/\.(exe|cmd|bat)$/i, "");
@@ -110,6 +166,8 @@ interface CheckResult {
110
166
  unverifiable?: boolean;
111
167
  reason?: string;
112
168
  evidence?: string;
169
+ /** testsPass only: judgeScoped's attribution against an exact recheck. */
170
+ failures?: FailureClassification;
113
171
  }
114
172
 
115
173
  // ---------------------------------------------------------------------------
@@ -144,16 +202,17 @@ async function runRun(
144
202
  if (!isCommandAllowed(check.command, allowlist)) {
145
203
  return { ok: false, unverifiable: true, reason: `command not allowlisted: ${check.command}` };
146
204
  }
147
- const r: ExecResult = await deps.exec(check.command, { cwd: deps.cwd, timeoutMs });
148
- if (r.timedOut) {
149
- return { ok: false, reason: `run timed out after ${timeoutMs}ms: ${check.command}` };
150
- }
205
+ const command = check.command;
206
+ const got = await obtainExec("run", command, deps, timeoutMs, (scope, deadline) => scope.runShell(command, deps.cwd, deadline));
207
+ if ("result" in got) return got.result;
208
+ const r = got.exec;
151
209
  const out = r.stdout + "\n" + r.stderr;
152
210
  if (check.expect !== undefined && !out.includes(check.expect)) {
153
211
  return {
154
212
  ok: false,
155
213
  reason: `expected substring not found: "${check.expect}"`,
156
214
  evidence: out.slice(0, 2000),
215
+ ...withNotes(got.notes),
157
216
  };
158
217
  }
159
218
  const ok = r.code === 0;
@@ -162,9 +221,10 @@ async function runRun(
162
221
  ok: false,
163
222
  reason: `command exited ${r.code}: ${check.command}`,
164
223
  evidence: out.slice(0, 2000),
224
+ ...withNotes(got.notes),
165
225
  };
166
226
  }
167
- return { ok: true, evidence: `exit 0: ${check.command}` };
227
+ return { ok: true, evidence: `exit 0: ${check.command}`, ...withNotes(got.notes) };
168
228
  } catch (err) {
169
229
  return { ok: false, reason: `run check errored: ${scrubText(String(err))}` };
170
230
  }
@@ -181,6 +241,1280 @@ export function resolveRepoCommand(
181
241
  return defaults?.lintCommand ?? "npm run lint";
182
242
  }
183
243
 
244
+ // ===============================================================================================
245
+ // testsPass PIPELINE: design and verdict algebra (plan Phase 2.1, task 2.1.1)
246
+ //
247
+ // Contract types: src/verify/types.ts, block "testsPass pipeline contract" (Deadline,
248
+ // ReferenceState, ScopedOutcome, RecheckOutcome, FailureClassification, TestsPassJudgement,
249
+ // ScopedExecutor, Rechecker, VerificationScope, TestsPassRequest/Run/Hook, JudgeScoped). That
250
+ // block is cherry-picked onto vrb/p22 (2.2 batch.ts) and vrb/p24 (2.4 pending.ts): later 2.1 tasks
251
+ // must NOT edit it (a different copy on both sides conflicts at merge); 2.1-internal types go
252
+ // elsewhere. Plan: docs/plans/verification-resource-budget-plan.md sections 1.2, 1.4, 1.5, 1.6.
253
+ // Record: docs/qa/verification-resource-budget/phase-2.1.md.
254
+ //
255
+ // -----------------------------------------------------------------------------------------------
256
+ // T1. GUARANTEES (plan section 1.2), as invariants of judgeScoped and the pipeline
257
+ //
258
+ // G1 Excuse. A failing scoped run passes ("no worse than before") ONLY when all hold: the scoped
259
+ // result is complete and has no collection error; the recheck is "exact" (reference exact,
260
+ // unreproduced inert, rerun complete, no collection error, total > 0); and EVERY failing id
261
+ // is failing at the reference. Anything less is unverifiable or fail, never pass.
262
+ // G2 Reject. testsPass reports fail ONLY when at least one failing id is PROVEN introduced
263
+ // against an "exact" recheck (T5). One proof suffices, so rejecting does not need a complete
264
+ // scoped inventory. Every other non-pass is unverifiable, never fail.
265
+ // G3 No false green. A scoped run passes without a recheck only when it ran, did not time out,
266
+ // is complete, has no collection error and lists no failing id. readResult's zero-test guard
267
+ // (runner.ts I step 2a) already turned untrustworthy zero-test runs into complete = false.
268
+ // G4 unverifiable is a caveat: gate.ts accepts it with caveats, or rejects it under
269
+ // strictUnverifiable, unchanged. A rejection keeps today's onFailure and escalation ladder.
270
+ // G5 No full suite. Only testScope "full" runs the resolved command unscoped. S6 never falls
271
+ // back to it. With no TestsPassHook in the deps, testsPass is unverifiable, never a run.
272
+ // G6 No test command at dispatch time: dispatch captures a git reference only (captureReference).
273
+ // G7 A deferred (unverified) delegation is never reported as verified. That is 2.4's footer.
274
+ //
275
+ // -----------------------------------------------------------------------------------------------
276
+ // T2. PIPELINE STEPS (one testsPass check of one gate or router_verify call)
277
+ //
278
+ // step owner (task) Wave-1 function used
279
+ // ----------------------------- ------------------------------ ------------------------------
280
+ // S0 deadline + AbortController index.ts both gate sites withTimeout (timeout.ts);
281
+ // per gate invocation (2.1.5a); router_verify 2.4 createDeadline (2.1.2.1)
282
+ // P0 prepare: tree snapshot, wiring.prepareVerification snapshotTree (tree.ts),
283
+ // changed files, reference (2.1.3), bounded by the deadline captureReference result
284
+ // P1 command + allowlist runCommandCheck (2.1.2.4) resolveRepoCommand,
285
+ // isCommandAllowed
286
+ // P2 S1 scoping TestsPassHook (2.1.2.4; 2.2 planScopedRun (runner.ts)
287
+ // swaps in the batch coordinator)
288
+ // P3 S6 fail-closed decisions TestsPassHook isUnverifiable, isNoAffected
289
+ // P4 S3 slot, once per scope VerificationScope (2.1.2.2) acquireSlot (slot.ts)
290
+ // P5 S4 caps, low priority, ScopedExecutor (2.1.2.2) runArgv (exec.ts); the worker
291
+ // abort; run cap is already in spec.args
292
+ // P6 readResult, on EVERY path ScopedExecutor readResult (runner.ts)
293
+ // P7 S2 recheck at the dispatch Rechecker (2.1.2.3) gcStaleReferences, materialize,
294
+ // reference MaterializedReference.toRefPath/
295
+ // dispose (reference.ts);
296
+ // detectRunner, resolveEntry,
297
+ // planRerun, readResult (runner.ts)
298
+ // P8 verdict judgeScoped (baseline.ts, -
299
+ // 2.1.4), then runDeterministic
300
+ // and gate.ts as today
301
+ // P9 cleanup VerificationScope.close SlotHandle.release, dispose
302
+ //
303
+ // P0 The deadline exists before prepareVerification, so the snapshot and the wait for a
304
+ // still-pending capture are bounded by it. ReferenceState is settled when the request is
305
+ // built: "captured" | "disabled" (failureRecheck off) | "none" (with a reason, T7 u4).
306
+ // P1 Not allowlisted -> unverifiable "command not allowlisted: <command>" (as today).
307
+ // testsPass does NOT run inside deps.mutex: that per-cwd lock would serialize exactly the
308
+ // concurrent gates that 2.2 must batch. buildPasses and run keep the mutex.
309
+ // P2 planScopedRun({ command, cwd, changedFiles, budget: { maxWorkers }, fs: PlannerFs,
310
+ // search: TestSearchSeam, host }). changedFiles is ChangedPath[] (tree-snapshot status,
311
+ // previousPath for renames) or "unavailable". fs and search are built in wiring.ts
312
+ // (2.1.3, T9). testScope "full": no planning; the resolved command runs as written (P5f).
313
+ // P3 NoAffected -> ScopedOutcome "no-affected" (pass with its note). Unverifiable ->
314
+ // "unverifiable" (code + reason). Neither takes the slot nor spawns anything.
315
+ // P4 scope = openScope({ cwd, command }). The first execute() calls acquireSlot({ max:
316
+ // budget.maxConcurrentVerifications, waitMs: deadline.bound(budget.slotWaitMs), signal:
317
+ // deadline.signal, meta, onLost }). busy -> "slot-busy" { waitedMs, deadlineCut:
318
+ // deadline.remaining() === 0 }. Later calls on a busy scope return the same outcome at once.
319
+ // The hold covers the scoped run AND the recheck (QA-1.4-18), and is never nested: the
320
+ // process holds at most one scope per check, and runDeterministic awaits a check's close()
321
+ // before the next check starts (T8).
322
+ // P5 argv(spec.file, spec.args, { cwd: spec.cwd, env: spec.env, lowPriority:
323
+ // budget.lowPriority, signal: deadline.signal, timeoutMs: deadline.bound(checkTimeoutMs) }),
324
+ // checkTimeoutMs = deps.timeoutMs ?? 120000. Specs are never run through a shell.
325
+ // timedOut -> "timed-out" { boundMs } when deadline.signal did not abort, else "aborted"
326
+ // { reason: "gate budget exhausted during the scoped run" }. A signal already aborted
327
+ // before the spawn -> "aborted", with no spawn.
328
+ // P5f testScope "full": runShell-backed exec(command, { cwd, lowPriority, signal, timeoutMs })
329
+ // under the same scope (user text keeps shell + allowlist, section 1.5-1). Its RunResult is
330
+ // synthesized from observeTests(execResult): source "text", failingIds = obs.failures,
331
+ // failingFiles = the id file parts (T5 fileKeyOfId) resolved against cwd, complete =
332
+ // obs.complete, collectionError = (code !== 0 && failures empty), total = undefined.
333
+ // P6 readResult(spec, execResult, runnerFs) after EVERY spawn attempt: exit, timeout, abort,
334
+ // and a spawn that threw (with { code: -1, stdout: "", stderr: <message> }), because it
335
+ // deletes the report file (QA-1.3-16). An executor exception -> "error".
336
+ // P7 The recheck runs only for "ran" with >= 1 failing id and >= 1 failing file (T4).
337
+ // P8 judgeScoped(scoped, recheck) -> TestsPassJudgement, returned as the check's CheckResult.
338
+ // P9 scope.close() waits for pending disposals, then releases the slot; never rejects. The
339
+ // testsPass hook waits for it only until CLOSE_MARGIN_MS before the gate deadline ends
340
+ // (closeWithinDeadline, QA-2.1-3, QA-2.1-13): within that a close is awaited, so scopes
341
+ // never nest (T8); after it the close carries on in the background (errors logged), still releasing
342
+ // the slot only after the disposal, and no later check of the gate can acquire one. A slow
343
+ // dispose never costs a verdict.
344
+ //
345
+ // -----------------------------------------------------------------------------------------------
346
+ // T3. DEADLINE SEMANTICS (section 1.5-13)
347
+ //
348
+ // - One Deadline per gate invocation (delegate tool AND native task) and per router_verify
349
+ // call, created with budget.gateBudgetMs. Its signal aborts at expiry, or when the owner's
350
+ // withTimeout(accept(...), gateBudgetMs, "verification gate") rejects (index.ts aborts the
351
+ // controller, then returns unverifiableGateResult as today).
352
+ // - Every step is bounded by deadline.bound(ownBudget) and receives deadline.signal:
353
+ // test search call bound(10_000) each (git ls-files / git grep, low priority)
354
+ // slot wait bound(slotWaitMs): a 60 s slot wait under a 5 s budget waits <= 5 s
355
+ // scoped run bound(checkTimeoutMs)
356
+ // recheck sub-deadline rd = deriveDeadline(deadline, recheckTimeoutMs): recheckTimeoutMs
357
+ // bounds GC + materialize + rerun together, never past the gate
358
+ // GC rd.bound(5_000)
359
+ // materialize rd.bound(DEFAULT_MATERIALIZE_TIMEOUT_MS)
360
+ // rerun rd.bound(recheckTimeoutMs)
361
+ // batch wait (2.2) bound(batchWindowMs)
362
+ // A step whose bound is 0 is not started: the slot reports busy (deadlineCut), a spawn
363
+ // reports aborted, a recheck reports skipped-deadline.
364
+ // - Recheck threshold: RECHECK_MIN_REMAINING_MS = 10_000. The Rechecker checks
365
+ // deadline.remaining() FIRST; below it -> "skipped-deadline" (u7 "gate budget exhausted
366
+ // before recheck"), with nothing materialized or spawned.
367
+ // - Abort kills the tree: runArgv/runShell kill the whole process tree on signal abort
368
+ // (exec.ts, 1.2); acquireSlot returns busy on an aborted signal; materialize and GC stop at
369
+ // their next check. dispose runs only after the rerun tree has exited.
370
+ // - The dispatch-side capture is NOT under a gate deadline. It is bounded by
371
+ // baselineTimeoutMs, and the dispatch awaits it for at most captureWaitMs (clamped to
372
+ // baselineTimeoutMs; 2.4 replaces it with VERIFY_WAIT). A timeout or error there means
373
+ // "no reference" and never blocks or fails the dispatch.
374
+ // - Deadline is fake-timer friendly: createDeadline uses an injected clock and setTimeout, and
375
+ // dispose() clears its timer, so no timer outlives the gate. It owns the gate's
376
+ // AbortController (plan 2.1.5.a): the owner calls abort() when withTimeout rejects.
377
+ //
378
+ // -----------------------------------------------------------------------------------------------
379
+ // T4. RECHECK (S2), steps of the Rechecker returned by scope.rechecker(command, liveCwd)
380
+ //
381
+ // Decided by the hook before any Rechecker call (no spawn):
382
+ // ReferenceState "disabled" -> { kind: "disabled" }.
383
+ // ReferenceState "none" -> { kind: "unusable", cause: "no-reference", reason }.
384
+ // Inside the Rechecker(reference, failingFiles, deadline), in this order:
385
+ // a. deadline.remaining() < RECHECK_MIN_REMAINING_MS -> "skipped-deadline".
386
+ // b. runner = detectRunner(command, liveCwd). S6 -> unusable "rerun-unplannable".
387
+ // runner.kind "pytest" -> unusable "runner-unsupported" (reference.ts OPEN RISKS: an
388
+ // editable install imports the LIVE tree's sources, so a pytest reference run can neither
389
+ // excuse nor prove; running it would only spend CPU).
390
+ // c. gcStaleReferences(reference.root, refDeps with rd.bound(5_000)) INSIDE the hold, before
391
+ // materialize (QA-1.5-10). Its report is logged; it never fails the recheck.
392
+ // d. materialize(reference, currentSnapshot, rd.signal, refDeps with the T3 bound) INSIDE the
393
+ // hold. ok:false "commit-missing" -> unusable "reference-vanished"; any other ok:false ->
394
+ // unusable "materialize-failed" (reason = its detail).
395
+ // e. !exact -> { kind: "approximate", inexactReasons }. Dispose; no rerun (it could neither
396
+ // excuse nor prove, section 1.5-7).
397
+ // f. Any unreproduced entry that is not inert -> unusable "unreproduced-inputs" (QA-1.5-7).
398
+ // Dispose; no rerun. INERT_UNREPRODUCED, matched on the entry's last segment (a dir ends
399
+ // in "/"), case-insensitive on win32:
400
+ // dirs coverage/ .nyc_output/ logs/ .idea/ .vscode/ .pytest_cache/ __pycache__/
401
+ // .mypy_cache/ .ruff_cache/
402
+ // files *.log .DS_Store Thumbs.db desktop.ini .eslintcache *.pyc
403
+ // Never inert: .env*, build output (dist/ build/ out/ .next/), generated sources, and
404
+ // anything not listed. Additions need evidence that tests cannot read them.
405
+ // g. For each failing file f (absolute live path): r = toRefPath(f). undefined (outside the
406
+ // root) -> f stays unclassified. !fileExists(r) -> absentFiles. Else -> the rerun list.
407
+ // h. Rerun list empty -> { kind: "exact", result: undefined, ranFiles: [], absentFiles }.
408
+ // i. entry = resolveEntry(runner, runner.runnerCwd) on the LIVE tree, the canonical start
409
+ // the scoped plan used (E2E-2: the raw liveCwd may be an 8.3 short path; the reference links its
410
+ // node_modules); spec = planRerun(runner, rerunList, toRefPath(runner.runnerCwd), budget,
411
+ // { fs, entry, host }). S6, or NoAffected (contradicts g) -> unusable "rerun-unplannable".
412
+ // j. Run it exactly as P5/P6 with timeoutMs = rd.bound(recheckTimeoutMs). A timeout or an
413
+ // abort -> { kind: "timed-out", boundMs }.
414
+ // k. After readResult: lstat(reference.dir) gone -> unusable "reference-vanished" (QA-1.5-4);
415
+ // complete === false -> "incomplete"; collectionError -> "collection-error" (1.5-8);
416
+ // total === 0 -> "no-tests" (QA-1.3-17). Otherwise { kind: "exact", result, ranFiles,
417
+ // absentFiles, notes }.
418
+ // l. dispose() once the rerun tree has exited; the scope tracks it and close() awaits it.
419
+ // File keys (ranFiles, absentFiles) live in id space: P.relative(spec.cwd, abs) with "/"
420
+ // separators, the construction readResult uses for ids. ranFiles use the rerun spec's cwd;
421
+ // absentFiles use runner.runnerCwd (the live spec's cwd). A spelling mismatch can only leave
422
+ // an id unclassified, which is unverifiable, never pass.
423
+ //
424
+ // -----------------------------------------------------------------------------------------------
425
+ // T5. VERDICT ALGEBRA: judgeScoped(scoped, recheck) (baseline.ts, 2.1.4). Pure and total.
426
+ //
427
+ // fileKeyOfId(id) = the part before the earliest " > " or "::", else id.
428
+ // C = scoped.result (kind "ran").
429
+ // 1. Planning, slot, timeout, abort and error kinds -> their row (T6); the recheck is ignored.
430
+ // 2. C.complete && !C.collectionError && C.failingIds empty -> pass (row R1).
431
+ // 3. C.failingIds empty -> unverifiable (row R4: incomplete without identities; R3 when
432
+ // C.collectionError).
433
+ // 4. recheck undefined -> unverifiable (u11 when C.collectionError, else u9). Non-exact kinds ->
434
+ // their column (T6).
435
+ // 5. Exact: classify each x in C.failingIds, with R = recheck.result and f = fileKeyOfId(x):
436
+ // f in absentFiles -> introduced (new test file)
437
+ // f in ranFiles and x in R.failingIds -> preexisting
438
+ // f in ranFiles and C.source === "report" -> introduced (id-level: same format)
439
+ // f in ranFiles and no id of R has file key f -> introduced (file-level: the file
440
+ // collected and passed at the reference)
441
+ // otherwise -> unknown
442
+ // A bare-file id (collection error now) is never preexisting: a comparable rerun has no
443
+ // collection error, hence no bare ids. It is introduced when its file ran or is absent.
444
+ // 6. introduced non-empty -> fail r1 (G2), naming ONLY the introduced ids.
445
+ // else unknown empty && C.complete && !C.collectionError -> pass n2 (G1).
446
+ // else -> unverifiable (u8 when unknown is non-empty, else u10).
447
+ //
448
+ // -----------------------------------------------------------------------------------------------
449
+ // T6. TRUTH TABLE
450
+ //
451
+ // Cell = ok / unverifiable, then the T7 code of the reason or note.
452
+ // P = ok:true unverifiable:false F = ok:false unverifiable:false (reject, escalate)
453
+ // V = ok:false unverifiable:true (caveat; rejected only under strictUnverifiable)
454
+ // Recheck columns:
455
+ // -- not attempted (recheck undefined) X+ exact, every failing id preexisting
456
+ // X- exact, >= 1 id introduced X? exact, none introduced, >= 1 unknown
457
+ // A approximate U unusable (any cause, incl. no reference)
458
+ // D disabled (failureRecheck off) T rerun timed out S skipped for deadline
459
+ //
460
+ // scoped row -- X+ X- X? A U D T S
461
+ // ------------------------------ ------ ------ ------ ------ ----- ----- ----- ----- -----
462
+ // R0 no-affected P n0 not attempted: a supplied recheck is ignored -> P n0
463
+ // R1 green P e1 not attempted: a supplied recheck is ignored -> P e1
464
+ // (plus note n1 when total === 0)
465
+ // R2 failures, complete V u9 P n2 F r1 V u8 V u3 V u4 V u5 V u6 V u7
466
+ // R2i failures, incomplete V u9 V u10 F r1 V u8 V u3 V u4 V u5 V u6 V u7
467
+ // inventory (complete false)
468
+ // R3 collection error V u11 V u10* F r1 V u8 V u3 V u4 V u5 V u6 V u7
469
+ // R4 incomplete, no failing id V u12 not attempted: nothing to recheck -> V u12
470
+ // R5 timed out / aborted V u13 not attempted -> V u13
471
+ // R6 slot busy V u14 not attempted -> V u14
472
+ // R7 S6 unverifiable V u15 not attempted -> V u15
473
+ // R8 executor error V u16 not attempted -> V u16
474
+ //
475
+ // --: for R2/R2i/R3 the recheck is not attempted when no failing file is identified (u9; u11
476
+ // for a collection error). A pipeline defect that skips it is caught the same way.
477
+ // X+ in R3 (*): cannot occur for a bare-file id (T5.5). With only non-bare ids, all
478
+ // preexisting, the collection error still leaves the inventory incomplete -> u10.
479
+ // R2 x X+ is the only pass that has failures (G1). Every F cell rests on a proven id (G2).
480
+ //
481
+ // -----------------------------------------------------------------------------------------------
482
+ // T7. WORDING (stable; tests assert it verbatim). <ids> = at most 10 ids, then " (+<k> more)".
483
+ // Every V and F reason of rows R2, R2i and R3 ends with "; observed failures: <ids>".
484
+ //
485
+ // n0 the NoAffected note, verbatim (runner.ts M.2), e.g. "no changed files, no affected tests"
486
+ // e1 evidence "testsPass: affected tests passed (<runner>, <total> tests)"
487
+ // n1 note "testsPass: no affected tests ran"
488
+ // n2 note "testsPass: no worse than before; pre-existing failures: <ids>; suite is NOT green
489
+ // (affected tests checked against the exact dispatch reference)"
490
+ // r1 reason "testsPass: introduced failures: <introduced>", plus the note "testsPass: also
491
+ // failing at the dispatch reference: <preexisting>" when that list is non-empty
492
+ // u3 "testsPass: cannot attribute failures: the dispatch reference is approximate
493
+ // (<cause> <path>, ...)"
494
+ // u4 no-reference: "testsPass: no reference: pre-existing failures cannot be told apart
495
+ // (<ReferenceState reason>)"; other causes: "testsPass: cannot attribute failures:
496
+ // reference unusable (<cause>): <reason>"
497
+ // ReferenceState "none" reasons: "the dispatch-time capture failed or timed out", "an edit
498
+ // was observed in an overlapping directory before the capture resolved", "the dispatch
499
+ // was not tracked", "the capture had not resolved within the gate budget"
500
+ // u5 "testsPass: cannot attribute failures: failureRecheck is off, pre-existing failures
501
+ // cannot be told apart"
502
+ // u6 "testsPass: cannot attribute failures: the reference rerun timed out after <n>ms"
503
+ // u7 "testsPass: gate budget exhausted before recheck"
504
+ // u8 "testsPass: cannot prove failures predate dispatch: <unknown>"
505
+ // u9 "testsPass: cannot attribute failures: no failing test file identified, recheck not
506
+ // attempted"
507
+ // u10 "testsPass: the scoped failure inventory is incomplete (<C.note or 'collection error'>);
508
+ // known failures predate dispatch, others may not"
509
+ // u11 "testsPass: collection error without failing test files: <C.note>"
510
+ // u12 "testsPass: the scoped result is incomplete: <C.note> (exit <code>)"
511
+ // u13 "testsPass timed out after <boundMs>ms: <command>" | "testsPass: <aborted reason>"
512
+ // u14 "verification slot busy (waited <n>ms)" | "gate budget exhausted waiting for the
513
+ // verification slot" (deadlineCut)
514
+ // u15 "testsPass: scoping impossible (<code>): <reason>"
515
+ // u16 "testsPass check errored: <scrubbed reason>"
516
+ //
517
+ // -----------------------------------------------------------------------------------------------
518
+ // T8. OTHER COMMAND CHECKS UNDER S3/S4 (2.1.2.5)
519
+ //
520
+ // buildPasses, lintClean and run each open their own scope (never nested: runDeterministic is
521
+ // sequential and awaits each check's close() before the next check). Low priority,
522
+ // deadline.signal, timeoutMs = deadline.bound(checkTimeoutMs). Slot busy -> unverifiable u14.
523
+ // Their timeouts and exit codes keep today's meaning (fail). lintClean: planScopedLint ->
524
+ // LintSpec (argv, exit code decides) | NoAffected (pass, note) | Unscoped (the resolved
525
+ // command through the shell, as today). run: section 1.5-12, as written.
526
+ //
527
+ // -----------------------------------------------------------------------------------------------
528
+ // T9. WAVE-1 HANDOFFS (verified against docs/qa/verification-resource-budget/phase-1.*.md)
529
+ //
530
+ // 1.1 wiring.ts `baselineTimeoutMs ?? 60000` and the two reads of the deprecated dispatch-time baseline key ->
531
+ // resolveVerifyBudget(cfg).baselineTimeoutMs / .failureRecheck (2.1.3). index.ts: drop
532
+ // the DEFAULT_GATE_BUDGET_MS import and read resolveVerifyBudget(cfg).gateBudgetMs
533
+ // (2.1.5c). timeout.ts:37 is outside 2.1's write-set and stays. tiers.json: remove
534
+ // `"gateBudgetMs": 90000` so the code default applies (2.1.5c).
535
+ // warnDeprecatedVerifyKeys(cfg, logger) after every loadConfig() (2.1.5c).
536
+ // resolveVerifyBudget clamps captureWaitMs to baselineTimeoutMs (QA-1.6-8, 2.1.5c).
537
+ // QA-1.4-21 residual stated in the slotWaitMs JSDoc (2.1.5c).
538
+ // 1.2 QA-1.2-13: every verification spawn passes lowPriority, and specs pass spec.env
539
+ // (2.1.2.2). Specs use runArgv; full and legacy commands use runShell (2.1.2.2/.4/.5).
540
+ // 1.3 QA-1.3-16: readResult on every path (P6). QA-1.3-17: complete false or collectionError
541
+ // are not comparable, and a rerun with 0 tests is unusable (T4.k, T5).
542
+ // PlannerFs: fs.promises.realpath, stat(p, { bigint: true }) mapped to FileStat, readdir,
543
+ // and a fileExists that accepts directories (2.1.3). TestSearchSeam over the ArgvSeam:
544
+ // `git -C <root> ls-files -z --cached --others --exclude-standard -- :(glob)**/<name>...`
545
+ // and `git -C <root> grep -l -z -F --untracked -e <needle> -- <globs>`; grep exit 1 -> [],
546
+ // any other failure or timeout -> undefined (2.1.3). previousPath from the porcelain rename
547
+ // source (tree.ts, 2.1.3). planRerun(deps.entry) with the live entry (T4.i). node comes
548
+ // from host.nodePath/PATH: never pass process.execPath (Bun 1.3.14 hosts the plugin).
549
+ // pytest specs keep the adapter's --rootdir (no rewriting of spec.args anywhere).
550
+ // 1.4 QA-1.4-18: one hold per scope, held across the recheck, never nested (P4, T8).
551
+ // onLost: a note "verification slot was reclaimed during the run" and a warning; the
552
+ // verdict stands. QA-1.4-19/31: max and waitMs come from the validated budget.
553
+ // 1.5 QA-1.5-7: inert allowlist (T4.f). QA-1.5-10: GC before materialize, both inside the
554
+ // hold (T4.c/d); gcStaleReferences at plugin start (2.1.5b). QA-1.5-4: vanished ->
555
+ // unusable (T4.d/k). QA-1.5-25: 2.1 passes no per-call maxBuffer; a future one must be
556
+ // Math.floor'ed. materialize failure -> unusable (T4.d).
557
+ // 1.6 QA-1.6-13: previousPath (2.1.3). QA-1.6-22: TreeSnapshot.root = realpath of
558
+ // `git rev-parse --show-toplevel` (tree.ts, 2.1.3); 2.4 passes it as the risk root.
559
+ // Tool-observed files never carry deletions: prepareVerification takes each path's status
560
+ // and previousPath from the current tree snapshot when it lists the path (2.1.3). 2.4
561
+ // parses only the orchestrator's prompt (not 2.1).
562
+ //
563
+ // -----------------------------------------------------------------------------------------------
564
+ // T10. IMPLEMENTATION TASKS (2.1.2-2.1.6; each <= ~20 tool calls; commit + push each green)
565
+ //
566
+ // Order: .1 -> 2.1.4 -> .2 -> .3 -> .4 -> 2.1.3a -> 2.1.3b (cut-over) -> .5 -> 2.1.5a/b/c
567
+ // -> 2.1.6a/b/c. Tests run scoped: npx vitest run <files>.
568
+ //
569
+ // 2.1.2.1 deterministic.ts: export createDeadline(budgetMs, { now? }): Deadline & { abort(reason?:
570
+ // string): void; dispose(): void }, deriveDeadline(parent, ownMs): Deadline,
571
+ // RECHECK_MIN_REMAINING_MS = 10_000, INERT_UNREPRODUCED + isInertUnreproduced(entry,
572
+ // platform), fileKeyOfId(id). Tests: test/unit/tests-pass-pipeline.test.ts (new),
573
+ // fake timers: bound/remaining/abort/dispose, derive never exceeds the parent.
574
+ // 2.1.4 baseline.ts: export judgeScoped: JudgeScoped per T5/T6/T7. Keep observeTests;
575
+ // the legacy comparator stays until the cut-over deletes it. Tests: a table-driven block in
576
+ // test/unit/baseline.test.ts with one case per T6 cell, T5 classification edge cases
577
+ // (bare ids, text source, absent files, id-level vs file-level) and the <ids> cap.
578
+ // 2.1.2.2 deterministic.ts: export createScopeOpener(deps: { argv: ArgvSeam; exec: ExecSeam;
579
+ // fs: RunnerFs; acquire?: typeof acquireSlot; budget: VerifyBudget; checkTimeoutMs:
580
+ // number; host?: Partial<RunnerHost>; logger? }) returning an OpenVerificationScope
581
+ // whose scopes also offer the 2.1-internal runShell(command, cwd, deadline) and
582
+ // runLint(spec, deadline) (a CheckScope interface in deterministic.ts). execute per
583
+ // P4-P6. Tests: busy, deadlineCut, abort before spawn (zero spawns), timeout (the argv
584
+ // seam sees an aborted signal), a spawn throw still unlinks the report, onLost note,
585
+ // lowPriority and env reach the seam, one acquire across several execute calls.
586
+ // 2.1.2.3 deterministic.ts: the Rechecker behind scope.rechecker(command, cwd), steps T4.a-l,
587
+ // with injectable materialize/gc/detectRunner/resolveEntry/planRerun seams (defaults
588
+ // from reference.ts/runner.ts) and dispose tracking in close(). Tests: every
589
+ // RecheckOutcome kind and cause, GC-before-materialize order, no rerun for approximate,
590
+ // non-inert unreproduced and pytest, the vanished dir, disposal before release.
591
+ // 2.1.2.4 deterministic.ts: export createDirectTestsPassHook(deps): TestsPassHook (P2, P3,
592
+ // P5f, then the T4 pre-decisions and the recheck, then close). Tests: planning outcomes
593
+ // spawn nothing, full mode runs once with the synthesized RunResult, green -> no
594
+ // Rechecker call, failures -> exactly one.
595
+ // 2.1.3a tree.ts: keep the rename source as previousPath; add root (realpath of
596
+ // show-toplevel). dispatch.ts: TreeSnapshot gains root; ChangedFile gains
597
+ // previousPath?. Additive. Tests: extend test/unit/baseline-wiring.test.ts snapshot cases.
598
+ // 2.1.3b CUT-OVER, one commit: DeterministicDeps (types.ts, outside the 2.1.1 block) drops
599
+ // the dispatch-time baseline hook and gains testsPass?: TestsPassHook, openScope?, argv?, changedFiles?,
600
+ // reference?, budget?, deadline? (a missing hook -> testsPass unverifiable, G5).
601
+ // runCommandCheck's testsPass branch calls deps.testsPass, then judgeScoped, outside
602
+ // the mutex. dispatch.ts: the store keeps bySession/delta/record/observeEdit/sweep,
603
+ // replaces cache/baselines/baseline() with a per-dispatch Promise<ReferenceState> made
604
+ // by an injected capture, and observeEdit contaminates an in-flight capture. wiring.ts:
605
+ // beginVerification is async (capture only for a testsPass DoD with failureRecheck
606
+ // on); prepareVerification(store, id, childID, cwd, deadline) returns { changedFiles:
607
+ // ChangedPath[], changeBaseline, reference: ReferenceState, snapshot }; buildGateDeps
608
+ // takes the deadline and wires the hook, the scope opener, the PlannerFs and the
609
+ // TestSearchSeam. index.ts: only the two lines that set the dispatch-time baseline
610
+ // change. Delete the legacy comparator and its baseline type. Update
611
+ // baseline(-wiring).test.ts for the removed APIs.
612
+ // 2.1.2.5 deterministic.ts: buildPasses, lintClean (planScopedLint) and run through per-check
613
+ // scopes (T8). Tests: the slot is taken once per check, never nested; lint scoping.
614
+ // 2.1.5a index.ts: a Deadline + AbortController per gate in both sites; the native task
615
+ // accept() gets the same withTimeout + abort + unverifiableGateResult as delegate.
616
+ // 2.1.5b index.ts: await beginVerification for at most captureWaitMs in the task before-hook
617
+ // and the delegate dispatch; call gcStaleReferences once at plugin start
618
+ // (fire-and-forget, failures logged).
619
+ // 2.1.5c config.ts: clamp captureWaitMs to baselineTimeoutMs; slotWaitMs JSDoc gets the
620
+ // QA-1.4-21 residual. index.ts: resolveVerifyBudget for gateBudgetMs; drop the
621
+ // DEFAULT_GATE_BUDGET_MS import; warnDeprecatedVerifyKeys after every loadConfig().
622
+ // tiers.json: drop gateBudgetMs. Tests: the clamp, and a warning on reload.
623
+ // 2.1.6a test/unit/baseline.test.ts: rewrite to the new model, keeping the escalation
624
+ // assertions (a rejected verdict still climbs the ladder exactly as before).
625
+ // 2.1.6b test/unit/baseline-wiring.test.ts: read-only dispatch (no reference, no command);
626
+ // implementation dispatch (a reference, zero test commands); bounded capture wait (2 s
627
+ // -> 2 s, 20 s -> 5 s and still usable); contamination; a throwing capture; retry reuses
628
+ // the first reference; failureRecheck false (or the deprecated dispatch-time baseline key false): no capture, no
629
+ // worktree ever.
630
+ // 2.1.6c test/unit/tests-pass-pipeline.test.ts: the plan's deadline cases (5 s budget cuts a
631
+ // 60 s slot wait; 8 s left skips the recheck; no step outlives the deadline, by seam
632
+ // timestamps), the native task budget, the gate abort killing the tree, full mode, and
633
+ // the acceptance greps (no dispatch-time run; every spawned argv is scoped).
634
+ //
635
+ // -----------------------------------------------------------------------------------------------
636
+ // T11. RESIDUAL RISKS (accepted; QA may challenge)
637
+ //
638
+ // - Flaky tests: failing now and passing at the reference reads as introduced (as with 1.14).
639
+ // - Id identity only: a test failing at the reference and failing now for a new cause is
640
+ // preexisting. The note says the suite is not green.
641
+ // - A native `task` re-dispatch after a rejection captures a new reference that contains the
642
+ // failed attempt's changes. The router cannot link it to the earlier dispatch (the delegate
643
+ // ladder can, and keeps its first reference). The n2 note still names the failures and says
644
+ // the suite is not green. Candidate mitigation: 2.4's registry, which knows the orchestrator.
645
+ // - A vitest `related` run aborted by a syntax error writes no report: no file identity, so
646
+ // the result is unverifiable (u11), not a rejection.
647
+ // - Concurrent agents editing the same files: attribution is per session (ADR 0002 D3); a
648
+ // reference cannot separate two producers' changes to one file.
649
+ // ===============================================================================================
650
+
651
+ export { fileKeyOfId } from "./baseline";
652
+
653
+ /** T3: below this many milliseconds left, the Rechecker skips (u7) without materializing or spawning. */
654
+ export const RECHECK_MIN_REMAINING_MS = 10_000;
655
+
656
+ /** A Deadline plus its owner's controls (T3, plan 2.1.5.a). */
657
+ export interface OwnedDeadline extends Deadline {
658
+ /** Aborts `signal` now (the owner's withTimeout rejected). Idempotent. */
659
+ abort(reason?: string): void;
660
+ /** Clears the expiry timer; no timer outlives the gate. Idempotent. */
661
+ dispose(): void;
662
+ }
663
+
664
+ export interface DeadlineOptions {
665
+ /** Injected clock in ms; default Date.now. */
666
+ now?: () => number;
667
+ }
668
+
669
+ /** setTimeout clamps delays above this to 1 ms, so longer waits are chained. */
670
+ const MAX_TIMER_MS = 2_147_483_647;
671
+
672
+ function clampMs(ms: number): number {
673
+ return Number.isNaN(ms) ? 0 : Math.max(0, ms);
674
+ }
675
+
676
+ function makeDeadline(
677
+ budgetMs: number,
678
+ now: () => number,
679
+ parent: Deadline | undefined,
680
+ defaultReason: string,
681
+ ): OwnedDeadline {
682
+ const budget = clampMs(budgetMs);
683
+ const endsAt = now() + budget;
684
+ const controller = new AbortController();
685
+ let timer: ReturnType<typeof setTimeout> | undefined;
686
+ const ownLeft = (): number => Math.max(0, endsAt - now());
687
+ const clear = (): void => {
688
+ if (timer !== undefined) clearTimeout(timer);
689
+ timer = undefined;
690
+ };
691
+ const onParentAbort = (): void => abort("parent deadline aborted");
692
+ const abort = (reason?: string): void => {
693
+ clear();
694
+ parent?.signal.removeEventListener("abort", onParentAbort);
695
+ if (!controller.signal.aborted) controller.abort(new Error(reason ?? defaultReason));
696
+ };
697
+ const schedule = (): void => {
698
+ const left = ownLeft();
699
+ if (left === Infinity) return;
700
+ if (left <= 0) {
701
+ abort(defaultReason);
702
+ return;
703
+ }
704
+ timer = setTimeout(schedule, Math.min(left, MAX_TIMER_MS));
705
+ timer.unref?.();
706
+ };
707
+ const remaining = (): number => {
708
+ if (controller.signal.aborted) return 0;
709
+ return parent ? Math.min(ownLeft(), parent.remaining()) : ownLeft();
710
+ };
711
+ if (parent?.signal.aborted) {
712
+ abort("parent deadline aborted");
713
+ } else {
714
+ parent?.signal.addEventListener("abort", onParentAbort, { once: true });
715
+ schedule();
716
+ }
717
+ return {
718
+ budgetMs: budget,
719
+ remaining,
720
+ bound: (ownBudgetMs: number): number => Math.min(clampMs(ownBudgetMs), remaining()),
721
+ signal: controller.signal,
722
+ abort,
723
+ dispose: (): void => {
724
+ clear();
725
+ parent?.signal.removeEventListener("abort", onParentAbort);
726
+ },
727
+ };
728
+ }
729
+
730
+ /**
731
+ * One deadline per gate invocation or router_verify call (T3). Its signal aborts at expiry (the
732
+ * timer is unref'd) or on abort(); dispose() clears the timer.
733
+ */
734
+ export function createDeadline(budgetMs: number, opts: DeadlineOptions = {}): OwnedDeadline {
735
+ return makeDeadline(budgetMs, opts.now ?? Date.now, undefined, "gate budget exhausted");
736
+ }
737
+
738
+ /**
739
+ * A sub-deadline of `ownMs` that never outlives `parent` (T3 recheck sub-deadline): remaining() is
740
+ * min(own, parent), and its signal aborts at its own expiry or when the parent aborts.
741
+ */
742
+ export function deriveDeadline(parent: Deadline, ownMs: number, opts: DeadlineOptions = {}): OwnedDeadline {
743
+ return makeDeadline(Math.min(clampMs(ownMs), parent.remaining()), opts.now ?? Date.now, parent, "recheck budget exhausted");
744
+ }
745
+
746
+ /**
747
+ * Where an INERT_UNREPRODUCED pattern may sit (QA-2.1-10), relative to the reference root:
748
+ * - "root": only at the root itself (`logs/`, `debug.log`), never deeper, so an ignored
749
+ * `test/fixtures/logs/` or a `*.log` fixture a test reads is not inert;
750
+ * - "package": at the root or at a monorepo package root `<dir>/<pkg>/` (`packages/web/coverage/`),
751
+ * and never under a test or fixture directory;
752
+ * - "anywhere": caches and OS metadata that tools write beside every source and no test reads.
753
+ */
754
+ export type InertScope = "root" | "package" | "anywhere";
755
+
756
+ /**
757
+ * T4.f: `unreproduced` entries tests cannot read, each anchored by its InertScope. An entry matches
758
+ * a pattern exactly (a directory ends in "/"; "*.ext" matches a file name), case-insensitive on
759
+ * win32. Additions need evidence that tests cannot read them.
760
+ */
761
+ export const INERT_UNREPRODUCED_SCOPES: Readonly<Record<string, InertScope>> = {
762
+ "logs/": "root", ".idea/": "root", ".vscode/": "root", "*.log": "root", ".eslintcache": "root",
763
+ "coverage/": "package", ".nyc_output/": "package", ".pytest_cache/": "package",
764
+ ".mypy_cache/": "package", ".ruff_cache/": "package",
765
+ "__pycache__/": "anywhere", "*.pyc": "anywhere", ".DS_Store": "anywhere", "Thumbs.db": "anywhere",
766
+ "desktop.ini": "anywhere",
767
+ };
768
+
769
+ export const INERT_UNREPRODUCED: readonly string[] = Object.keys(INERT_UNREPRODUCED_SCOPES);
770
+
771
+ /** Directory names under which a "package" pattern is never inert: tests may read what is there. */
772
+ const TEST_DIR_NAMES = new Set([
773
+ "test", "tests", "__tests__", "spec", "specs", "fixtures", "__fixtures__", "testdata", "test-data", "__snapshots__",
774
+ ]);
775
+
776
+ export function isInertUnreproduced(entry: string, platform: string): boolean {
777
+ const normalized = entry.replace(/\\/g, "/");
778
+ const isDir = normalized.endsWith("/");
779
+ const segments = normalized.split("/").filter(s => s !== "");
780
+ const last = segments[segments.length - 1];
781
+ if (last === undefined) return false;
782
+ const fold = (s: string): string => (platform === "win32" ? s.toLowerCase() : s);
783
+ const name = fold(last);
784
+ const parents = segments.slice(0, -1).map(fold);
785
+ const inScope = (scope: InertScope): boolean => {
786
+ if (scope === "anywhere") return true;
787
+ if (parents.length === 0) return true;
788
+ return scope === "package" && parents.length === 2 && !parents.some(s => TEST_DIR_NAMES.has(s));
789
+ };
790
+ for (const [raw, scope] of Object.entries(INERT_UNREPRODUCED_SCOPES)) {
791
+ const pattern = fold(raw);
792
+ let matches = false;
793
+ if (pattern.endsWith("/")) {
794
+ matches = isDir && `${name}/` === pattern;
795
+ } else if (!isDir) {
796
+ if (pattern.startsWith("*.")) {
797
+ const ext = pattern.slice(1);
798
+ matches = name.length > ext.length && name.endsWith(ext);
799
+ } else {
800
+ matches = name === pattern;
801
+ }
802
+ }
803
+ if (matches && inScope(scope)) return true;
804
+ }
805
+ return false;
806
+ }
807
+
808
+ // -----------------------------------------------------------------------------------------------
809
+ // Verification scopes (2.1.2.2): S3 slot, S4 caps, run and readResult (T2 P4-P6, P9)
810
+ // -----------------------------------------------------------------------------------------------
811
+
812
+ /** T7 u13 / P5: the stable abort phrases. */
813
+ export const ABORTED_BEFORE_RUN = "gate budget exhausted before the scoped run";
814
+ export const ABORTED_DURING_RUN = "gate budget exhausted during the scoped run";
815
+ /** T9 1.4: the note on an outcome whose slot was reclaimed while it ran. */
816
+ export const SLOT_LOST_NOTE = "verification slot was reclaimed during the run";
817
+
818
+ /** What a non-spec command (buildPasses, run, lint, testScope "full") produced under a scope. */
819
+ export type CommandOutcome =
820
+ | Extract<ScopedOutcome, { kind: "slot-busy" | "aborted" | "error" }>
821
+ | { readonly kind: "ran"; readonly exec: ExecResult; readonly notes: readonly string[] }
822
+ | { readonly kind: "timed-out"; readonly boundMs: number; readonly exec: ExecResult };
823
+
824
+ /** A VerificationScope plus the 2.1-internal non-spec runs (P5f, T8), all under the same hold. */
825
+ export interface CheckScope extends VerificationScope {
826
+ /** The resolved command through the shell seam (user text keeps shell + allowlist). Never rejects. */
827
+ runShell(command: string, cwd: string, deadline: Deadline): Promise<CommandOutcome>;
828
+ /** A scoped eslint spec through the argv seam. Never rejects. */
829
+ runLint(spec: LintSpec, deadline: Deadline): Promise<CommandOutcome>;
830
+ /**
831
+ * VerificationScope.rechecker plus the current tree snapshot, forwarded to materialize so it can
832
+ * detect drift since the snapshot (T4.d). Omitted -> materialize gets undefined.
833
+ */
834
+ rechecker(command: string, cwd: string, currentTree?: TreeSnapshot): Rechecker;
835
+ /**
836
+ * P4's hold, taken without running anything: the scope's one hold attempt, waiting at most
837
+ * deadline.bound(slotWaitMs). true when the scope holds the slot. It is the same memoized
838
+ * attempt as the first execute's, so a later execute reuses the hold (or its failure) and never
839
+ * takes a second one. For 2.2's batch coordinator (QA-2.2-25), which decides what to run only
840
+ * once it holds the slot. Never rejects. Optional: createScopeOpener's scopes have it.
841
+ */
842
+ hold?(deadline: Deadline): Promise<boolean>;
843
+ }
844
+
845
+ export type OpenCheckScope = (meta: Parameters<OpenVerificationScope>[0]) => CheckScope;
846
+
847
+ export interface ScopeOpenerDeps {
848
+ argv: ArgvSeam;
849
+ exec: ExecSeam;
850
+ fs: RunnerFs;
851
+ acquire?: typeof acquireSlot;
852
+ budget: VerifyBudget;
853
+ /** deps.timeoutMs ?? 120000 (P5). */
854
+ checkTimeoutMs: number;
855
+ host?: Partial<RunnerHost>;
856
+ logger?: Pick<PluginLogger, "warn">;
857
+ /** Clock for slot-busy waitedMs and the recheck sub-deadline; default Date.now. */
858
+ now?: () => number;
859
+ /** Reference seams for the recheck (T4); argv defaults to `argv`, fs to node:fs/promises, logger to `logger`. */
860
+ reference?: Partial<ReferenceDeps>;
861
+ /** T4 seams; each defaults to the reference.ts / runner.ts function of the same name. */
862
+ recheck?: Partial<RecheckSeams>;
863
+ }
864
+
865
+ /** The injectable steps of the T4 Rechecker (2.1.2.3). */
866
+ export interface RecheckSeams {
867
+ materialize: typeof materialize;
868
+ gcStaleReferences: typeof gcStaleReferences;
869
+ detectRunner: typeof detectRunner;
870
+ resolveEntry: typeof resolveEntry;
871
+ planRerun: typeof planRerun;
872
+ readResult: typeof readResult;
873
+ }
874
+
875
+ /** T4.c: GC's own bound inside the recheck sub-deadline. */
876
+ const RECHECK_GC_MS = 5_000;
877
+ /** How many non-inert `unreproduced` entries the T4.f reason names. */
878
+ const MAX_NAMED_UNREPRODUCED = 5;
879
+
880
+ function unusable(cause: RecheckUnusableCause, reason: string): RecheckOutcome {
881
+ return { kind: "unusable", cause, reason: scrubText(reason) };
882
+ }
883
+
884
+ type Blocked = Extract<ScopedOutcome, { kind: "slot-busy" | "aborted" | "error" }>;
885
+ type Hold = { readonly ok: true; readonly handle: SlotHandle } | { readonly ok: false; readonly outcome: Blocked };
886
+ interface Spawned {
887
+ readonly kind: "spawned";
888
+ readonly exec: ExecResult;
889
+ /** Set when the seam threw; exec is then the synthesized { code: -1, stderr: <message> }. */
890
+ readonly threw?: string;
891
+ readonly boundMs: number;
892
+ /** The deadline's signal had aborted by the time the run ended. */
893
+ readonly cut: boolean;
894
+ readonly notes: readonly string[];
895
+ }
896
+
897
+ function errorText(err: unknown): string {
898
+ return scrubText(err instanceof Error ? err.message : String(err));
899
+ }
900
+
901
+ function toCommandOutcome(a: Blocked | Spawned): CommandOutcome {
902
+ if (a.kind !== "spawned") return a;
903
+ if (a.threw !== undefined) return { kind: "error", reason: `command failed to start: ${a.threw}` };
904
+ if (a.exec.timedOut) {
905
+ return a.cut ? { kind: "aborted", reason: "gate budget exhausted during the run" } : { kind: "timed-out", boundMs: a.boundMs, exec: a.exec };
906
+ }
907
+ return { kind: "ran", exec: a.exec, notes: a.notes };
908
+ }
909
+
910
+ /**
911
+ * P4-P6, P9: each opened scope takes at most one slot hold (lazily, on its first run; never nested,
912
+ * QA-1.4-18), runs every process at low priority under the deadline, calls readResult after every
913
+ * spec spawn attempt (QA-1.3-16) and releases the hold on close(). Nothing here rejects.
914
+ */
915
+ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
916
+ const { argv, exec, fs, budget, checkTimeoutMs, host, logger } = deps;
917
+ const acquire = deps.acquire ?? acquireSlot;
918
+ const now = deps.now ?? Date.now;
919
+ const seams: RecheckSeams = {
920
+ materialize: deps.recheck?.materialize ?? materialize,
921
+ gcStaleReferences: deps.recheck?.gcStaleReferences ?? gcStaleReferences,
922
+ detectRunner: deps.recheck?.detectRunner ?? detectRunner,
923
+ resolveEntry: deps.recheck?.resolveEntry ?? resolveEntry,
924
+ planRerun: deps.recheck?.planRerun ?? planRerun,
925
+ readResult: deps.recheck?.readResult ?? readResult,
926
+ };
927
+ const refDeps: ReferenceDeps = {
928
+ ...deps.reference,
929
+ argv: deps.reference?.argv ?? argv,
930
+ fs: deps.reference?.fs ?? nodeReferenceFs,
931
+ ...(deps.reference?.logger === undefined && logger !== undefined ? { logger } : {}),
932
+ };
933
+ const P = (host?.platform ?? process.platform) === "win32" ? pathWin32 : pathPosix;
934
+ /** Id-space file key (T4): cwd-relative with "/" separators, as readResult builds ids. */
935
+ const fileKey = (cwd: string, abs: string): string => P.relative(cwd, abs).split(P.sep).join("/");
936
+
937
+ return (meta): CheckScope => {
938
+ let holdP: Promise<Hold> | undefined;
939
+ let lost = false;
940
+ let closed = false;
941
+ let closing: Promise<void> | undefined;
942
+ const inflight = new Set<Promise<unknown>>();
943
+
944
+ const onLost = (): void => {
945
+ lost = true;
946
+ logger?.warn(`${SLOT_LOST_NOTE}: ${scrubText(meta.command)}`);
947
+ };
948
+
949
+ const acquireHold = async (deadline: Deadline): Promise<Hold> => {
950
+ if (deadline.signal.aborted || deadline.remaining() === 0) {
951
+ return { ok: false, outcome: { kind: "slot-busy", waitedMs: 0, deadlineCut: true } };
952
+ }
953
+ const started = now();
954
+ // The deadline bounds the wait when it leaves less than slotWaitMs: a busy answer then ends
955
+ // at the deadline, even when the wait's own timer fires a few ms before remaining() reads 0.
956
+ const waitMs = deadline.bound(budget.slotWaitMs);
957
+ const cutByDeadline = waitMs < budget.slotWaitMs;
958
+ try {
959
+ const r = await acquire({
960
+ max: budget.maxConcurrentVerifications,
961
+ waitMs,
962
+ signal: deadline.signal,
963
+ meta: { cwd: meta.cwd, command: meta.command },
964
+ onLost,
965
+ });
966
+ if ("busy" in r) {
967
+ return {
968
+ ok: false,
969
+ outcome: { kind: "slot-busy", waitedMs: Math.max(0, now() - started), deadlineCut: cutByDeadline || deadline.remaining() === 0 },
970
+ };
971
+ }
972
+ return { ok: true, handle: r };
973
+ } catch (err) {
974
+ return { ok: false, outcome: { kind: "error", reason: `verification slot failed: ${errorText(err)}` } };
975
+ }
976
+ };
977
+
978
+ const attempt = async (
979
+ deadline: Deadline,
980
+ launch: (opts: ExecOptions) => Promise<ExecResult>,
981
+ ownMs: number = checkTimeoutMs,
982
+ ): Promise<Blocked | Spawned> => {
983
+ if (closed) return { kind: "error", reason: "verification scope already closed" };
984
+ holdP ??= acquireHold(deadline);
985
+ const hold = await holdP;
986
+ if (!hold.ok) return hold.outcome;
987
+ const boundMs = deadline.bound(ownMs);
988
+ if (deadline.signal.aborted || boundMs <= 0) return { kind: "aborted", reason: ABORTED_BEFORE_RUN };
989
+
990
+ // A per-run signal linked to the deadline: aborting it after a timeout or a failed spawn
991
+ // makes the seam kill whatever tree is left (T3).
992
+ const run = new AbortController();
993
+ const onAbort = (): void => run.abort(deadline.signal.reason);
994
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
995
+ let execResult: ExecResult;
996
+ let threw: string | undefined;
997
+ try {
998
+ execResult = await launch({ lowPriority: budget.lowPriority, signal: run.signal, timeoutMs: boundMs });
999
+ } catch (err) {
1000
+ threw = errorText(err);
1001
+ execResult = { code: -1, stdout: "", stderr: threw };
1002
+ }
1003
+ deadline.signal.removeEventListener("abort", onAbort);
1004
+ if (threw !== undefined || execResult.timedOut === true) {
1005
+ run.abort(new Error(threw ?? `run exceeded its ${boundMs}ms bound`));
1006
+ }
1007
+ return {
1008
+ kind: "spawned",
1009
+ exec: execResult,
1010
+ ...(threw !== undefined ? { threw } : {}),
1011
+ boundMs,
1012
+ cut: deadline.signal.aborted,
1013
+ notes: lost || hold.handle.lost ? [SLOT_LOST_NOTE] : [],
1014
+ };
1015
+ };
1016
+
1017
+ const track = <T>(p: Promise<T>): Promise<T> => {
1018
+ inflight.add(p);
1019
+ void p.finally(() => inflight.delete(p));
1020
+ return p;
1021
+ };
1022
+
1023
+ const runSpec = async (spec: Parameters<ScopedExecutor>[0], deadline: Deadline): Promise<ScopedOutcome> => {
1024
+ try {
1025
+ const a = await attempt(deadline, opts => argv(spec.file, spec.args, { ...opts, cwd: spec.cwd, env: { ...spec.env } }));
1026
+ if (a.kind !== "spawned") return a;
1027
+ let result: RunResult;
1028
+ try {
1029
+ // P6: on EVERY path after a spawn attempt; it deletes the report file (QA-1.3-16).
1030
+ result = await readResult(spec, a.exec, fs, host);
1031
+ } catch (err) {
1032
+ return { kind: "error", reason: `reading the scoped result failed: ${errorText(err)}` };
1033
+ }
1034
+ if (a.threw !== undefined) return { kind: "error", reason: `scoped run failed to start: ${a.threw}` };
1035
+ if (a.exec.timedOut) {
1036
+ return a.cut ? { kind: "aborted", reason: ABORTED_DURING_RUN } : { kind: "timed-out", boundMs: a.boundMs, result };
1037
+ }
1038
+ const notes = [...spec.notes, ...a.notes, ...(result.note !== undefined ? [result.note] : [])];
1039
+ return { kind: "ran", result, exitCode: a.exec.code, spec, notes };
1040
+ } catch (err) {
1041
+ return { kind: "error", reason: `scoped run errored: ${errorText(err)}` };
1042
+ }
1043
+ };
1044
+
1045
+ const runCommand = async (deadline: Deadline, launch: (opts: ExecOptions) => Promise<ExecResult>): Promise<CommandOutcome> => {
1046
+ try {
1047
+ return toCommandOutcome(await attempt(deadline, launch));
1048
+ } catch (err) {
1049
+ return { kind: "error", reason: `command errored: ${errorText(err)}` };
1050
+ }
1051
+ };
1052
+
1053
+ // T4.e-k at a materialized reference. The caller disposes it.
1054
+ const rerunAt = async (
1055
+ ref: MaterializedReference,
1056
+ runner: DetectedRunner,
1057
+ liveCwd: string,
1058
+ failingFiles: readonly string[],
1059
+ rd: Deadline,
1060
+ ): Promise<RecheckOutcome> => {
1061
+ if (!ref.exact) return { kind: "approximate", inexactReasons: ref.inexactReasons };
1062
+ const platform = host?.platform ?? process.platform;
1063
+ const hidden = ref.unreproduced.filter(e => !isInertUnreproduced(e, platform));
1064
+ if (hidden.length > 0) {
1065
+ const named = hidden.slice(0, MAX_NAMED_UNREPRODUCED).join(", ");
1066
+ const more = hidden.length > MAX_NAMED_UNREPRODUCED ? ` and ${hidden.length - MAX_NAMED_UNREPRODUCED} more` : "";
1067
+ return unusable("unreproduced-inputs", `the reference lacks ignored inputs tests may read: ${named}${more}`);
1068
+ }
1069
+
1070
+ const rerunList: string[] = [];
1071
+ const absentFiles: string[] = [];
1072
+ for (const f of failingFiles) {
1073
+ const r = ref.toRefPath(f);
1074
+ if (r === undefined) continue; // outside the root: stays unclassified (T4.g)
1075
+ if (await fs.fileExists(r)) rerunList.push(r);
1076
+ else absentFiles.push(fileKey(runner.runnerCwd, f));
1077
+ }
1078
+ if (rerunList.length === 0) return { kind: "exact", result: undefined, ranFiles: [], absentFiles, notes: [] };
1079
+
1080
+ // E2E-2: from runner.runnerCwd, the canonical start the scoped plan resolved its own entry
1081
+ // from (runner.ts planScopedRun). liveCwd is the request's spelling (the plugin directory
1082
+ // may be an 8.3 short path); resolveEntry canonicalises it too.
1083
+ const entry = await seams.resolveEntry(runner, runner.runnerCwd, fs, host);
1084
+ if (isUnverifiable(entry)) return unusable("rerun-unplannable", entry.reason);
1085
+ const refCwd = ref.toRefPath(runner.runnerCwd);
1086
+ if (refCwd === undefined) return unusable("rerun-unplannable", "the runner cwd is outside the reference root");
1087
+ const spec = await seams.planRerun(runner, rerunList, refCwd, { maxWorkers: budget.maxWorkers }, {
1088
+ fs,
1089
+ entry,
1090
+ ...(host !== undefined ? { host } : {}),
1091
+ });
1092
+ if (isUnverifiable(spec)) return unusable("rerun-unplannable", spec.reason);
1093
+ if ("noAffected" in spec) return unusable("rerun-unplannable", `the rerun planned nothing: ${spec.note}`);
1094
+
1095
+ const a = await attempt(
1096
+ rd,
1097
+ opts => argv(spec.file, spec.args, { ...opts, cwd: spec.cwd, env: { ...spec.env } }),
1098
+ budget.recheckTimeoutMs,
1099
+ );
1100
+ if (a.kind === "aborted") return { kind: "skipped-deadline", remainingMs: rd.remaining() };
1101
+ if (a.kind === "slot-busy") return unusable("error", "the verification slot was not available for the recheck");
1102
+ if (a.kind === "error") return unusable("error", a.reason);
1103
+ let result: RunResult;
1104
+ try {
1105
+ // P6: on every path after a spawn attempt; it deletes the report file (QA-1.3-16).
1106
+ result = await seams.readResult(spec, a.exec, fs, host);
1107
+ } catch (err) {
1108
+ return unusable("error", `reading the recheck result failed: ${errorText(err)}`);
1109
+ }
1110
+ if (a.threw !== undefined) return unusable("error", `the recheck failed to start: ${a.threw}`);
1111
+ if (a.exec.timedOut === true) return { kind: "timed-out", boundMs: a.boundMs };
1112
+ try {
1113
+ await refDeps.fs.lstat(ref.dir);
1114
+ } catch (err) {
1115
+ return unusable("reference-vanished", `the reference worktree vanished during the rerun: ${errorText(err)}`);
1116
+ }
1117
+ if (!result.complete) return unusable("incomplete", result.note ?? "the rerun at the reference reported an incomplete result");
1118
+ if (result.collectionError) return unusable("collection-error", "the rerun at the reference failed to collect its tests");
1119
+ if (result.total === 0) return unusable("no-tests", "the rerun at the reference ran no tests");
1120
+ return {
1121
+ kind: "exact",
1122
+ result,
1123
+ ranFiles: rerunList.map(r => fileKey(spec.cwd, r)),
1124
+ absentFiles,
1125
+ notes: [...a.notes, ...(result.note !== undefined ? [result.note] : [])],
1126
+ };
1127
+ };
1128
+
1129
+ // T4.a-l. The hook decides "disabled" and "none" before calling this.
1130
+ const recheck = async (
1131
+ command: string,
1132
+ liveCwd: string,
1133
+ reference: DispatchReference,
1134
+ failingFiles: readonly string[],
1135
+ deadline: Deadline,
1136
+ currentTree: TreeSnapshot | undefined,
1137
+ ): Promise<RecheckOutcome> => {
1138
+ const remainingMs = deadline.remaining();
1139
+ if (remainingMs < RECHECK_MIN_REMAINING_MS) return { kind: "skipped-deadline", remainingMs };
1140
+ const runner = await seams.detectRunner(command, liveCwd, fs, host);
1141
+ if (isUnverifiable(runner)) return unusable("rerun-unplannable", runner.reason);
1142
+ if (runner.kind === "pytest") {
1143
+ return unusable("runner-unsupported", "pytest cannot be pinned to the reference: an editable install imports the live sources");
1144
+ }
1145
+ if (closed) return unusable("error", "verification scope already closed");
1146
+ holdP ??= acquireHold(deadline);
1147
+ const hold = await holdP;
1148
+ if (!hold.ok) {
1149
+ return unusable("error", hold.outcome.kind === "error" ? hold.outcome.reason : "the verification slot was not available for the recheck");
1150
+ }
1151
+
1152
+ const rd = deriveDeadline(deadline, budget.recheckTimeoutMs, { now });
1153
+ try {
1154
+ // QA-1.5-10: GC, then materialize, both inside the hold.
1155
+ const gc = await seams.gcStaleReferences(reference.root, { ...refDeps, timeoutMs: rd.bound(RECHECK_GC_MS) });
1156
+ if (gc.removed.length > 0 || gc.failed.length > 0) {
1157
+ logger?.warn(`reference GC removed ${gc.removed.length}, failed ${gc.failed.length}`);
1158
+ }
1159
+ if (rd.signal.aborted || rd.remaining() === 0) return { kind: "skipped-deadline", remainingMs: rd.remaining() };
1160
+ const m = await seams.materialize(reference, currentTree, rd.signal, {
1161
+ ...refDeps,
1162
+ timeoutMs: rd.bound(DEFAULT_MATERIALIZE_TIMEOUT_MS),
1163
+ });
1164
+ if (!m.ok) {
1165
+ return m.reason === "commit-missing"
1166
+ ? unusable("reference-vanished", `the reference commit is gone: ${m.detail}`)
1167
+ : unusable("materialize-failed", `materialize ${m.reason}: ${m.detail}`);
1168
+ }
1169
+ const ref = m.reference;
1170
+ try {
1171
+ return await rerunAt(ref, runner, liveCwd, failingFiles, rd);
1172
+ } finally {
1173
+ // T4.l: the rerun tree has exited here; close() waits for this before releasing the slot.
1174
+ track(ref.dispose().catch((err: unknown) => logger?.warn(`reference dispose failed: ${errorText(err)}`)));
1175
+ }
1176
+ } finally {
1177
+ rd.dispose();
1178
+ }
1179
+ };
1180
+
1181
+ const rechecker = (command: string, liveCwd: string, currentTree?: TreeSnapshot): Rechecker => (reference, failingFiles, deadline) =>
1182
+ track(
1183
+ recheck(command, liveCwd, reference, failingFiles, deadline, currentTree).catch(
1184
+ (err: unknown): RecheckOutcome => unusable("error", `the reference recheck errored: ${errorText(err)}`),
1185
+ ),
1186
+ );
1187
+
1188
+ const close = (): Promise<void> => {
1189
+ closing ??= (async (): Promise<void> => {
1190
+ closed = true;
1191
+ // Loop: a recheck settling here tracks its reference disposal (T4.l, P9).
1192
+ while (inflight.size > 0) await Promise.allSettled([...inflight]);
1193
+ if (holdP === undefined) return;
1194
+ const hold = await holdP;
1195
+ if (!hold.ok) return;
1196
+ try {
1197
+ await hold.handle.release();
1198
+ } catch (err) {
1199
+ logger?.warn(`verification slot release failed: ${errorText(err)}`);
1200
+ }
1201
+ })();
1202
+ return closing;
1203
+ };
1204
+
1205
+ const hold = (deadline: Deadline): Promise<boolean> =>
1206
+ track(
1207
+ (async (): Promise<boolean> => {
1208
+ if (closed) return false;
1209
+ holdP ??= acquireHold(deadline);
1210
+ return (await holdP).ok;
1211
+ })(),
1212
+ );
1213
+
1214
+ return {
1215
+ execute: (spec, deadline) => track(runSpec(spec, deadline)),
1216
+ hold,
1217
+ rechecker,
1218
+ runShell: (command, cwd, deadline) => track(runCommand(deadline, opts => exec(command, { ...opts, cwd }))),
1219
+ runLint: (spec, deadline) =>
1220
+ track(runCommand(deadline, opts => argv(spec.file, spec.args, { ...opts, cwd: spec.cwd, env: { ...spec.env } }))),
1221
+ close,
1222
+ };
1223
+ };
1224
+ }
1225
+
1226
+ // -----------------------------------------------------------------------------------------------
1227
+ // The direct testsPass hook (2.1.2.4): P2, P3, P4-P6/P5f, the T4 pre-decisions, P7, P9
1228
+ // -----------------------------------------------------------------------------------------------
1229
+
1230
+ export interface DirectTestsPassHookDeps {
1231
+ openScope: OpenCheckScope;
1232
+ /** Built in wiring.ts (2.1.3, T9). */
1233
+ plannerFs: PlannerFs;
1234
+ search: TestSearchSeam;
1235
+ budget: Pick<VerifyBudget, "maxWorkers" | "failureRecheck">;
1236
+ host?: Partial<RunnerHost>;
1237
+ /** The gate's current tree snapshot, forwarded to materialize for drift detection (T4.d). */
1238
+ currentTree?: TreeSnapshot;
1239
+ /** Planner seam; default planScopedRun. */
1240
+ plan?: typeof planScopedRun;
1241
+ logger?: Pick<PluginLogger, "warn">;
1242
+ }
1243
+
1244
+ /** P5f: the note on a full-suite result whose text parse was not confident. */
1245
+ export const FULL_OUTPUT_INCOMPLETE_NOTE = "the full test output could not be parsed into a complete failure inventory";
1246
+
1247
+ /**
1248
+ * P5f: a RunResult from the full command's text output (observeTests). Failing files are the id
1249
+ * file parts resolved against cwd, kept only when they exist in the live tree: a key that is not a
1250
+ * real file must never reach the recheck, where a missing file would read as "added since dispatch".
1251
+ */
1252
+ async function synthesizeFullResult(
1253
+ exec: ExecResult,
1254
+ cwd: string,
1255
+ fs: PlannerFs,
1256
+ host: Partial<RunnerHost> | undefined,
1257
+ ): Promise<RunResult> {
1258
+ const obs = observeTests(exec);
1259
+ const P = (host?.platform ?? process.platform) === "win32" ? pathWin32 : pathPosix;
1260
+ const failingIds = [...new Set(obs.failures)].sort();
1261
+ const files = new Set<string>();
1262
+ for (const id of failingIds) {
1263
+ const abs = P.resolve(cwd, fileKeyOfId(id));
1264
+ if (await fs.fileExists(abs)) files.add(abs);
1265
+ }
1266
+ return {
1267
+ failingIds,
1268
+ failingFiles: [...files].sort(),
1269
+ collectionError: exec.code !== 0 && failingIds.length === 0,
1270
+ total: undefined,
1271
+ complete: obs.complete,
1272
+ source: "text",
1273
+ ...(obs.complete ? {} : { note: FULL_OUTPUT_INCOMPLETE_NOTE }),
1274
+ };
1275
+ }
1276
+
1277
+ /**
1278
+ * S5 as a direct call (2.1.2.4; 2.2 swaps in the batch coordinator): plan, run under ONE scope,
1279
+ * recheck the failing files at the dispatch reference, close the scope. Never rejects.
1280
+ */
1281
+ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsPassHook {
1282
+ const plan = deps.plan ?? planScopedRun;
1283
+
1284
+ // P5f: the resolved command as written, through the scope's shell seam (low priority, deadline-bound).
1285
+ const runFull = async (req: TestsPassRequest, scope: CheckScope): Promise<ScopedOutcome> => {
1286
+ const out = await scope.runShell(req.command, req.cwd, req.deadline);
1287
+ if (out.kind === "timed-out") return { kind: "timed-out", boundMs: out.boundMs };
1288
+ if (out.kind !== "ran") return out;
1289
+ const result = await synthesizeFullResult(out.exec, req.cwd, deps.plannerFs, deps.host);
1290
+ const notes = [...out.notes, ...(result.note !== undefined ? [result.note] : [])];
1291
+ return { kind: "ran", result, exitCode: out.exec.code, notes };
1292
+ };
1293
+
1294
+ const recheckFor = async (req: TestsPassRequest, scope: CheckScope, scoped: ScopedOutcome): Promise<RecheckOutcome | undefined> => {
1295
+ // P7: only a run with >= 1 failing id and >= 1 failing file (T4).
1296
+ if (scoped.kind !== "ran" || scoped.result.failingIds.length === 0 || scoped.result.failingFiles.length === 0) return undefined;
1297
+ const ref = req.reference;
1298
+ if (ref.kind === "disabled" || !deps.budget.failureRecheck) return { kind: "disabled" };
1299
+ if (ref.kind === "none") return { kind: "unusable", cause: "no-reference", reason: ref.reason };
1300
+ return scope.rechecker(req.command, req.cwd, deps.currentTree)(ref.reference, scoped.result.failingFiles, req.deadline);
1301
+ };
1302
+
1303
+ return async (req): Promise<TestsPassRun> => {
1304
+ let scope: CheckScope | undefined;
1305
+ let scoped: ScopedOutcome | undefined;
1306
+ try {
1307
+ if (req.testScope === "full") {
1308
+ scope = deps.openScope({ cwd: req.cwd, command: req.command });
1309
+ scoped = await runFull(req, scope);
1310
+ } else {
1311
+ // P2/P3: planning outcomes take no slot and spawn nothing.
1312
+ const planned = await plan({
1313
+ command: req.command,
1314
+ cwd: req.cwd,
1315
+ changedFiles: req.changedFiles,
1316
+ budget: { maxWorkers: deps.budget.maxWorkers },
1317
+ fs: deps.plannerFs,
1318
+ search: deps.search,
1319
+ ...(deps.host !== undefined ? { host: deps.host } : {}),
1320
+ });
1321
+ if (isNoAffected(planned)) return { scoped: { kind: "no-affected", note: planned.note }, recheck: undefined };
1322
+ if (isUnverifiable(planned)) {
1323
+ return { scoped: { kind: "unverifiable", code: planned.code, reason: planned.reason }, recheck: undefined };
1324
+ }
1325
+ scope = deps.openScope({ cwd: req.cwd, command: req.command });
1326
+ scoped = await scope.execute(planned, req.deadline);
1327
+ }
1328
+ return { scoped, recheck: await recheckFor(req, scope, scoped) };
1329
+ } catch (err) {
1330
+ const reason = errorText(err);
1331
+ if (scoped !== undefined) return { scoped, recheck: { kind: "unusable", cause: "error", reason: `the reference recheck errored: ${reason}` } };
1332
+ return { scoped: { kind: "error", reason: `testsPass hook errored: ${reason}` }, recheck: undefined };
1333
+ } finally {
1334
+ if (scope !== undefined) await closeWithinDeadline(scope, req.deadline, deps.logger);
1335
+ }
1336
+ };
1337
+ }
1338
+
1339
+ /**
1340
+ * QA-2.1-13: how long before the gate deadline's end `closeWithinDeadline` stops waiting for a
1341
+ * close. The gate's `withTimeout` is armed with the same deadline's `remaining()`, so a wait that
1342
+ * ran to the exact end would race it, and a proven failure could become a gate timeout.
1343
+ */
1344
+ export const CLOSE_MARGIN_MS = 100;
1345
+
1346
+ /**
1347
+ * P9 (QA-2.1-3): waits for `scope.close()` only until `CLOSE_MARGIN_MS` before `deadline` is spent
1348
+ * (or its abort), so a reference dispose (EBUSY retries) never outlasts the gate budget and turns
1349
+ * a verdict into a gate timeout (QA-2.1-13: the margin keeps the wait clear of the gate's own
1350
+ * `withTimeout`, armed at the same end). The close carries on in the background after that: it
1351
+ * still releases the slot only once every tracked disposal and killed tree has settled, and its
1352
+ * failure is logged. A spent deadline also bars every later scope of the gate from acquiring a
1353
+ * slot (acquireHold), so an unfinished close never nests with another hold. Never rejects.
1354
+ */
1355
+ export function closeWithinDeadline(scope: CheckScope, deadline: Deadline, logger?: Pick<PluginLogger, "warn">): Promise<void> {
1356
+ const warn = (err: unknown): void => logger?.warn(`verification scope close failed: ${errorText(err)}`);
1357
+ let closing: Promise<void>;
1358
+ try {
1359
+ closing = scope.close().catch(warn);
1360
+ } catch (err) {
1361
+ warn(err);
1362
+ return Promise.resolve();
1363
+ }
1364
+ return new Promise<void>(settle => {
1365
+ let timer: ReturnType<typeof setTimeout> | undefined;
1366
+ const done = (): void => {
1367
+ if (timer !== undefined) clearTimeout(timer);
1368
+ timer = undefined;
1369
+ deadline.signal.removeEventListener("abort", done);
1370
+ settle();
1371
+ };
1372
+ void closing.then(done);
1373
+ const left = deadline.remaining() - CLOSE_MARGIN_MS;
1374
+ if (deadline.signal.aborted || left <= 0) {
1375
+ done();
1376
+ return;
1377
+ }
1378
+ deadline.signal.addEventListener("abort", done, { once: true });
1379
+ if (Number.isFinite(left)) {
1380
+ timer = setTimeout(done, Math.min(left, MAX_TIMER_MS));
1381
+ timer.unref?.();
1382
+ }
1383
+ });
1384
+ }
1385
+
1386
+ // -----------------------------------------------------------------------------------------------
1387
+ // Command checks under per-check scopes (2.1.2.5, T8)
1388
+ // -----------------------------------------------------------------------------------------------
1389
+
1390
+ /** How one command check spawns under its scope. */
1391
+ type Launch = (scope: CheckScope, deadline: Deadline) => Promise<CommandOutcome>;
1392
+
1393
+ /** T7 u14, shared by every command check. */
1394
+ export const SLOT_DEADLINE_REASON = "gate budget exhausted waiting for the verification slot";
1395
+
1396
+ function withNotes(notes: readonly string[]): { note?: string } {
1397
+ return notes.length > 0 ? { note: notes.join("; ") } : {};
1398
+ }
1399
+
1400
+ /** Runs `fn` under the gate's deadline, or under one of its own (disposed afterwards) when the deps carry none. */
1401
+ async function withCheckDeadline<T>(deps: DeterministicDeps, timeoutMs: number, fn: (deadline: Deadline) => Promise<T>): Promise<T> {
1402
+ let owned: OwnedDeadline | undefined;
1403
+ const deadline: Deadline = deps.deadline ?? (owned = createDeadline(deps.budget?.gateBudgetMs ?? timeoutMs));
1404
+ try {
1405
+ return await fn(deadline);
1406
+ } finally {
1407
+ owned?.dispose();
1408
+ }
1409
+ }
1410
+
1411
+ /** T8: slot busy, a gate-budget cut and executor errors are unverifiable; the check's own timeout fails, as today. */
1412
+ function blockedResult(kind: string, command: string, out: Exclude<CommandOutcome, { kind: "ran" }>, deadline: Deadline): CheckResult {
1413
+ switch (out.kind) {
1414
+ case "slot-busy":
1415
+ return { ok: false, unverifiable: true, reason: out.deadlineCut ? SLOT_DEADLINE_REASON : `verification slot busy (waited ${out.waitedMs}ms)` };
1416
+ case "aborted":
1417
+ return { ok: false, unverifiable: true, reason: `${kind}: ${out.reason}: ${command}` };
1418
+ case "error":
1419
+ return { ok: false, unverifiable: true, reason: `${kind} check errored: ${scrubText(out.reason)}` };
1420
+ case "timed-out":
1421
+ // A bound the gate deadline cut short is budget exhaustion, not the command's own timeout.
1422
+ return deadline.remaining() === 0
1423
+ ? { ok: false, unverifiable: true, reason: `${kind}: gate budget exhausted during the run: ${command}` }
1424
+ : { ok: false, reason: `${kind} timed out after ${out.boundMs}ms: ${command}` };
1425
+ }
1426
+ }
1427
+
1428
+ /**
1429
+ * The exec result of one non-testsPass command check. With `deps.openScope` (T8): its own scope,
1430
+ * one slot hold, low priority, deadline-bound, closed before this returns so scopes never nest
1431
+ * (runDeterministic is sequential). Without it: deps.exec, as before.
1432
+ */
1433
+ async function obtainExec(
1434
+ kind: string,
1435
+ command: string,
1436
+ deps: DeterministicDeps,
1437
+ timeoutMs: number,
1438
+ launch: Launch,
1439
+ ): Promise<{ exec: ExecResult; notes: readonly string[] } | { result: CheckResult }> {
1440
+ const openScope = deps.openScope;
1441
+ if (!openScope) {
1442
+ const r: ExecResult = await deps.exec(command, { cwd: deps.cwd, timeoutMs });
1443
+ if (r.timedOut) return { result: { ok: false, reason: `${kind} timed out after ${timeoutMs}ms: ${command}` } };
1444
+ return { exec: r, notes: [] };
1445
+ }
1446
+ return withCheckDeadline(deps, timeoutMs, async deadline => {
1447
+ const scope = openScope({ cwd: deps.cwd, command });
1448
+ let out: CommandOutcome;
1449
+ try {
1450
+ out = await launch(scope, deadline);
1451
+ } finally {
1452
+ await scope.close();
1453
+ }
1454
+ return out.kind === "ran" ? { exec: out.exec, notes: out.notes } : { result: blockedResult(kind, command, out, deadline) };
1455
+ });
1456
+ }
1457
+
1458
+ /** T8 lintClean scoping. A planner failure, or a relative cwd, runs the command unscoped (as today). */
1459
+ async function planLint(command: string, deps: DeterministicDeps): Promise<LintSpec | NoAffected | Unscoped> {
1460
+ if (!deps.cwd || !isAbsolute(deps.cwd)) return { unscoped: true, reason: "no absolute working directory" };
1461
+ try {
1462
+ return await (deps.planLint ?? planScopedLint)({
1463
+ command,
1464
+ cwd: deps.cwd,
1465
+ changedFiles: deps.changedFiles ?? "unavailable",
1466
+ budget: { maxWorkers: deps.budget?.maxWorkers ?? 2 },
1467
+ fs: deps.fs,
1468
+ });
1469
+ } catch (err) {
1470
+ return { unscoped: true, reason: `lint planning failed: ${errorText(err)}` };
1471
+ }
1472
+ }
1473
+
1474
+ /** G5: testsPass with no TestsPassHook in the deps is unverifiable, never a run. */
1475
+ export const NO_TESTS_PASS_HOOK = "testsPass: not run: no scoped test pipeline is wired for this verification";
1476
+
1477
+ /** P8: a TestsPassJudgement as the check's CheckResult, carrying the attribution (2.4 lineage). */
1478
+ function fromJudgement(j: TestsPassJudgement): CheckResult {
1479
+ return {
1480
+ ok: j.ok,
1481
+ ...(j.unverifiable ? { unverifiable: true } : {}),
1482
+ ...(j.reason !== undefined ? { reason: j.reason } : {}),
1483
+ ...(j.note !== undefined ? { note: j.note } : {}),
1484
+ ...(j.evidence !== undefined ? { evidence: j.evidence } : {}),
1485
+ ...(j.failures !== undefined ? { failures: j.failures } : {}),
1486
+ };
1487
+ }
1488
+
1489
+ function defaultReference(deps: DeterministicDeps): ReferenceState {
1490
+ return deps.budget?.failureRecheck === false ? { kind: "disabled" } : { kind: "none", reason: REFERENCE_NONE.untracked };
1491
+ }
1492
+
1493
+ /** P0-P8 for one testsPass check whose command already passed the allowlist (P1). Never rejects. */
1494
+ async function runTestsPass(command: string, deps: DeterministicDeps, timeoutMs: number): Promise<CheckResult> {
1495
+ if (!deps.testsPass) return { ok: false, unverifiable: true, reason: `${NO_TESTS_PASS_HOOK}: ${command}` };
1496
+ if (!deps.cwd || !isAbsolute(deps.cwd)) {
1497
+ return { ok: false, unverifiable: true, reason: `testsPass cannot run without an absolute working directory: ${command}` };
1498
+ }
1499
+ const hook = deps.testsPass;
1500
+ const cwd = deps.cwd;
1501
+ try {
1502
+ return await withCheckDeadline(deps, timeoutMs, async deadline => {
1503
+ const run = await hook({
1504
+ command,
1505
+ cwd,
1506
+ testScope: deps.budget?.testScope ?? "affected",
1507
+ changedFiles: deps.changedFiles ?? "unavailable",
1508
+ reference: deps.reference ?? defaultReference(deps),
1509
+ deadline,
1510
+ });
1511
+ return fromJudgement(judgeScoped(run.scoped, run.recheck));
1512
+ });
1513
+ } catch (err) {
1514
+ return { ok: false, unverifiable: true, reason: `testsPass check errored: ${scrubText(String(err))}` };
1515
+ }
1516
+ }
1517
+
184
1518
  async function runCommandCheck(
185
1519
  check: Check,
186
1520
  kind: "testsPass" | "buildPasses" | "lintClean",
@@ -208,33 +1542,48 @@ async function runCommandCheck(
208
1542
  }
209
1543
  }
210
1544
 
1545
+ if (kind === "testsPass") {
1546
+ // P1: not allowlisted -> unverifiable, as today. P2-P8 run outside deps.mutex: that per-cwd
1547
+ // lock would serialize exactly the concurrent gates that 2.2 must batch.
1548
+ if (!isCommandAllowed(command, allowlist)) {
1549
+ return { ok: false, unverifiable: true, reason: `command not allowlisted: ${command}` };
1550
+ }
1551
+ return runTestsPass(command, deps, timeoutMs);
1552
+ }
1553
+
211
1554
  const fn = async (): Promise<CheckResult> => {
212
1555
  try {
213
1556
  if (!isCommandAllowed(command, allowlist)) {
214
1557
  return { ok: false, unverifiable: true, reason: `command not allowlisted: ${command}` };
215
1558
  }
216
- const baseline = kind === "testsPass" ? await deps.testBaseline?.(command) : undefined;
217
- const r: ExecResult = await deps.exec(command, { cwd: deps.cwd, timeoutMs });
218
- if (r.timedOut) {
219
- if (kind === "testsPass") {
220
- const observed = compareTests(observeTests(r));
221
- return { ...observed, reason: `${kind} timed out after ${timeoutMs}ms: ${command}; ${observed.reason}` };
1559
+ let launch: Launch = (scope, deadline) => scope.runShell(command, deps.cwd, deadline);
1560
+ let scopedTo: number | undefined;
1561
+ if (kind === "lintClean" && deps.openScope) {
1562
+ // T8: NoAffected passes with its note and takes no slot; Unscoped runs the command as today.
1563
+ const plan = await planLint(command, deps);
1564
+ if (isNoAffected(plan)) return { ok: true, note: `lintClean: ${plan.note}` };
1565
+ if (!isUnscoped(plan)) {
1566
+ launch = (scope, deadline) => scope.runLint(plan, deadline);
1567
+ scopedTo = plan.inputs.length;
222
1568
  }
223
- return { ok: false, reason: `${kind} timed out after ${timeoutMs}ms: ${command}` };
224
1569
  }
225
- if (kind === "testsPass") return compareTests(observeTests(r), baseline);
1570
+ const got = await obtainExec(kind, command, deps, timeoutMs, launch);
1571
+ if ("result" in got) return got.result;
1572
+ const r = got.exec;
226
1573
  const out = r.stdout + "\n" + r.stderr;
227
1574
  const ok = r.code === 0;
1575
+ const scoped = scopedTo !== undefined ? ` (scoped to ${scopedTo} changed files)` : "";
228
1576
  if (!ok) {
229
1577
  return {
230
1578
  ok: false,
231
- reason: `command exited ${r.code}: ${command}`,
1579
+ reason: `command exited ${r.code}: ${command}${scoped}`,
232
1580
  evidence: out.slice(0, 2000),
1581
+ ...withNotes(got.notes),
233
1582
  };
234
1583
  }
235
- return { ok: true, evidence: `exit 0: ${command}` };
1584
+ return { ok: true, evidence: `exit 0: ${command}${scoped}`, ...withNotes(got.notes) };
236
1585
  } catch (err) {
237
- return { ok: false, ...(kind === "testsPass" ? { unverifiable: true } : {}), reason: `${kind} check errored: ${scrubText(String(err))}` };
1586
+ return { ok: false, reason: `${kind} check errored: ${scrubText(String(err))}` };
238
1587
  }
239
1588
  };
240
1589
 
@@ -354,6 +1703,14 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
354
1703
  const evidenceParts = results.map(r => r.evidence ?? "").filter(e => e.length > 0);
355
1704
  const rawEvidence = evidenceParts.length > 0 ? evidenceParts.join("\n---\n") : undefined;
356
1705
  const evidence = rawEvidence !== undefined ? scrubText(rawEvidence) : undefined;
1706
+ const classified = results.flatMap(r => (r.failures ? [r.failures] : []));
1707
+ const failures: FailureClassification | undefined = classified.length
1708
+ ? {
1709
+ introduced: classified.flatMap(f => f.introduced),
1710
+ preexisting: classified.flatMap(f => f.preexisting),
1711
+ unknown: classified.flatMap(f => f.unknown),
1712
+ }
1713
+ : undefined;
357
1714
 
358
1715
  return {
359
1716
  pass: allPass,
@@ -363,5 +1720,6 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
363
1720
  method: "deterministic",
364
1721
  reasons,
365
1722
  ...(evidence !== undefined ? { evidence } : {}),
1723
+ ...(failures !== undefined ? { failures } : {}),
366
1724
  };
367
1725
  }