opencode-model-router 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -1,9 +1,10 @@
1
1
  import { parseRouteLine } from "../routing/classify/route-line";
2
+ import { displaySafe } from "../routing/roles/read-set";
2
3
 
3
4
  /** First characters of every router dispatch header (index.ts never adds a second one). */
4
5
  export const DISPATCH_HEADER_PREFIX = "[router] You are @";
5
6
 
6
- /** What index.ts puts between the header and the orchestrator's prompt. */
7
+ /** What index.ts (tiers) and the role dispatch path put between a header and the orchestrator's prompt. */
7
8
  export const DISPATCH_HEADER_SEPARATOR = "\n\n---\n\n";
8
9
 
9
10
  /** The header's last paragraph: the end of a header whose separator is missing. */
@@ -25,19 +26,31 @@ const FALSE_REFUSAL_PARAGRAPH = "A hand-back with zero tool calls is recorded as
25
26
  * `root` (plan §2.2, T1.5.3a): the dispatch's work root — the route line's `root=`
26
27
  * (`routeLineRoot`) — named by the working-directory paragraph instead of the
27
28
  * project directory. Absent or empty: the header is byte-identical to before.
29
+ *
30
+ * Cross-repo (`docs/design/cross-repo.md` §5, P1.7), all optional and inert when absent or empty:
31
+ * `location` names the working directory's repository, branch and head; `workingSet` and `readParents` add one paragraph
32
+ * listing the session's repositories and where a role may read.
28
33
  */
