opencode-model-router 2.6.1 → 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 (47) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +3 -1
  3. package/package.json +2 -2
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +12 -1
  6. package/src/compat/v2-hooks.ts +255 -53
  7. package/src/index.ts +328 -37
  8. package/src/router/config.ts +48 -2
  9. package/src/router/dispatch-header.ts +95 -2
  10. package/src/router/git-tools.ts +165 -9
  11. package/src/router/protocol.ts +5 -1
  12. package/src/router/role-agents.ts +110 -3
  13. package/src/router/roles-config.ts +83 -0
  14. package/src/router/roles.ts +1 -1
  15. package/src/router/sessions.ts +11 -0
  16. package/src/routing/classify/route-line.ts +96 -5
  17. package/src/routing/classify/types.ts +26 -0
  18. package/src/routing/outcomes/signals.ts +17 -0
  19. package/src/routing/roles/admission.ts +1028 -0
  20. package/src/routing/roles/approvals.ts +876 -0
  21. package/src/routing/roles/binding.ts +17 -4
  22. package/src/routing/roles/check-placement.ts +112 -0
  23. package/src/routing/roles/git-root.ts +500 -0
  24. package/src/routing/roles/policy.ts +9 -0
  25. package/src/routing/roles/read-set.ts +325 -0
  26. package/src/routing/roles/work-root.ts +9 -1
  27. package/src/routing/wire/dispatch.ts +611 -18
  28. package/src/routing/wire/working-set.ts +58 -0
  29. package/src/util/linear-trim.ts +32 -0
  30. package/src/verify/batch.ts +7 -2
  31. package/src/verify/branch.ts +135 -0
  32. package/src/verify/deterministic.ts +232 -10
  33. package/src/verify/dispatch.ts +284 -9
  34. package/src/verify/dod.ts +46 -0
  35. package/src/verify/edges.ts +817 -0
  36. package/src/verify/gate.ts +349 -16
  37. package/src/verify/git-top.ts +43 -0
  38. package/src/verify/head.ts +107 -0
  39. package/src/verify/pending.ts +155 -8
  40. package/src/verify/perimeter.ts +1180 -0
  41. package/src/verify/pin.ts +109 -0
  42. package/src/verify/reference.ts +174 -30
  43. package/src/verify/risk.ts +16 -3
  44. package/src/verify/runner.ts +706 -32
  45. package/src/verify/tree.ts +347 -8
  46. package/src/verify/types.ts +57 -0
  47. package/src/verify/wiring.ts +1324 -35
package/src/index.ts CHANGED
@@ -23,13 +23,13 @@ import {
23
23
  } from "./router/config";
24
24
  import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
25
25
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
26
- import { gitTools } from "./router/git-tools";
26
+ import { gitTools, nearestCheckout, type GitRootResolver } from "./router/git-tools";
27
27
  import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
28
28
  import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
29
29
  import { filterSensitiveGrep } from "./router/sensitive-paths";
30
30
  import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
31
31
  import { stripDelegateInstructions } from "./router/instructions";
32
- import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot } from "./router/dispatch-header";
32
+ import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot, stripDispatchHeader } from "./router/dispatch-header";
33
33
  import { detectFalseRefusal, parseTaskResult as parseRefusalTaskResult } from "./router/false-refusal";
