opencode-model-router 2.8.0 → 2.9.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -15,6 +15,8 @@
15
15
  */
16
16
  import { createHash } from "node:crypto";
17
17
  import type { ChildSessionRunner } from "../compat/child-session";
18
+ import { completionIdentity, observeV2, type ServiceIdentity, type V2Observations } from "../compat/v2-observations";
19
+ import { serviceObservation, type ServiceObservation } from "../executor/observations";
18
20
  import { access, readdir, readFile as fsReadFile, realpath, stat, unlink } from "node:fs/promises";
19
21
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
20
22
  import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
@@ -90,9 +92,10 @@ import { PERIMETER_MAX } from "./perimeter";
90
92
  import { defaultExternalLinks, pinTarget, type LinkPin } from "./pin";
91
93
  import { depthBelow, gitTopOf, perimeterKey } from "./git-top";
92
94
  import type { DispatchPerimeter, PerimeterEntry } from "./dispatch";
93
- import { branchSwitched, branchSwitchReason, branchUnconfirmedReason, treeMove, treeMoveReason } from "./branch";
95
+ import { AFTER_RESTART_WINDOW, branchSwitched, branchSwitchReason, branchUnconfirmedReason, treeMove, treeMoveReason } from "./branch";
94
96
  import { readHead, readHeadState, readReflogWindow, type HeadState, type ReflogEntry } from "./head";
95
- import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, nodeReferenceFs, type DispatchReference } from "./reference";
97
+ import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, keepReferences, nodeReferenceFs, REF_DIR_PATTERN, serializedReferenceLinks, type DispatchReference } from "./reference";
98
+ import { HEAD_LOST_REASON, PERIMETER_LOST_REASON, type PendingRecord } from "./pending";
96
99
  import type { PluginLogger } from "../router/logger";
97
100
  import { REFERENCE_NONE } from "./baseline";
98
101
  import { scrubText } from "../guard/scrub";
