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
@@ -8,13 +8,17 @@ import type { V2Runtime } from "./v2-client";
8
8
  import { V2_GRADER_AGENT } from "./v2-client";
9
9
  import { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
10
10
  import { realpathSync, statSync } from "node:fs";
11
- import { isAbsolute, join, posix, resolve, win32 } from "node:path";
12
- import { loadConfig } from "../router/config";
11
+ import { basename, isAbsolute, join, posix, resolve, win32 } from "node:path";
12
+ import { loadConfig, resolveRolesRouting } from "../router/config";
13
13
  import { getActiveTiers } from "../router/protocol";
14
14
  import { DEFER_MISSING_SUBAGENT_NOTICE, HOST_SEED_AGENTS, resolveSubagentOverrides } from "../router/subagents";
15
15
  import { warnAgentOptionsEffortOnce } from "../router/agent-options";
16
16
  import { pluginAgentMarker } from "../router/plugin-agents";
17
17
  import { registerRoleAgents, roleAgentAlias, roleAgentOf, roleAgentSteps } from "../router/role-agents";
18
+ import { readApprovals, type RepoApproval } from "../routing/roles/approvals";
19
+ // Static, not `await import`: a dynamic import made a bundle split src/router/config.ts into a chunk where its tiers.json
20
+ // lookup fails.
21
+ import { approvalReloadLine, approvalsChangedOf } from "../commands/approvals";
18
22
  import { stripDelegateInstructions } from "../router/instructions";
19
23
  import { createPluginLogger } from "../router/logger";
20
24
  import { budgetClaimObserved, GRADER_SYSTEM } from "../verify/checker";
@@ -31,6 +35,10 @@ import {
31
35
  BINDING_NOTES, bind, currentBinding, evict as evictBinding, evictCall, type Binding, type SessionLookup,
32
36
  } from "../routing/roles/binding";
33
37
  import type { DispatchGrant } from "../routing/roles/policy";
38
+ import { forgetWorkingSet, workingSetOf } from "../routing/wire/working-set";
39
+ import {
40
+ createRepoProbe, displaySafe, gitMetadataSegment, readSetEligible, readSetPredicate, type InReadSet,
41
+ } from "../routing/roles/read-set";
34
42
  import {
35
43
  AUTHORITY_TEXT, AUTHORITY_TOOL_NAME, consumeAuthority, discardAuthority, evictAuthority, markAnnotated, previewAuthority, quoteChildText,
36
44
  requestedAuthority, type AuthorityDeps,
@@ -250,6 +258,13 @@ export function isPermissionRefusal(error: unknown): boolean {
250
258
  export const AUTHORITY_BINDING_UNKNOWN_DROP = `${AUTHORITY_TEXT.dropped.bindingUnknown}.`;
251
259
 
252
260
  /** QA-P21-1-8: logged once when `routing.delegation` becomes `roles` while OpenCode runs in tiers mode. */
261
+ /**
262
+ * Cross-repo P4.7 (SD-P4-11, spike T6): whether reloading the role agents after `/router approve` makes the host allow the
263
+ * approved directory at once. True: the adapter says "Role agents reloaded; dispatch again with root=<path>."; false: "Restart
264
+ * OpenCode to use it." (as after a failed reload).
265
+ */
266
+ export const APPROVAL_RELOAD_APPLIES: boolean = true;
267
+
253
268
  export const ROLES_RESTART_NOTICE =
254
269
  "roles mode (OpenCode v2 only): routing.delegation is now `roles`, but this OpenCode instance started in tiers mode; restart OpenCode to register the role agents and tools (tiers mode stays active until then)";
255
270
 
@@ -458,15 +473,6 @@ export function toolCallPaths(tool: string, args: unknown): string[] | undefined
458
473
  return paths.length > 0 ? paths : undefined;
459
474
  }
460
475
 
461
- /**
462
- * QA-G-A2-2: a path segment that names git's metadata entry `.git` — compared case-insensitively (win32, and stricter
463
- * elsewhere), with the trailing dots and spaces win32 drops and an NTFS `:stream` suffix removed (`.git.`, `.GIT`,
464
- * `.git::$INDEX_ALLOCATION` all name `.git` there).
465
- */
466
- function gitMetadataSegment(segment: string): boolean {
467
- return segment.replace(/:.*$/s, "").replace(/[. ]+$/, "").toLowerCase() === ".git";
468
- }
469
-
470
476
  /**
471
477
  * QA-G-A2-2: an edit of `path` (canonical `target`, inside `root`) would write `.git` or anything below it — the work root's own
472
478
  * repository pointer (a file in a linked worktree) or metadata (config, hooks, `commondir`), or a nested repository's. Such an
@@ -480,11 +486,27 @@ export function editsGitMetadata(path: string, target: string, root: string): bo
480
486
  return [path, below].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
481
487
  }
482
488
 
483
- /** The decision for one role-session action: allowed, or refused with the reason the child sees. */
484
- export type RoleAuthorityDecision = { readonly allow: true } | { readonly allow: false; readonly reason: string };
489
+ /**
490
+ * What allowed a path action (QA-1 F6): every path inside the work root W, some only in the read set R (P1.5), or some only as the
491
+ * session's own truncated output (QA-P23-2-A1) — the last one present wins (`own-output` over `read-set` over `work-root`).
492
+ */
493
+ export type RoleAuthorityAllowance = "work-root" | "read-set" | "own-output";
494
+
495
+ /**
496
+ * The decision for one role-session action: allowed (`via`: what allowed it, for an action with paths), or refused with the reason
497
+ * the child sees.
498
+ */
499
+ export type RoleAuthorityDecision =
500
+ | { readonly allow: true; readonly via?: RoleAuthorityAllowance }
501
+ | { readonly allow: false; readonly reason: string };
485
502
 
486
503
  const ALLOW: RoleAuthorityDecision = Object.freeze({ allow: true });
487
504
  const refuse = (reason: string): RoleAuthorityDecision => ({ allow: false, reason });
505
+ const ALLOWANCE_ORDER: readonly RoleAuthorityAllowance[] = ["work-root", "read-set", "own-output"];
506
+ /** The allowance of a decision over several paths: the widest one any path needed. */
507
+ const widerAllowance = (a: RoleAuthorityAllowance | undefined, b: RoleAuthorityAllowance): RoleAuthorityAllowance =>
508
+ a === undefined || ALLOWANCE_ORDER.indexOf(b) > ALLOWANCE_ORDER.indexOf(a) ? b : a;
509
+ const allowedVia = (via: RoleAuthorityAllowance | undefined): RoleAuthorityDecision => (via === undefined ? ALLOW : { allow: true, via });
488
510
 
489
511
  export interface RoleAuthorityInput {
490
512
  /** The host permission action (`event.action`) or the tool name (`execute.before`). */
@@ -508,6 +530,58 @@ export interface RoleAuthorityInput {
508
530
  * root. Never `edit`, `glob` or anything else.
509
531
  */
510
532
  readonly ownOutputs?: ReadonlySet<string>;
533
+ /**
534
+ * Cross-repo P1.5: the read set R beyond the work root (`routing/roles/read-set.ts`) — where a CANONICAL target lies when it is
535
+ * in R, undefined (or no predicate at all) when it is not. Used only for an exact binding with a work root (I9): `read`, `glob`
536
+ * and `grep` may reach R, `external_directory` too when the grant has a local read action; an edit never, it only names where
537
+ * the file lies.
538
+ */
539
+ readonly inReadSet?: (canonicalTarget: string) => { readonly repository: string; readonly name: string; readonly branch: string | null } | undefined;
540
+ /**
541
+ * QA-1 F1: the paths are the host's own resources (`evaluate`): a relative `read`/`edit` resource is the host's Location-relative
542
+ * form of a file the call's `execute.before` already checked as the call wrote it, so it may reach R. Without it (the call's own
543
+ * arguments, `execute.before`) a relative path never reaches R: it resolves against the session directory, which may itself be
544
+ * a repository of R, and the role would read another checkout's file silently.
545
+ */
546
+ readonly hostRelative?: boolean;
547
+ /**
548
+ * QA-1 F1: the one path is a `glob`/`grep` search root the call did not name (the session directory, or the host's `.`): it never
549
+ * reaches R, only W.
550
+ */
551
+ readonly implicitRoot?: boolean;
552
+ }
553
+
554
+ /**
555
+ * Cross-repo P1.5 (§5 refusal wording): where an edit outside the work root `root` lands — another worktree of the bound
556
+ * repository (and the same file's path in the work root), or a repository of R this dispatch may only read. Undefined when it is
557
+ * neither: the caller keeps the plain "outside this dispatch's work root" text.
558
+ */
559
+ function editElsewhereReason(
560
+ action: string, path: string, target: string, root: string, location: DispatchGrant["location"],
561
+ readSet: RoleAuthorityInput["inReadSet"], canonicalOf: (path: string) => string | undefined,
562
+ ): string | undefined {
563
+ // QA-1 F2: names, branches and paths from the filesystem (and the call's own path) are echoed display-safe.
564
+ const branch = (name: string | null): string => displaySafe(name ?? "(detached)");
565
+ const shown = displaySafe(path);
566
+ if (location !== undefined) {
567
+ let match: { dir: string; branch: string | null } | undefined;
568
+ for (const entry of location.worktrees) {
569
+ const dir = canonicalOf(entry.path);
570
+ if (dir === undefined || permissionMatches(dir, root) || !insideWorkRoot(target, dir)) continue;
571
+ if (match === undefined || dir.length > match.dir.length) match = { dir, branch: entry.branch };
572
+ }
573
+ if (match !== undefined) {
574
+ const rel = target.slice(match.dir.replace(/[\\/]+$/, "").length).replace(/^[\\/]+/, "");
575
+ return `${action}: ${shown} is in worktree ${displaySafe(match.dir)} (repository ${displaySafe(location.name)}, branch ${branch(match.branch)}); `
576
+ + `this dispatch edits only in ${displaySafe(root)} (branch ${branch(location.branch)}). The same file in your work root is `
577
+ + `${displaySafe(rel === "" ? root : join(root, rel))}.`;
578
+ }
579
+ }
580
+ const repo = readSet?.(target);
581
+ if (repo === undefined) return undefined;
582
+ const name = displaySafe(repo.name);
583
+ return `${action}: ${shown} is in repository ${name} (branch ${branch(repo.branch)}), which this dispatch may read but not edit. `
584
+ + `Finish the ${displaySafe(location?.name ?? basename(root))} part and return NEED MORE: naming the ${name} change; it needs a dispatch with repo=${name}.`;
511
585
  }
512
586
 
513
587
  /** The shape of a tool-output store file: `<data>/tool-output/tool_<id>` (`MANAGED_DIRECTORY`, `tool_${Identifier.ascending()}`). */
@@ -577,8 +651,11 @@ export function listedWorktreeRoot(
577
651
  * - `execute` (Code Mode) never (R6/P-6: its inner calls are never evaluated); `router_request_authority` for dynamic roles only.
578
652
  * - an action outside every role class → refused; a role action outside the dispatch grant → refused (an unknown binding's grant
579
653
  * is the role max ∩ local, binding.ts);
580
- * - `external_directory` (P-13): only an EXACT binding with a work root and a local action, every resource inside that root;
581
- * an unknown binding or a grant without a root → refused (I9);
654
+ * - `external_directory` (P-13): only an EXACT binding with a work root and a local action, every resource inside that root —
655
+ * or inside the read set R (cross-repo P1.5, `inReadSet`) when the grant has a local read action; an unknown binding or a grant
656
+ * without a root → refused (I9);
657
+ * - cross-repo P1.5: `read`/`glob`/`grep` may also reach R (exact binding with a work root only); an edit outside W stays refused,
658
+ * and its text names another worktree of the bound repository or a repository of R ({@link editElsewhereReason});
582
659
  * - path actions (`read`, `edit`, `glob`, `grep`): every path, canonical ({@link canonicalAuthorityPath}; case folded on win32),
583
660
  * inside the bound work root — the plugin's directory when the grant has none, except for `edit`, which a grant without a work
584
661
  * root never allows (QA-G-B-2); `read`/`edit` with no path refuse (QA-P23-A5);
@@ -595,6 +672,9 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
595
672
  const canonical = input.canonical ?? ((path: string, base: string) => canonicalAuthorityPath(path, base));
596
673
  const cls = roleActionOf(action);
597
674
  if (cls === undefined) return refuse(`${action} is outside every role's authority`);
675
+ // Cross-repo P1.5: R beyond W only for an exact binding with a bound work root (I9: an unknown binding, or a grant without a
676
+ // root, never reaches outside its directory).
677
+ const readSet = binding.kind === "exact" && grant.workRoot !== null ? input.inReadSet : undefined;
598
678
  if (cls === "external_directory") {
599
679
  if (binding.kind !== "exact") return refuse("external_directory: this session is not bound to its dispatch (binding unknown, I9)");
600
680
  const root = grant.workRoot;
@@ -604,16 +684,30 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
604
684
  if (input.paths.length === 0) return refuse("external_directory: no path to check");
605
685
  // QA-P23-2-A1: the directory of the session's own truncated output, for `read`/`grep` of exactly those files.
606
686
  const outputs = grant.actions.has("read") || grant.actions.has("grep") ? input.ownOutputs : undefined;
687
+ // P1.5: a directory of R only for a grant with a local READ action; `router_git` alone keeps W only.
688
+ const reads = grant.actions.has("read") || grant.actions.has("glob") || grant.actions.has("grep");
689
+ let via: RoleAuthorityAllowance | undefined;
607
690
  for (const resource of input.paths) {
608
691
  const dir = resource.replace(/[\\/]\*$/, "");
609
692
  const target = dir === "" ? undefined : canonical(dir, input.sessionDirectory);
610
- if (target !== undefined && root !== null && insideWorkRoot(target, root)) continue;
611
- if (target !== undefined && ownOutputDirectory(target, outputs)) continue;
693
+ if (target !== undefined && root !== null && insideWorkRoot(target, root)) {
694
+ via = widerAllowance(via, "work-root");
695
+ continue;
696
+ }
697
+ if (target !== undefined && ownOutputDirectory(target, outputs)) {
698
+ via = widerAllowance(via, "own-output");
699
+ continue;
700
+ }
701
+ // QA-1 F1/F7: the host's resources are canonical absolute; never `.git` or below in R.
702
+ if (target !== undefined && reads && readSetEligible(dir, target) && readSet?.(target) !== undefined) {
703
+ via = widerAllowance(via, "read-set");
704
+ continue;
705
+ }
612
706
  return refuse(root === null
613
707
  ? "external_directory: this dispatch has no work root (root=)"
614
708
  : `external_directory: ${resource} is outside this dispatch's work root ${root}`);
615
709
  }
616
- return ALLOW;
710
+ return allowedVia(via);
617
711
  }
618
712
  if (!grant.actions.has(cls)) return refuse(`${action} is not in this dispatch's grant (${[...grant.actions].join(", ") || "none"})`);
619
713
  if (cls === "read" || cls === "edit" || cls === "glob" || cls === "grep") {
@@ -626,17 +720,35 @@ export function roleAuthorityDecision(input: RoleAuthorityInput): RoleAuthorityD
626
720
  for (const pattern of input.patterns ?? []) {
627
721
  if (unsafeSearchPattern(pattern)) return refuse(`${action}: the pattern ${pattern} reaches outside its search root (use a relative pattern and \`path\`)`);
628
722
  }
723
+ // QA-1 F1: R only for a path the call wrote fully qualified (or the host's own Location-relative resource) and a search root
724
+ // the call named; a relative path or a search without a path that lands outside W keeps the refusal it had before P1.5.
725
+ const mayReachReadSet = (path: string, target: string): boolean =>
726
+ cls !== "edit" && input.implicitRoot !== true && readSetEligible(path, target, input.hostRelative === true);
727
+ let via: RoleAuthorityAllowance | undefined;
629
728
  for (const path of input.paths) {
630
729
  const target = canonical(path, input.sessionDirectory);
631
730
  if (target !== undefined && insideWorkRoot(target, root)) {
632
731
  if (cls === "edit" && editsGitMetadata(path, target, root)) {
633
732
  return refuse(`${action}: ${path} is repository metadata (\`.git\` or below it); a role never edits it`);
634
733
  }
734
+ via = widerAllowance(via, "work-root");
635
735
  continue;
636
736
  }
637
- if (target !== undefined && (cls === "read" || cls === "grep") && ownOutput(target, input.ownOutputs)) continue; // QA-P23-2-A1
737
+ if (target !== undefined && (cls === "read" || cls === "grep") && ownOutput(target, input.ownOutputs)) { // QA-P23-2-A1
738
+ via = widerAllowance(via, "own-output");
739
+ continue;
740
+ }
741
+ if (target !== undefined && mayReachReadSet(path, target) && readSet?.(target) !== undefined) { // P1.5: read/glob/grep in R
742
+ via = widerAllowance(via, "read-set");
743
+ continue;
744
+ }
745
+ const elsewhere = cls === "edit" && target !== undefined
746
+ ? editElsewhereReason(action, path, target, root, grant.location, readSet, (named) => canonical(named, input.sessionDirectory))
747
+ : undefined;
748
+ if (elsewhere !== undefined) return refuse(elsewhere);
638
749
  return refuse(`${action}: ${path} is outside this dispatch's work root ${root} (use an absolute path inside it)`);
639
750
  }
751
+ return allowedVia(via);
640
752
  }
641
753
  return ALLOW;
642
754
  }
@@ -702,6 +814,8 @@ export async function registerV2Hooks(
702
814
  listWorktrees?: (cwd: string) => Promise<string>;
703
815
  /** Role-agent registration (roles mode): the repository's worktree roots for the `external_directory` allow rules. Default: `listWorktrees` (role-agents.ts, a real `git worktree list`). */
704
816
  listRegistrationWorktrees?: (directory: string) => Promise<string[]>;
817
+ /** Cross-repo Phase 4 (SD-P4-15): directory of the repository approvals store read at role registration. Default: `dirname(statePath())` (approvals.ts). */
818
+ approvalsDir?: string;
705
819
  /**
706
820
  * QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (index.ts `recordRoleRefusal`): the router's
707
821
  * role-authority refusal here in `execute.before`, a host permission denial in `execute.after`. Returns the guard's text to
@@ -895,11 +1009,35 @@ export async function registerV2Hooks(
895
1009
  if (typeof recorded === "string" && registeredRole(recorded)) return recorded;
896
1010
  return currentBinding(sessionID, { maxOf: () => [] }) !== undefined ? "(bound role session)" : undefined;
897
1011
  };
898
- /** The directory the host resolves a session's relative paths against (its location), else the plugin's. */
899
- const sessionDirectoryOf = async (sessionID: string): Promise<string> => {
900
- const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as { location?: { directory?: unknown } };
1012
+ /**
1013
+ * The directory the host resolves a session's relative paths against (its location), else the plugin's; and the session's
1014
+ * parent (cross-repo P1.5: the orchestrator whose working set widens R).
1015
+ */
1016
+ const sessionInfoOf = async (sessionID: string): Promise<{ directory: string; parentID: string | undefined }> => {
1017
+ const session = await ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]) as unknown as {
1018
+ location?: { directory?: unknown }; parentID?: unknown;
1019
+ };
901
1020
  const directory = session?.location?.directory;
902
- return typeof directory === "string" && directory !== "" ? directory : ctx.location.directory;
1021
+ const parentID = session?.parentID;
1022
+ return {
1023
+ directory: typeof directory === "string" && directory !== "" ? directory : ctx.location.directory,
1024
+ parentID: typeof parentID === "string" && parentID !== "" ? parentID : undefined,
1025
+ };
1026
+ };
1027
+ /**
1028
+ * Cross-repo P1.5: the read set R of a role session beyond its work root (`routing/roles/read-set.ts`) — the worktrees of its
1029
+ * orchestrator's working set (the session that dispatched it: its dispatch record, else the session's parent) and the
1030
+ * repositories below `routing.repoParents`. Only for an exact binding with a work root; undefined when R adds nothing (no
1031
+ * parents and no working set: I9). The probe (`.git` and `HEAD`, synchronous) is cached 5 s per directory.
1032
+ */
1033
+ const repoProbe = createRepoProbe();
1034
+ const readSetOf = (sessionID: string, binding: Pick<Binding, "kind" | "grant">, parentID: string | undefined): InReadSet | undefined => {
1035
+ if (binding.kind !== "exact" || binding.grant.workRoot === null) return undefined;
1036
+ const routing = resolveRolesRouting(loadConfig(ctx.location.directory), "v2");
1037
+ const recorded = lookupDispatch(sessionID)?.parentSessionID;
1038
+ const orchestrator = typeof recorded === "string" && recorded !== "" ? recorded : parentID;
1039
+ const workingSet = orchestrator === undefined ? [] : workingSetOf(orchestrator);
1040
+ return readSetPredicate({ parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSet, repoProbe);
903
1041
  };
904
1042
  /**
905
1043
  * §2.2: a sibling work root is re-checked against a fresh `git worktree list --porcelain` when `external_directory` is
@@ -910,9 +1048,10 @@ export async function registerV2Hooks(
910
1048
  */
911
1049
  const listWorktreesOf = options.listWorktrees ?? gitWorktreeList;
912
1050
  const worktreeChecks = new Map<string, { at: number; listed: Promise<boolean> }>();
913
- const checkWorktree = async (root: string): Promise<boolean> => {
1051
+ /** Cross-repo P1.5: lists the repository of the binding's grant (`grant.location.repository`), else the plugin's directory. */
1052
+ const checkWorktree = async (root: string, repository: string): Promise<boolean> => {
914
1053
  try {
915
- return listedWorktreeRoot(await listWorktreesOf(ctx.location.directory), root);
1054
+ return listedWorktreeRoot(await listWorktreesOf(repository), root);
916
1055
  } catch {
917
1056
  return false;
918
1057
  }
@@ -940,14 +1079,15 @@ export async function registerV2Hooks(
940
1079
  while (ownOutputs.size > 1000) ownOutputs.delete(ownOutputs.keys().next().value!);
941
1080
  }
942
1081
  };
943
- const stillAWorktree = (root: string): Promise<boolean> => {
1082
+ const stillAWorktree = (root: string, repository: string): Promise<boolean> => {
944
1083
  const own = fallbackRoot();
945
1084
  if (own !== undefined && normalizeRootText(own) === normalizeRootText(root)) return Promise.resolve(true);
946
- const cached = worktreeChecks.get(root);
1085
+ const key = `${normalizeRootText(repository)}\u0000${root}`;
1086
+ const cached = worktreeChecks.get(key);
947
1087
  if (cached !== undefined && Date.now() - cached.at < 5_000) return cached.listed;
948
- const listed = checkWorktree(root);
949
- worktreeChecks.delete(root);
950
- worktreeChecks.set(root, { at: Date.now(), listed });
1088
+ const listed = checkWorktree(root, repository);
1089
+ worktreeChecks.delete(key);
1090
+ worktreeChecks.set(key, { at: Date.now(), listed });
951
1091
  while (worktreeChecks.size > 64) worktreeChecks.delete(worktreeChecks.keys().next().value!);
952
1092
  return listed;
953
1093
  };
@@ -967,27 +1107,41 @@ export async function registerV2Hooks(
967
1107
  const roleEvaluateRefusal = async (
968
1108
  event: { sessionID: unknown; action: string; resources: readonly string[]; metadata?: Record<string, unknown> | undefined },
969
1109
  agent: string,
970
- ): Promise<string | undefined> => {
1110
+ ): Promise<{ readonly refusal: string | undefined; readonly exact: boolean; readonly lift: boolean }> => {
971
1111
  const sessionID = String(event.sessionID);
972
1112
  const authority = await roleAuthorityOf(sessionID, agent);
973
- if (authority === undefined) return "the role table is unavailable (fail closed)";
1113
+ if (authority === undefined) return { refusal: "the role table is unavailable (fail closed)", exact: false, lift: false };
1114
+ const exact = authority.binding.kind === "exact";
974
1115
  const cls = roleActionOf(event.action);
975
1116
  const metadata = event.metadata !== null && typeof event.metadata === "object" ? event.metadata : undefined;
976
1117
  const search = cls === "glob" || cls === "grep";
1118
+ // QA-1 F1: a search the call named no root for (the host's `.`) never reaches R.
1119
+ const namedRoot = search && typeof metadata?.path === "string" && metadata.path !== "" ? metadata.path : undefined;
977
1120
  const paths = cls === "read" || cls === "edit" || cls === "external_directory" ? event.resources
978
- : search && metadata !== undefined ? [typeof metadata.path === "string" && metadata.path !== "" ? metadata.path : "."] : [];
1121
+ : search && metadata !== undefined ? [namedRoot ?? "."] : [];
979
1122
  const patterns = searchPatterns(cls, event.resources[0], metadata?.include);
1123
+ const info = paths.length > 0 ? await sessionInfoOf(sessionID) : undefined;
1124
+ const readSet = info === undefined ? undefined : readSetOf(sessionID, authority.binding, info.parentID);
980
1125
  const decision = roleAuthorityDecision({
981
1126
  action: event.action, paths, patterns, binding: authority.binding, dynamic: authority.spec.authority.mode === "dynamic",
982
- sessionDirectory: paths.length > 0 ? await sessionDirectoryOf(sessionID) : ctx.location.directory, fallbackRoot: fallbackRoot(),
983
- ownOutputs: ownOutputs.get(sessionID),
1127
+ sessionDirectory: info?.directory ?? ctx.location.directory, fallbackRoot: fallbackRoot(),
1128
+ ownOutputs: ownOutputs.get(sessionID), inReadSet: readSet,
1129
+ // QA-1 F1: a relative read/edit resource is the host's Location-relative form; execute.before checked the call as written.
1130
+ hostRelative: cls === "read" || cls === "edit",
1131
+ implicitRoot: search && namedRoot === undefined,
984
1132
  });
985
- if (!decision.allow) return decision.reason;
986
- const root = authority.binding.grant.workRoot;
987
- if (cls === "external_directory" && root !== null && !(await stillAWorktree(root))) {
988
- return `external_directory: the work root ${root} is no longer a worktree listed by \`git worktree list --porcelain\``;
1133
+ if (!decision.allow) return { refusal: decision.reason, exact, lift: false };
1134
+ const grant = authority.binding.grant;
1135
+ const root = grant.workRoot;
1136
+ if (cls === "external_directory" && root !== null && !(await stillAWorktree(root, grant.location?.repository ?? ctx.location.directory))) {
1137
+ return { refusal: `external_directory: the work root ${root} is no longer a worktree listed by \`git worktree list --porcelain\``, exact, lift: false };
989
1138
  }
990
- return undefined;
1139
+ // QA-1 F6 (D13, I18): the lift is for an exact binding's `external_directory` allowed by W or R only — never by the session's
1140
+ // own output directory — and only while cross-repo is in use (`routing.repoParents`, a working set, or a grant that carries its
1141
+ // repository's location); otherwise a host ask stays an ask (I9).
1142
+ const crossRepo = readSet !== undefined || grant.location !== undefined;
1143
+ const lift = exact && cls === "external_directory" && crossRepo && (decision.via === "work-root" || decision.via === "read-set");
1144
+ return { refusal: undefined, exact, lift };
991
1145
  };
992
1146
  /**
993
1147
  * T2.3.1 (P-12, S11): the `execute.before` side of EVERY tool call a role session makes — the tool's role action must be in the
@@ -997,25 +1151,34 @@ export async function registerV2Hooks(
997
1151
  * (`router_run`, `router_git_*`: no `evaluate`, S11) and for Code Mode `execute` (S8). A tool outside every role class —
998
1152
  * `subagent` included — is refused here too (QA-P23-A7), whatever the agent's max policy or the parent's grants say.
999
1153
  */
1000
- const roleToolRefusal = async (event: { sessionID: unknown; tool: string }, args: any, agent: string): Promise<string | undefined> => {
1154
+ const roleToolRefusal = async (event: { sessionID: unknown; tool: string; input?: unknown }, args: any, agent: string): Promise<string | undefined> => {
1001
1155
  const cls = roleActionOf(event.tool);
1002
1156
  if (cls === undefined && event.tool !== "execute" && event.tool !== AUTHORITY_TOOL_NAME) return `${event.tool} is outside every role's authority`;
1003
1157
  const sessionID = String(event.sessionID);
1004
1158
  const authority = await roleAuthorityOf(sessionID, agent);
1005
1159
  if (authority === undefined) return "the role table is unavailable (fail closed)";
1006
1160
  const record = args !== null && typeof args === "object" ? args as Record<string, unknown> : {};
1007
- const sessionDirectory = await sessionDirectoryOf(sessionID);
1161
+ const info = await sessionInfoOf(sessionID);
1162
+ const sessionDirectory = info.directory;
1008
1163
  let paths: string[] = [];
1164
+ let implicitRoot = false;
1009
1165
  if (cls === "read" || cls === "edit") {
1010
- const named = toolCallPaths(event.tool, record);
1011
- if (named === undefined) return `${event.tool}: no path to check (or a patch whose paths cannot be read)`;
1012
- paths = named;
1166
+ // QA-2: `scopedArgs` resolves a relative `filePath` against the session directory (and `taskArgs` maps `path` onto `filePath`),
1167
+ // so the call's RAW arguments are read too: a path written relative stays among the checked ones as written, and is never
1168
+ // eligible for R (`readSetEligible`) — only a path inside W passes. The resolved forms are checked next to them.
1169
+ const scoped = toolCallPaths(event.tool, record);
1170
+ const raw = toolCallPaths(event.tool, event.input);
1171
+ if (scoped === undefined && raw === undefined) return `${event.tool}: no path to check (or a patch whose paths cannot be read)`;
1172
+ paths = [...new Set([...(raw ?? []), ...(scoped ?? [])])];
1013
1173
  } else if (cls === "glob" || cls === "grep") {
1014
- paths = [typeof record.path === "string" && record.path !== "" ? record.path : sessionDirectory];
1174
+ const named = typeof record.path === "string" && record.path !== "" ? record.path : undefined;
1175
+ implicitRoot = named === undefined; // QA-1 F1: the session directory by default — W only, never R
1176
+ paths = [named ?? sessionDirectory];
1015
1177
  }
1016
1178
  const decision = roleAuthorityDecision({
1017
1179
  action: event.tool, paths, patterns: searchPatterns(cls, record.pattern, record.include), binding: authority.binding,
1018
1180
  dynamic: authority.spec.authority.mode === "dynamic", sessionDirectory, fallbackRoot: fallbackRoot(), ownOutputs: ownOutputs.get(sessionID),
1181
+ inReadSet: paths.length > 0 ? readSetOf(sessionID, authority.binding, info.parentID) : undefined, implicitRoot,
1019
1182
  });
1020
1183
  return decision.allow ? undefined : decision.reason;
1021
1184
  };
@@ -1135,8 +1298,19 @@ export async function registerV2Hooks(
1135
1298
  const rolesRequested = routerConfig.routing?.delegation === "roles";
1136
1299
  rolesStarted ??= rolesRequested;
1137
1300
  if (rolesStarted) {
1301
+ // Cross-repo Phase 4 (SD-P4-15): the approvals store, read without git and only in roles mode with parents (no store
1302
+ // I/O otherwise, I9). An invalid store or a read failure gives no approved repository (fail closed).
1303
+ let approvedRoots: readonly RepoApproval[] = [];
1304
+ try {
1305
+ if (rolesRequested && resolveRolesRouting(routerConfig, "v2").repoParents.length > 0) {
1306
+ const read = readApprovals(options.approvalsDir !== undefined ? { dir: options.approvalsDir } : {});
1307
+ approvedRoots = read.invalid === undefined ? read.approvals : [];
1308
+ }
1309
+ } catch (error) {
1310
+ warnRoleOnce("roles:approvals", `roles mode (OpenCode v2 only): the repository approvals could not be read (${error instanceof Error ? error.message : String(error)}); no approved repository is granted`);
1311
+ }
1138
1312
  const registration = await registerRoleAgents(next.agent, routerConfig, {
1139
- context7: Boolean(context7), directory: ctx.location.directory, seed: baseSeed, warn: warnRoleOnce,
1313
+ context7: Boolean(context7), directory: ctx.location.directory, seed: baseSeed, warn: warnRoleOnce, approvedRoots,
1140
1314
  ...(options.listRegistrationWorktrees ? { listWorktrees: options.listRegistrationWorktrees } : {}),
1141
1315
  });
1142
1316
  // #84 P2.3 (T2.3.3, §2.5): the ladder tool is a plugin tool, advertised to a deny-by-default agent only with an explicit
@@ -1254,13 +1428,19 @@ export async function registerV2Hooks(
1254
1428
  event.effect = "ask";
1255
1429
  event.message = `Approval required by ${agentLabel(name)} ${name}: ${event.action}`;
1256
1430
  }
1257
- // #84 P2.3 (T2.3.1, P-13, I3/I9): a role session is narrowed to ITS dispatch grant and work root. Only ever a deny: an
1258
- // action the max policy refused stays refused, a sensitive-read ask stays an ask when the grant covers it.
1431
+ // #84 P2.3 (T2.3.1, P-13, I3/I9): a role session is narrowed to ITS dispatch grant and work root: an action the max
1432
+ // policy refused stays refused, a sensitive-read ask stays an ask when the grant covers it. The one widening is D13 below.
1259
1433
  if (role !== undefined && event.effect !== "deny") {
1260
- const refusal = await roleEvaluateRefusal(event, role);
1434
+ const { refusal, lift } = await roleEvaluateRefusal(event, role);
1261
1435
  if (refusal !== undefined) {
1262
1436
  event.effect = "deny";
1263
1437
  event.message = `Permission denied by role agent ${role} for this dispatch: ${refusal}`;
1438
+ } else if (lift && event.effect === "ask" && event.action === "external_directory") {
1439
+ // Cross-repo P4.5 / D13, I18 (lift only inside the grant): a host `ask` for `external_directory` becomes `allow` when the
1440
+ // binding is exact and the router's own decision allowed every resource — inside W (still a listed worktree) or R —
1441
+ // while cross-repo is in use (QA-1 F6: never for the session's own output directory, never without cross-repo: I9).
1442
+ // Never another action, never an unknown binding, never over a `deny` (host or configured: both skip this branch).
1443
+ event.effect = "allow";
1264
1444
  }
1265
1445
  }
1266
1446
  } catch (error) {
@@ -1296,6 +1476,21 @@ export async function registerV2Hooks(
1296
1476
  return;
1297
1477
  }
1298
1478
  if (name === "preset") await refresh();
1479
+ if (name === "router") {
1480
+ // Cross-repo P4.7 (SD-P4-11): after `/router approve|revoke` wrote the store, reload the role agents (their
1481
+ // `external_directory` patterns come from the store), then say whether the change is usable now. The text still goes
1482
+ // through `session.prompt` below, so the orchestrator sees it and dispatches again.
1483
+ const change = approvalsChangedOf(output.parts);
1484
+ if (change !== undefined) {
1485
+ let reloadError: string | undefined;
1486
+ try {
1487
+ await refresh();
1488
+ } catch (error) {
1489
+ reloadError = error instanceof Error ? error.message : String(error);
1490
+ }
1491
+ output.parts.push({ type: "text", text: approvalReloadLine(change, APPROVAL_RELOAD_APPLIES, reloadError) });
1492
+ }
1493
+ }
1299
1494
  await ctx.session.prompt({
1300
1495
  ...invocation.prompt,
1301
1496
  sessionID: invocation.sessionID,
@@ -1761,14 +1956,20 @@ export async function registerV2Hooks(
1761
1956
  }
1762
1957
  const text = event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
1763
1958
  ? structured.output : contentText(event.result.content);
1764
- // QA-P21-1-3: the plugin's signals and gate read the child from the legacy metadata; a role result names it there too when
1765
- // the host reports it only in the structured output (spike S1: `result.output.sessionID`). Tier calls: unchanged.
1959
+ // QA-P21-1-3: the plugin's signals and gate read the child from the legacy metadata; a result names it there when the host
1960
+ // reports it only in the structured output (spike S1: `result.output.sessionID`). A role call takes the child the role
1961
+ // path resolved; a tier subagent call takes the structured output's non-empty string `sessionID`, as v1 always had it, so the
1962
+ // child's tool-observed edits and unobservable-writer tally reach the producer lineage. Metadata that already names the
1963
+ // child (`sessionID` or `sessionId`) is never overwritten; every other call's metadata passes through unchanged.
1766
1964
  const resultMetadata = event.result.metadata as Record<string, unknown> | undefined;
1965
+ const structuredChild = event.tool === "subagent" && typeof structured?.sessionID === "string" && structured.sessionID !== ""
1966
+ ? structured.sessionID : undefined;
1967
+ const namedChild = role?.child != null ? role.child : structuredChild;
1767
1968
  const output = {
1768
1969
  title: "", output: text,
1769
1970
  metadata: {
1770
1971
  ...resultMetadata,
1771
- ...(role?.child != null && resultMetadata?.sessionID === undefined && resultMetadata?.sessionId === undefined ? { sessionID: role.child } : {}),
1972
+ ...(namedChild !== undefined && resultMetadata?.sessionID === undefined && resultMetadata?.sessionId === undefined ? { sessionID: namedChild } : {}),
1772
1973
  },
1773
1974
  };
1774
1975
  await within(hookContext(event), async () => {
@@ -1839,6 +2040,7 @@ export async function registerV2Hooks(
1839
2040
  // authority requests go with it.
1840
2041
  if (typeof data.sessionID === "string") {
1841
2042
  evictBinding(data.sessionID);
2043
+ forgetWorkingSet(data.sessionID); // cross-repo P1.4: the orchestrator's bound repository locations
1842
2044
  evictAuthority(data.sessionID);
1843
2045
  ownOutputs.delete(data.sessionID); // QA-P23-2-A1
1844
2046
  lookupNamedAgent.delete(data.sessionID);