29
34
  export function buildDispatchHeader(input: {
30
35
  tier: string;
31
36
  cap: number | "none";
32
37
  projectDirectory: string | undefined;
33
38
  root?: string | null;
39
+ location?: { readonly name: string; readonly branch: string | null; readonly head: string | null };
40
+ workingSet?: readonly { readonly name: string; readonly branch: string | null }[];
41
+ readParents?: readonly string[];
34
42
  }): string {
35
43
  const paragraphs = [
36
44
  `${DISPATCH_HEADER_PREFIX}${input.tier}. Execute this dispatch yourself; do not route it to another tier, and do not ask to be re-dispatched.`,
37
45
  ];
38
46
  const directory = input.root || input.projectDirectory;
39
47
  if (directory) {
40
- paragraphs.push(`Working directory: ${directory}. You are already there — do not ask permission to read or write inside it.`);
48
+ paragraphs.push(...locationParagraphs(directory, {
49
+ location: input.location,
50
+ workingSet: input.workingSet,
51
+ readParents: input.readParents,
52
+ verb: "read or write",
53
+ }));
41
54
  }
42
55
  paragraphs.push(
43
56
  'Tool names mentioned in this dispatch are descriptive and vary by provider; your own tool schema is the authority on what you can do. Never refuse or hand back work because a named tool looks unfamiliar or missing — attempt it, and if you cannot finish, name the specific step that failed.',
@@ -52,6 +65,86 @@ export function buildDispatchHeader(input: {
52
65
  return paragraphs.join("\n\n");
53
66
  }
54
67
 
68
+ type HeaderLocation = { readonly name: string; readonly branch: string | null; readonly head: string | null };
69
+ type HeaderRepository = { readonly name: string; readonly branch: string | null };
70
+
71
+ /**
72
+ * The working-directory paragraph and, with a working set or read parents, the repositories paragraph. Shared by the tier
73
+ * header and the role header; `verb` completes "do not ask permission to <verb> inside it". Callers escape what they pass.
74
+ */
75
+ function locationParagraphs(
76
+ directory: string,
77
+ input: {
78
+ location?: HeaderLocation;
79
+ workingSet?: readonly HeaderRepository[];
80
+ readParents?: readonly string[];
81
+ verb: string;
82
+ /** A read-only role: the repositories paragraph carries no edit clause. Absent: the tier wording, byte-identical. */
83
+ readOnly?: boolean;
84
+ },
85
+ ): string[] {
86
+ const where = input.location === undefined
87
+ ? ""
88
+ : ` (repository ${input.location.name}, branch ${input.location.branch ?? "detached"}${input.location.head ? ` at ${input.location.head.slice(0, 7)}` : ""})`;
89
+ const paragraphs = [`Working directory: ${directory}${where}. You are already there — do not ask permission to ${input.verb} inside it.`];
90
+ const set = input.workingSet ?? [];
91
+ const parents = input.readParents ?? [];
92
+ if (set.length > 0 || parents.length > 0) {
93
+ const listed = set.length > 0
94
+ ? `Repositories in this session: ${set.map((entry) => `${entry.name} (${entry.branch ?? "detached"})`).join(", ")}. `
95
+ : "";
96
+ const rest = input.readOnly === true
97
+ ? (parents.length > 0
98
+ ? `You may read any repository below ${parents.join(", ")}.`
99
+ : "You read only in your working directory.")
100
+ : parents.length > 0
101
+ ? `You may read any repository below ${parents.join(", ")}; you edit and run only in your working directory.`
102
+ : "You edit and run only in your working directory.";
103
+ paragraphs.push(`${listed}${rest}`.trimEnd());
104
+ }
105
+ return paragraphs;
106
+ }
107
+
108
+ /**
109
+ * The header of a role dispatch (OD6: a role delegate is told its work root). Ends with DISPATCH_HEADER_SEPARATOR so
110
+ * stripDispatchHeader removes it before DoD inference (E8). No cap, verify directive, route line or nonce: those belong to
111
+ * the tier header and the protocol. Every name, branch and path goes through displaySafe, so a newline, a bracket or a
112
+ * `\n\n---\n\n` in a directory, repository or branch name can neither end the header early nor forge a line.
113
+ * `edits` false (a read-only role): "do not ask permission to read inside it". `exactResume`: the head may be stale, so the
114
+ * head clause is left out (as for a null head). A read-only role's repositories paragraph carries no edit clause ("You may
115
+ * read any repository below <parents>."): it cannot edit or run anywhere, so telling it where it may is noise. A caller that
116
+ * wants only the work root (`dispatchHeader: false` with a `root=`/`repo=` work root) passes no `workingSet` / `readParents`.
117
+ */
118
+ export function buildRoleDispatchHeader(input: {
119
+ agent: string;
120
+ workRoot: string;
121
+ edits: boolean;
122
+ location?: HeaderLocation;
123
+ workingSet?: readonly HeaderRepository[];
124
+ readParents?: readonly string[];
125
+ exactResume?: boolean;
126
+ }): string {
127
+ const safeBranch = (branch: string | null): string | null => (branch === null ? null : displaySafe(branch));
128
+ const location = input.location === undefined
129
+ ? undefined
130
+ : {
131
+ name: displaySafe(input.location.name),
132
+ branch: safeBranch(input.location.branch),
133
+ head: input.exactResume || input.location.head === null ? null : displaySafe(input.location.head),
134
+ };
135
+ const paragraphs = [
136
+ `${DISPATCH_HEADER_PREFIX}${displaySafe(input.agent)}. Execute this dispatch yourself.`,
137
+ ...locationParagraphs(displaySafe(input.workRoot), {
138
+ location,
139
+ workingSet: input.workingSet?.map((entry) => ({ name: displaySafe(entry.name), branch: safeBranch(entry.branch) })),
140
+ readParents: input.readParents?.map((parent) => displaySafe(parent)),
141
+ verb: input.edits ? "read or write" : "read",
142
+ ...(input.edits ? {} : { readOnly: true }),
143
+ }),
144
+ ];
145
+ return `${paragraphs.join("\n\n")}${DISPATCH_HEADER_SEPARATOR}`;
146
+ }
147
+
55
148
  /**
56
149
  * The work root a dispatch prompt names on its first-line route line (`root=`,
57
150
  * an absolute path validated by the parser), or undefined. The caller passes it
@@ -20,6 +20,15 @@ export interface GitInspectOptions {
20
20
  * dispatch) the common directory must be that repository's. QA-G-A2-4: paths and output are limited to the work root.
21
21
  */
22
22
  role?: { dispatchRepository?: string };
23
+ /**
24
+ * Phase 2.1 (leases): a git search lists paths (`ls_files`). With this set, the listed repository-relative paths (`/`-separated, as
25
+ * git prints them) go through it and only `kept` is shown; a non-empty `note` is appended as the last line. It runs on the
26
+ * decoded path list (the same names `ls-files -z` reports), so a name git would quote is matched by its real spelling. A throwing
27
+ * filter fails the call closed (nothing is listed).
28
+ */
29
+ filterSearch?: (root: string, paths: readonly string[]) => { kept: readonly string[]; note?: string };
30
+ /** Absolute `Date.now()` deadline shared with the caller (a `root` resolution, SD-3b-8); without it a fresh 15 s budget starts. */
31
+ deadlineAt?: number;
23
32
  }
24
33
 
25
34
  const MAX_BYTES = 64 * 1024;
@@ -149,9 +158,18 @@ export function gitEnvironment(extra: Record<string, string> = {}): NodeJS.Proce
149
158
  GIT_TERMINAL_PROMPT: "0", GIT_PAGER: "cat", PAGER: "cat", GIT_NO_LAZY_FETCH: "1", ...extra };
150
159
  }
151
160
 