@@ -173,6 +176,10 @@ function graderPromptResponseError(res: unknown): Error | undefined {
173
176
 
174
177
  /** P0 (deterministic.ts header, T2): what a gate needs from its dispatch. */
175
178
  export interface PreparedVerification {
179
+ /** v2 diagnostics only; never contributes to the verdict. */
180
+ service?: ServiceObservation;
181
+ /** Plan-task identity for v2 grader-dispatch failure logs, including when observations are off. */
182
+ graderDispatchLabel?: string;
176
183
  /**
177
184
  * The producer's changed files: the tool-observed paths of every attempt judged against this
178
185
  * dispatch (QA-2.1-1), the paths the current snapshot added since dispatch, and the paths dirty
@@ -192,6 +199,11 @@ export interface PreparedVerification {
192
199
  concurrentDispatches?: number;
193
200
  /** QA-3.1-3: the tool whose call discarded the dispatch snapshot, which left the change set unavailable. */
194
201
  contaminatedBy?: string;
202
+ /**
203
+ * QA-2.1-11 (phase 2.1, v2 only): the producer's session. Its own tree leases are still held while its gate runs, so the
204
+ * gate's lease wait leaves them out. Absent or "": none known.
205
+ */
206
+ producerSessionID?: string;
195
207
  /**
196
208
  * I7 (P0.2, S9/S12): the gate's unverifiable reason when the working tree switched branch (branch.ts); absent: no switch
197
209
  * seen. The artefact builders hand it to the gate (Artefact.branchSwitch), which then refuses on either verifier.
@@ -414,6 +426,20 @@ export const DRIFT_DIGEST_MAX_BYTES = 64 * 1024 * 1024;
414
426
  export const STATIC_SCOPING_UNFINISHED_REASON = "static scoping did not finish within the deferred-finish bound";
415
427
  /** Section 1.4 pendingTtlMs default, used when the config cannot be read at plugin start. */
416
428
  export const DEFAULT_PENDING_TTL_MS = 3_600_000;
429
+
430
+ /**
431
+ * QA-2.1-27: the resolved `enforcement.verify.pendingTtlMs` at plugin start, as the pending registry reads it
432
+ * (`createVerificationWiring`); the section 1.4 default when the config cannot be read. The v2 pending journal
433
+ * compacts and reloads with it. Never throws.
434
+ */
435
+ export function resolvePendingTtlMs(config: RouterConfig): number {
436
+ try {
437
+ return resolveVerifyBudget(config).pendingTtlMs;
438
+ } catch (err) {
439
+ void err; // plugin start never fails on config: the default bound, as the pending registry falls back
440
+ return DEFAULT_PENDING_TTL_MS;
441
+ }
442
+ }
417
443
  /**
418
444
  * QA-2.4-9: the capture wait when the config cannot be read: section 1.4's captureWaitMs default
419
445
  * (5000 ms), clamped to the default baselineTimeoutMs (DEFAULT_CAPTURE_TIMEOUT_MS), as config.ts does.
@@ -455,6 +481,12 @@ export interface DeferredFinishInput {
455
481
  * the gate runs as before (I1).
456
482
  */
457
483
  readonly workRoot?: string;
484
+ /**
485
+ * Phase 2.1.4.b (v2 only): the change set captured at child end by `captureDelta`. A background completion
486
+ * registers THIS set, not the tree as it stands when the completion processor finally runs. Absent: the
487
+ * foreground path, which reads the store at return time as before.
488
+ */
489
+ readonly delta?: import("./dispatch").DispatchDelta;
458
490
  /**
459
491
  * Cross-repo I2 (P2.3): where the change capture observes a role dispatch (its work root W). Absent: `cwd`, as before.
460
492
  * Only the observation uses it; the registration keeps `cwd`, the base the checks run in (F5).
@@ -469,6 +501,20 @@ export interface DeferredFinishInput {
469
501
  readonly fullScope?: boolean;
470
502
  }
471
503
 
504
+ /** Upper bound on the reload wait before the start-time reference GC scans (phase 2.1 section 2.4). */
505
+ export const REFERENCE_RELOAD_WAIT_MS = 10_000;
506
+
507
+ /** Phase 2.1.5: the live wirings of this process; each can abort its background-queue run (QA-2.4-5 path). */
508
+ const liveWirings = new Set<{ preempt(): Promise<void> }>();
509
+
510
+ /**
511
+ * Aborts the in-flight background-queue verification run of every live wiring and resolves once each has
512
+ * settled. Held required runs are not touched: a parent waits on them. Never rejects.
513
+ */
514
+ export async function preemptBackgroundVerification(): Promise<void> {
515
+ await Promise.all([...liveWirings].map(w => w.preempt().then(() => undefined, () => undefined)));
516
+ }
517
+
472
518
  /** Deferred budget snapshots kept for `router_verify` (by handle; oldest dropped first, like the pending registry's bound). */
473
519
  export const MAX_DEFERRED_BUDGETS = 1000;
474
520
 
@@ -607,7 +653,9 @@ export type HandleReport =
607
653
  | { readonly kind: "unknown"; readonly input: string }
608
654
  | { readonly kind: "expired"; readonly handle: string }
609
655
  /** Joined another call's run, which outlived this call's deadline (R8). */
610
- | { readonly kind: "elsewhere"; readonly handle: string; readonly description: string };
656
+ | { readonly kind: "elsewhere"; readonly handle: string; readonly description: string }
657
+ /** QA-2.1-9 (phase 2.1): a held background result; its own gate posts the verdict to the session, so nothing ran here. */
658
+ | { readonly kind: "held"; readonly handle: string; readonly description: string };
611
659
 
612
660
  export interface VerifyReport {
613
661
  readonly items: readonly HandleReport[];
@@ -652,6 +700,9 @@ function linkCaveatText(text: string): string {
652
700
  }
653
701
  export const ROUTER_VERIFY_CANCELLED_REASON = "router_verify was cancelled before a verdict";
654
702
  export const ROUTER_VERIFY_RELEASED_REASON = "the delegation's verification data was released";
703
+ /** QA-2.1-9: the line of a held background result named to router_verify (refused; its gate posts the verdict). */
704
+ export const HELD_RESULT_TEXT =
705
+ "held background result: its own verification gate posts the verdict to this session when it settles; nothing was run.";
655
706
  /** Drifted paths named per handle; the rest are counted. */
656
707
  export const DRIFT_MAX_PATHS = 10;
657
708
 
@@ -764,6 +815,10 @@ export function formatVerifyReport(
764
815
  blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${VERIFYING_ELSEWHERE_TEXT}`);
765
816
  continue;
766
817
  }
818
+ if (item.kind === "held") {
819
+ blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${HELD_RESULT_TEXT}`);
820
+ continue;
821
+ }
767
822
  const { result } = item;
768
823
  const verdict = result.verdict;
769
824
  const via = item.via === "joined" ? " (joined a run already in progress)" : item.via === "cached" ? " (cached verdict; nothing was run)" : "";
@@ -785,7 +840,8 @@ export function formatVerifyReport(
785
840
  lines.push(indent(`[router] ${DRIFT_UNCHECKED_NOTICE}`));
786
841
  }
787
842
  if (judged.accepted) {
788
- lines.push(indent(buildAcceptedSuffix(verdict.method, judged.verdict.outcome, judged.verdict.caveats, verdict.notes).trim()));
843
+ // QA-DF1-30 (QA-3.1-21): a skipped check reads `⚠ UNVERIFIED`, never verified (a held trivial skip is stored as a pass).
844
+ lines.push(indent(buildAcceptedSuffix(verdict.method, verdict.skipped === true ? undefined : judged.verdict.outcome, judged.verdict.caveats, verdict.notes).trim()));
789
845
  } else {
790
846
  lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null, incomplete: isIncompleteVerdict(verdict) }))));
791
847
  lines.push(indent(ROUTER_VERIFY_NO_RETRY_TEXT));
@@ -815,11 +871,52 @@ export function backgroundOutcomes(items: readonly HandleReport[]): BackgroundOu
815
871
  ? { kind: "judged", handle: item.handle, description: item.description, result: item.result }
816
872
  : { kind: "reported", handle: item.handle };
817
873
  }
818
- if (item.kind === "elsewhere") return { kind: "reported", handle: item.handle };
874
+ if (item.kind === "elsewhere" || item.kind === "held") return { kind: "reported", handle: item.handle };
819
875
  return { kind: "gone", handle: item.kind === "unknown" ? item.input : item.handle };
820
876
  });
821
877
  }
822
878
 
