opencode-model-router 1.14.0 → 2.0.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.
@@ -13,20 +13,83 @@
13
13
  * settings that were active when the plugin loaded, and `/preset` would
14
14
  * silently stop applying to graded work.
15
15
  */
16
- import { access, readFile as fsReadFile } from "node:fs/promises";
17
- import { isAbsolute, join, resolve } from "node:path";
18
- import { createMutexRegistry, DEFAULT_ALLOWLIST, isCommandAllowed, resolveRepoCommand } from "./deterministic";
19
- import { tierModel, type createChangedFileStore } from "./dispatch";
20
- import { runShell } from "./exec";
16
+ import { createHash } from "node:crypto";
17
+ import type { ChildSessionRunner } from "../compat/child-session";
18
+ import { access, readdir, readFile as fsReadFile, realpath, stat, unlink } from "node:fs/promises";
19
+ import { isAbsolute, join, relative, resolve } from "node:path";
20
+ import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
21
+ import {
22
+ createDeadline,
23
+ createDirectTestsPassHook,
24
+ createMutexRegistry,
25
+ createScopeOpener,
26
+ DEFAULT_ALLOWLIST,
27
+ isCommandAllowed,
28
+ RECHECK_MIN_REMAINING_MS,
29
+ resolveRepoCommand,
30
+ type OwnedDeadline,
31
+ } from "./deterministic";
32
+ import { parseVerifyDirectives, type VerifyDirectives } from "./directives";
33
+ import {
34
+ ABANDONED_REASON,
35
+ ABSENT_DIGEST as PENDING_ABSENT_DIGEST,
36
+ buildDeferredFooter,
37
+ DISPOSED_REASON,
38
+ buildLineageCaveat,
39
+ createBackgroundQueue,
40
+ createPendingRegistry,
41
+ driftedPaths,
42
+ EXPIRED_HANDLE_TEXT,
43
+ MAX_HANDLES_PER_CALL,
44
+ MAX_STORED_CHANGED_FILES,
45
+ neutralizeDirectives,
46
+ normalizeHandle,
47
+ sanitizeDescription,
48
+ unattributedRisk,
49
+ UNKNOWN_HANDLE_TEXT,
50
+ VERIFYING_ELSEWHERE_TEXT,
51
+ VERIFYING_GRACE_MS,
52
+ type BackgroundOutcome,
53
+ type BackgroundQueue,
54
+ type BackgroundQueueOptions,
55
+ type FileDigests,
56
+ type PendingEntry,
57
+ type PendingRegistry,
58
+ type PendingRegistryOptions,
59
+ type SettledVerification,
60
+ type VerificationResult,
61
+ } from "./pending";
62
+ import { assessRisk, type RiskAssessment } from "./risk";
63
+ import { resolveBaseDir } from "./paths";
64
+ import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
65
+ import {
66
+ buildAcceptedSuffix,
67
+ buildForcingNote,
68
+ canonicalPath,
69
+ tierModel,
70
+ toolLabel,
71
+ type ChangedFile,
72
+ type createChangedFileStore,
73
+ type DispatchCaptureDeps,
74
+ type TreeSnapshot,
75
+ } from "./dispatch";
76
+ import { runArgv, runShell } from "./exec";
21
77
  import { snapshotTree } from "./tree";
78
+ import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, nodeReferenceFs, type DispatchReference } from "./reference";
79
+ import type { PluginLogger } from "../router/logger";
80
+ import { REFERENCE_NONE } from "./baseline";
81
+ import { scrubText } from "../guard/scrub";
22
82
  import type { DoD } from "./dod";
23
- import type { DeterministicDeps } from "./types";
83
+ import type { ArgvSeam, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ReferenceState, TestsPassHook, Verdict } from "./types";
84
+ import { planScopedRun, planStaticScoping, type ChangedPath, type RunnerFs, type StaticScoping, type TestSearchSeam } from "./runner";
24
85
  import {
86
+ DEFAULT_GATE_BUDGET_MS,
25
87
  graderTimeoutMs,
88
+ RouterTimeoutError,
26
89
  withTimeout,
27
90
  } from "./timeout";
