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
@@ -50,23 +50,34 @@ import { decideRole } from "../engine/kernel";
50
50
  import type { Candidate, ChosenDispatch, Decision, HostAgentInfo, Ladder, RoleLadder } from "../engine/types";
51
51
  import { CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches } from "../classify";
52
52
  import type { ClassifyResult, Detection, Need, RouteLine, TaskFacts } from "../classify/types";
53
- import { resolveVerifyBudget, type RouterConfig } from "../../router/config";
53
+ import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig } from "../../router/config";
54
54
  import { resolveEnforcementMode } from "../../router/enforcement";
55
55
  import { roleGuardProfile } from "../../router/guard-profile";
56
56
  import { resolveRoles, type AuthorityAction, type RoleSpec } from "../../router/roles";
57
57
  import { parseVerifyDirectives } from "../../verify/directives";
58
58
  import { buildDelegationDoD } from "../../verify/dispatch";
59
59
  import { requestedVerificationCwd, verificationScope } from "../roles/work-root";
60
+ import { resolveCheckPlacements } from "../roles/check-placement";
61
+ import { createRepoProbe, displaySafe, readSetPredicate } from "../roles/read-set";
60
62
  import { effectiveDetection, effectiveFactsOf, grantFor, tierBounds, type DispatchGrant, type EffectiveDetection } from "../roles/policy";
61
63
  import {
62
64
  BINDING_NOTES, LOCAL_ACTIONS, currentBinding, evictCall, newDispatchNonce, noncePromptLine, nonceTitleSuffix, registerPending, type Binding,
63
65
  } from "../roles/binding";
64
66
  import { realpathSync } from "node:fs";
67
+ import { dirname } from "node:path";
68
+ // Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json lookup
69
+ // fails. admission.ts imports this module back; both sides use the other only inside functions.
70
+ import {
71
+ createAdmission, defaultAdmissionDeps, gitShowToplevel, type Admission, type AdmissionConfig, type AdmissionService, type RepoLocation,
72
+ } from "../roles/admission";
73
+ import { buildRoleDispatchHeader, stripDispatchHeader } from "../../router/dispatch-header";
74
+ import { addToWorkingSet, dropFromWorkingSets, workingSetOf } from "./working-set";
65
75
  import {
66
76
  consumeRunnerDispatch, consumeRunnerDispatchLoose, forgetDispatch, lookupDispatch, rememberDispatch, runnerDescription,
67
77
  updateDispatchVerification, type CarriedVerification, type DetectionDepth, type DispatchInput, type DispatchRecord,
68
78
  } from "../../router/sessions";
69
- import type { ChangedFile } from "../../verify/dispatch";
79
+ import type { ChangedFile, TreeSnapshot } from "../../verify/dispatch";
80
+ import { branchSwitchReason, branchSwitched } from "../../verify/branch";
70
81
  import type { ReferenceState } from "../../verify/types";
71
82
  import { randomBytes } from "node:crypto";
