opencode-model-router 2.7.0 → 2.8.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 (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -16,7 +16,7 @@
16
16
  import { createHash } from "node:crypto";
17
17
  import type { ChildSessionRunner } from "../compat/child-session";
18
18
  import { access, readdir, readFile as fsReadFile, realpath, stat, unlink } from "node:fs/promises";
19
- import { isAbsolute, join, relative, resolve } from "node:path";
19
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
20
20
  import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
21
21
  import {
22
22
  createDeadline,
@@ -59,13 +59,14 @@ import {
59
59
  type SettledVerification,
60
60
  type VerificationResult,
61
61
  } from "./pending";
62
- import { assessRisk, type RiskAssessment } from "./risk";
62
+ import { assessRisk, FULL_SCOPE_PLAN, type FullScopePlan, type RiskAssessment } from "./risk";
63
63
  import { resolveBaseDir } from "./paths";
64
64
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
65
65
  import {
66
66
  buildAcceptedSuffix,
67
67
  buildForcingNote,
68
68
  canonicalPath,
69
+ isUnattributedWriter,
69
70
  tierModel,
70
71
  toolLabel,
71
72
  type ChangedFile,
@@ -74,22 +75,39 @@ import {
74
75
  type TreeSnapshot,
75
76
  } from "./dispatch";
76
77
  import { runArgv, runShell } from "./exec";
77
- import { snapshotTree } from "./tree";
78
+ import { fileMtimeMs, listIgnoredModules, snapshotTree } from "./tree";
79
+ import {
80
+ admissionFromData,
81
+ crossLinkAliases,
82
+ dependencyTargets,
83
+ discoverConsumers,
84
+ linkedTargets,
85
+ planPerimeter,
86
+ type ConsumerDiscovery,
87
+ type DependencyTargets,
88
+ } from "./perimeter";
89
+ import { PERIMETER_MAX } from "./perimeter";
90
+ import { defaultExternalLinks, pinTarget, type LinkPin } from "./pin";
91
+ import { depthBelow, gitTopOf, perimeterKey } from "./git-top";
92
+ import type { DispatchPerimeter, PerimeterEntry } from "./dispatch";
93
+ import { branchSwitched, branchSwitchReason, branchUnconfirmedReason, treeMove, treeMoveReason } from "./branch";
94
+ import { readHead, readHeadState, readReflogWindow, type HeadState, type ReflogEntry } from "./head";
78
95
  import { captureReference, DEFAULT_CAPTURE_TIMEOUT_MS, gcStaleReferences, nodeReferenceFs, type DispatchReference } from "./reference";
79
96
  import type { PluginLogger } from "../router/logger";
80
97
  import { REFERENCE_NONE } from "./baseline";
81
98
  import { scrubText } from "../guard/scrub";
99
+ import { displaySafe } from "../routing/roles/read-set";
82
100
  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";
101
+ import type { ArgvSeam, CheckPlacement, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ReferenceState, TestsPassHook, Verdict } from "./types";
102
+ import { planScopedRun, planStaticScoping, type ChangedPath, type RunnerFs, type StaticScoping, type StaticScopingInput, type TestSearchSeam } from "./runner";
85
103
  import {
86
104
  DEFAULT_GATE_BUDGET_MS,
87
105
  graderTimeoutMs,
88
106
  RouterTimeoutError,
89
107
  withTimeout,
90
108
  } from "./timeout";
91
- import { resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
92
- import { accept, gateResult, unverifiableGateResult, type GateDeps, type GateResult } from "./gate";
109
+ import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig, type VerifyBudget } from "../router/config";
110
+ import { accept, gateResult, PERIMETER_UNPLANNED, perimeterChangeReasons, unverifiableGateResult, type GateDeps, type GateResult, type PerimeterObservation, type PerimeterRoot } from "./gate";
93
111
  // The grader request shape is owned by checker.ts, which builds it. Re-exported
94
112
  // here because this module is where it is consumed, and because keeping a
95
113
  // second local copy is exactly how `cwd` got dropped: the checker set it, the
@@ -174,6 +192,29 @@ export interface PreparedVerification {
174
192
  concurrentDispatches?: number;
175
193
  /** QA-3.1-3: the tool whose call discarded the dispatch snapshot, which left the change set unavailable. */
176
194
  contaminatedBy?: string;
195
+ /**
196
+ * I7 (P0.2, S9/S12): the gate's unverifiable reason when the working tree switched branch (branch.ts); absent: no switch
197
+ * seen. The artefact builders hand it to the gate (Artefact.branchSwitch), which then refuses on either verifier.
198
+ */
199
+ branchSwitch?: string;
200
+ /** The cheap head state read at the gate (observeChange); absent when it was not read. The deferred finish registers it. */
201
+ head?: HeadState;
202
+ /**
203
+ * I5 (P0.3, S1/S3/S10): tools the producer lineage ran whose writes the router cannot observe (store.delta); the artefact
204
+ * builders hand them to the gate (Artefact.unattributedWriters). Absent or empty: none.
205
+ */
206
+ unattributedWriters?: string[];
207
+ /**
208
+ * Cross-repo P1.8 (I4, I8): the perimeter P observed at the gate (observeChange); the artefact builders hand it to the gate
209
+ * (Artefact.perimeter). Absent: the dispatch has no perimeter.
210
+ */
211
+ perimeter?: PerimeterObservation;
212
+ /**
213
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): when the dispatch began (DispatchStart.dispatchedAt; for a deferred
214
+ * verification, the entry's original dispatchedAt, never the router_verify time). buildGateDeps hands it to the gate
215
+ * (DeterministicDeps.dispatchStartedAt): only W's ignored modules modified since are cross-link inputs. Absent: none are.
216
+ */
217
+ dispatchStartedAt?: number;
177
218
  }
178
219
 
179
220
  /**
@@ -382,7 +423,11 @@ export const FALLBACK_CAPTURE_WAIT_MS = Math.min(5_000, DEFAULT_CAPTURE_TIMEOUT_
382
423
  /** What the orchestrator asked for at dispatch (directives.ts, parsed from its own prompt only). */
383
424
  export interface DispatchStart {
384
425
  readonly directives: VerifyDirectives;
385
- /** Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). */
426
+ /**
427
+ * Clock value when the dispatch started (pending.ts R3 dispatchedAt, R11 lineage). Cross-repo P3a (D23 as amended 2026-10-12,
428
+ * QA C1): also the gate's `DeterministicDeps.dispatchStartedAt`, the `since` of W's ignored-module listing, on the synchronous
429
+ * and the deferred path alike (the deferred entry keeps this value, never the router_verify time).
430
+ */
386
431
  readonly dispatchedAt: number;
387
432
  }
388
433
 
@@ -410,6 +455,18 @@ export interface DeferredFinishInput {
410
455
  * the gate runs as before (I1).
411
456
  */
412
457
  readonly workRoot?: string;
458
+ /**
459
+ * Cross-repo I2 (P2.3): where the change capture observes a role dispatch (its work root W). Absent: `cwd`, as before.
460
+ * Only the observation uses it; the registration keeps `cwd`, the base the checks run in (F5).
461
+ */
462
+ readonly captureRoot?: string;
463
+ /**
464
+ * Cross-repo P2e: the DoD's per-check placements (index-aligned with `dod.checks`), as the dispatch resolved them. Only the
465
+ * static scoping plan and the no-change shortcut read them. Absent: every check runs at `cwd` and in its default scope.
466
+ */
467
+ readonly placements?: readonly (CheckPlacement | undefined)[];
468
+ /** Cross-repo P2e: the dispatch runs the full scope (the whole suite), so an empty change set still spawns the suite. */
469
+ readonly fullScope?: boolean;
413
470
  }
414
471
 
415
472
  /** Deferred budget snapshots kept for `router_verify` (by handle; oldest dropped first, like the pending registry's bound). */
@@ -434,9 +491,14 @@ export type DeferredFinish =
434
491
  * "unregistered": the registry refused the entry (registry-full, handle-collision,
435
492
  * invalid-input); "no-change": an attributed empty change set of a testsPass-only DoD, which
436
493
  * 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.
494
+ * with the empty set instead, noChangeGateSpawnsNothing); "error": the finish itself failed;
495
+ * "branch-switched" (I7, P0.2): the working tree switched branch during the dispatch, so no handle is issued that could
496
+ * verify the other branch later; the required gate refuses it at once (its observeChange sees the same switch);
497
+ * "cross-repo" (P1.8, P2e.5 X7): the dispatch's perimeter, observed at return, cannot be frozen for a later handle: a
498
+ * repository of it changed while an unattributable writer ran (I4), or a linked repository could not be observed within
499
+ * the deferral bound; the required gate verifies it at once.
438
500
  */
439
- readonly reason: "unregistered" | "no-change" | "error";
501
+ readonly reason: "unregistered" | "no-change" | "error" | "branch-switched" | "cross-repo";
440
502
  readonly detail: string;
441
503
  };
442
504
 
@@ -477,8 +539,19 @@ export function hasTestsPass(dod: DoD): boolean {
477
539
  * there is no criterion. Only such a delegation takes finishDeferred's "no-change" answer
478
540
  * (QA-2.4-10); any other deferred DoD is registered with the empty change set instead, so its
479
541
  * build, lint, run, file and criteria checks run on router_verify, never synchronously.
542
+ *
543
+ * Cross-repo P2e (F13): a full scope runs the whole suite even with no changed file
544
+ * (deterministic.ts), so the gate spawns it: false when `fullScope` is set and the DoD has a
545
+ * testsPass or lintClean check, or when such a check's placement has `scope === "full"`. Without
546
+ * `opts`: as before.
480
547
  */
481
- export function noChangeGateSpawnsNothing(dod: DoD): boolean {
548
+ export function noChangeGateSpawnsNothing(
549
+ dod: DoD,
550
+ opts?: { readonly placements?: readonly (CheckPlacement | undefined)[] | undefined; readonly fullScope?: boolean | undefined },
551
+ ): boolean {
552
+ const scoped = (kind: DoD["checks"][number]["kind"]): boolean => kind === "testsPass" || kind === "lintClean";
553
+ if (opts?.fullScope === true && dod.checks.some(c => scoped(c.kind))) return false;
554
+ if (opts?.placements !== undefined && dod.checks.some((c, i) => scoped(c.kind) && opts.placements?.[i]?.scope === "full")) return false;
482
555
  return dod.checks.length > 0 && dod.checks.every(c => c.kind === "testsPass") && dod.criteria.length === 0;
483
556
  }
484
557
 
@@ -551,6 +624,32 @@ export const ROUTER_VERIFY_NO_RETRY_TEXT = "[router] Nothing was retried or esca
551
624
  export const DRIFT_NOTICE = "tree drifted since delegation; verdict reflects current state";
552
625
  /** No per-file proof either way (no stored or current digests): a pass is never kept then. */
553
626
  export const DRIFT_UNCHECKED_NOTICE = "drift since delegation could not be checked; verdict reflects current state";
627
+ /**
628
+ * Cross-repo P2e.4a (S11, OD-P2e-1 = UNVERIFIED): the caveat of a frozen link target that router_verify found changed, or could
629
+ * not observe again, since the producer returned. A would-be pass then is unverifiable; a fail stays a fail with the caveat.
630
+ */
631
+ export const LINK_DRIFT_CAVEAT = {
632
+ changed: (name: string, root: string): string =>
633
+ `the linked repository ${linkCaveatText(name)} at ${linkCaveatText(root)} changed since the producer returned; the checks ran against its new state`,
634
+ unobserved: (name: string, root: string): string =>
635
+ `the linked repository ${linkCaveatText(name)} at ${linkCaveatText(root)} could not be observed again since the producer returned`,
636
+ } as const;
637
+ /** Cross-repo P3 QA-1 M5: the longest repository text (a link's name or root) a router line quotes; past it, cut with "…". */
638
+ export const LINK_CAVEAT_TEXT_MAX = 256;
639
+ /**
640
+ * 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
641
+ * quotes it: capped at LINK_CAVEAT_TEXT_MAX characters (never splitting a surrogate pair), then escaped.
642
+ */
643
+ function linkCaveatText(text: string): string {
644
+ let shown = text;
645
+ if (shown.length > LINK_CAVEAT_TEXT_MAX) {
646
+ let end = LINK_CAVEAT_TEXT_MAX - 1;
647
+ const last = shown.charCodeAt(end - 1);
648
+ if (last >= 0xd800 && last <= 0xdbff) end -= 1;
649
+ shown = `${shown.slice(0, end)}…`;
650
+ }
651
+ return displaySafe(shown);
652
+ }
554
653
  export const ROUTER_VERIFY_CANCELLED_REASON = "router_verify was cancelled before a verdict";
555
654
  export const ROUTER_VERIFY_RELEASED_REASON = "the delegation's verification data was released";
556
655
  /** Drifted paths named per handle; the rest are counted. */
@@ -604,6 +703,9 @@ const TRANSIENT_REASON = new RegExp(
604
703
  escapeRegExp(ABANDONED_REASON),
605
704
  escapeRegExp(DISPOSED_REASON),
606
705
  "router_verify was cancelled",
706
+ // branch.ts branchUnconfirmedReason: the head state could not be read at router_verify; reading it again can settle it.
707
+ // Not the "when the dispatch started" variant, nor a "switched"/"checked out or reset" reason: those are terminal.
708
+ "cannot confirm the branch of [^\\r\\n]*?: the working tree could not be read at router_verify",
607
709
  ].join("|") +
608
710
  ")",
609
711
  "i",
@@ -900,13 +1002,18 @@ export interface VerificationWiring {
900
1002
  * clears a pending timer and aborts the git calls of a GC in flight. Never throws.
901
1003
  */
902
1004
  startReferenceGc(delayMs?: number): () => void;
903
- /** P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given. */
1005
+ /**
1006
+ * P0: the snapshot, the changed files and the settled reference, each bounded by `deadline` when given.
1007
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): `dispatchStartedAt` is the dispatch's start (DispatchStart.dispatchedAt),
1008
+ * carried as PreparedVerification.dispatchStartedAt; absent: W's ignored modules are never cross-link inputs.
1009
+ */
904
1010
  prepareVerification(
905
1011
  store: ReturnType<typeof createChangedFileStore>,
906
1012
  id: string,
907
1013
  childID: string,
908
1014
  cwd?: string,
909
1015
  deadline?: Deadline,
1016
+ dispatchStartedAt?: number,
910
1017
  ): Promise<PreparedVerification>;
911
1018
  /** Session ids currently running a grader prompt, so hooks can skip them. */
912
1019
  graderSessions: Set<string>;
@@ -1333,6 +1440,10 @@ export function createVerificationWiring(deps: {
1333
1440
  // QA-3.1-8: the snapshot's git processes run at the configured priority, as the capture's do.
1334
1441
  snapshot: (at: string, signal: AbortSignal) =>
1335
1442
  sharedSnapshots(flightKey(at), shared => snapshotTree(at, shared, { lowPriority: budget.lowPriority }), signal),
1443
+ // The branch-switch baseline: independent of the snapshot, so it survives a discarded or failed one.
1444
+ // QA2 F3b: each git process gets the whole baseline budget (a loaded runner outlasts readHead's 5 s default).
1445
+ headState: (at: string, signal: AbortSignal) =>
1446
+ readHead(at, { signal, timeoutMs: budget.baselineTimeoutMs, lowPriority: budget.lowPriority }),
1336
1447
  timeoutMs: budget.baselineTimeoutMs,
1337
1448
  };
1338
1449
  if (!judgedByTests) return { ...base, uncaptured: { kind: "none", reason: REFERENCE_NONE.notRequested } };
@@ -1362,9 +1473,12 @@ export function createVerificationWiring(deps: {
1362
1473
  // QA-2.1-5: the recheck's git processes (GC, materialize, dispose) run at the configured
1363
1474
  // priority too, like the capture and the start-up GC (QA-1.2-13).
1364
1475
  const referenceArgv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
1476
+ // QA-2 nit: materialize pins a link target as this gate's dispatch admitted it (its pins' admission); without pins, none.
1477
+ const gatePins = prepared?.reference?.kind === "captured" ? prepared.reference.reference.pins : undefined;
1478
+ const pinNow = pinNowFor(gatePins !== undefined ? pinAdmissions.get(gatePins) : undefined);
1365
1479
  const openScope = createScopeOpener({
1366
1480
  argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1367
- reference: { argv: referenceArgv },
1481
+ reference: { argv: referenceArgv, pinNow },
1368
1482
  });
1369
1483
  const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
1370
1484
  const direct = createDirectTestsPassHook({
@@ -1373,6 +1487,11 @@ export function createVerificationWiring(deps: {
1373
1487
  search: testSearch(budget, deadline),
1374
1488
  budget,
1375
1489
  ...currentTree,
1490
+ // Cross-repo P3a (D23): the linked repository's ignored modules, hardened and bounded; called only with crossLinkRoot and
1491
+ // the dispatch start (D23 as amended 2026-10-12: only the modules modified since, never a stale build output).
1492
+ listIgnored: (root, signal, since) => listIgnoredModules(root, { signal, since, lowPriority: budget.lowPriority }),
1493
+ // QA round 2 M-A: a changed source of W newer than the newest listed build output makes the request S6 build-stale.
1494
+ mtimeOf: (path) => fileMtimeMs(path),
1376
1495
  });
1377
1496
  // 2.2.3 (S5): with a batch window, concurrent testsPass checks of this plugin instance meet in
1378
1497
  // the coordinator; the direct hook stays behind it for "full" scope and single requests (B2).
@@ -1428,6 +1547,8 @@ export function createVerificationWiring(deps: {
1428
1547
  changedFiles: prepared?.changeBaseline === "available" ? prepared.changedFiles : "unavailable",
1429
1548
  ...(prepared !== undefined ? { reference: prepared.reference } : {}),
1430
1549
  ...(deadline !== undefined ? { deadline } : {}),
1550
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch start, the `since` of W's ignored-module listing; absent: none listed.
1551
+ ...(prepared?.dispatchStartedAt !== undefined ? { dispatchStartedAt: prepared.dispatchStartedAt } : {}),
1431
1552
  },
1432
1553
  checker: {
1433
1554
  dispatchGrader: (req: GraderRequest) =>
@@ -1441,6 +1562,84 @@ export function createVerificationWiring(deps: {
1441
1562
  };
1442
1563
  };
1443
1564
 
1565
+ /**
1566
+ * 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
1567
+ * root (`PerimeterSeed.at`). Each `pin` settles once and never rejects. QA-2 #9c: an unattributable writer that runs while a
1568
+ * pin (its root or a nested target) is still computed marks it `contaminatedBy`, and linkPinsAtGate drops it. QA-2 nit:
1569
+ * freed once the dispatch's gate took them, or with a reference that was not captured (freeLinkPins); bounded otherwise.
1570
+ */
1571
+ interface DispatchLinkPin {
1572
+ readonly pin: Promise<LinkPin>;
1573
+ pending: boolean;
1574
+ contaminatedBy?: string;
1575
+ }
1576
+ const linkPins = new Map<string, Map<string, DispatchLinkPin>>();
1577
+ const LINK_PINS_MAX = 256;
1578
+ /** QA-2 nit: per dispatch, the link roots (perimeterKey) its admission accepted; bounded, oldest out. */
1579
+ const admittedLinks = new Map<string, Set<string>>();
1580
+ /** The admitted link roots behind the pins a gate took (keyed by that pins array): pinNow admits as the dispatch did. */
1581
+ const pinAdmissions = new WeakMap<readonly LinkPin[], ReadonlySet<string>>();
1582
+ const rememberAdmittedLink = (id: string, dir: string): void => {
1583
+ let admitted = admittedLinks.get(id);
1584
+ if (admitted === undefined) {
1585
+ admitted = new Set();
1586
+ admittedLinks.set(id, admitted);
1587
+ }
1588
+ admitted.add(perimeterKey(dir));
1589
+ while (admitted.size > 1024) {
1590
+ const oldest = admitted.values().next();
1591
+ if (oldest.done === true) break;
1592
+ admitted.delete(oldest.value);
1593
+ }
1594
+ };
1595
+ /** QA-2 nit: forgets a dispatch's pins and admitted roots; the pins its gate took keep that admission for pinNow. */
1596
+ const freeLinkPins = (id: string, taken: readonly LinkPin[]): void => {
1597
+ const admitted = admittedLinks.get(id);
1598
+ if (admitted !== undefined && taken.length > 0) pinAdmissions.set(taken, admitted);
1599
+ linkPins.delete(id);
1600
+ admittedLinks.delete(id);
1601
+ };
1602
+ /**
1603
+ * QA-2 #9c: an unattributable writer (any session: its directory says nothing about where it writes) discards every pin still
1604
+ * being computed, as it discards an in-flight perimeter snapshot (dispatch.ts contaminateCaptures). M3: the store only signals
1605
+ * the writers that contaminate captures by the same predicate, so a delegating tool (task, delegate, subagent), which keeps
1606
+ * the perimeter snapshot, keeps the pins too; parallel role dispatches no longer drop each other's pins.
1607
+ */
1608
+ const contaminateLinkPins = (tool: string): void => {
1609
+ if (!isUnattributedWriter(tool)) return;
1610
+ for (const forDispatch of linkPins.values()) {
1611
+ for (const pin of forDispatch.values()) if (pin.pending) pin.contaminatedBy ??= tool;
1612
+ }
1613
+ };
1614
+ /**
1615
+ * QA-2 #9c: the store's own writer signal (store.onUnattributedWriter: observeEdit before a call, record after it, the calls
1616
+ * that contaminate an in-flight perimeter snapshot) also reaches the pins. Subscribed once per store, by the first dispatch
1617
+ * that pins a link target; the subscription is bounded by the store's own lifetime (it holds the pins map only).
1618
+ */
1619
+ const watchedStores = new WeakSet<object>();
1620
+ const watchWritersFor = (store: ReturnType<typeof createChangedFileStore>): void => {
1621
+ if (watchedStores.has(store)) return;
1622
+ watchedStores.add(store);
1623
+ store.onUnattributedWriter(tool => contaminateLinkPins(tool));
1624
+ };
1625
+ /**
1626
+ * Cross-repo P2d.3 (P2.6): the current pin of a link target at materialize time (hardened, ignored files digested), admitted
1627
+ * as the dispatch admitted it (QA-2 nit: the gate's own pins' admission, never another dispatch's). Never throws (pinTarget).
1628
+ */
1629
+ const pinNowFor = (admitted: ReadonlySet<string> | undefined) => (root: string): Promise<LinkPin> =>
1630
+ pinTarget(root, {
1631
+ snapshot: dir => {
1632
+ const controller = new AbortController();
1633
+ return withTimeout(
1634
+ snapshotTree(dir, controller.signal, { lowPriority: configuredLowPriority(), hardened: true, ignoredDigest: true }),
1635
+ GRADE_SNAPSHOT_TIMEOUT_MS,
1636
+ "link pin fingerprint",
1637
+ ).catch(() => undefined).finally(() => controller.abort());
1638
+ },
1639
+ admitted: dir => admitted?.has(perimeterKey(dir)) === true,
1640
+ externalLinks: defaultExternalLinks,
1641
+ });
1642
+
1444
1643
  const beginVerification: VerificationWiring["beginVerification"] = async (store, id, cwd, dod) => {
1445
1644
  let deps: DispatchCaptureDeps;
1446
1645
  try {
@@ -1450,17 +1649,506 @@ export function createVerificationWiring(deps: {
1450
1649
  // QA-3.1-8), and no reference.
1451
1650
  deps = {
1452
1651
  snapshot: (at, signal) => snapshotTree(at, signal, { lowPriority: true }),
1652
+ headState: (at, signal) => readHead(at, { signal, lowPriority: true }),
1453
1653
  timeoutMs: DEFAULT_CAPTURE_TIMEOUT_MS,
1454
1654
  uncaptured: { kind: "none", reason: `${REFERENCE_NONE.failed} (${errorText(err)})` },
1455
1655
  };
1456
1656
  }
1457
- const begun = store.beginDispatch(id, resolve(directory, cwd || "."), deps);
1657
+ const at = resolve(directory, cwd || ".");
1658
+ // Cross-repo P1.8 (I13): a role dispatch's perimeter is fixed now; every other dispatch plans none (I9). QA-1 F9: a ladder
1659
+ // retry keeps the dispatch's perimeter (beginDispatch keeps the original), so it is not planned again.
1660
+ let perimeter: DispatchPerimeter | undefined;
1661
+ if (store.perimeterOf(id) === undefined) {
1662
+ try {
1663
+ const plannedPerimeter = planPerimeter(id, at, () => {
1664
+ const routing = resolveRolesRouting(getConfig(), "v2");
1665
+ return { parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude };
1666
+ });
1667
+ perimeter = plannedPerimeter;
1668
+ // P3 QA-1 m4 (SD-P3c-4): a forward bound cut W's declared edges; logged, the cut targets are not in P.
1669
+ if (plannedPerimeter?.edgesIncomplete === true || (plannedPerimeter?.unadmittedMore ?? 0) > 0) {
1670
+ logger.warn("[verify] dispatch perimeter: declared dependency edges were cut by a bound", {
1671
+ id,
1672
+ incomplete: plannedPerimeter?.edgesIncomplete === true,
1673
+ unadmittedMore: plannedPerimeter?.unadmittedMore ?? 0,
1674
+ });
1675
+ }
1676
+ } catch (err) {
1677
+ logger.warn("[verify] dispatch perimeter could not be planned", { id, error: errorText(err) });
1678
+ // QA-1 F10: fail closed. A placeholder root that is never observed: a dispatch whose producer ran an unattributable
1679
+ // writer is unverifiable (I4), since a write in another repository cannot be ruled out.
1680
+ perimeter = { roots: [{ at, name: PERIMETER_UNPLANNED, fixed: "unobserved" }] };
1681
+ }
1682
+ }
1683
+ const lowPriority = configuredLowPriority();
1684
+ // Cross-repo P2d.3 (P2.6): an admitted link target is pinned at dispatch (bounded by the capture timeout; the nested targets
1685
+ // are snapshotted hardened, one level deep, by pinTarget). QA-2 #4: the perimeter snapshot stays the plain hardened one; the
1686
+ // pin takes its own snapshots (ignored files digested), started once that snapshot settled, and neither dispatch start nor
1687
+ // the perimeter entry waits for it.
1688
+ const perimeterRootSnapshot = (root: string, signal: AbortSignal): Promise<TreeSnapshot | undefined> => {
1689
+ const plain = snapshotTree(root, signal, { lowPriority, hardened: true });
1690
+ const seed = perimeter?.roots.find(candidate => candidate.at === root);
1691
+ // 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
1692
+ // dependency edge's root (origin "edge", or a working-set root marked `edged`) is observed but never pinned.
1693
+ if (seed === undefined || (seed.origin !== "link" && seed.linked !== true) || seed.fixed !== undefined) return plain;
1694
+ watchWritersFor(store);
1695
+ const seedAdmit = seed.admit ?? ((): boolean => false);
1696
+ // The roots the dispatch's admission accepted: the materialize-time pin (pinNow) is admitted by the same set.
1697
+ const admit = (dir: string): boolean => {
1698
+ const admitted = seedAdmit(dir);
1699
+ if (admitted) rememberAdmittedLink(id, dir);
1700
+ return admitted;
1701
+ };
1702
+ const pinSnapshot = async (dir: string): Promise<TreeSnapshot | undefined> => {
1703
+ const controller = new AbortController();
1704
+ try {
1705
+ return await withTimeout(
1706
+ snapshotTree(dir, controller.signal, { lowPriority, hardened: true, ignoredDigest: true }),
1707
+ deps.timeoutMs,
1708
+ "link pin fingerprint",
1709
+ );
1710
+ } catch {
1711
+ return undefined;
1712
+ } finally {
1713
+ controller.abort();
1714
+ }
1715
+ };
1716
+ const entry: DispatchLinkPin = {
1717
+ pending: true,
1718
+ pin: plain.then(() => undefined, () => undefined)
1719
+ .then(() => withTimeout(
1720
+ pinTarget(root, { snapshot: pinSnapshot, admitted: admit, externalLinks: defaultExternalLinks }),
1721
+ deps.timeoutMs,
1722
+ "link pin",
1723
+ ))
1724
+ .catch((): LinkPin => ({ kind: "unpinnable", root, why: "not-observed" }))
1725
+ .finally(() => {
1726
+ entry.pending = false;
1727
+ }),
1728
+ };
1729
+ let forDispatch = linkPins.get(id);
1730
+ if (forDispatch === undefined) {
1731
+ forDispatch = new Map();
1732
+ linkPins.set(id, forDispatch);
1733
+ // Bounded: a dispatch whose gate never ran is evicted by newer ones (oldest first), with its admitted roots.
1734
+ while (linkPins.size > LINK_PINS_MAX) {
1735
+ const oldest = linkPins.keys().next();
1736
+ if (oldest.done === true) break;
1737
+ linkPins.delete(oldest.value);
1738
+ admittedLinks.delete(oldest.value);
1739
+ }
1740
+ }
1741
+ forDispatch.set(root, entry);
1742
+ return plain;
1743
+ };
1744
+ const begun = store.beginDispatch(id, at, perimeter === undefined ? deps : {
1745
+ ...deps,
1746
+ perimeter,
1747
+ // QA-1 F4 (I11): git runs hardened in a repository other than W.
1748
+ perimeterSnapshot: perimeterRootSnapshot,
1749
+ });
1458
1750
  // pending.ts R10: remember the reference's settled value (the store hands out one promise).
1459
1751
  const reference = store.reference(id);
1460
1752
  if (!settledReferences.has(reference)) void reference.then(state => settledReferences.set(reference, state));
1461
1753
  await begun;
1462
1754
  };
1463
1755
 
1756
+ /**
1757
+ * Cross-repo P2d.3 (P2.6): the dispatch's link pins that are ready within the gate deadline. A pin whose root's dispatch
1758
+ * snapshot was discarded (contaminated), a fixed root and a pin not ready in time are omitted. Never throws.
1759
+ */
1760
+ const linkPinsAtGate = async (
1761
+ store: ReturnType<typeof createChangedFileStore>,
1762
+ id: string,
1763
+ deadline: Deadline | undefined,
1764
+ ): Promise<LinkPin[]> => {
1765
+ const forDispatch = linkPins.get(id);
1766
+ const planned = store.perimeterOf(id);
1767
+ if (forDispatch === undefined || planned === undefined) return [];
1768
+ const ready = await Promise.all([...forDispatch].map(async ([root, pinned]): Promise<LinkPin | undefined> => {
1769
+ const entry = planned.entries.get(root);
1770
+ if (entry === undefined || entry.seed.fixed !== undefined || entry.contaminatedBy !== undefined) return undefined;
1771
+ const ms = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
1772
+ if (ms <= 0 || deadline?.signal.aborted === true) return undefined;
1773
+ try {
1774
+ const pin = await withTimeout(pinned.pin, ms, "link pin");
1775
+ // QA-2 #9c: an unattributable writer ran while it (or a nested target's snapshot) was computed: dropped.
1776
+ return pinned.contaminatedBy === undefined ? pin : undefined;
1777
+ } catch {
1778
+ return undefined;
1779
+ }
1780
+ }));
1781
+ return ready.filter((pin): pin is LinkPin => pin !== undefined);
1782
+ };
1783
+
1784
+ /** The two snapshots of each extra root of a perimeter (perimeterSnapshotsAtGate); `fixed` roots have neither. */
1785
+ type PerimeterSnapshots = readonly { entry: PerimeterEntry; before: TreeSnapshot | undefined; now: TreeSnapshot | undefined }[];
1786
+
1787
+ /**
1788
+ * Cross-repo P1.8 (I4, I13): each extra root of the dispatch's perimeter snapshotted again, hardened (QA-1 F4) and bounded by
1789
+ * `deadline`, next to its dispatch snapshot. QA-1 F9: the roots are snapshotted concurrently with each other, and the caller
1790
+ * starts this before W's own gate snapshot so both run at once. A fixed root (never observed) is not snapshotted. Undefined
1791
+ * when the dispatch has no perimeter.
1792
+ */
1793
+ const perimeterSnapshotsAtGate = async (
1794
+ store: ReturnType<typeof createChangedFileStore>,
1795
+ id: string,
1796
+ deadline: Deadline | undefined,
1797
+ ): Promise<{ name?: string; snapshots: PerimeterSnapshots; admission?: DispatchPerimeter["admission"] } | undefined> => {
1798
+ const planned = store.perimeterOf(id);
1799
+ if (planned === undefined || planned.entries.size === 0) return undefined;
1800
+ const bound = (): number => (deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS);
1801
+ const lowPriority = configuredLowPriority();
1802
+ const snapshots = await Promise.all([...planned.entries.values()].map(async entry => {
1803
+ if (entry.seed.fixed !== undefined) return { entry, before: undefined, now: undefined };
1804
+ const before = withTimeout(entry.snapshot, Math.max(1, bound()), "perimeter fingerprint").catch(() => undefined);
1805
+ const now = (async (): Promise<TreeSnapshot | undefined> => {
1806
+ const ms = bound();
1807
+ if (ms <= 0 || deadline?.signal.aborted === true) return undefined;
1808
+ const controller = new AbortController();
1809
+ const onAbort = (): void => controller.abort();
1810
+ deadline?.signal.addEventListener("abort", onAbort, { once: true });
1811
+ try {
1812
+ return await withTimeout(snapshotTree(entry.seed.at, controller.signal, { lowPriority, hardened: true }), ms, "perimeter fingerprint");
1813
+ } catch {
1814
+ return undefined;
1815
+ } finally {
1816
+ deadline?.signal.removeEventListener("abort", onAbort);
1817
+ controller.abort();
1818
+ }
1819
+ })();
1820
+ return { entry, before: await before, now: await now };
1821
+ }));
1822
+ return {
1823
+ ...(planned.name !== undefined ? { name: planned.name } : {}),
1824
+ snapshots,
1825
+ // P3c.4 (SD-P3c-9): the dispatch's admission, for the perimeter frozen at return (perimeterAtReturn).
1826
+ ...(planned.admission !== undefined ? { admission: planned.admission } : {}),
1827
+ };
1828
+ };
1829
+
1830
+ /**
1831
+ * Cross-repo P1.8 (I4, I8): each extra root of the dispatch's perimeter compared with its dispatch snapshot: "changed" when
1832
+ * the fingerprint, HEAD or top level differs, "unobserved" when either snapshot is unavailable (fail closed), a fixed root with
1833
+ * its own status. QA-1 F4: a root whose git top level is not admitted at the gate is reported unobserved, never dropped (I12).
1834
+ * Roots are de-duplicated by top level, W's own excluded. Undefined when the dispatch has no perimeter or none remains.
1835
+ * Cross-repo P2b.3 (D6): the working-set roots (never W, never a link target) whose `node_modules` link into W are its
1836
+ * consumers (perimeter.ts discoverConsumers: fs only, bounded, never throws).
1837
+ */
1838
+ const perimeterAtGate = async (
1839
+ planned: { name?: string; snapshots: PerimeterSnapshots; admission?: { readonly parents: readonly string[] } } | undefined,
1840
+ snapshot: TreeSnapshot | undefined,
1841
+ base: string,
1842
+ deadline?: Deadline,
1843
+ // Cross-repo P2e.5 (return mode): `discover: false` skips consumer discovery (router_verify discovers over the frozen
1844
+ // working set instead); nothing else differs.
1845
+ options: { readonly discover?: boolean } = {},
1846
+ ): Promise<PerimeterObservation | undefined> => {
1847
+ if (planned === undefined) return undefined;
1848
+ const key = (at: string): string => {
1849
+ const normalized = resolve(at).replace(/\\/g, "/");
1850
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1851
+ };
1852
+ const wRoot = snapshot?.root ?? base;
1853
+ const rank = { unchanged: 0, unadmitted: 1, unobserved: 2, changed: 3 } as const;
1854
+ const roots = new Map<string, PerimeterRoot>();
1855
+ const workingSet = new Map<string, { root: string; name?: string }>();
1856
+ for (const { entry, before, now } of planned.snapshots) {
1857
+ const fixed = entry.seed.fixed;
1858
+ const known = fixed === undefined ? now?.root ?? before?.root : undefined;
1859
+ const refused = known !== undefined && entry.seed.admit !== undefined && !entry.seed.admit(known);
1860
+ const root = known !== undefined && !refused ? known : entry.seed.at;
1861
+ // W's own repository is W's snapshot (a fixed placeholder may stand at W's path: it is kept).
1862
+ if (fixed === undefined && key(root) === key(wRoot)) continue;
1863
+ if (entry.seed.origin === "working-set" && !workingSet.has(key(root))) {
1864
+ workingSet.set(key(root), { root, ...(entry.seed.name !== undefined ? { name: entry.seed.name } : {}) });
1865
+ }
1866
+ const status: PerimeterRoot["status"] = fixed ?? (refused || before === undefined || now === undefined
1867
+ ? "unobserved"
1868
+ : before.fingerprint !== now.fingerprint || before.head !== now.head || before.root !== now.root ? "changed" : "unchanged");
1869
+ // Only an admitted, observed root is described by its git state.
1870
+ const shown = fixed !== undefined || refused ? undefined : now ?? before;
1871
+ const next: PerimeterRoot = {
1872
+ root,
1873
+ name: entry.seed.name ?? basename(root),
1874
+ status,
1875
+ ...(typeof shown?.branch === "string" ? { branch: shown.branch } : {}),
1876
+ ...(shown?.head ? { head: shown.head } : {}),
1877
+ ...(entry.seed.sameRepository === true ? { sameRepository: true } : {}),
1878
+ };
1879
+ const previous = roots.get(key(root));
1880
+ if (previous === undefined || rank[next.status] > rank[previous.status]) roots.set(key(root), next);
1881
+ }
1882
+ if (roots.size === 0) return undefined;
1883
+ // QA-1 #13: the discovery is bounded by the gate deadline (and the grade snapshot bound); the roots it has not finished
1884
+ // then are incomplete. QA-1 #2: so is a root whose scan stopped on its entry bound without finding a consumer.
1885
+ const discover = async (): Promise<ConsumerDiscovery> => {
1886
+ const candidates = [...workingSet.values()];
1887
+ const controller = new AbortController();
1888
+ const ms = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
1889
+ const onAbort = (): void => controller.abort();
1890
+ if (ms <= 0 || deadline?.signal.aborted === true) controller.abort();
1891
+ deadline?.signal.addEventListener("abort", onAbort, { once: true });
1892
+ const timer = setTimeout(onAbort, Math.max(0, ms));
1893
+ try {
1894
+ // P3 QA-1 m5: both spellings of each parent, so an edge spelled through a junction-spelled parent is matched.
1895
+ const parents = planned.admission?.parents;
1896
+ return await discoverConsumers(wRoot, candidates, { signal: controller.signal, ...(parents !== undefined ? { parents } : {}) });
1897
+ } catch {
1898
+ return { consumers: [], incomplete: candidates }; // Never expected (it never throws): fail closed.
1899
+ } finally {
1900
+ clearTimeout(timer);
1901
+ deadline?.signal.removeEventListener("abort", onAbort);
1902
+ }
1903
+ };
1904
+ const { consumers, incomplete } = workingSet.size === 0 || options.discover === false
1905
+ ? { consumers: [], incomplete: [] }
1906
+ : await discover();
1907
+ return {
1908
+ w: {
1909
+ root: wRoot,
1910
+ name: planned.name ?? basename(wRoot),
1911
+ ...(typeof snapshot?.branch === "string" ? { branch: snapshot.branch } : {}),
1912
+ ...(snapshot?.head ? { head: snapshot.head } : {}),
1913
+ },
1914
+ roots: [...roots.values()],
1915
+ ...(consumers.length > 0 ? { consumers } : {}),
1916
+ ...(incomplete.length > 0 ? { consumersIncomplete: incomplete } : {}),
1917
+ };
1918
+ };
1919
+
1920
+ /** Cross-repo P2e.5: what a deferred entry freezes of its dispatch's perimeter (pending.ts DeferredPerimeter, without the pins). */
1921
+ type FrozenPerimeter = NonNullable<PendingEntry["perimeter"]>;
1922
+
1923
+ /**
1924
+ * Cross-repo P3c.6 (D26): the dependency targets the producer added to W during the dispatch, frozen at return. W's targets
1925
+ * are read again from `linkBase` through the union (`dependencyTargets`, fs only) with the dispatch's frozen admission; each
1926
+ * admitted one that no root in `covering` holds (the perimeter's roots), and that is not W's own repository (`own`: W's
1927
+ * directory and top level, as planPerimeter skips them), is snapshotted, hardened, within what remains of `deadline` (the
1928
+ * deferral bound), and frozen as a link. `unobserved`: one could not be observed in time, or its top level is no longer
1929
+ * admitted (X7: not deferred). An unadmitted target (no parent or worktree holds it, no git top level, a top the admission
1930
+ * refuses, or an unadmitted edge) is not snapshotted: it is returned in `unadmitted` (P3 QA-1 M4), frozen as covering only so
1931
+ * that router_verify does not name it new. Never a perimeter seed: P stays fixed at dispatch for writer attribution (I4, I13).
1932
+ * `targets`: what W depends on at return, so that a dispatch-time dependency the producer removed is frozen as such (P3 QA-1
1933
+ * M3); every target's path, an unadmitted one's included (P3 QA-2 F-2: a spelling the admission refuses still declares the
1934
+ * 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.
1935
+ */
1936
+ const dependenciesAddedAtReturn = async (
1937
+ linkBase: string,
1938
+ admission: NonNullable<DispatchPerimeter["admission"]>,
1939
+ covering: readonly string[],
1940
+ own: readonly string[],
1941
+ deadline: Deadline,
1942
+ // P3 QA-1 m2: how many new targets P may still take (PERIMETER_MAX, W and the dispatch's observed roots counted); past it
1943
+ // none is snapshotted and `unobserved` is set (fail closed: verified at once).
1944
+ room = Number.POSITIVE_INFINITY,
1945
+ ): Promise<{
1946
+ links: FrozenPerimeter["links"];
1947
+ unobserved: boolean;
1948
+ /**
1949
+ * 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
1950
+ * read, cut by a bound, or unadmitted targets past the names bound.
1951
+ */
1952
+ targets?: readonly string[];
1953
+ /** P3 QA-1 M4: the new targets not admitted, as router_verify names them (covering only, never seeds: I13). */
1954
+ unadmitted?: readonly string[];
1955
+ }> => {
1956
+ const read = ((): { context: ReturnType<typeof admissionFromData>; dependencies: DependencyTargets } | undefined => {
1957
+ try {
1958
+ const context = admissionFromData(admission);
1959
+ return { context, dependencies: dependencyTargets(linkBase, context) };
1960
+ } catch {
1961
+ return undefined; // Never expected (it skips what it cannot read).
1962
+ }
1963
+ })();
1964
+ // Fail closed: W's dependencies at return are unknown, so a new one cannot be ruled out (not deferred).
1965
+ if (read === undefined) return { links: [], unobserved: true };
1966
+ const { context, dependencies } = read;
1967
+ // P3 QA-2 F-2: every target, an unadmitted one included (its path: a spelling into a dispatch-time dependency still declares it).
1968
+ const targets = dependencies.targets.map(target => target.at);
1969
+ // Held by a perimeter root, or W's own repository (inside W, or W inside it): W's snapshot covers it.
1970
+ const covered = (at: string): boolean =>
1971
+ covering.some(root => depthBelow(at, root) >= 0) || own.some(dir => depthBelow(at, dir) >= 0 || depthBelow(dir, at) >= 0);
1972
+ // The admitted top level of each new target, once per repository.
1973
+ const added = new Map<string, string>();
1974
+ // P3 QA-1 M4: a new target not admitted, by the path router_verify reads it at (its text for an unadmitted edge).
1975
+ const unadmitted = new Map<string, string>();
1976
+ for (const target of dependencies.targets) {
1977
+ if (covered(target.at)) continue;
1978
+ // An unadmitted edge target is text only: never observed (I11).
1979
+ if ("fixed" in target) {
1980
+ unadmitted.set(perimeterKey(target.at), target.at);
1981
+ continue;
1982
+ }
1983
+ let top: string | undefined;
1984
+ if (target.origin === "edge") {
1985
+ top = target.at; // Already its admitted top level (resolveEdgeTarget).
1986
+ } else {
1987
+ // A package link target, admitted as at dispatch (SD-P3c-9, F8): its top level found without git below its parent (or
1988
+ // above its working-set worktree), then admitted by the frozen admission.
1989
+ const parent = context.parentOf(target.at);
1990
+ const worktree = context.worktreeOf(target.at);
1991
+ if (parent === undefined && worktree === undefined) {
1992
+ unadmitted.set(perimeterKey(target.at), target.at);
1993
+ continue;
1994
+ }
1995
+ top = gitTopOf(target.at, worktree !== undefined ? dirname(worktree.worktree) : parent);
1996
+ if (top === undefined || !context.admitTop(top)) {
1997
+ unadmitted.set(perimeterKey(target.at), target.at);
1998
+ continue;
1999
+ }
2000
+ }
2001
+ if (covered(top) || added.has(perimeterKey(top))) continue;
2002
+ added.set(perimeterKey(top), top);
2003
+ }
2004
+ // M3: only a complete read rules a dependency out (an unread manifest could still declare it: none is frozen as removed). P3
2005
+ // QA-2 F-2: nor one whose unadmitted targets the bound cut (one of them could lie in a dispatch-time dependency).
2006
+ const atReturn = {
2007
+ ...(dependencies.incomplete || dependencies.unadmittedMore > 0 ? {} : { targets }),
2008
+ ...(unadmitted.size > 0 ? { unadmitted: [...unadmitted.values()] } : {}),
2009
+ };
2010
+ if (added.size === 0) return { links: [], unobserved: false, ...atReturn };
2011
+ // P3 QA-1 m2: more new targets than P may take: none is snapshotted (not deferred, X7).
2012
+ if (added.size > room) return { links: [], unobserved: true, ...atReturn };
2013
+ const lowPriority = configuredLowPriority();
2014
+ const observed = await Promise.all([...added.values()].map(async top => ({ top, now: await hardenedSnapshotFor(top, deadline, lowPriority) })));
2015
+ const links: FrozenPerimeter["links"][number][] = [];
2016
+ let unobserved = false;
2017
+ for (const { top, now } of observed) {
2018
+ // As a seed at return: no snapshot in time, or a top level the admission refuses, is not observed (X7).
2019
+ if (now === undefined || now.root === undefined || !context.admitTop(now.root)) {
2020
+ unobserved = true;
2021
+ continue;
2022
+ }
2023
+ links.push({
2024
+ at: top,
2025
+ root: now.root,
2026
+ name: basename(now.root),
2027
+ head: now.head,
2028
+ fingerprint: now.fingerprint,
2029
+ admit: context.admitTop,
2030
+ });
2031
+ }
2032
+ return { links, unobserved, ...atReturn };
2033
+ };
2034
+
2035
+ /**
2036
+ * Cross-repo P2e.5 (X4, X5): the perimeter frozen when a deferred producer returns. The observation is perimeterAtGate's in
2037
+ * return mode (no consumer discovery inside the deferral bound: router_verify discovers over the frozen working set). Next to
2038
+ * it: the working-set roots (origin "working-set", never W), and the link targets (origin "link" or `linked`, never fixed)
2039
+ * with the top level, head and fingerprint of their return-time snapshot and their admission. `linkUnobserved`: a link root
2040
+ * whose status is "unobserved" (no snapshot at either end, or a top it does not admit): X7, not deferred. Undefined when the
2041
+ * dispatch has no perimeter or none of it remains beyond W.
2042
+ * Cross-repo P3c.6 (D26): W's dependency targets are read again at return through the union (`dependencyTargets`) with the
2043
+ * frozen admission; an admitted target the producer added during the dispatch (a `node_modules` link, a declared edge) and
2044
+ * no seed covers is snapshotted (hardened) within the remaining deferral bound and frozen with the links, so router_verify
2045
+ * (S11) compares it with its return-time state; one not observed in time sets `linkUnobserved` (verified at once, X7). It is
2046
+ * never a perimeter seed: P stays fixed at dispatch for writer attribution (I4, I13). An unadmitted new target is not
2047
+ * snapshotted.
2048
+ */
2049
+ const perimeterAtReturn = async (
2050
+ planned: { name?: string; snapshots: PerimeterSnapshots; admission?: DispatchPerimeter["admission"] } | undefined,
2051
+ snapshot: TreeSnapshot | undefined,
2052
+ base: string,
2053
+ // P3c.6 (D26): the deferral bound, what remains of it bounds the snapshots of the dependencies added during the dispatch.
2054
+ // Absent: none is read (as before P3c.6).
2055
+ deadline?: Deadline,
2056
+ ): Promise<{
2057
+ observation: PerimeterObservation;
2058
+ workingSet: FrozenPerimeter["workingSet"];
2059
+ links: FrozenPerimeter["links"];
2060
+ linkUnobserved: boolean;
2061
+ /** P3c.4 (SD-P3c-9): the dispatch's admission (planPerimeter), frozen with the perimeter. Absent: none recorded. */
2062
+ admission?: DispatchPerimeter["admission"];
2063
+ /** P3 QA-1 M4: the unadmitted dependency targets the producer added during the dispatch (covering only). Absent: none. */
2064
+ unadmitted?: readonly string[];
2065
+ } | undefined> => {
2066
+ const observation = await perimeterAtGate(planned, snapshot, base, undefined, { discover: false });
2067
+ if (planned === undefined || observation === undefined) return undefined;
2068
+ const wKey = perimeterKey(observation.w.root);
2069
+ const workingSet = new Map<string, FrozenPerimeter["workingSet"][number]>();
2070
+ const links = new Map<string, FrozenPerimeter["links"][number]>();
2071
+ let linkUnobserved = false;
2072
+ let unadmitted: readonly string[] = [];
2073
+ for (const { entry, before, now } of planned.snapshots) {
2074
+ const seed = entry.seed;
2075
+ const fixed = seed.fixed;
2076
+ // As perimeterAtGate names the root: its known top level when admitted, else where it was planned (a fixed root: there).
2077
+ const known = fixed === undefined ? now?.root ?? before?.root : undefined;
2078
+ const refused = known !== undefined && seed.admit !== undefined && !seed.admit(known);
2079
+ const root = known !== undefined && !refused ? known : seed.at;
2080
+ const key = perimeterKey(root);
2081
+ // W's own repository is W's snapshot (a fixed placeholder at W's path is kept, as perimeterAtGate keeps it).
2082
+ if (fixed === undefined && key === wKey) continue;
2083
+ // P2e QA-1 #1: a working-set root past the cap (fixed) is still a consumer candidate, as perimeterAtGate scans it.
2084
+ if (seed.origin === "working-set" && !workingSet.has(key)) {
2085
+ workingSet.set(key, { root, ...(seed.name !== undefined ? { name: seed.name } : {}) });
2086
+ }
2087
+ // P3c.4 (SD-P3c-2, S11): a dependency of W, a package link target or a declared edge's repository (origin "link" or
2088
+ // "edge", or a working-set root `linked` or `edged`), is frozen and observed again at router_verify, where W's
2089
+ // dependency targets are read through the same union (`dependencyTargets`, F1).
2090
+ const isDependency = seed.origin === "link" || seed.linked === true || seed.origin === "edge" || seed.edged === true;
2091
+ if (fixed !== undefined) {
2092
+ // P2e QA-1 #1: a dependency past the cap was never observed: not deferred (X7). An unadmitted one is never observed.
2093
+ if (fixed === "unobserved" && isDependency) linkUnobserved = true;
2094
+ continue;
2095
+ }
2096
+ if (!isDependency) continue;
2097
+ if (refused || before === undefined || now === undefined || now.root === undefined) {
2098
+ linkUnobserved = true;
2099
+ continue;
2100
+ }
2101
+ if (!links.has(key)) {
2102
+ links.set(key, {
2103
+ at: seed.at,
2104
+ root,
2105
+ name: seed.name ?? basename(root),
2106
+ head: now.head,
2107
+ fingerprint: now.fingerprint,
2108
+ ...(seed.admit !== undefined ? { admit: seed.admit } : {}),
2109
+ });
2110
+ }
2111
+ }
2112
+ // P3c.6 (D26): a dependency target the producer added during the dispatch, frozen with the links so that router_verify (S11)
2113
+ // compares it with its state at return; never a seed (I13: P stays the dispatch's for writer attribution, I4). Not read when
2114
+ // the dispatch is verified at once anyway, without a frozen admission (an entry planned before P3c.4), or without a bound.
2115
+ // The same read freezes which dispatch-time dependencies W no longer declares (M3) and the unadmitted new targets (M4).
2116
+ if (!linkUnobserved && planned.admission !== undefined && deadline !== undefined) {
2117
+ // What covers a target at router_verify: the roots frozen here (the perimeter's, fixed ones where they were planned).
2118
+ const covering = [
2119
+ ...observation.roots.map(root => root.root),
2120
+ ...planned.snapshots.map(({ entry }) => entry.seed.at),
2121
+ ...[...links.values()].map(link => link.root),
2122
+ ];
2123
+ // P3 QA-1 m2: P holds at most PERIMETER_MAX snapshotted roots, W and the dispatch's observed roots included.
2124
+ const observedSeeds = planned.snapshots.filter(({ entry }) => entry.seed.fixed === undefined).length;
2125
+ const room = Math.max(0, PERIMETER_MAX - 1 - observedSeeds);
2126
+ const added = await dependenciesAddedAtReturn(base, planned.admission, covering, [base, observation.w.root], deadline, room);
2127
+ if (added.unobserved) linkUnobserved = true;
2128
+ // P3 QA-1 M3: a dispatch-time dependency W no longer declares at return (the producer removed or retargeted it) is not an
2129
+ // input of the change: frozen as removed, router_verify skips it (no "no longer links", no re-observation).
2130
+ const atReturn = added.targets;
2131
+ if (atReturn !== undefined) {
2132
+ for (const [key, link] of links) {
2133
+ if (!atReturn.some(target => depthBelow(target, link.root) >= 0)) links.set(key, { ...link, removedAtReturn: true });
2134
+ }
2135
+ }
2136
+ for (const link of added.links) {
2137
+ const key = perimeterKey(link.root);
2138
+ if (key !== wKey && !links.has(key)) links.set(key, link);
2139
+ }
2140
+ if (added.unadmitted !== undefined) unadmitted = added.unadmitted;
2141
+ }
2142
+ return {
2143
+ observation,
2144
+ workingSet: [...workingSet.values()],
2145
+ links: [...links.values()],
2146
+ linkUnobserved,
2147
+ ...(planned.admission !== undefined ? { admission: planned.admission } : {}),
2148
+ ...(unadmitted.length > 0 ? { unadmitted } : {}),
2149
+ };
2150
+ };
2151
+
1464
2152
  /**
1465
2153
  * The producer's change since the dispatch: the gate-time snapshot (bounded by `deadline`), the
1466
2154
  * commits since the dispatch head, and the store's delta. Shared by prepareVerification and the
@@ -1472,8 +2160,13 @@ export function createVerificationWiring(deps: {
1472
2160
  childID: string,
1473
2161
  cwd: string | undefined,
1474
2162
  deadline: Deadline | undefined,
2163
+ observePerimeter = true,
1475
2164
  ): Promise<Omit<PreparedVerification, "reference">> => {
1476
2165
  const base = resolve(directory, cwd || ".");
2166
+ // QA-1 F9: the perimeter's gate snapshots start now, concurrently with W's own (never rejects).
2167
+ const perimeterSnapshots = observePerimeter
2168
+ ? perimeterSnapshotsAtGate(store, id, deadline).catch(() => undefined)
2169
+ : Promise.resolve(undefined);
1477
2170
  const controller = new AbortController();
1478
2171
  const onAbort = (): void => controller.abort();
1479
2172
  deadline?.signal.addEventListener("abort", onAbort, { once: true });
@@ -1509,13 +2202,74 @@ export function createVerificationWiring(deps: {
1509
2202
  deadline?.signal.removeEventListener("abort", onAbort);
1510
2203
  controller.abort();
1511
2204
  }
1512
- const committed = await committedSinceDispatch(store.baselineSnapshot(id), snapshot, deadline);
2205
+ const before = store.baselineSnapshot(id);
2206
+ // I7 (P0.2, S9): did the tree switch branch since the dispatch? Decided from the cheap head state, before the commit diff:
2207
+ // a diff across branches would be the other branch's net change, verified as the producer's, and must never reach the store.
2208
+ let headSwitch: string | undefined;
2209
+ let headRead = false;
2210
+ let gateHead: HeadState | undefined;
2211
+ const baselineHead = store.baselineHead(id);
2212
+ if (baselineHead !== undefined) {
2213
+ const bound = deadline ? deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS) : GRADE_SNAPSHOT_TIMEOUT_MS;
2214
+ if (bound > 0 && deadline?.signal.aborted !== true) {
2215
+ const signalOpt = deadline ? { signal: deadline.signal } : {};
2216
+ const startRead = await withTimeout(baselineHead, bound, "dispatch head").catch(() => undefined);
2217
+ // QA2 F3: "none" = no repository or an unborn HEAD at dispatch (e.g. the producer ran git init or made the first
2218
+ // commit): there was no branch to switch from. Unknown (a failed or late read): the dispatch snapshot's head and branch
2219
+ // stand in when it recorded them (no root or reflog then: the name rule decides).
2220
+ const startHead: HeadState | "none" | undefined = startRead === "none" || startRead !== undefined
2221
+ ? startRead
2222
+ : before !== undefined && before.branch !== undefined
2223
+ ? { root: before.root ?? base, head: before.head, branch: before.branch }
2224
+ : undefined;
2225
+ const nowHead = await withTimeout(
2226
+ readHeadState(base, { ...signalOpt, timeoutMs: bound, lowPriority: configuredLowPriority() }),
2227
+ bound,
2228
+ "gate head",
2229
+ ).catch(() => undefined);
2230
+ if (nowHead !== undefined) {
2231
+ headRead = true;
2232
+ gateHead = nowHead;
2233
+ if (startHead === "none") {
2234
+ // No branch existed at dispatch: nothing to compare.
2235
+ } else if (startHead === undefined) {
2236
+ // The dispatch-time head is unknown (an unreadable or late read, and no snapshot head): fail closed.
2237
+ 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.`;
2238
+ } else {
2239
+ let window: ReflogEntry[] | undefined;
2240
+ if (startHead.reflog !== undefined && nowHead.reflog !== undefined && nowHead.reflog >= startHead.reflog) {
2241
+ window = await readReflogWindow(nowHead.root, nowHead.reflog - startHead.reflog, {
2242
+ ...signalOpt, timeoutMs: bound, lowPriority: configuredLowPriority(),
2243
+ });
2244
+ }
2245
+ // The reflog grew but its entries cannot be read: a checkout or reset cannot be ruled out (fail closed).
2246
+ const unreadWindow = window === undefined && startHead.reflog !== undefined && nowHead.reflog !== undefined
2247
+ && nowHead.reflog > startHead.reflog;
2248
+ const move = unreadWindow
2249
+ ? { kind: "rewritten" as const, detail: "the reflog entries could not be read" }
2250
+ : treeMove(startHead, nowHead, window);
2251
+ if (move !== undefined) headSwitch = treeMoveReason(nowHead.root, startHead, nowHead, move, "during the dispatch");
2252
+ }
2253
+ }
2254
+ }
2255
+ }
2256
+ // Head state unavailable at the gate (or no head reader for this dispatch): the snapshot comparison, when both exist.
2257
+ const snapshotSwitch = !headRead && before !== undefined && snapshot !== undefined && branchSwitched(before, snapshot)
2258
+ ? branchSwitchReason(snapshot.root ?? base, before, snapshot, "during the dispatch")
2259
+ : undefined;
2260
+ const branchSwitch = headSwitch ?? snapshotSwitch;
2261
+ // B8: on a switch the commit diff is not run; "unavailable" keeps the whole change set unavailable (the gate refuses anyway).
2262
+ const committed = branchSwitch !== undefined ? "unavailable" as const : await committedSinceDispatch(before, snapshot, deadline);
1513
2263
  const contaminatedBy = store.snapshotContaminatedBy(id);
2264
+ const perimeter = await perimeterAtGate(await perimeterSnapshots, snapshot, base, deadline);
1514
2265
  return {
1515
2266
  ...store.delta(id, childID, snapshot, base, committed),
1516
2267
  snapshot,
1517
2268
  concurrentDispatches: store.concurrentDispatches(id, snapshot?.root),
1518
2269
  ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
2270
+ ...(branchSwitch !== undefined ? { branchSwitch } : {}),
2271
+ ...(gateHead !== undefined ? { head: gateHead } : {}),
2272
+ ...(perimeter !== undefined ? { perimeter } : {}),
1519
2273
  };
1520
2274
  };
1521
2275
 
@@ -1580,39 +2334,100 @@ export function createVerificationWiring(deps: {
1580
2334
  * for each testsPass check, with the command and cwd the gate would use. The first S6 result wins;
1581
2335
  * a command outside the allowlist is S6 too (the gate reports it unverifiable). Bounded by the
1582
2336
  * deferred-finish deadline; an unfinished plan counts as impossible (raises the risk, never lowers it).
2337
+ *
2338
+ * Cross-repo P2e: with `placements` (index-aligned with `dod.checks`), each testsPass check is planned at its placement's
2339
+ * cwd; a placement with `scope === "full"` is not planned (it runs in full); a foreign placement is S6
2340
+ * (attribution-unavailable), unless it is a cross-link plan (Y6, below). A check without a placement, or no placements at
2341
+ * all: the base dir, as before.
2342
+ *
2343
+ * P2e QA-1 #6: with `fullScope` (OD-P2e-2) no testsPass check is planned as affected (each runs in full); when every testsPass
2344
+ * check runs in full, the result is the neutral FULL_SCOPE plan, never the unfinished S6 one.
2345
+ *
2346
+ * Cross-repo P3a (Y6): a foreign testsPass with an explicit scope=affected is planned as the gate runs it (deterministic.ts):
2347
+ * at its placement's cwd, with `crossLinkRoot` = W's root (`changeRoot`, else the base dir, as the gate falls back) and the
2348
+ * consumer link spellings of it (perimeter.ts crossLinkAliases), the changed paths made absolute against that root (F7).
2349
+ * A scopable cross-link plan then raises no S6; a runner the link does not reach (jest, pytest, another vitest major) still
2350
+ * does. Any other foreign placement stays S6 (attribution-unavailable).
1583
2351
  */
1584
2352
  const staticScoping = async (
1585
2353
  dod: DoD,
1586
2354
  cwd: string | undefined,
1587
2355
  changedFiles: readonly ChangedPath[],
1588
2356
  deadline: Deadline,
1589
- ): Promise<StaticScoping> => {
2357
+ placements?: readonly (CheckPlacement | undefined)[],
2358
+ fullScope?: boolean,
2359
+ changeRoot?: string,
2360
+ ): Promise<StaticScoping | FullScopePlan> => {
1590
2361
  const unfinished: StaticScoping = { unverifiable: true, code: "search-failed", reason: STATIC_SCOPING_UNFINISHED_REASON };
1591
2362
  const budget = resolveVerifyBudget(getConfig());
1592
- const at = resolveBaseDir(cwd, directory);
2363
+ const base = resolveBaseDir(cwd, directory);
2364
+ // Y6: W's root as the gate takes it (gate.ts: artefact.changeRoot ?? effectiveBaseDir), and (F7) the changed paths absolute
2365
+ // against it, computed once and only for a cross-link plan.
2366
+ const linkRoot = changeRoot ?? base;
2367
+ let absoluteChanged: readonly ChangedPath[] | undefined;
2368
+ const linkChangedFiles = (): readonly ChangedPath[] => (absoluteChanged ??= changedFiles.map(file => ({
2369
+ ...file,
2370
+ path: isAbsolute(file.path) ? file.path : resolve(linkRoot, file.path),
2371
+ ...(file.previousPath !== undefined
2372
+ ? { previousPath: isAbsolute(file.previousPath) ? file.previousPath : resolve(linkRoot, file.previousPath) }
2373
+ : {}),
2374
+ })));
1593
2375
  const plans: StaticScoping[] = [];
1594
- for (const check of dod.checks) {
2376
+ let ranFull = false;
2377
+ for (const [index, check] of dod.checks.entries()) {
1595
2378
  if (check.kind !== "testsPass") continue;
1596
2379
  const command = resolveRepoCommand(check, "testsPass", undefined);
1597
2380
  if (!isCommandAllowed(command, DEFAULT_ALLOWLIST)) {
1598
2381
  plans.push({ unverifiable: true, code: "unsupported-command", reason: `command not allowlisted: ${scrubText(command)}` });
1599
2382
  continue;
1600
2383
  }
2384
+ const placement = placements?.[index];
2385
+ if (fullScope === true || placement?.scope === "full") {
2386
+ ranFull = true;
2387
+ continue;
2388
+ }
2389
+ // Y6: only an explicit scope=affected crosses the link (deterministic.ts runDeterministic); any other foreign check is S6.
2390
+ const crossLink = placement?.foreign === true && placement.scope === "affected";
2391
+ if (placement?.foreign === true && !crossLink) {
2392
+ plans.push({
2393
+ unverifiable: true,
2394
+ code: "attribution-unavailable",
2395
+ reason: "the check runs in another repository, whose changes are not attributed to this dispatch",
2396
+ });
2397
+ continue;
2398
+ }
2399
+ const at = placement?.cwd ?? base;
1601
2400
  const ms = deadline.remaining();
1602
2401
  if (ms <= 0) {
1603
2402
  plans.push(unfinished);
1604
2403
  continue;
1605
2404
  }
1606
2405
  try {
1607
- plans.push(await withTimeout(
1608
- planStaticScoping({ command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam }),
1609
- ms,
1610
- "static scoping",
1611
- ));
2406
+ const input: StaticScopingInput = crossLink
2407
+ ? {
2408
+ command,
2409
+ cwd: at,
2410
+ changedFiles: linkChangedFiles(),
2411
+ budget: { maxWorkers: budget.maxWorkers },
2412
+ fs: fsSeam,
2413
+ crossLinkRoot: linkRoot,
2414
+ // Fail-soft, as the gate's alias provider (deterministic.ts crossLinkTarget): an error gives no aliases.
2415
+ ...(() => {
2416
+ try {
2417
+ return { crossLinkAliases: crossLinkAliases(at, linkRoot) };
2418
+ } catch {
2419
+ return {};
2420
+ }
2421
+ })(),
2422
+ }
2423
+ : { command, cwd: at, changedFiles, budget: { maxWorkers: budget.maxWorkers }, fs: fsSeam };
2424
+ plans.push(await withTimeout(planStaticScoping(input), ms, "static scoping"));
1612
2425
  } catch {
1613
2426
  plans.push(unfinished);
1614
2427
  }
1615
2428
  }
2429
+ // P2e QA-1 #6: every testsPass check runs in full: the neutral plan (never the unfinished S6 one).
2430
+ if (plans.length === 0 && ranFull) return FULL_SCOPE_PLAN;
1616
2431
  return plans.find(p => "unverifiable" in p) ?? plans[0] ?? unfinished;
1617
2432
  };
1618
2433
 
@@ -1630,7 +2445,43 @@ export function createVerificationWiring(deps: {
1630
2445
  let risk: RiskAssessment = unattributedRisk();
1631
2446
  let deferred = false;
1632
2447
  try {
1633
- const change = await observeChange(store, input.dispatchID, input.producerSessionID, input.cwd, deadline);
2448
+ // Cross-repo P2e.5 (X4): a dispatch with a perimeter has it observed in return mode, its snapshots started now so they run
2449
+ // concurrently with W's own (never rejects; bounded by the same DEFERRED_FINISH_MS deadline). Without one: nothing extra.
2450
+ const changeCwd = input.captureRoot ?? input.cwd;
2451
+ const perimeterSnapshots = store.perimeterOf(input.dispatchID) !== undefined
2452
+ ? perimeterSnapshotsAtGate(store, input.dispatchID, deadline).catch(() => undefined)
2453
+ : undefined;
2454
+ const change = await observeChange(store, input.dispatchID, input.producerSessionID, changeCwd, deadline, false);
2455
+ // I7 (P0.2): a branch switch during the dispatch is never deferred: a handle could verify the other branch later. The
2456
+ // caller's required gate refuses it now (its own observeChange sees the switch). Before the no-change shortcut below.
2457
+ if (change.branchSwitch !== undefined) return { deferred: false, reason: "branch-switched", detail: change.branchSwitch };
2458
+ // Cross-repo P2e.5 (X5, X7): the perimeter as it was at return is frozen for router_verify, unless it cannot be: I4 already
2459
+ // holds (a root changed while an unattributable writer ran), or a link target was not observed. The caller's required
2460
+ // gate then verifies the dispatch now. Before the no-change shortcut below.
2461
+ let frozen: Awaited<ReturnType<typeof perimeterAtReturn>>;
2462
+ if (perimeterSnapshots !== undefined) {
2463
+ const base = resolve(directory, changeCwd || ".");
2464
+ // P3c.6 (D26): a dependency added during the dispatch is snapshotted within what remains of this deadline.
2465
+ frozen = await perimeterAtReturn(await perimeterSnapshots, change.snapshot, base, deadline);
2466
+ const writers = change.unattributedWriters ?? [];
2467
+ if (frozen !== undefined && perimeterChangeReasons({ perimeter: frozen.observation, unattributedWriters: [...writers] }, base).length > 0) {
2468
+ return {
2469
+ deferred: false,
2470
+ reason: "cross-repo",
2471
+ detail: "a repository of the perimeter changed during the dispatch while an unattributable writer ran; verified synchronously",
2472
+ };
2473
+ }
2474
+ if (frozen?.linkUnobserved === true) {
2475
+ return { deferred: false, reason: "cross-repo", detail: "a linked repository could not be observed within the deferral bound; verified synchronously" };
2476
+ }
2477
+ }
2478
+ // P2e.5 (X3): the frozen pins settle only once the registration succeeded (below); never rejects.
2479
+ let settlePins: (pins: readonly LinkPin[]) => void = () => undefined;
2480
+ const frozenPins = frozen !== undefined
2481
+ ? new Promise<readonly LinkPin[]>(settle => {
2482
+ settlePins = settle;
2483
+ })
2484
+ : undefined;
1634
2485
  // QA-2.4-10: an attributed empty change set is passed by the required gate with no process
1635
2486
  // (section 1.5-6): nothing to defer. The caller runs that gate, with the same outcome.
1636
2487
  // QA-G-1: only for a testsPass-only DoD. Any other check (build, lint, run, fileExists,
@@ -1638,7 +2489,7 @@ export function createVerificationWiring(deps: {
1638
2489
  // DoD stays deferred as a whole, with the attributed empty change set (risk low).
1639
2490
  if (
1640
2491
  change.changeBaseline === "available" && change.changedFiles.length === 0 && !deadline.signal.aborted &&
1641
- noChangeGateSpawnsNothing(input.dod)
2492
+ noChangeGateSpawnsNothing(input.dod, { placements: input.placements, fullScope: input.fullScope })
1642
2493
  ) {
1643
2494
  return { deferred: false, reason: "no-change", detail: "the producer changed no file" };
1644
2495
  }
@@ -1652,7 +2503,10 @@ export function createVerificationWiring(deps: {
1652
2503
  ...(f.previousPath !== undefined ? { previousPath: f.previousPath } : {}),
1653
2504
  }));
1654
2505
  changedFiles = paths;
1655
- const scopingPlan = await staticScoping(input.dod, input.cwd, paths, deadline);
2506
+ // Y6: W's root (the snapshot's git top) is the cross-link root of a foreign scope=affected testsPass.
2507
+ const scopingPlan = await staticScoping(
2508
+ input.dod, input.cwd, paths, deadline, input.placements, input.fullScope, change.snapshot?.root,
2509
+ );
1656
2510
  risk = assessRisk({ changedFiles: paths, reference: referenceCaptured, producerTier, scopingPlan, root: change.snapshot?.root });
1657
2511
  // QA-2.4-8: the drift baseline is taken BEFORE the result is released (fs reads only, under
1658
2512
  // the same DEFERRED_FINISH_MS bound). An edit that lands right after the return is then
@@ -1669,6 +2523,20 @@ export function createVerificationWiring(deps: {
1669
2523
  description: input.description,
1670
2524
  cwd: resolveBaseDir(input.cwd, directory),
1671
2525
  root: change.snapshot?.root,
2526
+ // I7 (P0.2, S12): the checkout the producer returned on; router_verify refuses a tree on another branch by then.
2527
+ // B4/B12: from the cheap head state the gate read (root and reflog count too); the snapshot's only without one.
2528
+ ...(change.head !== undefined
2529
+ ? {
2530
+ returnedTree: {
2531
+ root: change.head.root,
2532
+ head: change.head.head,
2533
+ branch: change.head.branch,
2534
+ ...(change.head.reflog !== undefined ? { reflog: change.head.reflog } : {}),
2535
+ },
2536
+ }
2537
+ : change.snapshot !== undefined
2538
+ ? { returnedTree: { head: change.snapshot.head, branch: change.snapshot.branch } }
2539
+ : {}),
1672
2540
  dispatchedAt: input.dispatchedAt,
1673
2541
  dod: input.dod,
1674
2542
  reference,
@@ -1679,12 +2547,52 @@ export function createVerificationWiring(deps: {
1679
2547
  // adds the caveats to its verdict.
1680
2548
  ...(change.concurrentDispatches !== undefined && change.concurrentDispatches > 0 ? { concurrentDispatches: change.concurrentDispatches } : {}),
1681
2549
  ...(change.contaminatedBy !== undefined ? { contaminatedBy: change.contaminatedBy } : {}),
2550
+ // I5 (P0.3): router_verify's gate adds the caveat to a pass on an empty change set.
2551
+ ...(change.unattributedWriters !== undefined && change.unattributedWriters.length > 0 ? { unattributedWriters: change.unattributedWriters } : {}),
2552
+ // Cross-repo P2e.5: the perimeter frozen at return (router_verify gates with it) and the dispatch's placements.
2553
+ ...(frozen !== undefined && frozenPins !== undefined
2554
+ ? {
2555
+ perimeter: {
2556
+ observation: frozen.observation,
2557
+ // 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).
2558
+ linkBase: resolve(directory, changeCwd || "."),
2559
+ workingSet: frozen.workingSet,
2560
+ links: frozen.links,
2561
+ pins: frozenPins,
2562
+ // P3c.4 (SD-P3c-9): the admission the dispatch's planPerimeter read W's links and edges with; router_verify reads
2563
+ // W's dependency targets again through it (the registry freezes a copy).
2564
+ ...(frozen.admission !== undefined ? { admission: frozen.admission } : {}),
2565
+ ...(frozen.unadmitted !== undefined ? { unadmittedAtReturn: frozen.unadmitted } : {}),
2566
+ },
2567
+ }
2568
+ : {}),
2569
+ ...(input.placements !== undefined ? { placements: input.placements } : {}),
1682
2570
  });
1683
2571
  if (!reg.ok) {
2572
+ // P2e.5 (X3): nothing reads it; the dispatch's own pins are left untouched for the required gate.
2573
+ settlePins([]);
1684
2574
  // QA-2.4-4: never a delegation without a verdict path: the caller runs the required gate.
1685
2575
  logger.warn("[verify] deferred delegation not registered; verifying synchronously", { code: reg.code, detail: reg.detail });
1686
2576
  return { deferred: false, reason: "unregistered", detail: `${reg.code}: ${reg.detail}` };
1687
2577
  }
2578
+ if (frozen !== undefined) {
2579
+ // P2e.5 (X3): the dispatch's link pins are taken now, before store.clear (below), then freed; the entry keeps the SAME
2580
+ // array (pinNow admission is keyed by its identity). Never rejects: a failure is [].
2581
+ const dispatchID = input.dispatchID;
2582
+ void linkPinsAtGate(store, dispatchID, undefined).then(
2583
+ pins => {
2584
+ freeLinkPins(dispatchID, pins);
2585
+ settlePins(pins);
2586
+ },
2587
+ () => {
2588
+ freeLinkPins(dispatchID, []);
2589
+ settlePins([]);
2590
+ },
2591
+ );
2592
+ } else if (perimeterSnapshots !== undefined) {
2593
+ // A perimeter with nothing to freeze beyond W: no gate takes this dispatch's pins any more.
2594
+ freeLinkPins(input.dispatchID, []);
2595
+ }
1688
2596
  deferred = true;
1689
2597
  // #84 P2.1 (handoff 24, R7): the budget captured at return travels with the handle to `router_verify`.
1690
2598
  if (input.budget !== undefined) {
@@ -1787,6 +2695,66 @@ export function createVerificationWiring(deps: {
1787
2695
  }
1788
2696
  };
1789
2697
 
2698
+ /**
2699
+ * Cross-repo P2e.4a (S11): a frozen link target observed again at router_verify, hardened as the perimeter snapshots it
2700
+ * (perimeterSnapshotsAtGate), bounded by the claim deadline. Undefined when it cannot be taken in time. Never throws.
2701
+ */
2702
+ const hardenedSnapshotFor = async (at: string, deadline: Deadline, lowPriority: boolean): Promise<TreeSnapshot | undefined> => {
2703
+ const controller = new AbortController();
2704
+ const onAbort = (): void => controller.abort();
2705
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
2706
+ try {
2707
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2708
+ if (bound <= 0 || controller.signal.aborted) return undefined;
2709
+ return await withTimeout(snapshotTree(at, controller.signal, { lowPriority, hardened: true }), bound, "router_verify link fingerprint");
2710
+ } catch {
2711
+ return undefined;
2712
+ } finally {
2713
+ deadline.signal.removeEventListener("abort", onAbort);
2714
+ controller.abort();
2715
+ }
2716
+ };
2717
+
2718
+ /**
2719
+ * Cross-repo P2e.4b: the first frozen check placement whose cwd no longer resolves to the same repository since the producer
2720
+ * returned: its real path is not its (canonical) cwd any more (a junction swapped under it, or gone), or its git top level is
2721
+ * not the frozen `top`. The reason names it ("nothing ran"); undefined when every placement still resolves as it did.
2722
+ */
2723
+ const placementDriftOf = async (entry: PendingEntry): Promise<{ readonly kind: "drift" | "unchecked"; readonly reason: string } | undefined> => {
2724
+ const placements = entry.placements;
2725
+ if (placements === undefined) return undefined;
2726
+ // Per placement: "same", "drift", or the code of a transient error (P2e QA-1 #5b: EPERM, EBUSY, EACCES…: not a drift).
2727
+ const states = await Promise.all(placements.map(async (placement): Promise<string> => {
2728
+ if (placement === undefined) return "same";
2729
+ let real: string;
2730
+ try {
2731
+ real = await realpath(placement.cwd);
2732
+ } catch (err) {
2733
+ const code = typeof err === "object" && err !== null && "code" in err ? String((err as { code: unknown }).code) : "unknown";
2734
+ // The directory is gone (or a file now stands in its path): it no longer resolves.
2735
+ return code === "ENOENT" || code === "ENOTDIR" ? "drift" : code;
2736
+ }
2737
+ if (perimeterKey(real) !== perimeterKey(placement.cwd)) return "drift";
2738
+ const top = gitTopOf(placement.cwd);
2739
+ const moved = top === undefined || placement.top === undefined
2740
+ ? top !== placement.top
2741
+ : perimeterKey(top) !== perimeterKey(placement.top);
2742
+ return moved ? "drift" : "same";
2743
+ }));
2744
+ const label = (index: number): string =>
2745
+ `check ${index + 1} (${entry.dod?.checks?.[index]?.kind ?? "check"}) cwd=${placements[index]?.cwd ?? ""}`;
2746
+ const drifted = states.indexOf("drift");
2747
+ if (drifted >= 0) {
2748
+ return { kind: "drift", reason: `${label(drifted)} no longer resolves to the same repository since the producer returned; nothing ran` };
2749
+ }
2750
+ const unchecked = states.findIndex(state => state !== "same");
2751
+ if (unchecked < 0) return undefined;
2752
+ return {
2753
+ kind: "unchecked",
2754
+ reason: `${label(unchecked)} could not be checked since the producer returned (${states[unchecked]}); nothing ran`,
2755
+ };
2756
+ };
2757
+
1790
2758
  /**
1791
2759
  * 2.4.3a, section 1.5-18: the producer's files now against their digests right after it returned.
1792
2760
  * "unchecked" whenever either side is missing (no change set, no stored digests, a digest that
@@ -1807,6 +2775,21 @@ export function createVerificationWiring(deps: {
1807
2775
  readonly drift: DriftCheck;
1808
2776
  /** R11 root: the registered one, else the current tree's. */
1809
2777
  readonly root: string | undefined;
2778
+ /**
2779
+ * Cross-repo P2e.4a (S11): the frozen link targets that changed, or could not be observed again, since the producer
2780
+ * returned. Absent: no frozen perimeter, or every link is as it was at return.
2781
+ */
2782
+ readonly linkDrift?: readonly { readonly name: string; readonly root: string; readonly why: "changed" | "unobserved" }[];
2783
+ /**
2784
+ * Cross-repo P2e.4b: the first frozen check placement whose cwd no longer resolves to the same repository (the gate then
2785
+ * runs nothing). Absent: no placements, or all still resolve as at return.
2786
+ */
2787
+ readonly placementDrift?: string;
2788
+ /**
2789
+ * P2e QA-1 #5b: the first frozen check placement whose cwd could not be checked now (a transient filesystem error, not a
2790
+ * missing directory): nothing runs, and the handle stays open (retryable). Absent: every placement could be checked.
2791
+ */
2792
+ readonly placementUnchecked?: string;
1810
2793
  }
1811
2794
 
1812
2795
  /** One claimed entry after its gate: a final result, or the raw gate result still to be judged. */
@@ -1814,26 +2797,271 @@ export function createVerificationWiring(deps: {
1814
2797
  | { readonly kind: "final"; readonly result: VerificationResult }
1815
2798
  | { readonly kind: "gate"; readonly res: GateResult; readonly retryable: boolean; readonly strict: boolean };
1816
2799
 
2800
+ /**
2801
+ * Cross-repo P3c.4 (SD-P3c-8): W's dependency targets (`dependencyTargets`) read at one router_verify call, keyed by W's
2802
+ * comparison key and the frozen admission it was read with: the call's entries of one W read them once.
2803
+ */
2804
+ type DependencyMemo = Map<string, DependencyTargets | undefined>;
2805
+
1817
2806
  /** 2.4.3a P0 from the pending entry: stored change set and reference, current tree, drift. */
1818
2807
  const prepareClaim = async (
1819
2808
  entry: PendingEntry,
1820
2809
  deadline: Deadline,
1821
2810
  snapshots: Map<string, Promise<TreeSnapshot | undefined>>,
1822
2811
  lowPriority: boolean,
2812
+ dependencies: DependencyMemo = new Map(),
1823
2813
  ): Promise<ClaimPreparation> => {
1824
2814
  let snapshot = snapshots.get(entry.cwd);
1825
2815
  if (snapshot === undefined) {
1826
2816
  snapshot = snapshotFor(entry.cwd, deadline, lowPriority);
1827
2817
  snapshots.set(entry.cwd, snapshot);
1828
2818
  }
1829
- const [reference, drift, tree] = await Promise.all([
2819
+ const atReturn = entry.returnedTree;
2820
+ // B4: the branch check reads the cheap head state, not the full tree snapshot (slow, and unavailable for large dirty
2821
+ // trees and submodules). Read in parallel with the rest, bounded by the deadline.
2822
+ const readNowHead = async (): Promise<HeadState | undefined> => {
2823
+ if (atReturn === undefined) return undefined;
2824
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2825
+ if (bound <= 0 || deadline.signal.aborted) return undefined;
2826
+ return withTimeout(
2827
+ readHeadState(entry.cwd, { signal: deadline.signal, timeoutMs: bound, lowPriority }),
2828
+ bound,
2829
+ "router_verify head",
2830
+ ).catch(() => undefined);
2831
+ };
2832
+ const [reference, drift, tree, nowHead, placementDrift] = await Promise.all([
1830
2833
  // The same bound as the store's reference(id, signal): a capture still pending at the deadline
1831
2834
  // is "no reference (gate budget)".
1832
2835
  untilAborted<ReferenceState>(entry.reference, deadline.signal, () => ({ kind: "none", reason: REFERENCE_NONE.gateBudget })),
1833
2836
  checkDrift(entry, deadline),
1834
2837
  snapshot,
2838
+ readNowHead(),
2839
+ // Cross-repo P2e.4b: no placements, no work (resolves undefined at once).
2840
+ placementDriftOf(entry),
1835
2841
  ]);
1836
2842
  const changed = entry.changedFiles;
2843
+ const root = entry.root ?? tree?.root;
2844
+ // I7 (P0.2, S12): the tree must still be on the checkout the producer returned on. A branch recorded at return with no
2845
+ // current head state to compare is refused too ("cannot confirm": retryable); nothing recorded: no check.
2846
+ let branchSwitch: string | undefined;
2847
+ if (atReturn !== undefined) {
2848
+ if (nowHead === undefined) {
2849
+ if (atReturn.branch !== undefined) branchSwitch = branchUnconfirmedReason(atReturn.root ?? root ?? entry.cwd);
2850
+ } else if (atReturn.branch === undefined) {
2851
+ // Registered without a branch (an unknown one): any HEAD move is a switch (branch.ts branchSwitched).
2852
+ if (branchSwitched(atReturn, nowHead)) {
2853
+ branchSwitch = branchSwitchReason(nowHead.root, atReturn, nowHead, "since the producer returned");
2854
+ }
2855
+ } else {
2856
+ const before: HeadState = {
2857
+ root: atReturn.root ?? nowHead.root,
2858
+ head: atReturn.head,
2859
+ branch: atReturn.branch,
2860
+ ...(atReturn.reflog !== undefined ? { reflog: atReturn.reflog } : {}),
2861
+ };
2862
+ let window: ReflogEntry[] | undefined;
2863
+ const comparable = before.reflog !== undefined && nowHead.reflog !== undefined && nowHead.reflog >= before.reflog;
2864
+ if (comparable) {
2865
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2866
+ window = bound > 0 && !deadline.signal.aborted
2867
+ ? await withTimeout(
2868
+ readReflogWindow(nowHead.root, (nowHead.reflog ?? 0) - (before.reflog ?? 0), {
2869
+ signal: deadline.signal, timeoutMs: bound, lowPriority,
2870
+ }),
2871
+ bound,
2872
+ "router_verify reflog",
2873
+ ).catch(() => undefined)
2874
+ : undefined;
2875
+ }
2876
+ // The reflog grew but its entries cannot be read: a checkout or reset cannot be ruled out (fail closed).
2877
+ const unreadWindow = window === undefined && before.reflog !== undefined && nowHead.reflog !== undefined
2878
+ && nowHead.reflog > before.reflog;
2879
+ const move = unreadWindow
2880
+ ? { kind: "rewritten" as const, detail: "the reflog entries could not be read" }
2881
+ : treeMove(before, nowHead, window);
2882
+ if (move !== undefined) branchSwitch = treeMoveReason(nowHead.root, before, nowHead, move, "since the producer returned");
2883
+ }
2884
+ }
2885
+ // Cross-repo P2e.3: a frozen perimeter (registered at return) is judged as it was then (I4, I8: its roots' statuses are
2886
+ // never re-snapshotted); the consumers (D6) are discovered now over its frozen working set, bounded by the claim deadline.
2887
+ let perimeter: PerimeterObservation | undefined;
2888
+ let gateReference: ReferenceState = reference;
2889
+ let linkDrift: ClaimPreparation["linkDrift"];
2890
+ const frozen = entry.perimeter;
2891
+ if (frozen !== undefined) {
2892
+ const discoverFrozen = async (): Promise<ConsumerDiscovery> => {
2893
+ const candidates = [...frozen.workingSet];
2894
+ if (candidates.length === 0) return { consumers: [], incomplete: [] };
2895
+ const controller = new AbortController();
2896
+ const ms = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2897
+ const onAbort = (): void => controller.abort();
2898
+ if (ms <= 0 || deadline.signal.aborted) controller.abort();
2899
+ deadline.signal.addEventListener("abort", onAbort, { once: true });
2900
+ const timer = setTimeout(onAbort, Math.max(0, ms));
2901
+ try {
2902
+ const parents = frozen.admission?.parents;
2903
+ return await discoverConsumers(frozen.observation.w.root, candidates, { signal: controller.signal, ...(parents !== undefined ? { parents } : {}) });
2904
+ } catch {
2905
+ return { consumers: [], incomplete: candidates }; // Never expected (it never throws): fail closed.
2906
+ } finally {
2907
+ clearTimeout(timer);
2908
+ deadline.signal.removeEventListener("abort", onAbort);
2909
+ }
2910
+ };
2911
+ const awaitPins = async (): Promise<readonly LinkPin[]> => {
2912
+ const bound = deadline.bound(GRADE_SNAPSHOT_TIMEOUT_MS);
2913
+ if (bound <= 0 || deadline.signal.aborted) return [];
2914
+ return withTimeout(frozen.pins, bound, "router_verify link pins").catch(() => []);
2915
+ };
2916
+ // Cross-repo P2e.4a (S11): each frozen link target observed again (one hardened snapshot per root per call, shared by
2917
+ // the call's entries through `snapshots`). Working-set roots are not: the I4 window ended at return.
2918
+ type FrozenLink = NonNullable<PendingEntry["perimeter"]>["links"][number];
2919
+ type Drift = { readonly name: string; readonly root: string; readonly why: "changed" | "unobserved" };
2920
+ // `real`: where link.at resolves now (fs only); `targets`: what W depends on now, its package link targets and its admitted
2921
+ // declared edges' top levels (P3c.4, SD-P3c-1: `dependencyTargets`, fs only, no git run); `every`: those and its unadmitted
2922
+ // edge targets' paths (P3 QA-2 F-2).
2923
+ const observeLink = async (
2924
+ link: FrozenLink,
2925
+ real: string | undefined,
2926
+ targets: readonly string[],
2927
+ every: readonly string[],
2928
+ ): Promise<Drift | undefined> => {
2929
+ const name = link.name ?? basename(link.root);
2930
+ // P3 QA-1 M3: a dependency the producer removed (or retargeted) during the dispatch is not an input of the change: skipped
2931
+ // entirely while W still does not depend on it; W depending on it again since the return is a new dependency: "changed".
2932
+ // 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).
2933
+ if (link.removedAtReturn === true) {
2934
+ return every.some(target => depthBelow(target, link.root) >= 0) ? { name, root: link.root, why: "changed" } : undefined;
2935
+ }
2936
+ // P2e QA-1 #4 (I12): no git where the link no longer resolves inside its frozen root, or where its admission refuses.
2937
+ if (real === undefined || depthBelow(real, link.root) < 0 || link.admit?.(link.root) === false) {
2938
+ return { name, root: link.root, why: "unobserved" };
2939
+ }
2940
+ // P2e QA-1 #2: W no longer links into it (retargeted or removed): the checks ran against another link target.
2941
+ if (!targets.some(target => depthBelow(target, link.root) >= 0)) return { name, root: link.root, why: "changed" };
2942
+ const key = `link\0${perimeterKey(link.at)}`;
2943
+ let pending = snapshots.get(key);
2944
+ if (pending === undefined) {
2945
+ pending = hardenedSnapshotFor(link.at, deadline, lowPriority);
2946
+ snapshots.set(key, pending);
2947
+ }
2948
+ const now = await pending;
2949
+ const top = now?.root;
2950
+ if (now === undefined) return { name, root: link.root, why: "unobserved" };
2951
+ if (top !== undefined && link.admit !== undefined && !link.admit(top)) return { name, root: link.root, why: "unobserved" };
2952
+ if (top === undefined || perimeterKey(top) !== perimeterKey(link.root) || now.fingerprint !== link.fingerprint || now.head !== link.head) {
2953
+ return { name, root: link.root, why: "changed" };
2954
+ }
2955
+ return undefined;
2956
+ };
2957
+ const observeLinks = async (): Promise<Drift[]> => {
2958
+ const reals = await Promise.all(frozen.links.map(link => realpath(link.at).catch(() => undefined)));
2959
+ // The W directory planPerimeter read links from at dispatch (it can be a subfolder of the git top level); an entry
2960
+ // registered without one falls back to the snapshot root.
2961
+ const wRoot = frozen.linkBase ?? frozen.observation.w.root;
2962
+ // P3c.4 (SD-P3c-1, F1): W's dependency targets now, the union of its package links and its declared edges, read through
2963
+ // the admission frozen at dispatch (SD-P3c-9) and once per W for this call's entries (SD-P3c-8). An entry registered
2964
+ // without a frozen admission reads W's package links only, as before P3c.
2965
+ const admission = frozen.admission;
2966
+ const context = admission !== undefined ? admissionFromData(admission) : undefined;
2967
+ const memoKey = `${perimeterKey(wRoot)}\0${admission !== undefined ? JSON.stringify(admission) : ""}`;
2968
+ if (!dependencies.has(memoKey)) {
2969
+ let read: DependencyTargets | undefined;
2970
+ try {
2971
+ read = context !== undefined
2972
+ ? dependencyTargets(wRoot, context)
2973
+ : { targets: linkedTargets(wRoot).map(at => ({ origin: "link" as const, at })), unadmittedMore: 0, incomplete: false };
2974
+ } catch {
2975
+ read = undefined; // Never expected (both skip what they cannot read): every frozen dependency is then "changed".
2976
+ }
2977
+ dependencies.set(memoKey, read);
2978
+ }
2979
+ const current = dependencies.get(memoKey)?.targets ?? [];
2980
+ // What W still depends on: its link targets (admitted or not, as before) and its admitted edges' top levels. An
2981
+ // unadmitted edge target is text only (never observed): it only names a new dependency below.
2982
+ const targets = current.filter(target => !("fixed" in target)).map(target => target.at);
2983
+ // P3 QA-2 F-2: a link removed at return is judged against every target, unadmitted ones included (as frozen at return).
2984
+ const every = current.map(target => target.at);
2985
+ const drifts = await Promise.all(frozen.links.map((link, index) => observeLink(link, reals[index], targets, every)));
2986
+ // P2e QA-1 #2: a dependency target of W now that none of the perimeter frozen at return covers (its links and edges'
2987
+ // roots, frozen at return, and its observed roots) is new: "changed". W's own repository is W's snapshot, as at
2988
+ // dispatch (planPerimeter); W's dependencies are read from `wRoot` (the dispatch's W), never from the snapshot root
2989
+ // (which is the git top level).
2990
+ // P3 QA-1 M3: a link removed at return covers nothing (observeLink names it when W depends on it again).
2991
+ const covering = [
2992
+ ...frozen.links.filter(link => link.removedAtReturn !== true).map(link => link.root),
2993
+ ...reals.filter((real, index): real is string => real !== undefined && frozen.links[index]?.removedAtReturn !== true),
2994
+ ...frozen.observation.roots.map(root => root.root),
2995
+ ];
2996
+ // P3 QA-1 M4: an unadmitted target the producer added during the dispatch covers itself, as a dispatch-time one does
2997
+ // through its unadmitted root. P3 QA-2 F-3: itself only (same key), and only while it is still unadmitted: an admitted
2998
+ // target at or below it is a new dependency ("changed").
2999
+ const unadmittedAtReturn = new Set((frozen.unadmittedAtReturn ?? []).map(at => perimeterKey(at)));
3000
+ // Not admitted now, as dependenciesAddedAtReturn judged it at return: an unadmitted edge, or a link target outside every
3001
+ // parent and worktree, without a git top level, or whose top level the frozen admission refuses.
3002
+ const unadmittedNow = (target: DependencyTargets["targets"][number]): boolean => {
3003
+ if ("fixed" in target) return true;
3004
+ if (target.origin === "edge" || context === undefined) return false;
3005
+ const parent = context.parentOf(target.at);
3006
+ const worktree = context.worktreeOf(target.at);
3007
+ if (parent === undefined && worktree === undefined) return true;
3008
+ const top = gitTopOf(target.at, worktree !== undefined ? dirname(worktree.worktree) : parent);
3009
+ return top === undefined || !context.admitTop(top);
3010
+ };
3011
+ // A new link target is named by its top level, found without git: below its parent (or above its working-set worktree)
3012
+ // as at dispatch (SD-P3c-9, F8). Outside every parent and worktree, it is named by its text: nothing runs there (I11).
3013
+ // Without a frozen admission: its top level, as before P3c.
3014
+ const linkTop = (target: string): string => {
3015
+ if (context === undefined) return gitTopOf(target) ?? target;
3016
+ const parent = context.parentOf(target);
3017
+ const worktree = context.worktreeOf(target);
3018
+ if (parent === undefined && worktree === undefined) return target;
3019
+ return gitTopOf(target, worktree !== undefined ? dirname(worktree.worktree) : parent) ?? target;
3020
+ };
3021
+ const fresh = new Map<string, Drift>();
3022
+ for (const target of current) {
3023
+ if (covering.some(root => depthBelow(target.at, root) >= 0)) continue;
3024
+ if (unadmittedAtReturn.has(perimeterKey(target.at)) && unadmittedNow(target)) continue;
3025
+ // An edge target is already its top level (admitted, found below its parent by `resolveEdgeTarget`) or text (not
3026
+ // admitted: named from its text, with no filesystem call, I11).
3027
+ const top = target.origin === "edge" ? target.at : linkTop(target.at);
3028
+ if (depthBelow(top, wRoot) >= 0 || depthBelow(wRoot, top) >= 0) continue;
3029
+ const name = "fixed" in target ? target.name : basename(top);
3030
+ if (!fresh.has(perimeterKey(top))) fresh.set(perimeterKey(top), { name, root: top, why: "changed" });
3031
+ }
3032
+ return [...drifts.filter((drift): drift is Drift => drift !== undefined), ...fresh.values()];
3033
+ };
3034
+ const [found, pins, drifted] = await Promise.all([discoverFrozen(), awaitPins(), observeLinks()]);
3035
+ if (drifted.length > 0) linkDrift = drifted;
3036
+ // P3 QA-2 F-3 (I8): an unadmitted dependency the producer added during the dispatch is named as a dispatch-time one is, a
3037
+ // root "unadmitted" (`<name> (not admitted)` in the verified-scope line, never refused), once per root already named.
3038
+ const named = new Set([frozen.observation.w.root, ...frozen.observation.roots.map(root => root.root)].map(at => perimeterKey(at)));
3039
+ const unadmittedRoots: PerimeterObservation["roots"][number][] = [];
3040
+ for (const at of frozen.unadmittedAtReturn ?? []) {
3041
+ if (named.has(perimeterKey(at))) continue;
3042
+ named.add(perimeterKey(at));
3043
+ unadmittedRoots.push({ root: at, name: basename(at), status: "unadmitted" });
3044
+ }
3045
+ perimeter = {
3046
+ ...frozen.observation,
3047
+ ...(unadmittedRoots.length > 0 ? { roots: [...frozen.observation.roots, ...unadmittedRoots] } : {}),
3048
+ ...(found.consumers.length > 0 ? { consumers: found.consumers } : {}),
3049
+ ...(found.incomplete.length > 0 ? { consumersIncomplete: found.incomplete } : {}),
3050
+ };
3051
+ if (reference.kind === "captured" && pins.length > 0) {
3052
+ // pinNow admits as the dispatch admitted, keyed by this pins array (buildGateDeps). P2e QA-1 #3: the deferred finish
3053
+ // registered the dispatch's own admission for it (freeLinkPins: nested link targets included); it is kept. Only without
3054
+ // one (an entry registered directly) the frozen links' roots stand in.
3055
+ if (!pinAdmissions.has(pins)) {
3056
+ const admitted = new Set<string>();
3057
+ for (const link of frozen.links) {
3058
+ if (link.admit === undefined || link.admit(link.root)) admitted.add(perimeterKey(link.root));
3059
+ }
3060
+ pinAdmissions.set(pins, admitted);
3061
+ }
3062
+ gateReference = { ...reference, reference: { ...reference.reference, pins } };
3063
+ }
3064
+ }
1837
3065
  return {
1838
3066
  prepared: {
1839
3067
  changedFiles: changed === "unavailable"
@@ -1841,11 +3069,19 @@ export function createVerificationWiring(deps: {
1841
3069
  : changed.map(c => ({ path: c.path, status: c.status ?? "", ...(c.previousPath !== undefined ? { previousPath: c.previousPath } : {}) })),
1842
3070
  // Section 1.5-6: an unattributed change set stays unattributed (never []).
1843
3071
  changeBaseline: changed === "unavailable" ? "unavailable" : "available",
1844
- reference,
3072
+ reference: gateReference,
1845
3073
  snapshot: tree,
3074
+ ...(branchSwitch !== undefined ? { branchSwitch } : {}),
3075
+ ...(entry.unattributedWriters !== undefined ? { unattributedWriters: [...entry.unattributedWriters] } : {}),
3076
+ ...(perimeter !== undefined ? { perimeter } : {}),
3077
+ // Cross-repo P3a (D23 as amended, QA C1): the ORIGINAL dispatch start (the entry's), never the router_verify time.
3078
+ ...(Number.isFinite(entry.dispatchedAt) ? { dispatchStartedAt: entry.dispatchedAt } : {}),
1846
3079
  },
1847
3080
  drift,
1848
- root: entry.root ?? tree?.root,
3081
+ root,
3082
+ ...(linkDrift !== undefined ? { linkDrift } : {}),
3083
+ ...(placementDrift?.kind === "drift" ? { placementDrift: placementDrift.reason } : {}),
3084
+ ...(placementDrift?.kind === "unchecked" ? { placementUnchecked: placementDrift.reason } : {}),
1849
3085
  };
1850
3086
  };
1851
3087
 
@@ -1868,6 +3104,12 @@ export function createVerificationWiring(deps: {
1868
3104
  const dod = entry.dod;
1869
3105
  // A claimed entry is never released (release happens on a terminal settle only).
1870
3106
  if (dod === undefined) return { kind: "final", result: { verdict: unverifiableVerdict(ROUTER_VERIFY_RELEASED_REASON), retryable: false } };
3107
+ // Cross-repo P2e.4b: a placed check whose cwd no longer resolves to the same repository would run elsewhere: nothing runs.
3108
+ if (prep.placementDrift !== undefined) return { kind: "final", result: { verdict: unverifiableVerdict(prep.placementDrift), retryable: false } };
3109
+ // P2e QA-1 #5b: a placement that could not be checked now: nothing runs; another router_verify may check it.
3110
+ if (prep.placementUnchecked !== undefined) {
3111
+ return { kind: "final", result: { verdict: unverifiableVerdict(prep.placementUnchecked), retryable: true } };
3112
+ }
1871
3113
  const strict = cfg.enforcement?.verify?.strictUnverifiable ?? false;
1872
3114
  const inFlight = new Set<string>();
1873
3115
  const completedFailures: string[] = [];
@@ -1876,6 +3118,11 @@ export function createVerificationWiring(deps: {
1876
3118
  const artefact = {
1877
3119
  changedFiles: prep.prepared.changedFiles,
1878
3120
  changeBaseline: prep.prepared.changeBaseline,
3121
+ ...(prep.root !== undefined ? { changeRoot: prep.root } : {}),
3122
+ ...(prep.prepared.branchSwitch !== undefined ? { branchSwitch: prep.prepared.branchSwitch } : {}),
3123
+ ...(prep.prepared.unattributedWriters !== undefined && prep.prepared.unattributedWriters.length > 0
3124
+ ? { unattributedWriters: prep.prepared.unattributedWriters } : {}),
3125
+ ...(prep.prepared.perimeter !== undefined ? { perimeter: prep.prepared.perimeter } : {}),
1879
3126
  // Not stored (R3): a testsPass DoD is deterministic, and no deterministic check reads it.
1880
3127
  finalReturnText: "",
1881
3128
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
@@ -1890,7 +3137,12 @@ export function createVerificationWiring(deps: {
1890
3137
  const workRoot = deferredWorkRoots.get(entry.handle);
1891
3138
  try {
1892
3139
  res = await withTimeout(
1893
- accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd, ...(workRoot !== undefined ? { workRoot } : {}) }, artefact, gateDeps),
3140
+ accept({
3141
+ dod, trivial: false, mode: "modeA", cwd: entry.cwd,
3142
+ ...(workRoot !== undefined ? { workRoot } : {}),
3143
+ // Cross-repo P2e.4b: the placements frozen at return (each still resolves as it did: prepareClaim).
3144
+ ...(entry.placements !== undefined ? { checkPlacements: entry.placements } : {}),
3145
+ }, artefact, gateDeps),
1894
3146
  deadline.remaining(),
1895
3147
  "verification gate",
1896
3148
  );
@@ -1933,7 +3185,8 @@ export function createVerificationWiring(deps: {
1933
3185
  */
1934
3186
  const judgeVerdict = (entry: PendingEntry, prep: ClaimPreparation, gate: ClaimGate, cfg: RouterConfig): VerificationResult => {
1935
3187
  if (gate.kind === "final") return gate.result;
1936
- const { strict, retryable } = gate;
3188
+ const { strict } = gate;
3189
+ let retryable = gate.retryable;
1937
3190
  // QA-3.1-2 / QA-3.1-3: the dispatch's own context, recorded when the producer returned.
1938
3191
  const res = applyDispatchCaveats(
1939
3192
  lineageDowngrade(gate.res, { orchestratorSessionID: entry.orchestratorSessionID, root: prep.root, dispatchedAt: entry.dispatchedAt, strictUnverifiable: strict }),
@@ -1955,6 +3208,27 @@ export function createVerificationWiring(deps: {
1955
3208
  strict,
1956
3209
  ).verdict;
1957
3210
  }
3211
+ if (prep.linkDrift !== undefined && prep.linkDrift.length > 0) {
3212
+ // Cross-repo P2e.4a (S11, OD-P2e-1): a linked repository not as it was at return never lets a pass stand; it is
3213
+ // unverifiable with one caveat per link. A fail stays a fail and carries the caveats too. They are reasons as well, so the
3214
+ // report (formatVerifyReport: a verdict not accepted shows its reasons) names them.
3215
+ const caveats = prep.linkDrift.map(link => LINK_DRIFT_CAVEAT[link.why](link.name, link.root));
3216
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
3217
+ // 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
3218
+ // cannot be resolved now) is transient: retryable, so the handle stays open for another router_verify. A changed link
3219
+ // is certain: final. A fail stays final.
3220
+ if (outcome === "pass" && prep.linkDrift.every(link => link.why === "unobserved")) retryable = true;
3221
+ verdict = gateResult(
3222
+ {
3223
+ ...verdict,
3224
+ ...(outcome === "pass" ? { pass: false, outcome: "unverifiable" as const } : {}),
3225
+ reasons: [...verdict.reasons, ...caveats],
3226
+ caveats: [...(verdict.caveats ?? []), ...caveats],
3227
+ },
3228
+ res.dodSource,
3229
+ strict,
3230
+ ).verdict;
3231
+ }
1958
3232
  const judged = gateResult(verdict, res.dodSource, strict);
1959
3233
  const outcome = judged.verdict.outcome;
1960
3234
  let nextTier: string | undefined;
@@ -2056,8 +3330,10 @@ export function createVerificationWiring(deps: {
2056
3330
  // 4. Every preparation first, then every gate at once: the testsPass requests share the
2057
3331
  // deadline and reach the S5 coordinator together (one window, one batch).
2058
3332
  const snapshots = new Map<string, Promise<TreeSnapshot | undefined>>();
3333
+ // P3c.4 (SD-P3c-8): W's dependency targets, read once per W for this call's entries.
3334
+ const dependencies: DependencyMemo = new Map();
2059
3335
  // 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));
3336
+ const preparations = claims.map(c => prepareClaim(c.entry, owned, snapshots, budget.lowPriority || options.background === true, dependencies));
2061
3337
  const allPrepared = Promise.allSettled(preparations);
2062
3338
  const gates = claims.map(async (c, i): Promise<{ readonly prep: ClaimPreparation | undefined; readonly gate: ClaimGate }> => {
2063
3339
  let prep: ClaimPreparation | undefined;
@@ -2217,10 +3493,23 @@ export function createVerificationWiring(deps: {
2217
3493
  stop.abort();
2218
3494
  };
2219
3495
  },
2220
- async prepareVerification(store, id, childID, cwd, deadline) {
3496
+ async prepareVerification(store, id, childID, cwd, deadline, dispatchStartedAt?: number) {
2221
3497
  const change = await observeChange(store, id, childID, cwd, deadline);
2222
- const reference = await store.reference(id, deadline?.signal);
2223
- return { ...change, reference };
3498
+ const captured = await store.reference(id, deadline?.signal);
3499
+ // Cross-repo P2d.3 (P2.6): the pins of the admitted link targets travel with a captured reference (required gate only).
3500
+ const pins = captured.kind === "captured" ? await linkPinsAtGate(store, id, deadline) : [];
3501
+ // QA-2 nit: the gate took the dispatch's pins (or its reference was discarded): free them.
3502
+ freeLinkPins(id, pins);
3503
+ const reference: ReferenceState = pins.length > 0 && captured.kind === "captured"
3504
+ ? { kind: "captured", reference: { ...captured.reference, pins } }
3505
+ : captured;
3506
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch start the caller holds (DispatchStart.dispatchedAt), the `since` of
3507
+ // W's ignored-module listing. Unknown: none listed (toward zero selection, never toward a stale build output).
3508
+ return {
3509
+ ...change,
3510
+ reference,
3511
+ ...(dispatchStartedAt !== undefined && Number.isFinite(dispatchStartedAt) ? { dispatchStartedAt } : {}),
3512
+ };
2224
3513
  },
2225
3514
  graderSessions,
2226
3515
  disposeChildSession,