879
+ /** QA-2.1-11: how often a lease wait that ignores the producer's own holder probes the tree again. */
880
+ const LEASE_WAIT_POLL_MS = 100;
881
+
882
+ /**
883
+ * QA-2.1-11 (phase 2.1, v2 only): waits until no holder of `tree` other than the sessions in `exclude` edits it, or `deadlineMs`
884
+ * passes. The producer's own leases stay until its completion is processed, after this gate, so waiting for them only delays
885
+ * its own check. `waitTreeFree` waits for every other holder: with no excluded holder in the tree it is called as is (event
886
+ * driven); otherwise it is used as a probe (deadline 0) and polled. Returns the holders that remain, excluded ones left out.
887
+ */
888
+ export async function waitTreeFreeExcept(
889
+ gate: Pick<import("../compat/background").LeaseGuard, "waitTreeFree">,
890
+ tree: string,
891
+ owner: { producer: string },
892
+ exclude: ReadonlySet<string>,
893
+ deadlineMs: number,
894
+ signal: AbortSignal,
895
+ now: () => number = Date.now,
896
+ ): Promise<{ waitedMs: number; holders: string[] }> {
897
+ const started = now();
898
+ for (;;) {
899
+ const probe = await gate.waitTreeFree(tree, owner, 0, signal);
900
+ const holders = probe.holders.filter(h => !exclude.has(h));
901
+ const left = deadlineMs - (now() - started);
902
+ if (holders.length === 0 || left <= 0 || signal.aborted) return { waitedMs: now() - started, holders };
903
+ if (holders.length === probe.holders.length) {
904
+ const wait = await gate.waitTreeFree(tree, owner, left, signal);
905
+ return { waitedMs: now() - started, holders: wait.holders.filter(h => !exclude.has(h)) };
906
+ }
907
+ await new Promise<void>(resolve => {
908
+ let timer: ReturnType<typeof setTimeout> | undefined;
909
+ const done = (): void => {
910
+ if (timer !== undefined) clearTimeout(timer);
911
+ signal.removeEventListener("abort", done);
912
+ resolve();
913
+ };
914
+ timer = setTimeout(done, Math.min(LEASE_WAIT_POLL_MS, left));
915
+ signal.addEventListener("abort", done, { once: true });
916
+ });
917
+ }
918
+ }
919
+
823
920
  /** A never-rejecting wait for `promise` that ends with `fallback()` once `signal` aborts. */
824
921
  function untilAborted<T>(promise: Promise<T>, signal: AbortSignal, fallback: () => T): Promise<T> {
825
922
  if (signal.aborted) return Promise.resolve(fallback());
@@ -936,6 +1033,8 @@ export interface VerificationWiring {
936
1033
  * check or a criterion stays deferred with that empty set.)
937
1034
  */
938
1035
  isDeferred(dod: DoD, directives: VerifyDirectives, trivial?: boolean): boolean;
1036
+ /** Phase 2.1: the directives a dispatch text resolves to, without starting or consuming a dispatch. */
1037
+ directivesFor(text: string): VerifyDirectives;
939
1038
  /**
940
1039
  * 2.4.2a: the deferred finish. No gate, no test command, no slot: a tree snapshot and the commit
941
1040
  * diff (git only, as prepareVerification) under DEFERRED_FINISH_MS, the static scoping plan
@@ -1014,6 +1113,13 @@ export interface VerificationWiring {
1014
1113
  cwd?: string,
1015
1114
  deadline?: Deadline,
1016
1115
  dispatchStartedAt?: number,
1116
+ /** QA-SYNC1-3: the journaled dispatch-time head of a held entry restored after a restart (the store lost its own). */
1117
+ restoredHead?: HeadState,
1118
+ /** V2 completion diagnostics only; the caller supplies the parent rather than inferring it from the dispatch key. */
1119
+ parentSessionID?: string,
1120
+ /** V2 diagnostics only: lazily supply a non-dispatch source and its retained call id. */
1121
+ captureObservation?: () => { source: string; callID: string },
1122
+ serviceIdentity?: () => ServiceIdentity,
1017
1123
  ): Promise<PreparedVerification>;
1018
1124
  /** Session ids currently running a grader prompt, so hooks can skip them. */
1019
1125
  graderSessions: Set<string>;
@@ -1038,7 +1144,7 @@ export interface VerificationWiring {
1038
1144
  * the changed files are "unavailable" and the reference is the untracked default. `deadline`
1039
1145
  * bounds every testsPass step (T3); without it each testsPass check owns one of gateBudgetMs.
1040
1146
  */
1041
- buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline, forceLowPriority?: boolean, creatorSessionID?: string | null): GateDeps;
1147
+ buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline, forceLowPriority?: boolean, creatorSessionID?: string | null, serviceIdentity?: () => ServiceIdentity): GateDeps;
1042
1148
  /**
1043
1149
  * 2.2.3: the idle-TTL sweep's hook into the plugin's one S5 batch coordinator (batch.ts B11):
1044
1150
  * evicts windows with no live member and batches whose seam hung past BATCH_STALE_GRACE_MS.
@@ -1086,6 +1192,7 @@ function errorText(err: unknown): string {
1086
1192
  }
1087
1193
 
1088
1194
  export function createVerificationWiring(deps: {
1195
+ observations?: V2Observations;
1089
1196
  client: any;
1090
1197
  childRunner?: ChildSessionRunner;
1091
1198
  /** Project root; relative paths in checks resolve against it. */
