opencode-model-router 2.7.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -15,8 +15,10 @@
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
- import { isAbsolute, join, relative, resolve } from "node:path";
21
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
20
22
  import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
21
23
  import {
22
24
  createDeadline,
@@ -59,13 +61,14 @@ import {
59
61
  type SettledVerification,
60
62
  type VerificationResult,
61
63
  } from "./pending";
62
- import { assessRisk, type RiskAssessment } from "./risk";
64
+ import { assessRisk, FULL_SCOPE_PLAN, type FullScopePlan, type RiskAssessment } from "./risk";
63
65
  import { resolveBaseDir } from "./paths";
64
66
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
65
67
  import {
66
68
  buildAcceptedSuffix,
67
69
  buildForcingNote,
68
70
  canonicalPath,
71
+ isUnattributedWriter,
69
72
  tierModel,
70
73
  toolLabel,
71
74
  type ChangedFile,
@@ -74,22 +77,40 @@ import {
74
77
  type TreeSnapshot,
75
78
  } from "./dispatch";
76
79
  import { runArgv, runShell } from "./exec";
77
- import { snapshotTree } from "./tree";
78
- import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, nodeReferenceFs, type DispatchReference } from "./reference";
80
+ import { fileMtimeMs, listIgnoredModules, snapshotTree } from "./tree";
81
+ import {
82
+ admissionFromData,
83
+ crossLinkAliases,
84
+ dependencyTargets,
85
+ discoverConsumers,
86
+ linkedTargets,
87
+ planPerimeter,
88
+ type ConsumerDiscovery,
89
+ type DependencyTargets,
90
+ } from "./perimeter";
91
+ import { PERIMETER_MAX } from "./perimeter";
92
+ import { defaultExternalLinks, pinTarget, type LinkPin } from "./pin";
93
+ import { depthBelow, gitTopOf, perimeterKey } from "./git-top";
94
+ import type { DispatchPerimeter, PerimeterEntry } from "./dispatch";
95
+ import { AFTER_RESTART_WINDOW, branchSwitched, branchSwitchReason, branchUnconfirmedReason, treeMove, treeMoveReason } from "./branch";
96
+ import { readHead, readHeadState, readReflogWindow, type HeadState, type ReflogEntry } from "./head";
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";
79
99
  import type { PluginLogger } from "../router/logger";
80
100
  import { REFERENCE_NONE } from "./baseline";
81
101
  import { scrubText } from "../guard/scrub";
102
+ import { displaySafe } from "../routing/roles/read-set";
82
103
  import type { DoD } from "./dod";
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";
104
+ import type { ArgvSeam, CheckPlacement, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ReferenceState, TestsPassHook, Verdict } from "./types";
105
+ import { planScopedRun, planStaticScoping, type ChangedPath, type RunnerFs, type StaticScoping, type StaticScopingInput, type TestSearchSeam } from "./runner";
85
106
  import {
86
107
  DEFAULT_GATE_BUDGET_MS,
87
108
  graderTimeoutMs,
88
109
  RouterTimeoutError,
89
110
  withTimeout,
90
111
  } from "./timeout";
91
- import { resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
92
- import { accept, gateResult, unverifiableGateResult, type GateDeps, type GateResult } from "./gate";
112
+ import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
113
+ import { accept, gateResult, PERIMETER_UNPLANNED, perimeterChangeReasons, unverifiableGateResult, type GateDeps, type GateResult, type PerimeterObservation, type PerimeterRoot } from "./gate";
93
114
  // The grader request shape is owned by checker.ts, which builds it. Re-exported
94
115
  // here because this module is where it is consumed, and because keeping a
95
116
  // second local copy is exactly how `cwd` got dropped: the checker set it, the
@@ -155,6 +176,10 @@ function graderPromptResponseError(res: unknown): Error | undefined {
155
176
 
156
177
  /** P0 (deterministic.ts header, T2): what a gate needs from its dispatch. */
157
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;
158
183
  /**
159
184
  * The producer's changed files: the tool-observed paths of every attempt judged against this
160
185
  * dispatch (QA-2.1-1), the paths the current snapshot added since dispatch, and the paths dirty
@@ -174,6 +199,34 @@ export interface PreparedVerification {
174
199
  concurrentDispatches?: number;
175
200
  /** QA-3.1-3: the tool whose call discarded the dispatch snapshot, which left the change set unavailable. */
176
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;
207
+ /**
208
+ * I7 (P0.2, S9/S12): the gate's unverifiable reason when the working tree switched branch (branch.ts); absent: no switch
209
+ * seen. The artefact builders hand it to the gate (Artefact.branchSwitch), which then refuses on either verifier.
210
+ */
211
+ branchSwitch?: string;
212
+ /** The cheap head state read at the gate (observeChange); absent when it was not read. The deferred finish registers it. */
213
+ head?: HeadState;
214
+ /**
215
+ * I5 (P0.3, S1/S3/S10): tools the producer lineage ran whose writes the router cannot observe (store.delta); the artefact
216
+ * builders hand them to the gate (Artefact.unattributedWriters). Absent or empty: none.
217
+ */
218
+ unattributedWriters?: string[];
219
+ /**
220
+ * Cross-repo P1.8 (I4, I8): the perimeter P observed at the gate (observeChange); the artefact builders hand it to the gate
221
+ * (Artefact.perimeter). Absent: the dispatch has no perimeter.
222
+ */
223
+ perimeter?: PerimeterObservation;
224
+ /**
225
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): when the dispatch began (DispatchStart.dispatchedAt; for a deferred
226
+ * verification, the entry's original dispatchedAt, never the router_verify time). buildGateDeps hands it to the gate
227
+ * (DeterministicDeps.dispatchStartedAt): only W's ignored modules modified since are cross-link inputs. Absent: none are.
228
+ */
229
+ dispatchStartedAt?: number;
177
230
  }
178
231
 
179
232
  /**
@@ -373,6 +426,20 @@ export const DRIFT_DIGEST_MAX_BYTES = 64 * 1024 * 1024;
373
426
  export const STATIC_SCOPING_UNFINISHED_REASON = "static scoping did not finish within the deferred-finish bound";
374
427
  /** Section 1.4 pendingTtlMs default, used when the config cannot be read at plugin start. */
375
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
+ }
376
443
  /**
377
444
  * QA-2.4-9: the capture wait when the config cannot be read: section 1.4's captureWaitMs default
378
445
  * (5000 ms), clamped to the default baselineTimeoutMs (DEFAULT_CAPTURE_TIMEOUT_MS), as config.ts does.
@@ -382,7 +449,11 @@ export const FALLBACK_CAPTURE_WAIT_MS = Math.min(5_000, DEFAULT_CAPTURE_TIMEOUT_
382
449
  /** What the orchestrator asked for at dispatch (directives.ts, parsed from its own prompt only). */
383
450
  export interface DispatchStart {
384
451
  readonly directives: VerifyDirectives;
385
- /** Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). */
452
+ /**
453
+ * Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). Cross-repo P3a (D23 as amended 2026-10-12,
454
+ * QA C1): also the gate's `DeterministicDeps.dispatchStartedAt`, the `since` of W's ignored-module listing, on the synchronous
455
+ * and the deferred path alike (the deferred entry keeps this value, never the router_verify time).
456
+ */
386
457
  readonly dispatchedAt: number;
387
458
  }
388
459
 
@@ -410,6 +481,38 @@ export interface DeferredFinishInput {
410
481
  * the gate runs as before (I1).
411
482
  */
412
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;
490
+ /**
491
+ * Cross-repo I2 (P2.3): where the change capture observes a role dispatch (its work root W). Absent: `cwd`, as before.
492
+ * Only the observation uses it; the registration keeps `cwd`, the base the checks run in (F5).
493
+ */
494
+ readonly captureRoot?: string;
495
+ /**
496
+ * Cross-repo P2e: the DoD's per-check placements (index-aligned with `dod.checks`), as the dispatch resolved them. Only the
497
+ * static scoping plan and the no-change shortcut read them. Absent: every check runs at `cwd` and in its default scope.
498
+ */
499
+ readonly placements?: readonly (CheckPlacement | undefined)[];
500
+ /** Cross-repo P2e: the dispatch runs the full scope (the whole suite), so an empty change set still spawns the suite. */
501
+ readonly fullScope?: boolean;
502
+ }
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)));
413
516
  }
414
517
 
415
518
  /** Deferred budget snapshots kept for `router_verify` (by handle; oldest dropped first, like the pending registry's bound). */
@@ -434,9 +537,14 @@ export type DeferredFinish =
434
537
  * "unregistered": the registry refused the entry (registry-full, handle-collision,
435
538
  * invalid-input); "no-change": an attributed empty change set of a testsPass-only DoD, which
436
539
  * the required gate passes with no process (section 1.5-6; QA-G-1: any other DoD is deferred
437
- * with the empty set instead, noChangeGateSpawnsNothing); "error": the finish itself failed.
540
+ * with the empty set instead, noChangeGateSpawnsNothing); "error": the finish itself failed;
541
+ * "branch-switched" (I7, P0.2): the working tree switched branch during the dispatch, so no handle is issued that could
542
+ * verify the other branch later; the required gate refuses it at once (its observeChange sees the same switch);
543
+ * "cross-repo" (P1.8, P2e.5 X7): the dispatch's perimeter, observed at return, cannot be frozen for a later handle: a
544
+ * repository of it changed while an unattributable writer ran (I4), or a linked repository could not be observed within
545
+ * the deferral bound; the required gate verifies it at once.
438
546
  */
439
- readonly reason: "unregistered" | "no-change" | "error";
547
+ readonly reason: "unregistered" | "no-change" | "error" | "branch-switched" | "cross-repo";
440
548
  readonly detail: string;
441
549
  };
442
550
 
