opencode-model-router 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -1,9 +1,18 @@
1
1
  import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2
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";
3
+ import { lstat, stat } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, win32 } from "node:path";
6
6
  import { tool } from "@opencode-ai/plugin";
7
+ import { canonicalArgs, dedupeAnswer, forgetAnswer, forgetToolAnswers, FORCE_ARG_DESCRIPTION, gitUnchangedStub, type AnswerKey } from "./answer-dedup";
8
+ import {
9
+ DIFF_SUMMARY_THRESHOLD_BYTES, diffSummaryShown, entryExcludedKind, excludedListShown, pairRawEntries, parseNumstat, parseRawDiff, renderDiffSummary,
10
+ renderExcludedList, type NumstatEntry, type RawEntry, type SummaryEntry, type SummaryHandles, type SummaryReason,
11
+ } from "./diff-summary";
12
+ import {
13
+ expandable, HANDLE_RE, isBlobId, lookupHandle, MAX_BLOB_BYTES, mintHandle, parseLineRange, renderExpansion, sideProblem, type HandleTarget,
14
+ type HandleVia, type WorktreeStat,
15
+ } from "./diff-handles";
7
16
  import { filterSensitiveDiff, isSensitivePath, sensitiveGitPathspecs } from "./sensitive-paths";
8
17
 
9
18
  export const GIT_OPERATIONS = ["status", "log", "diff", "show", "blame", "ls_files"] as const;
@@ -29,6 +38,16 @@ export interface GitInspectOptions {
29
38
  filterSearch?: (root: string, paths: readonly string[]) => { kept: readonly string[]; note?: string };
30
39
  /** Absolute `Date.now()` deadline shared with the caller (a `root` resolution, SD-3b-8); without it a fresh 15 s budget starts. */
31
40
  deadlineAt?: number;
41
+ /**
42
+ * #108 (OpenCode v2 roles mode, role sessions only): a `diff` without `path` in mode `patch` or `cached` lists the files whose
43
+ * content is excluded (diff-summary.ts) instead of their hunks, and is summarized when its patch exceeds 8 KiB. Absent: unchanged.
44
+ */
45
+ summary?: boolean;
46
+ /**
47
+ * #108 slice 3 (with `summary`): mints the `gd_` handle of a file version a summary or excluded list shows (diff-handles.ts),
48
+ * bound by the caller to the session (`context.sessionID`) and the way it reached the repository. Absent: no handles.
49
+ */
50
+ mintHandle?: (target: HandleTarget) => string | undefined;
32
51
  }
33
52
 
34
53
  const MAX_BYTES = 64 * 1024;
@@ -81,12 +100,28 @@ function lstatOrUndefined(path: string): Stats | undefined {
81
100
  }
82
101
  }
83
102
 
