opencode-model-router 2.9.1 → 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 (59) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +4 -2
  3. package/package.json +12 -5
  4. package/src/compat/background.ts +56 -19
  5. package/src/compat/child-history.ts +134 -0
  6. package/src/compat/child-report.ts +185 -0
  7. package/src/compat/child-session.ts +10 -0
  8. package/src/compat/session-lookup.ts +21 -0
  9. package/src/compat/v2-client.ts +124 -6
  10. package/src/compat/v2-hooks.ts +525 -203
  11. package/src/compat/v2-observations.ts +1 -0
  12. package/src/compat/v2-vocabulary.ts +14 -0
  13. package/src/executor/create.ts +47 -28
  14. package/src/executor/git.ts +226 -30
  15. package/src/executor/integrate/checks.ts +29 -11
  16. package/src/executor/integrate/land.ts +32 -2
  17. package/src/executor/integrate/queue.ts +95 -13
  18. package/src/executor/ledger.ts +16 -12
  19. package/src/executor/lfs-restore.ts +492 -0
  20. package/src/executor/paths.ts +7 -2
  21. package/src/executor/recovery.ts +2 -1
  22. package/src/executor/runtime.ts +1062 -243
  23. package/src/executor/slots/pool.ts +120 -19
  24. package/src/executor/slots/provision.ts +111 -23
  25. package/src/executor/slots/root.ts +81 -0
  26. package/src/executor/types.ts +28 -2
  27. package/src/executor/unattended.ts +6 -1
  28. package/src/executor/verify-trees.ts +507 -0
  29. package/src/guard/enforce.ts +2 -1
  30. package/src/guard/fingerprint.ts +9 -0
  31. package/src/guard/guards.ts +7 -1
  32. package/src/index.ts +191 -31
  33. package/src/router/answer-dedup.ts +198 -0
  34. package/src/router/common-dir.ts +241 -0
  35. package/src/router/config.ts +228 -40
  36. package/src/router/diff-handles.ts +322 -0
  37. package/src/router/diff-summary.ts +318 -0
  38. package/src/router/git-metadata-guard.ts +317 -0
  39. package/src/router/git-tools.ts +1136 -49
  40. package/src/router/read-only.ts +37 -13
  41. package/src/router/role-agents.ts +100 -36
  42. package/src/router/run-summary.ts +253 -0
  43. package/src/router/run-tools.ts +177 -25
  44. package/src/router/sessions.ts +23 -1
  45. package/src/router/tool-paths.ts +62 -4
  46. package/src/routing/classify/rules.ts +93 -14
  47. package/src/routing/roles/read-set.ts +10 -1
  48. package/src/routing/roles/work-root.ts +20 -3
  49. package/src/routing/wire/hint.ts +9 -2
  50. package/src/v2.ts +3 -1
  51. package/src/verify/exec.ts +454 -2
  52. package/src/verify/head.ts +6 -1
  53. package/src/verify/pending.ts +14 -1
  54. package/src/verify/plan-task.ts +86 -26
  55. package/src/verify/reference.ts +60 -7
  56. package/src/verify/runner.ts +14 -6
  57. package/src/verify/tree.ts +34 -10
  58. package/src/verify/types.ts +44 -0
  59. package/src/verify/wiring.ts +134 -22
