opencode-model-router 2.3.0 → 2.5.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 (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -0,0 +1,1152 @@
1
+ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, openSync, readSync, realpathSync, statSync, type Stats } from "node:fs";
3
+ import { lstat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, win32 } from "node:path";
6
+ import { tool } from "@opencode-ai/plugin";
7
+ import { filterSensitiveDiff, isSensitivePath, sensitiveGitPathspecs } from "./sensitive-paths";
8
+
9
+ export const GIT_OPERATIONS = ["status", "log", "diff", "show", "blame", "ls_files"] as const;
10
+ export type GitOperation = typeof GIT_OPERATIONS[number];
11
+ export const GIT_TOOL_NAMES = GIT_OPERATIONS.map(name => `router_git_${name}`);
12
+ export interface GitInput { path?: string; ref?: string; limit?: number; mode?: "patch" | "stat" | "name-only" | "cached" }
13
+ /** Extra inspection context: the session's project worktree (discovery boundary) and pre-resolved executables. */
14
+ export interface GitInspectOptions {
15
+ worktree?: string; executables?: readonly string[]; guards?: readonly string[];
16
+ /**
17
+ * Role mode: `directory` is the bound work root. QA-G-A2-2: its `.git` pointers are checked before anything is spawned (no
18
+ * network/device pointer), the git directories git reports must be the ones they name, a linked worktree's admin directory
19
+ * must point back to the root, and with `dispatchRepository` (the directory whose repository listed the worktrees at
20
+ * dispatch) the common directory must be that repository's. QA-G-A2-4: paths and output are limited to the work root.
21
+ */
22
+ role?: { dispatchRepository?: string };
23
+ }
24
+
25
+ const MAX_BYTES = 64 * 1024;
26
+ const DEADLINE_MS = 15_000;
27
+ /** After a kill is requested: fall back to child.kill() if the process has not exited yet. */
28
+ const KILL_FALLBACK_MS = 500;
29
+ /** After a kill is requested: settle even if neither `exit` nor `close` arrives. */
30
+ const SETTLE_GRACE_MS = 1_000;
31
+ /** After `exit`: how long helpers that inherited the pipes may keep `close` from firing. */
32
+ const DRAIN_AFTER_KILL_MS = 200;
33
+ const DRAIN_AFTER_EXIT_MS = 1_000;
34
+ /** How long a settled call waits for taskkill to finish removing the tree. */
35
+ const KILL_WAIT_MS = 300;
36
+ const MAX_INDEX_BYTES = 32 * 1024 * 1024;
37
+ // Linear grouping below makes 100k directories cheap; the shared deadline still bounds I/O.
38
+ const MAX_LINK_CHECKS = 100_000;
39
+ const MAX_LINKED_EXCLUDES = 200;
40
+ const LSTAT_BATCH = 64;
41
+ const NULL_DEVICE = process.platform === "win32" ? "NUL" : "/dev/null";
42
+ const DRIVER_KEYS = /^(filter|diff)\.(.+)\.(clean|smudge|process|textconv|command)$/;
43
+ const REPOSITORY_QUERY = "^((filter|diff)\\..+\\.(clean|smudge|process|textconv|command)|core\\.(autocrlf|eol|safecrlf|longpaths|quotepath))$";
44
+ const INHERITED_QUERY = "^(core\\.(autocrlf|eol|safecrlf|longpaths|quotepath)|safe\\.directory)$";
45
+ const BOOLEAN = /^(true|false|yes|no|on|off|1|0)$/i;
46
+ /** Non-executing settings Git for Windows commonly keeps in system/global config (G9). Nothing here can name a program. */
47
+ const INHERITED_VALUES = new Map<string, RegExp>([
48
+ ["core.autocrlf", /^(true|false|input|yes|no|on|off|1|0)$/i],
49
+ ["core.eol", /^(lf|crlf|native)$/i],
50
+ ["core.safecrlf", /^(true|false|warn|yes|no|on|off|1|0)$/i],
51
+ ["core.longpaths", BOOLEAN],
52
+ ["core.quotepath", BOOLEAN],
53
+ ["safe.directory", /^[^\x00-\x1f\x7f]{0,4096}$/],
54
+ ]);
55
+ const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)$/i;
56
+ const WINDOWS_SPOOF = /[\u00a0\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
57
+
58
+ function errorCode(error: unknown): string | undefined {
59
+ if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
60
+ return typeof error.code === "string" ? error.code : undefined;
61
+ }
62
+
63
+ export function errorMessage(error: unknown): string {
64
+ return (error instanceof Error ? error.message : String(error)).replace(/[\r\n]+\s*/g, " ");
65
+ }
66
+
67
+ /** lstat that reports a missing path (or a file used as a directory) as undefined. */
68
+ function lstatOrUndefined(path: string): Stats | undefined {
69
+ try { return lstatSync(path); } catch (error) {
70
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return undefined;
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ function isDirectory(path: string): boolean {
76
+ try { return statSync(path).isDirectory(); } catch (error) {
77
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return false;
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ function realpath(path: string): string { return realpathSync.native(path); }
83
+
84
+ export function validateRef(ref: string): string {
85
+ if (!ref || ref.length > 200 || ref.startsWith("-") || !/^[A-Za-z0-9._/@{}~^-]+$/.test(ref)) {
86
+ throw new Error("Invalid git ref: use at most 200 ref characters, never an option or rev:path; use read for sensitive files (asks for approval)");
87
+ }
88
+ return ref;
89
+ }
90
+
91
+ function inside(root: string, path: string): boolean {
92
+ const rel = relative(root, path);
93
+ return rel !== ".." && !rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) && !isAbsolute(rel);
94
+ }
95
+
96
+ /** A validated repository-relative path (`/`-separated) is `scope` or below it; case-insensitive on win32 (QA-G-A2-4). */
97
+ function withinScope(path: string, scope: string): boolean {
98
+ const fold = (part: string) => (process.platform === "win32" ? part.toLowerCase() : part);
99
+ const parts = path.split("/").filter(part => part !== "" && part !== ".");
100
+ return scope.split("/").filter(part => part !== "").every((part, index) => parts[index] !== undefined && fold(parts[index]!) === fold(part));
101
+ }
102
+
103
+ /**
104
+ * Literal repo-relative paths only. Existing ancestors are checked too: none may
105
+ * resolve outside the repository or be a symlink/junction (G5), and on Windows
106
+ * device names, trailing dots/spaces and spoofing characters are rejected (G13).
107
+ */
108
+ export function validatePath(root: string, path: string, platform: NodeJS.Platform = process.platform): string {
109
+ if (!path || path.length > 4096 || path.startsWith("-") || /[\x00-\x1f:]/.test(path)
110
+ || isAbsolute(path) || win32.isAbsolute(path) || path.split(/[\\/]/).includes("..")) {
111
+ throw new Error("Invalid git path: expected a relative path inside the repository");
112
+ }
113
+ const normalized = path.replaceAll("\\", "/");
114
+ const parts = normalized.split("/").filter(part => part !== "" && part !== ".");
115
+ if (platform === "win32") {
116
+ if (WINDOWS_SPOOF.test(path)) throw new Error("Invalid git path: no-break space or bidirectional control character");
117
+ for (const part of parts) {
118
+ if (/[. ]$/.test(part)) throw new Error("Invalid git path: trailing dot or space in a path component");
119
+ if (WINDOWS_DEVICE.test(part.split(".")[0]!.trimEnd())) throw new Error("Invalid git path: reserved Windows device name");
120
+ }
121
+ }
122
+ const absolute = resolve(root, normalized);
123
+ if (!inside(root, absolute)) throw new Error("Git path escapes repository");
124
+ let ancestor = absolute;
125
+ while (!existsSync(ancestor) && dirname(ancestor) !== ancestor) ancestor = dirname(ancestor);
126
+ if (!inside(realpath(root), realpath(ancestor))) throw new Error("Git path symlink escapes repository");
127
+ let current = root;
128
+ for (const [index, part] of parts.entries()) {
129
+ current = join(current, part);
130
+ const stats = lstatOrUndefined(current);
131
+ if (!stats) break;
132
+ if (stats.isSymbolicLink() && (index < parts.length - 1 || isDirectory(current))) {
133
+ throw new Error("Git path crosses a symlinked or junction directory");
134
+ }
135
+ }
136
+ return normalized;
137
+ }
138
+
139
+ function strippedEnvironment(): NodeJS.ProcessEnv {
140
+ // Inherited GIT_CONFIG_COUNT/KEY/VALUE, GIT_DIR, tracing, helpers and alternate
141
+ // object directories must not redirect inspection or re-enable executable config.
142
+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
143
+ }
144
+
145
+ export function gitEnvironment(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
146
+ // Pathspecs carry explicit `:(literal)` magic instead of GIT_LITERAL_PATHSPECS, so
147
+ // the tools can add `:(exclude,literal)` pathspecs for linked directories (G5).
148
+ return { ...strippedEnvironment(), GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: NULL_DEVICE, GIT_ATTR_NOSYSTEM: "1",
149
+ GIT_TERMINAL_PROMPT: "0", GIT_PAGER: "cat", PAGER: "cat", GIT_NO_LAZY_FETCH: "1", ...extra };
150
+ }
151
+
152
+ export function hardeningArgs(): string[] {
153
+ 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",
155
+ "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "color.ui=false",
156
+ // G2: signature display would run gpg.program; blank every signing program too.
157
+ "-c", "log.showSignature=false", "-c", "gpg.program=", "-c", "gpg.ssh.program=", "-c", "gpg.x509.program=",
158
+ // G3: diff's opportunistic index refresh writes .git even with --no-optional-locks.
159
+ "-c", "diff.autoRefreshIndex=false", "-c", "core.splitIndex=false", "-c", "index.threads=1"];
160
+ }
161
+
162
+ function validateInput(operation: GitOperation, input: GitInput): { ref?: string } {
163
+ if (!GIT_OPERATIONS.includes(operation)) throw new Error("Invalid git operation");
164
+ if (input.path && isSensitivePath(input.path)) throw new Error("Sensitive git path refused; use read (asks for approval)");
165
+ const ref = input.ref === undefined ? undefined : validateRef(input.ref);
166
+ if (input.limit !== undefined && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 50)) throw new Error("Git log limit must be 1..50");
167
+ if (input.mode !== undefined && !["patch", "stat", "name-only", "cached"].includes(input.mode)) throw new Error("Invalid git diff mode");
168
+ if (operation === "blame" && input.path === undefined) throw new Error("Git blame requires path");
169
+ return { ref };
170
+ }
171
+
172
+ /**
173
+ * Fixed argv for one inspection. `config` holds additional top-level options
174
+ * (neutralized drivers, inherited settings) placed right after
175
+ * the hardening; `exclude` lists repository paths hidden with exclude pathspecs.
176
+ */
177
+ export function gitArgv(operation: GitOperation, input: GitInput, root: string,
178
+ extra: { config?: readonly string[]; exclude?: readonly string[]; scope?: string } = {}): string[] {
179
+ const { ref } = validateInput(operation, input);
180
+ const path = input.path === undefined ? undefined : validatePath(root, input.path);
181
+ // QA-G-A2-4: a role work root below the top level (`scope`, repository-relative) limits the path and, without one, the pathspec.
182
+ if (path !== undefined && extra.scope !== undefined && !withinScope(path, extra.scope)) {
183
+ throw new Error(`Git path is outside the work root (paths are repository-relative; the work root is ${extra.scope}/)`);
184
+ }
185
+ const limit = path === undefined && extra.scope !== undefined ? [`:(literal)${extra.scope}`] : [];
186
+ const args = [...hardeningArgs(), ...(extra.config ?? [])];
187
+ switch (operation) {
188
+ case "status": args.push("status", "--porcelain=v1", "--untracked-files=normal", "--ignore-submodules=all"); break;
189
+ // Exclusion-only logs retain sensitive-only commits; explicit paths keep Git's normal file-history limiting.
190
+ case "log": args.push("log", ...(input.path === undefined ? ["--sparse", "--full-history"] : []), "--patch", "--src-prefix=a/", "--dst-prefix=b/", "--submodule=short", "--no-show-signature", "--no-ext-diff", "--no-textconv", `--max-count=${input.limit ?? 20}`, "--format=medium", ...(ref ? [ref] : [])); break;
191
+ case "diff": args.push("diff", "--src-prefix=a/", "--dst-prefix=b/", "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", "--submodule=short",
192
+ ...(input.mode && input.mode !== "patch" ? [`--${input.mode}`] : []), ...(ref ? [ref] : [])); break;
193
+ case "show": args.push("show", "--sparse", "--src-prefix=a/", "--dst-prefix=b/", "--no-show-signature", "--no-ext-diff", "--no-textconv", "--format=medium", "--submodule=short", ref ?? "HEAD"); break;
194
+ case "blame":
195
+ // G6: never read blame.ignoreRevsFile (it may name a file outside the repository).
196
+ // Blame takes one literal path, not a pathspec.
197
+ args.push("blame", "--no-textconv", "--no-ignore-revs-file", ...(ref ? [ref] : []));
198
+ return [...args, "--", path ?? ""];
199
+ case "ls_files": args.push("ls-files", "--cached"); break;
200
+ }
201
+ // Blame accepts one literal filename, not exclusion pathspecs: explicit
202
+ // sensitive paths were refused above. Status/ls-files may list names only.
203
+ return [...args, "--", ...(path ? [`:(literal)${path}`] : []), ...limit,
204
+ ...(["show", "diff", "log"].includes(operation) ? sensitiveGitPathspecs() : []),
205
+ ...(extra.exclude ?? []).map(dir => `:(exclude,literal)${dir}`)];
206
+ }
207
+
208
+ function envValue(env: NodeJS.ProcessEnv, name: string): string | undefined {
209
+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name.toUpperCase());
210
+ return key === undefined ? undefined : env[key];
211
+ }
212
+
213
+ function realFile(path: string): string | undefined {
214
+ try {
215
+ const real = realpath(path);
216
+ return statSync(real).isFile() ? real : undefined;
217
+ } catch (error) {
218
+ if (errorCode(error) === undefined) throw error;
219
+ return undefined; // missing, unreadable or a broken link: not a candidate
220
+ }
221
+ }
222
+
223
+ function registryGitInstall(env: NodeJS.ProcessEnv): string[] {
224
+ const reg = join(envValue(env, "SystemRoot") ?? "C:\\Windows", "System32", "reg.exe");
225
+ const found: string[] = [];
226
+ for (const key of ["HKLM\\SOFTWARE\\GitForWindows", "HKCU\\SOFTWARE\\GitForWindows"]) {
227
+ const result = spawnSync(reg, ["query", key, "/v", "InstallPath"], { encoding: "utf8", windowsHide: true, timeout: 5_000, shell: false });
228
+ const match = /InstallPath\s+REG_(?:EXPAND_)?SZ\s+(.+?)\s*$/im.exec(result.stdout ?? "");
229
+ if (match?.[1]) found.push(join(match[1], "cmd", "git.exe"));
230
+ }
231
+ return found;
232
+ }
233
+
234
+ /**
235
+ * Every plausible git executable, best first, as real paths. On Windows the Git
236
+ * for Windows install (Program Files, else the installer's registry key) is
237
+ * preferred over PATH; git.cmd/git.bat, relative PATH entries and cwd lookups are
238
+ * never considered. Callers filter candidates that live inside the session (G4).
239
+ */
240
+ export function gitCandidates(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string[] {
241
+ const found: string[] = [];
242
+ const add = (file: string) => {
243
+ if (!isAbsolute(file)) return;
244
+ const real = realFile(file);
245
+ if (real && !found.includes(real)) found.push(real);
246
+ };
247
+ if (platform === "win32") {
248
+ for (const name of ["ProgramFiles", "ProgramW6432"]) {
249
+ const base = envValue(env, name);
250
+ if (base) add(join(base, "Git", "cmd", "git.exe"));
251
+ }
252
+ if (found.length === 0) registryGitInstall(env).forEach(add);
253
+ }
254
+ for (const entry of (envValue(env, "PATH") ?? "").split(platform === "win32" ? ";" : delimiter)) {
255
+ const dir = entry.replace(/^"|"$/g, "");
256
+ if (dir && isAbsolute(dir)) add(join(dir, platform === "win32" ? "git.exe" : "git"));
257
+ }
258
+ return found;
259
+ }
260
+
261
+ let loadedCandidates: readonly string[] | undefined;
262
+ /** Resolved once (at plugin load, when gitTools() is built) and reused for every call. */
263
+ function defaultCandidates(): readonly string[] {
264
+ loadedCandidates ??= gitCandidates();
265
+ return loadedCandidates;
266
+ }
267
+
268
+ /**
269
+ * First candidate (a real path) outside every guarded directory (guards are
270
+ * canonicalised when they exist), or undefined. Nothing is spawned (G4).
271
+ */
272
+ export function firstOutside(candidates: readonly string[], guarded: readonly string[]): string | undefined {
273
+ const guards = guarded.map(dir => existsSync(dir) ? realpath(dir) : dir);
274
+ return candidates.find(candidate => !guards.some(dir => inside(dir, candidate)));
275
+ }
276
+
277
+ /** First candidate whose real path is outside every guarded directory. Nothing is spawned. */
278
+ export function selectGitExecutable(candidates: readonly string[], guarded: readonly string[]): string {
279
+ if (candidates.length === 0) throw new Error("Git executable not found (Git for Windows install or absolute PATH entries)");
280
+ const selected = firstOutside(candidates, guarded);
281
+ if (selected !== undefined) return selected;
282
+ throw new Error(`Refusing git executable inside the session repository: ${candidates[0]}`);
283
+ }
284
+
285
+ /** `path` is `root` or below it (lexical; callers pass real paths). */
286
+ export function isInside(root: string, path: string): boolean { return inside(root, path); }
287
+
288
+ /** The real path of an existing regular file, or undefined (missing, a directory, a broken link). */
289
+ export function realFileOrUndefined(path: string): string | undefined { return realFile(path); }
290
+
291
+ /** Environment lookup by case-insensitive name (Windows semantics). */
292
+ export function envLookup(env: NodeJS.ProcessEnv, name: string): string | undefined { return envValue(env, name); }
293
+
294
+ /** The nearest directory at or above `directory` holding `.git` (a checkout or a linked worktree). */
295
+ export function nearestCheckout(directory: string): string | undefined { return nearestRepository(directory); }
296
+
297
+ /**
298
+ * Absolute and, on win32, rooted at a drive letter or UNC host: a root-relative `\dir`
299
+ * or a drive-relative `C:dir` names no one directory.
300
+ */
301
+ export function isFullPath(path: string, platform: NodeJS.Platform = process.platform): boolean {
302
+ if (platform !== "win32") return path.startsWith("/");
303
+ return /^[A-Za-z]:[\\/]|^[\\/]{2}[^\\/]+[\\/][^\\/]/.test(path);
304
+ }
305
+
306
+ /**
307
+ * A regular file's text, read through one descriptor (QA-P13-1-8, QA-P13-2-4): opened
308
+ * without blocking on POSIX (a FIFO cannot hang the call), fstat-checked as a regular
309
+ * file, and read up to `max` bytes (a larger file or a device is refused, never read
310
+ * whole). Undefined when missing. Errors name the file, never quote its contents.
311
+ */
312
+ export function readBoundedRegularFile(path: string, max: number, label: string): string | undefined {
313
+ let fd: number;
314
+ try {
315
+ fd = openSync(path, fsConstants.O_RDONLY | (process.platform === "win32" ? 0 : (fsConstants.O_NONBLOCK ?? 0)));
316
+ } catch (error) {
317
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return undefined;
318
+ throw new Error(`${label} is not readable (${errorCode(error) ?? "error"})`);
319
+ }
320
+ try {
321
+ if (!fstatSync(fd).isFile()) throw new Error(`${label} is not a regular file`);
322
+ const buffer = Buffer.alloc(max + 1);
323
+ let length = 0;
324
+ while (length < buffer.length) {
325
+ const read = readSync(fd, buffer, length, buffer.length - length, null);
326
+ if (read === 0) break;
327
+ length += read;
328
+ }
329
+ if (length > max) throw new Error(`${label} is larger than ${max >= 1024 * 1024 ? `${max / (1024 * 1024)} MiB` : `${max} bytes`}`);
330
+ return buffer.subarray(0, length).toString("utf8").replace(/^\uFEFF/, "");
331
+ } catch (error) {
332
+ if (error instanceof Error && error.message.startsWith(label)) throw error;
333
+ throw new Error(`${label} is not readable (${errorCode(error) ?? "error"})`);
334
+ } finally {
335
+ closeSync(fd);
336
+ }
337
+ }
338
+
339
+ /** Bound of the `.git` pointer and `commondir` files (QA-P13-2-4). */
340
+ const GIT_POINTER_BYTES = 4 * 1024;
341
+
342
+ /**
343
+ * A path that names another host or a device (`\\host\share`, `//host/share`, `\\?\…`, `\\.\…`), on any platform: a git
344
+ * pointer naming one is never followed (QA-G-A2-2), so no filesystem call or git process reaches a network host through it.
345
+ */
346
+ export function isNetworkOrDevicePath(path: string): boolean {
347
+ return /^[\\/]{2}/.test(path);
348
+ }
349
+
350
+ /** The git directory of a checkout and its common directory, as the checkout's `.git` pointers name them (QA-G-A2-2). */
351
+ export interface GitPointers {
352
+ /** The git directory: `<checkout>/.git`, or what a `.git` file's `gitdir:` names. */
353
+ gitdir: string;
354
+ /** The common directory: what the git directory's `commondir` names, else the git directory itself. */
355
+ common: string;
356
+ /** `.git` is a file (a linked worktree, or a submodule's checkout). */
357
+ file: boolean;
358
+ /** The git directory has a non-empty `commondir` (a linked worktree's admin directory). */
359
+ linked: boolean;
360
+ }
361
+
362
+ /**
363
+ * Read a checkout's `.git` (a directory, or a file `gitdir: <path>`) and the git directory's `commondir`, both bounded (4 KiB,
364
+ * regular files only), WITHOUT following a pointer that names a network or device path: such a pointer throws before any
365
+ * filesystem call reaches it, and so does a `.git` that is a link. Undefined when `.git` is missing or names no git directory.
366
+ */
367
+ export function gitPointers(checkout: string): GitPointers | undefined {
368
+ const dotGit = join(checkout, ".git");
369
+ const stats = lstatOrUndefined(dotGit);
370
+ if (stats === undefined) return undefined;
371
+ if (stats.isSymbolicLink()) throw new Error("Refusing repository: its .git is a link");
372
+ const file = !stats.isDirectory();
373
+ let gitdir = dotGit;
374
+ if (file) {
375
+ const pointer = /^gitdir:\s*(.+?)\s*$/m.exec(readBoundedRegularFile(dotGit, GIT_POINTER_BYTES, ".git") ?? "")?.[1];
376
+ if (!pointer) return undefined;
377
+ if (isNetworkOrDevicePath(pointer)) throw new Error("Refusing repository: its .git file points to a network or device path");
378
+ gitdir = resolve(checkout, pointer);
379
+ }
380
+ const commondir = readBoundedRegularFile(join(gitdir, "commondir"), GIT_POINTER_BYTES, "commondir")?.trim() ?? "";
381
+ if (isNetworkOrDevicePath(commondir)) throw new Error("Refusing repository: its commondir points to a network or device path");
382
+ return { gitdir, common: commondir === "" ? gitdir : resolve(gitdir, commondir), file, linked: commondir !== "" };
383
+ }
384
+
385
+ /**
386
+ * The main worktree of the checkout at `checkout` (QA-P13-1-6): the checkout itself
387
+ * when `.git` is a directory; for a linked worktree (`.git` file → gitdir →
388
+ * `commondir`) the directory holding the common `.git`, or the common directory
389
+ * itself for a bare repository (QA-P13-2-3b). Both pointer files are read bounded
390
+ * (4 KiB, regular files only) by {@link gitPointers}. Undefined when unreadable, and
391
+ * when a pointer names a network or device path (QA-G-A2-2: never followed).
392
+ */
393
+ export function mainWorktree(checkout: string): string | undefined {
394
+ try {
395
+ const pointers = gitPointers(checkout);
396
+ if (pointers === undefined) return undefined;
397
+ if (!pointers.file) return checkout;
398
+ if (!pointers.linked) return undefined;
399
+ return basename(pointers.common).toLowerCase() === ".git" ? dirname(pointers.common) : pointers.common;
400
+ } catch { return undefined; }
401
+ }
402
+
403
+ function foldCase(path: string): string { return process.platform === "win32" ? path.toLowerCase() : path; }
404
+
405
+ /** A derived guard (never the work root itself) must not be a filesystem root or the home directory. */
406
+ function guardable(dir: string): boolean {
407
+ if (dirname(dir) === dir) return false; // a filesystem root would refuse every executable
408
+ try { return foldCase(realpath(dir)) !== foldCase(realpath(homedir())); } catch { return true; }
409
+ }
410
+
411
+ /**
412
+ * Directories no executable may come from for a run or inspection in `root` (#77 G4,
413
+ * QA-P13-1-6, QA-P13-2-3): always the work root itself; derived from it, its checkout
414
+ * and that checkout's main worktree (a sibling worktree's main checkout, or the bare
415
+ * repository, is the same repository); and the checkout of the plugin's working
416
+ * directory with its main worktree (never the working directory itself, which may be
417
+ * System32 or the home directory). Derived guards that are a filesystem root or the
418
+ * home directory are skipped. Deduplicated case-insensitively on win32 only.
419
+ */
420
+ export function workRootGuards(root: string): string[] {
421
+ const out: string[] = [];
422
+ const add = (dir: string | undefined, derived: boolean) => {
423
+ if (dir === undefined || (derived && !guardable(dir))) return;
424
+ if (!out.some(known => foldCase(known) === foldCase(dir))) out.push(dir);
425
+ };
426
+ add(root, false);
427
+ for (const start of [root, process.cwd()]) {
428
+ const checkout = nearestRepository(start);
429
+ add(checkout, true);
430
+ if (checkout !== undefined) add(mainWorktree(checkout), true);
431
+ }
432
+ return out;
433
+ }
434
+
435
+ /**
436
+ * Git executable for the plugin process: the first candidate outside `guards` (none by default: setup and tests;
437
+ * `workRootGuards(dir)` for a run in a work root, QA-G-A2-3).
438
+ */
439
+ export function gitExecutable(guards: readonly string[] = []): string {
440
+ return selectGitExecutable(defaultCandidates(), guards);
441
+ }
442
+
443
+ /**
444
+ * Remove URL credentials (G10): the whole `user:pass@` of scheme URLs (even with
445
+ * a `/` or `@` in the password), scp-style `user[:pass]@host:path` anchored at the
446
+ * start of a token, and credential-like query parameters. `image@sha256:` digests
447
+ * and e-mail addresses are left alone.
448
+ */
449
+ export function stripUrlUserinfo(text: string): string {
450
+ // Quantifiers are bounded so minified single-line output cannot backtrack quadratically.
451
+ return text
452
+ .replace(/\b([a-z][a-z0-9+.-]{0,31}:\/\/)((?:(?![a-z][a-z0-9+.-]{0,31}:\/\/)\S)+)/gi, (_match, scheme: string, rest: string) => scheme + stripAuthority(rest))
453
+ .replace(/(^|[\s"'`<>()[\]{}=,;])[^\s"'`<>()[\]{}=,;@/:]+(?::\S{0,256}?)?@(?!(?:sha|md|blake)\d*:)([A-Za-z0-9._-]{1,253}|\[[0-9A-Fa-f:.]{2,45}\]):(?=\S)/g, "$1$2:")
454
+ .replace(/([?&;][a-z0-9_.-]{0,64}?(?:token|password|passwd|pwd|secret|api[_-]?key|sig|signature|credential)=)[^\s&#"'<>]+/gi, "$1***");
455
+ }
456
+
457
+ function stripAuthority(rest: string): string {
458
+ const separator = rest.search(/[/?#]/);
459
+ const authority = separator === -1 ? rest : rest.slice(0, separator);
460
+ // Normal case: the userinfo ends at the last @ of the authority (a password may hold @).
461
+ const at = authority.lastIndexOf("@");
462
+ if (at > 0) return rest.slice(at + 1);
463
+ if (!authority.includes(":")) return rest;
464
+ // `user:pa/ss@host`: the password itself contains a slash. Use the last @ that
465
+ // is not a path segment such as /@scope/name (over-redaction is the safe side).
466
+ for (let index = rest.lastIndexOf("@"); index > 0; index = rest.lastIndexOf("@", index - 1)) {
467
+ if (rest[index - 1] !== "/") return rest.slice(index + 1);
468
+ }
469
+ return rest;
470
+ }
471
+
472
+ /**
473
+ * Truncated output may end inside a credential, before the @ that identifies it.
474
+ * Drop the final token from its last plausible credential start (a `scheme:` or
475
+ * `user:`/`user@` at a token boundary); a token without `:`/`@` is kept, so a
476
+ * minified single-line file still returns content.
477
+ */
478
+ export function dropPartialCredential(text: string): string {
479
+ let start = text.length;
480
+ while (start > 0 && !/\s/.test(text[start - 1]!)) start--;
481
+ const token = text.slice(start);
482
+ if (!/[:@]/.test(token)) return text;
483
+ let cut = -1;
484
+ for (const found of token.matchAll(/(?:^|["'`<>()[\]{}=,;])(?=[^\s"'`<>()[\]{}=,;@/:]+[:@])/g)) cut = found.index + found[0].length;
485
+ return cut === -1 ? text : text.slice(0, start + cut);
486
+ }
487
+
488
+ /** How a bounded run names itself in errors ("<message> timed out") and warnings ("<tag>: … terminating <program> directly"). */
489
+ export interface BoundedLabel { message: string; tag: string; program: string }
490
+ const GIT_LABEL: BoundedLabel = { message: "Git inspection", tag: "router_git", program: "git" };
491
+
492
+ async function killTree(child: ChildProcess, label: BoundedLabel): Promise<void> {
493
+ const pid = child.pid;
494
+ if (pid === undefined) return;
495
+ if (process.platform !== "win32") {
496
+ try { process.kill(-pid, "SIGKILL"); } catch (error) {
497
+ if (errorCode(error) !== "ESRCH") throw error; // ESRCH: the group already exited
498
+ }
499
+ return;
500
+ }
501
+ await new Promise<void>((done) => {
502
+ const killer = spawn(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"), ["/pid", String(pid), "/T", "/F"],
503
+ { shell: false, windowsHide: true, stdio: "ignore" });
504
+ killer.once("error", error => {
505
+ console.warn(`[model-router] ${label.tag}: taskkill failed to start (${error.message}); terminating ${label.program} directly`);
506
+ killDirect(child, label);
507
+ done();
508
+ });
509
+ killer.once("close", () => done());
510
+ });
511
+ }
512
+
513
+ function killDirect(child: ChildProcess, label: BoundedLabel): void {
514
+ try { child.kill("SIGKILL"); } catch (error) {
515
+ console.warn(`[model-router] ${label.tag}: could not terminate ${label.program} directly (${errorMessage(error)})`);
516
+ }
517
+ }
518
+
519
+ export interface BoundedOptions {
520
+ signal?: AbortSignal; timeoutMs?: number; maxBytes?: number; env?: NodeJS.ProcessEnv;
521
+ /**
522
+ * Keep running past `maxBytes` (the head) and retain only the last `tailBytes` of
523
+ * the remaining output. Absent: the process tree is stopped at `maxBytes` (router_git).
524
+ */
525
+ tailBytes?: number;
526
+ /** Collect stderr into the same bounded stream as stdout, in arrival order (absent: a separate 8 KiB stderr). */
527
+ mergeStderr?: boolean;
528
+ /**
529
+ * With `mergeStderr`: also keep the last `stderrTailBytes` of stderr on their own.
530
+ * stdout and stderr are separate pipes with no relative order (on Linux a large
531
+ * stdout write can still be draining when a later stderr write arrives), so the tail
532
+ * of the merged stream need not contain the final stderr lines.
533
+ */
534
+ stderrTailBytes?: number;
535
+ /** Resolve with `failure` set, keeping the output so far, instead of rejecting on timeout or abort. */
536
+ settleOnFailure?: boolean;
537
+ /** Error/warning wording; default router_git's. */
538
+ label?: BoundedLabel;
539
+ /**
540
+ * POSIX: SIGKILL the child's process group when the call settles, also after a
541
+ * normal exit, so a background process left behind by the run cannot outlive it
542
+ * (QA-P13-1-2; router_run only). Ignored on win32: once the parent has exited
543
+ * there is no tree left to walk. Absent: router_git's behaviour (I1).
544
+ */
545
+ killGroupOnSettle?: boolean;
546
+ }
547
+ export interface BoundedResult {
548
+ code: number | null; output: Buffer; stderr: Buffer; truncated: boolean;
549
+ /** `tailBytes` mode: the last bytes after the head, and how many bytes between head and tail were dropped. */
550
+ tail?: Buffer; omitted?: number;
551
+ /** `settleOnFailure` mode: why the run was stopped ("<message> timed out" / "<message> aborted"). */
552
+ failure?: string;
553
+ /** `stderrTailBytes` mode: the last stderr bytes, and how many stderr bytes arrived in total. */
554
+ stderrTail?: Buffer; stderrTotal?: number;
555
+ }
556
+
557
+ /** A rolling window over a byte stream: memory stays near `max` however much is pushed. */
558
+ function rollingWindow(max: number) {
559
+ const parts: Buffer[] = [];
560
+ let size = 0;
561
+ let total = 0;
562
+ return {
563
+ push(chunk: Buffer) {
564
+ total += chunk.length;
565
+ parts.push(chunk);
566
+ size += chunk.length;
567
+ while (parts.length > 1 && size - parts[0]!.length >= max) size -= parts.shift()!.length;
568
+ },
569
+ value(): Buffer {
570
+ const all = Buffer.concat(parts);
571
+ return all.subarray(Math.max(0, all.length - max));
572
+ },
573
+ total: () => total,
574
+ };
575
+ }
576
+
577
+ /**
578
+ * Spawn with byte, time and abort bounds. Settles on `close`, or shortly after
579
+ * `exit` when helpers that inherited the pipes (MSYS sh/sleep re-parented away
580
+ * from taskkill's tree) keep `close` from firing (G7). Never a shell.
581
+ */
582
+ export function spawnBounded(executable: string, args: readonly string[], cwd: string, options: BoundedOptions = {}): Promise<BoundedResult> {
583
+ 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`));
586
+ 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"] });
589
+ const max = options.maxBytes ?? MAX_BYTES;
590
+ const tailMax = options.tailBytes;
591
+ const errorTail = options.mergeStderr && options.stderrTailBytes !== undefined ? rollingWindow(options.stderrTailBytes) : undefined;
592
+ const chunks: Buffer[] = [];
593
+ const errors: Buffer[] = [];
594
+ const tails: Buffer[] = [];
595
+ let bytes = 0;
596
+ let errorBytes = 0;
597
+ let tailBytes = 0;
598
+ let overflow = 0;
599
+ let truncated = false;
600
+ let exited = false;
601
+ let settled = false;
602
+ let failure: string | undefined;
603
+ let killing: Promise<void> | undefined;
604
+ const timers = new Set<NodeJS.Timeout>();
605
+ const later = (ms: number, run: () => void) => {
606
+ const timer = setTimeout(() => { timers.delete(timer); run(); }, ms);
607
+ timers.add(timer);
608
+ return timer;
609
+ };
610
+ const settle = (outcome: () => void) => {
611
+ if (settled) return;
612
+ settled = true;
613
+ for (const timer of timers) clearTimeout(timer);
614
+ timers.clear();
615
+ options.signal?.removeEventListener("abort", abort);
616
+ child.stdout.destroy(); child.stderr.destroy();
617
+ if (options.killGroupOnSettle && process.platform !== "win32" && child.pid !== undefined) {
618
+ try { process.kill(-child.pid, "SIGKILL"); } catch (error) {
619
+ if (errorCode(error) !== "ESRCH") console.warn(`[model-router] ${label.tag}: could not kill the process group (${errorMessage(error)})`);
620
+ }
621
+ }
622
+ outcome();
623
+ };
624
+ const result = (code: number | null): BoundedResult => {
625
+ const base: BoundedResult = { code, output: Buffer.concat(chunks), stderr: Buffer.concat(errors), truncated };
626
+ if (tailMax !== undefined) {
627
+ const tail = Buffer.concat(tails);
628
+ const kept = tail.subarray(Math.max(0, tail.length - tailMax));
629
+ Object.assign(base, { tail: kept, omitted: overflow - kept.length });
630
+ }
631
+ if (failure !== undefined) base.failure = failure;
632
+ if (errorTail !== undefined) Object.assign(base, { stderrTail: errorTail.value(), stderrTotal: errorTail.total() });
633
+ return base;
634
+ };
635
+ const finish = (code: number | null) => {
636
+ if (settled) return;
637
+ const done = () => settle(() => failure && !options.settleOnFailure ? reject(new Error(failure)) : resolveResult(result(code)));
638
+ if (!killing) { done(); return; }
639
+ void Promise.race([killing, new Promise(wait => setTimeout(wait, KILL_WAIT_MS))]).then(done);
640
+ };
641
+ const stop = () => {
642
+ if (killing || settled) return;
643
+ killing = killTree(child, label).catch((error: unknown) => {
644
+ console.warn(`[model-router] ${label.tag}: could not kill the ${label.program} process tree (${errorMessage(error)})`);
645
+ killDirect(child, label);
646
+ });
647
+ later(KILL_FALLBACK_MS, () => { if (!exited) killDirect(child, label); });
648
+ later(SETTLE_GRACE_MS, () => finish(null));
649
+ };
650
+ const abort = () => { failure ??= `${label.message} aborted`; stop(); };
651
+ const deadline = later(options.timeoutMs ?? DEADLINE_MS, () => { failure ??= `${label.message} timed out`; stop(); });
652
+ options.signal?.addEventListener("abort", abort, { once: true });
653
+ if (options.signal?.aborted) abort();
654
+ const keepTail = (rest: Buffer) => {
655
+ // Rolling window: memory stays near tailMax however much the process prints.
656
+ overflow += rest.length;
657
+ tails.push(rest);
658
+ tailBytes += rest.length;
659
+ while (tails.length > 1 && tailBytes - tails[0]!.length >= tailMax!) tailBytes -= tails.shift()!.length;
660
+ };
661
+ const collect = (chunk: Buffer) => {
662
+ const kept = chunk.subarray(0, Math.max(0, max - bytes));
663
+ if (kept.length) chunks.push(kept);
664
+ bytes += kept.length;
665
+ if (kept.length < chunk.length) {
666
+ truncated = true;
667
+ if (tailMax === undefined) stop(); else keepTail(chunk.subarray(kept.length));
668
+ }
669
+ };
670
+ const collectError = (chunk: Buffer) => {
671
+ const kept = chunk.subarray(0, Math.max(0, 8 * 1024 - errorBytes));
672
+ if (kept.length) errors.push(kept);
673
+ errorBytes += kept.length;
674
+ };
675
+ child.stdout.on("data", collect);
676
+ child.stderr.on("data", !options.mergeStderr ? collectError
677
+ : errorTail === undefined ? collect : (chunk: Buffer) => { collect(chunk); errorTail.push(chunk); });
678
+ child.once("error", error => settle(() => reject(error)));
679
+ child.once("exit", code => {
680
+ exited = true;
681
+ clearTimeout(deadline); timers.delete(deadline);
682
+ later(killing ? DRAIN_AFTER_KILL_MS : DRAIN_AFTER_EXIT_MS, () => finish(code));
683
+ });
684
+ child.once("close", code => finish(code));
685
+ });
686
+ }
687
+
688
+ /** Internal runner; executable/argv/bounds are never exposed as tool input. */
689
+ export async function runBoundedProcess(executable: string, args: string[], cwd: string,
690
+ options: { signal?: AbortSignal; timeoutMs?: number; maxBytes?: number; env?: NodeJS.ProcessEnv } = {}): Promise<string> {
691
+ const result = await spawnBounded(executable, args, cwd, options);
692
+ const max = options.maxBytes ?? MAX_BYTES;
693
+ let text = result.output.toString("utf8");
694
+ // A byte boundary must not expose part of a credential: trim BEFORE redacting.
695
+ if (result.truncated) text = dropPartialCredential(text);
696
+ text = stripUrlUserinfo(text);
697
+ if (result.truncated) return withWarnings(`${text}\n[truncated: output exceeds ${max} bytes]`, result);
698
+ if (result.code !== 0) throw queryFailure("Git inspection failed", result);
699
+ return withWarnings(text, result);
700
+ }
701
+
702
+ function withWarnings(text: string, result: BoundedResult): string {
703
+ const warnings = stripUrlUserinfo(dropPartialCredential(result.stderr.toString("utf8"))).trim();
704
+ return warnings ? `${text}${text.endsWith("\n") || text === "" ? "" : "\n"}[router_git stderr]\n${warnings}\n` : text;
705
+ }
706
+
707
+ interface Budget { signal?: AbortSignal; timeoutMs: () => number }
708
+
709
+ async function query(executable: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, budget: Budget, maxBytes = 1024 * 1024): Promise<BoundedResult> {
710
+ const result = await spawnBounded(executable, args, cwd, { env, signal: budget.signal, timeoutMs: budget.timeoutMs(), maxBytes });
711
+ if (result.truncated) throw new Error("Git inspection metadata exceeds its size bound");
712
+ return result;
713
+ }
714
+
715
+ function queryFailure(label: string, result: BoundedResult): Error {
716
+ return new Error(`${label} (${result.code}): ${stripUrlUserinfo(dropPartialCredential(result.stderr.toString("utf8"))).trim()}`);
717
+ }
718
+
719
+ /** Keep sensitive-only commits visible, without mistaking genuinely empty commits for withheld patches. */
720
+ async function annotateWithheld(output: string, executable: string, base: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget,
721
+ pathspecs: readonly string[] = []): Promise<string> {
722
+ const sections = output.split(/(?=^commit [a-f0-9]{40,64}(?:\s|$))/m);
723
+ for (let index = 0; index < sections.length; index++) {
724
+ const section = sections[index]!;
725
+ const oid = /^commit ([a-f0-9]{40,64})(?:\s|$)/.exec(section)?.[1];
726
+ if (!oid || /^diff --/m.test(section) || section.includes("[truncated:")) continue;
727
+ const names = await query(executable, [...base, "diff-tree", "--root", "-m", "--no-commit-id", "--name-only", "-r", "-z", oid, "--", ...pathspecs], root, env, budget);
728
+ if (names.code !== 0) throw queryFailure("Cannot inspect withheld changes", names);
729
+ const paths = names.output.toString("utf8").split("\0").filter(Boolean);
730
+ if (paths.length && paths.every(path => isSensitivePath(path))) sections[index] = `${section.trimEnd()}\n\n[router_git] changes to sensitive files withheld\n\n`;
731
+ }
732
+ return sections.join("");
733
+ }
734
+
735
+ /** Parse `git config -z --get-regexp` output into allowlisted `key=value` pairs (G9). */
736
+ export function parseInheritedConfig(raw: string): string[] {
737
+ const pairs: string[] = [];
738
+ for (const entry of raw.split("\0")) {
739
+ if (!entry) continue;
740
+ const newline = entry.indexOf("\n");
741
+ const key = (newline === -1 ? entry : entry.slice(0, newline)).toLowerCase();
742
+ const allowed = INHERITED_VALUES.get(key);
743
+ // A value-less entry is boolean true (meaningless for safe.directory).
744
+ const value = newline === -1 ? (key === "safe.directory" ? undefined : "true") : entry.slice(newline + 1);
745
+ if (allowed && value !== undefined && allowed.test(value)) pairs.push(`${key}=${value}`);
746
+ }
747
+ return pairs;
748
+ }
749
+
750
+ const inheritedCache = new Map<string, readonly string[]>();
751
+ /**
752
+ * System and global values of the allowlist, read as plain git would see them
753
+ * (honouring the user's GIT_CONFIG_SYSTEM/GLOBAL/NOSYSTEM). Cached per executable
754
+ * and configuration location.
755
+ */
756
+ async function inheritedConfig(executable: string, budget: Budget): Promise<readonly string[]> {
757
+ const passed: Record<string, string> = {};
758
+ for (const name of ["GIT_CONFIG_SYSTEM", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM"]) {
759
+ const value = process.env[name];
760
+ if (value !== undefined) passed[name] = value;
761
+ }
762
+ const key = JSON.stringify([executable, passed, process.env.HOME, process.env.USERPROFILE, process.env.XDG_CONFIG_HOME]);
763
+ const cached = inheritedCache.get(key);
764
+ if (cached) return cached;
765
+ const cwd = dirname(executable);
766
+ const env: NodeJS.ProcessEnv = { ...strippedEnvironment(), ...passed, GIT_CEILING_DIRECTORIES: dirname(cwd),
767
+ GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" };
768
+ // `git config --system` ignores GIT_CONFIG_NOSYSTEM, so honour it here (git boolean: yes/on/true/non-zero).
769
+ const nosystem = passed.GIT_CONFIG_NOSYSTEM ?? "";
770
+ const scopes = /^(true|yes|on)$/i.test(nosystem) || (/^-?\d+$/.test(nosystem) && Number(nosystem) !== 0) ? ["--global"] : ["--system", "--global"];
771
+ const pairs: string[] = [];
772
+ for (const scope of scopes) {
773
+ const result = await query(executable, [...hardeningArgs(), "config", scope, "-z", "--get-regexp", INHERITED_QUERY], cwd, env, budget, 64 * 1024);
774
+ // 1: nothing set. Other failures (unreadable/malformed file) only lose fidelity.
775
+ if (result.code === 0) pairs.push(...parseInheritedConfig(result.output.toString("utf8")));
776
+ }
777
+ inheritedCache.set(key, pairs);
778
+ return pairs;
779
+ }
780
+
781
+ /**
782
+ * QA-G-A2-2-1: the user's system/global `safe.directory` values (read by {@link inheritedConfig}, as `inspectGit` does) as
783
+ * `-c safe.directory=<value>` pairs for a hardened git run, whose environment hides the system and global config
784
+ * (`gitEnvironment()`): without them, a repository the user trusts that way fails with "dubious ownership". Only
785
+ * `safe.directory` is passed; any failure to read the user's config yields no pairs (never a wider trust than git's default).
786
+ */
787
+ export async function inheritedSafeDirectoryArgs(executable: string, timeoutMs: number = DEADLINE_MS): Promise<string[]> {
788
+ const deadline = performance.now() + timeoutMs;
789
+ const budget: Budget = { timeoutMs: () => {
790
+ const remaining = deadline - performance.now();
791
+ if (remaining <= 0) throw new Error("Git configuration query timed out");
792
+ return remaining;
793
+ } };
794
+ try {
795
+ const inherited = await inheritedConfig(executable, budget);
796
+ return inherited.filter(pair => pair.startsWith("safe.directory=")).flatMap(pair => ["-c", pair]);
797
+ } catch {
798
+ return [];
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Repository-level (local, worktree, included) driver programs and line-ending
804
+ * settings. Every configured filter/diff program is blanked with `-c key=` (G1);
805
+ * filters also become optional so a blank one is not a hard failure.
806
+ */
807
+ async function repositoryConfig(executable: string, root: string, env: NodeJS.ProcessEnv, base: string[], budget: Budget): Promise<{ neutralize: string[]; overridden: Set<string> }> {
808
+ const result = await query(executable, [...base, "config", "-z", "--name-only", "--get-regexp", REPOSITORY_QUERY], root, env, budget);
809
+ if (result.code !== 0 && result.code !== 1) throw queryFailure("Cannot read repository configuration", result);
810
+ const neutralize: string[] = [];
811
+ const overridden = new Set<string>();
812
+ const optional = new Set<string>();
813
+ for (const key of result.output.toString("utf8").split("\0").filter(Boolean)) {
814
+ const driver = DRIVER_KEYS.exec(key);
815
+ if (!driver) { overridden.add(key.toLowerCase()); continue; }
816
+ // `-c` splits at the first '=': such a key cannot be blanked, so refuse the repository.
817
+ if (key.includes("=")) throw new Error("Refusing repository: a filter/diff driver name contains '=' and cannot be neutralized");
818
+ neutralize.push("-c", `${key}=`);
819
+ if (driver[1] === "filter") optional.add(`filter.${driver[2]}.required=false`);
820
+ }
821
+ for (const setting of optional) neutralize.push("-c", setting);
822
+ return { neutralize, overridden };
823
+ }
824
+
825
+ /** Operations that read working-tree files. */
826
+ function readsWorktree(operation: GitOperation, input: GitInput): boolean {
827
+ if (operation === "status") return true;
828
+ if (operation === "diff") return input.mode !== "cached" && !(input.ref ?? "").includes("..");
829
+ return false;
830
+ }
831
+
832
+ /**
833
+ * Tracked directories that are now symlinks/junctions (G5). Node reports
834
+ * junctions as symbolic links. Prefixes are deduplicated, checked shallow-first
835
+ * in bounded batches, and descendants of a linked/missing directory are skipped.
836
+ */
837
+ export async function linkedTrackedDirectories(root: string, trackedPaths: Iterable<string>, budget?: Budget): Promise<string[]> {
838
+ const dirs = new Set<string>();
839
+ for (const path of trackedPaths) {
840
+ for (let slash = path.lastIndexOf("/"); slash > 0; slash = path.lastIndexOf("/", slash - 1)) {
841
+ const dir = path.slice(0, slash);
842
+ if (dirs.has(dir)) break; // its ancestors were added with it
843
+ dirs.add(dir);
844
+ }
845
+ }
846
+ if (dirs.size > MAX_LINK_CHECKS) throw new Error(`Tracked-directory cap exceeded: too many tracked directories (${dirs.size} > ${MAX_LINK_CHECKS}); use diff mode: cached or a commit range`);
847
+ const levels = new Map<number, string[]>();
848
+ for (const dir of dirs) {
849
+ const depth = dir.split("/").length;
850
+ const level = levels.get(depth) ?? [];
851
+ level.push(dir);
852
+ levels.set(depth, level);
853
+ }
854
+ const blocked = new Set<string>();
855
+ const linked: string[] = [];
856
+ for (const depth of [...levels.keys()].sort((a, b) => a - b)) {
857
+ const level: string[] = [];
858
+ for (const dir of levels.get(depth) ?? []) {
859
+ const parent = dir.lastIndexOf("/");
860
+ if (parent !== -1 && blocked.has(dir.slice(0, parent))) blocked.add(dir);
861
+ else level.push(dir);
862
+ }
863
+ for (let index = 0; index < level.length; index += LSTAT_BATCH) {
864
+ if (budget?.signal?.aborted) throw new Error("Git inspection aborted");
865
+ budget?.timeoutMs();
866
+ await Promise.all(level.slice(index, index + LSTAT_BATCH).map(async dir => {
867
+ let stats: Stats | undefined;
868
+ try { stats = await lstat(join(root, dir)); } catch (error) {
869
+ if (errorCode(error) !== "ENOENT" && errorCode(error) !== "ENOTDIR") throw error;
870
+ }
871
+ if (stats?.isDirectory()) return;
872
+ blocked.add(dir);
873
+ if (stats?.isSymbolicLink()) linked.push(dir);
874
+ }));
875
+ }
876
+ }
877
+ return linked.sort();
878
+ }
879
+
880
+ /** Paths named by `diff --numstat -z` records; renames/copies report the new path, as --name-only does. */
881
+ export function numstatNames(raw: string, complete = true): string[] {
882
+ const fields = raw.split("\0");
883
+ if (!complete) fields.pop(); // a field cut by the byte bound
884
+ const names: string[] = [];
885
+ for (let index = 0; index < fields.length; index++) {
886
+ const field = fields[index]!;
887
+ const tab = field.indexOf("\t", field.indexOf("\t") + 1);
888
+ if (field === "" || tab === -1) continue;
889
+ const path = field.slice(tab + 1);
890
+ if (path) { names.push(path); continue; }
891
+ const renamed = fields[index + 2];
892
+ if (renamed) names.push(renamed);
893
+ index += 2;
894
+ }
895
+ return names;
896
+ }
897
+
898
+ /** C-style pathname display matching core.quotePath; control characters are always escaped. */
899
+ export function quoteGitPath(name: string, quoteHigh = true): string {
900
+ // Git's C-style quoting works on UTF-8 bytes, not Unicode code points.
901
+ const escapes: Record<number, string> = { 7: "\\a", 8: "\\b", 9: "\\t", 10: "\\n", 11: "\\v", 12: "\\f", 13: "\\r", 34: '\\"', 92: "\\\\" };
902
+ if (!/[\x00-\x1f\x7f"\\]/.test(name) && (!quoteHigh || !/[^\x00-\x7f]/.test(name))) return name;
903
+ const quoted = [...Buffer.from(name)].map(byte => escapes[byte] ?? (byte < 32 || byte === 127 || (quoteHigh && byte >= 128)
904
+ ? `\\${byte.toString(8).padStart(3, "0")}` : Buffer.from([byte])));
905
+ return `"${Buffer.concat(quoted.map(part => typeof part === "string" ? Buffer.from(part) : part)).toString("utf8")}"`;
906
+ }
907
+
908
+ /**
909
+ * `diff --name-only` without the index auto-refresh (G3) also lists files whose
910
+ * stat data is stale but whose content is unchanged. --numstat compares content,
911
+ * so name-only output is derived from it instead.
912
+ */
913
+ async function diffNames(executable: string, argv: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget): Promise<string> {
914
+ const quoting = await query(executable, [...argv.slice(0, argv.indexOf("diff")), "config", "--type=bool", "--get", "core.quotePath"], root, env, budget);
915
+ if (quoting.code !== 0 && quoting.code !== 1) throw queryFailure("Cannot read path quoting configuration", quoting);
916
+ const args = argv.flatMap(arg => arg === "--name-only" ? ["--numstat", "-z"] : [arg]);
917
+ const result = await spawnBounded(executable, args, root, { env, signal: budget.signal, timeoutMs: budget.timeoutMs() });
918
+ if (!result.truncated && result.code !== 0) throw queryFailure("Git inspection failed", result);
919
+ const names = numstatNames(result.output.toString("utf8"), !result.truncated);
920
+ const text = stripUrlUserinfo(names.map(name => `${quoteGitPath(name, quoting.output.toString("utf8").trim() !== "false")}\n`).join(""));
921
+ return withWarnings(result.truncated ? `${text}[truncated: output exceeds ${MAX_BYTES} bytes]` : text, result);
922
+ }
923
+
924
+ function nearestRepository(directory: string): string | undefined {
925
+ for (let current = directory; ; current = dirname(current)) {
926
+ if (existsSync(join(current, ".git"))) return current;
927
+ if (dirname(current) === current) return undefined;
928
+ }
929
+ }
930
+
931
+ /** Honour an explicit containing worktree; otherwise discover the nearest checkout, including linked worktrees. */
932
+ function sessionBoundary(session: string, worktree: string | undefined): string {
933
+ if (worktree && isAbsolute(worktree) && isDirectory(worktree)) {
934
+ const real = realpath(worktree);
935
+ if (dirname(real) !== real && inside(real, session)) return real;
936
+ }
937
+ return nearestRepository(session) ?? session;
938
+ }
939
+
940
+ /** Two existing paths are the same file or directory (real paths, case folded on win32); false when either does not resolve. */
941
+ function sameOnDisk(a: string, b: string): boolean {
942
+ try { return foldCase(realpath(a)) === foldCase(realpath(b)); } catch { return false; }
943
+ }
944
+
945
+ /** A role work root's checkout and the git directories its `.git` pointers name (QA-G-A2-2). */
946
+ interface RoleRepository { checkout: string; pointers: GitPointers }
947
+
948
+ /**
949
+ * QA-G-A2-2, before anything is spawned: the work root's checkout and its `.git` pointers (a network/device pointer throws, see
950
+ * {@link gitPointers}); with `dispatchRepository`, the common directory must be the one of the repository the dispatch listed
951
+ * the worktrees in.
952
+ */
953
+ function roleRepository(session: string, dispatchRepository: string | undefined): RoleRepository {
954
+ const checkout = nearestRepository(session);
955
+ if (checkout === undefined) throw new Error("The bound work root is not inside a git checkout");
956
+ const pointers = gitPointers(checkout);
957
+ if (pointers === undefined) throw new Error("Cannot read the work root's .git");
958
+ if (dispatchRepository !== undefined) {
959
+ const listedCheckout = isDirectory(dispatchRepository) ? nearestRepository(realpath(dispatchRepository)) : undefined;
960
+ const listed = listedCheckout === undefined ? undefined : gitPointers(listedCheckout);
961
+ if (listed === undefined) throw new Error("refused: the repository listed at dispatch cannot be read");
962
+ if (!sameOnDisk(listed.common, pointers.common)) throw new Error("refused: the work root's repository is not the repository listed at dispatch");
963
+ }
964
+ return { checkout, pointers };
965
+ }
966
+
967
+ /**
968
+ * QA-G-A2-2, once git can be run: `rev-parse --absolute-git-dir --git-common-dir` in the work root must name the directories its
969
+ * `.git` pointers name (never a network/device path); a linked worktree's git directory must be `<common>/worktrees/<id>` and its
970
+ * `gitdir` file must point back to this checkout's `.git` — which is how `git worktree list` listed the root at dispatch.
971
+ */
972
+ async function verifyRoleRepository(executable: string, base: string[], session: string, env: NodeJS.ProcessEnv, budget: Budget, role: RoleRepository): Promise<void> {
973
+ const dirs = await query(executable, [...base, "rev-parse", "--absolute-git-dir", "--git-common-dir"], session, env, budget, 64 * 1024);
974
+ if (dirs.code !== 0) throw queryFailure("Cannot resolve the repository's git directories", dirs);
975
+ const [gitDir, commonDir] = dirs.output.toString("utf8").split(/\r?\n/).map(line => line.trim());
976
+ if (!gitDir || !commonDir) throw new Error("Cannot resolve the repository's git directories");
977
+ if (isNetworkOrDevicePath(gitDir) || isNetworkOrDevicePath(commonDir)) throw new Error("Refusing repository: git reports a network or device path");
978
+ const { pointers, checkout } = role;
979
+ if (!sameOnDisk(gitDir, pointers.gitdir) || !sameOnDisk(resolve(session, commonDir), pointers.common)) {
980
+ throw new Error("refused: the repository git reports is not the one the work root's .git names");
981
+ }
982
+ if (sameOnDisk(pointers.gitdir, pointers.common)) return; // a main worktree (or a submodule's checkout): its own git directory
983
+ if (!sameOnDisk(dirname(pointers.gitdir), join(pointers.common, "worktrees"))) {
984
+ throw new Error("refused: the work root's git directory is not a worktree of the repository listed at dispatch");
985
+ }
986
+ const back = readBoundedRegularFile(join(pointers.gitdir, "gitdir"), GIT_POINTER_BYTES, "gitdir")?.trim() ?? "";
987
+ if (back === "" || isNetworkOrDevicePath(back) || !sameOnDisk(resolve(pointers.gitdir, back), join(checkout, ".git"))) {
988
+ throw new Error("refused: the work root's git directory does not point back to this work root (not the worktree listed at dispatch)");
989
+ }
990
+ }
991
+
992
+ 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;
995
+ const budget: Budget = { signal, timeoutMs: () => {
996
+ const remaining = deadline - performance.now();
997
+ if (remaining <= 0) throw new Error("Git inspection timed out");
998
+ return remaining;
999
+ } };
1000
+ validateInput(operation, input);
1001
+ if (!isDirectory(directory)) throw new Error("Session directory does not exist");
1002
+ const session = realpath(directory);
1003
+ const boundary = sessionBoundary(session, options.worktree);
1004
+ // QA-G-A2-2: a role work root's `.git` pointers are checked before anything is spawned.
1005
+ const role = options.role === undefined ? undefined : roleRepository(session, options.role.dispatchRepository);
1006
+ // G4: never run a git that lives in the session's tree, checked before anything is spawned.
1007
+ const nearest = nearestRepository(session);
1008
+ const executable = selectGitExecutable(options.executables ?? defaultCandidates(), [session, boundary, ...(nearest ? [nearest] : []), ...(options.guards ?? [])]);
1009
+ const inherited = await inheritedConfig(executable, budget);
1010
+ const trusted = inherited.filter(pair => pair.startsWith("safe.directory=")).flatMap(pair => ["-c", pair]);
1011
+ const base = [...hardeningArgs(), ...trusted];
1012
+ // G11: discovery cannot climb above the session's worktree.
1013
+ const env = gitEnvironment(dirname(boundary) === boundary ? {} : { GIT_CEILING_DIRECTORIES: dirname(boundary) });
1014
+ const shown = await runBoundedProcess(executable, [...base, "rev-parse", "--show-toplevel"],
1015
+ session, { signal, timeoutMs: budget.timeoutMs(), env });
1016
+ const top = shown.trim();
1017
+ if (!top || !isAbsolute(top) || !existsSync(top)) throw new Error("Cannot resolve repository toplevel");
1018
+ const root = realpath(top);
1019
+ if (!inside(boundary, root)) throw new Error("Repository toplevel is outside the session worktree");
1020
+ if (inside(root, executable)) throw new Error(`Refusing git executable inside the repository: ${executable}`);
1021
+ // QA-G-A2-4: a role work root below the top level limits every path and listing to it (`scope`, repository-relative).
1022
+ let scope: string | undefined;
1023
+ if (role !== undefined) {
1024
+ await verifyRoleRepository(executable, base, session, env, budget, role);
1025
+ if (!inside(root, session)) throw new Error("refused: the work root is not inside its repository's top level");
1026
+ const below = relative(root, session);
1027
+ scope = below === "" ? undefined : below.split(/[\\/]/).join("/");
1028
+ }
1029
+ const scopeSpec = scope === undefined ? [] : [`:(literal)${scope}`];
1030
+ const repository = await repositoryConfig(executable, root, env, base, budget);
1031
+ const config = [...trusted,
1032
+ ...inherited.filter(pair => !pair.startsWith("safe.directory=") && !repository.overridden.has(pair.slice(0, pair.indexOf("=")))).flatMap(pair => ["-c", pair]),
1033
+ ...repository.neutralize];
1034
+ let linked: string[] = [];
1035
+ if (readsWorktree(operation, input)) {
1036
+ const index = await spawnBounded(executable, [...base, "ls-files", "-z", "--cached", ...(scope === undefined ? [] : ["--", ...scopeSpec])], root,
1037
+ { env, signal, timeoutMs: budget.timeoutMs(), maxBytes: MAX_INDEX_BYTES });
1038
+ if (index.truncated) throw new Error(`Tracked-index listing size cap exceeded (${MAX_INDEX_BYTES} bytes); use diff mode: cached or a commit range`);
1039
+ if (index.code !== 0) throw queryFailure("Cannot list tracked files", index);
1040
+ linked = await linkedTrackedDirectories(root, index.output.toString("utf8").split("\0").filter(Boolean), budget);
1041
+ if (linked.length > MAX_LINKED_EXCLUDES) throw new Error("Refusing inspection: too many tracked directories were replaced by links; use diff mode: cached or a commit range");
1042
+ }
1043
+ let inspected = input;
1044
+ if (operation === "show") {
1045
+ // Deliberately single-object only: log/diff accept ranges, show preserves tag messages.
1046
+ if (input.ref?.includes("..")) throw new Error("Git show accepts one commit or annotated tag, not ranges; use log or diff for a range");
1047
+ const object = await query(executable, [...base, "rev-parse", "--verify", "--end-of-options", input.ref ?? "HEAD"], root, env, budget);
1048
+ const oid = object.output.toString("utf8").trim();
1049
+ const refused = () => new Error("Git show requires a commit or annotated tag pointing to a commit (not a blob/tree); use read for sensitive files (asks for approval)");
1050
+ if (object.code !== 0 || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(oid)) throw refused();
1051
+ const type = await query(executable, [...base, "cat-file", "-t", oid], root, env, budget);
1052
+ const kind = type.output.toString("utf8").trim();
1053
+ if (type.code !== 0 || !["commit", "tag"].includes(kind)) throw refused();
1054
+ if (kind === "tag") {
1055
+ const commit = await query(executable, [...base, "rev-parse", "--verify", `${oid}^{commit}`], root, env, budget);
1056
+ if (commit.code !== 0) throw refused();
1057
+ }
1058
+ inspected = { ...input, ref: oid };
1059
+ }
1060
+ 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 });
1064
+ let output = ["show", "diff", "log"].includes(operation) ? filterSensitiveDiff(raw) : raw;
1065
+ if (operation === "show" || operation === "log") output = await annotateWithheld(output, executable, base, root, env, budget, scopeSpec);
1066
+ if (linked.length === 0) return output;
1067
+ return `${output}${output.endsWith("\n") || output === "" ? "" : "\n"}[router_git] skipped tracked directories replaced by symlinks/junctions: ${linked.slice(0, 20).join(", ")}${linked.length > 20 ? ", ..." : ""}`;
1068
+ }
1069
+
1070
+ /**
1071
+ * A work-root resolver's answer for one session (R6/P-18, QA-P13-1-10). It is explicit
1072
+ * so that a lost binding can never read as "not a role session" (fail closed):
1073
+ * - `{ role: false }`: not a role session. The tool behaves exactly as without a
1074
+ * resolver (`context.directory` / `context.worktree`, I1).
1075
+ * - `{ role: true, root: null }`: a role session without a binding (or with
1076
+ * `workRoot: null`). The tool refuses and spawns nothing (I9).
1077
+ * - `{ role: true, root }`: the absolute work root bound to the session (a drive or
1078
+ * UNC path on win32, never root-relative). The tool inspects that directory (its
1079
+ * repository is discovered from it, never above its checkout; only paths inside the
1080
+ * root are shown or accepted, QA-G-A2-4; its `.git` pointers are checked, QA-G-A2-2) and ignores
1081
+ * `context.directory`/`context.worktree`, which under the v2 bridge name the main
1082
+ * checkout rather than a sibling worktree (S11, P-10).
1083
+ * Any other answer, or a throwing resolver, is reported as a tool error; nothing is spawned.
1084
+ */
1085
+ export type WorkRootAnswer = { role: false } | { role: true; root: string | null };
1086
+ /**
1087
+ * P1.3 injects, P2.1 wires it to the dispatch binding. Shared by router_git_* and
1088
+ * router_run (QA-P13-2-8); router_run refuses `{ role: false }` (it exists for role
1089
+ * sessions only) as well as `{ role: true, root: null }`.
1090
+ */
1091
+ export type GitWorkRootResolver = (sessionID: string) => WorkRootAnswer;
1092
+ export interface GitToolsOptions {
1093
+ resolveWorkRoot?: GitWorkRootResolver;
1094
+ /**
1095
+ * QA-G-A2-2: the directory in whose repository role dispatches list their worktrees (the plugin's directory). In role mode the
1096
+ * bound work root's common git directory must be that repository's. Absent: only the work root's own pointers are checked.
1097
+ */
1098
+ dispatchRepository?: string;
1099
+ }
1100
+
1101
+ /** Validate a resolver answer; throws for anything that is not a WorkRootAnswer. */
1102
+ export function checkWorkRootAnswer(answer: unknown): WorkRootAnswer {
1103
+ if (typeof answer === "object" && answer !== null && "role" in answer) {
1104
+ const { role } = answer as { role: unknown };
1105
+ if (role === false) return { role: false };
1106
+ if (role === true && "root" in answer) {
1107
+ const { root } = answer as { root: unknown };
1108
+ if (root === null) return { role: true, root: null };
1109
+ if (typeof root === "string" && isFullPath(root)) return { role: true, root };
1110
+ throw new Error("Bound work root is not an absolute path");
1111
+ }
1112
+ }
1113
+ throw new Error("Invalid work-root answer: expected { role: false } or { role: true, root }");
1114
+ }
1115
+
1116
+ export function gitTools(opts: GitToolsOptions = {}) {
1117
+ // G4: resolve the git executable once, at plugin load.
1118
+ const executables = defaultCandidates();
1119
+ const inputSchema = tool.schema.object({
1120
+ path: tool.schema.string().optional(), ref: tool.schema.string().optional(),
1121
+ limit: tool.schema.number().int().min(1).max(50).optional(),
1122
+ mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional(),
1123
+ }).strict();
1124
+ 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.`,
1126
+ args: {
1127
+ path: tool.schema.string().optional().describe("Literal repository-relative path; required for blame"),
1128
+ ...(operation === "log" || operation === "diff" || operation === "show" || operation === "blame"
1129
+ ? { 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
+ ...(operation === "log" ? { limit: tool.schema.number().int().min(1).max(50).optional() } : {}),
1131
+ ...(operation === "diff" ? { mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional() } : {}),
1132
+ },
1133
+ async execute(input, context) {
1134
+ try {
1135
+ if (opts.resolveWorkRoot) {
1136
+ const answer = checkWorkRootAnswer(opts.resolveWorkRoot(context.sessionID));
1137
+ if (answer.role) {
1138
+ 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, {
1140
+ executables, guards: workRootGuards(answer.root),
1141
+ role: opts.dispatchRepository ? { dispatchRepository: opts.dispatchRepository } : {},
1142
+ });
1143
+ }
1144
+ }
1145
+ return await inspectGit(operation, inputSchema.parse(input), context.directory, context.abort, { worktree: context.worktree, executables });
1146
+ } catch (error) {
1147
+ // G12: report, never throw into the session; messages are credential-redacted.
1148
+ return `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;
1149
+ }
1150
+ },
1151
+ })]));
1152
+ }