28
- import type { RouterConfig } from "../router/config";
29
- import type { GateDeps } from "./gate";
91
+ import { resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
92
+ import { accept, gateResult, unverifiableGateResult, type GateDeps, type GateResult } from "./gate";
30
93
  // The grader request shape is owned by checker.ts, which builds it. Re-exported
31
94
  // here because this module is where it is consumed, and because keeping a
32
95
  // second local copy is exactly how `cwd` got dropped: the checker set it, the
@@ -62,16 +125,775 @@ export function extractAssistantText(res: any): string {
62
125
  .join("\n");
63
126
  }
64
127
 
128
+ function isValidHttpStatus(status: unknown): status is number {
129
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599;
130
+ }
131
+
132
+ function graderPromptResponseError(res: unknown): Error | undefined {
133
+ if (typeof res !== "object" || res === null) return undefined;
134
+ const envelope = res as {
135
+ error?: unknown;
136
+ data?: { info?: { error?: unknown } };
137
+ response?: { status?: unknown };
138
+ };
139
+ const error = envelope.data?.info?.error ?? envelope.error;
140
+ const responseStatus = envelope.response?.status;
141
+ const validStatus = isValidHttpStatus(responseStatus);
142
+ const malformedStatus = responseStatus !== undefined && !validStatus;
143
+ const httpStatus = validStatus && responseStatus >= 400
144
+ ? responseStatus : undefined;
145
+ if (error == null && httpStatus === undefined && !malformedStatus) return undefined;
146
+ const detail = typeof error === "object" && error !== null ? error as {
147
+ data?: { statusCode?: unknown };
148
+ } : undefined;
149
+ const nestedStatus = detail?.data?.statusCode;
150
+ const status = httpStatus ?? (isValidHttpStatus(nestedStatus) ? nestedStatus : undefined);
151
+ return new Error(`grader prompt failed${status === undefined ? "" : ` (${status})`}: SDK error`);
152
+ }
153
+
154
+ /** P0 (deterministic.ts header, T2): what a gate needs from its dispatch. */
155
+ export interface PreparedVerification {
156
+ /**
157
+ * The producer's changed files: the tool-observed paths of every attempt judged against this
158
+ * dispatch (QA-2.1-1), the paths the current snapshot added since dispatch, and the paths dirty
159
+ * or untracked at dispatch whose content digest changed or which left the listing (QA-2.1-2);
160
+ * each with the snapshot's status letters and rename source when the snapshot lists it.
161
+ */
162
+ changedFiles: ChangedFile[];
163
+ changeBaseline: "available" | "unavailable";
164
+ /** Settled: the dispatch reference, or why there is none. */
165
+ reference: ReferenceState;
166
+ /** The current tree snapshot (materialize's drift check); undefined when unavailable. */
167
+ snapshot: TreeSnapshot | undefined;
168
+ /**
169
+ * QA-3.1-2: other dispatches in the same git tree that were live during this dispatch's window
170
+ * (the change set holds their edits too). Absent or 0: none.
171
+ */
172
+ concurrentDispatches?: number;
173
+ /** QA-3.1-3: the tool whose call discarded the dispatch snapshot, which left the change set unavailable. */
174
+ contaminatedBy?: string;
175
+ }
176
+
177
+ /**
178
+ * QA-3.1-2: appended to a rejection that lists introduced failures when other delegations were live in
179
+ * the same working tree during the dispatch: the tree delta is not partitioned between them.
180
+ */
181
+ export function concurrentDispatchesCaveat(count: number): string {
182
+ return `other delegations ran in this working tree concurrently (${count}); introduced failures may come from their edits`;
183
+ }
184
+
185
+ /** QA-3.1-3: an unverifiable verdict whose change baseline a tool call discarded names that tool. */
186
+ export function contaminatedBaselineCaveat(tool: string): string {
187
+ return `the dispatch-time change baseline was discarded: tool "${toolLabel(tool)}" ran in an overlapping directory before it resolved`;
188
+ }
189
+
190
+ /**
191
+ * QA-3.1-2 / QA-3.1-3: router caveats from the dispatch's own context, on a gate result. A fail that
192
+ * lists introduced failures gains concurrentDispatchesCaveat when other dispatches overlapped it; an
193
+ * unverifiable verdict gains contaminatedBaselineCaveat (reasons and caveats) when a tool call
194
+ * discarded its change baseline. The outcome and `accepted` never change. Pure; the text goes through
195
+ * neutralizeDirectives like all router text.
196
+ */
197
+ export function applyDispatchCaveats(
198
+ res: GateResult,
199
+ ctx: { readonly concurrentDispatches?: number; readonly contaminatedBy?: string },
200
+ ): GateResult {
201
+ const verdict = res.verdict;
202
+ if (verdict.skipped === true) return res;
203
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
204
+ const concurrent = ctx.concurrentDispatches ?? 0;
205
+ if (outcome === "fail" && concurrent > 0 && (verdict.failures?.introduced.length ?? 0) > 0) {
206
+ return { ...res, verdict: { ...verdict, reasons: [...verdict.reasons, neutralizeDirectives(concurrentDispatchesCaveat(concurrent))] } };
207
+ }
208
+ if (outcome === "unverifiable" && ctx.contaminatedBy !== undefined) {
209
+ const caveat = neutralizeDirectives(contaminatedBaselineCaveat(ctx.contaminatedBy));
210
+ return { ...res, verdict: { ...verdict, reasons: [...verdict.reasons, caveat], caveats: [...(verdict.caveats ?? []), caveat] } };
211
+ }
212
+ return res;
213
+ }
214
+
215
+ /**
216
+ * QA-3.1-3: single flight for the dispatch-time snapshot and capture. Each dispatch spawns 7 git
217
+ * processes for its snapshot and 8 for its capture; 20 parallel dispatches spawned 300, and on
218
+ * Windows each then took 130-560 ms instead of ~60 ms (p50 2.9 s per dispatch).
219
+ *
220
+ * Requests with one key share one run, but a run is only ever shared by requests made BEFORE it
221
+ * started: a request that arrives while a run is in flight waits for the next run, which starts when
222
+ * the current one settled and serves every request that arrived meanwhile. A shared result is so
223
+ * always taken after each sharer's request began, as its own run would have been. A request's signal
224
+ * ends only its own wait (undefined); a started run is aborted once every sharer has left, and a
225
+ * queued run nobody waits for any more never starts. The returned function never rejects.
226
+ *
227
+ * QA-3.1-24: a started run whose last sharer left is also detached from its lane, so a run that
228
+ * ignores its abort (snapshotTree's lstat/readlink/realpath take no signal) cannot hold every later
229
+ * request with its key. Known limit: a request that arrives just after a run started waits for that
230
+ * run and then its own, while its timeout counts from its own request; when one snapshot or capture
231
+ * takes longer than half of the caller's timeout (baselineTimeoutMs, default 15 s), such an early
232
+ * arrival can time out before its own run ends. That fails closed: no change baseline, reference
233
+ * none, verdict unverifiable.
234
+ */
235
+ export function createSharedFlight<T>(): (
236
+ key: string,
237
+ run: (signal: AbortSignal) => Promise<T | undefined>,
238
+ signal: AbortSignal,
239
+ ) => Promise<T | undefined> {
240
+ interface Flight {
241
+ readonly controller: AbortController;
242
+ readonly result: Promise<T | undefined>;
243
+ readonly start: () => void;
244
+ sharers: number;
245
+ started: boolean;
246
+ }
247
+ interface Lane {
248
+ running?: Flight;
249
+ next?: Flight;
250
+ }
251
+ const lanes = new Map<string, Lane>();
252
+ const makeFlight = (run: (signal: AbortSignal) => Promise<T | undefined>): Flight => {
253
+ const controller = new AbortController();
254
+ let settle = (_value: T | undefined): void => undefined;
255
+ const result = new Promise<T | undefined>(ok => {
256
+ settle = ok;
257
+ });
258
+ const flight: Flight = {
259
+ controller,
260
+ result,
261
+ // Synchronous: the run's own start-up (the first git spawn) happens inside the call that
262
+ // starts it, so a VERIFY_WAIT counted from the dispatch's start covers it (ab81633).
263
+ start: () => {
264
+ flight.started = true;
265
+ let running: Promise<T | undefined>;
266
+ try {
267
+ running = run(controller.signal);
268
+ } catch {
269
+ running = Promise.resolve(undefined);
270
+ }
271
+ running.then(settle, () => settle(undefined));
272
+ },
273
+ sharers: 0,
274
+ started: false,
275
+ };
276
+ return flight;
277
+ };
278
+ // The lane's running flight is done with (settled, or detached by its last sharer): start the
279
+ // queued one, or retire an idle lane.
280
+ const advance = (key: string, lane: Lane): void => {
281
+ lane.running = undefined;
282
+ const next = lane.next;
283
+ lane.next = undefined;
284
+ if (next !== undefined) launch(key, lane, next);
285
+ else if (lanes.get(key) === lane) lanes.delete(key);
286
+ };
287
+ const launch = (key: string, lane: Lane, flight: Flight): void => {
288
+ lane.running = flight;
289
+ flight.start();
290
+ void flight.result.then(() => {
291
+ // QA-3.1-24: a flight its last sharer detached no longer owns the lane.
292
+ if (lane.running === flight) advance(key, lane);
293
+ });
294
+ };
295
+ return (key, run, signal) => {
296
+ if (signal.aborted) return Promise.resolve(undefined);
297
+ let lane = lanes.get(key);
298
+ if (lane === undefined) {
299
+ lane = {};
300
+ lanes.set(key, lane);
301
+ }
302
+ let flight: Flight;
303
+ if (lane.next !== undefined) flight = lane.next;
304
+ else if (lane.running !== undefined) flight = lane.next = makeFlight(run);
305
+ else {
306
+ flight = makeFlight(run);
307
+ launch(key, lane, flight);
308
+ }
309
+ flight.sharers += 1;
310
+ const owner = lane;
311
+ return new Promise<T | undefined>(settle => {
312
+ const onAbort = (): void => {
313
+ flight.sharers -= 1;
314
+ if (flight.sharers === 0) {
315
+ // Nobody waits for it any more: stop a started run; never start a queued one.
316
+ if (flight.started) {
317
+ flight.controller.abort();
318
+ // QA-3.1-24: a run that ignores its abort must not hold the lane until it settles.
319
+ // Detach it, so the queued run (whose sharers all asked after it started) goes now.
320
+ if (owner.running === flight) advance(key, owner);
321
+ } else if (owner.next === flight) owner.next = undefined;
322
+ }
323
+ settle(undefined);
324
+ };
325
+ signal.addEventListener("abort", onAbort, { once: true });
326
+ void flight.result.then(value => {
327
+ signal.removeEventListener("abort", onAbort);
328
+ settle(value);
329
+ });
330
+ });
331
+ };
332
+ }
333
+
334
+ /**
335
+ * QA-2.1-11: the start-up reference GC runs this long after plugin start, so the start itself never
336
+ * holds the project directory with a git child process.
337
+ */
338
+ export const REFERENCE_GC_START_DELAY_MS = 45_000;
339
+ /** How long the gate-time tree snapshot may take (bounded further by a gate deadline). */
340
+ export const GRADE_SNAPSHOT_TIMEOUT_MS = 10_000;
341
+ /** T3: each git test search, bounded further by a gate deadline. */
342
+ export const TEST_SEARCH_TIMEOUT_MS = 10_000;
343
+ /** QA-2.1-12: the `git diff <dispatch head> HEAD` of a gate whose HEAD moved, bounded further by a gate deadline. */
344
+ export const COMMIT_DIFF_TIMEOUT_MS = 10_000;
345
+ /**
346
+ * QA-2.2-21: the effective batch window is at most gateBudgetMs / this. config.ts accepts any
347
+ * batchWindowMs up to the timer limit, and a window close to the gate budget would spend most of
348
+ * it waiting (batch.ts W3 still keeps each member's recheck reserve).
349
+ */
350
+ export const BATCH_WINDOW_BUDGET_DIVISOR = 10;
351
+
352
+ /** QA-2.2-21: batchWindowMs, capped at a tenth of the gate budget; <= 0 disables batching. */
353
+ export function effectiveBatchWindowMs(budget: Pick<VerifyBudget, "batchWindowMs" | "gateBudgetMs">): number {
354
+ return Math.min(budget.batchWindowMs, Math.floor(budget.gateBudgetMs / BATCH_WINDOW_BUDGET_DIVISOR));
355
+ }
356
+
357
+ // -----------------------------------------------------------------------------------------------
358
+ // 2.4.2 deferred verification (plan Phase 2.4, sections 1.5-14..17; pending.ts R3, R10, R11)
359
+ // -----------------------------------------------------------------------------------------------
360
+
361
+ /**
362
+ * phase-2.4.md gather item 11: the bound on a deferred finish (tree snapshot, commit diff, static
363
+ * scoping). On expiry the change set is "unavailable" and the risk is unattributedRisk(), never [].
364
+ */
365
+ export const DEFERRED_FINISH_MS = 2_000;
366
+ /** Upper bound on remembered native `task` dispatch starts (before hook -> after hook). */
367
+ export const DISPATCH_STARTS_MAX = 1_024;
368
+ /** Drift digests read at most this many bytes in total (tree.ts MAX_DIGEST_BYTES); beyond it: no digests. */
369
+ export const DRIFT_DIGEST_MAX_BYTES = 64 * 1024 * 1024;
370
+ /** Static scoping could not finish inside DEFERRED_FINISH_MS: counted as impossible (conservative). */
371
+ export const STATIC_SCOPING_UNFINISHED_REASON = "static scoping did not finish within the deferred-finish bound";
372
+ /** Section 1.4 pendingTtlMs default, used when the config cannot be read at plugin start. */
373
+ export const DEFAULT_PENDING_TTL_MS = 3_600_000;
374
+ /**
375
+ * QA-2.4-9: the capture wait when the config cannot be read: section 1.4's captureWaitMs default
376
+ * (5000 ms), clamped to the default baselineTimeoutMs (DEFAULT_CAPTURE_TIMEOUT_MS), as config.ts does.
377
+ */
378
+ export const FALLBACK_CAPTURE_WAIT_MS = Math.min(5_000, DEFAULT_CAPTURE_TIMEOUT_MS);
379
+
380
+ /** What the orchestrator asked for at dispatch (directives.ts, parsed from its own prompt only). */
381
+ export interface DispatchStart {
382
+ readonly directives: VerifyDirectives;
383
+ /** Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). */
384
+ readonly dispatchedAt: number;
385
+ }
386
+
387
+ /** What a deferred producer's return hands to finishDeferred (pending.ts R3). */
388
+ export interface DeferredFinishInput {
389
+ readonly dispatchID: string;
390
+ /** The session that called `task` / `delegate`; never the producer. */
391
+ readonly orchestratorSessionID: string;
392
+ readonly producerSessionID: string;
393
+ /** As received; canonicalised here (canonicalTier, 1.6 handoff item 8). */
394
+ readonly producerTier: string;
395
+ readonly description: string;
396
+ readonly cwd: string | undefined;
397
+ readonly dod: DoD;
398
+ readonly dispatchedAt: number;
399
+ }
400
+
401
+ /**
402
+ * What finishDeferred decided. `deferred: false` means the delegation is NOT deferred and the
403
+ * caller runs today's required gate on it (QA-2.4-4, QA-2.4-10): the dispatch record is left in the
404
+ * store for that gate. Deferred or background verification is never weaker than that gate.
405
+ */
406
+ export type DeferredFinish =
407
+ | {
408
+ readonly deferred: true;
409
+ /** The section 1.5-16 footer, naming the handle. */
410
+ readonly footer: string;
411
+ readonly handle: string;
412
+ readonly risk: RiskAssessment;
413
+ }
414
+ | {
415
+ readonly deferred: false;
416
+ /**
417
+ * "unregistered": the registry refused the entry (registry-full, handle-collision,
418
+ * invalid-input); "no-change": an attributed empty change set of a testsPass-only DoD, which
419
+ * the required gate passes with no process (section 1.5-6; QA-G-1: any other DoD is deferred
420
+ * with the empty set instead, noChangeGateSpawnsNothing); "error": the finish itself failed.
421
+ */
422
+ readonly reason: "unregistered" | "no-change" | "error";
423
+ readonly detail: string;
424
+ };
425
+
426
+ /** What R11 lineage needs from a required gate's dispatch. */
427
+ export interface LineageContext {
428
+ readonly orchestratorSessionID: string;
429
+ /** Git top-level of the gate-time snapshot (TreeSnapshot.root); undefined -> no lineage either way. */
430
+ readonly root: string | undefined;
431
+ readonly dispatchID: string;
432
+ readonly dispatchedAt: number;
433
+ /** When the producer returned: the landedAt of a rejection recorded now. */
434
+ readonly returnedAt: number;
435
+ readonly strictUnverifiable: boolean | undefined;
436
+ }
437
+
438
+ /** 1.6 handoff item 8: the canonical tier id is lowercase and trimmed. */
439
+ export function canonicalTier(tier: string): string {
440
+ return tier.trim().toLowerCase();
441
+ }
442
+
443
+ /**
444
+ * The text directives are parsed from: the orchestrator-authored `prompt` argument, or its
445
+ * `description` when the prompt is blank (the prompt-repair hook copies it in that case). Never a
446
+ * tool result or a subagent's text (directives.ts SECURITY).
447
+ */
448
+ export function dispatchDirectiveText(prompt: string | undefined, description: string | undefined): string {
449
+ return prompt !== undefined && prompt.trim() !== "" ? prompt : (description ?? "");
450
+ }
451
+
452
+ /** A DoD whose deferral section 1.5-14/16 governs: it carries a testsPass check. */
453
+ export function hasTestsPass(dod: DoD): boolean {
454
+ return dod.checks.some(c => c.kind === "testsPass");
455
+ }
456
+
457
+ /**
458
+ * QA-G-1: whether the required gate passes an attributed empty change set of this DoD with no
459
+ * process and no grader: every check is testsPass (its "no changed files" pass, section 1.5-6) and
460
+ * there is no criterion. Only such a delegation takes finishDeferred's "no-change" answer
461
+ * (QA-2.4-10); any other deferred DoD is registered with the empty change set instead, so its
462
+ * build, lint, run, file and criteria checks run on router_verify, never synchronously.
463
+ */
464
+ export function noChangeGateSpawnsNothing(dod: DoD): boolean {
465
+ return dod.checks.length > 0 && dod.checks.every(c => c.kind === "testsPass") && dod.criteria.length === 0;
466
+ }
467
+
468
+ /**
469
+ * pending.ts R3 `digests`: sha256 hex of each path's bytes, ABSENT_DIGEST for a missing path.
470
+ * fs reads only. Undefined (no drift claim either way) when a path is not a regular file or cannot
471
+ * be read, or when the set exceeds MAX_STORED_CHANGED_FILES paths or DRIFT_DIGEST_MAX_BYTES bytes.
472
+ * Never rejects. 2.4.3 computes the "after" side with the same function.
473
+ */
474
+ export async function digestFiles(paths: readonly string[]): Promise<FileDigests | undefined> {
475
+ if (paths.length > MAX_STORED_CHANGED_FILES) return undefined;
476
+ const out = new Map<string, string>();
477
+ let total = 0;
478
+ for (const path of paths) {
479
+ try {
480
+ const info = await stat(path);
481
+ if (!info.isFile()) return undefined;
482
+ total += info.size;
483
+ if (total > DRIFT_DIGEST_MAX_BYTES) return undefined;
484
+ out.set(path, createHash("sha256").update(await fsReadFile(path)).digest("hex"));
485
+ } catch (err) {
486
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
487
+ out.set(path, PENDING_ABSENT_DIGEST);
488
+ continue;
489
+ }
490
+ return undefined;
491
+ }
492
+ }
493
+ return out;
494
+ }
495
+
496
+ // -----------------------------------------------------------------------------------------------
497
+ // 2.4.3a router_verify (plan section 1.5-18; pending.ts R2, R4, R6, R8, R9, R11)
498
+ // -----------------------------------------------------------------------------------------------
499
+
500
+ /** What one router_verify call asks for (index.ts builds it with parseRouterVerifyArgs). */
501
+ export type VerifyTarget =
502
+ | { readonly kind: "handles"; readonly handles: readonly unknown[] }
503
+ | { readonly kind: "pending" };
504
+
505
+ /** One line of a router_verify report, in the order the handles were named. */
506
+ export type HandleReport =
507
+ | {
508
+ readonly kind: "verdict";
509
+ readonly handle: string;
510
+ readonly description: string;
511
+ readonly producerTier: string;
512
+ /** "run": judged by this call; "joined": another call's run; "cached": settled earlier, nothing ran. */
513
+ readonly via: "run" | "joined" | "cached";
514
+ readonly result: SettledVerification;
515
+ }
516
+ /** Malformed, never issued, or issued to another session (R6): nothing distinguishes them. */
517
+ | { readonly kind: "unknown"; readonly input: string }
518
+ | { readonly kind: "expired"; readonly handle: string }
519
+ /** Joined another call's run, which outlived this call's deadline (R8). */
520
+ | { readonly kind: "elsewhere"; readonly handle: string; readonly description: string };
521
+
522
+ export interface VerifyReport {
523
+ readonly items: readonly HandleReport[];
524
+ /** Distinct handles beyond MAX_HANDLES_PER_CALL: reported, never run (R2). */
525
+ readonly excess: number;
526
+ readonly text: string;
527
+ }
528
+
529
+ export const ROUTER_VERIFY_ARGS_TEXT =
530
+ "[router] router_verify: pass exactly one of `handles` (a non-empty list of vrf_ handles) or `pending: true`; nothing was run.";
531
+ export const ROUTER_VERIFY_NO_PENDING_TEXT = "[router] router_verify: no unverified delegations in this session; nothing was run.";
532
+ export const ROUTER_VERIFY_NO_RETRY_TEXT = "[router] Nothing was retried or escalated; whether to re-dispatch is your call.";
533
+ /** Section 1.5-18. The run always uses the current tree. */
534
+ export const DRIFT_NOTICE = "tree drifted since delegation; verdict reflects current state";
535
+ /** No per-file proof either way (no stored or current digests): a pass is never kept then. */
536
+ export const DRIFT_UNCHECKED_NOTICE = "drift since delegation could not be checked; verdict reflects current state";
537
+ export const ROUTER_VERIFY_CANCELLED_REASON = "router_verify was cancelled before a verdict";
538
+ export const ROUTER_VERIFY_RELEASED_REASON = "the delegation's verification data was released";
539
+ /** Drifted paths named per handle; the rest are counted. */
540
+ export const DRIFT_MAX_PATHS = 10;
541
+
542
+ /**
543
+ * index.ts `router_verify` args. The SDK's arg root is an object shape (phase-2.4.md gather item
544
+ * 1), so "exactly one of handles / pending" is checked here: both, neither, `pending` other than
545
+ * true, and `handles` that is not a non-empty array are errors. Pure; never throws.
546
+ */
547
+ export function parseRouterVerifyArgs(args: unknown): VerifyTarget | { readonly error: string } {
548
+ const a = args !== null && typeof args === "object" ? (args as Record<string, unknown>) : {};
549
+ const hasHandles = a.handles !== undefined && a.handles !== null;
550
+ const hasPending = a.pending !== undefined && a.pending !== null;
551
+ if (hasHandles === hasPending) return { error: ROUTER_VERIFY_ARGS_TEXT };
552
+ if (hasPending) return a.pending === true ? { kind: "pending" } : { error: ROUTER_VERIFY_ARGS_TEXT };
553
+ if (!Array.isArray(a.handles) || a.handles.length === 0) return { error: ROUTER_VERIFY_ARGS_TEXT };
554
+ return { kind: "handles", handles: a.handles };
555
+ }
556
+
557
+ /** A literal phrase inside a RegExp source. */
558
+ function escapeRegExp(text: string): string {
559
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
560
+ }
561
+
562
+ /**
563
+ * pending.ts R4: reasons that say nothing about the producer's work (slot busy, the deadline or an
564
+ * abort, a timeout, an executor or coordinator error). Matched on 2.1/2.2's stable phrases
565
+ * (deterministic.ts u6, u7, u13, u14, u16; batch.ts BATCH_REASONS; baseline.ts
566
+ * REFERENCE_NONE.gateBudget) and this module's own. REFERENCE_NONE.failed ("failed or timed out" at
567
+ * dispatch) is deliberately not matched: that reference cannot be recaptured, so it is terminal.
568
+ *
569
+ * QA-2.4-14: only where the ROUTER writes it: at the start of a reason, after at most one check-kind
570
+ * word ("testsPass: ", "testsPass "). Producer-controlled text (failing test ids, "file > title")
571
+ * only ever follows a router phrase ("introduced failures: ", "; observed failures: "), so a test
572
+ * titled "verification slot busy" can never make a terminal verdict retryable.
573
+ */
574
+ const TRANSIENT_REASON = new RegExp(
575
+ "^(?:[A-Za-z]+:? )?(?:" +
576
+ [
577
+ "gate budget exhausted", // u7, u14 (deadline cut)
578
+ "verification slot busy", // u14
579
+ "timed out after \\d+ ?ms", // u13: "testsPass timed out after <n>ms: <command>"
580
+ "check errored", // u16: "testsPass check errored: <reason>"
581
+ "cannot attribute failures: the reference rerun timed out after \\d+ ?ms", // u6
582
+ `(?:no reference: pre-existing failures cannot be told apart \\()?${escapeRegExp(REFERENCE_NONE.gateBudget)}`,
583
+ "verification gate timed out after \\d+ ?ms",
584
+ "verification coordinator (?:disposed|failed)",
585
+ "verification batch (?:failed|ended without an outcome|produced no outcome)",
586
+ "verification unavailable:",
587
+ escapeRegExp(ABANDONED_REASON),
588
+ escapeRegExp(DISPOSED_REASON),
589
+ "router_verify was cancelled",
590
+ ].join("|") +
591
+ ")",
592
+ "i",
593
+ );
594
+
595
+ /**
596
+ * pending.ts R4 `retryable`: only an unverifiable (or skipped) verdict can be retryable, and only
597
+ * when the call was cut (deadline, abort) or a reason is transient. A pass or a fail is a verdict on
598
+ * the work and always terminal. Misclassification is never a false pass either way: a retryable
599
+ * entry is re-run later, a terminal unverifiable is replayed.
600
+ */
601
+ export function isRetryableVerdict(verdict: Verdict, cut: boolean): boolean {
602
+ if (verdict.skipped === true) return true;
603
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
604
+ if (outcome !== "unverifiable") return false;
605
+ if (cut) return true;
606
+ return [...verdict.reasons, ...(verdict.caveats ?? [])].some(r => TRANSIENT_REASON.test(r));
607
+ }
608
+
609
+ function formatPaths(paths: readonly string[], base: string): string {
610
+ const shown = paths.slice(0, DRIFT_MAX_PATHS).map(p => {
611
+ const rel = relative(base, p);
612
+ return sanitizeDescription(rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel : p);
613
+ });
614
+ const rest = paths.length - shown.length;
615
+ return rest > 0 ? `${shown.join(", ")} (+${rest} more)` : shown.join(", ");
616
+ }
617
+
618
+ function indent(text: string): string {
619
+ return text.split("\n").map(line => ` ${line}`).join("\n");
620
+ }
621
+
622
+ /**
623
+ * Section 1.5-18 / R9: one block per handle, in call order. A judged handle carries the required
624
+ * gate's own wording: buildAcceptedSuffix when accepted, buildForcingNote (with the next tier on a
625
+ * fail) plus ROUTER_VERIFY_NO_RETRY_TEXT when not. A retryable result is "not judged" and the
626
+ * delegation stays unverified. Pure.
627
+ */
628
+ export function formatVerifyReport(
629
+ items: readonly HandleReport[],
630
+ excess: number,
631
+ strictUnverifiable: boolean,
632
+ cwdOf: (handle: string) => string | undefined = () => undefined,
633
+ ): string {
634
+ const blocks: string[] = [];
635
+ for (const item of items) {
636
+ if (item.kind === "unknown") {
637
+ blocks.push(`- ${sanitizeDescription(item.input)} \u00b7 ${UNKNOWN_HANDLE_TEXT}`);
638
+ continue;
639
+ }
640
+ if (item.kind === "expired") {
641
+ blocks.push(`- ${item.handle} \u00b7 ${EXPIRED_HANDLE_TEXT}`);
642
+ continue;
643
+ }
644
+ if (item.kind === "elsewhere") {
645
+ blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${VERIFYING_ELSEWHERE_TEXT}`);
646
+ continue;
647
+ }
648
+ const { result } = item;
649
+ const verdict = result.verdict;
650
+ const via = item.via === "joined" ? " (joined a run already in progress)" : item.via === "cached" ? " (cached verdict; nothing was run)" : "";
651
+ if (result.retryable) {
652
+ const why = scrubText([...new Set([...(verdict.caveats ?? []), ...verdict.reasons])].join("; ") || "no verdict");
653
+ blocks.push(
654
+ `- ${item.handle} \u00b7 ${item.description} \u00b7 not judged${via}: ${why}\n` +
655
+ " [router] The delegation is still unverified; call `router_verify` again for a verdict.",
656
+ );
657
+ continue;
658
+ }
659
+ const judged = gateResult(verdict, "explicit", strictUnverifiable);
660
+ const outcome = judged.verdict.outcome ?? "fail";
661
+ const lines = [`- ${item.handle} \u00b7 ${item.description} \u00b7 ${outcome}${via}`];
662
+ const base = cwdOf(item.handle) ?? "";
663
+ if (result.driftedPaths !== undefined && result.driftedPaths.length > 0) {
664
+ lines.push(indent(`[router] ${DRIFT_NOTICE} (changed after the producer returned: ${formatPaths(result.driftedPaths, base)})`));
665
+ } else if ((verdict.caveats ?? []).includes(DRIFT_UNCHECKED_NOTICE)) {
666
+ lines.push(indent(`[router] ${DRIFT_UNCHECKED_NOTICE}`));
667
+ }
668
+ if (judged.accepted) {
669
+ lines.push(indent(buildAcceptedSuffix(verdict.method, judged.verdict.outcome, judged.verdict.caveats, verdict.notes).trim()));
670
+ } else {
671
+ lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null }))));
672
+ lines.push(indent(ROUTER_VERIFY_NO_RETRY_TEXT));
673
+ }
674
+ blocks.push(lines.join("\n"));
675
+ }
676
+ if (excess > 0) {
677
+ blocks.push(`- ${excess} more handle(s) not run: at most ${MAX_HANDLES_PER_CALL} per call; call \`router_verify\` again with the rest.`);
678
+ }
679
+ // QA-2.4-6 (R9): reasons, caveats and notes quote producer-controlled text (failing test ids).
680
+ // An orchestrator that quotes this report before its own `VERIFY:` must not change its mode.
681
+ return neutralizeDirectives(
682
+ [`[router] router_verify: one verdict per handle (${items.length}${excess > 0 ? ` of ${items.length + excess}` : ""}).`, ...blocks].join("\n"),
683
+ );
684
+ }
685
+
686
+ /**
687
+ * 2.4.5 (pending.ts R14): a background run's report as queue outcomes. Only this run's own verdict
688
+ * ("run") is "judged"; a verdict another router_verify call produced or had cached, and a run that
689
+ * call still owns ("elsewhere"), are "reported" (that caller has or gets it); unknown and expired
690
+ * handles are "gone". Pure.
691
+ */
692
+ export function backgroundOutcomes(items: readonly HandleReport[]): BackgroundOutcome[] {
693
+ return items.map((item): BackgroundOutcome => {
694
+ if (item.kind === "verdict") {
695
+ return item.via === "run"
696
+ ? { kind: "judged", handle: item.handle, description: item.description, result: item.result }
697
+ : { kind: "reported", handle: item.handle };
698
+ }
699
+ if (item.kind === "elsewhere") return { kind: "reported", handle: item.handle };
700
+ return { kind: "gone", handle: item.kind === "unknown" ? item.input : item.handle };
701
+ });
702
+ }
703
+
704
+ /** A never-rejecting wait for `promise` that ends with `fallback()` once `signal` aborts. */
705
+ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal, fallback: () => T): Promise<T> {
706
+ if (signal.aborted) return Promise.resolve(fallback());
707
+ return new Promise<T>(settle => {
708
+ const onAbort = (): void => settle(fallback());
709
+ signal.addEventListener("abort", onAbort, { once: true });
710
+ promise.then(
711
+ value => {
712
+ signal.removeEventListener("abort", onAbort);
713
+ settle(value);
714
+ },
715
+ () => {
716
+ signal.removeEventListener("abort", onAbort);
717
+ settle(fallback());
718
+ },
719
+ );
720
+ });
721
+ }
722
+
723
+ function unverifiableVerdict(reason: string): Verdict {
724
+ return { pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] };
725
+ }
726
+
727
+ /** Drift of one delegation's files since its producer returned (pending.ts R3 digests). */
728
+ type DriftCheck = { readonly kind: "none" } | { readonly kind: "drifted"; readonly paths: readonly string[] } | { readonly kind: "unchecked" };
729
+
730
+ /** A full object name (SHA-1 or SHA-256); anything else (e.g. an unborn HEAD) is an unknown head. */
731
+ const OBJECT_NAME = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
732
+
733
+ /**
734
+ * QA-2.1-12: parses `git diff --name-status -z -M` into absolute paths under `root`: one status
735
+ * token, then one path, or two (source, destination) for a rename or copy. Undefined when malformed.
736
+ */
737
+ export function parseNameStatusZ(out: string, root: string): ChangedFile[] | undefined {
738
+ const tokens = out.split("\0");
739
+ if (tokens[tokens.length - 1] === "") tokens.pop();
740
+ const files: ChangedFile[] = [];
741
+ for (let i = 0; i < tokens.length;) {
742
+ const status = tokens[i++];
743
+ if (!/^[A-Z][0-9]*$/.test(status)) return undefined;
744
+ const letter = status[0];
745
+ if (letter === "R" || letter === "C") {
746
+ const source = tokens[i++];
747
+ const dest = tokens[i++];
748
+ if (!source || !dest) return undefined;
749
+ files.push({ path: resolve(root, dest), status: letter, previousPath: resolve(root, source) });
750
+ } else {
751
+ const path = tokens[i++];
752
+ if (!path) return undefined;
753
+ files.push({ path: resolve(root, path), status: letter });
754
+ }
755
+ }
756
+ return files;
757
+ }
758
+ /** P5: the per-check timeout (DeterministicDeps.timeoutMs default). */
759
+ const CHECK_TIMEOUT_MS = 120_000;
760
+
65
761
  export interface VerificationWiring {
66
- beginVerification(store: ReturnType<typeof createChangedFileStore>, id: string, cwd: string | undefined, dod: DoD): void;
67
- prepareVerification(store: ReturnType<typeof createChangedFileStore>, id: string, childID: string, cwd?: string): Promise<{
68
- changedFiles: { path: string; status: string }[];
69
- changeBaseline: "available" | "unavailable";
70
- testBaseline: NonNullable<DeterministicDeps["testBaseline"]>;
71
- }>;
762
+ /**
763
+ * Starts the dispatch's background work: the tree snapshot and, only for a DoD with an
764
+ * allowlisted testsPass check and failureRecheck on, a git-only reference capture bounded by
765
+ * baselineTimeoutMs. Resolves when both settled; never rejects. No test command runs (G6).
766
+ */
767
+ beginVerification(store: ReturnType<typeof createChangedFileStore>, id: string, cwd: string | undefined, dod: DoD): Promise<void>;
768
+ /**
769
+ * 2.1.5b: beginVerification, awaited for at most `waitMs` (2.4.2a: the dispatch's VERIFY_WAIT;
770
+ * default captureWaitMs). The capture keeps running (up to baselineTimeoutMs) in the store after
771
+ * a timeout; a timeout or error only means "no reference yet" and is logged. Never rejects.
772
+ */
773
+ beginVerificationBounded(
774
+ store: ReturnType<typeof createChangedFileStore>,
775
+ id: string,
776
+ cwd: string | undefined,
777
+ dod: DoD,
778
+ waitMs?: number,
779
+ ): Promise<void>;
780
+ /**
781
+ * 2.4.2a: parseVerifyDirectives over `text` with the config defaults (defaultVerify,
782
+ * captureWaitMs, baselineTimeoutMs). `text` MUST be the orchestrator's own prompt
783
+ * (dispatchDirectiveText). Unknown values are logged. Never throws: when the config cannot be
784
+ * read, the mode is "required" (today's gate) and the wait FALLBACK_CAPTURE_WAIT_MS (QA-2.4-9).
785
+ */
786
+ resolveDirectives(text: string): VerifyDirectives;
787
+ /**
788
+ * 2.4.2a: resolveDirectives, then beginVerificationBounded for at most the directives' waitMs
789
+ * (section 1.5-14: VERIFY_WAIT, 0 allowed), counted from this call, so the directive read and
790
+ * the capture's synchronous start-up are inside it. `remember` keeps the start for takeDispatch
791
+ * (the native `task` after hook). Never rejects.
792
+ */
793
+ startDispatch(
794
+ store: ReturnType<typeof createChangedFileStore>,
795
+ id: string,
796
+ cwd: string | undefined,
797
+ dod: DoD,
798
+ text: string,
799
+ remember: boolean,
800
+ ): Promise<DispatchStart>;
801
+ /**
802
+ * 2.4.2b: the start remembered by startDispatch, forgotten on read. When none is remembered (the
803
+ * before hook did not run, or the entry was swept), `text` is parsed again (same orchestrator
804
+ * prompt) and dispatchedAt is now: a later dispatchedAt can only widen R11 lineage (fewer
805
+ * passes), never narrow it.
806
+ */
807
+ takeDispatch(id: string, text: string): DispatchStart;
808
+ /**
809
+ * 2.4.2a: whether this delegation defers (section 1.5-16): mode "deferred", a testsPass check
810
+ * in the DoD, and verification not disabled (`require: "never"`). Everything else is gated
811
+ * exactly as before 2.4.
812
+ * QA-2.4-10: only what the required gate would actually judge defers. `trivial` is the gate's own
813
+ * input (the native path's dispatch-time classification; delegate passes none): the gate skips a
814
+ * trivial dispatch whose DoD was inferred (gate.ts), so that one is not deferred and takes the
815
+ * required path, with the same outcome. (An attributed empty change set of a testsPass-only DoD
816
+ * is the other case; finishDeferred answers "no-change" for it. QA-G-1: a DoD with any other
817
+ * check or a criterion stays deferred with that empty set.)
818
+ */
819
+ isDeferred(dod: DoD, directives: VerifyDirectives, trivial?: boolean): boolean;
820
+ /**
821
+ * 2.4.2a: the deferred finish. No gate, no test command, no slot: a tree snapshot and the commit
822
+ * diff (git only, as prepareVerification) under DEFERRED_FINISH_MS, the static scoping plan
823
+ * (runner.ts: no spawn), the risk (pending.ts R10), the drift digests (fs reads, awaited inside
824
+ * the same bound so the baseline predates the result, QA-2.4-8),
825
+ * `pending.register`, and the section 1.5-16 footer. The dispatch's reference promise is
826
+ * registered un-awaited, and the dispatch record is cleared only after it settles (clearing it
827
+ * earlier would abort the capture). Never rejects. QA-2.4-4: when the registry refuses the entry
828
+ * or the finish fails, the result is `deferred: false` and the caller runs the required gate on
829
+ * the dispatch (whose record is then left in the store); there is no footer without a handle.
830
+ */
831
+ finishDeferred(store: ReturnType<typeof createChangedFileStore>, input: DeferredFinishInput): Promise<DeferredFinish>;
832
+ /**
833
+ * 2.4.2b/c, pending.ts R11 on a required gate's result:
834
+ * - outcome "fail" with proven-introduced ids -> pending.recordRejection (label
835
+ * "dispatch <id>", landedAt = returnedAt); the result is returned unchanged;
836
+ * - otherwise, proven pre-existing ids that an earlier rejection of the same session and root
837
+ * introduced (findLineage) -> the verdict becomes unverifiable with buildLineageCaveat; it
838
+ * stays accepted unless strictUnverifiable. It never creates a pass or a fail.
839
+ * A verdict without `failures` (checker verdicts, a timed-out gate) and an unknown root are
840
+ * returned unchanged and record nothing.
841
+ */
842
+ applyLineage(res: GateResult, ctx: LineageContext): GateResult;
843
+ /**
844
+ * 2.4.3a, section 1.5-18: router_verify for `sessionID` (the calling orchestrator; "" = none, so
845
+ * every handle is unknown). Never rejects; never retries or escalates.
846
+ * - Handles are normalized, deduped and capped at MAX_HANDLES_PER_CALL; `pending` is listOpen, so
847
+ * runs already in flight are joined (R8). Lookups are scoped by session (R6).
848
+ * - ONE Deadline of gateBudgetMs per call, created before any preparation (section 1.5-13) and
849
+ * shared by every claimed handle, so their testsPass requests meet in one S5 window.
850
+ * - Each claimed handle runs the required gate's path: its stored changed files, its stored
851
+ * reference (awaited under the deadline), a fresh tree snapshot, buildGateDeps + accept under
852
+ * withTimeout(deadline.remaining()). All preparations finish before any gate starts.
853
+ * - R11 lineage can only turn a pass into unverifiable; drift (stored vs current digests) or
854
+ * unprovable drift never lets a pass stand (DRIFT_NOTICE / DRIFT_UNCHECKED_NOTICE).
855
+ * - QA-2.4-1: judged in two phases. Every gate of the call returns, every terminal fail with
856
+ * proven-introduced ids is recorded in the R11 ledger, and only then are lineage, drift and the
857
+ * next tier applied to every result, so the handle order and the gates' finishing order never
858
+ * decide a verdict. A background run is one such call.
859
+ * - claim.settle runs in a `finally`; a transient unverifiable (isRetryableVerdict) returns the
860
+ * entry to unverified. A fail carries buildForcingNote with the next tier, and nothing else.
861
+ * `signal` (the tool call's abort) aborts the deadline. `background` (2.4.5, the background
862
+ * queue's own runs only) runs the gates at low priority whatever `lowPriority` says; any other
863
+ * call marks the handles it reported, so no late notice repeats a verdict the caller received.
864
+ */
865
+ verifyHandles(
866
+ sessionID: string,
867
+ target: VerifyTarget,
868
+ options?: { readonly signal?: AbortSignal; readonly background?: boolean },
869
+ ): Promise<VerifyReport>;
870
+ /** 2.4.1: the plugin instance's pending registry (sweep, forgetSession, dispose are wired in index.ts). */
871
+ pending: PendingRegistry;
872
+ /**
873
+ * 2.4.5 (pending.ts R14): the background queue, constructed only when `background` is true at
874
+ * plugin start; undefined otherwise, and nothing then refers to one. The deferred finish feeds
875
+ * it; index.ts reads its late notices in the system transform and forgets a deleted session.
876
+ */
877
+ background: BackgroundQueue | undefined;
878
+ /**
879
+ * 2.1.5b: the crash GC of stale reference dirs, fire-and-forget. QA-2.1-11: it runs `delayMs`
880
+ * (default REFERENCE_GC_START_DELAY_MS) after the call, on an unref'd timer, so plugin start
881
+ * never spawns a git process in the project directory (a process's cwd holds the directory on
882
+ * Windows: EBUSY for whoever removes it). Returns a cancel function for plugin dispose: it
883
+ * clears a pending timer and aborts the git calls of a GC in flight. Never throws.
884
+ */
885
+ startReferenceGc(delayMs?: number): () => void;
886
+ /** P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given. */
887
+ prepareVerification(
888
+ store: ReturnType<typeof createChangedFileStore>,
889
+ id: string,
890
+ childID: string,
891
+ cwd?: string,
892
+ deadline?: Deadline,
893
+ ): Promise<PreparedVerification>;
72
894
  /** Session ids currently running a grader prompt, so hooks can skip them. */
73
895
  graderSessions: Set<string>;
74
- /** Abort then delete a plugin-created child session. Never throws. */
896
+ /** Stop a plugin-created child; v1 deletes it, a host runner owns v2 cleanup. Never throws. */
75
897
  disposeChildSession(sid: string): Promise<void>;
76
898
  /** Run one grader turn, parented to the caller's session when given. */
77
899
  dispatchGrader(
@@ -87,44 +909,250 @@ export interface VerificationWiring {
87
909
  * grader finishes. A caller enforcing a gate budget aborts THAT set — never
88
910
  * the wiring-global one, which belongs to every concurrent delegation at
89
911
  * once.
912
+ *
913
+ * `prepared` supplies the testsPass inputs (changed files, reference, current tree); without it
914
+ * the changed files are "unavailable" and the reference is the untracked default. `deadline`
915
+ * bounds every testsPass step (T3); without it each testsPass check owns one of gateBudgetMs.
90
916
  */
91
- buildGateDeps(parentSessionID?: string, inFlight?: Set<string>): GateDeps;
917
+ buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline): GateDeps;
918
+ /**
919
+ * 2.2.3: the idle-TTL sweep's hook into the plugin's one S5 batch coordinator (batch.ts B11):
920
+ * evicts windows with no live member and batches whose seam hung past BATCH_STALE_GRACE_MS.
921
+ * Returns the number evicted. Never throws.
922
+ */
923
+ sweepVerification(): number;
924
+ /**
925
+ * 2.2.3: plugin dispose. Settles pending batched requests, kills running batches and awaits
926
+ * their scope closes (batch.ts B11). Idempotent; never rejects.
927
+ */
928
+ disposeVerification(): Promise<void>;
929
+ }
930
+
931
+ /** How a bounded wait ended (awaitBounded). */
932
+ export type BoundedOutcome = { kind: "settled" } | { kind: "timeout" } | { kind: "error"; error: unknown };
933
+
934
+ /**
935
+ * Wait for `promise` for at most `ms`. Never rejects; clears its timer; the timer is unref'd so a
936
+ * pending wait never keeps the process alive. The promise itself keeps running after a timeout.
937
+ */
938
+ export function awaitBounded(promise: Promise<unknown>, ms: number): Promise<BoundedOutcome> {
939
+ return new Promise<BoundedOutcome>(resolveOutcome => {
940
+ let done = false;
941
+ const finish = (outcome: BoundedOutcome): void => {
942
+ if (done) return;
943
+ done = true;
944
+ clearTimeout(timer);
945
+ resolveOutcome(outcome);
946
+ };
947
+ const timer = setTimeout(() => finish({ kind: "timeout" }), Math.max(0, ms));
948
+ timer.unref?.();
949
+ promise.then(() => finish({ kind: "settled" }), (error: unknown) => finish({ kind: "error", error }));
950
+ });
951
+ }
952
+
953
+ /** Logging for the dispatch-time wait and the start-up GC. `debug` is optional (PluginLogger has none). */
954
+ export type WiringLogger = Pick<PluginLogger, "warn"> & { debug?: (message: string, extra?: Record<string, unknown>) => void };
955
+
956
+ function splitZ(out: string): string[] {
957
+ return out.split("\0").filter(s => s.length > 0);
958
+ }
959
+
960
+ function errorText(err: unknown): string {
961
+ return scrubText(err instanceof Error ? err.message : String(err));
92
962
  }
93
963
 
94
964
  export function createVerificationWiring(deps: {
95
965
  client: any;
966
+ childRunner?: ChildSessionRunner;
96
967
  /** Project root; relative paths in checks resolve against it. */
97
968
  directory: string;
98
969
  getConfig: () => RouterConfig;
970
+ /** Default: console.warn, no debug output. */
971
+ logger?: WiringLogger;
972
+ /** Test seams of the S5 batch coordinator (clock, timers, platform, maximum window size). */
973
+ batch?: Omit<BatchCoordinatorOptions, "logger">;
974
+ /** Test seams of the pending registry (clock, random source). */
975
+ pending?: Pick<PendingRegistryOptions, "now" | "random">;
976
+ /** Test seams of the 2.4.5 background queue; used only when `background` is true. */
977
+ background?: Pick<BackgroundQueueOptions, "now" | "timers" | "settleMs" | "retryBaseMs" | "maxAttempts" | "platform">;
99
978
  }): VerificationWiring {
100
979
  const { client, directory, getConfig } = deps;
980
+ const logger: WiringLogger = deps.logger ?? { warn: (message, extra) => console.warn(message, extra ?? "") };
101
981
  const graderSessions = new Set<string>();
102
982
  /** Child sessions already torn down; see disposeChildSession. */
103
983
  const disposed = new Set<string>();
104
984
  const mutex = createMutexRegistry();
985
+ /**
986
+ * 2.2.3: one S5 batch coordinator per plugin instance (batch.ts D6). Each gate hands it its own
987
+ * runtime, so a config reload reaches the next window without a new coordinator.
988
+ */
989
+ const coordinator = createBatchCoordinator({ ...deps.batch, logger });
990
+ /**
991
+ * 2.4.1/2.4.2a: one pending registry per plugin instance. Its TTL and abandonment bound are read
992
+ * from the config at plugin start (a reload applies after a restart; the registry holds no timer).
993
+ */
994
+ let pendingBudget: Pick<VerifyBudget, "pendingTtlMs" | "gateBudgetMs" | "background">;
995
+ try {
996
+ pendingBudget = resolveVerifyBudget(getConfig());
997
+ } catch (err) {
998
+ // Plugin start never fails on config: the section 1.4 defaults (background off).
999
+ logger.debug?.("[verify] pending registry uses default bounds: config unreadable", { error: errorText(err) });
1000
+ pendingBudget = { pendingTtlMs: DEFAULT_PENDING_TTL_MS, gateBudgetMs: DEFAULT_GATE_BUDGET_MS, background: false };
1001
+ }
1002
+ const pending = createPendingRegistry({
1003
+ ttlMs: pendingBudget.pendingTtlMs,
1004
+ maxVerifyingMs: pendingBudget.gateBudgetMs + VERIFYING_GRACE_MS,
1005
+ ...deps.pending,
1006
+ onEvict: (entry, cause) => logger.debug?.("[verify] pending delegation evicted", { handle: entry.handle, cause }),
1007
+ });
1008
+ const pendingNow = deps.pending?.now ?? Date.now;
1009
+ /**
1010
+ * 2.4.5: assigned once verifyHandles exists, and only when `background` is true at plugin start
1011
+ * (pending.ts R14). With background off this stays undefined: no queue, no timer, no run.
1012
+ */
1013
+ let background: BackgroundQueue | undefined;
1014
+ /** QA-2.4-5: foreground testsPass requests in flight (the background queue's `busy`). */
1015
+ const foreground = { tests: 0 };
1016
+ /** 2.4.2b: native `task` dispatch starts, before hook -> after hook (bounded FIFO, swept). */
1017
+ const dispatchStarts = new Map<string, DispatchStart>();
1018
+ /**
1019
+ * pending.ts R10: the settled value of each dispatch reference promise, recorded when it settles,
1020
+ * so a deferred finish can tell "already captured at return" without awaiting (0 ms). Keyed by
1021
+ * the promise object (the store returns the same one), so it holds nothing once the store drops it.
1022
+ */
1023
+ const settledReferences = new WeakMap<Promise<ReferenceState>, ReferenceState>();
1024
+ /**
1025
+ * QA-3.1-8: VerifyBudget.lowPriority for the tree snapshots; the section 1.4 default (true) when
1026
+ * the config cannot be read, so a snapshot never fails over it.
1027
+ */
1028
+ const configuredLowPriority = (): boolean => {
1029
+ try {
1030
+ return resolveVerifyBudget(getConfig()).lowPriority;
1031
+ } catch {
1032
+ return true;
1033
+ }
1034
+ };
1035
+ /** QA-3.1-3: dispatches starting together share their snapshot and capture (createSharedFlight). */
1036
+ const sharedSnapshots = createSharedFlight<TreeSnapshot>();
1037
+ const sharedCaptures = createSharedFlight<DispatchReference>();
1038
+ /** The gate-time snapshot of observeChange, shared the same way (keyed by priority, cwd and digest paths). */
1039
+ const sharedGateSnapshots = createSharedFlight<TreeSnapshot>();
105
1040
 
106
- const execSeam = (
107
- command: string,
108
- opts?: { cwd?: string; timeoutMs?: number; signal?: AbortSignal },
109
- ): Promise<ExecResult> =>
1041
+ const abs = (p: string): string => (isAbsolute(p) ? p : join(directory, p));
1042
+
1043
+ // QA-1.2-13: lowPriority and env reach the process; no per-call maxBuffer (QA-1.5-25).
1044
+ const execSeam: ExecSeam = (command: string, opts?: ExecOptions): Promise<ExecResult> =>
110
1045
  runShell(command, {
111
1046
  cwd: opts?.cwd ?? directory,
112
- timeoutMs: opts?.timeoutMs ?? 120000,
1047
+ timeoutMs: opts?.timeoutMs ?? CHECK_TIMEOUT_MS,
1048
+ signal: opts?.signal,
1049
+ lowPriority: opts?.lowPriority,
1050
+ env: opts?.env,
1051
+ });
1052
+
1053
+ const argvSeam: ArgvSeam = (file, args, opts) =>
1054
+ runArgv(file, args, {
1055
+ cwd: opts?.cwd ?? directory,
1056
+ timeoutMs: opts?.timeoutMs ?? CHECK_TIMEOUT_MS,
113
1057
  signal: opts?.signal,
1058
+ lowPriority: opts?.lowPriority,
1059
+ env: opts?.env,
114
1060
  });
115
1061
 
116
- const fsSeam = {
1062
+ // T9 1.3: PlannerFs + unlink over fs.promises. realpath is the native one; fileExists accepts
1063
+ // directories (access does).
1064
+ const fsSeam: RunnerFs = {
117
1065
  async fileExists(p: string): Promise<boolean> {
118
1066
  try {
119
- await access(isAbsolute(p) ? p : join(directory, p));
1067
+ await access(abs(p));
120
1068
  return true;
121
1069
  } catch {
122
1070
  return false;
123
1071
  }
124
1072
  },
125
1073
  async readFile(p: string): Promise<string> {
126
- return await fsReadFile(isAbsolute(p) ? p : join(directory, p), "utf-8");
1074
+ return await fsReadFile(abs(p), "utf-8");
1075
+ },
1076
+ realpath: p => realpath(abs(p)),
1077
+ async stat(p) {
1078
+ const s = await stat(abs(p), { bigint: true });
1079
+ return { isFile: s.isFile(), size: s.size, dev: s.dev, ino: s.ino };
127
1080
  },
1081
+ readdir: p => readdir(abs(p)),
1082
+ async unlink(p) {
1083
+ try {
1084
+ await unlink(abs(p));
1085
+ } catch (err) {
1086
+ // Already gone resolves (RunnerFs contract); anything else is the caller's to report.
1087
+ if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) throw err;
1088
+ }
1089
+ },
1090
+ };
1091
+
1092
+ /**
1093
+ * QA-2.1-12: the files of the commits made since the dispatch snapshot. A shell edit to a file
1094
+ * clean at dispatch, then committed, is invisible to `git status`. Undefined when HEAD did not
1095
+ * move (nothing is spawned) or either snapshot is missing (delta is unavailable then anyway).
1096
+ * "unavailable" when HEAD moved and the diff failed, timed out, or could not run, or when either
1097
+ * head is unknown (e.g. an unborn repository at dispatch).
1098
+ */
1099
+ const committedSinceDispatch = async (
1100
+ before: TreeSnapshot | undefined,
1101
+ now: TreeSnapshot | undefined,
1102
+ deadline: Deadline | undefined,
1103
+ ): Promise<ChangedFile[] | "unavailable" | undefined> => {
1104
+ if (!before || !now || before.head === now.head) return undefined;
1105
+ const root = now.root;
1106
+ if (!root || !OBJECT_NAME.test(before.head) || !OBJECT_NAME.test(now.head)) return "unavailable";
1107
+ const timeoutMs = deadline ? deadline.bound(COMMIT_DIFF_TIMEOUT_MS) : COMMIT_DIFF_TIMEOUT_MS;
1108
+ if (timeoutMs <= 0 || deadline?.signal.aborted) return "unavailable";
1109
+ try {
1110
+ const r = await argvSeam("git", ["--no-optional-locks", "-C", root, "diff", "--name-status", "-z", "-M", before.head, "HEAD"], {
1111
+ cwd: root,
1112
+ timeoutMs,
1113
+ lowPriority: resolveVerifyBudget(getConfig()).lowPriority,
1114
+ ...(deadline ? { signal: deadline.signal } : {}),
1115
+ });
1116
+ if (r.timedOut === true || r.code !== 0) return "unavailable";
1117
+ return parseNameStatusZ(r.stdout, root) ?? "unavailable";
1118
+ } catch {
1119
+ return "unavailable"; // The diff could not run: never the same as "no commit touched a file".
1120
+ }
1121
+ };
1122
+
1123
+ /** T9 1.3: the planners' git searches through the argv seam; no shell, no optional locks. */
1124
+ const testSearch = (budget: VerifyBudget, deadline: Deadline | undefined): TestSearchSeam => {
1125
+ const git = async (root: string, args: readonly string[]): Promise<SeamResult | undefined> => {
1126
+ const timeoutMs = deadline ? deadline.bound(TEST_SEARCH_TIMEOUT_MS) : TEST_SEARCH_TIMEOUT_MS;
1127
+ if (timeoutMs <= 0 || deadline?.signal.aborted) return undefined;
1128
+ try {
1129
+ const r = await argvSeam("git", ["--no-optional-locks", "-C", root, ...args], {
1130
+ cwd: root,
1131
+ timeoutMs,
1132
+ lowPriority: budget.lowPriority,
1133
+ ...(deadline ? { signal: deadline.signal } : {}),
1134
+ });
1135
+ return r.timedOut === true ? undefined : r;
1136
+ } catch {
1137
+ return undefined; // The search could not run: never the same as "no match".
1138
+ }
1139
+ };
1140
+ return {
1141
+ async findByName(gitRoot, names) {
1142
+ // QA-G-3: a name is literal, so its glob metacharacters are bracketed ([*], [[], [\\]):
1143
+ // git on Windows reads a backslash in a pathspec as a separator, not an escape.
1144
+ const lit = (n: string) => n.replace(/[*?[\]\\]/g, c => (c === "\\" ? "[\\\\]" : `[${c}]`));
1145
+ const r = await git(gitRoot, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...names.map(n => `:(glob)**/${lit(n)}`)]);
1146
+ return r && r.code === 0 ? splitZ(r.stdout).map(rel => resolve(gitRoot, rel)) : undefined;
1147
+ },
1148
+ async findByContent(gitRoot, needle, globs, options) {
1149
+ const word = options?.word === true ? ["-w"] : [];
1150
+ const r = await git(gitRoot, ["grep", "-l", "-z", "-F", ...word, "--untracked", "-e", needle, "--", ...globs]);
1151
+ if (!r) return undefined;
1152
+ if (r.code === 1) return [];
1153
+ return r.code === 0 ? splitZ(r.stdout).map(rel => resolve(gitRoot, rel)) : undefined;
1154
+ },
1155
+ };
128
1156
  };
129
1157
 
130
1158
  // Best-effort disposal of a plugin-created child session: abort any in-flight
@@ -153,6 +1181,10 @@ export function createVerificationWiring(deps: {
153
1181
  }
154
1182
  }
155
1183
  disposed.add(sid);
1184
+ if (deps.childRunner) {
1185
+ try { await deps.childRunner.dispose(sid); } catch { /* best-effort cleanup */ }
1186
+ return;
1187
+ }
156
1188
  try {
157
1189
  await client.session.abort({ path: { id: sid } });
158
1190
  } catch {
@@ -170,6 +1202,33 @@ export function createVerificationWiring(deps: {
170
1202
  parentSessionID?: string,
171
1203
  inFlight?: Set<string>,
172
1204
  ): Promise<{ sessionID: string; text: string }> => {
1205
+ if (deps.childRunner) {
1206
+ const cfg = getConfig();
1207
+ const controller = new AbortController();
1208
+ let sid: string | undefined;
1209
+ try {
1210
+ return await withTimeout(deps.childRunner.run({
1211
+ parentSessionID,
1212
+ cwd: req.cwd,
1213
+ model: tierModel(cfg, req.tier) ?? undefined,
1214
+ system: req.system,
1215
+ prompt: req.prompt,
1216
+ signal: controller.signal,
1217
+ async onCreated(sessionID) {
1218
+ sid = sessionID;
1219
+ graderSessions.add(sessionID);
1220
+ inFlight?.add(sessionID);
1221
+ },
1222
+ }), graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs), "grader prompt");
1223
+ } finally {
1224
+ controller.abort();
1225
+ if (sid) {
1226
+ graderSessions.delete(sid);
1227
+ inFlight?.delete(sid);
1228
+ await disposeChildSession(sid);
1229
+ }
1230
+ }
1231
+ }
173
1232
  // Scope the grader session to the producer's working directory when one was
174
1233
  // declared. Naming the directory in the prompt is not enough: the grader
175
1234
  // has real tools, and an unscoped session resolves every read and command
@@ -211,6 +1270,8 @@ export function createVerificationWiring(deps: {
211
1270
  graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs),
212
1271
  "grader prompt",
213
1272
  );
1273
+ const responseError = graderPromptResponseError(res);
1274
+ if (responseError) throw responseError;
214
1275
  return { sessionID: sid, text: extractAssistantText(res) };
215
1276
  } finally {
216
1277
  graderSessions.delete(sid);
@@ -219,17 +1280,116 @@ export function createVerificationWiring(deps: {
219
1280
  }
220
1281
  };
221
1282
 
1283
+ /** What beginDispatch captures for `dod` under the current config (T9 1.1: resolveVerifyBudget). */
1284
+ const captureDepsFor = (dod: DoD): DispatchCaptureDeps => {
1285
+ const cfg = getConfig();
1286
+ const budget = resolveVerifyBudget(cfg);
1287
+ // Only a dispatch that will be judged by testsPass captures a reference (G6: a git-only
1288
+ // capture, never a test run). Read-only fan-outs capture nothing.
1289
+ const judgedByTests = cfg.enforcement?.verify?.require !== "never" && dod.checks.some(
1290
+ c => c.kind === "testsPass" && isCommandAllowed(resolveRepoCommand(c, "testsPass", undefined), DEFAULT_ALLOWLIST),
1291
+ );
1292
+ // QA-3.1-3: one run per key serves every dispatch that asked before it started (same cwd and
1293
+ // the same priority and bound, so the same git processes).
1294
+ const flightKey = (at: string): string => `${budget.lowPriority ? "low" : "normal"}\0${budget.baselineTimeoutMs}\0${at}`;
1295
+ const base = {
1296
+ // QA-3.1-8: the snapshot's git processes run at the configured priority, as the capture's do.
1297
+ snapshot: (at: string, signal: AbortSignal) =>
1298
+ sharedSnapshots(flightKey(at), shared => snapshotTree(at, shared, { lowPriority: budget.lowPriority }), signal),
1299
+ timeoutMs: budget.baselineTimeoutMs,
1300
+ };
1301
+ if (!judgedByTests) return { ...base, uncaptured: { kind: "none", reason: REFERENCE_NONE.notRequested } };
1302
+ if (!budget.failureRecheck) return { ...base, uncaptured: { kind: "disabled" } };
1303
+ // QA-1.2-13: the capture's git processes run at the configured priority too.
1304
+ const argv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
1305
+ return {
1306
+ ...base,
1307
+ capture: (at, signal) =>
1308
+ sharedCaptures(flightKey(at), shared => captureReference(at, shared, { argv, fs: nodeReferenceFs, timeoutMs: budget.baselineTimeoutMs }), signal),
1309
+ };
1310
+ };
1311
+
222
1312
  const buildGateDeps = (
223
1313
  parentSessionID?: string,
224
1314
  inFlight?: Set<string>,
1315
+ prepared?: PreparedVerification,
1316
+ deadline?: Deadline,
1317
+ forceLowPriority = false,
225
1318
  ): GateDeps => {
226
1319
  const cfg = getConfig();
1320
+ const resolved = resolveVerifyBudget(cfg);
1321
+ // 2.4.5 (section 1.5-19): background runs are low priority whatever `lowPriority` says.
1322
+ // QA-2.4-5: and they never wait for the slot (waitMs 0): busy means back off and retry later.
1323
+ const budget: VerifyBudget = forceLowPriority ? { ...resolved, lowPriority: true, slotWaitMs: 0 } : resolved;
1324
+ // QA-2.1-5: the recheck's git processes (GC, materialize, dispose) run at the configured
1325
+ // priority too, like the capture and the start-up GC (QA-1.2-13).
1326
+ const referenceArgv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
1327
+ const openScope = createScopeOpener({
1328
+ argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1329
+ reference: { argv: referenceArgv },
1330
+ });
1331
+ const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
1332
+ const direct = createDirectTestsPassHook({
1333
+ openScope,
1334
+ plannerFs: fsSeam,
1335
+ search: testSearch(budget, deadline),
1336
+ budget,
1337
+ ...currentTree,
1338
+ });
1339
+ // 2.2.3 (S5): with a batch window, concurrent testsPass checks of this plugin instance meet in
1340
+ // the coordinator; the direct hook stays behind it for "full" scope and single requests (B2).
1341
+ // The planner is the direct hook's (planScopedRun over the same PlannerFs and budget), with
1342
+ // its git searches bound to whichever deadline the coordinator plans under (B6).
1343
+ let testsPass: TestsPassHook = direct;
1344
+ const batchWindowMs = effectiveBatchWindowMs(budget);
1345
+ if (batchWindowMs > 0) {
1346
+ const plan: BatchPlanner = (input, planDeadline) => planScopedRun({
1347
+ command: input.command,
1348
+ cwd: input.cwd,
1349
+ changedFiles: input.changedFiles,
1350
+ budget: { maxWorkers: budget.maxWorkers },
1351
+ fs: fsSeam,
1352
+ search: testSearch(budget, planDeadline),
1353
+ });
1354
+ testsPass = coordinator.hook({
1355
+ direct,
1356
+ plan,
1357
+ openScope,
1358
+ batchWindowMs,
1359
+ recheckMinRemainingMs: RECHECK_MIN_REMAINING_MS,
1360
+ failureRecheck: budget.failureRecheck,
1361
+ ...currentTree,
1362
+ });
1363
+ }
1364
+ // QA-2.4-5: foreground testsPass (a required gate, router_verify) takes precedence over a
1365
+ // background run: the run in flight is preempted before this request plans or asks for the
1366
+ // slot, and no background run starts while one is active.
1367
+ if (!forceLowPriority) {
1368
+ const inner = testsPass;
1369
+ testsPass = async request => {
1370
+ foreground.tests += 1;
1371
+ try {
1372
+ void background?.preempt();
1373
+ return await inner(request);
1374
+ } finally {
1375
+ foreground.tests -= 1;
1376
+ }
1377
+ };
1378
+ }
227
1379
  return {
228
1380
  deterministic: {
229
1381
  exec: execSeam,
230
1382
  fs: fsSeam,
231
1383
  cwd: directory,
232
1384
  mutex,
1385
+ argv: argvSeam,
1386
+ budget,
1387
+ openScope,
1388
+ testsPass,
1389
+ // Section 1.5-6: without a change baseline, shell edits are unattributed.
1390
+ changedFiles: prepared?.changeBaseline === "available" ? prepared.changedFiles : "unavailable",
1391
+ ...(prepared !== undefined ? { reference: prepared.reference } : {}),
1392
+ ...(deadline !== undefined ? { deadline } : {}),
233
1393
  },
234
1394
  checker: {
235
1395
  dispatchGrader: (req: GraderRequest) =>
@@ -239,47 +1399,794 @@ export function createVerificationWiring(deps: {
239
1399
  },
240
1400
  require: cfg.enforcement?.verify?.require,
241
1401
  strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
1402
+ canonicalPath,
242
1403
  };
243
1404
  };
244
1405
 
245
- return {
246
- beginVerification(store, id, cwd, dod) {
247
- const verify = getConfig().enforcement?.verify;
248
- const base = resolve(directory, cwd || ".");
249
- // Only a dispatch that will be judged by testsPass captures a baseline. Warming
250
- // the cache from read-only dispatches ran the full suite on every exploration
251
- // fan-out, and the capture was almost always discarded anyway: any shell or
252
- // edit tool in the directory contaminates it.
253
- const commands = dod.checks
254
- .filter(c => c.kind === "testsPass")
255
- .map(c => resolveRepoCommand(c, "testsPass", undefined))
256
- .filter(c => isCommandAllowed(c, DEFAULT_ALLOWLIST));
257
- const budget = verify?.baselineTimeoutMs ?? 60000;
258
- store.beginDispatch(id, base, verify?.testBaseline === false || verify?.require === "never" ? [] : commands, {
259
- snapshot: snapshotTree,
260
- run: (command, cwd, signal) => execSeam(command, { cwd, timeoutMs: budget, signal }),
261
- timeoutMs: budget,
1406
+ const beginVerification: VerificationWiring["beginVerification"] = async (store, id, cwd, dod) => {
1407
+ let deps: DispatchCaptureDeps;
1408
+ try {
1409
+ deps = captureDepsFor(dod);
1410
+ } catch (err) {
1411
+ // Never blocks or fails the dispatch: snapshot only (at the section 1.4 default low priority,
1412
+ // QA-3.1-8), and no reference.
1413
+ deps = {
1414
+ snapshot: (at, signal) => snapshotTree(at, signal, { lowPriority: true }),
1415
+ timeoutMs: DEFAULT_CAPTURE_TIMEOUT_MS,
1416
+ uncaptured: { kind: "none", reason: `${REFERENCE_NONE.failed} (${errorText(err)})` },
1417
+ };
1418
+ }
1419
+ const begun = store.beginDispatch(id, resolve(directory, cwd || "."), deps);
1420
+ // pending.ts R10: remember the reference's settled value (the store hands out one promise).
1421
+ const reference = store.reference(id);
1422
+ if (!settledReferences.has(reference)) void reference.then(state => settledReferences.set(reference, state));
1423
+ await begun;
1424
+ };
1425
+
1426
+ /**
1427
+ * The producer's change since the dispatch: the gate-time snapshot (bounded by `deadline`), the
1428
+ * commits since the dispatch head, and the store's delta. Shared by prepareVerification and the
1429
+ * deferred finish, so both attribute exactly the same files.
1430
+ */
1431
+ const observeChange = async (
1432
+ store: ReturnType<typeof createChangedFileStore>,
1433
+ id: string,
1434
+ childID: string,
1435
+ cwd: string | undefined,
1436
+ deadline: Deadline | undefined,
1437
+ ): Promise<Omit<PreparedVerification, "reference">> => {
1438
+ const base = resolve(directory, cwd || ".");
1439
+ const controller = new AbortController();
1440
+ const onAbort = (): void => controller.abort();
1441
+ deadline?.signal.addEventListener("abort", onAbort, { once: true });
1442
+ let snapshot: TreeSnapshot | undefined;
1443
+ try {
1444
+ const bound = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
1445
+ // QA-2.1-2: digest exactly the paths the dispatch snapshot digested (<= MAX_DIGEST_FILES),
1446
+ // so delta can tell which already-dirty file a shell edit changed.
1447
+ const digests = store.baselineSnapshot(id)?.digests;
1448
+ // QA-3.1-8: at the configured priority, like every other verification process.
1449
+ const lowPriority = configuredLowPriority();
1450
+ const options = digests === undefined
1451
+ ? { lowPriority }
1452
+ : { lowPriority, digestPaths: digests === "unavailable" ? [] : [...digests.keys()] };
1453
+ // QA-3.1-3 at the finish: parallel finishes share one gate-time snapshot per key, and a run
1454
+ // only serves finishes that asked before it started (createSharedFlight), so each still sees
1455
+ // the tree as it was after its own producer returned. Unshared, 20 parallel deferred finishes
1456
+ // spawned 140 git processes and hit DEFERRED_FINISH_MS on a 4-core Windows runner.
1457
+ const digestKey = options.digestPaths === undefined
1458
+ ? "all"
1459
+ : createHash("sha256").update([...options.digestPaths].sort().join("\0")).digest("hex");
1460
+ const key = `${lowPriority ? "low" : "normal"}\0${base}\0${digestKey}`;
1461
+ snapshot = bound > 0 && !controller.signal.aborted
1462
+ ? await withTimeout(
1463
+ sharedGateSnapshots(key, shared => snapshotTree(base, shared, options), controller.signal),
1464
+ bound,
1465
+ "grade fingerprint",
1466
+ )
1467
+ : undefined;
1468
+ } catch {
1469
+ snapshot = undefined; // Explicit unavailable disclaimer, never a raw tree.
1470
+ } finally {
1471
+ deadline?.signal.removeEventListener("abort", onAbort);
1472
+ controller.abort();
1473
+ }
1474
+ const committed = await committedSinceDispatch(store.baselineSnapshot(id), snapshot, deadline);
1475
+ const contaminatedBy = store.snapshotContaminatedBy(id);
1476
+ return {
1477
+ ...store.delta(id, childID, snapshot, base, committed),
1478
+ snapshot,
1479
+ concurrentDispatches: store.concurrentDispatches(id, snapshot?.root),
1480
+ ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
1481
+ };
1482
+ };
1483
+
1484
+ /**
1485
+ * beginVerificationBounded, with the wait counted from `startedAt` (a Date.now() value): the
1486
+ * dispatch waits at most `waitMs` from its start, not `waitMs` after the capture's synchronous
1487
+ * start-up returned. That start-up (config, the snapshot's first git spawn) is the dispatch's
1488
+ * time too, and under load it is not negligible (CI round 1, 3.1.2.f: 20 parallel dispatches on
1489
+ * a 4-core runner held their before hooks up to 104 ms past VERIFY_WAIT). Date.now rather than
1490
+ * performance.now, so fake clocks drive it together with the timer.
1491
+ */
1492
+ const boundedCaptureWait = async (
1493
+ store: ReturnType<typeof createChangedFileStore>,
1494
+ id: string,
1495
+ cwd: string | undefined,
1496
+ dod: DoD,
1497
+ waitOverrideMs: number | undefined,
1498
+ startedAt: number,
1499
+ ): Promise<void> => {
1500
+ let waitMs: number;
1501
+ let begun: Promise<void>;
1502
+ try {
1503
+ waitMs = waitOverrideMs ?? resolveVerifyBudget(getConfig()).captureWaitMs;
1504
+ begun = beginVerification(store, id, cwd, dod);
1505
+ } catch (err) {
1506
+ logger.warn("[verify] dispatch reference capture could not start", { id, error: errorText(err) });
1507
+ return;
1508
+ }
1509
+ // A clock stepped backwards never lengthens the wait past waitMs.
1510
+ const remaining = Math.min(waitMs, Math.max(0, waitMs - (Date.now() - startedAt)));
1511
+ const outcome = await awaitBounded(begun, remaining);
1512
+ if (outcome.kind === "timeout") {
1513
+ logger.debug?.("[verify] dispatch reference not ready; proceeding without waiting further", { id, waitMs });
1514
+ } else if (outcome.kind === "error") {
1515
+ logger.warn("[verify] dispatch reference capture failed; proceeding without a reference", { id, error: errorText(outcome.error) });
1516
+ }
1517
+ };
1518
+
1519
+ const beginVerificationBounded: VerificationWiring["beginVerificationBounded"] = (store, id, cwd, dod, waitOverrideMs) =>
1520
+ boundedCaptureWait(store, id, cwd, dod, waitOverrideMs, Date.now());
1521
+
1522
+ const resolveDirectives = (text: string): VerifyDirectives => {
1523
+ try {
1524
+ const budget = resolveVerifyBudget(getConfig());
1525
+ return parseVerifyDirectives(
1526
+ text,
1527
+ { defaultVerify: budget.defaultVerify, captureWaitMs: budget.captureWaitMs, baselineTimeoutMs: budget.baselineTimeoutMs },
1528
+ message => logger.warn(message),
1529
+ );
1530
+ } catch (err) {
1531
+ // No config, no deferral: today's synchronous gate. QA-2.4-9: with the section 1.4 default
1532
+ // capture wait (clamped to the default baselineTimeoutMs), as 2.1 waited: a producer started
1533
+ // before its capture resolves contaminates it, and pre-existing failures could no longer be
1534
+ // told apart.
1535
+ logger.warn("[verify] dispatch directives could not be resolved; verifying synchronously", { error: errorText(err) });
1536
+ return { mode: "required", waitMs: FALLBACK_CAPTURE_WAIT_MS, modeSource: "default", waitSource: "default" };
1537
+ }
1538
+ };
1539
+
1540
+ /**
1541
+ * Section 1.5-17 "scoping impossible", decided with no process (runner.ts:11): planStaticScoping
1542
+ * for each testsPass check, with the command and cwd the gate would use. The first S6 result wins;
1543
+ * a command outside the allowlist is S6 too (the gate reports it unverifiable). Bounded by the
1544
+ * deferred-finish deadline; an unfinished plan counts as impossible (raises the risk, never lowers it).
1545
+ */
1546
+ const staticScoping = async (
1547
+ dod: DoD,
1548
+ cwd: string | undefined,
1549
+ changedFiles: readonly ChangedPath[],
1550
+ deadline: Deadline,
1551
+ ): Promise<StaticScoping> => {
1552
+ const unfinished: StaticScoping = { unverifiable: true, code: "search-failed", reason: STATIC_SCOPING_UNFINISHED_REASON };
1553
+ const budget = resolveVerifyBudget(getConfig());
1554
+ const at = resolveBaseDir(cwd, directory);
1555
+ const plans: StaticScoping[] = [];
1556
+ for (const check of dod.checks) {
1557
+ if (check.kind !== "testsPass") continue;
1558
+ const command = resolveRepoCommand(check, "testsPass", undefined);
1559
+ if (!isCommandAllowed(command, DEFAULT_ALLOWLIST)) {
1560
+ plans.push({ unverifiable: true, code: "unsupported-command", reason: `command not allowlisted: ${scrubText(command)}` });
1561
+ continue;
1562
+ }
1563
+ const ms = deadline.remaining();
1564
+ if (ms <= 0) {
1565
+ plans.push(unfinished);
1566
+ continue;
1567
+ }
1568
+ try {
1569
+ plans.push(await withTimeout(
1570
+ planStaticScoping({ command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam }),
1571
+ ms,
1572
+ "static scoping",
1573
+ ));
1574
+ } catch {
1575
+ plans.push(unfinished);
1576
+ }
1577
+ }
1578
+ return plans.find(p => "unverifiable" in p) ?? plans[0] ?? unfinished;
1579
+ };
1580
+
1581
+ const finishDeferred: VerificationWiring["finishDeferred"] = async (store, input) => {
1582
+ const producerTier = canonicalTier(input.producerTier);
1583
+ // The live reference promise (no signal: never awaited here). Its settled value at this moment
1584
+ // is the R10 `reference` input; a capture still in flight counts as absent.
1585
+ const reference = store.reference(input.dispatchID);
1586
+ const referenceCaptured = settledReferences.get(reference)?.kind === "captured";
1587
+ const deadline = createDeadline(DEFERRED_FINISH_MS);
1588
+ let risk: RiskAssessment = unattributedRisk();
1589
+ let deferred = false;
1590
+ try {
1591
+ const change = await observeChange(store, input.dispatchID, input.producerSessionID, input.cwd, deadline);
1592
+ // QA-2.4-10: an attributed empty change set is passed by the required gate with no process
1593
+ // (section 1.5-6): nothing to defer. The caller runs that gate, with the same outcome.
1594
+ // QA-G-1: only for a testsPass-only DoD. Any other check (build, lint, run, fileExists,
1595
+ // schemaMatch) or a criterion would be run or graded by that gate synchronously, so such a
1596
+ // DoD stays deferred as a whole, with the attributed empty change set (risk low).
1597
+ if (
1598
+ change.changeBaseline === "available" && change.changedFiles.length === 0 && !deadline.signal.aborted &&
1599
+ noChangeGateSpawnsNothing(input.dod)
1600
+ ) {
1601
+ return { deferred: false, reason: "no-change", detail: "the producer changed no file" };
1602
+ }
1603
+ let changedFiles: ChangedPath[] | "unavailable" = "unavailable";
1604
+ let digests: Promise<FileDigests | undefined> | undefined;
1605
+ // Section 1.5-6 / QA-1.6-14: without a change baseline the set is unknown, never [].
1606
+ if (change.changeBaseline === "available" && !deadline.signal.aborted) {
1607
+ const paths: ChangedPath[] = change.changedFiles.map(f => ({
1608
+ path: f.path,
1609
+ status: f.status,
1610
+ ...(f.previousPath !== undefined ? { previousPath: f.previousPath } : {}),
1611
+ }));
1612
+ changedFiles = paths;
1613
+ const scopingPlan = await staticScoping(input.dod, input.cwd, paths, deadline);
1614
+ risk = assessRisk({ changedFiles: paths, reference: referenceCaptured, producerTier, scopingPlan, root: change.snapshot?.root });
1615
+ // QA-2.4-8: the drift baseline is taken BEFORE the result is released (fs reads only, under
1616
+ // the same DEFERRED_FINISH_MS bound). An edit that lands right after the return is then
1617
+ // drift, never part of the baseline. Not taken in time: no digests, so drift is
1618
+ // "unchecked" and a later pass is downgraded.
1619
+ const taken = await untilAborted(digestFiles(paths.map(p => p.path)), deadline.signal, () => undefined);
1620
+ if (taken !== undefined) digests = Promise.resolve(taken);
1621
+ }
1622
+ const reg = pending.register({
1623
+ orchestratorSessionID: input.orchestratorSessionID,
1624
+ dispatchID: input.dispatchID,
1625
+ producerSessionID: input.producerSessionID,
1626
+ producerTier,
1627
+ description: input.description,
1628
+ cwd: resolveBaseDir(input.cwd, directory),
1629
+ root: change.snapshot?.root,
1630
+ dispatchedAt: input.dispatchedAt,
1631
+ dod: input.dod,
1632
+ reference,
1633
+ changedFiles,
1634
+ risk,
1635
+ ...(digests !== undefined ? { digests } : {}),
1636
+ // QA-3.1-2 / QA-3.1-3: the window ends here (the change set is fixed now); router_verify
1637
+ // adds the caveats to its verdict.
1638
+ ...(change.concurrentDispatches !== undefined && change.concurrentDispatches > 0 ? { concurrentDispatches: change.concurrentDispatches } : {}),
1639
+ ...(change.contaminatedBy !== undefined ? { contaminatedBy: change.contaminatedBy } : {}),
262
1640
  });
1641
+ if (!reg.ok) {
1642
+ // QA-2.4-4: never a delegation without a verdict path: the caller runs the required gate.
1643
+ logger.warn("[verify] deferred delegation not registered; verifying synchronously", { code: reg.code, detail: reg.detail });
1644
+ return { deferred: false, reason: "unregistered", detail: `${reg.code}: ${reg.detail}` };
1645
+ }
1646
+ deferred = true;
1647
+ // 2.4.5 (pending.ts R14): queued, never awaited: the queue's own timer starts the run later.
1648
+ // An unattributed change set is not queued (nothing could run; it stays listed instead).
1649
+ if (background !== undefined && changedFiles !== "unavailable") {
1650
+ try {
1651
+ background.enqueue({ sessionID: input.orchestratorSessionID, handle: reg.handle, files: changedFiles.map(p => p.path) });
1652
+ } catch (err) {
1653
+ // The handle is registered: the delegation stays unverified and listed, as without background.
1654
+ logger.warn("[verify] deferred delegation not queued for background verification", { handle: reg.handle, error: errorText(err) });
1655
+ }
1656
+ }
1657
+ return { deferred: true, footer: buildDeferredFooter({ handle: reg.handle, risk }), handle: reg.handle, risk };
1658
+ } catch (err) {
1659
+ // QA-2.4-4: as for a refused registration, the required gate runs instead.
1660
+ logger.warn("[verify] deferred finish failed; verifying synchronously", { error: errorText(err) });
1661
+ return { deferred: false, reason: "error", detail: errorText(err) };
1662
+ } finally {
1663
+ deadline.dispose();
1664
+ // A deferred dispatch's record goes once the finish has read it (delta) AND its reference
1665
+ // settled: clearing it earlier aborts an in-flight capture (dispatch.ts evict) and ends its
1666
+ // contamination tracking (section 1.5-14). A dispatch that is not deferred keeps it for the
1667
+ // required gate, which clears it as before.
1668
+ if (deferred) void reference.then(() => store.clear(input.dispatchID));
1669
+ }
1670
+ };
1671
+
1672
+ /**
1673
+ * R11, the downgrade half: proven pre-existing ids that an earlier rejection of the same session
1674
+ * and root introduced turn a non-fail verdict into unverifiable with buildLineageCaveat. It never
1675
+ * creates a pass or a fail. Shared by applyLineage and verifyHandles.
1676
+ */
1677
+ const lineageDowngrade = (
1678
+ res: GateResult,
1679
+ ctx: Pick<LineageContext, "orchestratorSessionID" | "root" | "dispatchedAt" | "strictUnverifiable">,
1680
+ ): GateResult => {
1681
+ const failures = res.verdict.failures;
1682
+ if (failures === undefined || ctx.root === undefined || ctx.orchestratorSessionID === "") return res;
1683
+ const outcome = res.verdict.outcome ?? (res.verdict.pass ? "pass" : "fail");
1684
+ if (outcome === "fail" || failures.preexisting.length === 0) return res;
1685
+ const match = pending.findLineage({
1686
+ orchestratorSessionID: ctx.orchestratorSessionID,
1687
+ root: ctx.root,
1688
+ dispatchedAt: ctx.dispatchedAt,
1689
+ preexisting: failures.preexisting,
1690
+ });
1691
+ if (match === undefined) return res;
1692
+ const caveat = buildLineageCaveat(match);
1693
+ return gateResult(
1694
+ { ...res.verdict, pass: false, outcome: "unverifiable", caveats: [...(res.verdict.caveats ?? []), caveat] },
1695
+ res.dodSource,
1696
+ ctx.strictUnverifiable ?? false,
1697
+ );
1698
+ };
1699
+
1700
+ const applyLineage: VerificationWiring["applyLineage"] = (res, ctx) => {
1701
+ const failures = res.verdict.failures;
1702
+ if (failures === undefined || ctx.root === undefined || ctx.orchestratorSessionID === "") return res;
1703
+ const outcome = res.verdict.outcome ?? (res.verdict.pass ? "pass" : "fail");
1704
+ if (outcome === "fail") {
1705
+ if (failures.introduced.length > 0) {
1706
+ pending.recordRejection({
1707
+ orchestratorSessionID: ctx.orchestratorSessionID,
1708
+ root: ctx.root,
1709
+ label: `dispatch ${ctx.dispatchID}`,
1710
+ landedAt: ctx.returnedAt,
1711
+ introduced: failures.introduced,
1712
+ });
1713
+ }
1714
+ return res;
1715
+ }
1716
+ return lineageDowngrade(res, ctx);
1717
+ };
1718
+
1719
+ /** 2.4.3a: the current tree for one call, once per cwd (the materialize same-repository guard, P0). */
1720
+ const snapshotFor = async (cwd: string, deadline: Deadline, lowPriority: boolean): Promise<TreeSnapshot | undefined> => {
1721
+ const controller = new AbortController();
1722
+ const onAbort = (): void => controller.abort();
1723
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
1724
+ try {
1725
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
1726
+ if (bound <= 0 || controller.signal.aborted) return undefined;
1727
+ // No digests: the drift check digests the producer's files itself (checkDrift).
1728
+ return await withTimeout(snapshotTree(cwd, controller.signal, { digestPaths: [], lowPriority }), bound, "router_verify fingerprint");
1729
+ } catch {
1730
+ return undefined; // No current tree: materialize skips its same-repository guard, as without a snapshot.
1731
+ } finally {
1732
+ deadline.signal.removeEventListener("abort", onAbort);
1733
+ controller.abort();
1734
+ }
1735
+ };
1736
+
1737
+ /**
1738
+ * 2.4.3a, section 1.5-18: the producer's files now against their digests right after it returned.
1739
+ * "unchecked" whenever either side is missing (no change set, no stored digests, a digest that
1740
+ * could not be taken, or the deadline): never a claim of "no drift" without proof.
1741
+ */
1742
+ const checkDrift = async (entry: PendingEntry, deadline: Deadline): Promise<DriftCheck> => {
1743
+ if (entry.changedFiles === "unavailable" || entry.digests === undefined) return { kind: "unchecked" };
1744
+ const before = await untilAborted(entry.digests, deadline.signal, () => undefined);
1745
+ if (before === undefined) return { kind: "unchecked" };
1746
+ const after = await untilAborted(digestFiles([...before.keys()]), deadline.signal, () => undefined);
1747
+ if (after === undefined) return { kind: "unchecked" };
1748
+ const paths = driftedPaths(before, after);
1749
+ return paths.length > 0 ? { kind: "drifted", paths } : { kind: "none" };
1750
+ };
1751
+
1752
+ interface ClaimPreparation {
1753
+ readonly prepared: PreparedVerification;
1754
+ readonly drift: DriftCheck;
1755
+ /** R11 root: the registered one, else the current tree's. */
1756
+ readonly root: string | undefined;
1757
+ }
1758
+
1759
+ /** One claimed entry after its gate: a final result, or the raw gate result still to be judged. */
1760
+ type ClaimGate =
1761
+ | { readonly kind: "final"; readonly result: VerificationResult }
1762
+ | { readonly kind: "gate"; readonly res: GateResult; readonly retryable: boolean; readonly strict: boolean };
1763
+
1764
+ /** 2.4.3a P0 from the pending entry: stored change set and reference, current tree, drift. */
1765
+ const prepareClaim = async (
1766
+ entry: PendingEntry,
1767
+ deadline: Deadline,
1768
+ snapshots: Map<string, Promise<TreeSnapshot | undefined>>,
1769
+ lowPriority: boolean,
1770
+ ): Promise<ClaimPreparation> => {
1771
+ let snapshot = snapshots.get(entry.cwd);
1772
+ if (snapshot === undefined) {
1773
+ snapshot = snapshotFor(entry.cwd, deadline, lowPriority);
1774
+ snapshots.set(entry.cwd, snapshot);
1775
+ }
1776
+ const [reference, drift, tree] = await Promise.all([
1777
+ // The same bound as the store's reference(id, signal): a capture still pending at the deadline
1778
+ // is "no reference (gate budget)".
1779
+ untilAborted<ReferenceState>(entry.reference, deadline.signal, () => ({ kind: "none", reason: REFERENCE_NONE.gateBudget })),
1780
+ checkDrift(entry, deadline),
1781
+ snapshot,
1782
+ ]);
1783
+ const changed = entry.changedFiles;
1784
+ return {
1785
+ prepared: {
1786
+ changedFiles: changed === "unavailable"
1787
+ ? []
1788
+ : changed.map(c => ({ path: c.path, status: c.status ?? "", ...(c.previousPath !== undefined ? { previousPath: c.previousPath } : {}) })),
1789
+ // Section 1.5-6: an unattributed change set stays unattributed (never []).
1790
+ changeBaseline: changed === "unavailable" ? "unavailable" : "available",
1791
+ reference,
1792
+ snapshot: tree,
1793
+ },
1794
+ drift,
1795
+ root: entry.root ?? tree?.root,
1796
+ };
1797
+ };
1798
+
1799
+ /**
1800
+ * 2.4.3a: the required gate on one claimed entry (index.ts's sequence: buildGateDeps, accept
1801
+ * under withTimeout(deadline.remaining()), unverifiableGateResult on a reject). A timeout aborts
1802
+ * the shared deadline (every member is out of budget at that instant anyway) and this gate's
1803
+ * graders; any other error leaves the other handles running. Returns either a final result
1804
+ * (nothing was judged) or the raw gate result that judgeVerdict finishes once EVERY gate of the
1805
+ * call has returned (QA-2.4-1).
1806
+ */
1807
+ const runClaimGate = async (
1808
+ entry: PendingEntry,
1809
+ prep: ClaimPreparation,
1810
+ deadline: OwnedDeadline,
1811
+ cfg: RouterConfig,
1812
+ callSignal: AbortSignal | undefined,
1813
+ lowPriority: boolean,
1814
+ ): Promise<ClaimGate> => {
1815
+ const dod = entry.dod;
1816
+ // A claimed entry is never released (release happens on a terminal settle only).
1817
+ if (dod === undefined) return { kind: "final", result: { verdict: unverifiableVerdict(ROUTER_VERIFY_RELEASED_REASON), retryable: false } };
1818
+ const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
1819
+ const inFlight = new Set<string>();
1820
+ const completedFailures: string[] = [];
1821
+ const gateDeps = buildGateDeps(entry.orchestratorSessionID, inFlight, prep.prepared, deadline, lowPriority);
1822
+ gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
1823
+ const artefact = {
1824
+ changedFiles: prep.prepared.changedFiles,
1825
+ changeBaseline: prep.prepared.changeBaseline,
1826
+ // Not stored (R3): a testsPass DoD is deterministic, and no deterministic check reads it.
1827
+ finalReturnText: "",
1828
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
1829
+ producerSessionID: entry.producerSessionID,
1830
+ producerTier: entry.producerTier,
1831
+ };
1832
+ let res: GateResult;
1833
+ let timedOut = false;
1834
+ try {
1835
+ res = await withTimeout(
1836
+ accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd }, artefact, gateDeps),
1837
+ deadline.remaining(),
1838
+ "verification gate",
1839
+ );
1840
+ } catch (error) {
1841
+ timedOut = error instanceof RouterTimeoutError;
1842
+ if (timedOut) {
1843
+ deadline.abort("verification gate timed out");
1844
+ for (const gsid of inFlight) {
1845
+ try {
1846
+ await client.session.abort({ path: { id: gsid } });
1847
+ } catch (abortError) {
1848
+ logger.debug?.("[verify] router_verify could not abort a grader", { error: errorText(abortError) });
1849
+ }
1850
+ }
1851
+ }
1852
+ res = unverifiableGateResult(
1853
+ timedOut ? `verification gate timed out after ${deadline.budgetMs}ms` : `verification unavailable: ${errorText(error)}`,
1854
+ dod.source,
1855
+ strict,
1856
+ completedFailures,
1857
+ );
1858
+ }
1859
+ // verify.require "never" answers skipped: nothing was judged, so the entry stays unverified.
1860
+ if (res.verdict.skipped === true) return { kind: "final", result: { verdict: res.verdict, retryable: true } };
1861
+ // Decided on the gate's own verdict, before any router caveat (lineage, drift) is added.
1862
+ const retryable = isRetryableVerdict(res.verdict, timedOut || deadline.signal.aborted || callSignal?.aborted === true);
1863
+ return { kind: "gate", res, retryable, strict };
1864
+ };
1865
+
1866
+ /** QA-2.4-1: the proven-introduced ids of a terminal gate fail (what a required gate records). */
1867
+ const introducedOf = (gate: ClaimGate): readonly string[] => {
1868
+ if (gate.kind !== "gate" || gate.retryable) return [];
1869
+ const outcome = gate.res.verdict.outcome ?? (gate.res.verdict.pass ? "pass" : "fail");
1870
+ return outcome === "fail" ? (gate.res.verdict.failures?.introduced ?? []) : [];
1871
+ };
1872
+
1873
+ /**
1874
+ * 2.4.3a: one claimed entry's verdict from its raw gate result: R11 lineage, then the drift rule,
1875
+ * then the next tier. Runs only after every rejection of the call is in the ledger (QA-2.4-1).
1876
+ */
1877
+ const judgeVerdict = (entry: PendingEntry, prep: ClaimPreparation, gate: ClaimGate, cfg: RouterConfig): VerificationResult => {
1878
+ if (gate.kind === "final") return gate.result;
1879
+ const { strict, retryable } = gate;
1880
+ // QA-3.1-2 / QA-3.1-3: the dispatch's own context, recorded when the producer returned.
1881
+ const res = applyDispatchCaveats(
1882
+ lineageDowngrade(gate.res, { orchestratorSessionID: entry.orchestratorSessionID, root: prep.root, dispatchedAt: entry.dispatchedAt, strictUnverifiable: strict }),
1883
+ entry,
1884
+ );
1885
+ let verdict = res.verdict;
1886
+ if (prep.drift.kind !== "none") {
1887
+ // Section 1.5-18 and the owner's rule: a verdict on a tree that is not (provably) the
1888
+ // producer's never passes; it is unverifiable with the notice. A fail stays a fail.
1889
+ const notice = prep.drift.kind === "drifted" ? DRIFT_NOTICE : DRIFT_UNCHECKED_NOTICE;
1890
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
1891
+ verdict = gateResult(
1892
+ {
1893
+ ...verdict,
1894
+ ...(outcome === "pass" ? { pass: false, outcome: "unverifiable" as const } : {}),
1895
+ caveats: [...(verdict.caveats ?? []), notice],
1896
+ },
1897
+ res.dodSource,
1898
+ strict,
1899
+ ).verdict;
1900
+ }
1901
+ const judged = gateResult(verdict, res.dodSource, strict);
1902
+ const outcome = judged.verdict.outcome;
1903
+ let nextTier: string | undefined;
1904
+ if (!judged.accepted && outcome === "fail") {
1905
+ // index.ts's rule for the native path: the ladder's next tier after the producer's.
1906
+ const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
1907
+ const li = ladder.findIndex(t => canonicalTier(t) === entry.producerTier);
1908
+ if (li >= 0 && li < ladder.length - 1) nextTier = ladder[li + 1];
1909
+ }
1910
+ const introduced = outcome === "fail" ? judged.verdict.failures?.introduced : undefined;
1911
+ return {
1912
+ verdict: judged.verdict,
1913
+ retryable,
1914
+ ...(introduced !== undefined && introduced.length > 0 ? { introduced } : {}),
1915
+ ...(prep.drift.kind === "drifted" ? { driftedPaths: prep.drift.paths } : {}),
1916
+ ...(nextTier !== undefined ? { nextTier } : {}),
1917
+ };
1918
+ };
1919
+
1920
+ const verifyHandles: VerificationWiring["verifyHandles"] = async (sessionID, target, options = {}) => {
1921
+ let deadline: OwnedDeadline | undefined;
1922
+ const callSignal = options.signal;
1923
+ const onCallAbort = (): void => deadline?.abort(ROUTER_VERIFY_CANCELLED_REASON);
1924
+ try {
1925
+ // 1. Targets: normalized, deduped, capped (R2). `pending` = listOpen, so in-flight runs join.
1926
+ let targets: Array<{ readonly input: string; readonly handle: string | undefined }> = [];
1927
+ if (target.kind === "pending") {
1928
+ // QA-2.4-3: listPending adds the background verdicts not yet replayed (a cached replay, no run).
1929
+ if (sessionID !== "") targets = pending.listPending(sessionID, { verifying: true }).map(e => ({ input: e.handle, handle: e.handle }));
1930
+ if (targets.length === 0) return { items: [], excess: 0, text: ROUTER_VERIFY_NO_PENDING_TEXT };
1931
+ } else {
1932
+ const seen = new Set<string>();
1933
+ for (const raw of target.handles) {
1934
+ const input = typeof raw === "string" ? raw : "(not a string)";
1935
+ const handle = typeof raw === "string" ? normalizeHandle(raw) : undefined;
1936
+ const key = handle ?? `raw:${input}`;
1937
+ if (seen.has(key)) continue;
1938
+ seen.add(key);
1939
+ targets.push({ input, handle });
1940
+ }
1941
+ }
1942
+ const excess = Math.max(0, targets.length - MAX_HANDLES_PER_CALL);
1943
+ targets = targets.slice(0, MAX_HANDLES_PER_CALL);
1944
+
1945
+ // 2. The call's one deadline (section 1.5-13), before any preparation.
1946
+ const cfg = getConfig();
1947
+ const budget = resolveVerifyBudget(cfg);
1948
+ const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
1949
+ deadline = createDeadline(budget.gateBudgetMs);
1950
+ const owned = deadline;
1951
+ if (callSignal?.aborted === true) owned.abort(ROUTER_VERIFY_CANCELLED_REASON);
1952
+ else callSignal?.addEventListener("abort", onCallAbort, { once: true });
1953
+
1954
+ // QA-2.4-5: router_verify is foreground work. A background run in flight is preempted, and
1955
+ // its claims settle (retryable) before this call claims, so no handle joins a run that is
1956
+ // being aborted. The wait is bounded by this call's deadline.
1957
+ if (options.background !== true && background !== undefined && targets.length > 0 && sessionID !== "") {
1958
+ await untilAborted(background.preempt(), owned.signal, () => undefined);
1959
+ }
1960
+
1961
+ // 3. Claims (R8: synchronous, so two calls for one handle make one "claimed").
1962
+ type Claimed = Extract<ReturnType<PendingRegistry["markVerifying"]>, { kind: "claimed" }>;
1963
+ const claims: Claimed[] = [];
1964
+ const slots: Array<HandleReport | Promise<HandleReport> | { readonly claim: number }> = [];
1965
+ const cwds = new Map<string, string>();
1966
+ try {
1967
+ for (const t of targets) {
1968
+ if (t.handle === undefined || sessionID === "") {
1969
+ slots.push({ kind: "unknown", input: t.handle ?? t.input });
1970
+ continue;
1971
+ }
1972
+ const c = pending.markVerifying(sessionID, t.handle);
1973
+ if (c.kind === "unknown") slots.push({ kind: "unknown", input: t.handle });
1974
+ else if (c.kind === "expired") slots.push({ kind: "expired", handle: c.handle });
1975
+ else if (c.kind === "settled") {
1976
+ slots.push({ kind: "verdict", handle: c.entry.handle, description: c.entry.description, producerTier: c.entry.producerTier, via: "cached", result: c.result });
1977
+ } else if (c.kind === "joined") {
1978
+ const entry = c.entry;
1979
+ cwds.set(entry.handle, entry.cwd);
1980
+ slots.push(
1981
+ untilAborted<SettledVerification | undefined>(c.run, owned.signal, () => undefined).then((settled): HandleReport =>
1982
+ settled === undefined
1983
+ ? { kind: "elsewhere", handle: entry.handle, description: entry.description }
1984
+ : { kind: "verdict", handle: entry.handle, description: entry.description, producerTier: entry.producerTier, via: "joined", result: settled },
1985
+ ),
1986
+ );
1987
+ } else {
1988
+ cwds.set(c.entry.handle, c.entry.cwd);
1989
+ slots.push({ claim: claims.length });
1990
+ claims.push(c);
1991
+ }
1992
+ }
1993
+ } catch (error) {
1994
+ // Never leave a claim verifying until the reaper: settle what was claimed, retryable.
1995
+ for (const c of claims) c.settle({ verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true });
1996
+ throw error;
1997
+ }
1998
+
1999
+ // 4. Every preparation first, then every gate at once: the testsPass requests share the
2000
+ // deadline and reach the S5 coordinator together (one window, one batch).
2001
+ const snapshots = new Map<string, Promise<TreeSnapshot | undefined>>();
2002
+ // QA-3.1-8: the current-tree snapshot at the configured priority; a background run's always low.
2003
+ const preparations = claims.map(c => prepareClaim(c.entry, owned, snapshots, budget.lowPriority || options.background === true));
2004
+ const allPrepared = Promise.allSettled(preparations);
2005
+ const gates = claims.map(async (c, i): Promise<{ readonly prep: ClaimPreparation | undefined; readonly gate: ClaimGate }> => {
2006
+ let prep: ClaimPreparation | undefined;
2007
+ try {
2008
+ prep = await preparations[i];
2009
+ await allPrepared;
2010
+ return { prep, gate: await runClaimGate(c.entry, prep, owned, cfg, callSignal, options.background === true) };
2011
+ } catch (error) {
2012
+ return { prep, gate: { kind: "final", result: { verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true } } };
2013
+ }
2014
+ });
2015
+ // 5. QA-2.4-1: judged in two phases. A verdict of this call must see every rejection of this
2016
+ // call, as it would across two calls or two required gates: (a) every gate returns;
2017
+ // (b) every terminal fail with proven-introduced ids goes into the R11 ledger; (c) lineage,
2018
+ // drift and the next tier are applied to every result; (d) every claim settles.
2019
+ const judged = (async (): Promise<void> => {
2020
+ const results: VerificationResult[] = claims.map(() => ({ verdict: unverifiableVerdict("verification unavailable: no verdict"), retryable: true }));
2021
+ try {
2022
+ const outcomes = await Promise.all(gates);
2023
+ outcomes.forEach(({ prep, gate }, i) => {
2024
+ const introduced = introducedOf(gate);
2025
+ const root = prep?.root;
2026
+ if (introduced.length === 0 || root === undefined) return;
2027
+ const entry = claims[i].entry;
2028
+ pending.recordRejection({ orchestratorSessionID: entry.orchestratorSessionID, root, label: entry.handle, landedAt: entry.createdAt, introduced });
2029
+ });
2030
+ outcomes.forEach(({ prep, gate }, i) => {
2031
+ if (prep !== undefined) results[i] = judgeVerdict(claims[i].entry, prep, gate, cfg);
2032
+ else if (gate.kind === "final") results[i] = gate.result;
2033
+ // QA-2.4-3: a background verdict that did not pass stays listed until it is replayed.
2034
+ if (options.background === true) results[i] = { ...results[i], background: true };
2035
+ });
2036
+ } catch (error) {
2037
+ for (let i = 0; i < results.length; i += 1) {
2038
+ results[i] = { verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true };
2039
+ }
2040
+ } finally {
2041
+ // R4: single use, in a finally; false only when the claim was reaped or disposed.
2042
+ claims.forEach((c, i) => {
2043
+ if (!c.settle(results[i])) logger.debug?.("[verify] router_verify settled a claim that was already reaped", { handle: c.entry.handle });
2044
+ });
2045
+ }
2046
+ })();
2047
+ const runs = claims.map(async (c): Promise<HandleReport> => {
2048
+ await judged;
2049
+ const settled = await c.run;
2050
+ return { kind: "verdict", handle: c.entry.handle, description: c.entry.description, producerTier: c.entry.producerTier, via: "run", result: settled };
2051
+ });
2052
+
2053
+ const items = await Promise.all(slots.map(s => ("claim" in s ? runs[s.claim] : s)));
2054
+ // 2.4.5: this caller receives these verdicts, so no late notice repeats them (R14), and a
2055
+ // background verdict among them leaves the pending list (QA-2.4-3). QA-2.4-17: only a
2056
+ // terminal verdict counts; a retryable "not judged" leaves a later background verdict to notice.
2057
+ if (options.background !== true) {
2058
+ const reported = items.flatMap(i => (i.kind === "verdict" && !i.result.retryable ? [i.handle] : []));
2059
+ background?.markReported(reported);
2060
+ pending.markReplayed(sessionID, reported);
2061
+ }
2062
+ return { items, excess, text: formatVerifyReport(items, excess, strict, h => cwds.get(h)) };
2063
+ } catch (error) {
2064
+ logger.warn("[verify] router_verify failed", { error: errorText(error) });
2065
+ return { items: [], excess: 0, text: `[router] router_verify failed; nothing was verified: ${errorText(error)}` };
2066
+ } finally {
2067
+ callSignal?.removeEventListener("abort", onCallAbort);
2068
+ deadline?.dispose();
2069
+ }
2070
+ };
2071
+
2072
+ // 2.4.5 (section 1.5-19, pending.ts R14): only when `background` is true at plugin start. A run is
2073
+ // this instance's own verifyHandles, so it claims, gates, batches and settles exactly as
2074
+ // router_verify does, at low priority.
2075
+ if (pendingBudget.background) {
2076
+ background = createBackgroundQueue({
2077
+ ...deps.background,
2078
+ ttlMs: pendingBudget.pendingTtlMs,
2079
+ verify: async (sessionID, handles, signal) =>
2080
+ backgroundOutcomes((await verifyHandles(sessionID, { kind: "handles", handles }, { signal, background: true })).items),
2081
+ onError: error => logger.warn("[verify] background verification run failed", { error: errorText(error) }),
2082
+ // QA-2.4-5: no background run starts while foreground testsPass verification is active.
2083
+ busy: () => foreground.tests > 0,
2084
+ });
2085
+ }
2086
+
2087
+ return {
2088
+ beginVerification,
2089
+ resolveDirectives,
2090
+ async startDispatch(store, id, cwd, dod, text, remember) {
2091
+ // VERIFY_WAIT counts from here, the dispatch's start (see boundedCaptureWait).
2092
+ const startedAt = Date.now();
2093
+ const start: DispatchStart = { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
2094
+ if (remember) {
2095
+ dispatchStarts.delete(id);
2096
+ dispatchStarts.set(id, start);
2097
+ while (dispatchStarts.size > DISPATCH_STARTS_MAX) {
2098
+ const oldest = dispatchStarts.keys().next();
2099
+ if (oldest.done === true) break;
2100
+ dispatchStarts.delete(oldest.value);
2101
+ }
2102
+ }
2103
+ await boundedCaptureWait(store, id, cwd, dod, start.directives.waitMs, startedAt);
2104
+ return start;
263
2105
  },
264
- async prepareVerification(store, id, childID, cwd) {
265
- const controller = new AbortController();
266
- let current;
2106
+ takeDispatch(id, text) {
2107
+ const start = dispatchStarts.get(id);
2108
+ if (start !== undefined) {
2109
+ dispatchStarts.delete(id);
2110
+ return start;
2111
+ }
2112
+ return { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
2113
+ },
2114
+ isDeferred(dod, directives, trivial = false) {
2115
+ if (directives.mode !== "deferred" || !hasTestsPass(dod)) return false;
2116
+ // QA-2.4-10: gate.ts skips exactly this case ("trivial dispatch; verification skipped").
2117
+ if (trivial && dod.source === "inferred") return false;
267
2118
  try {
268
- current = await withTimeout(snapshotTree(resolve(directory, cwd || "."), controller.signal), 10000, "grade fingerprint");
2119
+ return getConfig().enforcement?.verify?.require !== "never";
269
2120
  } catch {
270
- current = undefined; // Explicit unavailable disclaimer, never a raw tree.
271
- } finally {
272
- controller.abort();
2121
+ return false;
2122
+ }
2123
+ },
2124
+ finishDeferred,
2125
+ applyLineage,
2126
+ verifyHandles,
2127
+ pending,
2128
+ background,
2129
+ beginVerificationBounded,
2130
+ startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS) {
2131
+ if (!directory) {
2132
+ logger.debug?.("[verify] reference GC skipped: plugin root unknown");
2133
+ return () => undefined;
273
2134
  }
274
- return {
275
- ...store.delta(id, childID, current, resolve(directory, cwd || ".")),
276
- testBaseline: command => getConfig().enforcement?.verify?.testBaseline === false
277
- ? Promise.resolve(undefined) : store.baseline(id, command, current?.head),
2135
+ const stop = new AbortController();
2136
+ const run = (): void => {
2137
+ if (stop.signal.aborted) return;
2138
+ try {
2139
+ const budget = resolveVerifyBudget(getConfig());
2140
+ // Low priority (QA-1.2-13), and every git call dies with the plugin (dispose).
2141
+ const argv: ArgvSeam = (file, args, opts) => argvSeam(file, args, {
2142
+ ...opts,
2143
+ lowPriority: budget.lowPriority,
2144
+ signal: opts?.signal ? AbortSignal.any([opts.signal, stop.signal]) : stop.signal,
2145
+ });
2146
+ gcStaleReferences(directory, { argv, fs: nodeReferenceFs, logger }).then(
2147
+ report => {
2148
+ if (report.removed.length > 0) logger.debug?.("[verify] reference GC removed stale dirs", { removed: report.removed.length });
2149
+ },
2150
+ (err: unknown) => logger.warn("[verify] reference GC failed", { error: errorText(err) }),
2151
+ );
2152
+ } catch (err) {
2153
+ logger.warn("[verify] reference GC failed", { error: errorText(err) });
2154
+ }
278
2155
  };
2156
+ const timer = setTimeout(run, Math.max(0, delayMs));
2157
+ timer.unref?.();
2158
+ return () => {
2159
+ clearTimeout(timer);
2160
+ stop.abort();
2161
+ };
2162
+ },
2163
+ async prepareVerification(store, id, childID, cwd, deadline) {
2164
+ const change = await observeChange(store, id, childID, cwd, deadline);
2165
+ const reference = await store.reference(id, deadline?.signal);
2166
+ return { ...change, reference };
279
2167
  },
280
2168
  graderSessions,
281
2169
  disposeChildSession,
282
2170
  dispatchGrader,
283
2171
  buildGateDeps,
2172
+ sweepVerification: () => {
2173
+ // Native task starts whose after hook never came (the call was cancelled), past the idle TTL.
2174
+ const at = pendingNow();
2175
+ let evicted = 0;
2176
+ for (const [id, start] of [...dispatchStarts]) {
2177
+ if (at - start.dispatchedAt >= DEFAULT_IDLE_TTL_MS) {
2178
+ dispatchStarts.delete(id);
2179
+ evicted += 1;
2180
+ }
2181
+ }
2182
+ // 2.4.5: undelivered late notices past pendingTtlMs; also the queue's idle trigger.
2183
+ return evicted + coordinator.sweep() + (background?.sweep() ?? 0);
2184
+ },
2185
+ disposeVerification: () => {
2186
+ dispatchStarts.clear();
2187
+ // 2.4.5: abort the background run first, so nothing re-queues while the coordinator stops.
2188
+ background?.dispose();
2189
+ return coordinator.dispose();
2190
+ },
284
2191
  };
285
2192
  }