@@ -0,0 +1,198 @@
1
+ /**
2
+ * #108 slice 4 (OpenCode v2 roles mode, role sessions only): an identical repeated answer is replaced by a short stub.
3
+ *
4
+ * `router_git_diff`, `router_git_status`, `router_git_show`, `router_git_log` and `router_run` remember, per call key, the
5
+ * SHA-256 and byte length of the last answer they gave in full. When the same key gets the same answer again, the tool returns
6
+ * a stub naming the earlier call instead; `force: true` returns the full answer (byte-identical) and stores it again.
7
+ *
8
+ * - Key: the session, the tool, how the repository was reached (`via`), the resolved root's real path and the call's canonical
9
+ * arguments ({@link canonicalArgs}: without `force`, defaults filled in). Stored as the SHA-256 of that text.
10
+ * - Only a successful answer above {@link DEDUP_MIN_BYTES} bytes is stored or stubbed. Any other answer for the key (an error,
11
+ * one at most that long, or one given while the call was aborted) forgets the key, so a stub always names the answer the
12
+ * previous identical call returned. A refusal before the key is known forgets the session's entries of that tool.
13
+ * - Window: a stub is given only while fewer than {@link ANSWER_WINDOW_CALLS} tool calls of the session have completed since the
14
+ * full answer was given ({@link noteToolCall}); later the answer is given in full again (the host may have pruned the old one).
15
+ * A stub does not renew the window. Entries also go on compaction (the v2 compaction hook and `session.compaction.ended`), on
16
+ * a revert ({@link ANSWER_FORGET_EVENTS}) and on `session.deleted`; a resume keeps them. Banners the router appends after the
17
+ * tool ran (cap banner, lease run note) are never part of the comparison.
18
+ * - Off for the whole process once {@link disableAnswerDedup} ran (the compaction hook could not be registered).
19
+ *
20
+ * MODULE (process) scope, like the dispatch-facts registry (sessions.ts): the host may deliver a session's events to the
21
+ * plugin instance of every live location, so every instance must see the same entries. Bounded: the least recently used key
22
+ * goes first, at most {@link MAX_ANSWERS_PER_SESSION} per session and {@link MAX_ANSWERS} overall.
23
+ */
24
+ import { createHash } from "node:crypto";
25
+
26
+ /** Answers of at most this many bytes are always given in full (a stub would save little). */
27
+ export const DEDUP_MIN_BYTES = 512;
28
+ export const MAX_ANSWERS_PER_SESSION = 128;
29
+ export const MAX_ANSWERS = 4096;
30
+ /** A stored answer may be stubbed while fewer than this many tool calls of its session have completed since it was given. */
31
+ export const ANSWER_WINDOW_CALLS = 20;
32
+ /** OpenCode v2 events after which a session's answers are forgotten: a revert removes them, a compaction summarizes them. */
33
+ export const ANSWER_FORGET_EVENTS: ReadonlySet<string> = new Set([
34
+ "session.revert.staged", "session.revert.committed", "session.revert.cleared", "session.compaction.ended",
35
+ ]);
36
+ /** The `force` argument's description (the tools' own descriptions do not change). */
37
+ export const FORCE_ARG_DESCRIPTION = "Return the full answer even when it is identical to your previous identical call";
38
+ /** The stub of a `router_run` whose output is unchanged; it follows the run's own status line. */
39
+ export const RUN_UNCHANGED_NOTE = "[router_run] unchanged: the output is exactly that of your previous identical run in this session. Pass force: true to see it again.";
40
+
41
+ /** One call's identity. `via` and `args` must be JSON-serialisable; build `args` with {@link canonicalArgs}. */
42
+ export interface AnswerKey {
43
+ readonly sessionID: string;
44
+ readonly tool: string;
45
+ readonly via: unknown;
46
+ /** The real path of the directory the call inspected or ran in. */
47
+ readonly root: string;
48
+ readonly args: unknown;
49
+ }
50
+
51
+ interface Stored {
52
+ readonly digest: string;
53
+ readonly bytes: number;
54
+ readonly tool: string;
55
+ /** The session's completed-call count when the answer was given in full. */
56
+ readonly at: number;
57
+ }
58
+ interface SessionAnswers {
59
+ /** Tool calls of the session completed while it had entries. */
60
+ calls: number;
61
+ /** Its entries by key digest, least recently used first. */
62
+ readonly entries: Map<string, Stored>;
63
+ }
64
+
65
+ /** Every entry's key digest, least recently used first (Map insertion order); the value is the entry's session. */
66
+ const order = new Map<string, string>();
67
+ const bySession = new Map<string, SessionAnswers>();
68
+ let disabled = false;
69
+
70
+ const ERROR_ANSWER = /^\[[a-z_]+\] error:/;
71
+
72
+ const sha256 = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex");
73
+
74
+ function keyId(key: AnswerKey): string {
75
+ return sha256(JSON.stringify([key.sessionID, key.tool, key.via, key.root, key.args]));
76
+ }
77
+
78
+ function drop(id: string): void {
79
+ const session = order.get(id);
80
+ if (session === undefined) return;
81
+ order.delete(id);
82
+ const answers = bySession.get(session);
83
+ answers?.entries.delete(id);
84
+ if (answers !== undefined && answers.entries.size === 0) bySession.delete(session);
85
+ }
86
+
87
+ function store(sessionID: string, id: string, value: Omit<Stored, "at">, at?: number): void {
88
+ let answers = bySession.get(sessionID);
89
+ if (answers === undefined) bySession.set(sessionID, answers = { calls: 0, entries: new Map() });
90
+ // Re-inserted as the most recently used; the session (and its call count) stays, even when this was its only entry.
91
+ answers.entries.delete(id);
92
+ order.delete(id);
93
+ answers.entries.set(id, { ...value, at: at ?? answers.calls });
94
+ order.set(id, sessionID);
95
+ while (answers.entries.size > MAX_ANSWERS_PER_SESSION) drop(answers.entries.keys().next().value as string);
96
+ while (order.size > MAX_ANSWERS) drop(order.keys().next().value as string);
97
+ }
98
+
99
+ /** A key's canonical form of nested values: object keys sorted at every depth, undefined members dropped, arrays in order. */
100
+ function sortedValue(value: unknown): unknown {
101
+ if (Array.isArray(value)) return value.map(sortedValue);
102
+ if (value === null || typeof value !== "object") return value;
103
+ return Object.fromEntries(Object.entries(value).filter(([, member]) => member !== undefined)
104
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([name, member]) => [name, sortedValue(member)]));
105
+ }
106
+
107
+ /**
108
+ * A call's arguments for its key: the parsed arguments without `force` (and the names in `omit`), undefined values dropped,
109
+ * `defaults` filled in for absent ones, keys sorted at every depth. A new argument is part of the key without listing it here.
110
+ */
111
+ export function canonicalArgs(args: object, defaults: Readonly<Record<string, unknown>> = {}, omit: readonly string[] = []): Record<string, unknown> {
112
+ const merged: Record<string, unknown> = { ...defaults };
113
+ for (const [name, value] of Object.entries(args)) if (value !== undefined && name !== "force" && !omit.includes(name)) merged[name] = value;
114
+ return sortedValue(merged) as Record<string, unknown>;
115
+ }
116
+
117
+ /**
118
+ * The answer to give for `key`: `stub(bytes)` when `compared` (default `answer`) equals the last answer given in full for the key,
119
+ * within the window, and `force` is not set; else `answer`, stored when it qualifies (successful, more than
120
+ * {@link DEDUP_MIN_BYTES} bytes, the call not `aborted`) and otherwise forgetting the key. `bytes` is the UTF-8 length of `compared`.
121
+ */
122
+ export function dedupeAnswer(key: AnswerKey, answer: string,
123
+ options: { force: boolean; stub: (bytes: number) => string; compared?: string; aborted?: boolean }): string {
124
+ if (disabled) return answer;
125
+ const compared = options.compared ?? answer;
126
+ const id = keyId(key);
127
+ const bytes = Buffer.byteLength(compared);
128
+ if (options.aborted === true || ERROR_ANSWER.test(answer) || bytes <= DEDUP_MIN_BYTES) {
129
+ drop(id);
130
+ return answer;
131
+ }
132
+ const digest = sha256(compared);
133
+ const answers = bySession.get(key.sessionID);
134
+ const previous = answers?.entries.get(id);
135
+ const named = answers !== undefined && previous !== undefined && !options.force && previous.digest === digest && previous.bytes === bytes
136
+ && answers.calls - previous.at < ANSWER_WINDOW_CALLS ? previous : undefined;
137
+ // A stub keeps the window of the full answer it names; a full answer starts a new one.
138
+ store(key.sessionID, id, { digest, bytes, tool: key.tool }, named?.at);
139
+ return named === undefined ? answer : options.stub(bytes);
140
+ }
141
+
142
+ /** Forget one key (its call failed, or was aborted, before an answer could be compared). */
143
+ export function forgetAnswer(key: AnswerKey): void {
144
+ drop(keyId(key));
145
+ }
146
+
147
+ /** Forget a session's entries of one tool (a refusal before the call's key was known; at most 128 entries are looked at). */
148
+ export function forgetToolAnswers(sessionID: string, tool: string): void {
149
+ const answers = bySession.get(sessionID);
150
+ if (answers === undefined) return;
151
+ for (const [id, stored] of [...answers.entries]) if (stored.tool === tool) drop(id);
152
+ }
153
+
154
+ /** Forget every answer of a session (compaction, revert, `session.deleted`). */
155
+ export function forgetAnswers(sessionID: string): void {
156
+ const answers = bySession.get(sessionID);
157
+ if (answers === undefined) return;
158
+ for (const id of [...answers.entries.keys()]) drop(id);
159
+ }
160
+
161
+ /** One completed tool call of `sessionID` (any tool): moves the window of its stored answers. A no-op for a session without any. */
162
+ export function noteToolCall(sessionID: string): void {
163
+ const answers = bySession.get(sessionID);
164
+ if (answers !== undefined) answers.calls += 1;
165
+ }
166
+
167
+ /** Turn dedup off for the process and drop every entry. True the first time only (log once). */
168
+ export function disableAnswerDedup(): boolean {
169
+ const first = !disabled;
170
+ disabled = true;
171
+ order.clear();
172
+ bySession.clear();
173
+ return first;
174
+ }
175
+
176
+ /** Tests: dedup on again, no entries. */
177
+ export function resetAnswerDedupForTests(): void {
178
+ disabled = false;
179
+ order.clear();
180
+ bySession.clear();
181
+ }
182
+
183
+ /** How many answers are stored: for one session, or overall (tests, diagnostics). */
184
+ export function storedAnswerCount(sessionID?: string): number {
185
+ return sessionID === undefined ? order.size : bySession.get(sessionID)?.entries.size ?? 0;
186
+ }
187
+
188
+ /** The stub of a `router_git_*` call whose answer is unchanged. */
189
+ export function gitUnchangedStub(tool: string, bytes: number): string {
190
+ return `[router_git] unchanged: this ${tool} call returns exactly the answer of your previous identical call in this session (${bytes} bytes). Pass force: true to get it again.`;
191
+ }
192
+
193
+ /** A `router_run` answer as compared: its first line (the status line) without `; duration <x>`. */
194
+ export function withoutRunDuration(answer: string): string {
195
+ const end = answer.indexOf("\n");
196
+ const first = end === -1 ? answer : answer.slice(0, end);
197
+ return `${first.replace(/; duration [^;\n]*$/, "")}${end === -1 ? "" : answer.slice(end)}`;
198
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * #192, QA-62C-15 (OpenCode v2 roles mode only): the git common directory of the repository holding a directory, found on
3
+ * disk without running git. Role agent registration denies `<git common dir>/omr-executor` with it where git cannot be
4
+ * asked: off Windows, where the plan executor does not run but a Windows host sharing the repository (WSL) may, and off
5
+ * Windows where git reports no repository although one exists (Linux git cannot read a Git for Windows worktree whose `.git`
6
+ * names `gitdir: D:/…`).
7
+ *
8
+ * The walk follows git's discovery order: at each level a `.git` entry, then a bare repository (git's shape,
9
+ * {@link bareShaped}, with a `HEAD` git accepts), then the parent directory. A `.git` directory is the git directory; a
10
+ * `.git` file names it on a `gitdir:` line. The common directory is what the git directory's `commondir` names, else the
11
+ * git directory itself. A checkout's `.git` ends the walk; a bare repository does not: its shape can be committed to a
12
+ * checkout (a `.git` entry cannot), so the walk goes on to the enclosing repository and every common directory found is
13
+ * returned (an extra deny is harmless). Pointers are read as `gitPointers` (router/git-tools.ts) reads them: `.git`,
14
+ * `commondir` and `HEAD` at most 4 KiB, regular files only, opened non-blocking; a `.git` that is a link and a pointer
15
+ * naming a network or device path are refused before any filesystem call reaches them. Off win32 a pointer naming a
16
+ * Windows drive path (`D:/…`, `D:\…`) is read under WSL at the drive's automount path (`<root>/<drive>/<rest>`, the root
17
+ * from `/etc/wsl.conf` `[automount] root`, default `/mnt/`), which must exist; a realpath naming a network or device path
18
+ * (`//host/…`) is refused, but a network drive Windows mounts there (`/mnt/z`) is not told apart. Anywhere else such a
19
+ * pointer cannot be read.
20
+ *
21
+ * Results: `none` (no repository up to the filesystem root); `resolved` with every common directory found (not
22
+ * canonicalized, nearest first) and, under WSL, the automount root (`drvfsRoot`: Windows drives below it compare names
23
+ * case-insensitively; `/` when it cannot be read); or `unresolved` with the reason: a repository was found, but a common
24
+ * directory cannot be read (the caller fails closed). Every OS access is a seam ({@link CommonDirDeps}). Errors never quote
25
+ * a pointer's text. Never throws.
26
+ */
27
+ import { lstatSync, realpathSync } from "node:fs";
28
+ import { release } from "node:os";
29
+ import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
30
+ import { bareShaped } from "./git-metadata-guard";
31
+ import { errorMessage, isNetworkOrDevicePath, readBoundedRegularFile } from "./git-tools";
32
+
33
+ /** What {@link resolveCommonDirOnDisk} found. */
34
+ export type CommonDirOnDisk =
35
+ | { readonly kind: "none" }
36
+ | { readonly kind: "resolved"; readonly commons: readonly string[]; readonly drvfsRoot?: string }
37
+ | { readonly kind: "unresolved"; readonly reason: string };
38
+
39
+ /** What `lstat` reports of an entry, never following a link. */
40
+ export interface EntryStats {
41
+ isSymbolicLink(): boolean;
42
+ isDirectory(): boolean;
43
+ }
44
+
45
+ /** Seams of {@link resolveCommonDirOnDisk} (tests); every field defaults to the real thing. */
46
+ export interface CommonDirDeps {
47
+ /** Pointer syntax (default `process.platform`): off win32 a Windows drive path is mapped under WSL. */
48
+ readonly platform?: NodeJS.Platform;
49
+ /** Whether this is WSL (default: `os.release()` names Microsoft); asked only for a drive-path pointer. */
50
+ readonly isWsl?: () => boolean;
51
+ /** The text of `/etc/wsl.conf`, undefined when missing (default: a bounded regular-file read); asked only under WSL. */
52
+ readonly readWslConf?: () => string | undefined;
53
+ /** `lstat`, undefined when the entry is missing (default `lstatSync`; ENOENT and ENOTDIR are a missing entry). */
54
+ readonly lstat?: (path: string) => EntryStats | undefined;
55
+ /** A bounded regular-file read, undefined when missing (default `readBoundedRegularFile`: non-blocking, regular files only). */
56
+ readonly readFile?: (path: string, max: number, label: string) => string | undefined;
57
+ /** `realpath` (default `realpathSync.native`): a mapped drive path must resolve. */
58
+ readonly realpath?: (path: string) => string;
59
+ /** Git's bare repository shape (default {@link bareShaped}). */
60
+ readonly bareShaped?: (dir: string) => boolean;
61
+ }
62
+
63
+ /** Bound of the `.git` pointer and `commondir` files, as `gitPointers` bounds them (QA-P13-2-4). */
64
+ const GIT_POINTER_BYTES = 4 * 1024;
65
+ /** Bound of `/etc/wsl.conf`. */
66
+ const WSL_CONF_BYTES = 64 * 1024;
67
+ const WSL_CONF = "/etc/wsl.conf";
68
+ /** The WSL automount root when `/etc/wsl.conf` sets none. */
69
+ export const DEFAULT_AUTOMOUNT_ROOT = "/mnt/";
70
+ const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
71
+ /** A `HEAD` git accepts (`validate_headref`): a symbolic ref into `refs/`, or an object id (SHA-1 or SHA-256 hex). */
72
+ const VALID_HEAD = /^(?:ref:\s*refs\/|[0-9a-fA-F]{40})/;
73
+ const NONE: CommonDirOnDisk = Object.freeze({ kind: "none" });
74
+
75
+ type Seams = Required<CommonDirDeps>;
76
+
77
+ /** The code of a filesystem error, never its message (which would quote the path). */
78
+ function codeOf(error: unknown): string {
79
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "error";
80
+ }
81
+
82
+ /** `lstatSync`, undefined for a missing entry or a file used as a directory (as `existsSync` treats them); else it throws. */
83
+ function lstatOrUndefined(path: string): EntryStats | undefined {
84
+ try {
85
+ return lstatSync(path);
86
+ } catch (error) {
87
+ if (codeOf(error) === "ENOENT" || codeOf(error) === "ENOTDIR") return undefined;
88
+ throw error;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The `[automount] root` value of a wsl.conf text, or undefined when it sets none: section and key case-insensitive, the
94
+ * last value wins, a trailing ` # comment` and surrounding double quotes dropped; comment lines never match.
95
+ */
96
+ export function wslConfRoot(text: string): string | undefined {
97
+ let section = "";
98
+ let root: string | undefined;
99
+ for (const raw of text.split(/\r?\n/)) {
100
+ const line = raw.trim();
101
+ const header = /^\[([^\]]*)\]/.exec(line);
102
+ if (header !== null) {
103
+ section = header[1].trim().toLowerCase();
104
+ continue;
105
+ }
106
+ const entry = section === "automount" ? /^root\s*=(.*)$/i.exec(line) : null;
107
+ if (entry !== null) root = entry[1].replace(/\s+#.*$/, "").trim().replace(/^"(.*)"$/, "$1");
108
+ }
109
+ return root === "" ? undefined : root;
110
+ }
111
+
112
+ /** The WSL automount root: `/etc/wsl.conf`'s, else {@link DEFAULT_AUTOMOUNT_ROOT}. Throws when it is not usable. */
113
+ function automountRoot(seams: Seams): string {
114
+ const text = seams.readWslConf();
115
+ const root = text === undefined ? undefined : wslConfRoot(text);
116
+ if (root === undefined) return DEFAULT_AUTOMOUNT_ROOT;
117
+ if (!isAbsolute(root) || isNetworkOrDevicePath(root) || /[\x00-\x1f\x7f]/.test(root)) {
118
+ throw new Error(`the [automount] root of ${WSL_CONF} is not a local absolute path`);
119
+ }
120
+ return root;
121
+ }
122
+
123
+ /**
124
+ * A Windows drive path pointer read under WSL: `<automount root>/<drive, lower case>/<rest, / separated>`, `..` clamped at the
125
+ * drive root as Windows does. It must resolve, and its realpath must not name a network or device path (`//host/…`); a
126
+ * network drive mounted below the automount root looks local and is not detected.
127
+ */
128
+ function underAutomount(pointer: string, label: string, seams: Seams): string {
129
+ if (!seams.isWsl()) throw new Error(`its ${label} names a Windows drive path, which cannot be read outside Windows or WSL`);
130
+ const root = automountRoot(seams);
131
+ const drive = win32.normalize(pointer);
132
+ const rest = drive.slice(3).split("\\").filter((segment) => segment !== "");
133
+ const mapped = [root.replace(/[\\/]+$/, ""), drive.charAt(0).toLowerCase(), ...rest].join("/");
134
+ let real: string;
135
+ try {
136
+ real = seams.realpath(mapped);
137
+ } catch (error) {
138
+ throw new Error(`its ${label} names a Windows drive path that is not found under the WSL automount root (${codeOf(error)})`);
139
+ }
140
+ if (isNetworkOrDevicePath(real)) {
141
+ throw new Error(`Refusing repository: its ${label} names a Windows drive path that resolves to a network or device path`);
142
+ }
143
+ return mapped;
144
+ }
145
+
146
+ /** Where `pointer` (a `.git` file's `gitdir:` or a `commondir`) leads from `base`; throws when it is refused or unreadable. */
147
+ function located(base: string, pointer: string, label: string, seams: Seams): string {
148
+ if (isNetworkOrDevicePath(pointer)) throw new Error(`Refusing repository: its ${label} points to a network or device path`);
149
+ if (seams.platform === "win32" || !WINDOWS_DRIVE.test(pointer)) return resolve(base, pointer);
150
+ return underAutomount(pointer, label, seams);
151
+ }
152
+
153
+ /** The common directory of git directory `gitdir`: what its `commondir` names, else `gitdir` itself. */
154
+ function commonOf(gitdir: string, seams: Seams): string {
155
+ const pointer = seams.readFile(join(gitdir, "commondir"), GIT_POINTER_BYTES, "commondir")?.trim() ?? "";
156
+ return pointer === "" ? gitdir : located(gitdir, pointer, "commondir", seams);
157
+ }
158
+
159
+ /** The common directory of the checkout whose `.git` entry `dotGit` has `stats`. */
160
+ function commonOfCheckout(checkout: string, dotGit: string, stats: EntryStats, seams: Seams): string {
161
+ if (stats.isSymbolicLink()) throw new Error("Refusing repository: its .git is a link");
162
+ if (stats.isDirectory()) return commonOf(dotGit, seams);
163
+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(seams.readFile(dotGit, GIT_POINTER_BYTES, ".git") ?? "");
164
+ const pointer = match === null ? "" : match[1].trim();
165
+ if (pointer === "") throw new Error("its .git file has no gitdir: line");
166
+ return commonOf(located(checkout, pointer, ".git file", seams), seams);
167
+ }
168
+
169
+ /** `dir` is a bare repository as git's discovery accepts one: git's shape, and a `HEAD` git validates (bounded read). */
170
+ function bareRepository(dir: string, seams: Seams): boolean {
171
+ return seams.bareShaped(dir) && VALID_HEAD.test(seams.readFile(join(dir, "HEAD"), GIT_POINTER_BYTES, "HEAD") ?? "");
172
+ }
173
+
174
+ /** Under WSL the automount root, `/` when it cannot be read (any path may then be on a Windows drive); else undefined. */
175
+ function drvfsRootOf(seams: Seams): string | undefined {
176
+ if (seams.platform === "win32" || !seams.isWsl()) return undefined;
177
+ try {
178
+ return automountRoot(seams);
179
+ } catch {
180
+ return "/"; // an unusable wsl.conf root: treat every path as possibly on a Windows drive (fail closed)
181
+ }
182
+ }
183
+
184
+ /** A path compared as a Windows drive compares names: `/` separators, case-folded. */
185
+ function foldedKey(path: string): string {
186
+ return path.replace(/\\/g, "/").toLowerCase();
187
+ }
188
+
189
+ /** #192: `path` is the WSL automount root `root` or below it (a Windows drive, where letter case is not significant). */
190
+ export function onDrvfs(path: string, root: string): boolean {
191
+ const base = foldedKey(root).replace(/\/+$/, "");
192
+ const key = foldedKey(path);
193
+ return base === "" || key === base || key.startsWith(`${base}/`);
194
+ }
195
+
196
+ /**
197
+ * #192: an `external_directory` allow pattern can match a path inside `home` once letter case is ignored (a Windows drive
198
+ * under WSL): its static prefix (before the first glob character) and `<home>/` are prefixes of one another, compared
199
+ * case-insensitively. The host's own match is case-sensitive off win32, so a deny on `home` does not stop such an allow.
200
+ */
201
+ export function reachesFolded(pattern: string, home: string): boolean {
202
+ const globAt = pattern.search(/[*?[\]{}]/);
203
+ const prefix = foldedKey(globAt === -1 ? `${pattern}/` : pattern.slice(0, globAt));
204
+ const inside = `${foldedKey(home).replace(/\/+$/, "")}/`;
205
+ return inside.startsWith(prefix) || prefix.startsWith(inside);
206
+ }
207
+
208
+ /**
209
+ * The git common directories of the repository holding `start` (made absolute), found on disk in git's discovery order
210
+ * without running git. See the module comment for the rules; never throws.
211
+ */
212
+ export function resolveCommonDirOnDisk(start: string, deps: CommonDirDeps = {}): CommonDirOnDisk {
213
+ const seams: Seams = {
214
+ platform: deps.platform ?? process.platform,
215
+ isWsl: deps.isWsl ?? (() => /microsoft/i.test(release())),
216
+ readWslConf: deps.readWslConf ?? (() => readBoundedRegularFile(WSL_CONF, WSL_CONF_BYTES, WSL_CONF)),
217
+ lstat: deps.lstat ?? lstatOrUndefined,
218
+ readFile: deps.readFile ?? readBoundedRegularFile,
219
+ realpath: deps.realpath ?? ((path) => realpathSync.native(path)),
220
+ bareShaped: deps.bareShaped ?? bareShaped,
221
+ };
222
+ const commons: string[] = [];
223
+ try {
224
+ for (let current = resolve(start); ; current = dirname(current)) {
225
+ const dotGit = join(current, ".git");
226
+ const stats = seams.lstat(dotGit);
227
+ if (stats !== undefined) {
228
+ commons.push(commonOfCheckout(current, dotGit, stats, seams));
229
+ break;
230
+ }
231
+ // A bare repository ends git's discovery, but its shape can be committed to a checkout: keep walking (#192).
232
+ if (bareRepository(current, seams)) commons.push(commonOf(current, seams));
233
+ if (dirname(current) === current) break;
234
+ }
235
+ } catch (error) {
236
+ return { kind: "unresolved", reason: errorMessage(error) };
237
+ }
238
+ if (commons.length === 0) return NONE;
239
+ const drvfsRoot = drvfsRootOf(seams);
240
+ return { kind: "resolved", commons: [...new Set(commons)], ...(drvfsRoot === undefined ? {} : { drvfsRoot }) };
241
+ }