34
34
  import {
35
35
  buildTiersOutput,
@@ -74,10 +74,11 @@ import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from
74
74
  import { currentBinding } from "./routing/roles/binding";
75
75
  import { authorityTool, requestedAuthority } from "./routing/roles/authority";
76
76
  import {
77
- CARRIED_NO_PROCESS_REASON, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions, routedRoleOf, strippedRouteRoot,
77
+ CARRIED_NO_PROCESS_REASON, lapsedApprovalReason, pruneLapsedApprovals, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions,
78
+ routedRoleOf, strippedRouteRoot,
78
79
  } from "./routing/wire/dispatch";
79
80
  import { roleTierOrder } from "./routing/engine/ladders";
80
- import { detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
81
+ import { acceptanceScriptsOf, detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
81
82
  import type { IngestSettings } from "./routing/outcomes/ingest";
82
83
  import { captureBudget } from "./guard/enforce";
83
84
  import { budgetClaimObserved, isIncompleteVerdict } from "./verify/checker";
@@ -96,6 +97,7 @@ import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/comman
96
97
  import type { HostAgentInfo } from "./routing/engine/types";
97
98
  import { createEngineRuntime } from "./routing/wire/runtime";
98
99
  import type { EngineRuntime } from "./routing/wire/runtime";
100
+ import { forgetWorkingSet, workingSetOf } from "./routing/wire/working-set";
99
101
  import {
100
102
  advisorSettings,
101
103
  catalogFromProviders,
@@ -125,7 +127,7 @@ import { createTrajectoryStore } from "./telemetry/trajectory";
125
127
  import { createGuardStore } from "./guard/store";
126
128
  import { createIdleTtlSweeper } from "./router/idle-sweep";
127
129
  import { guardBeforeCall, guardAfterCall, guardRefusedCall, formatScorecard } from "./guard/enforce";
128
- import { mkdirSync, writeFileSync, existsSync } from "node:fs";
130
+ import { mkdirSync, writeFileSync, existsSync, realpathSync, statSync } from "node:fs";
129
131
  import { tmpdir } from "node:os";
130
132
  import { join, isAbsolute } from "node:path";
131
133
  import { access, readFile as fsReadFile } from "node:fs/promises";
@@ -150,7 +152,14 @@ import {
150
152
  buildForcingNote,
151
153
  buildAcceptedSuffix,
152
154
  } from "./verify/dispatch";
153
- import { requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
155
+ import { canonicalAuthorityPath, captureRootOf, insideWorkRoot, requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
156
+ import { resolveCheckPlacements } from "./routing/roles/check-placement";
157
+ // Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json
158
+ // lookup fails (the e2e child bundle). Each module below is used only inside functions.
159
+ import { createAdmission, type AdmissionConfig, type AdmissionService } from "./routing/roles/admission";
160
+ import * as gitRoot from "./routing/roles/git-root";
161
+ import * as approvalsCommands from "./commands/approvals";
162
+ import { createRepoProbe, displaySafe, readSetEligible, readSetPredicate } from "./routing/roles/read-set";
154
163
  import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard, startCostRatio } from "./escalate/ladder";
155
164
  import { createCatalogLookup, planFirstAttempt, planNextAttempt } from "./escalate/resume";
156
165
  import type { AttemptPlan, CatalogLookup } from "./escalate/resume";
@@ -183,6 +192,16 @@ function describeError(error: unknown): string {
183
192
  }
184
193
  }
185
194
 
195
+ /**
196
+ * Cross-repo P2b.7 (OD1=B, v2 only): a tier dispatch honours no per-check `cwd=`. The first check of the DoD that sets one (0-based
197
+ * index) is the refusal the gate reports (`why: "tier"`, nothing runs); undefined when none does. `scope=` alone is ignored.
198
+ */
199
+ function tierCheckCwdRefusal(dod: Parameters<typeof resolveCheckPlacements>[0]): NonNullable<Parameters<typeof accept>[0]["refusedCheck"]> | undefined {
200
+ const index = dod.checks.findIndex((check) => check.cwd !== undefined);
201
+ const check = index < 0 ? undefined : dod.checks[index];
202
+ return check?.cwd === undefined ? undefined : { index, kind: check.kind, text: check.cwd, why: "tier" };
203
+ }
204
+
186
205
  /**
187
206
  * #84 P2.2 (advisor `tierDispatches`): dispatch rows WITHOUT a role at or after `since` — non-annotation `dispatch` decision rows,
188
207
  * the first row per decision id (as `summarizeRoles` keeps them), whose row names no role and whose chosen key is not a role's.
@@ -247,7 +266,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
247
266
  * `/router` dispatch. Decides and persists here; rendering lives in
248
267
  * src/commands/output.ts.
249
268
  */
250
- function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>): string {
269
+ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>, approvals = false): string {
251
270
  const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
252
271
  const sub = (tokens[0] ?? "").toLowerCase();
253
272
 
@@ -280,10 +299,14 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string,
280
299
  resolveEnforcementMode({ config: cfg, env: process.env }).mode,
281
300
  // `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
282
301
  // #84 P2.2: the role lines, only when the caller hands roles (roles mode on v2); otherwise the help is what it was.
283
- { stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }) },
302
+ // Cross-repo P4.7: `/router approve|repos|revoke`, only where they run (SD-P4-10); otherwise the help is what it was.
303
+ { stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }), ...(approvals ? { approvals: true } : {}) },
284
304
  );
285
305
  }
286
306
 
307
+ /** Cross-repo P4.7: the `/router` subcommands of `commands/approvals.ts` (checked before that module is used). */
308
+ const APPROVAL_SUBCOMMANDS: ReadonlySet<string> = new Set(["approve", "repos", "revoke"]);
309
+
287
310
  /** `/budget` dispatch. Persists the switch, then renders. */
288
311
  function buildBudgetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
289
312
  const modes = cfg.modes;
@@ -507,6 +530,19 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
507
530
  // every role branch below is skipped there and both stay byte-identical (§2.7, I1, I8).
508
531
  // -------------------------------------------------------------------------
509
532
  const isV2Host = ctx.routerHost === "v2";