72
83
  import {
@@ -89,6 +100,138 @@ import {
89
100
  } from "../outcomes/types";
90
101
  import { agentModelRef, type AgentView } from "./host-info";
91
102
  import { sessionRulesOf, type EngineRuntime, type Prepared, type RolePrepared, type WireLogger } from "./runtime";
103
+ import {
104
+ applyApproval, inspectCandidate, isApprovalValid, readApprovals, validApprovals, type ApprovalsEnv, type CandidateIdentity,
105
+ } from "../roles/approvals";
106
+ import { DEFAULT_REPO_APPROVAL_DAYS } from "../../router/roles-config";
107
+
108
+ // ── Cross-repo Phase 4: repositories approved with `/router approve` (docs/design/cross-repo-phase4-plan.md) ────────────────
109
+
110
+ /** The approval part of a D15 refusal waits at most this long for `inspectCandidate`; then the note stays as it is (SD-P4-8). */
111
+ export const APPROVAL_NOTE_TIMEOUT_MS = 8_000;
112
+
113
+ export interface ApprovalNoteOptions {
114
+ /** `routing.repoExclude`. */
115
+ readonly exclude?: readonly string[];
116
+ /** The approvals store environment (tests: an injected directory). */
117
+ readonly env?: ApprovalsEnv;
118
+ /** Default {@link inspectCandidate}; tests inject a fake. */
119
+ readonly inspect?: typeof inspectCandidate;
120
+ /** Default {@link APPROVAL_NOTE_TIMEOUT_MS}. */
121
+ readonly timeoutMs?: number;
122
+ }
123
+
124
+ /** The details of an approvable candidate, every field from git (`inspectCandidate`) and through `displaySafe` (SD-P4-8, -9). */
125
+ function approvalDetails(identity: CandidateIdentity): string {
126
+ const where = displaySafe(identity.path);
127
+ const head = displaySafe(identity.head).slice(0, 7) || "unknown";
128
+ const at = identity.branch === "(detached)" ? `detached at ${head}` : `branch ${displaySafe(identity.branch)} at ${head}`;
129
+ const command = /\s/.test(where) ? `/router approve "${where}"` : `/router approve ${where}`;
130
+ return `${where} is a git repository outside routing.repoParents (origin ${displaySafe(identity.origin)}, ${at}). `
131
+ + `Only the user can approve it: ask the user to run ${command}, then dispatch again.`;
132
+ }
133
+
134
+ /**
135
+ * Cross-repo Phase 4 (SD-P4-8, -9): the text appended to the D15 refusal of a dispatch whose admission refusal carries
136
+ * `approvable` (admission's canonical candidate). Built only from what `inspectCandidate` reports about that candidate — never
137
+ * from the dispatch text: its path, origin (credentials stripped), branch (or detached) at the short head, and the command the
138
+ * user types; or, when `inspectCandidate` names a problem, why no approval can be requested. Undefined — the note stays as it
139
+ * is — when the inspection throws or takes longer than {@link APPROVAL_NOTE_TIMEOUT_MS}. Never throws.
140
+ */
141
+ export async function approvalNote(approvable: string, opts: ApprovalNoteOptions = {}): Promise<string | undefined> {
142
+ const inspect = opts.inspect ?? inspectCandidate;
143
+ let timer: ReturnType<typeof setTimeout> | undefined;
144
+ try {
145
+ const timedOut = new Promise<undefined>((resolve) => {
146
+ timer = setTimeout(() => resolve(undefined), opts.timeoutMs ?? APPROVAL_NOTE_TIMEOUT_MS);
147
+ });
148
+ const inspected = inspect(approvable, { exclude: opts.exclude ?? [], ...(opts.env === undefined ? {} : { env: opts.env }) });
149
+ const found = await Promise.race([inspected, timedOut]);
150
+ if (found === undefined) return undefined;
151
+ if (typeof found === "string") {
152
+ const problem = found.trim().replace(/\.+$/, "");
153
+ return problem === "" ? undefined : `No approval can be requested for ${displaySafe(approvable)}: it ${displaySafe(problem)}.`;
154
+ }
155
+ return approvalDetails(found);
156
+ } catch {
157
+ return undefined;
158
+ } finally {
159
+ if (timer !== undefined) clearTimeout(timer);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Cross-repo Phase 4 (SD-P4-7): records the use of the approval `approvalPath` after a binding it backs — fire and forget: the
165
+ * entry's roots come from the store (read without git), `applyApproval` `touch` writes at most once per hour per path, only while
166
+ * the entry still has those roots and is valid, and never throws. Nothing here can fail the dispatch.
167
+ */
168
+ export function touchApproval(approvalPath: string, days: number, env: ApprovalsEnv = {}): void {
169
+ try {
170
+ const entry = readApprovals(env).approvals.find((candidate) => candidate.path === approvalPath);
171
+ if (entry === undefined) return;
172
+ void applyApproval({ kind: "touch", path: entry.path, roots: entry.roots, days }, env).catch(() => undefined);
173
+ } catch {
174
+ // a failed touch never fails the dispatch
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Phase 4 QA (m2): why a binding backed by the approved path `approval` no longer binds, or undefined while that approval applies:
180
+ * read from the store without git (`readApprovals` + `isApprovalValid` with `days`); revoked, expired and an unreadable store
181
+ * (fail closed) all lapse.
182
+ */
183
+ export function lapsedApprovalReason(
184
+ approval: string,
185
+ days: number,
186
+ env: ApprovalsEnv = {},
187
+ platform: NodeJS.Platform = process.platform,
188
+ ): string | undefined {
189
+ let valid = false;
190
+ try {
191
+ const now = (env.now ?? Date.now)();
192
+ const key = normalizeRootText(approval, platform);
193
+ valid = readApprovals(env).approvals.some((entry) => normalizeRootText(entry.path, platform) === key && isApprovalValid(entry, days, now));
194
+ } catch {
195
+ valid = false;
196
+ }
197
+ return valid ? undefined : `approval for ${approval} was revoked or expired: no work root. Only the user can approve it again (/router approve ${approval}).`;
198
+ }
199
+
200
+ /**
201
+ * Cross-repo Phase 4 (SD-P4-12): `locations` (a working set) without the entries backed by an approval that no longer applies
202
+ * (revoked, expired, or an unreadable store: fail closed), read from the store without git. The lapsed approvals are dropped from
203
+ * every working set too (`dropFromWorkingSets`), so the read set shrinks with them. No store I/O when no entry is backed by an
204
+ * approval.
205
+ */
206
+ export function pruneLapsedApprovals(
207
+ locations: readonly RepoLocation[],
208
+ days: number,
209
+ env: ApprovalsEnv = {},
210
+ platform: NodeJS.Platform = process.platform,
211
+ ): readonly RepoLocation[] {
212
+ if (!locations.some((location) => location.approval !== undefined)) return locations;
213
+ let valid: ReadonlySet<string>;
214
+ try {
215
+ const now = (env.now ?? Date.now)();
216
+ valid = new Set(readApprovals(env).approvals.filter((entry) => isApprovalValid(entry, days, now)).map((entry) => normalizeRootText(entry.path, platform)));
217
+ } catch {
218
+ valid = new Set();
219
+ }
220
+ const lapsed = new Set<string>();
221
+ const kept = locations.filter((location) => {
222
+ if (location.approval === undefined || valid.has(normalizeRootText(location.approval, platform))) return true;
223
+ lapsed.add(location.approval);
224
+ return false;
225
+ });
226
+ for (const approval of lapsed) {
227
+ try {
228
+ dropFromWorkingSets(approval, platform);
229
+ } catch {
230
+ // the entries are left out of `known` above in any case
231
+ }
232
+ }
233
+ return kept;
234
+ }
92
235
 
93
236
  /** A fresh dispatch can be claimed by a `session.created` event for at most this long. */
94
237
  export const PENDING_TTL_MS = 120_000;
@@ -159,7 +302,7 @@ export interface RoleRouted {
159
302
  readonly verifyRoot: string;
160
303
  /** The route line's `root=` as written, or null. */
161
304
  readonly requestedRoot: string | null;
162
- /** Work-root, grant and catalog notes (for the dispatch header / parent result). */
305
+ /** Grant and catalog notes (decision-row / diagnostic text; they are not shown in the dispatch header or the parent result). */
163
306
  readonly notes: readonly string[];
164
307
  readonly detection: EffectiveDetection;
165
308
  /** The dispatch's total call budget (`roleGuardProfile(spec, tier, routeLine.budget).budget`). */
@@ -191,7 +334,7 @@ export interface RoleRouted {
191
334
 
192
335
  /**
193
336
  * #84 P2.1: a role dispatch the router refuses (malformed first route line, no candidate inside the tier window, the router could not
194
- * route it). `route()` THROWS it — the one exception to "never throws" — so the adapter's `execute.before` fails the call with this
337
+ * route it, or a declared `repo=` / `branch=` / `root=` target the router refused — Q9). `route()` THROWS it — the one exception to "never throws" — so the adapter's `execute.before` fails the call with this
195
338
  * message and the host never runs the child. It never falls back to a tier agent (QA-P12-1-5).
196
339
  */
197
340
  export class RoleDispatchRefusal extends Error {
@@ -256,6 +399,19 @@ export interface DispatchRouter {
256
399
  }
257
400
 
258
401
  export interface DispatchRouterDeps {
402
+ /**
403
+ * Cross-repo (P1.4): builds the admission of a resolved `{ repoParents, repoDepth, repoExclude }` (once per triple); default
404
+ * `createAdmission` (`roles/admission.ts`). Tests inject a fake.
405
+ */
406
+ readonly createAdmission?: (config: AdmissionConfig) => Pick<AdmissionService, "admit" | "resolve">;
407
+ /**
408
+ * Cross-repo Phase 4: the approvals store environment of the dispatch bind path (the D15 approval note, `touch` after an
409
+ * approval-backed binding, pruning lapsed approvals from the working set). Default: the real store. Tests inject a directory
410
+ * and a clock.
411
+ */
412
+ readonly approvalsEnv?: ApprovalsEnv;
413
+ /** Cross-repo Phase 4 (SD-P4-8): `inspectCandidate` for the D15 approval note; tests inject a fake. */
414
+ readonly inspectCandidate?: typeof inspectCandidate;
259
415
  readonly runtime: EngineRuntime;
260
416
  /** `ctx.session.get({ sessionID })`. */
261
417
  readonly getSession: (sessionID: string) => Promise<unknown>;
@@ -270,6 +426,11 @@ export interface DispatchRouterDeps {
270
426
  * {@link gitWorktreeList} (the hardened spawn, 5 s timeout). Injected by tests.
271
427
  */
272
428
  readonly listWorktrees?: (cwd: string) => Promise<string>;
429
+ /**
430
+ * Cross-repo QA round 2: hardened `git rev-parse --show-toplevel` in `cwd` (default `gitShowToplevel`, `roles/admission.ts`), used
431
+ * to check that the session directory belongs to the bound worktree before it stays the work root. Injected by tests.
432
+ */
433
+ readonly showToplevel?: (cwd: string) => Promise<string | undefined>;
273
434
  /** #84 P2.1: canonical long form of an existing path (default `realpathSync.native`). Only called on an already matched root. */
274
435
  readonly realpath?: (path: string) => string;
275
436
  /** #84 P2.1: path rules of the work-root comparison (default `process.platform`). */
@@ -506,8 +667,31 @@ export interface WorkRootResolution {
506
667
  readonly workRoot: string | null;
507
668
  /** The route line's `root=` as written, or null. */
508
669
  readonly requested: string | null;
509
- /** Why there is no work root (for the grant notes and the dispatch header); null when resolved. */
670
+ /** Why there is no work root; null when resolved. A dispatch that declared `repo=`/`branch=`/`root=` is refused with this note (Q9). */
510
671
  readonly note: string | null;
672
+ /** Cross-repo (P1.4): where the work root lies, when admission bound it. */
673
+ readonly location?: RepoLocation;
674
+ /**
675
+ * Cross-repo Phase 4 (SD-P4-8): the canonical candidate of an admission refusal that a human could approve with
676
+ * `/router approve` (admission's `approvable`). Set only with `workRoot: null`; the dispatch bind path turns it into a note.
677
+ */
678
+ readonly approvable?: string;
679
+ }
680
+
681
+ /**
682
+ * Cross-repo (P1.4): what admission needs to bind a role dispatch's work root. Without `admission`, `resolveRoleWorkRoot` is
683
+ * today's text match (invariant I9).
684
+ */
685
+ export interface WorkRootAdmissionInput {
686
+ /** The route line's `repo=`, as written. */
687
+ readonly repo?: string | null | undefined;
688
+ /** The route line's `branch=`, as written. */
689
+ readonly branch?: string | null | undefined;
690
+ readonly admission?: Pick<AdmissionService, "admit" | "resolve"> | undefined;
691
+ /** The session repository; the session directory when absent. */
692
+ readonly sessionRepository?: string | undefined;
693
+ /** Repositories whose worktrees are admissible by rule 2 (the session directory, the working set). */
694
+ readonly known?: readonly string[] | undefined;
511
695
  }
512
696
 
513
697
  export interface WorkRootDeps {
@@ -544,12 +728,15 @@ export async function gitWorktreeList(cwd: string): Promise<string> {
544
728
  * - no `root=` → the session directory (canonical long form);
545
729
  * - `root=` → its normalised TEXT is compared with the session directory and with every worktree of `git worktree list --porcelain`
546
730
  * (run in the session directory) BEFORE any filesystem call on it; a match → the canonical long form of the matched entry;
731
+ * with an admission (cross-repo), any `root=` other than the session directory binds only through `admission.admit`
732
+ * (QA round 1, F1), and an admitted worktree binds only while its `realpath` still equals it (F8);
547
733
  * - anything else (no match, git unavailable, an entry that does not resolve) → `workRoot: null` with a note.
548
734
  * Never throws.
549
735
  */
550
736
  export async function resolveRoleWorkRoot(
551
737
  input: { readonly root: string | null; readonly sessionDirectory: string },
552
738
  deps: WorkRootDeps,
739
+ cross?: WorkRootAdmissionInput,
553
740
  ): Promise<WorkRootResolution> {
554
741
  const canonical = (path: string): string | null => {
555
742
  try {
@@ -559,6 +746,39 @@ export async function resolveRoleWorkRoot(
559
746
  return null;
560
747
  }
561
748
  };
749
+ // Cross-repo (P1.4): admission binds `repo=` / `branch=` (with or without `root=`), and a `root=` the text match below did not find.
750
+ const admission = cross?.admission;
751
+ const sessionRepository = cross?.sessionRepository ?? input.sessionDirectory;
752
+ const known = [...new Set([sessionRepository, ...(cross?.known ?? [])])];
753
+ const admitted = async (run: () => Promise<Admission>): Promise<WorkRootResolution> => {
754
+ let result: Admission;
755
+ try {
756
+ result = await run();
757
+ } catch (error) {
758
+ result = { ok: false, reason: `admission failed: ${describeError(error)}: no work root.` };
759
+ }
760
+ if (!result.ok) {
761
+ const approvable = result.approvable;
762
+ return approvable === undefined
763
+ ? { workRoot: null, requested: input.root, note: result.reason }
764
+ : { workRoot: null, requested: input.root, note: result.reason, approvable };
765
+ }
766
+ const resolved = canonical(result.location.worktree);
767
+ if (resolved === null) return { workRoot: null, requested: input.root, note: `${result.location.worktree} does not resolve on disk: no work root` };
768
+ // QA round 1 (F8): the admitted worktree is canonical; one that now resolves elsewhere (a link swapped in since) binds nothing.
769
+ if (normalizeRootText(resolved, deps.platform) !== normalizeRootText(result.location.worktree, deps.platform)) {
770
+ return { workRoot: null, requested: input.root, note: `the admitted work root ${result.location.worktree} now resolves to ${resolved}: no work root` };
771
+ }
772
+ return { workRoot: resolved, requested: input.root, note: null, location: result.location };
773
+ };
774
+ const repo = cross?.repo?.trim() || undefined;
775
+ const branch = cross?.branch?.trim() || undefined;
776
+ if (admission !== undefined && (repo !== undefined || branch !== undefined)) {
777
+ return admitted(() => admission.resolve(
778
+ { ...(input.root === null ? {} : { root: input.root }), ...(repo === undefined ? {} : { repo }), ...(branch === undefined ? {} : { branch }) },
779
+ { sessionRepository, known },
780
+ ));
781
+ }
562
782
  if (input.root === null) {
563
783
  const dir = canonical(input.sessionDirectory);
564
784
  return dir === null
@@ -577,6 +797,12 @@ export async function resolveRoleWorkRoot(
577
797
  match = listed.find((path) => normalizeRootText(path, deps.platform) === want);
578
798
  }
579
799
  const none = `root=${input.root} is neither the session directory nor a worktree listed by \`git worktree list --porcelain\`: no work root`;
800
+ // QA round 1 (F1): with an admission, a worktree the session repository lists is a work root only if admission admits it too
801
+ // (routing.repoExclude, links, parents); the session directory itself keeps today's match (I9).
802
+ if (admission !== undefined && match !== input.sessionDirectory) {
803
+ const root = input.root;
804
+ return admitted(() => admission.admit(root, known, sessionRepository));
805
+ }
580
806
  if (match === undefined) return { workRoot: null, requested: input.root, note: none };
581
807
  const resolved = canonical(match);
582
808
  return resolved === null
@@ -636,7 +862,8 @@ export function roleVerificationRuns(input: {
636
862
  /**
637
863
  * QA-P21-1-2: the dispatch's verification would be deferred, exactly as the native path decides it (index.ts `isDeferred` →
638
864
  * verify/wiring.ts `isDeferred`): its `VERIFY:` directives resolve to `deferred` (the configured `defaultVerify` when the text has
639
- * none; the text is `dispatchDirectiveText(prompt, description)`) AND its DoD carries a `testsPass` check. A deferred dispatch
865
+ * none; the text is `dispatchDirectiveText(prompt, description)`) AND its DoD carries a `testsPass` check (with or without
866
+ * per-check `cwd=`/`scope=` keys: the classification does not depend on where a check runs). A deferred dispatch
640
867
  * returns without the gate (`router_verify` runs it later), so the router's gate cannot back a `deterministic` detection.
641
868
  * Fails toward "deferred" on any error (a weaker detection, never a stronger one). QA-P21-2 nit 3: nothing is deferred when
642
869
  * `router_verify` is not registered (`verifyEnabled: false`, index.ts `routerVerifyEnabled`): the gate then runs at the return.
@@ -668,10 +895,17 @@ export function roleGateDeferred(cfg: RouterConfig, prompt: string, description:
668
895
  * only the return shows (every change outside the work root, a timeout, a verifier error) does not rewrite the row — its verdict
669
896
  * carries the caveat (`[router ⚠ UNVERIFIED …]`) and is never accepted as verified.
670
897
  */
671
- export function roleGateOutsideWorkRoot(workRoot: string | null, prompt: string, description: string, argsCwd?: unknown): boolean {
898
+ export function roleGateOutsideWorkRoot(
899
+ workRoot: string | null, prompt: string, description: string, argsCwd?: unknown, inReadSet?: (absPath: string) => boolean,
900
+ ): boolean {
672
901
  if (workRoot === null) return true;
673
902
  try {
674
- return verificationScope(requestedVerificationCwd(argsCwd, buildDelegationDoD({ prompt, description }).cwd), workRoot).outside;
903
+ const dod = buildDelegationDoD({ prompt, description });
904
+ const scope = verificationScope(requestedVerificationCwd(argsCwd, dod.cwd), workRoot);
905
+ if (scope.outside) return true;
906
+ // P2.5 (SD4): a check's own `cwd=` / `scope=` must resolve too (inside W, or an absolute path in the read set R `inReadSet`);
907
+ // one that is refused makes the gate refuse the delegation, so the router's gate cannot back `deterministic`.
908
+ return resolveCheckPlacements(dod, scope, inReadSet === undefined ? {} : { inReadSet }).refused !== undefined;
675
909
  } catch {
676
910
  return true;
677
911
  }
@@ -837,7 +1071,7 @@ function higherTier(order: readonly string[], a: string | null, b: string | null
837
1071
  * cannot touch it: binding.ts holds its enforced grant), so the verification root, the outside-root check and the classification
838
1072
  * never use it.
839
1073
  */
840
- function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
1074
+ export function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
841
1075
  const root = boundGrant.workRoot;
842
1076
  const actions = new Set<AuthorityAction>([...boundGrant.actions, ...widened]);
843
1077
  if (boundGrant.workRoot === null) {
@@ -846,7 +1080,9 @@ function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityActi
846
1080
  actions.delete("router_run");
847
1081
  actions.delete("edit");
848
1082
  }
849
- return { actions, notes: [...boundGrant.notes], workRoot: root };
1083
+ // QA round 1 (F10): the location travels only with a validated work root, the bound one (binding.ts `locationOf`).
1084
+ const location = root !== null && root === boundGrant.workRoot && boundGrant.location !== undefined ? { location: boundGrant.location } : {};
1085
+ return { actions, notes: [...boundGrant.notes], workRoot: root, ...location };
850
1086
  }
851
1087
 
852
1088
  /** verify/dod.ts `OPEN_TAG_RE` / `CLOSE_TAG_RE`: the lines that open and close an `[acceptance]` block. */
@@ -895,6 +1131,19 @@ export interface RoleAttemptChanges {
895
1131
  readonly changedFiles: ChangedFile[];
896
1132
  readonly changeBaseline: "available" | "unavailable";
897
1133
  readonly reference: ReferenceState;
1134
+ readonly snapshot?: Pick<TreeSnapshot, "cwd" | "root" | "head" | "branch"> | undefined;
1135
+ readonly branchSwitch?: string | undefined;
1136
+ readonly unattributedWriters?: string[] | undefined;
1137
+ }
1138
+
1139
+ /** QA2 F3c: a "cannot confirm the branch" reason (an unreadable tree), as opposed to an observed switch. */
1140
+ function isUnconfirmedBranch(reason: string): boolean {
1141
+ return reason.startsWith("cannot confirm the branch of ");
1142
+ }
1143
+
1144
+ /** I5 (P0.3): the sorted union of two writer lists. */
1145
+ function unionWriters(older: readonly string[] | undefined, newer: readonly string[] | undefined): string[] {
1146
+ return [...new Set([...(older ?? []), ...(newer ?? [])])].sort();
898
1147
  }
899
1148
 
900
1149
  /** The union of two change sets, keyed by path (separators unified, case folded on win32); `newer` wins. */
@@ -921,19 +1170,50 @@ export function roleAttemptVerification<T extends RoleAttemptChanges>(childSessi
921
1170
  const verification = lookupDispatch(childSessionID)?.verification;
922
1171
  if (verification === undefined) return prepared;
923
1172
  const own: readonly ChangedFile[] | "unavailable" = prepared.changeBaseline === "available" ? prepared.changedFiles : "unavailable";
1173
+ const now = prepared.snapshot;
924
1174
  if (!opts.carried) {
925
- updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: prepared.reference, changed: own } });
1175
+ const tree = now === undefined ? {} : { tree: { head: now.head, ...(now.branch === undefined ? {} : { branch: now.branch }), root: now.root ?? now.cwd } };
1176
+ // QA2 F3c: an attempt that only could not confirm its branch is not a switch of the lineage (a later attempt with a
1177
+ // readable tree is judged on its own); only a real switch is recorded and inherited.
1178
+ const switched = prepared.branchSwitch === undefined || isUnconfirmedBranch(prepared.branchSwitch) ? {} : { switched: prepared.branchSwitch };
1179
+ const ownWriters = unionWriters(undefined, prepared.unattributedWriters);
1180
+ const writers = ownWriters.length === 0 ? {} : { writers: ownWriters };
1181
+ updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: prepared.reference, changed: own, ...tree, ...switched, ...writers } });
926
1182
  return prepared;
927
1183
  }
928
1184
  const baseline = verification.baseline;
929
1185
  if (baseline === undefined) return { ...prepared, changeBaseline: "unavailable", reference: CARRIED_NO_REFERENCE };
930
1186
  const changed = unionChanges(baseline.changed, own);
931
- updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: baseline.reference, changed } });
1187
+ // I5 (P0.3): a write an earlier attempt made through a tool the router cannot observe is part of the carried change too.
1188
+ const lineageWriters = unionWriters(baseline.writers, prepared.unattributedWriters);
1189
+ // I7 across attempts. Precedence: a switch seen during this dispatch, then one inherited from an earlier attempt,
1190
+ // then a switch between the introducing attempt's tree and this one.
1191
+ const computedSwitch = prepared.branchSwitch !== undefined || baseline.switched !== undefined ? undefined
1192
+ : baseline.tree !== undefined && now !== undefined && branchSwitched(baseline.tree, now)
1193
+ ? branchSwitchReason(now.root ?? now.cwd, baseline.tree, now, "since the attempt that introduced this acceptance") : undefined;
1194
+ // B3: the first switch the lineage finds is recorded, so every later carried attempt inherits it.
1195
+ const ownSwitch = prepared.branchSwitch !== undefined && !isUnconfirmedBranch(prepared.branchSwitch) ? prepared.branchSwitch : undefined;
1196
+ const recordedSwitch = baseline.switched ?? ownSwitch ?? computedSwitch;
1197
+ updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: baseline.reference, changed,
1198
+ ...(baseline.tree === undefined ? {} : { tree: baseline.tree }),
1199
+ ...(recordedSwitch === undefined ? {} : { switched: recordedSwitch }),
1200
+ ...(lineageWriters.length === 0 ? {} : { writers: lineageWriters }) } });
1201
+ const INHERITED_PREFIX = "in an earlier attempt of this acceptance: ";
1202
+ // B11: a switch inherited from an earlier attempt says so (once); one found by this attempt is returned as it is.
1203
+ const lineageSwitch = prepared.branchSwitch !== undefined ? undefined
1204
+ : baseline.switched !== undefined ? (baseline.switched.startsWith(INHERITED_PREFIX) ? baseline.switched : `${INHERITED_PREFIX}${baseline.switched}`)
1205
+ : computedSwitch !== undefined ? computedSwitch
1206
+ // B9: a recorded branch but no current snapshot: this attempt cannot be confirmed to be on it.
1207
+ : baseline.tree?.branch !== undefined && now === undefined
1208
+ ? `cannot confirm the branch of ${baseline.tree.root ?? "the work root"}: the working tree could not be read for this carried attempt, so the checks could verify another branch. Send a fresh [acceptance] block, or re-dispatch.`
1209
+ : undefined;
932
1210
  return {
933
1211
  ...prepared,
934
1212
  changedFiles: changed === "unavailable" ? prepared.changedFiles : changed,
935
1213
  changeBaseline: changed === "unavailable" ? "unavailable" : "available",
936
1214
  reference: baseline.reference,
1215
+ ...(lineageSwitch === undefined ? {} : { branchSwitch: lineageSwitch }),
1216
+ ...(lineageWriters.length === 0 ? {} : { unattributedWriters: lineageWriters }),
937
1217
  };
938
1218
  }
939
1219
 
@@ -1467,6 +1747,228 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1467
1747
  platform: deps.platform ?? process.platform,
1468
1748
  };
1469
1749
 
1750
+ // QA round 2: the hardened `git rev-parse --show-toplevel` of admission; tests inject a fake.
1751
+ const showToplevel = async (cwd: string): Promise<string | undefined> =>
1752
+ deps.showToplevel !== undefined ? deps.showToplevel(cwd) : gitShowToplevel(cwd);
1753
+
1754
+ // Cross-repo P2.5: the read set R of this dispatch's role session beyond its work root, for the per-check `cwd=` roots the gate
1755
+ // places (the same inputs as the read guard: the dispatching session's working set, `routing.repoParents/Depth/Exclude`, one
1756
+ // cached probe). Undefined when R adds nothing, or on any error: only roots inside W are valid (fail closed).
1757
+ const readSetProbe = createRepoProbe();
1758
+ const readSetFor = (cfg: RouterConfig, orchestratorSessionID: string): ((absPath: string) => boolean) | undefined => {
1759
+ try {
1760
+ const routing = resolveRolesRouting(cfg, "v2");
1761
+ const inSet = readSetPredicate(
1762
+ { parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSetOf(orchestratorSessionID), readSetProbe,
1763
+ );
1764
+ return inSet === undefined ? undefined : (absPath) => inSet(absPath) !== undefined;
1765
+ } catch {
1766
+ return undefined;
1767
+ }
1768
+ };
1769
+
1770
+ /** The real admission; with an injected {@link DispatchRouterDeps.approvalsEnv}, its rule 3 reads that store (Phase 4). */
1771
+ const defaultAdmission = async (config: AdmissionConfig): Promise<Pick<AdmissionService, "admit" | "resolve">> => {
1772
+ const env = deps.approvalsEnv;
1773
+ if (env === undefined) return createAdmission(config);
1774
+ const days = config.approvalDays ?? DEFAULT_REPO_APPROVAL_DAYS;
1775
+ return createAdmission(config, { ...defaultAdmissionDeps({ approvalDays: days }), approvals: () => validApprovals(days, env) });
1776
+ };
1777
+
1778
+ // Cross-repo (P1.4): one admission per resolved `{ repoParents, repoDepth, repoExclude, repoApprovalDays }` (it caches its git
1779
+ // results for 5 s).
1780
+ let admissionMemo: { readonly key: string; readonly service: Pick<AdmissionService, "admit" | "resolve"> } | undefined;
1781
+ const admissionFor = async (config: AdmissionConfig): Promise<Pick<AdmissionService, "admit" | "resolve">> => {
1782
+ const key = JSON.stringify([config.parents, config.depth, config.exclude, config.approvalDays ?? null]);
1783
+ if (admissionMemo !== undefined && admissionMemo.key === key) return admissionMemo.service;
1784
+ const service = deps.createAdmission !== undefined ? deps.createAdmission(config) : await defaultAdmission(config);
1785
+ admissionMemo = { key, service };
1786
+ return service;
1787
+ };
1788
+
1789
+ /**
1790
+ * Cross-repo (P1.4): the admission input of a role dispatch. Undefined — today's text match, nothing else (I9) — unless roles mode
1791
+ * is active on v2 and `routing.repoParents` is set or the route line declares `repo=` / `branch=` (`branch=` alone needs no parent:
1792
+ * the session repository answers it). `known`: the session directory and the worktrees of the orchestrator's working set.
1793
+ */
1794
+ const crossRepoOf = async (
1795
+ cfg: RouterConfig,
1796
+ orchestratorSessionID: string,
1797
+ sessionDirectory: string,
1798
+ line: Pick<RouteLine, "repo" | "branch"> | null | undefined,
1799
+ ): Promise<WorkRootAdmissionInput | undefined> => {
1800
+ const routing = resolveRolesRouting(cfg, "v2");
1801
+ const repo = line?.repo ?? undefined;
1802
+ const branch = line?.branch ?? undefined;
1803
+ if (routing.delegation !== "roles") return undefined;
1804
+ if (routing.repoParents.length === 0 && repo === undefined && branch === undefined) return undefined;
1805
+ const admission = await admissionFor({
1806
+ parents: routing.repoParents,
1807
+ depth: routing.repoDepth,
1808
+ exclude: routing.repoExclude,
1809
+ approvalDays: routing.repoApprovalDays,
1810
+ });
1811
+ // Phase 4 (SD-P4-12): a working-set entry whose approval lapsed (revoked, expired) is dropped before it can admit by rule 2;
1812
+ // a store read without git, only with parents (I9) and only when an entry is backed by an approval. Phase 4 QA (M1): with the
1813
+ // parents emptied at runtime no approval applies (the store is not read), so an approval-backed entry is left out; admission's
1814
+ // rule 2 then admits only worktrees of the session repository.
1815
+ const workingSet = routing.repoParents.length === 0
1816
+ ? workingSetOf(orchestratorSessionID).filter((location) => location.approval === undefined)
1817
+ : pruneLapsedApprovals(workingSetOf(orchestratorSessionID), routing.repoApprovalDays, deps.approvalsEnv, workRootDeps.platform);
1818
+ const known = [...new Set([sessionDirectory, ...workingSet.map((location) => location.worktree)])];
1819
+ return { repo, branch, admission, sessionRepository: sessionDirectory, known };
1820
+ };
1821
+
1822
+ /** `child` lies strictly below `parent` (text comparison, no filesystem call). */
1823
+ const strictlyWithin = (parent: string, child: string): boolean => {
1824
+ const platform = workRootDeps.platform;
1825
+ const p = normalizeRootText(parent, platform);
1826
+ const c = normalizeRootText(child, platform);
1827
+ const sep = platform === "win32" ? "\\" : "/";
1828
+ return c.length > p.length && c.startsWith(p.endsWith(sep) ? p : p + sep);
1829
+ };
1830
+
1831
+ /**
1832
+ * The work root of a role dispatch: {@link resolveRoleWorkRoot} plus the route-flow rules of the cross-repo QA (round 1).
1833
+ * - F3: a `repo=` / `branch=` / `root=` the route line declared but the parser rejected (invalid value, bare key, duplicate or
1834
+ * conflicting key) gives NO work root and a note, never the session directory (design §5).
1835
+ * - F6: a `root=` that is the session directory, with `branch=`, is accepted when the worktree on that branch contains it (the
1836
+ * session may have started in a subdirectory); and a worktree bound without `root=` that contains the session directory keeps
1837
+ * the session directory as the work root (the write root does not grow to the worktree's top level).
1838
+ */
1839
+ const bindWorkRoot = async (
1840
+ cfg: RouterConfig,
1841
+ orchestratorSessionID: string,
1842
+ sessionDirectory: string,
1843
+ line: RouteLine | null | undefined,
1844
+ ): Promise<WorkRootResolution> => {
1845
+ const declaredRoot = line?.root ?? null;
1846
+ const invalid = line?.invalidCrossRepo ?? [];
1847
+ if (invalid.length > 0) {
1848
+ const note = invalid
1849
+ .map(({ key, value }) => `${key}=${value} is not a valid ${key === "repo" ? "repository name" : key === "branch" ? "branch name" : "absolute work root"}: no work root. Fix the route line.`)
1850
+ .join(" ");
1851
+ return { workRoot: null, requested: declaredRoot, note };
1852
+ }
1853
+ const cross = await crossRepoOf(cfg, orchestratorSessionID, sessionDirectory, line);
1854
+ const first = await resolveRoleWorkRoot({ root: declaredRoot, sessionDirectory }, workRootDeps, cross);
1855
+ const canonicalSession = (): string | null => {
1856
+ try {
1857
+ const resolved = workRootDeps.realpath(sessionDirectory);
1858
+ return typeof resolved === "string" && resolved !== "" ? resolved : null;
1859
+ } catch {
1860
+ return null;
1861
+ }
1862
+ };
1863
+ const platform = workRootDeps.platform;
1864
+ /**
1865
+ * QA round 2: `worktree` holds the session directory — not merely by text: a worktree or repository NESTED inside `worktree`
1866
+ * (`.worktrees/`, `.claude/worktrees/`) lies below it too. Walking up from the canonical session directory to `worktree`, the
1867
+ * first directory that is itself a git top level (hardened `rev-parse --show-toplevel`, whose ceiling is the directory's parent,
1868
+ * so a plain subdirectory answers nothing) must be `worktree`; any other top level on the way, or anything unreadable, is "no".
1869
+ */
1870
+ const sessionBelongsTo = async (worktree: string): Promise<boolean> => {
1871
+ if (!strictlyWithin(worktree, sessionDirectory)) return false;
1872
+ const start = canonicalSession();
1873
+ if (start === null) return false;
1874
+ try {
1875
+ const bound = normalizeRootText(workRootDeps.realpath(worktree), platform);
1876
+ let dir = start;
1877
+ for (let depth = 0; depth < 64; depth++) {
1878
+ const here = normalizeRootText(dir, platform);
1879
+ if (here === bound) return true;
1880
+ if (!strictlyWithin(bound, here)) return false;
1881
+ const top = await showToplevel(dir);
1882
+ if (top !== undefined && top !== "" && normalizeRootText(workRootDeps.realpath(top), platform) === here) return false;
1883
+ const parent = dirname(dir);
1884
+ if (parent === dir) return false;
1885
+ dir = parent;
1886
+ }
1887
+ return false;
1888
+ } catch {
1889
+ return false;
1890
+ }
1891
+ };
1892
+ const atSession = declaredRoot !== null && line?.branch !== undefined && cross?.admission !== undefined
1893
+ && normalizeRootText(declaredRoot, platform) === normalizeRootText(sessionDirectory, platform);
1894
+ if (atSession && first.workRoot === null) {
1895
+ // The session directory may be inside a worktree rather than its top level: bind by branch, then check it holds the session.
1896
+ const retry = await resolveRoleWorkRoot({ root: null, sessionDirectory }, workRootDeps, cross);
1897
+ const inside = retry.location !== undefined && retry.workRoot !== null && await sessionBelongsTo(retry.location.worktree);
1898
+ const dir = inside ? canonicalSession() : null;
1899
+ return dir === null ? first : { ...retry, workRoot: dir, requested: declaredRoot };
1900
+ }
1901
+ if (declaredRoot === null && first.workRoot !== null && first.location !== undefined && await sessionBelongsTo(first.location.worktree)) {
1902
+ const dir = canonicalSession();
1903
+ if (dir !== null) return { ...first, workRoot: dir };
1904
+ }
1905
+ return first;
1906
+ };
1907
+
1908
+ /**
1909
+ * Q9 (QA round 3): the target the route line of an EXACT resume declares is the child's bound root — by text only, no admission
1910
+ * and no filesystem call: a `root=` equal (normalised) to the bound work root or its worktree, a `repo=` equal to the bound
1911
+ * repository's name, a `branch=` equal to the bound branch. An invalid declaration, or a bound grant without a work root, never is.
1912
+ */
1913
+ const declaresBoundRoot = (line: RouteLine | null | undefined, grant: DispatchGrant): boolean => {
1914
+ if (line === null || line === undefined) return true;
1915
+ if ((line.invalidCrossRepo?.length ?? 0) > 0 || grant.workRoot === null) return false;
1916
+ const platform = workRootDeps.platform;
1917
+ const location = grant.location;
1918
+ if (line.root !== undefined) {
1919
+ const declared = normalizeRootText(line.root, platform);
1920
+ const candidates = location === undefined ? [grant.workRoot] : [grant.workRoot, location.worktree];
1921
+ if (!candidates.some((candidate) => normalizeRootText(candidate, platform) === declared)) return false;
1922
+ }
1923
+ const sameName = (a: string, b: string): boolean => (platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
1924
+ if (line.repo !== undefined && (location === undefined || !sameName(location.name, line.repo))) return false;
1925
+ if (line.branch !== undefined && (location === undefined || location.branch !== line.branch.replace(/^refs\/heads\//, ""))) return false;
1926
+ return true;
1927
+ };
1928
+
1929
+ /**
1930
+ * D17 (cross-repo QA): the target an exact resume declares is the child's bound root. The text fast path ({@link declaresBoundRoot})
1931
+ * runs no admission and no filesystem call. When it does not match — `repo=<worktree directory>` (Q10: the location's name is the
1932
+ * repository's), a `root=` spelled through a junction / symlink / subst drive — the declaration is resolved exactly as a fresh
1933
+ * dispatch resolves it ({@link bindWorkRoot}) and accepted when the work root it binds is the child's bound work root or its
1934
+ * worktree (`normalizeRootText` of the realpath on both sides). So admission may now run on a resume, but only when the fast path
1935
+ * fails. Whatever the answer, the resume keeps the BOUND grant: the resolution is only compared, never adopted (no widening).
1936
+ */
1937
+ const declaresBoundTarget = async (
1938
+ cfg: RouterConfig,
1939
+ orchestratorSessionID: string,
1940
+ sessionDirectory: string,
1941
+ line: RouteLine | null | undefined,
1942
+ grant: DispatchGrant,
1943
+ ): Promise<boolean> => {
1944
+ if (declaresBoundRoot(line, grant)) return true;
1945
+ if (line === null || line === undefined || (line.invalidCrossRepo?.length ?? 0) > 0 || grant.workRoot === null) return false;
1946
+ const platform = workRootDeps.platform;
1947
+ const canonicalText = (path: string): string => {
1948
+ try {
1949
+ const real = workRootDeps.realpath(path);
1950
+ return normalizeRootText(typeof real === "string" && real !== "" ? real : path, platform);
1951
+ } catch {
1952
+ return normalizeRootText(path, platform);
1953
+ }
1954
+ };
1955
+ const resolved = await bindWorkRoot(cfg, orchestratorSessionID, sessionDirectory, line);
1956
+ if (resolved.workRoot === null) return false;
1957
+ const got = canonicalText(resolved.workRoot);
1958
+ const bound = grant.location === undefined ? [grant.workRoot] : [grant.workRoot, grant.location.worktree];
1959
+ return bound.some((candidate) => canonicalText(candidate) === got);
1960
+ };
1961
+
1962
+ /** Q9 (QA round 3): the refusal of an exact resume whose route line declares another target than the child's bound root. */
1963
+ const boundRootRefusal = (grant: DispatchGrant): string => {
1964
+ const where = grant.workRoot === null ? "no work root" : displaySafe(grant.workRoot);
1965
+ const location = grant.location;
1966
+ const detail = location === undefined
1967
+ ? ""
1968
+ : ` (repository ${displaySafe(location.name)}, branch ${location.branch === null ? "(detached)" : displaySafe(location.branch)})`;
1969
+ return `this child is bound to ${where}${detail}; a resume cannot change its work root: dispatch a new child`;
1970
+ };
1971
+
1470
1972
  /**
1471
1973
  * The rung a resumed child runs on: the dispatch registry's record (its `tier` is the role tier the router registered), else the
1472
1974
  * child session's own model; unknown → a model off every ladder, which the kernel lifts to the window ceiling (never below).
@@ -1514,13 +2016,53 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1514
2016
  if (lined.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
1515
2017
 
1516
2018
  // 2. work root: `root=` from the trace only, text-compared with `git worktree list --porcelain` before any filesystem call.
1517
- const root = await resolveRoleWorkRoot({ root: lined.trace.routeLine?.root ?? null, sessionDirectory }, workRootDeps);
2019
+ // Cross-repo (P1.4): `repo=` / `branch=`, and a `root=` the text match does not find, are bound through admission.
2020
+ const declaredLine = lined.trace.routeLine;
1518
2021
  const bound = resumeID === null ? undefined : currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) });
2022
+ // Q9: a dispatch that DECLARED a target (`repo=` / `branch=` / `root=`, or an invalid `repo=` / `branch=` / `root=`) whose
2023
+ // binding was refused is refused with the note — it never runs in the session directory instead. A dispatch that declared
2024
+ // nothing is untouched.
2025
+ const declaredTarget = declaredLine !== null && declaredLine !== undefined
2026
+ && (declaredLine.repo !== undefined || declaredLine.branch !== undefined || declaredLine.root !== undefined || (declaredLine.invalidCrossRepo?.length ?? 0) > 0);
2027
+ // A resume of an exactly bound child keeps the child's bound root: a target it declares must name that root — by text first (no
2028
+ // admission), else by the same resolution a fresh dispatch uses (D17) — else the resume is refused: a resume cannot move a child.
2029
+ const exactBound = bound?.kind === "exact" ? bound.grant : undefined;
2030
+ // Phase 4 QA (m2): a child bound through an approval resumes only while that approval applies (store read, no git): a revoked or
2031
+ // expired approval ends the binding, so the resume is refused and the lapsed location never rejoins the working set.
2032
+ const boundApproval = exactBound?.location?.approval;
2033
+ const lapsedApproval = boundApproval === undefined ? undefined
2034
+ : lapsedApprovalReason(boundApproval, resolveRolesRouting(rp.cfg, "v2").repoApprovalDays, deps.approvalsEnv, workRootDeps.platform);
2035
+ if (lapsedApproval !== undefined) throw new RoleDispatchRefusal(agent, displaySafe(`resume refused: ${lapsedApproval}`));
2036
+ if (declaredTarget && exactBound !== undefined && !await declaresBoundTarget(rp.cfg, call.sessionID, sessionDirectory, declaredLine, exactBound)) {
2037
+ throw new RoleDispatchRefusal(agent, boundRootRefusal(exactBound));
2038
+ }
2039
+ const root: WorkRootResolution = declaredTarget && exactBound !== undefined
2040
+ ? {
2041
+ workRoot: exactBound.workRoot,
2042
+ requested: declaredLine?.root ?? null,
2043
+ note: null,
2044
+ ...(exactBound.location === undefined ? {} : { location: exactBound.location }),
2045
+ }
2046
+ : await bindWorkRoot(rp.cfg, call.sessionID, sessionDirectory, declaredLine);
2047
+ // The note may echo route-line text and filesystem names: escaped before it reaches the orchestrator.
2048
+ if (declaredTarget && root.workRoot === null && root.note !== null && bound?.kind !== "exact") {
2049
+ // Phase 4 (SD-P4-8): a candidate a human could approve gets the details git reports about it (never the dispatch text).
2050
+ // Only here, on the dispatch bind path: `declaresBoundTarget` also runs `bindWorkRoot` but only compares, so no git there.
2051
+ const approval = root.approvable === undefined ? undefined : await approvalNote(root.approvable, {
2052
+ exclude: resolveRolesRouting(rp.cfg, "v2").repoExclude,
2053
+ ...(deps.approvalsEnv === undefined ? {} : { env: deps.approvalsEnv }),
2054
+ ...(deps.inspectCandidate === undefined ? {} : { inspect: deps.inspectCandidate }),
2055
+ });
2056
+ throw new RoleDispatchRefusal(agent, displaySafe(approval === undefined ? root.note : `${root.note} ${approval}`));
2057
+ }
2058
+ // Phase 4 (SD-P4-7): a fresh binding backed by an approval records its use (fire and forget, at most once per hour).
2059
+ const approvedBy = declaredTarget && exactBound !== undefined ? undefined : root.location?.approval;
2060
+ if (root.workRoot !== null && approvedBy !== undefined) touchApproval(approvedBy, resolveRolesRouting(rp.cfg, "v2").repoApprovalDays, deps.approvalsEnv);
1519
2061
 
1520
2062
  // 3. classify in the dispatch's own root (QA-G-B-3 (1)): an absolute path inside it is no `external_dir`. A resume of an exactly
1521
2063
  // bound child is classified in its bound root (QA-P33F1-1-1); without a `root=` (the work root is the session directory) or a
1522
2064
  // validated one, in the session directory as the host names it.
1523
- const requestedRoot = root.requested !== null ? root.workRoot : null;
2065
+ const requestedRoot = root.requested !== null || root.location !== undefined ? root.workRoot : null;
1524
2066
  const classifyCwd = (bound?.kind === "exact" ? bound.grant.workRoot : null) ?? requestedRoot ?? sessionDirectory;
1525
2067
  const result = await classify({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
1526
2068
  if (result.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
@@ -1544,7 +2086,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1544
2086
  // 4. grant (widened actions of a resume recompute the floor, handoff 36). QA-P21-2-1: a resume of an EXACTLY bound child keeps
1545
2087
  // what that child holds (its bound grant) plus the widened actions — the resume prompt alone ("continue") would lose them.
1546
2088
  const grant: DispatchGrant = bound?.kind === "exact" ? resumedGrant(bound.grant, call.widened ?? [])
1547
- : grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine);
2089
+ : grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine, root.location);
1548
2090
 
1549
2091
  // 5. effective detection (S10/P-9, A34; handoff 5): never `result.detection` as is. QA-G-B-1: a resume that names no
1550
2092
  // `[acceptance]` block of its own carries the one of the dispatch it resumes (and its `VERIFY:` lines, when it names none), so
@@ -1567,6 +2109,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1567
2109
  const bypassed = deps.isBypassed?.(call.sessionID) === true;
1568
2110
  const env = deps.env === undefined ? {} : { env: deps.env };
1569
2111
  const verifyRoot = verifyRootOf(grant, sessionDirectory, workRootDeps.realpath);
2112
+ const inReadSet = readSetFor(rp.cfg, call.sessionID);
1570
2113
  const routerGate = roleRouterGate({
1571
2114
  cfg: rp.cfg, bypassed, acceptance, ...env,
1572
2115
  // QA-P21-1-2, QA-P21-2 nit 3. QA-G-B-2-1: a carried acceptance is never deferred (its gate runs at the return); its change-set
@@ -1575,12 +2118,12 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1575
2118
  deferred: carried === null
1576
2119
  ? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
1577
2120
  : (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block),
1578
- outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd), // DF2-F1, QA-P33F1-1-1, nit 3
2121
+ outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd, inReadSet), // DF2-F1, QA-P33F1-1-1, nit 3
1579
2122
  });
1580
2123
  // QA-G-B-7: the gate verifies nothing at all (enforcement off, /bypass, `require: never`, a cwd outside the root it verifies in)
1581
2124
  // → detection `none`.
1582
2125
  const verifies = roleVerificationRuns({
1583
- cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd),
2126
+ cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd, inReadSet),
1584
2127
  });
1585
2128
  const detection = effectiveDetection({ routerGate, claim, acceptance, verifies });
1586
2129
 
@@ -1727,7 +2270,57 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1727
2270
  ...(carried !== null ? { carried: true as const } : {}), // QA-G-B-2-1
1728
2271
  };
1729
2272
  rememberRoutedRole(routed);
2273
+ // Cross-repo (P1.4, QA round 1 F5/F9): the dispatch is accepted. The location the GRANT holds (a resume keeps its bound one)
2274
+ // joins the orchestrator's working set (rule 2 for its later dispatches), and only when `routing.repoParents` is set: a
2275
+ // `branch=` / `repo=` alone binds through declare-then-check but does not grow the working set.
2276
+ if (grant.location !== undefined && grant.workRoot !== null && resolveRolesRouting(rp.cfg, "v2").repoParents.length > 0) addToWorkingSet(call.sessionID, grant.location);
1730
2277
  if (raised !== null && resumeID !== null) resumeRaises.delete(resumeID); // QA-P21-2-2: consumed once, by a routed resume
2278
+ // P2g (OD6): a role delegate is told its work root. The header goes FIRST; the nonce line / carried block stay last. Only a
2279
+ // grant with a work root and read access gets one; a resume only when its binding is exact (the bound grant is what it holds).
2280
+ const exactResume = resumed && bound?.kind === "exact";
2281
+ // QA round 1 #11: the router's header is always the one the delegate reads. A header the orchestrator copied from another
2282
+ // dispatch (it names that dispatch's work root) is stripped first and replaced, never kept in place of ours.
2283
+ // QA round 1 #12: `dispatchHeader: false` turns the header off, except that a work root other than the session directory is
2284
+ // still told (the work-root rule points to ENVIRONMENT, which is the session directory): then a MINIMAL header, the identity
2285
+ // paragraph (so stripDispatchHeader still removes it before DoD inference) and the `Working directory:` paragraph, no
2286
+ // repositories paragraph.
2287
+ const headerEligible = grant.workRoot !== null
2288
+ && (grant.actions.has("read") || grant.actions.has("glob") || grant.actions.has("grep"))
2289
+ && (!resumed || exactResume);
2290
+ const headerOn = rp.cfg.dispatchHeader !== false;
2291
+ const tellsOtherRoot = (root: string): boolean => {
2292
+ const platform = workRootDeps.platform;
2293
+ const same = (candidate: string): boolean => normalizeRootText(root, platform) === normalizeRootText(candidate, platform);
2294
+ if (same(sessionDirectory)) return false;
2295
+ try {
2296
+ const real = workRootDeps.realpath(sessionDirectory);
2297
+ return !(typeof real === "string" && real !== "" && same(real));
2298
+ } catch {
2299
+ return true;
2300
+ }
2301
+ };
2302
+ // Q8 (invariant I9): the header is emitted only when it is relevant — cross-repo is configured (`routing.repoParents`), the route
2303
+ // line declared `repo=` / `branch=` / `root=`, or the work root differs from the session directory. Otherwise the role prompt
2304
+ // is byte-identical to what it was before the header existed (route-stripped text + nonce / carried block).
2305
+ const headerRelevant = (root: string): boolean =>
2306
+ resolveRolesRouting(rp.cfg, "v2").repoParents.length > 0
2307
+ || declaredLine?.repo !== undefined || declaredLine?.branch !== undefined || declaredLine?.root !== undefined
2308
+ || tellsOtherRoot(root);
2309
+ const headerWanted = headerEligible && grant.workRoot !== null && headerRelevant(grant.workRoot) && (headerOn || tellsOtherRoot(grant.workRoot));
2310
+ const finalPrompt = headerWanted && grant.workRoot !== null
2311
+ ? `${buildRoleDispatchHeader({
2312
+ agent,
2313
+ workRoot: grant.workRoot,
2314
+ edits: grant.actions.has("edit"),
2315
+ ...(grant.location === undefined ? {} : { location: grant.location }),
2316
+ ...(headerOn
2317
+ ? { workingSet: workingSetOf(call.sessionID), readParents: resolveRolesRouting(rp.cfg, "v2").repoParents }
2318
+ : {}),
2319
+ ...(exactResume ? { exactResume: true } : {}),
2320
+ })}${stripDispatchHeader(outPrompt)}`
2321
+ // QA round 3: a header the orchestrator copied (it names another dispatch's root and verb) is stripped even when the router
2322
+ // adds none; a prompt without one is returned unchanged (Q8: byte-identical).
2323
+ : stripDispatchHeader(outPrompt);
1731
2324
 
1732
2325
  decided.set(call.callID, {
1733
2326
  parentSessionID: call.sessionID,
@@ -1753,7 +2346,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1753
2346
  trim(decided, MAX_PENDING);
1754
2347
  return {
1755
2348
  mode,
1756
- ...(outPrompt !== prompt ? { prompt: outPrompt } : {}),
2349
+ ...(finalPrompt !== prompt ? { prompt: finalPrompt } : {}),
1757
2350
  model,
1758
2351
  ...(logged === null ? {} : { decisionID: logged }),
1759
2352
  ...(outDescription === null ? {} : { description: outDescription }),