@@ -477,8 +585,19 @@ export function hasTestsPass(dod: DoD): boolean {
477
585
  * there is no criterion. Only such a delegation takes finishDeferred's "no-change" answer
478
586
  * (QA-2.4-10); any other deferred DoD is registered with the empty change set instead, so its
479
587
  * build, lint, run, file and criteria checks run on router_verify, never synchronously.
588
+ *
589
+ * Cross-repo P2e (F13): a full scope runs the whole suite even with no changed file
590
+ * (deterministic.ts), so the gate spawns it: false when `fullScope` is set and the DoD has a
591
+ * testsPass or lintClean check, or when such a check's placement has `scope === "full"`. Without
592
+ * `opts`: as before.
480
593
  */
481
- export function noChangeGateSpawnsNothing(dod: DoD): boolean {
594
+ export function noChangeGateSpawnsNothing(
595
+ dod: DoD,
596
+ opts?: { readonly placements?: readonly (CheckPlacement | undefined)[] | undefined; readonly fullScope?: boolean | undefined },
597
+ ): boolean {
598
+ const scoped = (kind: DoD["checks"][number]["kind"]): boolean => kind === "testsPass" || kind === "lintClean";
599
+ if (opts?.fullScope === true && dod.checks.some(c => scoped(c.kind))) return false;
600
+ if (opts?.placements !== undefined && dod.checks.some((c, i) => scoped(c.kind) && opts.placements?.[i]?.scope === "full")) return false;
482
601
  return dod.checks.length > 0 && dod.checks.every(c => c.kind === "testsPass") && dod.criteria.length === 0;
483
602
  }
484
603
 
@@ -534,7 +653,9 @@ export type HandleReport =
534
653
  | { readonly kind: "unknown"; readonly input: string }
535
654
  | { readonly kind: "expired"; readonly handle: string }
536
655
  /** Joined another call's run, which outlived this call's deadline (R8). */
537
- | { 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 };
538
659
 
539
660
  export interface VerifyReport {
540
661
  readonly items: readonly HandleReport[];
@@ -551,8 +672,37 @@ export const ROUTER_VERIFY_NO_RETRY_TEXT = "[router] Nothing was retried or esca
551
672
  export const DRIFT_NOTICE = "tree drifted since delegation; verdict reflects current state";
552
673
  /** No per-file proof either way (no stored or current digests): a pass is never kept then. */
553
674
  export const DRIFT_UNCHECKED_NOTICE = "drift since delegation could not be checked; verdict reflects current state";
675
+ /**
676
+ * Cross-repo P2e.4a (S11, OD-P2e-1 = UNVERIFIED): the caveat of a frozen link target that router_verify found changed, or could
677
+ * not observe again, since the producer returned. A would-be pass then is unverifiable; a fail stays a fail with the caveat.
678
+ */
679
+ export const LINK_DRIFT_CAVEAT = {
680
+ changed: (name: string, root: string): string =>
681
+ `the linked repository ${linkCaveatText(name)} at ${linkCaveatText(root)} changed since the producer returned; the checks ran against its new state`,
682
+ unobserved: (name: string, root: string): string =>
683
+ `the linked repository ${linkCaveatText(name)} at ${linkCaveatText(root)} could not be observed again since the producer returned`,
684
+ } as const;
685
+ /** Cross-repo P3 QA-1 M5: the longest repository text (a link's name or root) a router line quotes; past it, cut with "…". */
686
+ export const LINK_CAVEAT_TEXT_MAX = 256;
687
+ /**
688
+ * Cross-repo P3 QA-1 M5: repository text (a link's name or root, read from a manifest or the file system) as a router line
689
+ * quotes it: capped at LINK_CAVEAT_TEXT_MAX characters (never splitting a surrogate pair), then escaped.
690
+ */
691
+ function linkCaveatText(text: string): string {
692
+ let shown = text;
693
+ if (shown.length > LINK_CAVEAT_TEXT_MAX) {
694
+ let end = LINK_CAVEAT_TEXT_MAX - 1;
695
+ const last = shown.charCodeAt(end - 1);
696
+ if (last >= 0xd800 && last <= 0xdbff) end -= 1;
697
+ shown = `${shown.slice(0, end)}…`;
698
+ }
699
+ return displaySafe(shown);
700
+ }
554
701
  export const ROUTER_VERIFY_CANCELLED_REASON = "router_verify was cancelled before a verdict";
555
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.";
556
706
  /** Drifted paths named per handle; the rest are counted. */
557
707
  export const DRIFT_MAX_PATHS = 10;
558
708
 
@@ -604,6 +754,9 @@ const TRANSIENT_REASON = new RegExp(
604
754
  escapeRegExp(ABANDONED_REASON),
605
755
  escapeRegExp(DISPOSED_REASON),
606
756
  "router_verify was cancelled",
757
+ // branch.ts branchUnconfirmedReason: the head state could not be read at router_verify; reading it again can settle it.
758
+ // Not the "when the dispatch started" variant, nor a "switched"/"checked out or reset" reason: those are terminal.
759
+ "cannot confirm the branch of [^\\r\\n]*?: the working tree could not be read at router_verify",
607
760
  ].join("|") +
608
761
  ")",
609
762
  "i",
@@ -662,6 +815,10 @@ export function formatVerifyReport(
662
815
  blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${VERIFYING_ELSEWHERE_TEXT}`);
663
816
  continue;
664
817
  }
818
+ if (item.kind === "held") {
819
+ blocks.push(`- ${item.handle} \u00b7 ${item.description} \u00b7 ${HELD_RESULT_TEXT}`);
820
+ continue;
821
+ }
665
822
  const { result } = item;
666
823
  const verdict = result.verdict;
667
824
  const via = item.via === "joined" ? " (joined a run already in progress)" : item.via === "cached" ? " (cached verdict; nothing was run)" : "";
@@ -683,7 +840,8 @@ export function formatVerifyReport(
683
840
  lines.push(indent(`[router] ${DRIFT_UNCHECKED_NOTICE}`));
684
841
  }
685
842
  if (judged.accepted) {
686
- 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()));
687
845
  } else {
688
846
  lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null, incomplete: isIncompleteVerdict(verdict) }))));
689
847
  lines.push(indent(ROUTER_VERIFY_NO_RETRY_TEXT));
@@ -713,11 +871,52 @@ export function backgroundOutcomes(items: readonly HandleReport[]): BackgroundOu
713
871
  ? { kind: "judged", handle: item.handle, description: item.description, result: item.result }
714
872
  : { kind: "reported", handle: item.handle };
715
873
  }
716
- if (item.kind === "elsewhere") return { kind: "reported", handle: item.handle };
874
+ if (item.kind === "elsewhere" || item.kind === "held") return { kind: "reported", handle: item.handle };
717
875
  return { kind: "gone", handle: item.kind === "unknown" ? item.input : item.handle };
718
876
  });
719
877
  }
720
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
+
721
920
  /** A never-rejecting wait for `promise` that ends with `fallback()` once `signal` aborts. */
722
921
  function untilAborted<T>(promise: Promise<T>, signal: AbortSignal, fallback: () => T): Promise<T> {
723
922
  if (signal.aborted) return Promise.resolve(fallback());
@@ -834,6 +1033,8 @@ export interface VerificationWiring {
834
1033
  * check or a criterion stays deferred with that empty set.)
835
1034
  */
836
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;
837
1038
  /**
838
1039
  * 2.4.2a: the deferred finish. No gate, no test command, no slot: a tree snapshot and the commit
839
1040
  * diff (git only, as prepareVerification) under DEFERRED_FINISH_MS, the static scoping plan
@@ -900,13 +1101,25 @@ export interface VerificationWiring {
900
1101
  * clears a pending timer and aborts the git calls of a GC in flight. Never throws.
901
1102
  */
902
1103
  startReferenceGc(delayMs?: number): () => void;
903
- /** P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given. */
1104
+ /**
1105
+ * P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given.
1106
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): `dispatchStartedAt` is the dispatch's start (DispatchStart.dispatchedAt),
1107
+ * carried as PreparedVerification.dispatchStartedAt; absent: W's ignored modules are never cross-link inputs.
1108
+ */
904
1109
  prepareVerification(
905
1110
  store: ReturnType<typeof createChangedFileStore>,
906
1111
  id: string,
907
1112
  childID: string,
908
1113
  cwd?: string,
909
1114
  deadline?: Deadline,
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,
910
1123
  ): Promise<PreparedVerification>;
911
1124
  /** Session ids currently running a grader prompt, so hooks can skip them. */
912
1125
  graderSessions: Set<string>;
@@ -931,7 +1144,7 @@ export interface VerificationWiring {
931
1144
  * the changed files are "unavailable" and the reference is the untracked default. `deadline`
932
1145
  * bounds every testsPass step (T3); without it each testsPass check owns one of gateBudgetMs.
933
1146
  */
934
- 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;
935
1148
  /**
936
1149
  * 2.2.3: the idle-TTL sweep's hook into the plugin's one S5 batch coordinator (batch.ts B11):
937
1150
  * evicts windows with no live member and batches whose seam hung past BATCH_STALE_GRACE_MS.
@@ -979,6 +1192,7 @@ function errorText(err: unknown): string {
979
1192
  }
980
1193
 
981
1194
  export function createVerificationWiring(deps: {
1195
+ observations?: V2Observations;
982
1196
  client: any;
983
1197
  childRunner?: ChildSessionRunner;
984
1198
  /** Project root; relative paths in checks resolve against it. */
@@ -991,7 +1205,17 @@ export function createVerificationWiring(deps: {
991
1205
  /** Test seams of the S5 batch coordinator (clock, timers, platform, maximum window size). */
992
1206
  batch?: Omit<BatchCoordinatorOptions, "logger">;
993
1207
  /** Test seams of the pending registry (clock, random source). */
994
- 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">;
995
1219
  /** Test seams of the 2.4.5 background queue; used only when `background` is true. */
996
1220
  background?: Pick<BackgroundQueueOptions, "now" | "timers" | "settleMs" | "retryBaseMs" | "maxAttempts" | "platform">;
997
1221
  }): VerificationWiring {
@@ -1025,11 +1249,41 @@ export function createVerificationWiring(deps: {
1025
1249
  onEvict: (entry, cause) => logger.debug?.("[verify] pending delegation evicted", { handle: entry.handle, cause }),
1026
1250
  });
1027
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
+ });
1028
1280
  /**
1029
1281
  * 2.4.5: assigned once verifyHandles exists, and only when `background` is true at plugin start
1030
1282
  * (pending.ts R14). With background off this stays undefined: no queue, no timer, no run.
1031
1283
  */
1032
1284
  let background: BackgroundQueue | undefined;
1285
+ const liveWiring = { preempt: async (): Promise<void> => { await background?.preempt(); } };
1286
+ liveWirings.add(liveWiring);
1033
1287
  /** QA-2.4-5: foreground testsPass requests in flight (the background queue's `busy`). */
1034
1288
  const foreground = { tests: 0 };
1035
1289
  /** 2.4.2b: native `task` dispatch starts, before hook -> after hook (bounded FIFO, swept). */
@@ -1067,6 +1321,7 @@ export function createVerificationWiring(deps: {
1067
1321
  signal: opts?.signal,
1068
1322
  lowPriority: opts?.lowPriority,
1069
1323
  env: opts?.env,
1324
+ ...(opts?.service === undefined ? {} : { service: opts.service }),
1070
1325
  });
1071
1326
 
1072
1327
  const argvSeam: ArgvSeam = (file, args, opts) =>
@@ -1076,6 +1331,7 @@ export function createVerificationWiring(deps: {
1076
1331
  signal: opts?.signal,
1077
1332
  lowPriority: opts?.lowPriority,
1078
1333
  env: opts?.env,
1334
+ ...(opts?.service === undefined ? {} : { service: opts.service }),
1079
1335
  });
1080
1336
 
1081
1337
  // T9 1.3: PlannerFs + unlink over fs.promises. realpath is the native one; fileExists accepts
@@ -1229,6 +1485,8 @@ export function createVerificationWiring(deps: {
1229
1485
  parentSessionID?: string,
1230
1486
  inFlight?: Set<string>,
1231
1487
  creatorSessionID: string | null = parentSessionID ?? null,
1488
+ service?: ServiceObservation,
1489
+ graderDispatchLabel?: string,
1232
1490
  ): Promise<{ sessionID: string; text: string; model: string | null }> => {
1233
1491
  // #84 P3.3 fix 2: the model the grader is dispatched on travels with its answer (checker.ts GraderResult.model → the
1234
1492
  // verdict's `grader`), so the outcome signals can check its independence (plan §2.6). Null: the host's default model.
@@ -1239,6 +1497,7 @@ export function createVerificationWiring(deps: {
1239
1497
  const controller = new AbortController();
1240
1498
  const model = tierModel(cfg, req.tier);
1241
1499
  let sid: string | undefined;
1500
+ const preparation = service?.start("service-prep", "grader-startup");
1242
1501
  try {
1243
1502
  const answer = await withTimeout(deps.childRunner.run({
1244
1503
  parentSessionID,
@@ -1247,6 +1506,7 @@ export function createVerificationWiring(deps: {
1247
1506
  system: req.system,
1248
1507
  prompt: req.prompt,
1249
1508
  signal: controller.signal,
1509
+ ...(service === undefined ? {} : { service, onServiceStart: () => preparation?.end("completed") }),
1250
1510
  async onCreated(sessionID) {
1251
1511
  sid = sessionID;
1252
1512
  graderSessions.add(sessionID);
@@ -1255,7 +1515,15 @@ export function createVerificationWiring(deps: {
1255
1515
  },
1256
1516
  }), graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs), "grader prompt");
1257
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;
1258
1525
  } finally {
1526
+ preparation?.end("error");
1259
1527
  controller.abort();
1260
1528
  if (sid) {
1261
1529
  graderSessions.delete(sid);
@@ -1333,6 +1601,10 @@ export function createVerificationWiring(deps: {
1333
1601
  // QA-3.1-8: the snapshot's git processes run at the configured priority, as the capture's do.
1334
1602
  snapshot: (at: string, signal: AbortSignal) =>
1335
1603
  sharedSnapshots(flightKey(at), shared => snapshotTree(at, shared, { lowPriority: budget.lowPriority }), signal),
1604
+ // The branch-switch baseline: independent of the snapshot, so it survives a discarded or failed one.
1605
+ // QA2 F3b: each git process gets the whole baseline budget (a loaded runner outlasts readHead's 5 s default).
1606
+ headState: (at: string, signal: AbortSignal) =>
1607
+ readHead(at, { signal, timeoutMs: budget.baselineTimeoutMs, lowPriority: budget.lowPriority }),
1336
1608
  timeoutMs: budget.baselineTimeoutMs,
1337
1609
  };
1338
1610
  if (!judgedByTests) return { ...base, uncaptured: { kind: "none", reason: REFERENCE_NONE.notRequested } };
@@ -1353,7 +1625,10 @@ export function createVerificationWiring(deps: {
1353
1625
  deadline?: Deadline,
1354
1626
  forceLowPriority = false,
1355
1627
  creatorSessionID: string | null = parentSessionID ?? null,
1628
+ serviceIdentity?: () => ServiceIdentity,
1356
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);
1357
1632
  const cfg = getConfig();
1358
1633
  const resolved = resolveVerifyBudget(cfg);
1359
1634
  // 2.4.5 (section 1.5-19): background runs are low priority whatever `lowPriority` says.
@@ -1362,17 +1637,27 @@ export function createVerificationWiring(deps: {
1362
1637
  // QA-2.1-5: the recheck's git processes (GC, materialize, dispose) run at the configured
1363
1638
  // priority too, like the capture and the start-up GC (QA-1.2-13).
1364
1639
  const referenceArgv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
1640
+ // QA-2 nit: materialize pins a link target as this gate's dispatch admitted it (its pins' admission); without pins, none.
1641
+ const gatePins = prepared?.reference?.kind === "captured" ? prepared.reference.reference.pins : undefined;
1642
+ const pinNow = pinNowFor(gatePins !== undefined ? pinAdmissions.get(gatePins) : undefined);
1365
1643
  const openScope = createScopeOpener({
1644
+ service,
1366
1645
  argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1367
- reference: { argv: referenceArgv },
1646
+ reference: { argv: referenceArgv, pinNow },
1368
1647
  });
1369
1648
  const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
1370
1649
  const direct = createDirectTestsPassHook({
1650
+ service,
1371
1651
  openScope,
1372
1652
  plannerFs: fsSeam,
1373
1653
  search: testSearch(budget, deadline),
1374
1654
  budget,
1375
1655
  ...currentTree,
1656
+ // Cross-repo P3a (D23): the linked repository's ignored modules, hardened and bounded; called only with crossLinkRoot and
1657
+ // the dispatch start (D23 as amended 2026-10-12: only the modules modified since, never a stale build output).
1658
+ listIgnored: (root, signal, since) => listIgnoredModules(root, { signal, since, lowPriority: budget.lowPriority }),
1659
+ // QA round 2 M-A: a changed source of W newer than the newest listed build output makes the request S6 build-stale.
1660
+ mtimeOf: (path) => fileMtimeMs(path),
1376
1661
  });
1377
1662
  // 2.2.3 (S5): with a batch window, concurrent testsPass checks of this plugin instance meet in
1378
1663
  // the coordinator; the direct hook stays behind it for "full" scope and single requests (B2).
@@ -1408,6 +1693,29 @@ export function createVerificationWiring(deps: {
1408
1693
  foreground.tests += 1;
1409
1694
  try {
1410
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
+ }
1411
1719
  return await inner(request);
1412
1720
  } finally {
1413
1721
  foreground.tests -= 1;
@@ -1416,6 +1724,7 @@ export function createVerificationWiring(deps: {
1416
1724
  }
1417
1725
  return {
1418
1726
  deterministic: {
1727
+ ...(service === undefined ? {} : { service }),
1419
1728
  exec: execSeam,
1420
1729
  fs: fsSeam,
1421
1730
  cwd: directory,
@@ -1428,10 +1737,12 @@ export function createVerificationWiring(deps: {
1428
1737
  changedFiles: prepared?.changeBaseline === "available" ? prepared.changedFiles : "unavailable",
1429
1738
  ...(prepared !== undefined ? { reference: prepared.reference } : {}),
1430
1739
  ...(deadline !== undefined ? { deadline } : {}),
1740
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch start, the `since` of W's ignored-module listing; absent: none listed.
1741
+ ...(prepared?.dispatchStartedAt !== undefined ? { dispatchStartedAt: prepared.dispatchStartedAt } : {}),
1431
1742
  },
1432
1743
  checker: {
1433
1744
  dispatchGrader: (req: GraderRequest) =>
1434
- dispatchGrader(req, parentSessionID, inFlight, creatorSessionID),
1745
+ dispatchGrader(req, parentSessionID, inFlight, creatorSessionID, service, prepared?.graderDispatchLabel),
1435
1746
  ladder: ["fast", "medium", "heavy"],
1436
1747
  minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
1437
1748
  },
@@ -1441,6 +1752,84 @@ export function createVerificationWiring(deps: {
1441
1752
  };
1442
1753
  };
1443
1754
 
1755
+ /**
1756
+ * Cross-repo P2d.3 (P2.6): the dispatch-time pins of a dispatch's admitted link targets, by dispatch id then by the seed's
1757
+ * root (`PerimeterSeed.at`). Each `pin` settles once and never rejects. QA-2 #9c: an unattributable writer that runs while a
1758
+ * pin (its root or a nested target) is still computed marks it `contaminatedBy`, and linkPinsAtGate drops it. QA-2 nit:
1759
+ * freed once the dispatch's gate took them, or with a reference that was not captured (freeLinkPins); bounded otherwise.
1760
+ */
1761
+ interface DispatchLinkPin {
1762
+ readonly pin: Promise<LinkPin>;
1763
+ pending: boolean;
1764
+ contaminatedBy?: string;
1765
+ }
1766
+ const linkPins = new Map<string, Map<string, DispatchLinkPin>>();
1767
+ const LINK_PINS_MAX = 256;
1768
+ /** QA-2 nit: per dispatch, the link roots (perimeterKey) its admission accepted; bounded, oldest out. */
1769
+ const admittedLinks = new Map<string, Set<string>>();
1770
+ /** The admitted link roots behind the pins a gate took (keyed by that pins array): pinNow admits as the dispatch did. */
1771
+ const pinAdmissions = new WeakMap<readonly LinkPin[], ReadonlySet<string>>();
1772
+ const rememberAdmittedLink = (id: string, dir: string): void => {
1773
+ let admitted = admittedLinks.get(id);
1774
+ if (admitted === undefined) {
1775
+ admitted = new Set();
1776
+ admittedLinks.set(id, admitted);
1777
+ }
1778
+ admitted.add(perimeterKey(dir));
1779
+ while (admitted.size > 1024) {
1780
+ const oldest = admitted.values().next();
1781
+ if (oldest.done === true) break;
1782
+ admitted.delete(oldest.value);
1783
+ }
1784
+ };
1785
+ /** QA-2 nit: forgets a dispatch's pins and admitted roots; the pins its gate took keep that admission for pinNow. */
1786
+ const freeLinkPins = (id: string, taken: readonly LinkPin[]): void => {
1787
+ const admitted = admittedLinks.get(id);
1788
+ if (admitted !== undefined && taken.length > 0) pinAdmissions.set(taken, admitted);
1789
+ linkPins.delete(id);
1790
+ admittedLinks.delete(id);
1791
+ };
1792
+ /**
1793
+ * QA-2 #9c: an unattributable writer (any session: its directory says nothing about where it writes) discards every pin still
1794
+ * being computed, as it discards an in-flight perimeter snapshot (dispatch.ts contaminateCaptures). M3: the store only signals
1795
+ * the writers that contaminate captures by the same predicate, so a delegating tool (task, delegate, subagent), which keeps
1796
+ * the perimeter snapshot, keeps the pins too; parallel role dispatches no longer drop each other's pins.
1797
+ */
1798
+ const contaminateLinkPins = (tool: string): void => {
1799
+ if (!isUnattributedWriter(tool)) return;
1800
+ for (const forDispatch of linkPins.values()) {
1801
+ for (const pin of forDispatch.values()) if (pin.pending) pin.contaminatedBy ??= tool;
1802
+ }
1803
+ };
1804
+ /**
1805
+ * QA-2 #9c: the store's own writer signal (store.onUnattributedWriter: observeEdit before a call, record after it, the calls
1806
+ * that contaminate an in-flight perimeter snapshot) also reaches the pins. Subscribed once per store, by the first dispatch
1807
+ * that pins a link target; the subscription is bounded by the store's own lifetime (it holds the pins map only).
1808
+ */
1809
+ const watchedStores = new WeakSet<object>();
1810
+ const watchWritersFor = (store: ReturnType<typeof createChangedFileStore>): void => {
1811
+ if (watchedStores.has(store)) return;
1812
+ watchedStores.add(store);
1813
+ store.onUnattributedWriter(tool => contaminateLinkPins(tool));
1814
+ };
1815
+ /**
1816
+ * Cross-repo P2d.3 (P2.6): the current pin of a link target at materialize time (hardened, ignored files digested), admitted
1817
+ * as the dispatch admitted it (QA-2 nit: the gate's own pins' admission, never another dispatch's). Never throws (pinTarget).
1818
+ */
1819
+ const pinNowFor = (admitted: ReadonlySet<string> | undefined) => (root: string): Promise<LinkPin> =>
1820
+ pinTarget(root, {
1821
+ snapshot: dir => {
1822
+ const controller = new AbortController();
1823
+ return withTimeout(
1824
+ snapshotTree(dir, controller.signal, { lowPriority: configuredLowPriority(), hardened: true, ignoredDigest: true }),
1825
+ GRADE_SNAPSHOT_TIMEOUT_MS,
1826
+ "link pin fingerprint",
1827
+ ).catch(() => undefined).finally(() => controller.abort());
1828
+ },
1829
+ admitted: dir => admitted?.has(perimeterKey(dir)) === true,
1830
+ externalLinks: defaultExternalLinks,
1831
+ });
1832
+
1444
1833
  const beginVerification: VerificationWiring["beginVerification"] = async (store, id, cwd, dod) => {
1445
1834
  let deps: DispatchCaptureDeps;
1446
1835
  try {
@@ -1450,17 +1839,506 @@ export function createVerificationWiring(deps: {
1450
1839
  // QA-3.1-8), and no reference.
1451
1840
  deps = {
1452
1841
  snapshot: (at, signal) => snapshotTree(at, signal, { lowPriority: true }),
1842
+ headState: (at, signal) => readHead(at, { signal, lowPriority: true }),
1453
1843
  timeoutMs: DEFAULT_CAPTURE_TIMEOUT_MS,
1454
1844
  uncaptured: { kind: "none", reason: `${REFERENCE_NONE.failed} (${errorText(err)})` },
1455
1845
  };
1456
1846
  }
1457
- const begun = store.beginDispatch(id, resolve(directory, cwd || "."), deps);
1847
+ const at = resolve(directory, cwd || ".");
1848
+ // Cross-repo P1.8 (I13): a role dispatch's perimeter is fixed now; every other dispatch plans none (I9). QA-1 F9: a ladder
1849
+ // retry keeps the dispatch's perimeter (beginDispatch keeps the original), so it is not planned again.
1850
+ let perimeter: DispatchPerimeter | undefined;
1851
+ if (store.perimeterOf(id) === undefined) {
1852
+ try {
1853
+ const plannedPerimeter = planPerimeter(id, at, () => {
1854
+ const routing = resolveRolesRouting(getConfig(), "v2");
1855
+ return { parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude };
1856
+ });
1857
+ perimeter = plannedPerimeter;
1858
+ // P3 QA-1 m4 (SD-P3c-4): a forward bound cut W's declared edges; logged, the cut targets are not in P.
1859
+ if (plannedPerimeter?.edgesIncomplete === true || (plannedPerimeter?.unadmittedMore ?? 0) > 0) {
1860
+ logger.warn("[verify] dispatch perimeter: declared dependency edges were cut by a bound", {
1861
+ id,
1862
+ incomplete: plannedPerimeter?.edgesIncomplete === true,
1863
+ unadmittedMore: plannedPerimeter?.unadmittedMore ?? 0,
1864
+ });
1865
+ }
1866
+ } catch (err) {
1867
+ logger.warn("[verify] dispatch perimeter could not be planned", { id, error: errorText(err) });
1868
+ // QA-1 F10: fail closed. A placeholder root that is never observed: a dispatch whose producer ran an unattributable
1869
+ // writer is unverifiable (I4), since a write in another repository cannot be ruled out.
1870
+ perimeter = { roots: [{ at, name: PERIMETER_UNPLANNED, fixed: "unobserved" }] };
1871
+ }
1872
+ }
1873
+ const lowPriority = configuredLowPriority();
1874
+ // Cross-repo P2d.3 (P2.6): an admitted link target is pinned at dispatch (bounded by the capture timeout; the nested targets
1875
+ // are snapshotted hardened, one level deep, by pinTarget). QA-2 #4: the perimeter snapshot stays the plain hardened one; the
1876
+ // pin takes its own snapshots (ignored files digested), started once that snapshot settled, and neither dispatch start nor
1877
+ // the perimeter entry waits for it.
1878
+ const perimeterRootSnapshot = (root: string, signal: AbortSignal): Promise<TreeSnapshot | undefined> => {
1879
+ const plain = snapshotTree(root, signal, { lowPriority, hardened: true });
1880
+ const seed = perimeter?.roots.find(candidate => candidate.at === root);
1881
+ // QA-1 #9a: a working-set root that is also a link target of W (`linked`) is pinned too. Cross-repo P3c.3 (F3): a declared
1882
+ // dependency edge's root (origin "edge", or a working-set root marked `edged`) is observed but never pinned.
1883
+ if (seed === undefined || (seed.origin !== "link" && seed.linked !== true) || seed.fixed !== undefined) return plain;
1884
+ watchWritersFor(store);
1885
+ const seedAdmit = seed.admit ?? ((): boolean => false);
1886
+ // The roots the dispatch's admission accepted: the materialize-time pin (pinNow) is admitted by the same set.
1887
+ const admit = (dir: string): boolean => {
1888
+ const admitted = seedAdmit(dir);
1889
+ if (admitted) rememberAdmittedLink(id, dir);
1890
+ return admitted;
1891
+ };
1892
+ const pinSnapshot = async (dir: string): Promise<TreeSnapshot | undefined> => {
1893
+ const controller = new AbortController();
1894
+ try {
1895
+ return await withTimeout(
1896
+ snapshotTree(dir, controller.signal, { lowPriority, hardened: true, ignoredDigest: true }),
1897
+ deps.timeoutMs,
1898
+ "link pin fingerprint",
1899
+ );
1900
+ } catch {
1901
+ return undefined;
1902
+ } finally {
1903
+ controller.abort();
1904
+ }
1905
+ };
1906
+ const entry: DispatchLinkPin = {
1907
+ pending: true,
1908
+ pin: plain.then(() => undefined, () => undefined)
1909
+ .then(() => withTimeout(
1910
+ pinTarget(root, { snapshot: pinSnapshot, admitted: admit, externalLinks: defaultExternalLinks }),
1911
+ deps.timeoutMs,
1912
+ "link pin",
1913
+ ))
1914
+ .catch((): LinkPin => ({ kind: "unpinnable", root, why: "not-observed" }))
1915
+ .finally(() => {
1916
+ entry.pending = false;
1917
+ }),
1918
+ };
1919
+ let forDispatch = linkPins.get(id);
1920
+ if (forDispatch === undefined) {
1921
+ forDispatch = new Map();
1922
+ linkPins.set(id, forDispatch);
1923
+ // Bounded: a dispatch whose gate never ran is evicted by newer ones (oldest first), with its admitted roots.
1924
+ while (linkPins.size > LINK_PINS_MAX) {
1925
+ const oldest = linkPins.keys().next();
1926
+ if (oldest.done === true) break;
1927
+ linkPins.delete(oldest.value);
1928
+ admittedLinks.delete(oldest.value);
1929
+ }
1930
+ }
1931
+ forDispatch.set(root, entry);
1932
+ return plain;
1933
+ };
1934
+ const begun = store.beginDispatch(id, at, perimeter === undefined ? deps : {
1935
+ ...deps,
1936
+ perimeter,
1937
+ // QA-1 F4 (I11): git runs hardened in a repository other than W.
1938
+ perimeterSnapshot: perimeterRootSnapshot,
1939
+ });
1458
1940
  // pending.ts R10: remember the reference's settled value (the store hands out one promise).
1459
1941
  const reference = store.reference(id);
1460
1942
  if (!settledReferences.has(reference)) void reference.then(state => settledReferences.set(reference, state));
1461
1943
  await begun;
1462
1944
  };
1463
1945
 
1946
+ /**
1947
+ * Cross-repo P2d.3 (P2.6): the dispatch's link pins that are ready within the gate deadline. A pin whose root's dispatch
1948
+ * snapshot was discarded (contaminated), a fixed root and a pin not ready in time are omitted. Never throws.
1949
+ */
1950
+ const linkPinsAtGate = async (
1951
+ store: ReturnType<typeof createChangedFileStore>,
1952
+ id: string,
1953
+ deadline: Deadline | undefined,
1954
+ ): Promise<LinkPin[]> => {
1955
+ const forDispatch = linkPins.get(id);
1956
+ const planned = store.perimeterOf(id);
1957
+ if (forDispatch === undefined || planned === undefined) return [];
1958
+ const ready = await Promise.all([...forDispatch].map(async ([root, pinned]): Promise<LinkPin | undefined> => {
1959
+ const entry = planned.entries.get(root);
1960
+ if (entry === undefined || entry.seed.fixed !== undefined || entry.contaminatedBy !== undefined) return undefined;
1961
+ const ms = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
1962
+ if (ms <= 0 || deadline?.signal.aborted === true) return undefined;
1963
+ try {
1964
+ const pin = await withTimeout(pinned.pin, ms, "link pin");
1965
+ // QA-2 #9c: an unattributable writer ran while it (or a nested target's snapshot) was computed: dropped.
1966
+ return pinned.contaminatedBy === undefined ? pin : undefined;
1967
+ } catch {
1968
+ return undefined;
1969
+ }
1970
+ }));
1971
+ return ready.filter((pin): pin is LinkPin => pin !== undefined);
1972
+ };
1973
+
1974
+ /** The two snapshots of each extra root of a perimeter (perimeterSnapshotsAtGate); `fixed` roots have neither. */
1975
+ type PerimeterSnapshots = readonly { entry: PerimeterEntry; before: TreeSnapshot | undefined; now: TreeSnapshot | undefined }[];
1976
+
1977
+ /**
1978
+ * Cross-repo P1.8 (I4, I13): each extra root of the dispatch's perimeter snapshotted again, hardened (QA-1 F4) and bounded by
1979
+ * `deadline`, next to its dispatch snapshot. QA-1 F9: the roots are snapshotted concurrently with each other, and the caller
1980
+ * starts this before W's own gate snapshot so both run at once. A fixed root (never observed) is not snapshotted. Undefined
1981
+ * when the dispatch has no perimeter.
1982
+ */
1983
+ const perimeterSnapshotsAtGate = async (
1984
+ store: ReturnType<typeof createChangedFileStore>,
1985
+ id: string,
1986
+ deadline: Deadline | undefined,
1987
+ ): Promise<{ name?: string; snapshots: PerimeterSnapshots; admission?: DispatchPerimeter["admission"] } | undefined> => {
1988
+ const planned = store.perimeterOf(id);
1989
+ if (planned === undefined || planned.entries.size === 0) return undefined;
1990
+ const bound = (): number => (deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS);
1991
+ const lowPriority = configuredLowPriority();
1992
+ const snapshots = await Promise.all([...planned.entries.values()].map(async entry => {
1993
+ if (entry.seed.fixed !== undefined) return { entry, before: undefined, now: undefined };
1994
+ const before = withTimeout(entry.snapshot, Math.max(1, bound()), "perimeter fingerprint").catch(() => undefined);
1995
+ const now = (async (): Promise<TreeSnapshot | undefined> => {
1996
+ const ms = bound();
1997
+ if (ms <= 0 || deadline?.signal.aborted === true) return undefined;
1998
+ const controller = new AbortController();
1999
+ const onAbort = (): void => controller.abort();
2000
+ deadline?.signal.addEventListener("abort", onAbort, { once: true });
2001
+ try {
2002
+ return await withTimeout(snapshotTree(entry.seed.at, controller.signal, { lowPriority, hardened: true }), ms, "perimeter fingerprint");
2003
+ } catch {
2004
+ return undefined;
2005
+ } finally {
2006
+ deadline?.signal.removeEventListener("abort", onAbort);
2007
+ controller.abort();
2008
+ }
2009
+ })();
2010
+ return { entry, before: await before, now: await now };
2011
+ }));
2012
+ return {
2013
+ ...(planned.name !== undefined ? { name: planned.name } : {}),
2014
+ snapshots,
2015
+ // P3c.4 (SD-P3c-9): the dispatch's admission, for the perimeter frozen at return (perimeterAtReturn).
2016
+ ...(planned.admission !== undefined ? { admission: planned.admission } : {}),
2017
+ };
2018
+ };
2019
+
2020
+ /**
2021
+ * Cross-repo P1.8 (I4, I8): each extra root of the dispatch's perimeter compared with its dispatch snapshot: "changed" when
2022
+ * the fingerprint, HEAD or top level differs, "unobserved" when either snapshot is unavailable (fail closed), a fixed root with
2023
+ * its own status. QA-1 F4: a root whose git top level is not admitted at the gate is reported unobserved, never dropped (I12).
2024
+ * Roots are de-duplicated by top level, W's own excluded. Undefined when the dispatch has no perimeter or none remains.
2025
+ * Cross-repo P2b.3 (D6): the working-set roots (never W, never a link target) whose `node_modules` link into W are its
2026
+ * consumers (perimeter.ts discoverConsumers: fs only, bounded, never throws).
2027
+ */
2028
+ const perimeterAtGate = async (
2029
+ planned: { name?: string; snapshots: PerimeterSnapshots; admission?: { readonly parents: readonly string[] } } | undefined,
2030
+ snapshot: TreeSnapshot | undefined,
2031
+ base: string,
2032
+ deadline?: Deadline,
2033
+ // Cross-repo P2e.5 (return mode): `discover: false` skips consumer discovery (router_verify discovers over the frozen
2034
+ // working set instead); nothing else differs.
2035
+ options: { readonly discover?: boolean } = {},
2036
+ ): Promise<PerimeterObservation | undefined> => {
2037
+ if (planned === undefined) return undefined;
2038
+ const key = (at: string): string => {
2039
+ const normalized = resolve(at).replace(/\\/g, "/");
2040
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
2041
+ };
2042
+ const wRoot = snapshot?.root ?? base;
2043
+ const rank = { unchanged: 0, unadmitted: 1, unobserved: 2, changed: 3 } as const;
2044
+ const roots = new Map<string, PerimeterRoot>();
2045
+ const workingSet = new Map<string, { root: string; name?: string }>();
2046
+ for (const { entry, before, now } of planned.snapshots) {
2047
+ const fixed = entry.seed.fixed;
2048
+ const known = fixed === undefined ? now?.root ?? before?.root : undefined;
2049
+ const refused = known !== undefined && entry.seed.admit !== undefined && !entry.seed.admit(known);
2050
+ const root = known !== undefined && !refused ? known : entry.seed.at;
2051
+ // W's own repository is W's snapshot (a fixed placeholder may stand at W's path: it is kept).
2052
+ if (fixed === undefined && key(root) === key(wRoot)) continue;
2053
+ if (entry.seed.origin === "working-set" && !workingSet.has(key(root))) {
2054
+ workingSet.set(key(root), { root, ...(entry.seed.name !== undefined ? { name: entry.seed.name } : {}) });
2055
+ }
2056
+ const status: PerimeterRoot["status"] = fixed ?? (refused || before === undefined || now === undefined
2057
+ ? "unobserved"
2058
+ : before.fingerprint !== now.fingerprint || before.head !== now.head || before.root !== now.root ? "changed" : "unchanged");
2059
+ // Only an admitted, observed root is described by its git state.
2060
+ const shown = fixed !== undefined || refused ? undefined : now ?? before;
2061
+ const next: PerimeterRoot = {
2062
+ root,
2063
+ name: entry.seed.name ?? basename(root),
2064
+ status,
2065
+ ...(typeof shown?.branch === "string" ? { branch: shown.branch } : {}),
2066
+ ...(shown?.head ? { head: shown.head } : {}),
2067
+ ...(entry.seed.sameRepository === true ? { sameRepository: true } : {}),
2068
+ };
2069
+ const previous = roots.get(key(root));
2070
+ if (previous === undefined || rank[next.status] > rank[previous.status]) roots.set(key(root), next);
2071
+ }
2072
+ if (roots.size === 0) return undefined;
2073
+ // QA-1 #13: the discovery is bounded by the gate deadline (and the grade snapshot bound); the roots it has not finished
2074
+ // then are incomplete. QA-1 #2: so is a root whose scan stopped on its entry bound without finding a consumer.
2075
+ const discover = async (): Promise<ConsumerDiscovery> => {
2076
+ const candidates = [...workingSet.values()];
2077
+ const controller = new AbortController();
2078
+ const ms = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
2079
+ const onAbort = (): void => controller.abort();
2080
+ if (ms <= 0 || deadline?.signal.aborted === true) controller.abort();
2081
+ deadline?.signal.addEventListener("abort", onAbort, { once: true });
2082
+ const timer = setTimeout(onAbort, Math.max(0, ms));
2083
+ try {
2084
+ // P3 QA-1 m5: both spellings of each parent, so an edge spelled through a junction-spelled parent is matched.
2085
+ const parents = planned.admission?.parents;
2086
+ return await discoverConsumers(wRoot, candidates, { signal: controller.signal, ...(parents !== undefined ? { parents } : {}) });
2087
+ } catch {
2088
+ return { consumers: [], incomplete: candidates }; // Never expected (it never throws): fail closed.
2089
+ } finally {
2090
+ clearTimeout(timer);
2091
+ deadline?.signal.removeEventListener("abort", onAbort);
2092
+ }
2093
+ };
2094
+ const { consumers, incomplete } = workingSet.size === 0 || options.discover === false
2095
+ ? { consumers: [], incomplete: [] }
2096
+ : await discover();
2097
+ return {
2098
+ w: {
2099
+ root: wRoot,
2100
+ name: planned.name ?? basename(wRoot),
2101
+ ...(typeof snapshot?.branch === "string" ? { branch: snapshot.branch } : {}),
2102
+ ...(snapshot?.head ? { head: snapshot.head } : {}),
2103
+ },
2104
+ roots: [...roots.values()],
2105
+ ...(consumers.length > 0 ? { consumers } : {}),
2106
+ ...(incomplete.length > 0 ? { consumersIncomplete: incomplete } : {}),
2107
+ };
2108
+ };
2109
+
2110
+ /** Cross-repo P2e.5: what a deferred entry freezes of its dispatch's perimeter (pending.ts DeferredPerimeter, without the pins). */
2111
+ type FrozenPerimeter = NonNullable<PendingEntry["perimeter"]>;
2112
+
2113
+ /**
2114
+ * Cross-repo P3c.6 (D26): the dependency targets the producer added to W during the dispatch, frozen at return. W's targets
2115
+ * are read again from `linkBase` through the union (`dependencyTargets`, fs only) with the dispatch's frozen admission; each
2116
+ * admitted one that no root in `covering` holds (the perimeter's roots), and that is not W's own repository (`own`: W's
2117
+ * directory and top level, as planPerimeter skips them), is snapshotted, hardened, within what remains of `deadline` (the
2118
+ * deferral bound), and frozen as a link. `unobserved`: one could not be observed in time, or its top level is no longer
2119
+ * admitted (X7: not deferred). An unadmitted target (no parent or worktree holds it, no git top level, a top the admission
2120
+ * refuses, or an unadmitted edge) is not snapshotted: it is returned in `unadmitted` (P3 QA-1 M4), frozen as covering only so
2121
+ * that router_verify does not name it new. Never a perimeter seed: P stays fixed at dispatch for writer attribution (I4, I13).
2122
+ * `targets`: what W depends on at return, so that a dispatch-time dependency the producer removed is frozen as such (P3 QA-1
2123
+ * M3); every target's path, an unadmitted one's included (P3 QA-2 F-2: a spelling the admission refuses still declares the
2124
+ * dependency), and absent when the read was cut (`incomplete`, or unadmitted targets past the names bound). More new targets than `room` (P3 QA-1 m2: PERIMETER_MAX) are not snapshotted: `unobserved`. Never throws.
2125
+ */
2126
+ const dependenciesAddedAtReturn = async (
2127
+ linkBase: string,
2128
+ admission: NonNullable<DispatchPerimeter["admission"]>,
2129
+ covering: readonly string[],
2130
+ own: readonly string[],
2131
+ deadline: Deadline,
2132
+ // P3 QA-1 m2: how many new targets P may still take (PERIMETER_MAX, W and the dispatch's observed roots counted); past it
2133
+ // none is snapshotted and `unobserved` is set (fail closed: verified at once).
2134
+ room = Number.POSITIVE_INFINITY,
2135
+ ): Promise<{
2136
+ links: FrozenPerimeter["links"];
2137
+ unobserved: boolean;
2138
+ /**
2139
+ * P3 QA-1 M3: what W depends on at return (every target's path, an unadmitted one's included: P3 QA-2 F-2). Absent: not
2140
+ * read, cut by a bound, or unadmitted targets past the names bound.
2141
+ */
2142
+ targets?: readonly string[];
2143
+ /** P3 QA-1 M4: the new targets not admitted, as router_verify names them (covering only, never seeds: I13). */
2144
+ unadmitted?: readonly string[];
2145
+ }> => {
2146
+ const read = ((): { context: ReturnType<typeof admissionFromData>; dependencies: DependencyTargets } | undefined => {
2147
+ try {
2148
+ const context = admissionFromData(admission);
2149
+ return { context, dependencies: dependencyTargets(linkBase, context) };
2150
+ } catch {
2151
+ return undefined; // Never expected (it skips what it cannot read).
2152
+ }
2153
+ })();
2154
+ // Fail closed: W's dependencies at return are unknown, so a new one cannot be ruled out (not deferred).
2155
+ if (read === undefined) return { links: [], unobserved: true };
2156
+ const { context, dependencies } = read;
2157
+ // P3 QA-2 F-2: every target, an unadmitted one included (its path: a spelling into a dispatch-time dependency still declares it).
2158
+ const targets = dependencies.targets.map(target => target.at);
2159
+ // Held by a perimeter root, or W's own repository (inside W, or W inside it): W's snapshot covers it.
2160
+ const covered = (at: string): boolean =>
2161
+ covering.some(root => depthBelow(at, root) >= 0) || own.some(dir => depthBelow(at, dir) >= 0 || depthBelow(dir, at) >= 0);
2162
+ // The admitted top level of each new target, once per repository.
2163
+ const added = new Map<string, string>();
2164
+ // P3 QA-1 M4: a new target not admitted, by the path router_verify reads it at (its text for an unadmitted edge).
2165
+ const unadmitted = new Map<string, string>();
2166
+ for (const target of dependencies.targets) {
2167
+ if (covered(target.at)) continue;
2168
+ // An unadmitted edge target is text only: never observed (I11).
2169
+ if ("fixed" in target) {
2170
+ unadmitted.set(perimeterKey(target.at), target.at);
2171
+ continue;
2172
+ }
2173
+ let top: string | undefined;
2174
+ if (target.origin === "edge") {
2175
+ top = target.at; // Already its admitted top level (resolveEdgeTarget).
2176
+ } else {
2177
+ // A package link target, admitted as at dispatch (SD-P3c-9, F8): its top level found without git below its parent (or
2178
+ // above its working-set worktree), then admitted by the frozen admission.
2179
+ const parent = context.parentOf(target.at);
2180
+ const worktree = context.worktreeOf(target.at);
2181
+ if (parent === undefined && worktree === undefined) {
2182
+ unadmitted.set(perimeterKey(target.at), target.at);
2183
+ continue;
2184
+ }
2185
+ top = gitTopOf(target.at, worktree !== undefined ? dirname(worktree.worktree) : parent);
2186
+ if (top === undefined || !context.admitTop(top)) {
2187
+ unadmitted.set(perimeterKey(target.at), target.at);
2188
+ continue;
2189
+ }
2190
+ }
2191
+ if (covered(top) || added.has(perimeterKey(top))) continue;
2192
+ added.set(perimeterKey(top), top);
2193
+ }
2194
+ // M3: only a complete read rules a dependency out (an unread manifest could still declare it: none is frozen as removed). P3
2195
+ // QA-2 F-2: nor one whose unadmitted targets the bound cut (one of them could lie in a dispatch-time dependency).
2196
+ const atReturn = {
2197
+ ...(dependencies.incomplete || dependencies.unadmittedMore > 0 ? {} : { targets }),
2198
+ ...(unadmitted.size > 0 ? { unadmitted: [...unadmitted.values()] } : {}),
2199
+ };
2200
+ if (added.size === 0) return { links: [], unobserved: false, ...atReturn };
2201
+ // P3 QA-1 m2: more new targets than P may take: none is snapshotted (not deferred, X7).
2202
+ if (added.size > room) return { links: [], unobserved: true, ...atReturn };
2203
+ const lowPriority = configuredLowPriority();
2204
+ const observed = await Promise.all([...added.values()].map(async top => ({ top, now: await hardenedSnapshotFor(top, deadline, lowPriority) })));
2205
+ const links: FrozenPerimeter["links"][number][] = [];
2206
+ let unobserved = false;
2207
+ for (const { top, now } of observed) {
2208
+ // As a seed at return: no snapshot in time, or a top level the admission refuses, is not observed (X7).
2209
+ if (now === undefined || now.root === undefined || !context.admitTop(now.root)) {
2210
+ unobserved = true;
2211
+ continue;
2212
+ }
2213
+ links.push({
2214
+ at: top,
2215
+ root: now.root,
2216
+ name: basename(now.root),
2217
+ head: now.head,
2218
+ fingerprint: now.fingerprint,
2219
+ admit: context.admitTop,
2220
+ });
2221
+ }
2222
+ return { links, unobserved, ...atReturn };
2223
+ };
2224
+
2225
+ /**
2226
+ * Cross-repo P2e.5 (X4, X5): the perimeter frozen when a deferred producer returns. The observation is perimeterAtGate's in
2227
+ * return mode (no consumer discovery inside the deferral bound: router_verify discovers over the frozen working set). Next to
2228
+ * it: the working-set roots (origin "working-set", never W), and the link targets (origin "link" or `linked`, never fixed)
2229
+ * with the top level, head and fingerprint of their return-time snapshot and their admission. `linkUnobserved`: a link root
2230
+ * whose status is "unobserved" (no snapshot at either end, or a top it does not admit): X7, not deferred. Undefined when the
2231
+ * dispatch has no perimeter or none of it remains beyond W.
2232
+ * Cross-repo P3c.6 (D26): W's dependency targets are read again at return through the union (`dependencyTargets`) with the
2233
+ * frozen admission; an admitted target the producer added during the dispatch (a `node_modules` link, a declared edge) and
2234
+ * no seed covers is snapshotted (hardened) within the remaining deferral bound and frozen with the links, so router_verify
2235
+ * (S11) compares it with its return-time state; one not observed in time sets `linkUnobserved` (verified at once, X7). It is
2236
+ * never a perimeter seed: P stays fixed at dispatch for writer attribution (I4, I13). An unadmitted new target is not
2237
+ * snapshotted.
2238
+ */
2239
+ const perimeterAtReturn = async (
2240
+ planned: { name?: string; snapshots: PerimeterSnapshots; admission?: DispatchPerimeter["admission"] } | undefined,
2241
+ snapshot: TreeSnapshot | undefined,
2242
+ base: string,
2243
+ // P3c.6 (D26): the deferral bound, what remains of it bounds the snapshots of the dependencies added during the dispatch.
2244
+ // Absent: none is read (as before P3c.6).
2245
+ deadline?: Deadline,
2246
+ ): Promise<{
2247
+ observation: PerimeterObservation;
2248
+ workingSet: FrozenPerimeter["workingSet"];
2249
+ links: FrozenPerimeter["links"];
2250
+ linkUnobserved: boolean;
2251
+ /** P3c.4 (SD-P3c-9): the dispatch's admission (planPerimeter), frozen with the perimeter. Absent: none recorded. */
2252
+ admission?: DispatchPerimeter["admission"];
2253
+ /** P3 QA-1 M4: the unadmitted dependency targets the producer added during the dispatch (covering only). Absent: none. */
2254
+ unadmitted?: readonly string[];
2255
+ } | undefined> => {
2256
+ const observation = await perimeterAtGate(planned, snapshot, base, undefined, { discover: false });
2257
+ if (planned === undefined || observation === undefined) return undefined;
2258
+ const wKey = perimeterKey(observation.w.root);
2259
+ const workingSet = new Map<string, FrozenPerimeter["workingSet"][number]>();
2260
+ const links = new Map<string, FrozenPerimeter["links"][number]>();
2261
+ let linkUnobserved = false;
2262
+ let unadmitted: readonly string[] = [];
2263
+ for (const { entry, before, now } of planned.snapshots) {
2264
+ const seed = entry.seed;
2265
+ const fixed = seed.fixed;
2266
+ // As perimeterAtGate names the root: its known top level when admitted, else where it was planned (a fixed root: there).
2267
+ const known = fixed === undefined ? now?.root ?? before?.root : undefined;
2268
+ const refused = known !== undefined && seed.admit !== undefined && !seed.admit(known);
2269
+ const root = known !== undefined && !refused ? known : seed.at;
2270
+ const key = perimeterKey(root);
2271
+ // W's own repository is W's snapshot (a fixed placeholder at W's path is kept, as perimeterAtGate keeps it).
2272
+ if (fixed === undefined && key === wKey) continue;
2273
+ // P2e QA-1 #1: a working-set root past the cap (fixed) is still a consumer candidate, as perimeterAtGate scans it.
2274
+ if (seed.origin === "working-set" && !workingSet.has(key)) {
2275
+ workingSet.set(key, { root, ...(seed.name !== undefined ? { name: seed.name } : {}) });
2276
+ }
2277
+ // P3c.4 (SD-P3c-2, S11): a dependency of W, a package link target or a declared edge's repository (origin "link" or
2278
+ // "edge", or a working-set root `linked` or `edged`), is frozen and observed again at router_verify, where W's
2279
+ // dependency targets are read through the same union (`dependencyTargets`, F1).
2280
+ const isDependency = seed.origin === "link" || seed.linked === true || seed.origin === "edge" || seed.edged === true;
2281
+ if (fixed !== undefined) {
2282
+ // P2e QA-1 #1: a dependency past the cap was never observed: not deferred (X7). An unadmitted one is never observed.
2283
+ if (fixed === "unobserved" && isDependency) linkUnobserved = true;
2284
+ continue;
2285
+ }
2286
+ if (!isDependency) continue;
2287
+ if (refused || before === undefined || now === undefined || now.root === undefined) {
2288
+ linkUnobserved = true;
2289
+ continue;
2290
+ }
2291
+ if (!links.has(key)) {
2292
+ links.set(key, {
2293
+ at: seed.at,
2294
+ root,
2295
+ name: seed.name ?? basename(root),
2296
+ head: now.head,
2297
+ fingerprint: now.fingerprint,
2298
+ ...(seed.admit !== undefined ? { admit: seed.admit } : {}),
2299
+ });
2300
+ }
2301
+ }
2302
+ // P3c.6 (D26): a dependency target the producer added during the dispatch, frozen with the links so that router_verify (S11)
2303
+ // compares it with its state at return; never a seed (I13: P stays the dispatch's for writer attribution, I4). Not read when
2304
+ // the dispatch is verified at once anyway, without a frozen admission (an entry planned before P3c.4), or without a bound.
2305
+ // The same read freezes which dispatch-time dependencies W no longer declares (M3) and the unadmitted new targets (M4).
2306
+ if (!linkUnobserved && planned.admission !== undefined && deadline !== undefined) {
2307
+ // What covers a target at router_verify: the roots frozen here (the perimeter's, fixed ones where they were planned).
2308
+ const covering = [
2309
+ ...observation.roots.map(root => root.root),
2310
+ ...planned.snapshots.map(({ entry }) => entry.seed.at),
2311
+ ...[...links.values()].map(link => link.root),
2312
+ ];
2313
+ // P3 QA-1 m2: P holds at most PERIMETER_MAX snapshotted roots, W and the dispatch's observed roots included.
2314
+ const observedSeeds = planned.snapshots.filter(({ entry }) => entry.seed.fixed === undefined).length;
2315
+ const room = Math.max(0, PERIMETER_MAX - 1 - observedSeeds);
2316
+ const added = await dependenciesAddedAtReturn(base, planned.admission, covering, [base, observation.w.root], deadline, room);
2317
+ if (added.unobserved) linkUnobserved = true;
2318
+ // P3 QA-1 M3: a dispatch-time dependency W no longer declares at return (the producer removed or retargeted it) is not an
2319
+ // input of the change: frozen as removed, router_verify skips it (no "no longer links", no re-observation).
2320
+ const atReturn = added.targets;
2321
+ if (atReturn !== undefined) {
2322
+ for (const [key, link] of links) {
2323
+ if (!atReturn.some(target => depthBelow(target, link.root) >= 0)) links.set(key, { ...link, removedAtReturn: true });
2324
+ }
2325
+ }
2326
+ for (const link of added.links) {
2327
+ const key = perimeterKey(link.root);
2328
+ if (key !== wKey && !links.has(key)) links.set(key, link);
2329
+ }
2330
+ if (added.unadmitted !== undefined) unadmitted = added.unadmitted;
2331
+ }
2332
+ return {
2333
+ observation,
2334
+ workingSet: [...workingSet.values()],
2335
+ links: [...links.values()],
2336
+ linkUnobserved,
2337
+ ...(planned.admission !== undefined ? { admission: planned.admission } : {}),
2338
+ ...(unadmitted.length > 0 ? { unadmitted } : {}),
2339
+ };
2340
+ };
2341
+
1464
2342
  /**
1465
2343
  * The producer's change since the dispatch: the gate-time snapshot (bounded by `deadline`), the
1466
2344
  * commits since the dispatch head, and the store's delta. Shared by prepareVerification and the
@@ -1472,8 +2350,15 @@ export function createVerificationWiring(deps: {
1472
2350
  childID: string,
1473
2351
  cwd: string | undefined,
1474
2352
  deadline: Deadline | undefined,
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,
1475
2356
  ): Promise<Omit<PreparedVerification, "reference">> => {
1476
2357
  const base = resolve(directory, cwd || ".");
2358
+ // QA-1 F9: the perimeter's gate snapshots start now, concurrently with W's own (never rejects).
2359
+ const perimeterSnapshots = observePerimeter
2360
+ ? perimeterSnapshotsAtGate(store, id, deadline).catch(() => undefined)
2361
+ : Promise.resolve(undefined);
1477
2362
  const controller = new AbortController();
1478
2363
  const onAbort = (): void => controller.abort();
1479
2364
  deadline?.signal.addEventListener("abort", onAbort, { once: true });
@@ -1509,13 +2394,78 @@ export function createVerificationWiring(deps: {
1509
2394
  deadline?.signal.removeEventListener("abort", onAbort);
1510
2395
  controller.abort();
1511
2396
  }
1512
- const committed = await committedSinceDispatch(store.baselineSnapshot(id), snapshot, deadline);
2397
+ const before = store.baselineSnapshot(id);
2398
+ // I7 (P0.2, S9): did the tree switch branch since the dispatch? Decided from the cheap head state, before the commit diff:
2399
+ // a diff across branches would be the other branch's net change, verified as the producer's, and must never reach the store.
2400
+ let headSwitch: string | undefined;
2401
+ let headRead = false;
2402
+ let gateHead: HeadState | undefined;
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";
2407
+ if (baselineHead !== undefined) {
2408
+ const bound = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
2409
+ if (bound > 0 && deadline?.signal.aborted !== true) {
2410
+ const signalOpt = deadline ? { signal: deadline.signal } : {};
2411
+ const startRead = await withTimeout(baselineHead, bound, "dispatch head").catch(() => undefined);
2412
+ // QA2 F3: "none" = no repository or an unborn HEAD at dispatch (e.g. the producer ran git init or made the first
2413
+ // commit): there was no branch to switch from. Unknown (a failed or late read): the dispatch snapshot's head and branch
2414
+ // stand in when it recorded them (no root or reflog then: the name rule decides).
2415
+ const startHead: HeadState | "none" | undefined = startRead === "none" || startRead !== undefined
2416
+ ? startRead
2417
+ : before !== undefined && before.branch !== undefined
2418
+ ? { root: before.root ?? base, head: before.head, branch: before.branch }
2419
+ : undefined;
2420
+ const nowHead = await withTimeout(
2421
+ readHeadState(base, { ...signalOpt, timeoutMs: bound, lowPriority: configuredLowPriority() }),
2422
+ bound,
2423
+ "gate head",
2424
+ ).catch(() => undefined);
2425
+ if (nowHead !== undefined) {
2426
+ headRead = true;
2427
+ gateHead = nowHead;
2428
+ if (startHead === "none") {
2429
+ // No branch existed at dispatch: nothing to compare.
2430
+ } else if (startHead === undefined) {
2431
+ // The dispatch-time head is unknown (an unreadable or late read, and no snapshot head): fail closed.
2432
+ headSwitch = `cannot confirm the branch of ${nowHead.root}: the working tree could not be read when the dispatch started, so the checks could verify another branch. Re-dispatch, or send a fresh [acceptance] block.`;
2433
+ } else {
2434
+ let window: ReflogEntry[] | undefined;
2435
+ if (startHead.reflog !== undefined && nowHead.reflog !== undefined && nowHead.reflog >= startHead.reflog) {
2436
+ window = await readReflogWindow(nowHead.root, nowHead.reflog - startHead.reflog, {
2437
+ ...signalOpt, timeoutMs: bound, lowPriority: configuredLowPriority(),
2438
+ });
2439
+ }
2440
+ // The reflog grew but its entries cannot be read: a checkout or reset cannot be ruled out (fail closed).
2441
+ const unreadWindow = window === undefined && startHead.reflog !== undefined && nowHead.reflog !== undefined
2442
+ && nowHead.reflog > startHead.reflog;
2443
+ const move = unreadWindow
2444
+ ? { kind: "rewritten" as const, detail: "the reflog entries could not be read" }
2445
+ : treeMove(startHead, nowHead, window);
2446
+ if (move !== undefined) headSwitch = treeMoveReason(nowHead.root, startHead, nowHead, move, switchWindow);
2447
+ }
2448
+ }
2449
+ }
2450
+ }
2451
+ // Head state unavailable at the gate (or no head reader for this dispatch): the snapshot comparison, when both exist.
2452
+ const snapshotSwitch = !headRead && before !== undefined && snapshot !== undefined && branchSwitched(before, snapshot)
2453
+ ? branchSwitchReason(snapshot.root ?? base, before, snapshot, "during the dispatch")
2454
+ : undefined;
2455
+ const branchSwitch = headSwitch ?? snapshotSwitch;
2456
+ // B8: on a switch the commit diff is not run; "unavailable" keeps the whole change set unavailable (the gate refuses anyway).
2457
+ const committed = branchSwitch !== undefined ? "unavailable" as const : await committedSinceDispatch(before, snapshot, deadline);
1513
2458
  const contaminatedBy = store.snapshotContaminatedBy(id);
2459
+ const perimeter = await perimeterAtGate(await perimeterSnapshots, snapshot, base, deadline);
1514
2460
  return {
1515
2461
  ...store.delta(id, childID, snapshot, base, committed),
1516
2462
  snapshot,
1517
2463
  concurrentDispatches: store.concurrentDispatches(id, snapshot?.root),
1518
2464
  ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
2465
+ ...(childID !== "" ? { producerSessionID: childID } : {}),
2466
+ ...(branchSwitch !== undefined ? { branchSwitch } : {}),
2467
+ ...(gateHead !== undefined ? { head: gateHead } : {}),
2468
+ ...(perimeter !== undefined ? { perimeter } : {}),
1519
2469
  };
1520
2470
  };
1521
2471
 
@@ -1580,39 +2530,100 @@ export function createVerificationWiring(deps: {
1580
2530
  * for each testsPass check, with the command and cwd the gate would use. The first S6 result wins;
1581
2531
  * a command outside the allowlist is S6 too (the gate reports it unverifiable). Bounded by the
1582
2532
  * deferred-finish deadline; an unfinished plan counts as impossible (raises the risk, never lowers it).
2533
+ *
2534
+ * Cross-repo P2e: with `placements` (index-aligned with `dod.checks`), each testsPass check is planned at its placement's
2535
+ * cwd; a placement with `scope === "full"` is not planned (it runs in full); a foreign placement is S6
2536
+ * (attribution-unavailable), unless it is a cross-link plan (Y6, below). A check without a placement, or no placements at
2537
+ * all: the base dir, as before.
2538
+ *
2539
+ * P2e QA-1 #6: with `fullScope` (OD-P2e-2) no testsPass check is planned as affected (each runs in full); when every testsPass
2540
+ * check runs in full, the result is the neutral FULL_SCOPE plan, never the unfinished S6 one.
2541
+ *
2542
+ * Cross-repo P3a (Y6): a foreign testsPass with an explicit scope=affected is planned as the gate runs it (deterministic.ts):
2543
+ * at its placement's cwd, with `crossLinkRoot` = W's root (`changeRoot`, else the base dir, as the gate falls back) and the
2544
+ * consumer link spellings of it (perimeter.ts crossLinkAliases), the changed paths made absolute against that root (F7).
2545
+ * A scopable cross-link plan then raises no S6; a runner the link does not reach (jest, pytest, another vitest major) still
2546
+ * does. Any other foreign placement stays S6 (attribution-unavailable).
1583
2547
  */
1584
2548
  const staticScoping = async (
1585
2549
  dod: DoD,
1586
2550
  cwd: string | undefined,
1587
2551
  changedFiles: readonly ChangedPath[],
1588
2552
  deadline: Deadline,
1589
- ): Promise<StaticScoping> => {
2553
+ placements?: readonly (CheckPlacement | undefined)[],
2554
+ fullScope?: boolean,
2555
+ changeRoot?: string,
2556
+ ): Promise<StaticScoping | FullScopePlan> => {
1590
2557
  const unfinished: StaticScoping = { unverifiable: true, code: "search-failed", reason: STATIC_SCOPING_UNFINISHED_REASON };
1591
2558
  const budget = resolveVerifyBudget(getConfig());
1592
- const at = resolveBaseDir(cwd, directory);
2559
+ const base = resolveBaseDir(cwd, directory);
2560
+ // Y6: W's root as the gate takes it (gate.ts: artefact.changeRoot ?? effectiveBaseDir), and (F7) the changed paths absolute
2561
+ // against it, computed once and only for a cross-link plan.
2562
+ const linkRoot = changeRoot ?? base;
2563
+ let absoluteChanged: readonly ChangedPath[] | undefined;
2564
+ const linkChangedFiles = (): readonly ChangedPath[] => (absoluteChanged ??= changedFiles.map(file => ({
2565
+ ...file,
2566
+ path: isAbsolute(file.path) ? file.path : resolve(linkRoot, file.path),
2567
+ ...(file.previousPath !== undefined
2568
+ ? { previousPath: isAbsolute(file.previousPath) ? file.previousPath : resolve(linkRoot, file.previousPath) }
2569
+ : {}),
2570
+ })));
1593
2571
  const plans: StaticScoping[] = [];
1594
- for (const check of dod.checks) {
2572
+ let ranFull = false;
2573
+ for (const [index, check] of dod.checks.entries()) {
1595
2574
  if (check.kind !== "testsPass") continue;
1596
2575
  const command = resolveRepoCommand(check, "testsPass", undefined);
1597
2576
  if (!isCommandAllowed(command, DEFAULT_ALLOWLIST)) {
1598
2577
  plans.push({ unverifiable: true, code: "unsupported-command", reason: `command not allowlisted: ${scrubText(command)}` });
1599
2578
  continue;
1600
2579
  }
2580
+ const placement = placements?.[index];
2581
+ if (fullScope === true || placement?.scope === "full") {
2582
+ ranFull = true;
2583
+ continue;
2584
+ }
2585
+ // Y6: only an explicit scope=affected crosses the link (deterministic.ts runDeterministic); any other foreign check is S6.
2586
+ const crossLink = placement?.foreign === true && placement.scope === "affected";
2587
+ if (placement?.foreign === true && !crossLink) {
2588
+ plans.push({
2589
+ unverifiable: true,
2590
+ code: "attribution-unavailable",
2591
+ reason: "the check runs in another repository, whose changes are not attributed to this dispatch",
2592
+ });
2593
+ continue;
2594
+ }
2595
+ const at = placement?.cwd ?? base;
1601
2596
  const ms = deadline.remaining();
1602
2597
  if (ms <= 0) {
1603
2598
  plans.push(unfinished);
1604
2599
  continue;
1605
2600
  }
1606
2601
  try {
1607
- plans.push(await withTimeout(
1608
- planStaticScoping({ command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam }),
1609
- ms,
1610
- "static scoping",
1611
- ));
2602
+ const input: StaticScopingInput = crossLink
2603
+ ? {
2604
+ command,
2605
+ cwd: at,
2606
+ changedFiles: linkChangedFiles(),
2607
+ budget: { maxWorkers: budget.maxWorkers },
2608
+ fs: fsSeam,
2609
+ crossLinkRoot: linkRoot,
2610
+ // Fail-soft, as the gate's alias provider (deterministic.ts crossLinkTarget): an error gives no aliases.
2611
+ ...(() => {
2612
+ try {
2613
+ return { crossLinkAliases: crossLinkAliases(at, linkRoot) };
2614
+ } catch {
2615
+ return {};
2616
+ }
2617
+ })(),
2618
+ }
2619
+ : { command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam };
2620
+ plans.push(await withTimeout(planStaticScoping(input), ms, "static scoping"));
1612
2621
  } catch {
1613
2622
  plans.push(unfinished);
1614
2623
  }
1615
2624
  }
2625
+ // P2e QA-1 #6: every testsPass check runs in full: the neutral plan (never the unfinished S6 one).
2626
+ if (plans.length === 0 && ranFull) return FULL_SCOPE_PLAN;
1616
2627
  return plans.find(p => "unverifiable" in p) ?? plans[0] ?? unfinished;
1617
2628
  };
1618
2629
 
@@ -1630,7 +2641,55 @@ export function createVerificationWiring(deps: {
1630
2641
  let risk: RiskAssessment = unattributedRisk();
1631
2642
  let deferred = false;
1632
2643
  try {
1633
- const change = await observeChange(store, input.dispatchID, input.producerSessionID, input.cwd, deadline);
2644
+ // Cross-repo P2e.5 (X4): a dispatch with a perimeter has it observed in return mode, its snapshots started now so they run
2645
+ // concurrently with W's own (never rejects; bounded by the same DEFERRED_FINISH_MS deadline). Without one: nothing extra.
2646
+ const changeCwd = input.captureRoot ?? input.cwd;
2647
+ const perimeterSnapshots = store.perimeterOf(input.dispatchID) !== undefined
2648
+ ? perimeterSnapshotsAtGate(store, input.dispatchID, deadline).catch(() => undefined)
2649
+ : undefined;
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
+ };
2663
+ // I7 (P0.2): a branch switch during the dispatch is never deferred: a handle could verify the other branch later. The
2664
+ // caller's required gate refuses it now (its own observeChange sees the switch). Before the no-change shortcut below.
2665
+ if (change.branchSwitch !== undefined) return { deferred: false, reason: "branch-switched", detail: change.branchSwitch };
2666
+ // Cross-repo P2e.5 (X5, X7): the perimeter as it was at return is frozen for router_verify, unless it cannot be: I4 already
2667
+ // holds (a root changed while an unattributable writer ran), or a link target was not observed. The caller's required
2668
+ // gate then verifies the dispatch now. Before the no-change shortcut below.
2669
+ let frozen: Awaited<ReturnType<typeof perimeterAtReturn>>;
2670
+ if (perimeterSnapshots !== undefined) {
2671
+ const base = resolve(directory, changeCwd || ".");
2672
+ // P3c.6 (D26): a dependency added during the dispatch is snapshotted within what remains of this deadline.
2673
+ frozen = await perimeterAtReturn(await perimeterSnapshots, change.snapshot, base, deadline);
2674
+ const writers = change.unattributedWriters ?? [];
2675
+ if (frozen !== undefined && perimeterChangeReasons({ perimeter: frozen.observation, unattributedWriters: [...writers] }, base).length > 0) {
2676
+ return {
2677
+ deferred: false,
2678
+ reason: "cross-repo",
2679
+ detail: "a repository of the perimeter changed during the dispatch while an unattributable writer ran; verified synchronously",
2680
+ };
2681
+ }
2682
+ if (frozen?.linkUnobserved === true) {
2683
+ return { deferred: false, reason: "cross-repo", detail: "a linked repository could not be observed within the deferral bound; verified synchronously" };
2684
+ }
2685
+ }
2686
+ // P2e.5 (X3): the frozen pins settle only once the registration succeeded (below); never rejects.
2687
+ let settlePins: (pins: readonly LinkPin[]) => void = () => undefined;
2688
+ const frozenPins = frozen !== undefined
2689
+ ? new Promise<readonly LinkPin[]>(settle => {
2690
+ settlePins = settle;
2691
+ })
2692
+ : undefined;
1634
2693
  // QA-2.4-10: an attributed empty change set is passed by the required gate with no process
1635
2694
  // (section 1.5-6): nothing to defer. The caller runs that gate, with the same outcome.
1636
2695
  // QA-G-1: only for a testsPass-only DoD. Any other check (build, lint, run, fileExists,
@@ -1638,7 +2697,7 @@ export function createVerificationWiring(deps: {
1638
2697
  // DoD stays deferred as a whole, with the attributed empty change set (risk low).
1639
2698
  if (
1640
2699
  change.changeBaseline === "available" && change.changedFiles.length === 0 && !deadline.signal.aborted &&
1641
- noChangeGateSpawnsNothing(input.dod)
2700
+ noChangeGateSpawnsNothing(input.dod, { placements: input.placements, fullScope: input.fullScope })
1642
2701
  ) {
1643
2702
  return { deferred: false, reason: "no-change", detail: "the producer changed no file" };
1644
2703
  }
@@ -1652,7 +2711,10 @@ export function createVerificationWiring(deps: {
1652
2711
  ...(f.previousPath !== undefined ? { previousPath: f.previousPath } : {}),
1653
2712
  }));
1654
2713
  changedFiles = paths;
1655
- const scopingPlan = await staticScoping(input.dod, input.cwd, paths, deadline);
2714
+ // Y6: W's root (the snapshot's git top) is the cross-link root of a foreign scope=affected testsPass.
2715
+ const scopingPlan = await staticScoping(
2716
+ input.dod, input.cwd, paths, deadline, input.placements, input.fullScope, change.snapshot?.root,
2717
+ );
1656
2718
  risk = assessRisk({ changedFiles: paths, reference: referenceCaptured, producerTier, scopingPlan, root: change.snapshot?.root });
1657
2719
  // QA-2.4-8: the drift baseline is taken BEFORE the result is released (fs reads only, under
1658
2720
  // the same DEFERRED_FINISH_MS bound). An edit that lands right after the return is then
@@ -1661,6 +2723,8 @@ export function createVerificationWiring(deps: {
1661
2723
  const taken = await untilAborted(digestFiles(paths.map(p => p.path)), deadline.signal, () => undefined);
1662
2724
  if (taken !== undefined) digests = Promise.resolve(taken);
1663
2725
  }
2726
+ observeV2(deps.observations, () => ({ family: "completion-effect", effect: "deferred-register", source: "pending-register",
2727
+ ...completionIdentity(input.orchestratorSessionID, input.dispatchID, input.producerSessionID) }));
1664
2728
  const reg = pending.register({
1665
2729
  orchestratorSessionID: input.orchestratorSessionID,
1666
2730
  dispatchID: input.dispatchID,
@@ -1669,6 +2733,20 @@ export function createVerificationWiring(deps: {
1669
2733
  description: input.description,
1670
2734
  cwd: resolveBaseDir(input.cwd, directory),
1671
2735
  root: change.snapshot?.root,
2736
+ // I7 (P0.2, S12): the checkout the producer returned on; router_verify refuses a tree on another branch by then.
2737
+ // B4/B12: from the cheap head state the gate read (root and reflog count too); the snapshot's only without one.
2738
+ ...(change.head !== undefined
2739
+ ? {
2740
+ returnedTree: {
2741
+ root: change.head.root,
2742
+ head: change.head.head,
2743
+ branch: change.head.branch,
2744
+ ...(change.head.reflog !== undefined ? { reflog: change.head.reflog } : {}),
2745
+ },
2746
+ }
2747
+ : change.snapshot !== undefined
2748
+ ? { returnedTree: { head: change.snapshot.head, branch: change.snapshot.branch } }
2749
+ : {}),
1672
2750
  dispatchedAt: input.dispatchedAt,
1673
2751
  dod: input.dod,
1674
2752
  reference,
@@ -1679,12 +2757,52 @@ export function createVerificationWiring(deps: {
1679
2757
  // adds the caveats to its verdict.
1680
2758
  ...(change.concurrentDispatches !== undefined && change.concurrentDispatches > 0 ? { concurrentDispatches: change.concurrentDispatches } : {}),
1681
2759
  ...(change.contaminatedBy !== undefined ? { contaminatedBy: change.contaminatedBy } : {}),
2760
+ // I5 (P0.3): router_verify's gate adds the caveat to a pass on an empty change set.
2761
+ ...(change.unattributedWriters !== undefined && change.unattributedWriters.length > 0 ? { unattributedWriters: change.unattributedWriters } : {}),
2762
+ // Cross-repo P2e.5: the perimeter frozen at return (router_verify gates with it) and the dispatch's placements.
2763
+ ...(frozen !== undefined && frozenPins !== undefined
2764
+ ? {
2765
+ perimeter: {
2766
+ observation: frozen.observation,
2767
+ // The W directory the dispatch's planPerimeter read <W>/node_modules from (the cwd observeChange ran at, as `base` below; beginDispatch planned with the same captureRootOf).
2768
+ linkBase: resolve(directory, changeCwd || "."),
2769
+ workingSet: frozen.workingSet,
2770
+ links: frozen.links,
2771
+ pins: frozenPins,
2772
+ // P3c.4 (SD-P3c-9): the admission the dispatch's planPerimeter read W's links and edges with; router_verify reads
2773
+ // W's dependency targets again through it (the registry freezes a copy).
2774
+ ...(frozen.admission !== undefined ? { admission: frozen.admission } : {}),
2775
+ ...(frozen.unadmitted !== undefined ? { unadmittedAtReturn: frozen.unadmitted } : {}),
2776
+ },
2777
+ }
2778
+ : {}),
2779
+ ...(input.placements !== undefined ? { placements: input.placements } : {}),
1682
2780
  });
1683
2781
  if (!reg.ok) {
2782
+ // P2e.5 (X3): nothing reads it; the dispatch's own pins are left untouched for the required gate.
2783
+ settlePins([]);
1684
2784
  // QA-2.4-4: never a delegation without a verdict path: the caller runs the required gate.
1685
2785
  logger.warn("[verify] deferred delegation not registered; verifying synchronously", { code: reg.code, detail: reg.detail });
1686
2786
  return { deferred: false, reason: "unregistered", detail: `${reg.code}: ${reg.detail}` };
1687
2787
  }
2788
+ if (frozen !== undefined) {
2789
+ // P2e.5 (X3): the dispatch's link pins are taken now, before store.clear (below), then freed; the entry keeps the SAME
2790
+ // array (pinNow admission is keyed by its identity). Never rejects: a failure is [].
2791
+ const dispatchID = input.dispatchID;
2792
+ void linkPinsAtGate(store, dispatchID, undefined).then(
2793
+ pins => {
2794
+ freeLinkPins(dispatchID, pins);
2795
+ settlePins(pins);
2796
+ },
2797
+ () => {
2798
+ freeLinkPins(dispatchID, []);
2799
+ settlePins([]);
2800
+ },
2801
+ );
2802
+ } else if (perimeterSnapshots !== undefined) {
2803
+ // A perimeter with nothing to freeze beyond W: no gate takes this dispatch's pins any more.
2804
+ freeLinkPins(input.dispatchID, []);
2805
+ }
1688
2806
  deferred = true;
1689
2807
  // #84 P2.1 (handoff 24, R7): the budget captured at return travels with the handle to `router_verify`.
1690
2808
  if (input.budget !== undefined) {
@@ -1701,6 +2819,8 @@ export function createVerificationWiring(deps: {
1701
2819
  // An unattributed change set is not queued (nothing could run; it stays listed instead).
1702
2820
  if (background !== undefined && changedFiles !== "unavailable") {
1703
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) }));
1704
2824
  background.enqueue({ sessionID: input.orchestratorSessionID, handle: reg.handle, files: changedFiles.map(p => p.path) });
1705
2825
  } catch (err) {
1706
2826
  // The handle is registered: the delegation stays unverified and listed, as without background.
@@ -1787,6 +2907,66 @@ export function createVerificationWiring(deps: {
1787
2907
  }
1788
2908
  };
1789
2909
 
2910
+ /**
2911
+ * Cross-repo P2e.4a (S11): a frozen link target observed again at router_verify, hardened as the perimeter snapshots it
2912
+ * (perimeterSnapshotsAtGate), bounded by the claim deadline. Undefined when it cannot be taken in time. Never throws.
2913
+ */
2914
+ const hardenedSnapshotFor = async (at: string, deadline: Deadline, lowPriority: boolean): Promise<TreeSnapshot | undefined> => {
2915
+ const controller = new AbortController();
2916
+ const onAbort = (): void => controller.abort();
2917
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
2918
+ try {
2919
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2920
+ if (bound <= 0 || controller.signal.aborted) return undefined;
2921
+ return await withTimeout(snapshotTree(at, controller.signal, { lowPriority, hardened: true }), bound, "router_verify link fingerprint");
2922
+ } catch {
2923
+ return undefined;
2924
+ } finally {
2925
+ deadline.signal.removeEventListener("abort", onAbort);
2926
+ controller.abort();
2927
+ }
2928
+ };
2929
+
2930
+ /**
2931
+ * Cross-repo P2e.4b: the first frozen check placement whose cwd no longer resolves to the same repository since the producer
2932
+ * returned: its real path is not its (canonical) cwd any more (a junction swapped under it, or gone), or its git top level is
2933
+ * not the frozen `top`. The reason names it ("nothing ran"); undefined when every placement still resolves as it did.
2934
+ */
2935
+ const placementDriftOf = async (entry: PendingEntry): Promise<{ readonly kind: "drift" | "unchecked"; readonly reason: string } | undefined> => {
2936
+ const placements = entry.placements;
2937
+ if (placements === undefined) return undefined;
2938
+ // Per placement: "same", "drift", or the code of a transient error (P2e QA-1 #5b: EPERM, EBUSY, EACCES…: not a drift).
2939
+ const states = await Promise.all(placements.map(async (placement): Promise<string> => {
2940
+ if (placement === undefined) return "same";
2941
+ let real: string;
2942
+ try {
2943
+ real = await realpath(placement.cwd);
2944
+ } catch (err) {
2945
+ const code = typeof err === "object" && err !== null && "code" in err ? String((err as { code: unknown }).code) : "unknown";
2946
+ // The directory is gone (or a file now stands in its path): it no longer resolves.
2947
+ return code === "ENOENT" || code === "ENOTDIR" ? "drift" : code;
2948
+ }
2949
+ if (perimeterKey(real) !== perimeterKey(placement.cwd)) return "drift";
2950
+ const top = gitTopOf(placement.cwd);
2951
+ const moved = top === undefined || placement.top === undefined
2952
+ ? top !== placement.top
2953
+ : perimeterKey(top) !== perimeterKey(placement.top);
2954
+ return moved ? "drift" : "same";
2955
+ }));
2956
+ const label = (index: number): string =>
2957
+ `check ${index + 1} (${entry.dod?.checks?.[index]?.kind ?? "check"}) cwd=${placements[index]?.cwd ?? ""}`;
2958
+ const drifted = states.indexOf("drift");
2959
+ if (drifted >= 0) {
2960
+ return { kind: "drift", reason: `${label(drifted)} no longer resolves to the same repository since the producer returned; nothing ran` };
2961
+ }
2962
+ const unchecked = states.findIndex(state => state !== "same");
2963
+ if (unchecked < 0) return undefined;
2964
+ return {
2965
+ kind: "unchecked",
2966
+ reason: `${label(unchecked)} could not be checked since the producer returned (${states[unchecked]}); nothing ran`,
2967
+ };
2968
+ };
2969
+
1790
2970
  /**
1791
2971
  * 2.4.3a, section 1.5-18: the producer's files now against their digests right after it returned.
1792
2972
  * "unchecked" whenever either side is missing (no change set, no stored digests, a digest that
@@ -1807,6 +2987,21 @@ export function createVerificationWiring(deps: {
1807
2987
  readonly drift: DriftCheck;
1808
2988
  /** R11 root: the registered one, else the current tree's. */
1809
2989
  readonly root: string | undefined;
2990
+ /**
2991
+ * Cross-repo P2e.4a (S11): the frozen link targets that changed, or could not be observed again, since the producer
2992
+ * returned. Absent: no frozen perimeter, or every link is as it was at return.
2993
+ */
2994
+ readonly linkDrift?: readonly { readonly name: string; readonly root: string; readonly why: "changed" | "unobserved" }[];
2995
+ /**
2996
+ * Cross-repo P2e.4b: the first frozen check placement whose cwd no longer resolves to the same repository (the gate then
2997
+ * runs nothing). Absent: no placements, or all still resolve as at return.
2998
+ */
2999
+ readonly placementDrift?: string;
3000
+ /**
3001
+ * P2e QA-1 #5b: the first frozen check placement whose cwd could not be checked now (a transient filesystem error, not a
3002
+ * missing directory): nothing runs, and the handle stays open (retryable). Absent: every placement could be checked.
3003
+ */
3004
+ readonly placementUnchecked?: string;
1810
3005
  }
1811
3006
 
1812
3007
  /** One claimed entry after its gate: a final result, or the raw gate result still to be judged. */
@@ -1814,26 +3009,271 @@ export function createVerificationWiring(deps: {
1814
3009
  | { readonly kind: "final"; readonly result: VerificationResult }
1815
3010
  | { readonly kind: "gate"; readonly res: GateResult; readonly retryable: boolean; readonly strict: boolean };
1816
3011
 
3012
+ /**
3013
+ * Cross-repo P3c.4 (SD-P3c-8): W's dependency targets (`dependencyTargets`) read at one router_verify call, keyed by W's
3014
+ * comparison key and the frozen admission it was read with: the call's entries of one W read them once.
3015
+ */
3016
+ type DependencyMemo = Map<string, DependencyTargets | undefined>;
3017
+
1817
3018
  /** 2.4.3a P0 from the pending entry: stored change set and reference, current tree, drift. */
1818
3019
  const prepareClaim = async (
1819
3020
  entry: PendingEntry,
1820
3021
  deadline: Deadline,
1821
3022
  snapshots: Map<string, Promise<TreeSnapshot | undefined>>,
1822
3023
  lowPriority: boolean,
3024
+ dependencies: DependencyMemo = new Map(),
1823
3025
  ): Promise<ClaimPreparation> => {
1824
3026
  let snapshot = snapshots.get(entry.cwd);
1825
3027
  if (snapshot === undefined) {
1826
3028
  snapshot = snapshotFor(entry.cwd, deadline, lowPriority);
1827
3029
  snapshots.set(entry.cwd, snapshot);
1828
3030
  }
1829
- const [reference, drift, tree] = await Promise.all([
3031
+ const atReturn = entry.returnedTree;
3032
+ // B4: the branch check reads the cheap head state, not the full tree snapshot (slow, and unavailable for large dirty
3033
+ // trees and submodules). Read in parallel with the rest, bounded by the deadline.
3034
+ const readNowHead = async (): Promise<HeadState | undefined> => {
3035
+ if (atReturn === undefined) return undefined;
3036
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
3037
+ if (bound <= 0 || deadline.signal.aborted) return undefined;
3038
+ return withTimeout(
3039
+ readHeadState(entry.cwd, { signal: deadline.signal, timeoutMs: bound, lowPriority }),
3040
+ bound,
3041
+ "router_verify head",
3042
+ ).catch(() => undefined);
3043
+ };
3044
+ const [reference, drift, tree, nowHead, placementDrift] = await Promise.all([
1830
3045
  // The same bound as the store's reference(id, signal): a capture still pending at the deadline
1831
3046
  // is "no reference (gate budget)".
1832
3047
  untilAborted<ReferenceState>(entry.reference, deadline.signal, () => ({ kind: "none", reason: REFERENCE_NONE.gateBudget })),
1833
3048
  checkDrift(entry, deadline),
1834
3049
  snapshot,
3050
+ readNowHead(),
3051
+ // Cross-repo P2e.4b: no placements, no work (resolves undefined at once).
3052
+ placementDriftOf(entry),
1835
3053
  ]);
1836
3054
  const changed = entry.changedFiles;
3055
+ const root = entry.root ?? tree?.root;
3056
+ // I7 (P0.2, S12): the tree must still be on the checkout the producer returned on. A branch recorded at return with no
3057
+ // current head state to compare is refused too ("cannot confirm": retryable); nothing recorded: no check.
3058
+ let branchSwitch: string | undefined;
3059
+ if (atReturn !== undefined) {
3060
+ if (nowHead === undefined) {
3061
+ if (atReturn.branch !== undefined) branchSwitch = branchUnconfirmedReason(atReturn.root ?? root ?? entry.cwd);
3062
+ } else if (atReturn.branch === undefined) {
3063
+ // Registered without a branch (an unknown one): any HEAD move is a switch (branch.ts branchSwitched).
3064
+ if (branchSwitched(atReturn, nowHead)) {
3065
+ branchSwitch = branchSwitchReason(nowHead.root, atReturn, nowHead, "since the producer returned");
3066
+ }
3067
+ } else {
3068
+ const before: HeadState = {
3069
+ root: atReturn.root ?? nowHead.root,
3070
+ head: atReturn.head,
3071
+ branch: atReturn.branch,
3072
+ ...(atReturn.reflog !== undefined ? { reflog: atReturn.reflog } : {}),
3073
+ };
3074
+ let window: ReflogEntry[] | undefined;
3075
+ const comparable = before.reflog !== undefined && nowHead.reflog !== undefined && nowHead.reflog >= before.reflog;
3076
+ if (comparable) {
3077
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
3078
+ window = bound > 0 && !deadline.signal.aborted
3079
+ ? await withTimeout(
3080
+ readReflogWindow(nowHead.root, (nowHead.reflog ?? 0) - (before.reflog ?? 0), {
3081
+ signal: deadline.signal, timeoutMs: bound, lowPriority,
3082
+ }),
3083
+ bound,
3084
+ "router_verify reflog",
3085
+ ).catch(() => undefined)
3086
+ : undefined;
3087
+ }
3088
+ // The reflog grew but its entries cannot be read: a checkout or reset cannot be ruled out (fail closed).
3089
+ const unreadWindow = window === undefined && before.reflog !== undefined && nowHead.reflog !== undefined
3090
+ && nowHead.reflog > before.reflog;
3091
+ const move = unreadWindow
3092
+ ? { kind: "rewritten" as const, detail: "the reflog entries could not be read" }
3093
+ : treeMove(before, nowHead, window);
3094
+ if (move !== undefined) branchSwitch = treeMoveReason(nowHead.root, before, nowHead, move, "since the producer returned");
3095
+ }
3096
+ }
3097
+ // Cross-repo P2e.3: a frozen perimeter (registered at return) is judged as it was then (I4, I8: its roots' statuses are
3098
+ // never re-snapshotted); the consumers (D6) are discovered now over its frozen working set, bounded by the claim deadline.
3099
+ let perimeter: PerimeterObservation | undefined;
3100
+ let gateReference: ReferenceState = reference;
3101
+ let linkDrift: ClaimPreparation["linkDrift"];
3102
+ const frozen = entry.perimeter;
3103
+ if (frozen !== undefined) {
3104
+ const discoverFrozen = async (): Promise<ConsumerDiscovery> => {
3105
+ const candidates = [...frozen.workingSet];
3106
+ if (candidates.length === 0) return { consumers: [], incomplete: [] };
3107
+ const controller = new AbortController();
3108
+ const ms = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
3109
+ const onAbort = (): void => controller.abort();
3110
+ if (ms <= 0 || deadline.signal.aborted) controller.abort();
3111
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
3112
+ const timer = setTimeout(onAbort, Math.max(0, ms));
3113
+ try {
3114
+ const parents = frozen.admission?.parents;
3115
+ return await discoverConsumers(frozen.observation.w.root, candidates, { signal: controller.signal, ...(parents !== undefined ? { parents } : {}) });
3116
+ } catch {
3117
+ return { consumers: [], incomplete: candidates }; // Never expected (it never throws): fail closed.
3118
+ } finally {
3119
+ clearTimeout(timer);
3120
+ deadline.signal.removeEventListener("abort", onAbort);
3121
+ }
3122
+ };
3123
+ const awaitPins = async (): Promise<readonly LinkPin[]> => {
3124
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
3125
+ if (bound <= 0 || deadline.signal.aborted) return [];
3126
+ return withTimeout(frozen.pins, bound, "router_verify link pins").catch(() => []);
3127
+ };
3128
+ // Cross-repo P2e.4a (S11): each frozen link target observed again (one hardened snapshot per root per call, shared by
3129
+ // the call's entries through `snapshots`). Working-set roots are not: the I4 window ended at return.
3130
+ type FrozenLink = NonNullable<PendingEntry["perimeter"]>["links"][number];
3131
+ type Drift = { readonly name: string; readonly root: string; readonly why: "changed" | "unobserved" };
3132
+ // `real`: where link.at resolves now (fs only); `targets`: what W depends on now, its package link targets and its admitted
3133
+ // declared edges' top levels (P3c.4, SD-P3c-1: `dependencyTargets`, fs only, no git run); `every`: those and its unadmitted
3134
+ // edge targets' paths (P3 QA-2 F-2).
3135
+ const observeLink = async (
3136
+ link: FrozenLink,
3137
+ real: string | undefined,
3138
+ targets: readonly string[],
3139
+ every: readonly string[],
3140
+ ): Promise<Drift | undefined> => {
3141
+ const name = link.name ?? basename(link.root);
3142
+ // P3 QA-1 M3: a dependency the producer removed (or retargeted) during the dispatch is not an input of the change: skipped
3143
+ // entirely while W still does not depend on it; W depending on it again since the return is a new dependency: "changed".
3144
+ // P3 QA-2 F-2: an unadmitted spelling into it still declares it (frozen removed only when no target of any kind lay in it).
3145
+ if (link.removedAtReturn === true) {
3146
+ return every.some(target => depthBelow(target, link.root) >= 0) ? { name, root: link.root, why: "changed" } : undefined;
3147
+ }
3148
+ // P2e QA-1 #4 (I12): no git where the link no longer resolves inside its frozen root, or where its admission refuses.
3149
+ if (real === undefined || depthBelow(real, link.root) < 0 || link.admit?.(link.root) === false) {
3150
+ return { name, root: link.root, why: "unobserved" };
3151
+ }
3152
+ // P2e QA-1 #2: W no longer links into it (retargeted or removed): the checks ran against another link target.
3153
+ if (!targets.some(target => depthBelow(target, link.root) >= 0)) return { name, root: link.root, why: "changed" };
3154
+ const key = `link\0${perimeterKey(link.at)}`;
3155
+ let pending = snapshots.get(key);
3156
+ if (pending === undefined) {
3157
+ pending = hardenedSnapshotFor(link.at, deadline, lowPriority);
3158
+ snapshots.set(key, pending);
3159
+ }
3160
+ const now = await pending;
3161
+ const top = now?.root;
3162
+ if (now === undefined) return { name, root: link.root, why: "unobserved" };
3163
+ if (top !== undefined && link.admit !== undefined && !link.admit(top)) return { name, root: link.root, why: "unobserved" };
3164
+ if (top === undefined || perimeterKey(top) !== perimeterKey(link.root) || now.fingerprint !== link.fingerprint || now.head !== link.head) {
3165
+ return { name, root: link.root, why: "changed" };
3166
+ }
3167
+ return undefined;
3168
+ };
3169
+ const observeLinks = async (): Promise<Drift[]> => {
3170
+ const reals = await Promise.all(frozen.links.map(link => realpath(link.at).catch(() => undefined)));
3171
+ // The W directory planPerimeter read links from at dispatch (it can be a subfolder of the git top level); an entry
3172
+ // registered without one falls back to the snapshot root.
3173
+ const wRoot = frozen.linkBase ?? frozen.observation.w.root;
3174
+ // P3c.4 (SD-P3c-1, F1): W's dependency targets now, the union of its package links and its declared edges, read through
3175
+ // the admission frozen at dispatch (SD-P3c-9) and once per W for this call's entries (SD-P3c-8). An entry registered
3176
+ // without a frozen admission reads W's package links only, as before P3c.
3177
+ const admission = frozen.admission;
3178
+ const context = admission !== undefined ? admissionFromData(admission) : undefined;
3179
+ const memoKey = `${perimeterKey(wRoot)}\0${admission !== undefined ? JSON.stringify(admission) : ""}`;
3180
+ if (!dependencies.has(memoKey)) {
3181
+ let read: DependencyTargets | undefined;
3182
+ try {
3183
+ read = context !== undefined
3184
+ ? dependencyTargets(wRoot, context)
3185
+ : { targets: linkedTargets(wRoot).map(at => ({ origin: "link" as const, at })), unadmittedMore: 0, incomplete: false };
3186
+ } catch {
3187
+ read = undefined; // Never expected (both skip what they cannot read): every frozen dependency is then "changed".
3188
+ }
3189
+ dependencies.set(memoKey, read);
3190
+ }
3191
+ const current = dependencies.get(memoKey)?.targets ?? [];
3192
+ // What W still depends on: its link targets (admitted or not, as before) and its admitted edges' top levels. An
3193
+ // unadmitted edge target is text only (never observed): it only names a new dependency below.
3194
+ const targets = current.filter(target => !("fixed" in target)).map(target => target.at);
3195
+ // P3 QA-2 F-2: a link removed at return is judged against every target, unadmitted ones included (as frozen at return).
3196
+ const every = current.map(target => target.at);
3197
+ const drifts = await Promise.all(frozen.links.map((link, index) => observeLink(link, reals[index], targets, every)));
3198
+ // P2e QA-1 #2: a dependency target of W now that none of the perimeter frozen at return covers (its links and edges'
3199
+ // roots, frozen at return, and its observed roots) is new: "changed". W's own repository is W's snapshot, as at
3200
+ // dispatch (planPerimeter); W's dependencies are read from `wRoot` (the dispatch's W), never from the snapshot root
3201
+ // (which is the git top level).
3202
+ // P3 QA-1 M3: a link removed at return covers nothing (observeLink names it when W depends on it again).
3203
+ const covering = [
3204
+ ...frozen.links.filter(link => link.removedAtReturn !== true).map(link => link.root),
3205
+ ...reals.filter((real, index): real is string => real !== undefined && frozen.links[index]?.removedAtReturn !== true),
3206
+ ...frozen.observation.roots.map(root => root.root),
3207
+ ];
3208
+ // P3 QA-1 M4: an unadmitted target the producer added during the dispatch covers itself, as a dispatch-time one does
3209
+ // through its unadmitted root. P3 QA-2 F-3: itself only (same key), and only while it is still unadmitted: an admitted
3210
+ // target at or below it is a new dependency ("changed").
3211
+ const unadmittedAtReturn = new Set((frozen.unadmittedAtReturn ?? []).map(at => perimeterKey(at)));
3212
+ // Not admitted now, as dependenciesAddedAtReturn judged it at return: an unadmitted edge, or a link target outside every
3213
+ // parent and worktree, without a git top level, or whose top level the frozen admission refuses.
3214
+ const unadmittedNow = (target: DependencyTargets["targets"][number]): boolean => {
3215
+ if ("fixed" in target) return true;
3216
+ if (target.origin === "edge" || context === undefined) return false;
3217
+ const parent = context.parentOf(target.at);
3218
+ const worktree = context.worktreeOf(target.at);
3219
+ if (parent === undefined && worktree === undefined) return true;
3220
+ const top = gitTopOf(target.at, worktree !== undefined ? dirname(worktree.worktree) : parent);
3221
+ return top === undefined || !context.admitTop(top);
3222
+ };
3223
+ // A new link target is named by its top level, found without git: below its parent (or above its working-set worktree)
3224
+ // as at dispatch (SD-P3c-9, F8). Outside every parent and worktree, it is named by its text: nothing runs there (I11).
3225
+ // Without a frozen admission: its top level, as before P3c.
3226
+ const linkTop = (target: string): string => {
3227
+ if (context === undefined) return gitTopOf(target) ?? target;
3228
+ const parent = context.parentOf(target);
3229
+ const worktree = context.worktreeOf(target);
3230
+ if (parent === undefined && worktree === undefined) return target;
3231
+ return gitTopOf(target, worktree !== undefined ? dirname(worktree.worktree) : parent) ?? target;
3232
+ };
3233
+ const fresh = new Map<string, Drift>();
3234
+ for (const target of current) {
3235
+ if (covering.some(root => depthBelow(target.at, root) >= 0)) continue;
3236
+ if (unadmittedAtReturn.has(perimeterKey(target.at)) && unadmittedNow(target)) continue;
3237
+ // An edge target is already its top level (admitted, found below its parent by `resolveEdgeTarget`) or text (not
3238
+ // admitted: named from its text, with no filesystem call, I11).
3239
+ const top = target.origin === "edge" ? target.at : linkTop(target.at);
3240
+ if (depthBelow(top, wRoot) >= 0 || depthBelow(wRoot, top) >= 0) continue;
3241
+ const name = "fixed" in target ? target.name : basename(top);
3242
+ if (!fresh.has(perimeterKey(top))) fresh.set(perimeterKey(top), { name, root: top, why: "changed" });
3243
+ }
3244
+ return [...drifts.filter((drift): drift is Drift => drift !== undefined), ...fresh.values()];
3245
+ };
3246
+ const [found, pins, drifted] = await Promise.all([discoverFrozen(), awaitPins(), observeLinks()]);
3247
+ if (drifted.length > 0) linkDrift = drifted;
3248
+ // P3 QA-2 F-3 (I8): an unadmitted dependency the producer added during the dispatch is named as a dispatch-time one is, a
3249
+ // root "unadmitted" (`<name> (not admitted)` in the verified-scope line, never refused), once per root already named.
3250
+ const named = new Set([frozen.observation.w.root, ...frozen.observation.roots.map(root => root.root)].map(at => perimeterKey(at)));
3251
+ const unadmittedRoots: PerimeterObservation["roots"][number][] = [];
3252
+ for (const at of frozen.unadmittedAtReturn ?? []) {
3253
+ if (named.has(perimeterKey(at))) continue;
3254
+ named.add(perimeterKey(at));
3255
+ unadmittedRoots.push({ root: at, name: basename(at), status: "unadmitted" });
3256
+ }
3257
+ perimeter = {
3258
+ ...frozen.observation,
3259
+ ...(unadmittedRoots.length > 0 ? { roots: [...frozen.observation.roots, ...unadmittedRoots] } : {}),
3260
+ ...(found.consumers.length > 0 ? { consumers: found.consumers } : {}),
3261
+ ...(found.incomplete.length > 0 ? { consumersIncomplete: found.incomplete } : {}),
3262
+ };
3263
+ if (reference.kind === "captured" && pins.length > 0) {
3264
+ // pinNow admits as the dispatch admitted, keyed by this pins array (buildGateDeps). P2e QA-1 #3: the deferred finish
3265
+ // registered the dispatch's own admission for it (freeLinkPins: nested link targets included); it is kept. Only without
3266
+ // one (an entry registered directly) the frozen links' roots stand in.
3267
+ if (!pinAdmissions.has(pins)) {
3268
+ const admitted = new Set<string>();
3269
+ for (const link of frozen.links) {
3270
+ if (link.admit === undefined || link.admit(link.root)) admitted.add(perimeterKey(link.root));
3271
+ }
3272
+ pinAdmissions.set(pins, admitted);
3273
+ }
3274
+ gateReference = { ...reference, reference: { ...reference.reference, pins } };
3275
+ }
3276
+ }
1837
3277
  return {
1838
3278
  prepared: {
1839
3279
  changedFiles: changed === "unavailable"
@@ -1841,11 +3281,21 @@ export function createVerificationWiring(deps: {
1841
3281
  : changed.map(c => ({ path: c.path, status: c.status ?? "", ...(c.previousPath !== undefined ? { previousPath: c.previousPath } : {}) })),
1842
3282
  // Section 1.5-6: an unattributed change set stays unattributed (never []).
1843
3283
  changeBaseline: changed === "unavailable" ? "unavailable" : "available",
1844
- reference,
3284
+ reference: gateReference,
1845
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 } : {}),
3288
+ ...(branchSwitch !== undefined ? { branchSwitch } : {}),
3289
+ ...(entry.unattributedWriters !== undefined ? { unattributedWriters: [...entry.unattributedWriters] } : {}),
3290
+ ...(perimeter !== undefined ? { perimeter } : {}),
3291
+ // Cross-repo P3a (D23 as amended, QA C1): the ORIGINAL dispatch start (the entry's), never the router_verify time.
3292
+ ...(Number.isFinite(entry.dispatchedAt) ? { dispatchStartedAt: entry.dispatchedAt } : {}),
1846
3293
  },
1847
3294
  drift,
1848
- root: entry.root ?? tree?.root,
3295
+ root,
3296
+ ...(linkDrift !== undefined ? { linkDrift } : {}),
3297
+ ...(placementDrift?.kind === "drift" ? { placementDrift: placementDrift.reason } : {}),
3298
+ ...(placementDrift?.kind === "unchecked" ? { placementUnchecked: placementDrift.reason } : {}),
1849
3299
  };
1850
3300
  };
1851
3301
 
@@ -1868,6 +3318,16 @@ export function createVerificationWiring(deps: {
1868
3318
  const dod = entry.dod;
1869
3319
  // A claimed entry is never released (release happens on a terminal settle only).
1870
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 } };
3325
+ // Cross-repo P2e.4b: a placed check whose cwd no longer resolves to the same repository would run elsewhere: nothing runs.
3326
+ if (prep.placementDrift !== undefined) return { kind: "final", result: { verdict: unverifiableVerdict(prep.placementDrift), retryable: false } };
3327
+ // P2e QA-1 #5b: a placement that could not be checked now: nothing runs; another router_verify may check it.
3328
+ if (prep.placementUnchecked !== undefined) {
3329
+ return { kind: "final", result: { verdict: unverifiableVerdict(prep.placementUnchecked), retryable: true } };
3330
+ }
1871
3331
  const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
1872
3332
  const inFlight = new Set<string>();
1873
3333
  const completedFailures: string[] = [];
@@ -1876,6 +3336,11 @@ export function createVerificationWiring(deps: {
1876
3336
  const artefact = {
1877
3337
  changedFiles: prep.prepared.changedFiles,
1878
3338
  changeBaseline: prep.prepared.changeBaseline,
3339
+ ...(prep.root !== undefined ? { changeRoot: prep.root } : {}),
3340
+ ...(prep.prepared.branchSwitch !== undefined ? { branchSwitch: prep.prepared.branchSwitch } : {}),
3341
+ ...(prep.prepared.unattributedWriters !== undefined && prep.prepared.unattributedWriters.length > 0
3342
+ ? { unattributedWriters: prep.prepared.unattributedWriters } : {}),
3343
+ ...(prep.prepared.perimeter !== undefined ? { perimeter: prep.prepared.perimeter } : {}),
1879
3344
  // Not stored (R3): a testsPass DoD is deterministic, and no deterministic check reads it.
1880
3345
  finalReturnText: "",
1881
3346
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
@@ -1890,7 +3355,12 @@ export function createVerificationWiring(deps: {
1890
3355
  const workRoot = deferredWorkRoots.get(entry.handle);
1891
3356
  try {
1892
3357
  res = await withTimeout(
1893
- accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd, ...(workRoot !== undefined ? { workRoot } : {}) }, artefact, gateDeps),
3358
+ accept({
3359
+ dod, trivial: false, mode: "modeA", cwd: entry.cwd,
3360
+ ...(workRoot !== undefined ? { workRoot } : {}),
3361
+ // Cross-repo P2e.4b: the placements frozen at return (each still resolves as it did: prepareClaim).
3362
+ ...(entry.placements !== undefined ? { checkPlacements: entry.placements } : {}),
3363
+ }, artefact, gateDeps),
1894
3364
  deadline.remaining(),
1895
3365
  "verification gate",
1896
3366
  );
@@ -1933,7 +3403,8 @@ export function createVerificationWiring(deps: {
1933
3403
  */
1934
3404
  const judgeVerdict = (entry: PendingEntry, prep: ClaimPreparation, gate: ClaimGate, cfg: RouterConfig): VerificationResult => {
1935
3405
  if (gate.kind === "final") return gate.result;
1936
- const { strict, retryable } = gate;
3406
+ const { strict } = gate;
3407
+ let retryable = gate.retryable;
1937
3408
  // QA-3.1-2 / QA-3.1-3: the dispatch's own context, recorded when the producer returned.
1938
3409
  const res = applyDispatchCaveats(
1939
3410
  lineageDowngrade(gate.res, { orchestratorSessionID: entry.orchestratorSessionID, root: prep.root, dispatchedAt: entry.dispatchedAt, strictUnverifiable: strict }),
@@ -1955,6 +3426,27 @@ export function createVerificationWiring(deps: {
1955
3426
  strict,
1956
3427
  ).verdict;
1957
3428
  }
3429
+ if (prep.linkDrift !== undefined && prep.linkDrift.length > 0) {
3430
+ // Cross-repo P2e.4a (S11, OD-P2e-1): a linked repository not as it was at return never lets a pass stand; it is
3431
+ // unverifiable with one caveat per link. A fail stays a fail and carries the caveats too. They are reasons as well, so the
3432
+ // report (formatVerifyReport: a verdict not accepted shows its reasons) names them.
3433
+ const caveats = prep.linkDrift.map(link => LINK_DRIFT_CAVEAT[link.why](link.name, link.root));
3434
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
3435
+ // P2e QA-1 #5a: a would-be pass held back only by links that could not be observed (a snapshot not in time, a link that
3436
+ // cannot be resolved now) is transient: retryable, so the handle stays open for another router_verify. A changed link
3437
+ // is certain: final. A fail stays final.
3438
+ if (outcome === "pass" && prep.linkDrift.every(link => link.why === "unobserved")) retryable = true;
3439
+ verdict = gateResult(
3440
+ {
3441
+ ...verdict,
3442
+ ...(outcome === "pass" ? { pass: false, outcome: "unverifiable" as const } : {}),
3443
+ reasons: [...verdict.reasons, ...caveats],
3444
+ caveats: [...(verdict.caveats ?? []), ...caveats],
3445
+ },
3446
+ res.dodSource,
3447
+ strict,
3448
+ ).verdict;
3449
+ }
1958
3450
  const judged = gateResult(verdict, res.dodSource, strict);
1959
3451
  const outcome = judged.verdict.outcome;
1960
3452
  let nextTier: string | undefined;
@@ -2026,6 +3518,16 @@ export function createVerificationWiring(deps: {
2026
3518
  slots.push({ kind: "unknown", input: t.handle ?? t.input });
2027
3519
  continue;
2028
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
+ }
2029
3531
  const c = pending.markVerifying(sessionID, t.handle);
2030
3532
  if (c.kind === "unknown") slots.push({ kind: "unknown", input: t.handle });
2031
3533
  else if (c.kind === "expired") slots.push({ kind: "expired", handle: c.handle });
@@ -2049,15 +3551,21 @@ export function createVerificationWiring(deps: {
2049
3551
  }
2050
3552
  } catch (error) {
2051
3553
  // Never leave a claim verifying until the reaper: settle what was claimed, retryable.
2052
- 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
+ }
2053
3559
  throw error;
2054
3560
  }
2055
3561
 
2056
3562
  // 4. Every preparation first, then every gate at once: the testsPass requests share the
2057
3563
  // deadline and reach the S5 coordinator together (one window, one batch).
2058
3564
  const snapshots = new Map<string, Promise<TreeSnapshot | undefined>>();
3565
+ // P3c.4 (SD-P3c-8): W's dependency targets, read once per W for this call's entries.
3566
+ const dependencies: DependencyMemo = new Map();
2059
3567
  // QA-3.1-8: the current-tree snapshot at the configured priority; a background run's always low.
2060
- const preparations = claims.map(c => prepareClaim(c.entry, owned, snapshots, budget.lowPriority || options.background === true));
3568
+ const preparations = claims.map(c => prepareClaim(c.entry, owned, snapshots, budget.lowPriority || options.background === true, dependencies));
2061
3569
  const allPrepared = Promise.allSettled(preparations);
2062
3570
  const gates = claims.map(async (c, i): Promise<{ readonly prep: ClaimPreparation | undefined; readonly gate: ClaimGate }> => {
2063
3571
  let prep: ClaimPreparation | undefined;
@@ -2097,6 +3605,8 @@ export function createVerificationWiring(deps: {
2097
3605
  } finally {
2098
3606
  // R4: single use, in a finally; false only when the claim was reaped or disposed.
2099
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) }));
2100
3610
  if (!c.settle(results[i])) logger.debug?.("[verify] router_verify settled a claim that was already reaped", { handle: c.entry.handle });
2101
3611
  });
2102
3612
  }
@@ -2168,6 +3678,9 @@ export function createVerificationWiring(deps: {
2168
3678
  }
2169
3679
  return { directives: resolveDirectives(text), dispatchedAt: pendingNow() };
2170
3680
  },
3681
+ directivesFor(text) {
3682
+ return resolveDirectives(text);
3683
+ },
2171
3684
  isDeferred(dod, directives, trivial = false) {
2172
3685
  if (directives.mode !== "deferred" || !hasTestsPass(dod)) return false;
2173
3686
  // QA-2.4-10: gate.ts skips exactly this case ("trivial dispatch; verification skipped").
@@ -2184,7 +3697,7 @@ export function createVerificationWiring(deps: {
2184
3697
  pending,
2185
3698
  background,
2186
3699
  beginVerificationBounded,
2187
- startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS) {
3700
+ startReferenceGc(delayMs = REFERENCE_GC_START_DELAY_MS, reloaded?: Promise<unknown>) {
2188
3701
  if (!directory) {
2189
3702
  logger.debug?.("[verify] reference GC skipped: plugin root unknown");
2190
3703
  return () => undefined;
@@ -2200,7 +3713,20 @@ export function createVerificationWiring(deps: {
2200
3713
  lowPriority: budget.lowPriority,
2201
3714
  signal: opts?.signal ? AbortSignal.any([opts.signal, stop.signal]) : stop.signal,
2202
3715
  });
2203
- 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(
2204
3730
  report => {
2205
3731
  if (report.removed.length > 0) logger.debug?.("[verify] reference GC removed stale dirs", { removed: report.removed.length });
2206
3732
  },
@@ -2217,10 +3743,31 @@ export function createVerificationWiring(deps: {
2217
3743
  stop.abort();
2218
3744
  };
2219
3745
  },
2220
- async prepareVerification(store, id, childID, cwd, deadline) {
2221
- const change = await observeChange(store, id, childID, cwd, deadline);
2222
- const reference = await store.reference(id, deadline?.signal);
2223
- return { ...change, reference };
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"); }
2224
3771
  },
2225
3772
  graderSessions,
2226
3773
  disposeChildSession,
@@ -2245,6 +3792,7 @@ export function createVerificationWiring(deps: {
2245
3792
  deferredWorkRoots.clear();
2246
3793
  // 2.4.5: abort the background run first, so nothing re-queues while the coordinator stops.
2247
3794
  background?.dispose();
3795
+ liveWirings.delete(liveWiring);
2248
3796
  return coordinator.dispose();
2249
3797
  },
2250
3798
  };