533
+ /**
534
+ * Cross-repo P2e.6 (OD-P2e-2): a dispatch runs the full scope when the host is OpenCode v2 and the effective testScope is
535
+ * "full"; the deferred finish then never treats an empty change set as nothing to run. Always false on v1. Never throws (an
536
+ * unreadable verify block is not full).
537
+ */
538
+ const fullScopeOf = (cfg: Parameters<typeof resolveVerifyBudget>[0]): boolean => {
539
+ if (!isV2Host) return false;
540
+ try {
541
+ return resolveVerifyBudget(cfg).testScope === "full";
542
+ } catch {
543
+ return false;
544
+ }
545
+ };
510
546
  /**
511
547
  * QA-P21-1-8 (plan R8): the role runtime exists only when the plugin STARTED in roles mode — its role tools are registered at
512
548
  * start and its role agents only then (the v2 adapter logs "restart OpenCode" when the config switches to roles at runtime).
@@ -568,7 +604,160 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
568
604
  const answer = resolveWorkRoot(sessionID);
569
605
  if (!answer.role) return answer;
570
606
  const grant = currentBinding(sessionID, { maxOf: roleMaxOf })?.grant;
571
- return grant !== undefined && grant.actions.has(action) ? answer : { role: true, root: null };
607
+ if (grant === undefined || !grant.actions.has(action)) return { role: true, root: null };
608
+ // Phase 4 QA (m2): a binding backed by an approval holds only while the approval applies (store read, no git). The tools
609
+ // report a resolver's throw as their error, nothing runs.
610
+ const approval = grant.location?.approval;
611
+ if (approval !== undefined && answer.root !== null) {
612
+ const lapsed = lapsedApprovalReason(approval, resolveRolesRouting(cfg, "v2").repoApprovalDays);
613
+ if (lapsed !== undefined) throw new Error(`refused: ${lapsed}`);
614
+ }
615
+ // Cross-repo (P1.5): a binding that carries its repository makes it the repository `router_git_*` expects.
616
+ const repository = grant.location?.repository;
617
+ return repository !== undefined && answer.root !== null ? { ...answer, repository } : answer;
618
+ };
619
+ /**
620
+ * Cross-repo (P1.9, v2 only): the provenance line of a role's `read`, `glob` or `grep` whose target (the file, or the search root)
621
+ * canonicalises outside the session's work root but inside its read set (`routing/roles/read-set.ts`: the orchestrator's working
622
+ * set and the repositories below `routing.repoParents`). Undefined for a non-role session, an unbound or rootless one, a target in
623
+ * the work root, a target outside the read set, and whenever cross-repo is not in use (no parents and no working set: I9).
624
+ */
625
+ const repoProbe = createRepoProbe();
626
+ /** The read set R (P1.5) of the role dispatches of `orchestrator`: its working set plus `routing.repoParents`. Undefined when R adds nothing. */
627
+ const readSetMemberOf = (orchestrator: string | undefined): ReturnType<typeof readSetPredicate> => {
628
+ const routing = resolveRolesRouting(cfg, "v2");
629
+ const workingSet = orchestrator === undefined ? [] : workingSetOf(orchestrator);
630
+ return readSetPredicate({ parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSet, repoProbe);
631
+ };
632
+ /**
633
+ * Cross-repo P2a.3 (v2 only): R as a yes/no test on a canonical absolute path, for the role dispatch `routed` (its orchestrator's
634
+ * working set). Undefined when no R applies.
635
+ */
636
+ const roleReadSetFor = (routed: { readonly parentSessionID: string }): ((absPath: string) => boolean) | undefined => {
637
+ if (ctx.routerHost !== "v2") return undefined;
638
+ const member = readSetMemberOf(routed.parentSessionID === "" ? undefined : routed.parentSessionID);
639
+ return member === undefined ? undefined : (absPath) => member(absPath) !== undefined;
640
+ };
641
+ /** F11: the orchestrator that dispatched role session `sid`: its dispatch record, else the session's parent (as the v2 adapter's readSetOf). */
642
+ const orchestratorOf = async (sid: string): Promise<string | undefined> => {
643
+ const recorded = lookupDispatch(sid)?.parentSessionID ?? undefined;
644
+ if (recorded !== undefined && recorded !== "") return recorded;
645
+ const res = await ctx.client.session.get({ path: { id: sid } });
646
+ const parentID = res?.data?.parentID;
647
+ return typeof parentID === "string" && parentID !== "" ? parentID : undefined;
648
+ };
649
+ /**
650
+ * Cross-repo P4.7 (SD-P4-10, S1): whether `/router approve|repos|revoke` run for the session `sessionID`. All of: the v2 host,
651
+ * roles mode (`rolesNow()` non-empty), `routing.repoParents` non-empty, and a top-level session typed in by the human: not a
652
+ * role session, not a known child (a dispatch record), and the host reports it without a parent. A failed lookup refuses.
653
+ */
654
+ const approvalsCommandsAvailable = async (sessionID: unknown): Promise<boolean> => {
655
+ if (ctx.routerHost !== "v2" || rolesNow().size === 0) return false;
656
+ if (resolveRolesRouting(cfg, "v2").repoParents.length === 0) return false;
657
+ if (typeof sessionID !== "string" || sessionID === "") return false;
658
+ if (roleOfSession(sessionID) !== undefined || lookupDispatch(sessionID) !== undefined) return false;
659
+ try {
660
+ const res = await ctx.client.session.get({ path: { id: sessionID } });
661
+ const data = res?.data;
662
+ if (data === undefined || data === null || typeof data !== "object") return false;
663
+ const parentID: unknown = Reflect.get(data, "parentID");
664
+ return !(typeof parentID === "string" && parentID !== "");
665
+ } catch {
666
+ return false;
667
+ }
668
+ };
669
+ /**
670
+ * Cross-repo 3b.4 (F10): one admission per resolved `{ repoParents, repoDepth, repoExclude }` for `router_git` `root` (it caches its
671
+ * git results for 5 s). Created on first use.
672
+ */
673
+ type GitRootAdmission = Pick<AdmissionService, "admit" | "find">;
674
+ let gitRootAdmissionMemo: { readonly key: string; readonly service: GitRootAdmission } | undefined;
675
+ const gitRootAdmissionFor = async (config: AdmissionConfig): Promise<GitRootAdmission> => {
676
+ const key = JSON.stringify([config.parents, config.depth, config.exclude, config.approvalDays ?? null]);
677
+ if (gitRootAdmissionMemo !== undefined && gitRootAdmissionMemo.key === key) return gitRootAdmissionMemo.service;
678
+ const service = createAdmission(config);
679
+ gitRootAdmissionMemo = { key, service };
680
+ return service;
681
+ };
682
+ /**
683
+ * Cross-repo 3b.4 (OpenCode v2, roles mode, `routing.repoParents` at start; SD-3b-1): the `root` resolver of `router_git_*`. Step 1
684
+ * here, no filesystem call and no spawn: a role session (D21), an exact binding with a work root and `router_git` in the grant (I9,
685
+ * F12), a local read action in the grant (SD-3b-5), parents still configured. Steps 2–10: `routing/roles/git-root.ts`.
686
+ */
687
+ const resolveGitRootFor: GitRootResolver = async (value, { sessionID, signal, deadlineAt }) => {
688
+ if (roleOfSession(sessionID) === undefined) return { ok: false, reason: gitRoot.GIT_ROOT_ROLE_ONLY };
689
+ const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
690
+ const grant = binding?.kind === "exact" ? binding.grant : undefined;
691
+ const workRoot = grant?.workRoot;
692
+ if (grant === undefined || workRoot === null || workRoot === undefined || workRoot === "" || !grant.actions.has("router_git")) {
693
+ return { ok: false, reason: gitRoot.GIT_ROOT_NO_WORK_ROOT };
694
+ }
695
+ if (!grant.actions.has("read") && !grant.actions.has("glob") && !grant.actions.has("grep")) {
696
+ return { ok: false, reason: gitRoot.gitRootNeedsRead([...grant.actions].sort()) };
697
+ }
698
+ const routing = resolveRolesRouting(cfg, "v2");
699
+ if (routing.repoParents.length === 0) return { ok: false, reason: gitRoot.GIT_ROOT_NO_PARENTS };
700
+ // Phase 4 QA (m2): a binding backed by an approval that no longer applies (revoked, expired) inspects nothing (store read, no git).
701
+ const approval = grant.location?.approval;
702
+ const lapsed = approval === undefined ? undefined : lapsedApprovalReason(approval, routing.repoApprovalDays);
703
+ if (lapsed !== undefined) return { ok: false, reason: lapsed };
704
+ // QA round 1 (Phase 3 lot 1, F5): the session lookup is bounded by the call's deadline and signal (SD-3b-8).
705
+ const asked = await gitRoot.gitRootBounded(() => orchestratorOf(sessionID), { ...(signal === undefined ? {} : { signal }), deadlineAt });
706
+ if ("stop" in asked && asked.stop !== "failed") return { ok: false, reason: gitRoot.gitRootStopReason(value, asked.stop) };
707
+ // A failed lookup: no working set, R narrows to the parents (fail closed).
708
+ const orchestrator = "value" in asked ? asked.value : undefined;
709
+ // Phase 4 QA (M1): as for a dispatch (`crossRepoOf`), an entry whose approval lapsed is dropped before it can admit by rule 2;
710
+ // the drop reaches every working set, so the read set below shrinks with it.
711
+ const workingSet = (orchestrator === undefined ? [] : pruneLapsedApprovals(workingSetOf(orchestrator), routing.repoApprovalDays))
712
+ .map((location) => location.worktree);
713
+ const member = readSetMemberOf(orchestrator);
714
+ const admissionConfig = {
715
+ parents: routing.repoParents,
716
+ depth: routing.repoDepth,
717
+ exclude: routing.repoExclude,
718
+ approvalDays: routing.repoApprovalDays,
719
+ };
720
+ const known = [ctx.directory, ...(grant.location?.repository === undefined ? [] : [grant.location.repository]), ...workingSet];
721
+ return gitRoot.resolveGitRoot(value, { workRoot, parents: routing.repoParents, workingSet }, {
722
+ realpath: (path) => realpathSync.native(path),
723
+ isDirectory: (path) => statSync(path).isDirectory(),
724
+ nearestCheckout,
725
+ inReadSet: (path) => member !== undefined && member(path) !== undefined,
726
+ // Created on first use only: a text refusal never creates an admission.
727
+ admission: {
728
+ // Phase 4 QA (M1): the session repository is named, whatever order `known` reaches admission in.
729
+ admit: async (root, knownRepositories) => (await gitRootAdmissionFor(admissionConfig)).admit(root, knownRepositories, ctx.directory),
730
+ // QA round 1 (Phase 3 lot 1, F4): the resolver's `eligible` (the text gate and R) reaches the lookup.
731
+ find: async (name, opts) => (await gitRootAdmissionFor(admissionConfig)).find(name, opts),
732
+ },
733
+ known,
734
+ platform: process.platform,
735
+ ...(signal === undefined ? {} : { signal }),
736
+ deadlineAt,
737
+ });
738
+ };
739
+ const readProvenanceLine = async (input: any): Promise<string | undefined> => {
740
+ const sid: unknown = input?.sessionID;
741
+ if (ctx.routerHost !== "v2" || typeof sid !== "string" || !["read", "glob", "grep"].includes(input?.tool)) return undefined;
742
+ if (roleOfSession(sid) === undefined) return undefined;
743
+ const binding = currentBinding(sid, { maxOf: roleMaxOf });
744
+ const workRoot = binding?.kind === "exact" ? binding.grant.workRoot : null;
745
+ if (workRoot === null || workRoot === undefined) return undefined;
746
+ const args: Record<string, unknown> = input?.args && typeof input.args === "object" ? input.args : {};
747
+ const named = input.tool === "read" ? [args.filePath, args.path, args.file_path] : [args.path];
748
+ const target = named.find((value): value is string => typeof value === "string" && value !== "");
749
+ // No path (the session directory) or a relative one: the decision (v2-hooks `roleAuthorityDecision`) never lets it reach the
750
+ // read set (QA-1 F1) — it ran inside the work root or was refused — so there is no line. A fully qualified path canonicalises
751
+ // the same whatever the base, as in the decision; `.git` and below never reach R (F7).
752
+ if (target === undefined) return undefined;
753
+ const canonical = canonicalAuthorityPath(target, workRoot);
754
+ if (canonical === undefined || insideWorkRoot(canonical, workRoot) || !readSetEligible(target, canonical)) return undefined;
755
+ // The orchestrator that dispatched this role: its dispatch record, else the session's parent (as the v2 adapter's readSetOf).
756
+ const orchestrator = await orchestratorOf(sid);
757
+ const member = readSetMemberOf(orchestrator)?.(canonical);
758
+ if (member === undefined) return undefined;
759
+ // QA-1 F2: the name, branch and path come from the filesystem: display-safe.
760
+ return `[router: read from ${displaySafe(member.name)} (${displaySafe(member.branch ?? "detached")}) at ${displaySafe(member.repository)} — read-only in this dispatch]`;
572
761
  };
573
762
  /** What a routed role dispatch decided for its child's guard (QA-G-A3-3): the dispatched tier and the route line's `budget=`. */
574
763
  interface RoutedGuardInput { readonly agent: string; readonly tier: string; readonly routeBudget: number | null }
@@ -1104,6 +1293,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1104
1293
  // directory resolution). Switching to roles mode registers them on the next start.
1105
1294
  const rolesAtStart = rolesNow().size > 0;
1106
1295
  const dynamicRolesAtStart = [...rolesNow().values()].some((spec) => spec.authority.mode === "dynamic");
1296
+ /**
1297
+ * Cross-repo 3b.4 (SD-3b-1): `router_git_*` declare `root` only on v2, in roles mode, with `routing.repoParents` non-empty at start
1298
+ * (the tool map is fixed at start). Everywhere else, v1 included, schema and description stay byte-identical; no notice.
1299
+ */
1300
+ const crossRepoAtStart = ((): boolean => {
1301
+ if (!isV2Host || !rolesAtStart) return false;
1302
+ try {
1303
+ return resolveRolesRouting(cfg, "v2").repoParents.length > 0;
1304
+ } catch {
1305
+ return false;
1306
+ }
1307
+ })();
1107
1308
  /** `router_request_authority` dependencies (P1.6): the role by child session; only the parent of `dispatchOf` is read. */
1108
1309
  const authorityDeps = {
1109
1310
  roleOf: (child: string) => roleOfSession(child),
@@ -1116,28 +1317,24 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1116
1317
  },
1117
1318
  bindingOf: (child: string) => currentBinding(child, { maxOf: roleMaxOf }),
1118
1319
  };