161
+ /**
162
+ * Every transport refused on the command line. A repository's `protocol.<name>.allow=always` beats a
163
+ * generic `protocol.allow=never`, and GIT_NO_LAZY_FETCH is honoured only from git 2.44, so a partial
164
+ * clone's promisor (an `ext::` command, say) could otherwise run on a lazy fetch. Command-line `-c`
165
+ * overrides repository config; no router git call needs a transport.
166
+ */
167
+ export const PROTOCOL_HARDENING: readonly string[] = Object.freeze(["ext", "file", "ssh", "git", "http", "https"]
168
+ .flatMap(name => ["-c", `protocol.${name}.allow=never`]).concat(["-c", "protocol.allow=never"]));
169
+
152
170
  export function hardeningArgs(): string[] {
153
171
  return ["--no-optional-locks", "--no-pager", "-c", "core.pager=cat", "-c", "core.fsmonitor=false", "-c", "diff.external=",
154
- "-c", `core.hooksPath=${NULL_DEVICE}`, "-c", "protocol.allow=never",
172
+ "-c", `core.hooksPath=${NULL_DEVICE}`, ...PROTOCOL_HARDENING,
155
173
  "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "color.ui=false",
156
174
  // G2: signature display would run gpg.program; blank every signing program too.
157
175
  "-c", "log.showSignature=false", "-c", "gpg.program=", "-c", "gpg.ssh.program=", "-c", "gpg.x509.program=",
@@ -517,6 +535,8 @@ function killDirect(child: ChildProcess, label: BoundedLabel): void {
517
535
  }
518
536
 
519
537
  export interface BoundedOptions {
538
+ /** Optional v2 process-lifetime diagnostics; never includes executable/environment/directory preparation. */
539
+ service?: import("../executor/observations").ServiceExecution;
520
540
  signal?: AbortSignal; timeoutMs?: number; maxBytes?: number; env?: NodeJS.ProcessEnv;
521
541
  /**
522
542
  * Keep running past `maxBytes` (the head) and retain only the last `tailBytes` of
@@ -574,18 +594,43 @@ function rollingWindow(max: number) {
574
594
  };
575
595
  }
576
596
 
597
+ function observeBoundedProcess(options: BoundedOptions, event: "prepare" | "start" | "end", result = "error"): void {
598
+ try {
599
+ if (event === "end") options.service?.end(result);
600
+ else options.service?.[event]();
601
+ } catch { /* Diagnostics must never affect the process. */ }
602
+ }
603
+
577
604
  /**
578
605
  * Spawn with byte, time and abort bounds. Settles on `close`, or shortly after
579
606
  * `exit` when helpers that inherited the pipes (MSYS sh/sleep re-parented away
580
607
  * from taskkill's tree) keep `close` from firing (G7). Never a shell.
581
608
  */
582
609
  export function spawnBounded(executable: string, args: readonly string[], cwd: string, options: BoundedOptions = {}): Promise<BoundedResult> {
610
+ observeBoundedProcess(options, "prepare");
583
611
  const label = options.label ?? GIT_LABEL;
584
- if (options.signal?.aborted) return Promise.reject(new Error(`${label.message} aborted`));
585
- if (!isDirectory(cwd)) return Promise.reject(new Error(`${label.message} directory does not exist`));
612
+ if (options.signal?.aborted) {
613
+ observeBoundedProcess(options, "end", "interrupted");
614
+ return Promise.reject(new Error(`${label.message} aborted`));
615
+ }
616
+ if (!isDirectory(cwd)) {
617
+ observeBoundedProcess(options, "end");
618
+ return Promise.reject(new Error(`${label.message} directory does not exist`));
619
+ }
586
620
  return new Promise((resolveResult, reject) => {
587
- const child = spawn(executable, args, { cwd, env: options.env ?? gitEnvironment(), shell: false, windowsHide: true,
588
- detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
621
+ const launch = () => {
622
+ const env = options.env ?? gitEnvironment();
623
+ observeBoundedProcess(options, "start");
624
+ return spawn(executable, args, { cwd, env, shell: false, windowsHide: true,
625
+ detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
626
+ };
627
+ let child: ReturnType<typeof launch>;
628
+ try { child = launch(); }
629
+ catch (error) {
630
+ observeBoundedProcess(options, "end");
631
+ reject(error);
632
+ return;
633
+ }
589
634
  const max = options.maxBytes ?? MAX_BYTES;
590
635
  const tailMax = options.tailBytes;
591
636
  const errorTail = options.mergeStderr && options.stderrTailBytes !== undefined ? rollingWindow(options.stderrTailBytes) : undefined;
@@ -607,9 +652,10 @@ export function spawnBounded(executable: string, args: readonly string[], cwd: s
607
652
  timers.add(timer);
608
653
  return timer;
609
654
  };
610
- const settle = (outcome: () => void) => {
655
+ const settle = (outcome: () => void, serviceResult = "error") => {
611
656
  if (settled) return;
612
657
  settled = true;
658
+ observeBoundedProcess(options, "end", serviceResult);
613
659
  for (const timer of timers) clearTimeout(timer);
614
660
  timers.clear();
615
661
  options.signal?.removeEventListener("abort", abort);
@@ -634,7 +680,8 @@ export function spawnBounded(executable: string, args: readonly string[], cwd: s
634
680
  };
635
681
  const finish = (code: number | null) => {
636
682
  if (settled) return;
637
- const done = () => settle(() => failure && !options.settleOnFailure ? reject(new Error(failure)) : resolveResult(result(code)));
683
+ const done = () => settle(() => failure && !options.settleOnFailure ? reject(new Error(failure)) : resolveResult(result(code)),
684
+ failure !== undefined ? options.signal?.aborted ? "interrupted" : "timed-out" : truncated ? "fail" : code === 0 ? "pass" : "fail");
638
685
  if (!killing) { done(); return; }
639
686
  void Promise.race([killing, new Promise(wait => setTimeout(wait, KILL_WAIT_MS))]).then(done);
640
687
  };
@@ -799,6 +846,31 @@ export async function inheritedSafeDirectoryArgs(executable: string, timeoutMs:
799
846
  }
800
847
  }
801
848
 
849
+ /**
850
+ * Cross-repo QA round 2: the user's inherited non-executing settings (`core.autocrlf`, `core.eol`, `core.safecrlf`,
851
+ * `core.longpaths`, `core.quotepath`; not `safe.directory`, see {@link inheritedSafeDirectoryArgs}) as `-c key=value` pairs for a
852
+ * hardened git run in `root`, whose environment hides the system and global config (`gitEnvironment()`). Without them a CRLF
853
+ * checkout made under `core.autocrlf=true` reads as modified. Exactly what `inspectGit` passes: a key the repository's own
854
+ * configuration sets is left out (a `-c` value would override it). `base` is the hardening (and trusted `safe.directory`)
855
+ * prefix the repository query runs with. Any failure yields no pairs (the previous behaviour, never a wider setting).
856
+ */
857
+ export async function inheritedConfigArgs(executable: string, root: string, base: readonly string[], timeoutMs: number = DEADLINE_MS): Promise<string[]> {
858
+ const deadline = performance.now() + timeoutMs;
859
+ const budget: Budget = { timeoutMs: () => {
860
+ const remaining = deadline - performance.now();
861
+ if (remaining <= 0) throw new Error("Git configuration query timed out");
862
+ return remaining;
863
+ } };
864
+ try {
865
+ const pairs = (await inheritedConfig(executable, budget)).filter(pair => !pair.startsWith("safe.directory="));
866
+ if (pairs.length === 0) return [];
867
+ const repository = await repositoryConfig(executable, root, gitEnvironment(), [...base], budget);
868
+ return pairs.filter(pair => !repository.overridden.has(pair.slice(0, pair.indexOf("=")))).flatMap(pair => ["-c", pair]);
869
+ } catch {
870
+ return [];
871
+ }
872
+ }
873
+
802
874
  /**
803
875
  * Repository-level (local, worktree, included) driver programs and line-ending
804
876
  * settings. Every configured filter/diff program is blanked with `-c key=` (G1);
@@ -921,13 +993,50 @@ async function diffNames(executable: string, argv: string[], root: string, env:
921
993
  return withWarnings(result.truncated ? `${text}[truncated: output exceeds ${MAX_BYTES} bytes]` : text, result);
922
994
  }
923
995
 
924
- function nearestRepository(directory: string): string | undefined {
996
+ /**
997
+ * Phase 2.1: `ls-files` with its listing filtered (leases). The listing is read NUL-separated, so a name git would quote is still
998
+ * matched by its real spelling; the filter's `kept` paths are printed one per line, then its note. A `[truncated: …]` marker the
999
+ * bounded runner appended stays last. A throwing filter propagates: the call fails and lists nothing (fail closed).
1000
+ */
1001
+ async function filteredListing(executable: string, argv: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget,
1002
+ filter: NonNullable<GitInspectOptions["filterSearch"]>): Promise<string> {
1003
+ const at = argv.indexOf("ls-files");
1004
+ const run = (args: string[]) => runBoundedProcess(executable, args, root, { signal: budget.signal, timeoutMs: budget.timeoutMs(), env });
1005
+ if (at < 0) return await run(argv); // not a listing argv: nothing to filter
1006
+ const raw = await run([...argv.slice(0, at + 1), "-z", ...argv.slice(at + 1)]);
1007
+ const marker = /\n?\[truncated:[^\]]*\]\s*$/.exec(raw);
1008
+ const body = marker === null ? raw : raw.slice(0, marker.index);
1009
+ const listed = body.split("\0").filter(name => name !== "");
1010
+ const { kept, note } = filter(root, listed);
1011
+ const lines = [...kept, ...(note === undefined || note === "" ? [] : [note])];
1012
+ const text = lines.length === 0 ? "" : `${lines.join("\n")}\n`;
1013
+ return marker === null ? text : `${text}${marker[0].replace(/^\n/, "")}`;
1014
+ }
1015
+
1016
+ export function nearestRepository(directory: string): string | undefined {
925
1017
  for (let current = directory; ; current = dirname(current)) {
926
1018
  if (existsSync(join(current, ".git"))) return current;
927
1019
  if (dirname(current) === current) return undefined;
928
1020
  }
929
1021
  }
930
1022
 
1023
+ /**
1024
+ * Phase 2.1 (`LeaseSeams.repoKeyOf`): the repository and work tree containing `dir`, or undefined outside any (and when its `.git`
1025
+ * cannot be read safely). `repo` is the common git directory, so every linked worktree of one repository shares it; `tree` is the
1026
+ * checkout. Both are real paths. Reads `.git` pointers only (bounded, never followed onto a network or device path); spawns nothing.
1027
+ */
1028
+ export function repositoryIdentity(dir: string): { repo: string; tree: string } | undefined {
1029
+ try {
1030
+ const checkout = nearestRepository(dir);
1031
+ if (checkout === undefined) return undefined;
1032
+ const pointers = gitPointers(checkout);
1033
+ if (pointers === undefined) return undefined;
1034
+ return { repo: realpath(pointers.common), tree: realpath(checkout) };
1035
+ } catch {
1036
+ return undefined; // unreadable or refused (link, network/device path): outside any repository for the lease keys
1037
+ }
1038
+ }
1039
+
931
1040
  /** Honour an explicit containing worktree; otherwise discover the nearest checkout, including linked worktrees. */
932
1041
  function sessionBoundary(session: string, worktree: string | undefined): string {
933
1042
  if (worktree && isAbsolute(worktree) && isDirectory(worktree)) {
@@ -990,8 +1099,8 @@ async function verifyRoleRepository(executable: string, base: string[], session:
990
1099
  }
991
1100
 
992
1101
  export async function inspectGit(operation: GitOperation, input: GitInput, directory: string, signal?: AbortSignal, options: GitInspectOptions = {}): Promise<string> {
993
- // Discovery and inspection share one tool-call deadline, not two 15 s waits.
994
- const deadline = performance.now() + DEADLINE_MS;
1102
+ // Discovery and inspection share one tool-call deadline, not two 15 s waits (SD-3b-8: with a `root`, resolution shares it too).
1103
+ const deadline = performance.now() + (options.deadlineAt === undefined ? DEADLINE_MS : options.deadlineAt - Date.now());
995
1104
  const budget: Budget = { signal, timeoutMs: () => {
996
1105
  const remaining = deadline - performance.now();
997
1106
  if (remaining <= 0) throw new Error("Git inspection timed out");
@@ -1058,9 +1167,12 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1058
1167
  inspected = { ...input, ref: oid };
1059
1168
  }
1060
1169
  const argv = gitArgv(operation, inspected, root, { config, exclude: linked, ...(scope === undefined ? {} : { scope }) });
1061
- const raw = operation === "diff" && input.mode === "name-only"
1062
- ? await diffNames(executable, argv, root, env, budget)
1063
- : await runBoundedProcess(executable, argv, root, { signal, timeoutMs: budget.timeoutMs(), env });
1170
+ const searchFilter = operation === "ls_files" ? options.filterSearch : undefined;
1171
+ const raw = searchFilter !== undefined
1172
+ ? await filteredListing(executable, argv, root, env, budget, searchFilter)
1173
+ : operation === "diff" && input.mode === "name-only"
1174
+ ? await diffNames(executable, argv, root, env, budget)
1175
+ : await runBoundedProcess(executable, argv, root, { signal, timeoutMs: budget.timeoutMs(), env });
1064
1176
  let output = ["show", "diff", "log"].includes(operation) ? filterSensitiveDiff(raw) : raw;
1065
1177
  if (operation === "show" || operation === "log") output = await annotateWithheld(output, executable, base, root, env, budget, scopeSpec);
1066
1178
  if (linked.length === 0) return output;
@@ -1082,7 +1194,7 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1082
1194
  * checkout rather than a sibling worktree (S11, P-10).
1083
1195
  * Any other answer, or a throwing resolver, is reported as a tool error; nothing is spawned.
1084
1196
  */
1085
- export type WorkRootAnswer = { role: false } | { role: true; root: string | null };
1197
+ export type WorkRootAnswer = { role: false } | { role: true; root: string | null; repository?: string };
1086
1198
  /**
1087
1199
  * P1.3 injects, P2.1 wires it to the dispatch binding. Shared by router_git_* and
1088
1200
  * router_run (QA-P13-2-8); router_run refuses `{ role: false }` (it exists for role
@@ -1096,6 +1208,55 @@ export interface GitToolsOptions {
1096
1208
  * bound work root's common git directory must be that repository's. Absent: only the work root's own pointers are checked.
1097
1209
  */
1098
1210
  dispatchRepository?: string;
1211
+ /**
1212
+ * Cross-repo (3b.3, OpenCode v2 roles mode only): resolves a `root` argument against the session's read set and admission.
1213
+ * Only when set do the tools declare `root` and the longer description (SD-3b-1); absent, schema and behaviour are unchanged.
1214
+ */
1215
+ resolveRoot?: GitRootResolver;
1216
+ }
1217
+
1218
+ /**
1219
+ * A `root` resolver's answer (structurally `GitRootResolution` of `routing/roles/git-root.ts`, not imported: no cycle):
1220
+ * - `{ ok: false, reason }`: refused; the tool reports `refused: <reason>` and spawns nothing.
1221
+ * - `{ ok: true, inWorkRoot: true }`: `root` names the work root; the tool behaves exactly as without `root` (SD-3b-4).
1222
+ * - `{ ok: true, inWorkRoot: false, … }`: an admitted repository; the tool inspects `root` (the git cwd only) with the role
1223
+ * hardening against `repository`, guards for `root` and `workRoot`, and `provenance` as its first line (SD-3b-6, SD-3b-7).
1224
+ */
1225
+ export type GitRootAnswer =
1226
+ | { readonly ok: false; readonly reason: string }
1227
+ | { readonly ok: true; readonly inWorkRoot: true }
1228
+ | {
1229
+ readonly ok: true;
1230
+ readonly inWorkRoot: false;
1231
+ readonly root: string;
1232
+ readonly repository: string;
1233
+ readonly name: string;
1234
+ readonly branch: string | null;
1235
+ readonly workRoot: string;
1236
+ readonly provenance: string;
1237
+ };
1238
+ /** Resolves `root` for one call; `deadlineAt` (a `Date.now()` value) is the call's single 15 s deadline (SD-3b-8). */
1239
+ export type GitRootResolver = (value: string, ctx: { sessionID: string; signal?: AbortSignal; deadlineAt: number }) => Promise<GitRootAnswer>;
1240
+
1241
+ /** The refusal for a resolver answer that is not a {@link GitRootAnswer} (fail closed, SD-3b-11). */
1242
+ const INVALID_ROOT_ANSWER = "the root resolver returned an invalid answer; nothing ran";
1243
+
1244
+ /** Validate a `root` resolver answer; anything malformed becomes a refusal (never an inspection). */
1245
+ export function checkGitRootAnswer(answer: unknown): GitRootAnswer {
1246
+ const refused: GitRootAnswer = { ok: false, reason: INVALID_ROOT_ANSWER };
1247
+ if (typeof answer !== "object" || answer === null) return refused;
1248
+ const a = answer as Record<string, unknown>;
1249
+ if (a.ok === false) return typeof a.reason === "string" && a.reason.trim() !== "" ? { ok: false, reason: a.reason } : refused;
1250
+ if (a.ok !== true) return refused;
1251
+ if (a.inWorkRoot === true) return { ok: true, inWorkRoot: true };
1252
+ if (a.inWorkRoot !== false) return refused;
1253
+ const { root, repository, name, branch, workRoot, provenance } = a;
1254
+ const fullPath = (value: unknown): value is string => typeof value === "string" && isFullPath(value) && !isNetworkOrDevicePath(value);
1255
+ if (!fullPath(root) || !fullPath(repository) || !fullPath(workRoot)) return refused;
1256
+ if (typeof name !== "string" || name === "" || (branch !== null && typeof branch !== "string")) return refused;
1257
+ // The provenance is the output's first line: one non-empty line.
1258
+ if (typeof provenance !== "string" || provenance.trim() === "" || /[\r\n]/.test(provenance)) return refused;
1259
+ return { ok: true, inWorkRoot: false, root, repository, name, branch, workRoot, provenance };
1099
1260
  }
1100
1261
 
1101
1262
  /** Validate a resolver answer; throws for anything that is not a WorkRootAnswer. */
@@ -1106,43 +1267,129 @@ export function checkWorkRootAnswer(answer: unknown): WorkRootAnswer {
1106
1267
  if (role === true && "root" in answer) {
1107
1268
  const { root } = answer as { root: unknown };
1108
1269
  if (root === null) return { role: true, root: null };
1109
- if (typeof root === "string" && isFullPath(root)) return { role: true, root };
1270
+ if (typeof root === "string" && isFullPath(root)) {
1271
+ // Cross-repo (P1.5): the binding's repository, when the dispatch recorded one, replaces the session directory's.
1272
+ const { repository } = answer as { repository?: unknown };
1273
+ if (repository === undefined) return { role: true, root };
1274
+ if (typeof repository === "string" && isFullPath(repository)) return { role: true, root, repository };
1275
+ throw new Error("Bound repository is not an absolute path");
1276
+ }
1110
1277
  throw new Error("Bound work root is not an absolute path");
1111
1278
  }
1112
1279
  }
1113
1280
  throw new Error("Invalid work-root answer: expected { role: false } or { role: true, root }");
1114
1281
  }
1115
1282
 
1283
+ /** Phase 2.1: a process-wide filter for the listings of `router_git_ls_files` (leases); installed by the v2 adapter only. */
1284
+ export type GitSearchFilter = (e: { sessionID: string; root: string; paths: readonly string[] }) => { kept: readonly string[]; note?: string };
1285
+ let installedSearchFilter: GitSearchFilter | undefined;
1286
+ /** Install the listing filter; the returned function removes it (only while it is still the installed one). */
1287
+ export function installGitSearchFilter(filter: GitSearchFilter): () => void {
1288
+ installedSearchFilter = filter;
1289
+ return () => { if (installedSearchFilter === filter) installedSearchFilter = undefined; };
1290
+ }
1291
+
1292
+ /** SD-3b-1: appended to every router_git_* description only when a `root` resolver is configured. */
1293
+ const GIT_ROOT_DESCRIPTION_SUFFIX = " Role agents may set root to inspect another repository they may read (its absolute top-level path, or its name below routing.repoParents).";
1294
+ const GIT_ROOT_ARG_DESCRIPTION = "Another repository to inspect, read-only: its absolute top-level path, or its name below routing.repoParents; path is then relative to it";
1295
+ const UNSAFE_DISPLAY = /[\p{Cc}\p{Cf}\p{Cn}\p{Co}\p{Cs}\u2028\u2029[\]]/u;
1296
+
1297
+ /** A `root` value as echoed into an error: `displaySafe` of `routing/roles/read-set.ts` (not imported: read-set imports this module). */
1298
+ function displayRoot(text: string): string {
1299
+ if (!UNSAFE_DISPLAY.test(text)) return text;
1300
+ const quoted = quoteGitPath(text, true);
1301
+ return (quoted.startsWith('"') ? quoted : `"${quoted}"`).replaceAll("[", "\\133").replaceAll("]", "\\135");
1302
+ }
1303
+
1304
+ /**
1305
+ * 3b.3: one call with `root` (SD-3b-4, SD-3b-6 to SD-3b-8). Undefined: `root` names the work root, inspect as without it.
1306
+ * `root` is only the git cwd, never a git argument; a refusal or a malformed answer spawns nothing. `filtering` (leases, Phase 2.1)
1307
+ * applies to the other repository's listing as to the work root's.
1308
+ */
1309
+ async function inspectRoot(operation: GitOperation, input: GitInput, value: unknown, resolveRoot: GitRootResolver,
1310
+ executables: readonly string[], sessionID: string, signal: AbortSignal, deadlineAt: number,
1311
+ filtering: Pick<GitInspectOptions, "filterSearch"> = {}): Promise<string | undefined> {
1312
+ if (typeof value !== "string") return "[router_git] error: refused: root must be a string; nothing ran";
1313
+ try {
1314
+ const answer = checkGitRootAnswer(await resolveRoot(value, { sessionID, signal, deadlineAt }));
1315
+ if (!answer.ok) return `[router_git] error: refused: ${stripUrlUserinfo(answer.reason)}`;
1316
+ if (answer.inWorkRoot) return undefined;
1317
+ // F2, before anything is spawned: `root` is still the real path the resolver answered (no junction or link swapped in since
1318
+ // resolution), and a main worktree's `.git` is its own git directory (no gitdir file, link or junction naming another
1319
+ // repository): for a main worktree the dispatch check below compares `root` with itself.
1320
+ let real: string | undefined;
1321
+ try { real = realpath(answer.root); } catch { real = undefined; }
1322
+ if (real === undefined || foldCase(real) !== foldCase(answer.root)) {
1323
+ return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(answer.root)} changed since it was resolved; nothing ran`;
1324
+ }
1325
+ if (sameOnDisk(answer.repository, answer.root)) {
1326
+ const dotGit = join(answer.root, ".git");
1327
+ let own = false;
1328
+ try { const stats = lstatSync(dotGit); own = stats.isDirectory() && !stats.isSymbolicLink(); } catch { own = false; }
1329
+ if (!own) return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(dotGit)} is not the repository's own git directory; nothing ran`;
1330
+ }
1331
+ const output = await inspectGit(operation, input, answer.root, signal, {
1332
+ executables, guards: [...workRootGuards(answer.root), ...workRootGuards(answer.workRoot)],
1333
+ role: { dispatchRepository: answer.repository }, deadlineAt, ...filtering,
1334
+ });
1335
+ return `${answer.provenance}\n${output}`;
1336
+ } catch (error) {
1337
+ return `[router_git] error: root=${displayRoot(value)}: ${stripUrlUserinfo(errorMessage(error))}`;
1338
+ }
1339
+ }
1340
+
1116
1341
  export function gitTools(opts: GitToolsOptions = {}) {
1117
1342
  // G4: resolve the git executable once, at plugin load.
1118
1343
  const executables = defaultCandidates();
1344
+ const resolveRoot = opts.resolveRoot;
1119
1345
  const inputSchema = tool.schema.object({
1120
1346
  path: tool.schema.string().optional(), ref: tool.schema.string().optional(),
1121
1347
  limit: tool.schema.number().int().min(1).max(50).optional(),
1122
1348
  mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional(),
1123
1349
  }).strict();
1124
1350
  return Object.fromEntries(GIT_OPERATIONS.map(operation => [`router_git_${operation}`, tool({
1125
- description: `Read-only git ${operation.replaceAll("_", "-")} in the session repository. No shell, helpers, arbitrary options or writes. Output is bounded to 64 KiB and 15 seconds. Paths are literal and repository-relative.`,
1351
+ description: `Read-only git ${operation.replaceAll("_", "-")} in the session repository. No shell, helpers, arbitrary options or writes. Output is bounded to 64 KiB and 15 seconds. Paths are literal and repository-relative.${resolveRoot === undefined ? "" : GIT_ROOT_DESCRIPTION_SUFFIX}`,
1126
1352
  args: {
1127
1353
  path: tool.schema.string().optional().describe("Literal repository-relative path; required for blame"),
1128
1354
  ...(operation === "log" || operation === "diff" || operation === "show" || operation === "blame"
1129
1355
  ? { ref: tool.schema.string().optional().describe(operation === "show" ? "One commit or annotated tag pointing to a commit; ranges require log or diff" : "Ref or diff range, at most 200 characters; never an option") } : {}),
1130
1356
  ...(operation === "log" ? { limit: tool.schema.number().int().min(1).max(50).optional() } : {}),
1131
1357
  ...(operation === "diff" ? { mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional() } : {}),
1358
+ ...(resolveRoot === undefined ? {} : { root: tool.schema.string().optional().describe(GIT_ROOT_ARG_DESCRIPTION) }),
1132
1359
  },
1133
1360
  async execute(input, context) {
1134
1361
  try {
1362
+ const searchFilter = installedSearchFilter;
1363
+ const filtering: Pick<GitInspectOptions, "filterSearch"> = searchFilter === undefined ? {}
1364
+ : { filterSearch: (root, paths) => searchFilter({ sessionID: context.sessionID, root, paths }) };
1365
+ // 3b.3: `root` is stripped before the strict parse; without a resolver the input is parsed as given (unchanged, I9).
1366
+ let args: unknown = input;
1367
+ let deadline: { deadlineAt?: number } = {};
1368
+ if (resolveRoot !== undefined && typeof input === "object" && input !== null && "root" in input) {
1369
+ const { root, ...rest } = input as GitInput & { root?: unknown };
1370
+ args = rest;
1371
+ if (root !== undefined) {
1372
+ // SD-3b-8: one 15 s deadline covers resolution and inspection.
1373
+ const deadlineAt = Date.now() + DEADLINE_MS;
1374
+ deadline = { deadlineAt };
1375
+ const other = await inspectRoot(operation, inputSchema.parse(rest), root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt, filtering);
1376
+ if (other !== undefined) return other;
1377
+ }
1378
+ }
1135
1379
  if (opts.resolveWorkRoot) {
1136
1380
  const answer = checkWorkRootAnswer(opts.resolveWorkRoot(context.sessionID));
1137
1381
  if (answer.role) {
1138
1382
  if (answer.root === null) return "[router_git] error: refused: this role session has no bound work root (I9)";
1139
- return await inspectGit(operation, inputSchema.parse(input), answer.root, context.abort, {
1383
+ // Cross-repo (P1.5): a binding's repository is the expected one; without it, the plugin's directory.
1384
+ const expected = answer.repository ?? opts.dispatchRepository;
1385
+ return await inspectGit(operation, inputSchema.parse(args), answer.root, context.abort, {
1140
1386
  executables, guards: workRootGuards(answer.root),
1141
- role: opts.dispatchRepository ? { dispatchRepository: opts.dispatchRepository } : {},
1387
+ role: expected ? { dispatchRepository: expected } : {}, ...deadline,
1388
+ ...filtering,
1142
1389
  });
1143
1390
  }
1144
1391
  }
1145
- return await inspectGit(operation, inputSchema.parse(input), context.directory, context.abort, { worktree: context.worktree, executables });
1392
+ return await inspectGit(operation, inputSchema.parse(args), context.directory, context.abort, { worktree: context.worktree, executables, ...deadline, ...filtering });
1146
1393
  } catch (error) {
1147
1394
  // G12: report, never throw into the session; messages are credential-redacted.
1148
1395
  return `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;