84
- /** stat (following links) that reports a missing path, a dangling link or a file used as a directory as undefined. */
85
- function statOrUndefined(path: string): Stats | undefined {
86
- try { return statSync(path); } catch (error) {
103
+ const DRIVER_QUERY_TIMEOUT = "Git driver configuration query timed out";
104
+
105
+ /**
106
+ * Async stat (following links): false for a missing path, a dangling link or a file used as a directory; any other error
107
+ * throws. With `deadline` (a `performance.now()` value) a stat still pending then, or a deadline already past, throws.
108
+ */
109
+ async function includeTargetExists(path: string, deadline: number | undefined): Promise<boolean> {
110
+ return (await statWithin(path, deadline, true)) !== undefined;
111
+ }
112
+
113
+ /** {@link includeTargetExists}'s bounded stat, returning the stats (undefined: missing); `follow: false` is an lstat. */
114
+ async function statWithin(path: string, deadline: number | undefined, follow: boolean): Promise<Stats | undefined> {
115
+ const remaining = deadline === undefined ? undefined : deadline - performance.now();
116
+ if (remaining !== undefined && remaining <= 0) throw new Error(DRIVER_QUERY_TIMEOUT);
117
+ const found = (follow ? stat(path) : lstat(path)).then(stats => stats, (error: unknown) => {
87
118
  if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return undefined;
88
119
  throw error;
89
- }
120
+ });
121
+ if (remaining === undefined) return found;
122
+ let timer: NodeJS.Timeout | undefined;
123
+ const expired = new Promise<never>((_resolve, reject) => { timer = setTimeout(() => reject(new Error(DRIVER_QUERY_TIMEOUT)), remaining); });
124
+ try { return await Promise.race([found, expired]); } finally { clearTimeout(timer); }
90
125
  }
91
126
 
92
127
  function isDirectory(path: string): boolean {
@@ -204,7 +239,49 @@ export function workRootReadArgs(): string[] {
204
239
  * `protocol.<name>.allow` (a remote helper), and the include directives that can bring more of them in.
205
240
  */
206
241
  const REPOSITORY_DRIVER_QUERY = "^(filter\\..+\\.(clean|smudge|process)|merge\\..+\\.driver|protocol\\..+\\.allow|include\\.path|includeif\\..+\\.path)$";
207
- const DRIVER_KEY = /^(?:filter\.(.+)\.(?:clean|smudge|process)|merge\..+\.driver)$/;
242
+ /**
243
+ * #184: what a forwarded filter or merge program (git-lfs) runs, registers or writes to from a key it reads, matched against
244
+ * the key as git-lfs derives it (see {@link derivedKeys}) and folded (see {@link foldings}), as a superset of git-lfs's own
245
+ * matches: an extension's `clean`/`smudge` (any `lfs.*.clean|smudge`), a custom transfer agent's path or args (git-lfs finds
246
+ * agents with an unanchored `lfs.customtransfer.([^.]+).path` and passes path and args to `sh -c`: any key holding
247
+ * `customtransfer` and later `path` or `args`), the standalone agent that selects one (also per URL), `core.sshCommand`,
248
+ * `core.askPass`, and `lfs.storage` (where git-lfs writes objects). `s`: a CR in a key still matches, and is then refused.
249
+ */
250
+ const LFS_PROGRAM_SETTING = /^lfs\..+\.(?:clean|smudge)$|customtransfer.*(?:path|args)|standalonetransferagent|^core\.(?:sshcommand|askpass)$|^lfs\.storage$/s;
251
+ /** `credential.helper` and `credential.<url>.helper`: git runs every value, not only the last, so one `-c credential.helper=` resets them. */
252
+ const CREDENTIAL_HELPER_SETTING = /^credential\..*helper$/s;
253
+ /**
254
+ * Exactly an extension's command as git-lfs reads it (`lfs.extension.<name>.clean|smudge`, four parts once folded): git-lfs
255
+ * never takes one from `.lfsconfig` (its safe-key filter drops it), and blanking it there would register an extension with no
256
+ * command in git's configuration, failing every LFS write. Only such a `.lfsconfig` key is left out of the blanking.
257
+ */
258
+ const LFS_EXTENSION_COMMAND = /^lfs\.extension\.[^.]+\.(?:clean|smudge)$/s;
259
+ /**
260
+ * Any include directive, any letter or byte in its condition (`s`): in a `.lfsconfig` (git-lfs has git read the file with
261
+ * `--includes`), and in the repository's configuration when forwarding.
262
+ */
263
+ const ANY_INCLUDE_KEY = /^(?:include|includeif\..*)\.path$/s;
264
+ /**
265
+ * #184: config-based hooks (`hook.<name>.command`, attached to an event by `hook.<name>.event`; git 2.56 runs them), which no
266
+ * `core.hooksPath` disables and no verified `-c` setting turns off. Matched folded; `s`: any byte in the name.
267
+ */
268
+ const HOOK_SETTING = /^hook\..+\.(?:command|event)$/s;
269
+ /**
270
+ * The verification snapshot's and reference's hook pre-check ({@link DRIVER_SCOPE_ARGS}' format; their own listing is
271
+ * unchanged): every `hook.<name>.command|event`, includes followed as git follows them now. Exit 1: none.
272
+ */
273
+ export const HOOK_SCOPE_ARGS: readonly string[] = Object.freeze(["config", "-z", "--show-scope", "--show-origin", "--get-regexp", "^hook\\..+\\.(command|event)$"]);
274
+ /** What a verification include read lists: the repository driver query's keys and every config-based hook setting. */
275
+ const INCLUDE_READ_QUERY = "^(filter\\..+\\.(clean|smudge|process)|merge\\..+\\.driver|protocol\\..+\\.allow|include\\.path|includeif\\..+\\.path|hook\\..+\\.(command|event))$";
276
+ /**
277
+ * A key `-c <key>=` names exactly as git stores it: a lowercase section of letters, digits and `-`, an optional subsection
278
+ * (anything but a line break, NUL or U+FFFD, checked apart), and a lowercase variable that starts with a letter. `-c`
279
+ * lowercases a section or variable, so a key spelled otherwise would blank another key.
280
+ */
281
+ const PASSABLE_KEY = /^[a-z0-9-]+(?:\.[^]*)?\.[a-z][a-z0-9-]*$/;
282
+ const DRIVER_KEY = /^(?:filter\.(.+)\.(?:clean|smudge|process|required)|merge\..+\.driver)$/;
283
+ /** A driver key that names a program; `filter.<name>.required` names none and is never blanked. */
284
+ const PROGRAM_KEY = /^(?:filter\.(.+)\.(?:clean|smudge|process)|merge\..+\.driver)$/;
208
285
  const PROTOCOL_KEY = /^protocol\..+\.allow$/;
209
286
  const INCLUDE_KEY = /^(?:include\.path|includeif\..+\.path)$/;
210
287
  /** The configuration scopes the user controls; every other scope (local, worktree, an unknown one) is the repository's. */
@@ -218,9 +295,17 @@ const MAX_INCLUDE_TARGETS = 50;
218
295
  * >= 2.26), NUL-separated: `<scope>\0<origin>\0<key>\n<value>\0`. Exit 1: none is set. Parsed by {@link parseDriverListing}.
219
296
  */
220
297
  export const DRIVER_SCOPE_ARGS: readonly string[] = Object.freeze(["config", "-z", "--show-scope", "--show-origin", "--get-regexp", REPOSITORY_DRIVER_QUERY]);
298
+ /**
299
+ * The listing of a call that forwards the user's drivers (`forwardUser`, see {@link repositoryOnlyDriverArgs}): every setting,
300
+ * in {@link DRIVER_SCOPE_ARGS}'s format, so the drivers to forward (`filter.<name>.required` too) and every repository line
301
+ * git-lfs could read (#184, any key and value) come from one listing.
302
+ */
303
+ const FORWARD_SCOPE_ARGS: readonly string[] = Object.freeze(["config", "-z", "--show-scope", "--show-origin", "--list"]);
221
304
 
305
+ /** One configuration entry; `value` is undefined for a value-less key. */
306
+ export interface ConfigEntry { readonly key: string; readonly value: string | undefined }
222
307
  /** One entry of a {@link DRIVER_SCOPE_ARGS} listing; `value` is undefined for a value-less key. */
223
- export interface DriverEntry { readonly scope: string; readonly origin: string; readonly key: string; readonly value: string | undefined }
308
+ export interface DriverEntry extends ConfigEntry { readonly scope: string; readonly origin: string }
224
309
 
225
310
  function splitConfigEntry(field: string): { key: string; value: string | undefined } {
226
311
  const newline = field.indexOf("\n");
@@ -247,10 +332,21 @@ export function parseDriverListing(listing: string): DriverEntry[] {
247
332
  * - a blanked filter gets `-c filter.<name>.required=<required>`: `false` for a read-only snapshot (as `inspectGit`), `true`
248
333
  * where git writes (the executor, the reference), so git refuses instead of storing or checking out unfiltered content.
249
334
  * - `-c protocol.<name>.allow=never` for every `protocol.<name>.allow` the repository sets.
250
- * Throws when a key cannot be blanked (`-c` splits at the first `=`).
335
+ * - with `forwardUser` (the executor, whose git hides the system and global configuration), first `-c <key>=<value>` for every
336
+ * filter clean/smudge/process/required and merge driver whose effective value comes from the system, global or command-line
337
+ * configuration, so the call runs the filter programs plain git would run (a global Git LFS filter, #162). Nothing of a
338
+ * filter with a blanked key, and no blanked merge driver, is forwarded; nothing is ever forwarded from the repository's
339
+ * configuration. A user key `-c` would not pass on as git read it (see {@link UNFORWARDABLE}) is not forwarded: it is
340
+ * blanked (a `required` key is not: blank reads as false) and its filter gets `required=true` whatever `required` is, so
341
+ * git refuses only where that filter is used; no other key of that filter is forwarded.
342
+ * - with `forwardUser`, last, every setting of the repository's configuration (the listing's repository scopes, `included`)
343
+ * and of its `.lfsconfig` (`lfsconfig`) a forwarded filter program (git-lfs) would run, register or write to from is
344
+ * neutralized (#184, see {@link repositoryProgramArgs}).
345
+ * Throws when a key cannot be blanked (`-c` splits at the first `=`), and when a key to forward has a `=` in its name.
251
346
  */
252
- export function repositoryOnlyDriverArgs(listing: string,
253
- options: { required?: boolean; included?: readonly { key: string; value: string | undefined }[] } = {}): string[] {
347
+ export function repositoryOnlyDriverArgs(listing: string, options: {
348
+ required?: boolean; forwardUser?: boolean; included?: readonly ConfigEntry[]; lfsconfig?: readonly ConfigEntry[];
349
+ } = {}): string[] {
254
350
  const userValues = new Map<string, Set<string>>();
255
351
  const effective = new Map<string, { scope: string; value: string | undefined }>();
256
352
  const protocols = new Set<string>();
@@ -271,12 +367,13 @@ export function repositoryOnlyDriverArgs(listing: string,
271
367
  }
272
368
  const trusted = (key: string, value: string | undefined) => value !== undefined && userValues.get(key)?.has(value) === true;
273
369
  const blank = new Set<string>();
274
- for (const [key, { scope, value }] of effective) if (!USER_SCOPES.has(scope) && !trusted(key, value)) blank.add(key);
370
+ for (const [key, { scope, value }] of effective) if (PROGRAM_KEY.test(key) && !USER_SCOPES.has(scope) && !trusted(key, value)) blank.add(key);
275
371
  for (const { key, value } of options.included ?? []) {
276
372
  if (PROTOCOL_KEY.test(key)) protocols.add(key);
277
- else if (DRIVER_KEY.test(key) && !trusted(key, value)) blank.add(key);
373
+ else if (PROGRAM_KEY.test(key) && !trusted(key, value)) blank.add(key);
278
374
  }
279
- const args: string[] = [];
375
+ const { args, refused }: { args: string[]; refused: readonly string[] } =
376
+ options.forwardUser === true ? forwardedUserDrivers(effective, blank) : { args: [], refused: [] };
280
377
  const filters = new Set<string>();
281
378
  const refuse = () => new Error("Refusing repository: a filter/merge driver or protocol name contains '=' and cannot be neutralized");
282
379
  for (const key of blank) {
@@ -286,15 +383,131 @@ export function repositoryOnlyDriverArgs(listing: string,
286
383
  if (filter) filters.add(`filter.${filter[1]}.required=${options.required === true}`);
287
384
  }
288
385
  for (const setting of filters) args.push("-c", setting);
386
+ const refusedFilters = new Set<string>();
387
+ for (const key of refused) {
388
+ if (PROGRAM_KEY.test(key)) args.push("-c", `${key}=`);
389
+ const name = DRIVER_KEY.exec(key)?.[1];
390
+ if (name !== undefined) refusedFilters.add(`filter.${name}.required=true`);
391
+ }
392
+ for (const setting of refusedFilters) args.push("-c", setting);
289
393
  for (const key of protocols) {
290
394
  if (key.includes("=")) throw refuse();
291
395
  args.push("-c", `${key}=never`);
292
396
  }
397
+ if (options.forwardUser === true) {
398
+ const repository = parseDriverListing(listing).filter(({ scope }) => !USER_SCOPES.has(scope));
399
+ args.push(...repositoryProgramArgs([...repository, ...(options.included ?? [])], options.lfsconfig ?? []));
400
+ }
293
401
  return args;
294
402
  }
295
403
 
296
- /** One `git config` query, run where and as the protected command runs: its exit code and stdout. */
297
- export type DriverQuery = (args: readonly string[]) => Promise<{ readonly code: number | null; readonly stdout: string }>;
404
+ /**
405
+ * The keys git-lfs reads from one entry: it lists the configuration with `git config -l` (no `-z`), splits the output at line
406
+ * breaks and each line at its first `=`. A key holding `=`, or a value holding a line break, so yields keys git never set.
407
+ */
408
+ function derivedKeys(key: string, value: string | undefined): string[] {
409
+ const keys: string[] = [];
410
+ for (const line of (value === undefined ? key : `${key}=${value}`).split("\n")) {
411
+ const equals = line.indexOf("=");
412
+ if (equals !== -1) keys.push(line.slice(0, equals));
413
+ }
414
+ return keys;
415
+ }
416
+
417
+ /**
418
+ * A key as a case-insensitive reader may fold it: Go's `strings.ToLower` (simple case mapping: U+0130 to `i`, U+212A to `k`,
419
+ * as JavaScript per code point otherwise) and, as a superset, JavaScript's `toLowerCase`. git-lfs 3.7.0 takes keys as git
420
+ * prints them; an older or later one that lowercases them is covered too.
421
+ */
422
+ function foldings(key: string): string[] {
423
+ return [Array.from(key, letter => (letter === "\u0130" ? "i" : letter.toLowerCase())).join(""), key.toLowerCase()];
424
+ }
425
+
426
+ /**
427
+ * The #184 part of {@link repositoryOnlyDriverArgs} (`forwardUser`). A forwarded filter or merge program (git-lfs) runs in the
428
+ * call's environment and reads the repository's configuration and its `.lfsconfig` itself, line by line (see
429
+ * {@link derivedKeys}). For every key so derived from a `repository` or `lfsconfig` entry that matches
430
+ * {@link LFS_PROGRAM_SETTING} once folded (from `lfsconfig`, not {@link LFS_EXTENSION_COMMAND}): `-c <key>=`, spelled as
431
+ * derived (git-lfs takes a key's last value, git-lfs reads git's configuration after its
432
+ * `.lfsconfig`, and the command line comes last, so the blank wins). A credential helper ({@link CREDENTIAL_HELPER_SETTING}, as
433
+ * git or git-lfs reads it) gets one `-c credential.helper=`, which resets git's helper list. Nothing is kept for being also
434
+ * the user's: the executor's git hides the user's values, so git-lfs could only see the repository's copy. Throws (fail closed)
435
+ * for a key `-c` cannot name ({@link PASSABLE_KEY}: a CR, U+FFFD for a byte that is not UTF-8, a malformed section or name,
436
+ * a section or variable that is not lowercase).
437
+ */
438
+ function repositoryProgramArgs(repository: readonly ConfigEntry[], lfsconfig: readonly ConfigEntry[]): string[] {
439
+ const blank = new Set<string>();
440
+ let helpers = false;
441
+ const matches = (pattern: RegExp, key: string) => foldings(key).some(folded => pattern.test(folded));
442
+ for (const [entries, fromLfsconfig] of [[repository, false], [lfsconfig, true]] as const) {
443
+ for (const { key, value } of entries) {
444
+ if (matches(CREDENTIAL_HELPER_SETTING, key)) helpers = true;
445
+ for (const derived of derivedKeys(key, value)) {
446
+ if (matches(CREDENTIAL_HELPER_SETTING, derived)) helpers = true;
447
+ else if (fromLfsconfig && matches(LFS_EXTENSION_COMMAND, derived)) continue;
448
+ else if (matches(LFS_PROGRAM_SETTING, derived)) blank.add(derived);
449
+ }
450
+ }
451
+ }
452
+ const args: string[] = [];
453
+ for (const key of blank) {
454
+ if (UNFORWARDABLE.test(key) || !PASSABLE_KEY.test(key)) {
455
+ throw new Error("Refusing repository: a key git-lfs would read as an lfs, core.sshCommand or core.askPass setting cannot be passed with -c to neutralize it");
456
+ }
457
+ args.push("-c", `${key}=`);
458
+ }
459
+ if (helpers) args.push("-c", "credential.helper=");
460
+ return args;
461
+ }
462
+
463
+ /**
464
+ * What a forwarded key or value must not hold: a line break or NUL, which `-c` would not pass on as git read it, or U+FFFD.
465
+ * Listings are decoded as UTF-8 (`toString("utf8")`), so a byte that is not UTF-8 reads as U+FFFD, and forwarding that value
466
+ * would name another command (a literal U+FFFD is refused the same way, fail closed).
467
+ */
468
+ const UNFORWARDABLE = /[\0\r\n\uFFFD]/;
469
+
470
+ /**
471
+ * The `forwardUser` part of {@link repositoryOnlyDriverArgs}. `args`: `-c <key>=<value>` (`-c <key>` for a value-less key,
472
+ * git's boolean true) for every driver key of `effective` set last by a user scope, except the keys of a filter with a key in
473
+ * `blank`, a merge driver in `blank`, and every key of a filter with a `refused` key. `refused`: the user keys whose key or
474
+ * value matches {@link UNFORWARDABLE}. Throws (fail closed) for a key with a `=` in its name, which `-c` would split.
475
+ */
476
+ function forwardedUserDrivers(effective: ReadonlyMap<string, { scope: string; value: string | undefined }>,
477
+ blank: ReadonlySet<string>): { args: string[]; refused: string[] } {
478
+ const blankedFilters = new Set<string>();
479
+ for (const key of blank) {
480
+ const name = PROGRAM_KEY.exec(key)?.[1];
481
+ if (name !== undefined) blankedFilters.add(name);
482
+ }
483
+ const candidates: { key: string; value: string | undefined; filter: string | undefined }[] = [];
484
+ const refused: string[] = [];
485
+ const refusedFilters = new Set<string>();
486
+ for (const [key, { scope, value }] of effective) {
487
+ if (!USER_SCOPES.has(scope) || blank.has(key)) continue;
488
+ const filter = DRIVER_KEY.exec(key)?.[1];
489
+ if (filter !== undefined && blankedFilters.has(filter)) continue;
490
+ if (key.includes("=")) throw new Error(`Refusing to run git: the user's ${key} cannot be passed with -c (its name contains '=')`);
491
+ if (UNFORWARDABLE.test(key) || (value !== undefined && UNFORWARDABLE.test(value))) {
492
+ refused.push(key);
493
+ if (filter !== undefined) refusedFilters.add(filter);
494
+ continue;
495
+ }
496
+ candidates.push({ key, value, filter });
497
+ }
498
+ const args: string[] = [];
499
+ for (const { key, value, filter } of candidates) {
500
+ if (filter === undefined || !refusedFilters.has(filter)) args.push("-c", value === undefined ? key : `${key}=${value}`);
501
+ }
502
+ return { args, refused };
503
+ }
504
+
505
+ /**
506
+ * One `git config` (or `rev-parse`) query, run where and as the protected command runs: its exit code and stdout. An exit
507
+ * other than 0 or 1 throws, unless `anyExit` (a probe whose failure is an answer, such as a missing `.lfsconfig` blob).
508
+ */
509
+ export type DriverQuery = (args: readonly string[], options?: { anyExit?: boolean }) =>
510
+ Promise<{ readonly code: number | null; readonly stdout: string }>;
298
511
 
299
512
  /** The file an include directive names (git's rules: `~/`, absolute, else relative to the including file); undefined: none. */
300
513
  function includeTarget(value: string | undefined, base: string | undefined): string | undefined {
@@ -314,19 +527,42 @@ function includeTarget(value: string | undefined, base: string | undefined): str
314
527
  * is resolved against it). A missing target is skipped, as git skips it, and so is a dangling link on every platform (as
315
528
  * POSIX git does; Git for Windows may fail on one instead); an unreadable, network or device target (on win32 also a
316
529
  * reserved device name such as `NUL` or `com1.cfg`), or more than {@link MAX_INCLUDE_TARGETS} targets or
317
- * {@link MAX_INCLUDE_DEPTH} levels, throws (fail closed).
530
+ * {@link MAX_INCLUDE_DEPTH} levels, throws (fail closed). `deadline` (a `performance.now()` value, the queries' own) also
531
+ * bounds the existence check of every target: one still pending then throws. `forwardUser`: the listing and every include read
532
+ * list every setting ({@link FORWARD_SCOPE_ARGS}), and when a filter or merge program is configured (git-lfs runs as one,
533
+ * and only then reads `.lfsconfig`) the `.lfsconfig` git-lfs would read is read too ({@link lfsconfigEntries}, #184); see
534
+ * {@link repositoryOnlyDriverArgs}. Also with `forwardUser`, an include target (any include directive, any condition, existing
535
+ * or missing) inside a work tree of the repository throws: git-lfs reads the configuration, includes followed, when it
536
+ * starts, which may be after the call's own checkout, cherry-pick or rebase wrote a tracked target there. In both modes a
537
+ * config-based hook setting (`hook.<name>.command|event`) of the repository's configuration or of an include target throws
538
+ * ({@link refuseRepositoryHooks}): without forwarding, through one more listing ({@link HOOK_SCOPE_ARGS}) and the include reads.
318
539
  */
319
- export async function collectRepositoryDriverArgs(query: DriverQuery, cwd: string, options: { required?: boolean } = {}): Promise<string[]> {
320
- const listed = await query(DRIVER_SCOPE_ARGS);
540
+ export async function collectRepositoryDriverArgs(query: DriverQuery, cwd: string,
541
+ options: { required?: boolean; forwardUser?: boolean; deadline?: number } = {}): Promise<string[]> {
542
+ const forward = options.forwardUser === true;
543
+ const includeKey = (key: string) => (forward ? ANY_INCLUDE_KEY : INCLUDE_KEY).test(key);
544
+ const listed = await query(forward ? FORWARD_SCOPE_ARGS : DRIVER_SCOPE_ARGS);
545
+ if (listed.code !== 0 && listed.code !== 1) throw new Error(`Cannot read the repository's driver configuration (exit ${listed.code})`);
546
+ const refusal = forward ? EXECUTOR_HOOK_REFUSAL : VERIFICATION_HOOK_REFUSAL;
547
+ if (!forward) {
548
+ // The verification snapshot and reference fire hook events too (the reference's worktree add: post-checkout; an index
549
+ // write: post-index-change): one pre-check listing, their own listing unchanged.
550
+ const hooks = await query(HOOK_SCOPE_ARGS);
551
+ if (hooks.code !== 0 && hooks.code !== 1) throw new Error(`Cannot read the repository's hook configuration (exit ${hooks.code})`);
552
+ if (hooks.code === 0) refuseRepositoryHooks(parseDriverListing(hooks.stdout).filter(({ scope }) => !USER_SCOPES.has(scope)), false, refusal);
553
+ }
321
554
  if (listed.code === 1) return []; // nothing set anywhere
322
- if (listed.code !== 0) throw new Error(`Cannot read the repository's driver configuration (exit ${listed.code})`);
555
+ const entries = parseDriverListing(listed.stdout);
556
+ if (forward) refuseRepositoryHooks(entries.filter(({ scope }) => !USER_SCOPES.has(scope)), true, refusal);
323
557
  const pending: { path: string; depth: number }[] = [];
324
- for (const { scope, origin, key, value } of parseDriverListing(listed.stdout)) {
325
- if (USER_SCOPES.has(scope) || !INCLUDE_KEY.test(key)) continue;
558
+ for (const { scope, origin, key, value } of entries) {
559
+ if (USER_SCOPES.has(scope) || !includeKey(key)) continue;
326
560
  const base = origin.startsWith("file:") ? dirname(resolve(cwd, origin.slice("file:".length))) : undefined;
327
561
  const path = includeTarget(value, base);
328
562
  if (path !== undefined) pending.push({ path, depth: 1 });
329
563
  }
564
+ // Listed once, only for a repository with an include directive.
565
+ const worktrees = forward && pending.length > 0 ? await worktreeRoots(query) : [];
330
566
  const included: { key: string; value: string | undefined }[] = [];
331
567
  const seen = new Set<string>();
332
568
  for (let next = pending.shift(); next !== undefined; next = pending.shift()) {
@@ -342,16 +578,20 @@ export async function collectRepositoryDriverArgs(query: DriverQuery, cwd: strin
342
578
  if (process.platform === "win32" && WINDOWS_DEVICE.test(win32.basename(path).split(/[.:]/)[0]!.trimEnd())) {
343
579
  throw new Error(`Refusing repository: the config include ${path} names a reserved Windows device`);
344
580
  }
581
+ const tree = enclosingWorktree(worktrees, path);
582
+ if (tree !== undefined) {
583
+ throw new Error(`Refusing to run git: the config include ${path} is inside the work tree ${tree}, where git itself may write it during the call`);
584
+ }
345
585
  // Links are followed: a dangling link is skipped like a missing include, on every platform. POSIX git skips it too (its
346
586
  // access() follows the link); Git for Windows' access() may not, so it may fail on the link instead (not tested).
347
- if (statOrUndefined(path) === undefined) continue;
348
- const read = await query(["config", "--file", path, "-z", "--get-regexp", REPOSITORY_DRIVER_QUERY]);
587
+ if (!(await includeTargetExists(path, options.deadline))) continue;
588
+ const read = await query(["config", "--file", path, "-z", ...(forward ? ["--list"] : ["--get-regexp", INCLUDE_READ_QUERY])]);
349
589
  if (read.code === 1) continue;
350
590
  if (read.code !== 0) throw new Error(`Cannot read the config include ${path} (exit ${read.code})`);
351
591
  for (const field of read.stdout.split("\0")) {
352
592
  if (field === "") continue;
353
593
  const entry = splitConfigEntry(field);
354
- if (!INCLUDE_KEY.test(entry.key)) {
594
+ if (!includeKey(entry.key)) {
355
595
  included.push(entry);
356
596
  continue;
357
597
  }
@@ -359,7 +599,109 @@ export async function collectRepositoryDriverArgs(query: DriverQuery, cwd: strin
359
599
  if (target !== undefined) pending.push({ path: target, depth: depth + 1 });
360
600
  }
361
601
  }
362
- return repositoryOnlyDriverArgs(listed.stdout, { required: options.required === true, included });
602
+ refuseRepositoryHooks(included, forward, refusal); // an include target's hooks, whatever its condition
603
+ // git-lfs reads .lfsconfig only while it runs as a filter or merge program: with none configured (most repositories) the
604
+ // call starts no further process.
605
+ const programs = [...entries, ...included].some(({ key }) => PROGRAM_KEY.test(key));
606
+ const lfsconfig = forward && programs ? await lfsconfigEntries(query, options.deadline) : [];
607
+ return repositoryOnlyDriverArgs(listed.stdout, { required: options.required === true, forwardUser: forward, included, lfsconfig });
608
+ }
609
+
610
+ const EXECUTOR_HOOK_REFUSAL =
611
+ "Refusing to run git: repository config defines git hooks (hook.<name>.*); the plan executor does not run repository hooks";
612
+ const VERIFICATION_HOOK_REFUSAL =
613
+ "Refusing to run git: repository config defines git hooks (hook.<name>.*); verification does not run repository hooks";
614
+
615
+ /**
616
+ * #184: throws `refusal` when an entry of the repository's configuration (its own scopes or an include target) is a
617
+ * config-based hook setting ({@link HOOK_SETTING}, folded), or, with `derived` (forwarding), a key git-lfs would derive from it.
618
+ * The executor's empty `core.hooksPath` disables only classic hooks, and no `-c` setting is verified to disable these.
619
+ */
620
+ function refuseRepositoryHooks(entries: readonly ConfigEntry[], derived: boolean, refusal: string): void {
621
+ const hook = (key: string) => foldings(key).some(folded => HOOK_SETTING.test(folded));
622
+ for (const { key, value } of entries) {
623
+ if (hook(key) || (derived && derivedKeys(key, value).some(hook))) throw new Error(refusal);
624
+ }
625
+ }
626
+
627
+ /** The entries of a `git config -z --list` (or `--get-regexp`) listing without scopes. */
628
+ function configEntries(listing: string): ConfigEntry[] {
629
+ return listing.split("\0").filter(field => field !== "").map(splitConfigEntry);
630
+ }
631
+
632
+ /** `path` with its nearest existing ancestor resolved to its real path (links and junctions followed), the rest appended. */
633
+ function canonicalPath(path: string): string {
634
+ let existing = resolve(path);
635
+ const rest: string[] = [];
636
+ while (!existsSync(existing) && dirname(existing) !== existing) {
637
+ rest.unshift(basename(existing));
638
+ existing = dirname(existing);
639
+ }
640
+ try { return join(realpath(existing), ...rest); } catch { return resolve(path); }
641
+ }
642
+
643
+ /**
644
+ * #184: the work trees of the repository, as real paths: `git worktree list --porcelain -z` (git >= 2.36), else its line
645
+ * format. A bare repository's entry is no work tree.
646
+ */
647
+ async function worktreeRoots(query: DriverQuery): Promise<string[]> {
648
+ const listed = await query(["worktree", "list", "--porcelain", "-z"], { anyExit: true });
649
+ const fields = listed.code === 0 ? listed.stdout.split("\0") : (await query(["worktree", "list", "--porcelain"])).stdout.split("\n");
650
+ const roots: string[] = [];
651
+ let current: string | undefined;
652
+ for (const field of [...fields, "worktree "]) {
653
+ if (field.startsWith("worktree ")) {
654
+ if (current !== undefined && current !== "") roots.push(canonicalPath(current));
655
+ current = field.slice("worktree ".length);
656
+ } else if (field === "bare") {
657
+ current = undefined;
658
+ }
659
+ }
660
+ return roots;
661
+ }
662
+
663
+ /**
664
+ * The work tree of `roots` that holds `path` (both canonical), if any; the `.git` directory of a main work tree is no part of
665
+ * it (git writes no work tree file there).
666
+ */
667
+ function enclosingWorktree(roots: readonly string[], path: string): string | undefined {
668
+ if (roots.length === 0) return undefined; // forwarding off, or no include: no file system call
669
+ const target = canonicalPath(path);
670
+ return roots.find(root => inside(root, target) && foldCase(relative(root, target).split(/[\\/]/)[0] ?? "") !== ".git");
671
+ }
672
+
673
+ /**
674
+ * #184: the `.lfsconfig` entries git-lfs would read where the protected command runs, picked as git-lfs picks the file: the
675
+ * work tree's `.lfsconfig` when it exists, else the index's (`:.lfsconfig`), else `HEAD:.lfsconfig` (a bare repository, or a
676
+ * call outside a work tree, starts at the index). The work tree's file must be a regular file git reads with exit 0 (else
677
+ * this fails closed); a blob git cannot read is skipped, as git-lfs skips it, keeping whatever git printed before it failed.
678
+ * Throws for a work-tree `.lfsconfig` that is a link, and for an include directive in the file read: git-lfs has git read `.lfsconfig` with
679
+ * `--includes`, so git would open the included file (on Windows a network path there sends the user's credentials).
680
+ * `deadline` bounds the work tree's lstat as it bounds the include checks.
681
+ */
682
+ async function lfsconfigEntries(query: DriverQuery, deadline: number | undefined): Promise<ConfigEntry[]> {
683
+ const top = await query(["rev-parse", "--show-toplevel"], { anyExit: true });
684
+ const worktree = top.code === 0 ? top.stdout.replace(/\r?\n$/, "") : "";
685
+ const file = worktree === "" ? undefined : join(worktree, ".lfsconfig");
686
+ const stats = file === undefined ? undefined : await statWithin(file, deadline, false);
687
+ if (stats?.isSymbolicLink() === true) throw new Error("Refusing to run git: the work tree's .lfsconfig is a link");
688
+ if (stats !== undefined && !stats.isFile()) throw new Error("Refusing to run git: the work tree's .lfsconfig is not a regular file");
689
+ const entries: ConfigEntry[] = [];
690
+ if (file !== undefined && stats !== undefined) {
691
+ const read = await query(["config", "--file", file, "-z", "--list"]);
692
+ if (read.code !== 0) throw new Error(`Cannot read the work tree's .lfsconfig (exit ${read.code})`);
693
+ entries.push(...configEntries(read.stdout));
694
+ } else {
695
+ for (const blob of [":.lfsconfig", "HEAD:.lfsconfig"]) {
696
+ const read = await query(["config", "--blob", blob, "-z", "--list"], { anyExit: true });
697
+ entries.push(...configEntries(read.stdout));
698
+ if (read.code === 0) break;
699
+ }
700
+ }
701
+ if (entries.some(({ key }) => ANY_INCLUDE_KEY.test(key))) {
702
+ throw new Error("Refusing to run git: the repository's .lfsconfig includes another file, which git-lfs would have git read");
703
+ }
704
+ return entries;
363
705
  }
364
706
 
365
707
  /** The user's own configuration locations, which plain git honours (git-tools strips every other GIT_* variable). */
@@ -390,25 +732,30 @@ export function driverListingEnvironment(runEnv?: NodeJS.ProcessEnv): NodeJS.Pro
390
732
  /**
391
733
  * {@link collectRepositoryDriverArgs} for a router-run git in `root`, spawned directly: `executable` (default the router's git
392
734
  * outside the work-root guards of `root`), `location` (the command's `--git-dir=`/`--work-tree=` options), `env` (the
393
- * command's environment, see {@link driverListingEnvironment}), `required` (see {@link repositoryOnlyDriverArgs}). Throws when
394
- * the configuration cannot be read: the caller has no run (fail closed).
735
+ * command's environment, see {@link driverListingEnvironment}), `required` and `forwardUser` (see
736
+ * {@link repositoryOnlyDriverArgs}; `forwardUser` only for the executor). `timeoutMs` bounds the whole listing, include-target
737
+ * checks included. Throws when the configuration cannot be read: the caller has no run (fail closed).
395
738
  */
396
739
  export async function repositoryDriverArgs(root: string, options: {
397
- executable?: string; signal?: AbortSignal; timeoutMs?: number; required?: boolean; location?: readonly string[]; env?: NodeJS.ProcessEnv;
740
+ executable?: string; signal?: AbortSignal; timeoutMs?: number; required?: boolean; forwardUser?: boolean; location?: readonly string[];
741
+ env?: NodeJS.ProcessEnv;
398
742
  } = {}): Promise<string[]> {
399
743
  const executable = options.executable ?? gitExecutable(workRootGuards(root));
400
744
  const env = driverListingEnvironment(options.env);
401
745
  const deadline = performance.now() + (options.timeoutMs ?? DEADLINE_MS);
402
- const query: DriverQuery = async (args) => {
746
+ const query: DriverQuery = async (args, queryOptions) => {
403
747
  const remaining = deadline - performance.now();
404
- if (remaining <= 0) throw new Error("Git driver configuration query timed out");
748
+ if (remaining <= 0) throw new Error(DRIVER_QUERY_TIMEOUT);
749
+ // The forwarding listing holds every setting (thousands of branch.* or submodule.* entries in a large repository).
405
750
  const result = await spawnBounded(executable, [...hardeningArgs(), ...(options.location ?? []), ...args], root,
406
- { env, signal: options.signal, timeoutMs: remaining, maxBytes: 1024 * 1024 });
751
+ { env, signal: options.signal, timeoutMs: remaining, maxBytes: (options.forwardUser === true ? 8 : 1) * 1024 * 1024 });
407
752
  if (result.truncated) throw new Error("Git driver configuration exceeds its size bound");
408
- if (result.code !== 0 && result.code !== 1) throw queryFailure("Cannot read the repository's driver configuration", result);
753
+ if (result.code !== 0 && result.code !== 1 && queryOptions?.anyExit !== true) {
754
+ throw queryFailure("Cannot read the repository's driver configuration", result);
755
+ }
409
756
  return { code: result.code, stdout: result.output.toString("utf8") };
410
757
  };
411
- return collectRepositoryDriverArgs(query, root, { required: options.required === true });
758
+ return collectRepositoryDriverArgs(query, root, { required: options.required === true, forwardUser: options.forwardUser === true, deadline });
412
759
  }
413
760
 
414
761
  function validateInput(operation: GitOperation, input: GitInput): { ref?: string } {
@@ -1213,16 +1560,234 @@ export function quoteGitPath(name: string, quoteHigh = true): string {
1213
1560
  * so name-only output is derived from it instead.
1214
1561
  */
1215
1562
  async function diffNames(executable: string, argv: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget): Promise<string> {
1216
- const quoting = await query(executable, [...argv.slice(0, argv.indexOf("diff")), "config", "--type=bool", "--get", "core.quotePath"], root, env, budget);
1217
- if (quoting.code !== 0 && quoting.code !== 1) throw queryFailure("Cannot read path quoting configuration", quoting);
1563
+ const quoteHigh = await quotePathSetting(executable, argv, root, env, budget);
1218
1564
  const args = argv.flatMap(arg => arg === "--name-only" ? ["--numstat", "-z"] : [arg]);
1219
1565
  const result = await spawnBounded(executable, args, root, { env, signal: budget.signal, timeoutMs: budget.timeoutMs() });
1220
1566
  if (!result.truncated && result.code !== 0) throw queryFailure("Git inspection failed", result);
1221
1567
  const names = numstatNames(result.output.toString("utf8"), !result.truncated);
1222
- const text = stripUrlUserinfo(names.map(name => `${quoteGitPath(name, quoting.output.toString("utf8").trim() !== "false")}\n`).join(""));
1568
+ const text = stripUrlUserinfo(names.map(name => `${quoteGitPath(name, quoteHigh)}\n`).join(""));
1223
1569
  return withWarnings(result.truncated ? `${text}[truncated: output exceeds ${MAX_BYTES} bytes]` : text, result);
1224
1570
  }
1225
1571
 
1572
+ /** `core.quotePath` as git reads it for this diff argv (default true): how a name read from `-z` output is shown, as git would. */
1573
+ async function quotePathSetting(executable: string, argv: readonly string[], root: string, env: NodeJS.ProcessEnv, budget: Budget): Promise<boolean> {
1574
+ return await quotePathOf(executable, argv.slice(0, argv.indexOf("diff")), root, env, budget);
1575
+ }
1576
+
1577
+ /** `core.quotePath` as git reads it with the top-level options `prefix` (hardening and `-c` settings; default true). */
1578
+ async function quotePathOf(executable: string, prefix: readonly string[], root: string, env: NodeJS.ProcessEnv, budget: Budget): Promise<boolean> {
1579
+ const quoting = await query(executable, [...prefix, "config", "--type=bool", "--get", "core.quotePath"], root, env, budget);
1580
+ if (quoting.code !== 0 && quoting.code !== 1) throw queryFailure("Cannot read path quoting configuration", quoting);
1581
+ return quoting.output.toString("utf8").trim() !== "false";
1582
+ }
1583
+
1584
+ /** #108: bound of a summary's `--numstat -z` listing (about 40 000 files); a larger one fails the call. */
1585
+ const DIFF_LISTING_BYTES = 4 * 1024 * 1024;
1586
+ /** #108: at most this many paths are left out of a role's patch by literal exclude; past it, a summary. */
1587
+ const MAX_EXCLUDED_PATHSPECS = 200;
1588
+ /**
1589
+ * #108: bound of the patch argv with those excludes, summed as `arg.length + 1` (as the verify runner's MAX_ARGV_CHARS; Windows
1590
+ * CreateProcess takes 32767); past it, a summary instead of a spawn error.
1591
+ */
1592
+ const MAX_DIFF_ARGV_CHARS = 30_000;
1593
+
1594
+ /** #108 P4: an entry either of whose names is sensitive (sensitive-paths.ts). */
1595
+ function sensitiveEntry(entry: NumstatEntry): boolean {
1596
+ return isSensitivePath(entry.path) || (entry.from !== undefined && isSensitivePath(entry.from));
1597
+ }
1598
+
1599
+ /** #108 P4: a sensitive entry as listed: its names only, never its counts. */
1600
+ function withheldEntry(entry: NumstatEntry): SummaryEntry {
1601
+ return { path: entry.path, ...(entry.from === undefined ? {} : { from: entry.from }), sensitive: true };
1602
+ }
1603
+
1604
+ /** A diff argv with `--numstat -z` right after the subcommand (its first `diff`: refs and pathspecs come later). */
1605
+ function numstatArgv(argv: readonly string[]): string[] {
1606
+ const at = argv.indexOf("diff");
1607
+ return [...argv.slice(0, at + 1), "--numstat", "-z", ...argv.slice(at + 1)];
1608
+ }
1609
+
1610
+ /** The listing of a summary's diff argv, parsed. */
1611
+ async function diffListing(executable: string, argv: readonly string[], root: string, env: NodeJS.ProcessEnv, budget: Budget) {
1612
+ const listing = await spawnBounded(executable, numstatArgv(argv), root, { env, signal: budget.signal, timeoutMs: budget.timeoutMs(), maxBytes: DIFF_LISTING_BYTES });
1613
+ if (listing.truncated) throw new Error(`Git diff listing exceeds ${DIFF_LISTING_BYTES / (1024 * 1024)} MiB; call router_git_diff with path, or mode stat`);
1614
+ if (listing.code !== 0) throw queryFailure("Git inspection failed", listing);
1615
+ return { entries: parseNumstat(listing.output.toString("utf8")), result: listing };
1616
+ }
1617
+
1618
+ /** #108 slice 3: bound of the `--raw -z --no-abbrev` listing handles are minted from; past it, no handles. */
1619
+ const RAW_LISTING_BYTES = 4 * DIFF_LISTING_BYTES;
1620
+ /** #108 slice 3: a mintable line is measured with this in place of its handle (the same length). */
1621
+ const HANDLE_PLACEHOLDER = `gd_${"0".repeat(10)}`;
1622
+
1623
+ /** #108 slice 3: how a summary mints: the bound closure, the work-root scope, and whether the diff reads the working tree. */
1624
+ interface SummaryMinting { readonly mint: (target: HandleTarget) => string | undefined; readonly scope?: string; readonly worktree: boolean }
1625
+
1626
+ /** Names of a listed entry, as one key. */
1627
+ function namesOf(entry: { readonly path: string; readonly from?: string }): string {
1628
+ return JSON.stringify([entry.from ?? null, entry.path]);
1629
+ }
1630
+
1631
+ /**
1632
+ * #108 slice 3: the file versions (modes, blob ids, status) of `entries`, the visible listing, from one `--raw -z --no-abbrev`
1633
+ * listing of the same argv, paired by names (pairRawEntries). `unavailable` (a note) when the listings disagree or it is too large.
1634
+ */
1635
+ async function listedVersions(executable: string, argv: readonly string[], root: string, env: NodeJS.ProcessEnv, budget: Budget,
1636
+ entries: readonly NumstatEntry[]): Promise<{ versions: Map<string, RawEntry> } | { unavailable: string }> {
1637
+ const at = argv.indexOf("diff");
1638
+ const listing = await spawnBounded(executable, [...argv.slice(0, at + 1), "--raw", "-z", "--no-abbrev", ...argv.slice(at + 1)], root,
1639
+ { env, signal: budget.signal, timeoutMs: budget.timeoutMs(), maxBytes: RAW_LISTING_BYTES });
1640
+ if (listing.truncated) return { unavailable: "[router_git] handles unavailable: the file listing is too large; call router_git_diff with path" };
1641
+ if (listing.code !== 0) throw queryFailure("Git inspection failed", listing);
1642
+ const raw = parseRawDiff(listing.output.toString("utf8"));
1643
+ const paired = raw === undefined ? undefined : pairRawEntries(entries, raw);
1644
+ if (paired === undefined) return { unavailable: "[router_git] handles unavailable: the working tree changed while listing; call again" };
1645
+ const versions = new Map<string, RawEntry>();
1646
+ paired.forEach((record, index) => { if (record !== undefined) versions.set(namesOf(entries[index]!), record); });
1647
+ return { versions };
1648
+ }
1649
+
1650
+ /**
1651
+ * #108 slice 3: the file version a listed entry names, when one of its sides can be expanded: never for an unmerged or unknown
1652
+ * pair, a sensitive name, or a pair whose sides are all binary, links, submodules, absent or the working tree.
1653
+ */
1654
+ function listedVersion(entry: NumstatEntry, record: RawEntry, root: string, minting: SummaryMinting): HandleTarget | undefined {
1655
+ if (record.status === "U" || record.status === "X" || isSensitivePath(record.path) || (record.from !== undefined && isSensitivePath(record.from))) {
1656
+ return undefined;
1657
+ }
1658
+ const old = record.status === "A" || !isBlobId(record.oldOid) ? undefined : { path: record.from ?? record.path, oid: record.oldOid, mode: record.oldMode };
1659
+ const next = record.status === "D" ? undefined
1660
+ : { path: record.path, mode: record.newMode, worktree: minting.worktree, ...(minting.worktree || !isBlobId(record.newOid) ? {} : { oid: record.newOid }) };
1661
+ const target: HandleTarget = {
1662
+ toplevel: root, status: record.status, ...(minting.scope === undefined ? {} : { scope: minting.scope }),
1663
+ ...(old === undefined ? {} : { old }), ...(next === undefined ? {} : { new: next }), ...(entry.added === undefined ? { binary: true } : {}),
1664
+ };
1665
+ return expandable(target) ? target : undefined;
1666
+ }
1667
+
1668
+ /** #108 slice 3: mint a shown version's handle; a working-tree side adds its lstat. No handle when that lstat fails. */
1669
+ function mintVersion(target: HandleTarget, root: string, minting: SummaryMinting): string | undefined {
1670
+ if (target.new?.worktree !== true) return minting.mint(target);
1671
+ let worktreeStat: WorktreeStat;
1672
+ try {
1673
+ const stats = lstatSync(join(root, target.new.path), { bigint: true });
1674
+ worktreeStat = { size: String(stats.size), mtimeNs: String(stats.mtimeNs), ino: String(stats.ino) };
1675
+ } catch {
1676
+ return undefined; // the file changed or vanished since it was listed: no handle (fail closed)
1677
+ }
1678
+ return minting.mint({ ...target, worktreeStat });
1679
+ }
1680
+
1681
+ /**
1682
+ * #108 slice 3: `entries` with the handles of the lines `shown` lets through (it measures each mintable line with a handle's
1683
+ * length in place), the list options (the expand sentence, and `limit`: that count, so that a line left without a handle is never
1684
+ * shown in its room), and the note when no handle could be minted from the listing. Sensitive entries never get one; without
1685
+ * `minting` nothing changes and nothing is spawned.
1686
+ */
1687
+ async function mintedEntries(entries: readonly SummaryEntry[], visible: readonly NumstatEntry[], minting: SummaryMinting | undefined,
1688
+ run: { executable: string; argv: readonly string[]; root: string; env: NodeJS.ProcessEnv; budget: Budget },
1689
+ shown: (entries: readonly SummaryEntry[], handles: SummaryHandles) => number)
1690
+ : Promise<{ entries: readonly SummaryEntry[]; list: { handles?: SummaryHandles; limit?: number }; note: string }> {
1691
+ if (minting === undefined || entries.every(entry => entry.sensitive === true)) return { entries, list: {}, note: "" };
1692
+ let listed: Awaited<ReturnType<typeof listedVersions>>;
1693
+ try {
1694
+ listed = await listedVersions(run.executable, run.argv, run.root, run.env, run.budget, visible);
1695
+ } catch (error) {
1696
+ // The listing is optional: when it fails (a timeout, a non-zero exit) the summary is still given, without handles. An abort
1697
+ // of the call is the caller's to see.
1698
+ if (run.budget.signal?.aborted === true) throw error;
1699
+ return { entries, list: {}, note: "[router_git] handles unavailable: the file listing failed; call again" };
1700
+ }
1701
+ if ("unavailable" in listed) return { entries, list: {}, note: listed.unavailable };
1702
+ const targets = entries.map(entry => {
1703
+ const record = entry.sensitive === true ? undefined : listed.versions.get(namesOf(entry));
1704
+ return record === undefined ? undefined : listedVersion(entry, record, run.root, minting);
1705
+ });
1706
+ if (targets.every(target => target === undefined)) return { entries, list: {}, note: "" };
1707
+ const handles: SummaryHandles = { worktree: minting.worktree };
1708
+ const count = shown(entries.map((entry, index) => targets[index] === undefined ? entry : { ...entry, handle: HANDLE_PLACEHOLDER }), handles);
1709
+ const minted = entries.map((entry, index) => {
1710
+ const target = targets[index];
1711
+ const handle = target === undefined || index >= count ? undefined : mintVersion(target, run.root, minting);
1712
+ return handle === undefined ? entry : { ...entry, handle };
1713
+ });
1714
+ return { entries: minted, list: { handles, limit: count }, note: "" };
1715
+ }
1716
+
1717
+ /** Notes, each on its own line(s). */
1718
+ function joinedNotes(parts: readonly string[]): string {
1719
+ return parts.filter(part => part !== "").map(part => part.endsWith("\n") ? part : `${part}\n`).join("");
1720
+ }
1721
+
1722
+ /**
1723
+ * #108 slice 1 (OpenCode v2 roles mode, role sessions): a `patch`/`cached` diff without `path`. `argv` is the diff's own (sensitive
1724
+ * paths, links replaced by directories and the work-root scope already excluded); `note` is the skipped-links note, if any.
1725
+ * 1. The files of the diff are listed (`--numstat -z`); those of an excluded kind (lockfiles, snapshots, goldens, fixtures, by
1726
+ * the new path) are left out of the patch by literal pathspec (and a rename's old name, unless a listed file still has that
1727
+ * name, as a copy's source does).
1728
+ * 2. A patch of at most 8 KiB is returned as before (credentials redacted, sensitive sections withheld), followed by the list
1729
+ * of excluded files with their kind and counts, when there are any; an excluded file with a sensitive name is listed by name
1730
+ * only (`sensitive: content withheld`).
1731
+ * 3. Otherwise (or with more than {@link MAX_EXCLUDED_PATHSPECS} excluded files, or a patch argv above
1732
+ * {@link MAX_DIFF_ARGV_CHARS}) the answer is a summary: every file in git's order, its counts, excluded files marked, and
1733
+ * sensitive files by name only. Sensitive files are found by listing the same diff without the sensitive exclusions: a file
1734
+ * found only there, or one sensitive-paths.ts flags, is never shown with counts. At most 4 KiB, with the exact count of what
1735
+ * it leaves out.
1736
+ * 4. Slice 3, with `minting`: every shown line of the summary or the excluded list that is not sensitive and has a side that can
1737
+ * be expanded ends with its `gd_` handle ({@link mintedEntries}); lines the bound leaves out get none.
1738
+ */
1739
+ async function summarizedDiff(executable: string, argv: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget, note: string,
1740
+ minting?: SummaryMinting): Promise<string> {
1741
+ const run = { executable, argv, root, env, budget };
1742
+ const visible = await diffListing(executable, argv, root, env, budget);
1743
+ const excluded: SummaryEntry[] = visible.entries.flatMap(entry => {
1744
+ const kind = entryExcludedKind(entry);
1745
+ return kind === undefined ? [] : [sensitiveEntry(entry) ? withheldEntry(entry) : { ...entry, excluded: kind }];
1746
+ });
1747
+ const quoteHigh = await quotePathSetting(executable, argv, root, env, budget);
1748
+ const display = (path: string) => stripUrlUserinfo(quoteGitPath(path, quoteHigh));
1749
+ // An excluded entry's old name is left out too (a rename's deletion side), unless a listed file still has that name: a copy's
1750
+ // source (`diff.renames=copies`) keeps its own hunks.
1751
+ const listed = new Set(visible.entries.map(entry => entry.path));
1752
+ const pathspecs = [...new Set(excluded.flatMap(entry => entry.from === undefined || listed.has(entry.from) ? [entry.path] : [entry.from, entry.path]))]
1753
+ .map(path => `:(exclude,literal)${path}`);
1754
+ const argvChars = [...argv, ...pathspecs].reduce((sum, arg) => sum + arg.length + 1, 0);
1755
+ let reason: SummaryReason = "many-excluded";
1756
+ // The argv bound only decides for the excludes added here; a base argv that is too long by itself fails as before.
1757
+ if (pathspecs.length === 0 || (pathspecs.length <= MAX_EXCLUDED_PATHSPECS && argvChars <= MAX_DIFF_ARGV_CHARS)) {
1758
+ const patch = await spawnBounded(executable, [...argv, ...pathspecs], root,
1759
+ { env, signal: budget.signal, timeoutMs: budget.timeoutMs(), maxBytes: DIFF_SUMMARY_THRESHOLD_BYTES });
1760
+ if (!patch.truncated) {
1761
+ if (patch.code !== 0) throw queryFailure("Git inspection failed", patch);
1762
+ const output = filterSensitiveDiff(withWarnings(stripUrlUserinfo(patch.output.toString("utf8")), patch));
1763
+ const minted = await mintedEntries(excluded, visible.entries, minting, run, (list, handles) => excludedListShown(list, display, { handles }));
1764
+ const list = renderExcludedList(minted.entries, display, minted.list);
1765
+ const parts = [output, list, minted.note, note].filter(part => part !== "");
1766
+ return parts.map((part, index) => index < parts.length - 1 && !part.endsWith("\n") ? `${part}\n` : part).join("");
1767
+ }
1768
+ reason = "large";
1769
+ }
1770
+ const sensitive = new Set(sensitiveGitPathspecs());
1771
+ const dash = argv.indexOf("--");
1772
+ const everything = await diffListing(executable, argv.filter((arg, index) => index < dash || !sensitive.has(arg)), root, env, budget);
1773
+ const shown = new Set(visible.entries.map(entry => entry.path));
1774
+ const entries: SummaryEntry[] = everything.entries.map(entry => {
1775
+ if (!shown.has(entry.path) || sensitiveEntry(entry)) return withheldEntry(entry);
1776
+ const kind = entryExcludedKind(entry);
1777
+ return kind === undefined ? entry : { ...entry, excluded: kind };
1778
+ });
1779
+ const warnings = withWarnings("", visible.result);
1780
+ const footer = joinedNotes([warnings, note]);
1781
+ const minted = await mintedEntries(entries, visible.entries, minting, run, (list, handles) => diffSummaryShown(list, display, { reason, footer, handles }));
1782
+ return renderDiffSummary(minted.entries, display, { reason, footer: minted.note === "" ? footer : joinedNotes([warnings, minted.note, note]), ...minted.list });
1783
+ }
1784
+
1785
+ /** The note appended when tracked directories replaced by links were left out of an inspection. */
1786
+ function linkedNote(linked: readonly string[]): string {
1787
+ return linked.length === 0 ? ""
1788
+ : `[router_git] skipped tracked directories replaced by symlinks/junctions: ${linked.slice(0, 20).join(", ")}${linked.length > 20 ? ", ..." : ""}`;
1789
+ }
1790
+
1226
1791
  /**
1227
1792
  * Phase 2.1: `ls-files` with its listing filtered (leases). The listing is read NUL-separated, so a name git would quote is still
1228
1793
  * matched by its real spelling; the filter's `kept` paths are printed one per line, then its note. A `[truncated: …]` marker the
@@ -1328,7 +1893,30 @@ async function verifyRoleRepository(executable: string, base: string[], session:
1328
1893
  }
1329
1894
  }
1330
1895
 
1331
- export async function inspectGit(operation: GitOperation, input: GitInput, directory: string, signal?: AbortSignal, options: GitInspectOptions = {}): Promise<string> {
1896
+ /** An open inspection: what every git call of one tool call shares once its repository is resolved and checked. */
1897
+ interface Inspection {
1898
+ readonly executable: string;
1899
+ /** The user's inherited allowlisted settings (G9). */
1900
+ readonly inherited: readonly string[];
1901
+ /** `-c safe.directory=…` pairs of the user's config. */
1902
+ readonly trusted: readonly string[];
1903
+ /** Hardening plus `trusted`: the prefix of every git argv. */
1904
+ readonly base: string[];
1905
+ readonly env: NodeJS.ProcessEnv;
1906
+ readonly budget: Budget;
1907
+ /** The repository's top level, a real path. */
1908
+ readonly root: string;
1909
+ /** A role work root below the top level (repository-relative, `/`-separated; QA-G-A2-4). */
1910
+ readonly scope?: string;
1911
+ }
1912
+
1913
+ /**
1914
+ * The setup shared by {@link inspectGit} and a handle expansion (#108 slice 3): one tool-call deadline, a git executable outside
1915
+ * the session's tree (G4), the user's inherited settings (G9), discovery bounded by the session's worktree (G11), the top level,
1916
+ * and, for a role work root, its `.git` pointers before anything is spawned and the directories git reports after
1917
+ * (QA-G-A2-2), with the scope of a work root below the top level (QA-G-A2-4).
1918
+ */
1919
+ async function openInspection(directory: string, signal: AbortSignal | undefined, options: GitInspectOptions): Promise<Inspection> {
1332
1920
  // Discovery and inspection share one tool-call deadline, not two 15 s waits (SD-3b-8: with a `root`, resolution shares it too).
1333
1921
  const deadline = performance.now() + (options.deadlineAt === undefined ? DEADLINE_MS : options.deadlineAt - Date.now());
1334
1922
  const budget: Budget = { signal, timeoutMs: () => {
@@ -1336,7 +1924,6 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1336
1924
  if (remaining <= 0) throw new Error("Git inspection timed out");
1337
1925
  return remaining;
1338
1926
  } };
1339
- validateInput(operation, input);
1340
1927
  if (!isDirectory(directory)) throw new Error("Session directory does not exist");
1341
1928
  const session = realpath(directory);
1342
1929
  const boundary = sessionBoundary(session, options.worktree);
@@ -1365,11 +1952,27 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1365
1952
  const below = relative(root, session);
1366
1953
  scope = below === "" ? undefined : below.split(/[\\/]/).join("/");
1367
1954
  }
1368
- const scopeSpec = scope === undefined ? [] : [`:(literal)${scope}`];
1955
+ return { executable, inherited, trusted, base, env, budget, root, ...(scope === undefined ? {} : { scope }) };
1956
+ }
1957
+
1958
+ /**
1959
+ * The `-c` settings of an open inspection, placed after the hardening: the user's trusted `safe.directory` values, the user's
1960
+ * inherited settings the repository does not set itself (G9), and every repository driver program blanked (G1).
1961
+ */
1962
+ async function inspectionConfig(inspection: Inspection): Promise<string[]> {
1963
+ const { executable, root, env, base, budget, trusted, inherited } = inspection;
1369
1964
  const repository = await repositoryConfig(executable, root, env, base, budget);
1370
- const config = [...trusted,
1965
+ return [...trusted,
1371
1966
  ...inherited.filter(pair => !pair.startsWith("safe.directory=") && !repository.overridden.has(pair.slice(0, pair.indexOf("=")))).flatMap(pair => ["-c", pair]),
1372
1967
  ...repository.neutralize];
1968
+ }
1969
+
1970
+ export async function inspectGit(operation: GitOperation, input: GitInput, directory: string, signal?: AbortSignal, options: GitInspectOptions = {}): Promise<string> {
1971
+ validateInput(operation, input);
1972
+ const inspection = await openInspection(directory, signal, options);
1973
+ const { executable, base, env, budget, root, scope } = inspection;
1974
+ const scopeSpec = scope === undefined ? [] : [`:(literal)${scope}`];
1975
+ const config = await inspectionConfig(inspection);
1373
1976
  let linked: string[] = [];
1374
1977
  if (readsWorktree(operation, input)) {
1375
1978
  const index = await spawnBounded(executable, [...base, "ls-files", "-z", "--cached", ...(scope === undefined ? [] : ["--", ...scopeSpec])], root,
@@ -1397,6 +2000,13 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1397
2000
  inspected = { ...input, ref: oid };
1398
2001
  }
1399
2002
  const argv = gitArgv(operation, inspected, root, { config, exclude: linked, ...(scope === undefined ? {} : { scope }) });
2003
+ // #108 (v2 roles mode, role sessions): a patch without `path` lists excluded content and is summarized above 8 KiB.
2004
+ if (operation === "diff" && options.summary === true && input.path === undefined && (input.mode === undefined || input.mode === "patch" || input.mode === "cached")) {
2005
+ // Slice 3: the handles name blobs of this repository, bound to the session and the way the caller reached it.
2006
+ const minting: SummaryMinting | undefined = options.mintHandle === undefined ? undefined
2007
+ : { mint: options.mintHandle, ...(scope === undefined ? {} : { scope }), worktree: readsWorktree(operation, input) };
2008
+ return await summarizedDiff(executable, argv, root, env, budget, linkedNote(linked), minting);
2009
+ }
1400
2010
  const searchFilter = operation === "ls_files" ? options.filterSearch : undefined;
1401
2011
  const raw = searchFilter !== undefined
1402
2012
  ? await filteredListing(executable, argv, root, env, budget, searchFilter)
@@ -1406,7 +2016,7 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1406
2016
  let output = ["show", "diff", "log"].includes(operation) ? filterSensitiveDiff(raw) : raw;
1407
2017
  if (operation === "show" || operation === "log") output = await annotateWithheld(output, executable, base, root, env, budget, scopeSpec);
1408
2018
  if (linked.length === 0) return output;
1409
- return `${output}${output.endsWith("\n") || output === "" ? "" : "\n"}[router_git] skipped tracked directories replaced by symlinks/junctions: ${linked.slice(0, 20).join(", ")}${linked.length > 20 ? ", ..." : ""}`;
2019
+ return `${output}${output.endsWith("\n") || output === "" ? "" : "\n"}${linkedNote(linked)}`;
1410
2020
  }
1411
2021
 
1412
2022
  /**
@@ -1443,6 +2053,21 @@ export interface GitToolsOptions {
1443
2053
  * Only when set do the tools declare `root` and the longer description (SD-3b-1); absent, schema and behaviour are unchanged.
1444
2054
  */
1445
2055
  resolveRoot?: GitRootResolver;
2056
+ /**
2057
+ * #108 slice 1 (OpenCode v2, roles mode at start only): a role session's `router_git_diff` (in its work root or with `root`) is
2058
+ * stat-first, see {@link GitInspectOptions.summary}. Other sessions, and every tool's schema and description, are unchanged.
2059
+ */
2060
+ summarizeDiffs?: boolean;
2061
+ /**
2062
+ * #108 slice 3 (OpenCode v2, roles mode at start only, with `summarizeDiffs`): a role session's diff summary lines carry `gd_`
2063
+ * handles, and `router_git_show` declares `handle`, `lines` and `side` to expand one. Absent: schemas and behaviour unchanged.
2064
+ */
2065
+ handles?: boolean;
2066
+ /**
2067
+ * #108 slice 4 (OpenCode v2, roles mode at start only): `router_git_diff`, `_status`, `_show` and `_log` declare `force`, and a
2068
+ * role session's identical repeated answer becomes a stub (answer-dedup.ts). Absent: schema and behaviour are unchanged.
2069
+ */
2070
+ dedupe?: boolean;
1446
2071
  }
1447
2072
 
1448
2073
  /**
@@ -1534,38 +2159,223 @@ function displayRoot(text: string): string {
1534
2159
  /**
1535
2160
  * 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.
1536
2161
  * `root` is only the git cwd, never a git argument; a refusal or a malformed answer spawns nothing. `filtering` (leases, Phase 2.1)
1537
- * applies to the other repository's listing as to the work root's.
2162
+ * applies to the other repository's listing as to the work root's, and `summary` (#108) to its diff. `settle` (#108 slice 4)
2163
+ * receives every answer it gives, with the other repository's path once `root` resolved to one (undefined before).
2164
+ */
2165
+ type AdmittedRootAnswer = Extract<GitRootAnswer, { inWorkRoot: false }>;
2166
+
2167
+ /**
2168
+ * F2, before anything is spawned: `root` is still the real path the resolver answered (no junction or link swapped in since
2169
+ * resolution), and a main worktree's `.git` is its own git directory (no gitdir file, link or junction naming another
2170
+ * repository): for a main worktree the dispatch check compares `root` with itself. The refusal reason, or undefined when admitted.
2171
+ * Shared by a `root` call and a cross-repo handle expansion (#108 slice 3), which re-resolves its `root` every time.
1538
2172
  */
2173
+ function admittedRoot(value: string, answer: AdmittedRootAnswer): string | undefined {
2174
+ let real: string | undefined;
2175
+ try { real = realpath(answer.root); } catch { real = undefined; }
2176
+ if (real === undefined || foldCase(real) !== foldCase(answer.root)) {
2177
+ return `root=${displayRoot(value)}: ${displayRoot(answer.root)} changed since it was resolved; nothing ran`;
2178
+ }
2179
+ if (sameOnDisk(answer.repository, answer.root)) {
2180
+ const dotGit = join(answer.root, ".git");
2181
+ let own = false;
2182
+ try { const stats = lstatSync(dotGit); own = stats.isDirectory() && !stats.isSymbolicLink(); } catch { own = false; }
2183
+ if (!own) return `root=${displayRoot(value)}: ${displayRoot(dotGit)} is not the repository's own git directory; nothing ran`;
2184
+ }
2185
+ return undefined;
2186
+ }
2187
+
2188
+ /** The inspection options of an admitted `root`: the role hardening against its repository, guards for it and the work root. */
2189
+ function rootInspection(answer: AdmittedRootAnswer, executables: readonly string[], deadlineAt: number): GitInspectOptions {
2190
+ return {
2191
+ executables, guards: [...workRootGuards(answer.root), ...workRootGuards(answer.workRoot)],
2192
+ role: { dispatchRepository: answer.repository }, deadlineAt,
2193
+ };
2194
+ }
2195
+
1539
2196
  async function inspectRoot(operation: GitOperation, input: GitInput, value: unknown, resolveRoot: GitRootResolver,
1540
2197
  executables: readonly string[], sessionID: string, signal: AbortSignal, deadlineAt: number,
1541
- filtering: Pick<GitInspectOptions, "filterSearch"> = {}): Promise<string | undefined> {
1542
- if (typeof value !== "string") return "[router_git] error: refused: root must be a string; nothing ran";
2198
+ filtering: Pick<GitInspectOptions, "filterSearch" | "summary"> = {},
2199
+ mintFor?: (via: HandleVia) => Pick<GitInspectOptions, "mintHandle">,
2200
+ settle?: (root: string | undefined, text: string) => string): Promise<string | undefined> {
2201
+ let resolved: string | undefined;
2202
+ const done = (text: string): string => settle === undefined ? text : settle(resolved, text);
2203
+ if (typeof value !== "string") return done("[router_git] error: refused: root must be a string; nothing ran");
1543
2204
  try {
1544
2205
  const answer = checkGitRootAnswer(await resolveRoot(value, { sessionID, signal, deadlineAt }));
1545
- if (!answer.ok) return `[router_git] error: refused: ${stripUrlUserinfo(answer.reason)}`;
2206
+ if (!answer.ok) return done(`[router_git] error: refused: ${stripUrlUserinfo(answer.reason)}`);
1546
2207
  if (answer.inWorkRoot) return undefined;
1547
- // F2, before anything is spawned: `root` is still the real path the resolver answered (no junction or link swapped in since
1548
- // resolution), and a main worktree's `.git` is its own git directory (no gitdir file, link or junction naming another
1549
- // repository): for a main worktree the dispatch check below compares `root` with itself.
1550
- let real: string | undefined;
1551
- try { real = realpath(answer.root); } catch { real = undefined; }
1552
- if (real === undefined || foldCase(real) !== foldCase(answer.root)) {
1553
- return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(answer.root)} changed since it was resolved; nothing ran`;
1554
- }
1555
- if (sameOnDisk(answer.repository, answer.root)) {
1556
- const dotGit = join(answer.root, ".git");
1557
- let own = false;
1558
- try { const stats = lstatSync(dotGit); own = stats.isDirectory() && !stats.isSymbolicLink(); } catch { own = false; }
1559
- if (!own) return `[router_git] error: refused: root=${displayRoot(value)}: ${displayRoot(dotGit)} is not the repository's own git directory; nothing ran`;
1560
- }
1561
- const output = await inspectGit(operation, input, answer.root, signal, {
1562
- executables, guards: [...workRootGuards(answer.root), ...workRootGuards(answer.workRoot)],
1563
- role: { dispatchRepository: answer.repository }, deadlineAt, ...filtering,
1564
- });
1565
- return `${answer.provenance}\n${output}`;
2208
+ resolved = answer.root;
2209
+ const refusal = admittedRoot(value, answer);
2210
+ if (refusal !== undefined) return done(`[router_git] error: refused: ${refusal}`);
2211
+ const minting = mintFor?.({ kind: "root", value, root: answer.root, repository: answer.repository, workRoot: answer.workRoot }) ?? {};
2212
+ const output = await inspectGit(operation, input, answer.root, signal, { ...rootInspection(answer, executables, deadlineAt), ...filtering, ...minting });
2213
+ return done(`${answer.provenance}\n${output}`);
1566
2214
  } catch (error) {
1567
- return `[router_git] error: root=${displayRoot(value)}: ${stripUrlUserinfo(errorMessage(error))}`;
2215
+ return done(`[router_git] error: root=${displayRoot(value)}: ${stripUrlUserinfo(errorMessage(error))}`);
2216
+ }
2217
+ }
2218
+
2219
+ /** #108 slice 3: the arguments of a handle expansion, taken out before the strict parse (as `root` is). */
2220
+ const HANDLE_ARGS: ReadonlySet<string> = new Set(["handle", "lines", "side"]);
2221
+ const HANDLE_ARG_DESCRIPTION = "A gd_ handle from a router_git_diff summary line (role agents): shows that file version's lines instead of a commit; "
2222
+ + "never combined with path, ref or root";
2223
+ const LINES_ARG_DESCRIPTION = "With handle: \"a\" (from line a) or \"a-b\" (lines a to b), 1-based in that side's numbering; at most 400 lines or 16 KiB per call";
2224
+ const SIDE_ARG_DESCRIPTION = "With handle: the side of the diff to show, new (the default) or old (the default for a deleted file)";
2225
+
2226
+ /** A refusal decided before any git ran. */
2227
+ function refusedBeforeGit(reason: string): string { return `[router_git] error: refused: ${reason}; nothing ran`; }
2228
+ /**
2229
+ * A path as an expansion shows it: git's C-style quoting with the repository's `core.quotePath` (`quoteHigh`, as the summary
2230
+ * shows it; git's default, true, for a refusal decided before git runs), credentials redacted.
2231
+ */
2232
+ function expansionPath(path: string, quoteHigh = true): string { return stripUrlUserinfo(quoteGitPath(path, quoteHigh)); }
2233
+
2234
+ /**
2235
+ * #108 slice 3: `router_git_show({ handle, lines?, side? })`, for a role session whose `router_git_diff` summary listed the handle.
2236
+ * The handle is looked up by the host's session id; its repository is re-resolved and compared every time (the bound work root
2237
+ * as recorded, or `root` resolved again with the same admission checks); the inspection is opened as any other (G4, hardening,
2238
+ * ceiling, QA-G-A2-2) and its top level and scope must be the recorded ones; both names are checked for sensitivity again. Only
2239
+ * the stored, validated blob id reaches git (`cat-file -t`, `-s`, `blob`): no argument of the call does.
2240
+ */
2241
+ async function expandHandle(input: Record<string, unknown>, sessionID: string, signal: AbortSignal, opts: GitToolsOptions,
2242
+ executables: readonly string[]): Promise<string> {
2243
+ const { handle, lines, side, ...rest } = input;
2244
+ if (handle === undefined) return refusedBeforeGit("lines and side need a handle");
2245
+ const answer: WorkRootAnswer = opts.resolveWorkRoot === undefined ? { role: false } : checkWorkRootAnswer(opts.resolveWorkRoot(sessionID));
2246
+ if (!answer.role) return refusedBeforeGit("handle is for role agents in roles mode; pass ref (and path) instead");
2247
+ if (answer.root === null) return "[router_git] error: refused: this role session has no bound work root (I9)";
2248
+ if (Object.values(rest).some(value => value !== undefined)) {
2249
+ return refusedBeforeGit("handle cannot be combined with ref, path or root (the handle names its file version and repository)");
2250
+ }
2251
+ if (typeof handle !== "string" || !HANDLE_RE.test(handle)) return refusedBeforeGit("handle must be gd_ followed by 10 lowercase hex characters");
2252
+ const range = typeof lines === "string" ? parseLineRange(lines) : undefined;
2253
+ if (lines !== undefined && range === undefined) return refusedBeforeGit("lines must be \"a\" or \"a-b\" with 1 <= a <= b");
2254
+ const askedSide = side === "new" || side === "old" ? side : undefined;
2255
+ if (side !== undefined && askedSide === undefined) return refusedBeforeGit("side must be \"new\" or \"old\"");
2256
+ const entry = lookupHandle(sessionID, handle);
2257
+ if (entry === undefined) {
2258
+ return refusedBeforeGit(`unknown handle ${handle} for this session (a handle belongs to the session whose router_git_diff summary listed it, `
2259
+ + "and lasts 2 hours after its last use, at most 1024 per session); call router_git_diff again, then expand with an explicit lines range "
2260
+ + "other than this call's");
2261
+ }
2262
+ const elsewhere = (what: "work root" | "repository") => `${handle} was listed in another ${what} than this session's current one; call router_git_diff again`;
2263
+ // The repository, re-resolved and compared every time.
2264
+ const deadlineAt = Date.now() + DEADLINE_MS;
2265
+ let directory: string;
2266
+ let options: GitInspectOptions;
2267
+ let provenance: string | undefined;
2268
+ if (entry.via.kind === "workRoot") {
2269
+ if (foldCase(answer.root) !== foldCase(entry.via.workRoot)) return refusedBeforeGit(elsewhere("work root"));
2270
+ const expected = answer.repository ?? opts.dispatchRepository;
2271
+ directory = answer.root;
2272
+ options = { executables, guards: workRootGuards(answer.root), role: expected ? { dispatchRepository: expected } : {}, deadlineAt };
2273
+ } else {
2274
+ if (opts.resolveRoot === undefined) return refusedBeforeGit(elsewhere("repository"));
2275
+ const value = entry.via.value;
2276
+ const resolved = checkGitRootAnswer(await opts.resolveRoot(value, { sessionID, signal, deadlineAt }));
2277
+ if (!resolved.ok) return `[router_git] error: refused: ${handle}: ${stripUrlUserinfo(resolved.reason)}`;
2278
+ if (resolved.inWorkRoot || foldCase(resolved.root) !== foldCase(entry.via.root) || foldCase(resolved.repository) !== foldCase(entry.via.repository)
2279
+ || foldCase(resolved.workRoot) !== foldCase(entry.via.workRoot)) {
2280
+ return refusedBeforeGit(elsewhere("repository"));
2281
+ }
2282
+ const refusal = admittedRoot(value, resolved);
2283
+ if (refusal !== undefined) return `[router_git] error: refused: ${handle}: ${refusal}`;
2284
+ directory = resolved.root;
2285
+ provenance = resolved.provenance;
2286
+ options = rootInspection(resolved, executables, deadlineAt);
2287
+ }
2288
+ // Both names, checked again; then the side.
2289
+ if ([entry.old?.path, entry.new?.path].some(path => path !== undefined && isSensitivePath(path))) {
2290
+ return refusedBeforeGit(`${handle} names a sensitive file; use read (asks for approval)`);
1568
2291
  }
2292
+ const chosenSide: "new" | "old" = askedSide ?? (entry.status === "D" ? "old" : "new");
2293
+ const chosen = chosenSide === "old" ? entry.old : entry.new;
2294
+ const shown = expansionPath(chosen?.path ?? entry.new?.path ?? entry.old?.path ?? "");
2295
+ switch (sideProblem(entry, chosenSide)) {
2296
+ case "absent":
2297
+ return refusedBeforeGit(chosenSide === "old" ? `${handle}: ${shown} was added; it has no old side` : `${handle}: ${shown} was deleted; it has no new side (use side old)`);
2298
+ case "worktree":
2299
+ return refusedBeforeGit(`${handle}: the new side of ${shown} is the working tree, which router_git_show does not read; use read with offset/limit `
2300
+ + "(same line numbers), or side old");
2301
+ case "binary": return refusedBeforeGit(`${handle}: ${shown} is binary on that side; no lines to show`);
2302
+ case "symlink": return refusedBeforeGit(`${handle}: ${shown} is a symlink on that side; no lines to show`);
2303
+ case "submodule": return refusedBeforeGit(`${handle}: ${shown} is a submodule on that side; no lines to show`);
2304
+ case "not-a-file": return refusedBeforeGit(`${handle}: ${shown} is not a file on that side; no lines to show`);
2305
+ case undefined: break;
2306
+ }
2307
+ const oid = chosen?.oid;
2308
+ if (chosen === undefined || !isBlobId(oid)) return refusedBeforeGit(`${handle}: ${shown} has no blob on that side; no lines to show`);
2309
+ const inspection = await openInspection(directory, signal, options);
2310
+ const refused = (reason: string) => `[router_git] error: refused: ${reason}`;
2311
+ if (foldCase(inspection.root) !== foldCase(entry.toplevel) || foldCase(inspection.scope ?? "") !== foldCase(entry.scope ?? "")
2312
+ || (inspection.scope !== undefined && !withinScope(chosen.path, inspection.scope))) {
2313
+ return refused(elsewhere(entry.via.kind === "workRoot" ? "work root" : "repository"));
2314
+ }
2315
+ const { executable, base, root, env, budget } = inspection;
2316
+ // From here the path is shown as the summary showed it: with the repository's core.quotePath, read with the same settings.
2317
+ const quoteHigh = await quotePathOf(executable, [...hardeningArgs(), ...await inspectionConfig(inspection)], root, env, budget);
2318
+ const path = expansionPath(chosen.path, quoteHigh);
2319
+ const gone = refused(`${handle}: that version of ${path} is no longer in the repository; call router_git_diff again`);
2320
+ const tooLarge = refused(`${handle}: that version of ${path} is larger than ${MAX_BLOB_BYTES / (1024 * 1024)} MiB`);
2321
+ const type = await query(executable, [...base, "cat-file", "-t", oid], root, env, budget);
2322
+ if (type.code !== 0 || type.output.toString("utf8").trim() !== "blob") return gone;
2323
+ const sized = await query(executable, [...base, "cat-file", "-s", oid], root, env, budget);
2324
+ const size = Number(sized.output.toString("utf8").trim());
2325
+ if (sized.code !== 0 || !Number.isSafeInteger(size)) return gone;
2326
+ if (size > MAX_BLOB_BYTES) return tooLarge;
2327
+ const blob = await spawnBounded(executable, [...base, "cat-file", "blob", oid], root,
2328
+ { env, signal: budget.signal, timeoutMs: budget.timeoutMs(), maxBytes: MAX_BLOB_BYTES });
2329
+ if (blob.truncated) return tooLarge;
2330
+ if (blob.code !== 0) throw queryFailure("Git inspection failed", blob);
2331
+ // git's own test (a NUL in the first 8000 bytes): no lines of a binary blob.
2332
+ if (blob.output.subarray(0, 8000).includes(0)) return refused(`${handle}: ${path} is binary on that side; no lines to show`);
2333
+ const rendered = renderExpansion({
2334
+ handle, side: chosenSide, path, oid, text: blob.output.toString("utf8"), ...(range === undefined ? {} : { range }), redact: stripUrlUserinfo,
2335
+ });
2336
+ if (!rendered.ok) return refused(rendered.reason);
2337
+ return provenance === undefined ? rendered.text : `${provenance}\n${rendered.text}`;
2338
+ }
2339
+
2340
+ /** #108 slice 4: the operations whose answers are deduplicated (`blame` and `ls_files` are not). */
2341
+ const DEDUPED_OPERATIONS: ReadonlySet<GitOperation> = new Set(["status", "log", "diff", "show"]);
2342
+
2343
+ /** #108 slice 4: `force` taken out of a call before the strict parse; anything but a boolean is refused. */
2344
+ function takeForce(input: unknown): { args: unknown; force: boolean } {
2345
+ if (typeof input !== "object" || input === null || !("force" in input)) return { args: input, force: false };
2346
+ const { force, ...rest } = input as { force?: unknown };
2347
+ if (force !== undefined && typeof force !== "boolean") throw new Error("force must be true or false");
2348
+ return { args: rest, force: force === true };
2349
+ }
2350
+
2351
+ /** #108 slice 4: git's defaults for the dedup key, so `{}` and `{ mode: "patch" }` are the same call. */
2352
+ const GIT_KEY_DEFAULTS: Partial<Record<GitOperation, Readonly<Record<string, unknown>>>> = { diff: { mode: "patch" }, log: { limit: 20 }, show: { ref: "HEAD" } };
2353
+
2354
+ /**
2355
+ * #108 slice 4: a role session's answer through the dedup store (answer-dedup.ts). An answer given after the call was aborted
2356
+ * may never reach the model: it is not stored.
2357
+ */
2358
+ function dedupedGitAnswer(operation: GitOperation, key: AnswerKey, force: boolean, text: string, signal: AbortSignal | undefined): string {
2359
+ return dedupeAnswer(key, text, { force, stub: bytes => gitUnchangedStub(`router_git_${operation}`, bytes), aborted: signal?.aborted === true });
2360
+ }
2361
+
2362
+ /**
2363
+ * #108 slice 4: a call's dedup key: the parsed arguments with git's defaults filled in ({@link canonicalArgs}); `via` tells the
2364
+ * work root from a `root`, `root` is the inspected directory's real path.
2365
+ */
2366
+ function gitAnswerKey(operation: GitOperation, sessionID: string, via: unknown, root: string, input: GitInput): AnswerKey {
2367
+ let real = root;
2368
+ try { real = realpath(root); } catch { /* the inspection reports a missing directory */ }
2369
+ return { sessionID, tool: `router_git_${operation}`, via, root: real, args: canonicalArgs(input, GIT_KEY_DEFAULTS[operation]) };
2370
+ }
2371
+
2372
+ /**
2373
+ * #108 slice 4: a handle expansion's dedup key: its own arguments (`handle`, `lines`, `side`, and anything else given, which
2374
+ * makes it a refusal), without git's defaults. The handle names the repository and the file version (an HMAC over both, per
2375
+ * session), so no root is part of the key: a different handle, range or side is a different answer.
2376
+ */
2377
+ function expansionAnswerKey(sessionID: string, args: Record<string, unknown>): AnswerKey {
2378
+ return { sessionID, tool: "router_git_show", via: { kind: "handle" }, root: "", args: canonicalArgs(args) };
1569
2379
  }
1570
2380
 
1571
2381
  export function gitTools(opts: GitToolsOptions = {}) {
@@ -1586,43 +2396,90 @@ export function gitTools(opts: GitToolsOptions = {}) {
1586
2396
  ...(operation === "log" ? { limit: tool.schema.number().int().min(1).max(50).optional() } : {}),
1587
2397
  ...(operation === "diff" ? { mode: tool.schema.enum(["patch", "stat", "name-only", "cached"]).optional() } : {}),
1588
2398
  ...(resolveRoot === undefined ? {} : { root: tool.schema.string().optional().describe(GIT_ROOT_ARG_DESCRIPTION) }),
2399
+ // #108 slice 3: declared only in roles mode at start (OpenCode v2); v1 and tiers mode keep today's schema.
2400
+ ...(operation === "show" && opts.handles === true ? {
2401
+ handle: tool.schema.string().optional().describe(HANDLE_ARG_DESCRIPTION),
2402
+ lines: tool.schema.string().optional().describe(LINES_ARG_DESCRIPTION),
2403
+ side: tool.schema.enum(["new", "old"]).optional().describe(SIDE_ARG_DESCRIPTION),
2404
+ } : {}),
2405
+ // #108 slice 4: likewise roles mode at start only.
2406
+ ...(opts.dedupe === true && DEDUPED_OPERATIONS.has(operation) ? { force: tool.schema.boolean().optional().describe(FORCE_ARG_DESCRIPTION) } : {}),
1589
2407
  },
1590
2408
  async execute(input, context) {
2409
+ // #108 slice 4: the work-root call's dedup key, once known; an error answer forgets it. A refusal before it is known forgets
2410
+ // the session's entries of this tool (`unkeyed`).
2411
+ const dedupe = opts.dedupe === true && DEDUPED_OPERATIONS.has(operation);
2412
+ let dedupKey: AnswerKey | undefined;
2413
+ const unkeyed = (text: string): string => {
2414
+ if (dedupe) forgetToolAnswers(context.sessionID, `router_git_${operation}`);
2415
+ return text;
2416
+ };
1591
2417
  try {
2418
+ // #108 slice 4: `force` (declared in roles mode only) is stripped first, before the expansion and `root` checks and the
2419
+ // strict parse; elsewhere it is refused by the strict parse.
2420
+ const { args: unforced, force } = dedupe ? takeForce(input) : { args: input as unknown, force: false };
2421
+ // #108 slice 3: `handle`, `lines` and `side` are stripped before the strict parse; any of them makes the call an expansion.
2422
+ let source: unknown = unforced;
2423
+ if (operation === "show" && opts.handles === true && typeof unforced === "object" && unforced !== null) {
2424
+ const record = unforced as Record<string, unknown>;
2425
+ if ([...HANDLE_ARGS].some(key => record[key] !== undefined)) {
2426
+ // #108 slice 4: an expansion is deduplicated by its handle, lines and side.
2427
+ if (dedupe) dedupKey = expansionAnswerKey(context.sessionID, record);
2428
+ const text = await expandHandle(record, context.sessionID, context.abort, opts, executables);
2429
+ return dedupKey === undefined ? text : dedupedGitAnswer(operation, dedupKey, force, text, context.abort);
2430
+ }
2431
+ source = Object.fromEntries(Object.entries(record).filter(([key]) => !HANDLE_ARGS.has(key)));
2432
+ }
1592
2433
  const searchFilter = installedSearchFilter;
1593
2434
  const filtering: Pick<GitInspectOptions, "filterSearch"> = searchFilter === undefined ? {}
1594
2435
  : { filterSearch: (root, paths) => searchFilter({ sessionID: context.sessionID, root, paths }) };
2436
+ // #108: role sessions only (a `root` is only ever admitted for one; the work-root branch below checks the binding).
2437
+ const roleShaping: Pick<GitInspectOptions, "filterSearch" | "summary"> = opts.summarizeDiffs === true ? { ...filtering, summary: true } : filtering;
2438
+ // #108 slice 3: a role session's diff summary mints handles bound to the host's session id and the way it reached the repository.
2439
+ const mintFor = (via: HandleVia): Pick<GitInspectOptions, "mintHandle"> => operation === "diff" && opts.handles === true && opts.summarizeDiffs === true
2440
+ ? { mintHandle: target => mintHandle({ ...target, sessionID: context.sessionID, via }) } : {};
1595
2441
  // 3b.3: `root` is stripped before the strict parse; without a resolver the input is parsed as given (unchanged, I9).
1596
- let args: unknown = input;
2442
+ let args: unknown = source;
1597
2443
  let deadline: { deadlineAt?: number } = {};
1598
- if (resolveRoot !== undefined && typeof input === "object" && input !== null && "root" in input) {
1599
- const { root, ...rest } = input as GitInput & { root?: unknown };
2444
+ if (resolveRoot !== undefined && typeof source === "object" && source !== null && "root" in source) {
2445
+ const { root, ...rest } = source as GitInput & { root?: unknown };
1600
2446
  args = rest;
1601
2447
  if (root !== undefined) {
1602
2448
  // SD-3b-8: one 15 s deadline covers resolution and inspection.
1603
2449
  const deadlineAt = Date.now() + DEADLINE_MS;
1604
2450
  deadline = { deadlineAt };
1605
- const other = await inspectRoot(operation, inputSchema.parse(rest), root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt, filtering);
2451
+ const parsed = inputSchema.parse(rest);
2452
+ const other = await inspectRoot(operation, parsed, root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt,
2453
+ roleShaping, mintFor,
2454
+ dedupe ? (resolved, text) => resolved === undefined ? unkeyed(text)
2455
+ : dedupedGitAnswer(operation, gitAnswerKey(operation, context.sessionID, { kind: "root", value: root }, resolved, parsed), force, text, context.abort)
2456
+ : undefined);
1606
2457
  if (other !== undefined) return other;
1607
2458
  }
1608
2459
  }
1609
2460
  if (opts.resolveWorkRoot) {
1610
2461
  const answer = checkWorkRootAnswer(opts.resolveWorkRoot(context.sessionID));
1611
2462
  if (answer.role) {
1612
- if (answer.root === null) return "[router_git] error: refused: this role session has no bound work root (I9)";
2463
+ if (answer.root === null) return unkeyed("[router_git] error: refused: this role session has no bound work root (I9)");
1613
2464
  // Cross-repo (P1.5): a binding's repository is the expected one; without it, the plugin's directory.
1614
2465
  const expected = answer.repository ?? opts.dispatchRepository;
1615
- return await inspectGit(operation, inputSchema.parse(args), answer.root, context.abort, {
2466
+ const parsed = inputSchema.parse(args);
2467
+ if (dedupe) dedupKey = gitAnswerKey(operation, context.sessionID, { kind: "workRoot" }, answer.root, parsed);
2468
+ const text = await inspectGit(operation, parsed, answer.root, context.abort, {
1616
2469
  executables, guards: workRootGuards(answer.root),
1617
2470
  role: expected ? { dispatchRepository: expected } : {}, ...deadline,
1618
- ...filtering,
2471
+ ...roleShaping, ...mintFor({ kind: "workRoot", workRoot: answer.root }),
1619
2472
  });
2473
+ return dedupKey === undefined ? text : dedupedGitAnswer(operation, dedupKey, force, text, context.abort);
1620
2474
  }
1621
2475
  }
1622
2476
  return await inspectGit(operation, inputSchema.parse(args), context.directory, context.abort, { worktree: context.worktree, executables, ...deadline, ...filtering });
1623
2477
  } catch (error) {
1624
2478
  // G12: report, never throw into the session; messages are credential-redacted.
1625
- return `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;
2479
+ const text = `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;
2480
+ if (dedupKey === undefined) return unkeyed(text);
2481
+ forgetAnswer(dedupKey);
2482
+ return text;
1626
2483
  }
1627
2484
  },
1628
2485
  })]));