1119
- /** Exact npm forms of a deterministic check's command → the `routing.run` script it names (`npm test`, `npm run <name>`). */
1120
- const NPM_SCRIPT_RE = /^npm(?:\.cmd)?\s+(?:(test|t)|run(?:-script)?\s+([A-Za-z0-9_][A-Za-z0-9_.:@+-]*))$/;
1121
- /** The acceptance commands of a role dispatch as `routing.run` names (handoff 13): only exact npm script forms count. */
1122
- const acceptanceScripts = (prompt: unknown, description: unknown): string[] => {
1123
- const dod = buildDelegationDoD({
1124
- prompt: typeof prompt === "string" ? prompt : undefined,
1125
- description: typeof description === "string" ? description : undefined,
1126
- });
1127
- if (dod.kind !== "deterministic") return [];
1128
- return dod.checks.flatMap((check) => {
1129
- const match = typeof check.command === "string" ? NPM_SCRIPT_RE.exec(check.command.trim()) : null;
1130
- return match === null ? [] : [match[1] !== undefined ? "test" : (match[2] as string)];
1131
- });
1132
- };
1320
+ /** The acceptance commands of a role dispatch as `routing.run` names (handoff 13); see `acceptanceScriptsOf`. */
1321
+ const acceptanceScripts = (prompt: unknown, description: unknown): string[] =>
1322
+ acceptanceScriptsOf(
1323
+ buildDelegationDoD({
1324
+ prompt: typeof prompt === "string" ? prompt : undefined,
1325
+ description: typeof description === "string" ? description : undefined,
1326
+ }),
1327
+ );
1133
1328
  /**
1134
1329
  * QA-P21-2-3: the read-only cap a role dispatch asks for itself — `CAP:N`, or `CAP:none` with a `reason:` line (an unjustified
1135
1330
  * `CAP:none` is no cap, as for tier dispatches); `null` when it names none (then the child gets no read-only cap).
1136
1331
  */