@@ -1098,7 +1205,17 @@ export function createVerificationWiring(deps: {
1098
1205
  /** Test seams of the S5 batch coordinator (clock, timers, platform, maximum window size). */
1099
1206
  batch?: Omit<BatchCoordinatorOptions, "logger">;
1100
1207
  /** Test seams of the pending registry (clock, random source). */
1101
- pending?: Pick<PendingRegistryOptions, "now" | "random">;
1208
+ pending?: Pick<PendingRegistryOptions, "now" | "random" | "onVerdict" | "persist">;
1209
+ /**
1210
+ * Phase 2.1, v2 only: the records of pending.jsonl, loaded by the caller. They are folded into the registry
1211
+ * and their reference dirs are kept (keepReferences) before the start-time reference GC scans.
1212
+ */
1213
+ pendingRestore?: Promise<readonly PendingRecord[]>;
1214
+ /**
1215
+ * Phase 2.1.5: the lease guard's wait (v2 only; absent on v1 and when `routing.leases.mode` is "off").
1216
+ * Plugin verification runs in a tree wait for its holders first.
1217
+ */
1218
+ leaseGate?: Pick<import("../compat/background").LeaseGuard, "waitTreeFree">;
1102
1219
  /** Test seams of the 2.4.5 background queue; used only when `background` is true. */
1103
1220
  background?: Pick<BackgroundQueueOptions, "now" | "timers" | "settleMs" | "retryBaseMs" | "maxAttempts" | "platform">;
1104
1221
  }): VerificationWiring {
@@ -1132,11 +1249,41 @@ export function createVerificationWiring(deps: {
1132
1249
  onEvict: (entry, cause) => logger.debug?.("[verify] pending delegation evicted", { handle: entry.handle, cause }),
1133
1250
  });
1134
1251
  const pendingNow = deps.pending?.now ?? Date.now;
1252
+ /** Phase 2.1 (v2 only): resolves once pending.jsonl is folded in and its reference dirs are kept; never rejects. */
1253
+ const restoreDone: Promise<void> | undefined = deps.pendingRestore === undefined ? undefined : deps.pendingRestore.then(
1254
+ records => {
1255
+ const dirs = new Set<string>();
1256
+ for (const record of records) {
1257
+ if (record.kind !== "ref") continue;
1258
+ for (const link of Object.keys(serializedReferenceLinks(record.reference))) {
1259
+ // The link lives inside the materialized dir: walk up to the omr-ref-<pid>-<hex> segment.
1260
+ let at = link.length;
1261
+ while (at > 0) {
1262
+ const cut = Math.max(link.lastIndexOf("/", at - 1), link.lastIndexOf("\\", at - 1));
1263
+ const name = link.slice(cut + 1, at);
1264
+ if (REF_DIR_PATTERN.test(name)) {
1265
+ dirs.add(link.slice(0, at));
1266
+ break;
1267
+ }
1268
+ if (cut <= 0) break;
1269
+ at = cut;
1270
+ }
1271
+ }
1272
+ }
1273
+ keepReferences(dirs, { logger });
1274
+ const report = pending.restore(records, { now: pendingNow() });
1275
+ logger.debug?.("[verify] pending.jsonl restored", { ...report });
1276
+ },
1277
+ ).catch((err: unknown) => {
1278
+ logger.warn("[verify] pending.jsonl could not be restored", { error: errorText(err) });
1279
+ });
1135
1280
  /**
1136
1281
  * 2.4.5: assigned once verifyHandles exists, and only when `background` is true at plugin start
1137
1282
  * (pending.ts R14). With background off this stays undefined: no queue, no timer, no run.
1138
1283
  */
1139
1284
  let background: BackgroundQueue | undefined;
1285
+ const liveWiring = { preempt: async (): Promise<void> => { await background?.preempt(); } };
1286
+ liveWirings.add(liveWiring);
1140
1287
  /** QA-2.4-5: foreground testsPass requests in flight (the background queue's `busy`). */
1141
1288
  const foreground = { tests: 0 };
1142
1289
  /** 2.4.2b: native `task` dispatch starts, before hook -> after hook (bounded FIFO, swept). */
@@ -1174,6 +1321,7 @@ export function createVerificationWiring(deps: {
1174
1321
  signal: opts?.signal,
1175
1322
  lowPriority: opts?.lowPriority,
1176
1323
  env: opts?.env,
1324
+ ...(opts?.service === undefined ? {} : { service: opts.service }),
1177
1325
  });
1178
1326
 
1179
1327
  const argvSeam: ArgvSeam = (file, args, opts) =>
@@ -1183,6 +1331,7 @@ export function createVerificationWiring(deps: {
1183
1331
  signal: opts?.signal,
1184
1332
  lowPriority: opts?.lowPriority,
1185
1333
  env: opts?.env,
1334
+ ...(opts?.service === undefined ? {} : { service: opts.service }),
1186
1335
  });
1187
1336
 
1188
1337
  // T9 1.3: PlannerFs + unlink over fs.promises. realpath is the native one; fileExists accepts
@@ -1336,6 +1485,8 @@ export function createVerificationWiring(deps: {
1336
1485
  parentSessionID?: string,
1337
1486
  inFlight?: Set<string>,
1338
1487
  creatorSessionID: string | null = parentSessionID ?? null,
1488
+ service?: ServiceObservation,
1489
+ graderDispatchLabel?: string,
1339
1490
  ): Promise<{ sessionID: string; text: string; model: string | null }> => {
1340
1491
  // #84 P3.3 fix 2: the model the grader is dispatched on travels with its answer (checker.ts GraderResult.model → the
1341
1492
  // verdict's `grader`), so the outcome signals can check its independence (plan §2.6). Null: the host's default model.
@@ -1346,6 +1497,7 @@ export function createVerificationWiring(deps: {
1346
1497
  const controller = new AbortController();
1347
1498
  const model = tierModel(cfg, req.tier);
1348
1499
  let sid: string | undefined;
1500
+ const preparation = service?.start("service-prep", "grader-startup");
1349
1501
  try {
1350
1502
  const answer = await withTimeout(deps.childRunner.run({
1351
1503
  parentSessionID,
@@ -1354,6 +1506,7 @@ export function createVerificationWiring(deps: {
1354
1506
  system: req.system,
1355
1507
  prompt: req.prompt,
1356
1508
  signal: controller.signal,
1509
+ ...(service === undefined ? {} : { service, onServiceStart: () => preparation?.end("completed") }),
1357
1510
  async onCreated(sessionID) {
1358
1511
  sid = sessionID;
1359
1512
  graderSessions.add(sessionID);
@@ -1362,7 +1515,15 @@ export function createVerificationWiring(deps: {
1362
1515
  },
1363
1516
  }), graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs), "grader prompt");
1364
1517
  return { sessionID: answer.sessionID, text: answer.text, model: modelRef(model) };
1518
+ } catch (error) {
1519
+ // Service results stay low-cardinality; the schema has no free-text reason field.
1520
+ try {
1521
+ const label = graderDispatchLabel === undefined ? "" : ` for ${scrubText(graderDispatchLabel).replace(/\s+/g, " ").trim().slice(0, 200)}`;
1522
+ logger.warn(`[verify] grader dispatch failed${label}: ${errorText(error).replace(/\s+/g, " ").trim().slice(0, 200)}`);
1523
+ } catch { /* Diagnostics must preserve the original dispatch error. */ }
1524
+ throw error;
1365
1525
  } finally {
1526
+ preparation?.end("error");
1366
1527
  controller.abort();
1367
1528
  if (sid) {
1368
1529
  graderSessions.delete(sid);
@@ -1464,7 +1625,10 @@ export function createVerificationWiring(deps: {
1464
1625
  deadline?: Deadline,
1465
1626
  forceLowPriority = false,
1466
1627
  creatorSessionID: string | null = parentSessionID ?? null,
1628
+ serviceIdentity?: () => ServiceIdentity,
1467
1629
  ): GateDeps => {
1630
+ // A plan task's prepared verification already carries its service span; native dispatches carry none.
1631
+ const service = serviceIdentity === undefined ? prepared?.service : serviceObservation(deps.observations, serviceIdentity);
1468
1632
  const cfg = getConfig();
1469
1633
  const resolved = resolveVerifyBudget(cfg);
1470
1634
  // 2.4.5 (section 1.5-19): background runs are low priority whatever `lowPriority` says.
@@ -1477,11 +1641,13 @@ export function createVerificationWiring(deps: {
1477
1641
  const gatePins = prepared?.reference?.kind === "captured" ? prepared.reference.reference.pins : undefined;
1478
1642
  const pinNow = pinNowFor(gatePins !== undefined ? pinAdmissions.get(gatePins) : undefined);
1479
1643
  const openScope = createScopeOpener({
1644
+ service,
1480
1645
  argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1481
1646
  reference: { argv: referenceArgv, pinNow },
1482
1647
  });
1483
1648
  const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
1484
1649
  const direct = createDirectTestsPassHook({
1650
+ service,
1485
1651
  openScope,
1486
1652
  plannerFs: fsSeam,
1487
1653
  search: testSearch(budget, deadline),
@@ -1527,6 +1693,29 @@ export function createVerificationWiring(deps: {
1527
1693
  foreground.tests += 1;
1528
1694
  try {
1529
1695
  void background?.preempt();
1696
+ // Phase 2.1 (v2, leases on): wait for the holders of the tree, within a quarter of the gate budget; then run
1697
+ // anyway, with the concurrent-dispatches caveat for the holders that remain.
1698
+ if (deps.leaseGate !== undefined) {
1699
+ const leaseWait = service?.start("service-wait", "lease");
1700
+ try {
1701
+ // QA-2.1-11: the producer's own leases never delay its own check.
1702
+ const producer = prepared?.producerSessionID;
1703
+ const wait = await waitTreeFreeExcept(
1704
+ deps.leaseGate,
1705
+ prepared?.snapshot?.root ?? directory,
1706
+ { producer: parentSessionID ?? creatorSessionID ?? "router" },
1707
+ new Set(producer !== undefined && producer !== "" ? [producer] : []),
1708
+ Math.min(Math.floor(resolved.gateBudgetMs / 4), deadline?.remaining() ?? resolved.gateBudgetMs),
1709
+ deadline?.signal ?? new AbortController().signal,
1710
+ );
1711
+ if (wait.holders.length > 0 && prepared !== undefined) {
1712
+ prepared.concurrentDispatches = Math.max(prepared.concurrentDispatches ?? 0, wait.holders.length);
1713
+ }
1714
+ leaseWait?.end("completed");
1715
+ } catch (err) {
1716
+ logger.warn("[verify] lease wait failed; verifying anyway", { error: errorText(err) });
1717
+ } finally { leaseWait?.end("error"); }
1718
+ }
1530
1719
  return await inner(request);
1531
1720
  } finally {
1532
1721
  foreground.tests -= 1;
@@ -1535,6 +1724,7 @@ export function createVerificationWiring(deps: {
1535
1724
  }
1536
1725
  return {
1537
1726
  deterministic: {
1727
+ ...(service === undefined ? {} : { service }),
1538
1728
  exec: execSeam,
1539
1729
  fs: fsSeam,
1540
1730
  cwd: directory,
@@ -1552,7 +1742,7 @@ export function createVerificationWiring(deps: {
1552
1742
  },
1553
1743
  checker: {
1554
1744
  dispatchGrader: (req: GraderRequest) =>
1555
- dispatchGrader(req, parentSessionID, inFlight, creatorSessionID),
1745
+ dispatchGrader(req, parentSessionID, inFlight, creatorSessionID, service, prepared?.graderDispatchLabel),
1556
1746
  ladder: ["fast", "medium", "heavy"],
1557
1747
  minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
1558
1748
  },
@@ -2161,6 +2351,8 @@ export function createVerificationWiring(deps: {
2161
2351
  cwd: string | undefined,
2162
2352
  deadline: Deadline | undefined,
2163
2353
  observePerimeter = true,
2354
+ // QA-SYNC1-3: a restored held entry's journaled dispatch-time head stands in for the store's (gone after a restart).
2355
+ restoredHead?: HeadState,
2164
2356
  ): Promise<Omit<PreparedVerification, "reference">> => {
2165
2357
  const base = resolve(directory, cwd || ".");
2166
2358
  // QA-1 F9: the perimeter's gate snapshots start now, concurrently with W's own (never rejects).
@@ -2208,7 +2400,10 @@ export function createVerificationWiring(deps: {
2208
2400
  let headSwitch: string | undefined;
2209
2401
  let headRead = false;
2210
2402
  let gateHead: HeadState | undefined;
2211
- const baselineHead = store.baselineHead(id);
2403
+ const liveHead = store.baselineHead(id);
2404
+ const baselineHead = liveHead ?? (restoredHead !== undefined ? Promise.resolve<HeadState>(restoredHead) : undefined);
2405
+ // QA-SYNC1-17: a head restored from the journal spans the dispatch and the restart; the live wording stays unchanged.
2406
+ const switchWindow = liveHead === undefined && restoredHead !== undefined ? AFTER_RESTART_WINDOW : "during the dispatch";
2212
2407
  if (baselineHead !== undefined) {
2213
2408
  const bound = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
2214
2409
  if (bound > 0 && deadline?.signal.aborted !== true) {
@@ -2248,7 +2443,7 @@ export function createVerificationWiring(deps: {
2248
2443
  const move = unreadWindow
2249
2444
  ? { kind: "rewritten" as const, detail: "the reflog entries could not be read" }
2250
2445
  : treeMove(startHead, nowHead, window);
2251
- if (move !== undefined) headSwitch = treeMoveReason(nowHead.root, startHead, nowHead, move, "during the dispatch");
2446
+ if (move !== undefined) headSwitch = treeMoveReason(nowHead.root, startHead, nowHead, move, switchWindow);
2252
2447
  }
2253
2448
  }
2254
2449
  }
@@ -2267,6 +2462,7 @@ export function createVerificationWiring(deps: {
2267
2462
  snapshot,
2268
2463
  concurrentDispatches: store.concurrentDispatches(id, snapshot?.root),
2269
2464
  ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
2465
+ ...(childID !== "" ? { producerSessionID: childID } : {}),
2270
2466
  ...(branchSwitch !== undefined ? { branchSwitch } : {}),
2271
2467
  ...(gateHead !== undefined ? { head: gateHead } : {}),
2272
2468
  ...(perimeter !== undefined ? { perimeter } : {}),
@@ -2451,7 +2647,19 @@ export function createVerificationWiring(deps: {
2451
2647
  const perimeterSnapshots = store.perimeterOf(input.dispatchID) !== undefined
2452
2648
  ? perimeterSnapshotsAtGate(store, input.dispatchID, deadline).catch(() => undefined)
2453
2649
  : undefined;
2454
- const change = await observeChange(store, input.dispatchID, input.producerSessionID, changeCwd, deadline, false);
2650
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "change-set-capture", source: "deferred-change",
2651
+ ...completionIdentity(input.orchestratorSessionID, input.dispatchID, input.producerSessionID) }));
2652
+ const observed = await observeChange(store, input.dispatchID, input.producerSessionID, changeCwd, deadline, false);
2653
+ // Phase 2.1.4.b / QA-2.1-7: the set frozen at child end holds only the child's tool-observed paths, a subset of the
2654
+ // observed change set (which also holds the tree delta, shell edits and commits), so it never replaces it. A delta whose
2655
+ // dispatch snapshot a foreign write contaminated makes the change set unavailable, as the foreground gate treats it.
2656
+ const delta = input.delta;
2657
+ const change = delta === undefined || delta.files !== "unavailable" ? observed : {
2658
+ ...observed,
2659
+ changeBaseline: "unavailable" as const,
2660
+ changedFiles: [],
2661
+ ...(delta.contaminatedBy !== undefined ? { contaminatedBy: delta.contaminatedBy } : {}),
2662
+ };
2455
2663
  // I7 (P0.2): a branch switch during the dispatch is never deferred: a handle could verify the other branch later. The
2456
2664
  // caller's required gate refuses it now (its own observeChange sees the switch). Before the no-change shortcut below.
2457
2665
  if (change.branchSwitch !== undefined) return { deferred: false, reason: "branch-switched", detail: change.branchSwitch };
@@ -2515,6 +2723,8 @@ export function createVerificationWiring(deps: {
2515
2723
  const taken = await untilAborted(digestFiles(paths.map(p => p.path)), deadline.signal, () => undefined);
2516
2724
  if (taken !== undefined) digests = Promise.resolve(taken);
2517
2725
  }
2726
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "deferred-register", source: "pending-register",
2727
+ ...completionIdentity(input.orchestratorSessionID, input.dispatchID, input.producerSessionID) }));
2518
2728
  const reg = pending.register({
2519
2729
  orchestratorSessionID: input.orchestratorSessionID,
2520
2730
  dispatchID: input.dispatchID,
@@ -2609,6 +2819,8 @@ export function createVerificationWiring(deps: {
2609
2819
  // An unattributed change set is not queued (nothing could run; it stays listed instead).
2610
2820
  if (background !== undefined && changedFiles !== "unavailable") {
2611
2821
  try {
2822
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "verification-enqueue", source: "deferred-background", handle: reg.handle,
2823
+ ...completionIdentity(input.orchestratorSessionID, input.dispatchID, input.producerSessionID) }));
2612
2824
  background.enqueue({ sessionID: input.orchestratorSessionID, handle: reg.handle, files: changedFiles.map(p => p.path) });
2613
2825
  } catch (err) {
2614
2826
  // The handle is registered: the delegation stays unverified and listed, as without background.
@@ -3071,6 +3283,8 @@ export function createVerificationWiring(deps: {
3071
3283
  changeBaseline: changed === "unavailable" ? "unavailable" : "available",
3072
3284
  reference: gateReference,
3073
3285
  snapshot: tree,
3286
+ // QA-2.1-11: the producer's own retained leases never delay its own check.
3287
+ ...(entry.producerSessionID !== "" ? { producerSessionID: entry.producerSessionID } : {}),
3074
3288
  ...(branchSwitch !== undefined ? { branchSwitch } : {}),
3075
3289
  ...(entry.unattributedWriters !== undefined ? { unattributedWriters: [...entry.unattributedWriters] } : {}),
3076
3290
  ...(perimeter !== undefined ? { perimeter } : {}),
@@ -3104,6 +3318,10 @@ export function createVerificationWiring(deps: {
3104
3318
  const dod = entry.dod;
3105
3319
  // A claimed entry is never released (release happens on a terminal settle only).
3106
3320
  if (dod === undefined) return { kind: "final", result: { verdict: unverifiableVerdict(ROUTER_VERIFY_RELEASED_REASON), retryable: false } };
3321
+ // A restored entry whose registration had a perimeter (never journaled) cannot be judged as registered: never a pass.
3322
+ if (entry.perimeterLost === true) return { kind: "final", result: { verdict: unverifiableVerdict(PERIMETER_LOST_REASON), retryable: false } };
3323
+ // QA-SYNC1-3: a restored held entry whose gate checked the dispatch-time head (not journaled) cannot confirm its branch.
3324
+ if (entry.headLost === true) return { kind: "final", result: { verdict: unverifiableVerdict(HEAD_LOST_REASON), retryable: false } };
3107
3325
  // Cross-repo P2e.4b: a placed check whose cwd no longer resolves to the same repository would run elsewhere: nothing runs.
3108
3326
  if (prep.placementDrift !== undefined) return { kind: "final", result: { verdict: unverifiableVerdict(prep.placementDrift), retryable: false } };
3109
3327
  // P2e QA-1 #5b: a placement that could not be checked now: nothing runs; another router_verify may check it.
@@ -3300,6 +3518,16 @@ export function createVerificationWiring(deps: {
3300
3518
  slots.push({ kind: "unknown", input: t.handle ?? t.input });
3301
3519
  continue;
3302
3520
  }
3521
+ // QA-2.1-9 (phase 2.1, v2 only): a held entry is verified by its background gate, which posts the verdict to the
3522
+ // parent. While it is "held", router_verify refuses it (never a second run, never a second post). QA-2.1-31: the live
3523
+ // gate claims and settles the entry in one step when it ends, so a live held entry is never joined; only a gate
3524
+ // re-run after a restart claims first (state "verifying"), and the claim below joins that run. A settled entry
3525
+ // reports the cached verdict. A held entry starts in state "held" (pending.ts); "verified" is its verdict.
3526
+ const looked = pending.get(sessionID, t.handle);
3527
+ if (looked.kind === "found" && looked.entry.hold !== undefined && looked.entry.state !== "verifying" && looked.entry.state !== "verified") {
3528
+ slots.push({ kind: "held", handle: looked.entry.handle, description: looked.entry.description });
3529
+ continue;
3530
+ }
3303
3531
  const c = pending.markVerifying(sessionID, t.handle);
3304
3532
  if (c.kind === "unknown") slots.push({ kind: "unknown", input: t.handle });
3305
3533
  else if (c.kind === "expired") slots.push({ kind: "expired", handle: c.handle });
@@ -3323,7 +3551,11 @@ export function createVerificationWiring(deps: {
3323
3551
  }
3324
3552
  } catch (error) {
3325
3553
  // Never leave a claim verifying until the reaper: settle what was claimed, retryable.
3326
- for (const c of claims) c.settle({ verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true });
3554
+ for (const c of claims) {
3555
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "verification-settle", source: "claim-error", handle: c.entry.handle,
3556
+ ...completionIdentity(c.entry.orchestratorSessionID, c.entry.dispatchID, c.entry.producerSessionID) }));
3557
+ c.settle({ verdict: unverifiableVerdict(`verification unavailable: ${errorText(error)}`), retryable: true });
3558
+ }
3327
3559
  throw error;
3328
3560
  }
3329
3561
 
@@ -3373,6 +3605,8 @@ export function createVerificationWiring(deps: {
3373
3605
  } finally {
3374
3606
  // R4: single use, in a finally; false only when the claim was reaped or disposed.
3375
3607
  claims.forEach((c, i) => {
3608
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "verification-settle", source: "verify-handles", handle: c.entry.handle,
3609
+ ...completionIdentity(c.entry.orchestratorSessionID, c.entry.dispatchID, c.entry.producerSessionID) }));
3376
3610
  if (!c.settle(results[i])) logger.debug?.("[verify] router_verify settled a claim that was already reaped", { handle: c.entry.handle });
3377
3611
  });
3378
3612
  }
@@ -3444,6 +3678,9 @@ export function createVerificationWiring(deps: {
3444
3678
  }
3445
3679
  return { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
3446
3680
  },
3681
+ directivesFor(text) {
3682
+ return resolveDirectives(text);
3683
+ },
3447
3684
  isDeferred(dod, directives, trivial = false) {
3448
3685
  if (directives.mode !== "deferred" || !hasTestsPass(dod)) return false;
3449
3686
  // QA-2.4-10: gate.ts skips exactly this case ("trivial dispatch; verification skipped").
@@ -3460,7 +3697,7 @@ export function createVerificationWiring(deps: {
3460
3697
  pending,
3461
3698
  background,
3462
3699
  beginVerificationBounded,
3463
- startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS) {
3700
+ startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS, reloaded?: Promise<unknown>) {
3464
3701
  if (!directory) {
3465
3702
  logger.debug?.("[verify] reference GC skipped: plugin root unknown");
3466
3703
  return () => undefined;
@@ -3476,7 +3713,20 @@ export function createVerificationWiring(deps: {
3476
3713
  lowPriority: budget.lowPriority,
3477
3714
  signal: opts?.signal ? AbortSignal.any([opts.signal, stop.signal]) : stop.signal,
3478
3715
  });
3479
- gcStaleReferences(directory, { argv, fs: nodeReferenceFs, logger }).then(
3716
+ // v2: pending.jsonl is reloaded (keepReferences) before the scan, bounded so a stuck reload never blocks GC.
3717
+ const reloadedOrRestored = reloaded ?? restoreDone;
3718
+ const reloadWait: Promise<unknown> = reloadedOrRestored === undefined
3719
+ ? Promise.resolve()
3720
+ : Promise.race([
3721
+ reloadedOrRestored.then(() => undefined, () => undefined),
3722
+ new Promise<void>(resolve => {
3723
+ const t = setTimeout(resolve, REFERENCE_RELOAD_WAIT_MS);
3724
+ t.unref?.();
3725
+ }),
3726
+ ]);
3727
+ reloadWait.then(() => (stop.signal.aborted
3728
+ ? { removed: [], kept: [], failed: [] }
3729
+ : gcStaleReferences(directory, { argv, fs: nodeReferenceFs, logger }))).then(
3480
3730
  report => {
3481
3731
  if (report.removed.length > 0) logger.debug?.("[verify] reference GC removed stale dirs", { removed: report.removed.length });
3482
3732
  },
@@ -3493,23 +3743,31 @@ export function createVerificationWiring(deps: {
3493
3743
  stop.abort();
3494
3744
  };
3495
3745
  },
3496
- async prepareVerification(store, id, childID, cwd, deadline, dispatchStartedAt?: number) {
3497
- const change = await observeChange(store, id, childID, cwd, deadline);
3498
- const captured = await store.reference(id, deadline?.signal);
3499
- // Cross-repo P2d.3 (P2.6): the pins of the admitted link targets travel with a captured reference (required gate only).
3500
- const pins = captured.kind === "captured" ? await linkPinsAtGate(store, id, deadline) : [];
3501
- // QA-2 nit: the gate took the dispatch's pins (or its reference was discarded): free them.
3502
- freeLinkPins(id, pins);
3503
- const reference: ReferenceState = pins.length > 0 && captured.kind === "captured"
3504
- ? { kind: "captured", reference: { ...captured.reference, pins } }
3505
- : captured;
3506
- // Cross-repo P3a (D23 as amended, QA C1): the dispatch start the caller holds (DispatchStart.dispatchedAt), the `since` of
3507
- // W's ignored-module listing. Unknown: none listed (toward zero selection, never toward a stale build output).
3508
- return {
3509
- ...change,
3510
- reference,
3511
- ...(dispatchStartedAt !== undefined && Number.isFinite(dispatchStartedAt) ? { dispatchStartedAt } : {}),
3512
- };
3746
+ async prepareVerification(store, id, childID, cwd, deadline, dispatchStartedAt, restoredHead, parentSessionID, captureObservation, serviceIdentity) {
3747
+ const service = serviceIdentity === undefined ? undefined : serviceObservation(deps.observations, serviceIdentity);
3748
+ const preparation = service?.start("service-prep", "change-capture");
3749
+ try {
3750
+ if (parentSessionID !== undefined) observeV2(deps.observations, () => ({ family: "completion-effect", effect: "change-set-capture", source: "required-change",
3751
+ ...completionIdentity(parentSessionID, id, childID || null), ...captureObservation?.() }));
3752
+ const change = await observeChange(store, id, childID, cwd, deadline, undefined, restoredHead);
3753
+ const captured = await store.reference(id, deadline?.signal);
3754
+ // Cross-repo P2d.3 (P2.6): the pins of the admitted link targets travel with a captured reference (required gate only).
3755
+ const pins = captured.kind === "captured" ? await linkPinsAtGate(store, id, deadline) : [];
3756
+ // QA-2 nit: the gate took the dispatch's pins (or its reference was discarded): free them.
3757
+ freeLinkPins(id, pins);
3758
+ const reference: ReferenceState = pins.length > 0 && captured.kind === "captured"
3759
+ ? { kind: "captured", reference: { ...captured.reference, pins } }
3760
+ : captured;
3761
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch start the caller holds (DispatchStart.dispatchedAt), the `since` of
3762
+ // W's ignored-module listing. Unknown: none listed (toward zero selection, never toward a stale build output).
3763
+ preparation?.end("completed");
3764
+ return {
3765
+ ...change,
3766
+ ...(service === undefined ? {} : { service }),
3767
+ reference,
3768
+ ...(dispatchStartedAt !== undefined && Number.isFinite(dispatchStartedAt) ? { dispatchStartedAt } : {}),
3769
+ };
3770
+ } finally { preparation?.end("error"); }
3513
3771
  },
3514
3772
  graderSessions,
3515
3773
  disposeChildSession,
@@ -3534,6 +3792,7 @@ export function createVerificationWiring(deps: {
3534
3792
  deferredWorkRoots.clear();
3535
3793
  // 2.4.5: abort the background run first, so nothing re-queues while the coordinator stops.
3536
3794
  background?.dispose();
3795
+ liveWirings.delete(liveWiring);
3537
3796
  return coordinator.dispose();
3538
3797
  },
3539
3798
  };