1137
1332
  const roleDispatchCap = (prompt: unknown): Cap | null => {
1138
1333
  if (typeof prompt !== "string") return null;
1139
- const parsed = parseCapDirective(prompt);
1140
- return parsed === "none" && !/\breason:/i.test(prompt) ? null : parsed;
1334
+ // P2g.3 (OD6): the orchestrator's own text — a router role header (a work root such as `.../CAP:9`) is never read as the cap.
1335
+ const text = stripDispatchHeader(prompt);
1336
+ const parsed = parseCapDirective(text);
1337
+ return parsed === "none" && !/\breason:/i.test(text) ? null : parsed;
1141
1338
  };
1142
1339
  /** Caps of fresh role dispatches, by the parent's call, until the child binds (bounded, oldest out). */
1143
1340
  const pendingRoleCaps = new Map<string, { agent: string; cap: Cap }>();
@@ -1172,8 +1369,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1172
1369
  */
1173
1370
  const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }): VerificationScope =>
1174
1371
  verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), typeof callID === "string" ? routedRoleOf(callID)?.verifyRoot : undefined);
1175
- /** The prompt as the orchestrator wrote it: without the router's nonce line (handoff 18; role dispatches carry no header). */
1176
- const withoutNonceLine = (prompt: string): string => prompt.replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
1372
+ /** The prompt as the orchestrator wrote it: without the router's role dispatch header (P2g.3, OD6) and its nonce line (handoff 18). */
1373
+ const withoutNonceLine = (prompt: string): string => stripDispatchHeader(prompt).replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
1177
1374
  /**
1178
1375
  * The parent's `task` call of a routed role dispatch (before it runs): a resume opens a new guard round for the child (its
1179
1376
  * budget and `budgetExhausted` are per round), and the re-dispatch signal (P1.4, handoff 16) compares the dispatch with the
@@ -1309,7 +1506,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1309
1506
  },
1310
1507
  tool: {
1311
1508
  // QA-G-A2-2: a role session's work root must belong to the repository its dispatch listed the worktrees in (this directory's).
1312
- ...gitTools(rolesAtStart ? { resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}) } : {}),
1509
+ ...gitTools(rolesAtStart ? {
1510
+ resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}),
1511
+ ...(crossRepoAtStart ? { resolveRoot: resolveGitRootFor } : {}),
1512
+ } : {}),
1313
1513
  // #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
1314
1514
  ...(rolesAtStart ? {
1315
1515
  router_run: routerRunTool({
@@ -1399,6 +1599,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1399
1599
  acceptance: args.acceptance,
1400
1600
  });
1401
1601
  const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
1602
+ // Cross-repo P2b.7 (OD1=B, v2 only): `delegate` is a tier dispatch; a per-check `cwd=` is unverifiable there. On v1 nothing changes.
1603
+ const tierRefusal = ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
1402
1604
 
1403
1605
  // Phase 2.3 (D10/D11): on v2 with `variantSteps: auto` (A15: only with a `routing` block) and a catalog,
1404
1606
  // the ladder is session-aware: variant steps on the same model first, resume of the child session
@@ -1618,7 +1820,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1618
1820
  // 2.4.2c, section 1.5-16: a deferred delegation runs no gate and no ladder. A producer
1619
1821
  // that failed outright produced nothing to verify later; it keeps today's
1620
1822
  // failed-attempt path, which runs no verification process either.
1621
- const finish = dispatchStart !== undefined && producerError === null && isDeferred(dod, dispatchStart.directives) &&
1823
+ const finish = dispatchStart !== undefined && producerError === null && tierRefusal === undefined && isDeferred(dod, dispatchStart.directives) &&
1622
1824
  await isProvenRootCaller(toolCtx?.sessionID)
1623
1825
  ? await finishDeferred(changedFileStore, {
1624
1826
  dispatchID: baselineID,
@@ -1631,6 +1833,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1631
1833
  dispatchedAt: dispatchStart.dispatchedAt,
1632
1834
  // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
1633
1835
  budget: captureBudget(producerSid, sessionStore.readCapReached(producerSid)),
1836
+ // Cross-repo P2e.6 (OD-P2e-2): the full scope on v2; a delegate dispatch has no per-check placements.
1837
+ ...(fullScopeOf(activeCfg) ? { fullScope: true } : {}),
1634
1838
  })
1635
1839
  : undefined;
1636
1840
  // QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
@@ -1653,6 +1857,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1653
1857
  await disposeChildSession(producerSid);
1654
1858
  return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
1655
1859
  }
1860
+ // B2: the finish saw the tree switch branch; the gate's own read below may not (it can fail), so the finish's
1861
+ // reason is carried into the artefact.
1862
+ const deferredSwitch = finish !== undefined && !finish.deferred && finish.reason === "branch-switched" ? finish.detail : undefined;
1656
1863
  // Once a delegation is gated, every later attempt of its ladder is gated too.
1657
1864
  if (finish !== undefined && dispatchStart !== undefined) {
1658
1865
  dispatchStart = { ...dispatchStart, directives: { ...dispatchStart.directives, mode: "required" } };
@@ -1668,7 +1875,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1668
1875
  const gateDeadline = createDeadline(gateBudgetMs);
1669
1876
  let verification;
1670
1877
  try {
1671
- verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline);
1878
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch's own start, the `since` of W's ignored-module listing.
1879
+ verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline, dispatchStart?.dispatchedAt);
1672
1880
  } catch (error) {
1673
1881
  gateDeadline.dispose();
1674
1882
  throw error;
@@ -1676,6 +1884,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1676
1884
  const artefact = {
1677
1885
  changedFiles: verification.changedFiles,
1678
1886
  changeBaseline: verification.changeBaseline,
1887
+ ...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
1888
+ ...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
1889
+ ...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
1890
+ ? { unattributedWriters: verification.unattributedWriters } : {}),
1891
+ ...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
1679
1892
  finalReturnText: producerText,
1680
1893
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
1681
1894
  producerSessionID: producerSid,
@@ -1706,6 +1919,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1706
1919
  trivial: false,
1707
1920
  mode: "modeA",
1708
1921
  ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
1922
+ ...(tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
1709
1923
  },
1710
1924
  artefact,
1711
1925
  gateDeps,
@@ -2161,9 +2375,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2161
2375
  // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
2162
2376
  // dispatch header or any repair touches it, and are kept for the after hook. The capture
2163
2377
  // is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
2164
- // DF2-F1: a role dispatch's capture is taken in its verification root (never in a refused cwd).
2378
+ // DF2-F1 / I2 (P2.3): a role dispatch's capture is taken in its work root W (never in a refused cwd or a check
2379
+ // subdirectory); a tier dispatch has no workRoot, so this is its explicit cwd, as before.
2165
2380
  await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
2166
- verificationScopeOf(input.callID, output?.args, dod).cwd,
2381
+ captureRootOf(verificationScopeOf(input.callID, output?.args, dod)),
2167
2382
  dod,
2168
2383
  dispatchDirectiveText(prompt, description),
2169
2384
  true);
@@ -2224,8 +2439,15 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2224
2439
  // Handoff 30, R7 (I1/I8 exemption: T1.5.3a, the header names `root=`): on v2 shadow/advise/enforce the engine stripped the
2225
2440
  // route line already; its `root=` comes from the router. No root → the header is byte-identical to before.
2226
2441
  const root = routeLineRoot(args.prompt) ?? (typeof input.callID === "string" ? strippedRouteRoot(input.callID) : undefined);
2227
- const prompt = buildDispatchHeader({ tier, cap, projectDirectory: ctx.directory, root }) +
2228
- DISPATCH_HEADER_SEPARATOR + args.prompt;
2442
+ // Cross-repo (P1.7, v2 only): the orchestrator's working set and the read parents (a tier call has no routed role,
2443
+ // hence no location). All empty unless cross-repo is in use, so the header is then byte-identical to before.
2444
+ const crossRepo = ctx.routerHost === "v2" ? resolveRolesRouting(cfg, "v2") : undefined;
2445
+ const workingSet = ctx.routerHost === "v2" && typeof input.sessionID === "string" ? workingSetOf(input.sessionID) : [];
2446
+ const prompt = buildDispatchHeader({
2447
+ tier, cap, projectDirectory: ctx.directory, root,
2448
+ ...(workingSet.length === 0 ? {} : { workingSet }),
2449
+ ...(crossRepo === undefined || crossRepo.repoParents.length === 0 ? {} : { readParents: crossRepo.repoParents }),
2450
+ }) + DISPATCH_HEADER_SEPARATOR + args.prompt;
2229
2451
  args.prompt = prompt;
2230
2452
  if (process.env.MODEL_ROUTER_DISPATCH_DEBUG === "1" && !dispatchDebugLogged) {
2231
2453
  dispatchDebugLogged = true;
@@ -2251,7 +2473,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2251
2473
  }
2252
2474
  }
2253
2475
  const sid = input?.sessionID;
2476
+ // F1: the unattributed-writer tally is also kept before the call runs: a call that ends in error never reaches the
2477
+ // after-hook's record(). Reached only by calls the router did not refuse (a refusal throws below, before this runs).
2478
+ const noteWriter = (): void => {
2479
+ if (typeof sid === "string" && typeof input?.tool === "string") changedFileStore.noteWriter(sid, input.tool);
2480
+ };
2254
2481
  if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
2482
+ noteWriter();
2255
2483
  return;
2256
2484
  }
2257
2485
  // Start-of-call refresh: the idle TTL must cover the tool's runtime, not
@@ -2274,6 +2502,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2274
2502
  ...(profile === undefined ? {} : { profile }),
2275
2503
  });
2276
2504
  } catch {
2505
+ noteWriter(); // the call proceeds
2277
2506
  return; // never break a real session on a guard-internal error
2278
2507
  }
2279
2508
  if (res.block) {
@@ -2285,6 +2514,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2285
2514
  });
2286
2515
  throw new Error(res.message);
2287
2516
  }
2517
+ noteWriter();
2288
2518
  },
2289
2519
 
2290
2520
  // -----------------------------------------------------------------------
@@ -2386,6 +2616,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2386
2616
  }
2387
2617
  }
2388
2618
 
2619
+ // Cross-repo (P1.9): a role's read from outside its work root says where it came from. Last, after every router banner.
2620
+ try {
2621
+ const provenance = await readProvenanceLine(input);
2622
+ if (provenance !== undefined && typeof output?.output === "string") {
2623
+ output.output = `${output.output}${output.output.endsWith("\n") ? "" : "\n"}${provenance}`;
2624
+ }
2625
+ } catch {
2626
+ // best-effort: a provenance line must never break a tool result
2627
+ }
2628
+
2389
2629
  // Option (i): verify-dispatch around the built-in `task` tool (advisory-grade —
2390
2630
  // we observe the finished task result and append a forcing note if it is not
2391
2631
  // accepted; we cannot retry a task call that already finished).
@@ -2420,6 +2660,14 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2420
2660
  // earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
2421
2661
  const routedRole = typeof input.callID === "string" ? routedRoleOf(input.callID) : undefined;
2422
2662
  const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
2663
+ // Cross-repo P2a.3 (v2 only): where each check of a routed role dispatch runs. Tier dispatches resolve nothing.
2664
+ // P2e.6: valid per-check `cwd=`/`scope=` keys may be deferred (the placements travel with the handle, and router_verify
2665
+ // runs each check where it was placed); only a refusal is verified at once, below.
2666
+ const placement = routedRole === undefined ? undefined : resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routedRole) });
2667
+ // P2b.7 (OD1=B, v2 only): a tier dispatch with a per-check `cwd=` is unverifiable (the gate refuses it); it is never deferred.
2668
+ const tierRefusal = routedRole === undefined && ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
2669
+ // P2e.6: a refused placement or the OD1 tier refusal is certain now: verified at once, never deferred.
2670
+ const placementRefused = tierRefusal !== undefined || placement?.refused !== undefined;
2423
2671
  const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
2424
2672
  const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
2425
2673
  const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
@@ -2430,7 +2678,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2430
2678
  : false;
2431
2679
  // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
2432
2680
  // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
2433
- if (!scope.outside && !carriedRole && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
2681
+ // B2: the reason a deferred finish refused for a branch switch, carried into the artefact below.
2682
+ let deferredSwitch: string | undefined;
2683
+ if (!scope.outside && !carriedRole && !placementRefused && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
2434
2684
  // Section 1.5-16: no gate, no test process; the result goes back now with the
2435
2685
  // footer, which is appended last and never says accepted or verified.
2436
2686
  const finish = await finishDeferred(changedFileStore, {
@@ -2440,12 +2690,17 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2440
2690
  producerTier,
2441
2691
  description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
2442
2692
  cwd: effectiveCwd,
2693
+ // I2 (P2.3): the change observation stays in W; the registration's cwd above is the check base (F5).
2694
+ ...(scope.workRoot !== undefined ? { captureRoot: captureRootOf(scope) } : {}),
2443
2695
  // #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
2444
2696
  ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
2445
2697
  dod,
2446
2698
  dispatchedAt: start.dispatchedAt,
2447
2699
  // Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
2448
2700
  budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
2701
+ // Cross-repo P2e.6: the checks' placements (registered with the handle), and the full scope on v2 (OD-P2e-2).
2702
+ ...(placement?.placements !== undefined ? { placements: placement.placements } : {}),
2703
+ ...(fullScopeOf(cfg) ? { fullScope: true } : {}),
2449
2704
  });
2450
2705
  if (finish.deferred) {
2451
2706
  output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
@@ -2453,6 +2708,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2453
2708
  if (childSessionID) changedFileStore.clear(childSessionID);
2454
2709
  return;
2455
2710
  }
2711
+ if (finish.reason === "branch-switched") deferredSwitch = finish.detail;
2456
2712
  // QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
2457
2713
  }
2458
2714
  // Same bound as the delegate gate: one deadline per invocation,
@@ -2464,11 +2720,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2464
2720
  const gateDeadline = createDeadline(gateBudgetMs);
2465
2721
  let verification;
2466
2722
  try {
2467
- verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", effectiveCwd, gateDeadline);
2723
+ // Cross-repo P3a (D23 as amended, QA C1): the dispatch's start (takeDispatch), the `since` of W's ignored-module
2724
+ // listing. A start that was never remembered reads as now (the return), which lists nothing older: never stale inputs.
2725
+ verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", captureRootOf(scope), gateDeadline, start.dispatchedAt);
2468
2726
  } catch (error) {
2469
2727
  gateDeadline.dispose();
2470
2728
  throw error;
2471
2729
  }
2730
+ // QA2 F4: a switch the deferred finish saw (and this gate's own read missed) is part of this attempt before the role
2731
+ // lineage records it; its change set may hold the other branch's commits, so it is unavailable.
2732
+ if (deferredSwitch !== undefined && verification.branchSwitch === undefined) {
2733
+ verification = { ...verification, branchSwitch: deferredSwitch, changeBaseline: "unavailable" as const };
2734
+ }
2472
2735
  // #84 QA-G-B-2-1: the role child's lineage — this attempt starts it (its own block) or is judged on everything the child
2473
2736
  // changed since the attempt that introduced the carried block, against that attempt's reference.
2474
2737
  if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
@@ -2477,6 +2740,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2477
2740
  const artefact = {
2478
2741
  changedFiles: verification.changedFiles,
2479
2742
  changeBaseline: verification.changeBaseline,
2743
+ ...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
2744
+ ...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
2745
+ ...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
2746
+ ? { unattributedWriters: verification.unattributedWriters } : {}),
2747
+ ...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
2480
2748
  finalReturnText,
2481
2749
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
2482
2750
  producerSessionID: childSessionID ?? "",
@@ -2526,6 +2794,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2526
2794
  ...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
2527
2795
  // Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
2528
2796
  ...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
2797
+ // Cross-repo P2b.5 (v2 only): where each check of a routed role dispatch runs, or the check the router refused.
2798
+ ...(placement?.placements !== undefined ? { checkPlacements: placement.placements } : {}),
2799
+ ...(placement?.refused !== undefined ? { refusedCheck: placement.refused } : tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
2529
2800
  },
2530
2801
  artefact,
2531
2802
  gateDeps,
@@ -2652,6 +2923,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
2652
2923
  }
2653
2924
  warnedNoCallID.delete(id);
2654
2925
  forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
2926
+ forgetWorkingSet(id); // cross-repo P1.4: the orchestrator's bound repository locations
2655
2927
  // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
2656
2928
  // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
2657
2929
  background?.forgetSession(id);
@@ -3190,6 +3462,25 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3190
3462
  const parts = args.split(/\s+/).filter(Boolean);
3191
3463
  const sub = (parts[0] ?? "").toLowerCase();
3192
3464
  let text: string;
3465
+ // Cross-repo P4.7 (SD-P4-10): `approve`, `repos`, `revoke` only on v2, in roles mode, with `routing.repoParents`, typed in a
3466
+ // top-level session; otherwise they fall through to the help below, unchanged (S5). Nothing runs in tiers mode or on v1.
3467
+ // The help lists them only where they run; `approvalsCommandsAvailable` returns before any session lookup unless v2 + roles
3468
+ // + parents hold.
3469
+ const approvalsAvailable = await approvalsCommandsAvailable(input.sessionID);
3470
+ const approvalsCmd = approvalsAvailable && APPROVAL_SUBCOMMANDS.has(sub) ? approvalsCommands : undefined;
3471
+ if (approvalsCmd !== undefined && approvalsCmd.isRouterApprovalSubcommand(sub)) {
3472
+ const routing = resolveRolesRouting(cfg, "v2");
3473
+ const result = await approvalsCmd.runRouterApprovals(sub, args.slice((parts[0] ?? "").length), {
3474
+ parents: routing.repoParents,
3475
+ exclude: routing.repoExclude,
3476
+ days: routing.repoApprovalDays,
3477
+ repoDepth: routing.repoDepth,
3478
+ });
3479
+ output.parts.push({ type: "text" as const, text: result.text });
3480
+ // SD-P4-11: the v2 command adapter reloads the role agents before it sends this text on.
3481
+ if (result.change !== undefined) approvalsCmd.markApprovalsChanged(output.parts, result.change);
3482
+ return;
3483
+ }
3193
3484
  if (sub === "models") {
3194
3485
  const catalog = await fetchCatalog();
3195
3486
  const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
@@ -3204,7 +3495,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
3204
3495
  }
3205
3496
  } else {
3206
3497
  // #84 P2.2: `/router` lists the roles in roles mode on v2 (`rolesNow()` is empty in tiers mode and on v1).
3207
- text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined);
3498
+ text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined, approvalsAvailable);
3208
3499
  // On the bare status view, surface stale or missing models inline.
3209
3500
  if (sub === "") {
3210
3501
  text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");