opencode-model-router 2.6.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +3 -1
  3. package/package.json +2 -2
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +12 -1
  6. package/src/compat/v2-hooks.ts +255 -53
  7. package/src/index.ts +328 -37
  8. package/src/router/config.ts +48 -2
  9. package/src/router/dispatch-header.ts +95 -2
  10. package/src/router/git-tools.ts +165 -9
  11. package/src/router/protocol.ts +5 -1
  12. package/src/router/role-agents.ts +110 -3
  13. package/src/router/roles-config.ts +83 -0
  14. package/src/router/roles.ts +1 -1
  15. package/src/router/sessions.ts +11 -0
  16. package/src/routing/classify/route-line.ts +96 -5
  17. package/src/routing/classify/types.ts +26 -0
  18. package/src/routing/outcomes/signals.ts +17 -0
  19. package/src/routing/roles/admission.ts +1028 -0
  20. package/src/routing/roles/approvals.ts +876 -0
  21. package/src/routing/roles/binding.ts +17 -4
  22. package/src/routing/roles/check-placement.ts +112 -0
  23. package/src/routing/roles/git-root.ts +500 -0
  24. package/src/routing/roles/policy.ts +9 -0
  25. package/src/routing/roles/read-set.ts +325 -0
  26. package/src/routing/roles/work-root.ts +9 -1
  27. package/src/routing/wire/dispatch.ts +611 -18
  28. package/src/routing/wire/working-set.ts +58 -0
  29. package/src/util/linear-trim.ts +32 -0
  30. package/src/verify/batch.ts +7 -2
  31. package/src/verify/branch.ts +135 -0
  32. package/src/verify/deterministic.ts +232 -10
  33. package/src/verify/dispatch.ts +284 -9
  34. package/src/verify/dod.ts +46 -0
  35. package/src/verify/edges.ts +817 -0
  36. package/src/verify/gate.ts +349 -16
  37. package/src/verify/git-top.ts +43 -0
  38. package/src/verify/head.ts +107 -0
  39. package/src/verify/pending.ts +155 -8
  40. package/src/verify/perimeter.ts +1180 -0
  41. package/src/verify/pin.ts +109 -0
  42. package/src/verify/reference.ts +174 -30
  43. package/src/verify/risk.ts +16 -3
  44. package/src/verify/runner.ts +706 -32
  45. package/src/verify/tree.ts +347 -8
  46. package/src/verify/types.ts +57 -0
  47. package/src/verify/wiring.ts +1324 -35
@@ -0,0 +1,1028 @@
1
+ /**
2
+ * Admission of work roots across repositories (`docs/design/cross-repo.md` §3 "Admission" and "Names", §5 refusal wording;
3
+ * Phase 1 step P1.2). Decides which directories are admissible work roots and resolves `root=` / `repo=` / `branch=`
4
+ * declarations (declare, then check).
5
+ *
6
+ * A directory is admitted when
7
+ * 1. it lies 1..`repoDepth` segments below a `routing.repoParents` entry (text first, then the canonical form, never the parent
8
+ * itself), no `routing.repoExclude` glob matches it, and hardened git prints it for `rev-parse --show-toplevel`; or
9
+ * 2. its TEXT equals a worktree that a known repository (the session repository, the working set, the named repository) lists in
10
+ * `git worktree list --porcelain`, the repository still lists it after `realpath`, and hardened git run in it names the same
11
+ * repository (`rev-parse --git-common-dir`), so a listed path swapped for a link to another repository is not admitted.
12
+ *
13
+ * QA round 1: whichever rule admits a directory, a final gate refuses it when `routing.repoExclude` matches its text or its
14
+ * canonical form, when its text lies below a parent but its canonical form does not lie below that parent's canonical form (it
15
+ * leads out through a link), or when its canonical form is, or contains, a parent. A rule-1 refusal for an exclusion, a link or
16
+ * the parent itself is final: rule 2 never admits what rule 1 refused for those. Git never runs in a candidate without a `.git`
17
+ * entry, and a `repo=` lookup skips dot-directories, `node_modules` and excluded directories and stops after
18
+ * {@link LOOKUP_MAX_DIRS} directories.
19
+ *
20
+ * Cross-repo Phase 4 (`docs/design/cross-repo-phase4-plan.md`, SD-P4-5, -6), only with parents configured:
21
+ * 3. its TEXT equals the path of a repository a human approved with `/router approve` (a valid entry of the approvals store), it
22
+ * is not a protected location, and its identity still holds (`verifyIdentity`: realpath, `.git` directory, top level, common
23
+ * dir, root commits). Rule 3 runs before rule 2 and its refusal is final; `locate` and the gate follow. Rule 3 binds exactly the
24
+ * directory it verified (Phase 4 QA, m1). Rule 2 judges the repository that LISTS the candidate (git's main worktree), not the
25
+ * known entry's text (Phase 4 QA, M1): unless it is the session repository, it must be an approved path whose identity holds
26
+ * (the binding is then marked with the approval) or lie below a parent; otherwise the known entry is skipped (with no parents,
27
+ * only the session repository's worktrees). The final "not below routing.repoParents" refusal resolves the
28
+ * candidate (realpath, no git): another spelling of an approved path is refused naming it; otherwise `approvable` carries the
29
+ * canonical candidate when it lies outside every parent and passes the text checks.
30
+ *
31
+ * Text is compared before any filesystem call on a path outside the parents: git never runs in a directory that the text did
32
+ * not place below a parent, that no known repository lists and that is not an approved path. Network and device paths (`\\host`,
33
+ * `//host`, `\\?\`, `\\.\`), 8.3 short-name segments, `..` segments and relative paths are refused before any call at all.
34
+ *
35
+ * All I/O goes through {@link AdmissionDeps}; git results are cached for 5 s per normalised path.
36
+ */
37
+ import { lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
38
+ import { dirname, isAbsolute, join, posix, win32 } from "node:path";
39
+ import { gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded, workRootGuards } from "../../router/git-tools";
40
+ import { permissionMatches } from "../../router/read-only";
41
+ import { DEFAULT_REPO_APPROVAL_DAYS } from "../../router/roles-config";
42
+ import { gitWorktreeList, normalizeRootText } from "../wire/dispatch";
43
+ import { protectedProblem, validApprovals, verifyIdentity, type EntryStat, type IdentityDeps, type RepoApproval } from "./approvals";
44
+
45
+ /** One entry of `git worktree list --porcelain`, as git prints it. */
46
+ export interface WorktreeEntry {
47
+ readonly path: string;
48
+ readonly head: string | null;
49
+ /** Short branch name (`refs/heads/` stripped); null when detached or bare. */
50
+ readonly branch: string | null;
51
+ readonly detached: boolean;
52
+ readonly bare: boolean;
53
+ readonly prunable: boolean;
54
+ }
55
+
56
+ export interface RepoLocation {
57
+ /** Canonical path of the main worktree (the first porcelain entry). */
58
+ readonly repository: string;
59
+ /** Basename of the main worktree's path: the repository's name. */
60
+ readonly name: string;
61
+ /** Canonical path of the matched worktree: the work root. */
62
+ readonly worktree: string;
63
+ /** The matched worktree's branch; null = detached. */
64
+ readonly branch: string | null;
65
+ readonly head: string | null;
66
+ /** Non-prunable entries, in git's order (the main worktree first). */
67
+ readonly worktrees: readonly WorktreeEntry[];
68
+ /**
69
+ * Cross-repo Phase 4: the approved path (`/router approve`) when an approval backs this binding: rule 3, or rule 2 through a
70
+ * known repository that is an approved one. Absent otherwise.
71
+ */
72
+ readonly approval?: string;
73
+ }
74
+
75
+ export type Admission =
76
+ | { readonly ok: true; readonly location: RepoLocation }
77
+ | {
78
+ readonly ok: false;
79
+ readonly reason: string;
80
+ /**
81
+ * Cross-repo Phase 4: the canonical candidate, set only on the final "not below routing.repoParents" refusal, with parents
82
+ * configured, when the candidate lies outside every parent and passes the text checks (it could be approved).
83
+ */
84
+ readonly approvable?: string;
85
+ };
86
+
87
+ export interface AdmissionConfig {
88
+ /** `routing.repoParents`: literal, absolute, canonical long-form directories. */
89
+ readonly parents: readonly string[];
90
+ /** `routing.repoDepth`: repositories are admitted 1..depth segments below a parent. */
91
+ readonly depth: number;
92
+ /** `routing.repoExclude`: absolute globs matched against the text and the canonical path of a candidate. */
93
+ readonly exclude: readonly string[];
94
+ /** `routing.repoApprovalDays` for the default {@link AdmissionDeps.approvals} (default 14). */
95
+ readonly approvalDays?: number;
96
+ }
97
+
98
+ export interface AdmissionDeps {
99
+ /** `git worktree list --porcelain` in `cwd` (hardened); rejects on failure. */
100
+ listWorktrees(cwd: string): Promise<string>;
101
+ /** Hardened `git rev-parse --show-toplevel` in `cwd`; undefined on failure. */
102
+ showToplevel(cwd: string): Promise<string | undefined>;
103
+ /** Hardened `git rev-parse --git-common-dir` in `cwd`, absolute (a relative answer joined to `cwd`); undefined on failure. */
104
+ commonDir(cwd: string): Promise<string | undefined>;
105
+ /** Whether `dir` holds a `.git` entry (`lstat`: a file, a directory or a link, not followed). Git never runs without one. */
106
+ gitEntry(dir: string): boolean;
107
+ /** `realpathSync.native`; throws when the path does not resolve. */
108
+ realpath(path: string): string;
109
+ isDirectory(path: string): boolean;
110
+ /** Names of the directories (not links) in `path`; [] on error. */
111
+ readdir(path: string): string[];
112
+ platform: NodeJS.Platform;
113
+ now(): number;
114
+ /**
115
+ * Cross-repo Phase 4 (SD-P4-5): the approvals that apply now (a valid store, entries not expired; no git). Asked only with
116
+ * parents configured. Absent: no approvals (rule 3 is inert).
117
+ */
118
+ approvals?(): readonly RepoApproval[];
119
+ /** Phase 4 (SD-P4-6): hardened sorted root commits of `HEAD` in `cwd`; undefined on failure. Absent: `gitRootCommits`. */
120
+ rootCommits?(cwd: string): Promise<string[] | undefined>;
121
+ /** Phase 4 (SD-P4-6): hardened `HEAD` commit and branch in `cwd`; undefined on failure. Absent: `gitHeadInfo`. */
122
+ headInfo?(cwd: string): Promise<GitHeadInfo | undefined>;
123
+ /** Phase 4 (SD-P4-4): `lstat` (links not followed); throws when the entry is absent. Absent: `lstatSync`. */
124
+ lstat?(path: string): EntryStat;
125
+ }
126
+
127
+ export interface Declaration { readonly repo?: string; readonly branch?: string; readonly root?: string }
128
+ export interface DeclarationContext { readonly sessionRepository: string; readonly known?: readonly string[] }
129
+
130
+ export interface AdmissionService {
131
+ /**
132
+ * Rule 1 (below a parent), then rule 3 (an approved path), then rule 2 (a worktree that a repository in `known` lists); every
133
+ * admission passes the final gate. `sessionRepository` is the repository whose worktrees rule 2 admits without a parent or an
134
+ * approval (Phase 4 QA, M1); without it, every repository that lists `root` must lie below a parent or be approved.
135
+ */
136
+ admit(root: string, known?: readonly string[], sessionRepository?: string): Promise<Admission>;
137
+ /** Resolve `root=` / `repo=` / `branch=`; every declaration must agree. */
138
+ resolve(decl: Declaration, ctx: DeclarationContext): Promise<Admission>;
139
+ /**
140
+ * The `repo=` lookup `resolve` uses for a bare name (a repository name, or the directory name of a linked worktree below the
141
+ * parents), read-only. The name is not checked here: refuse a non-bare name with {@link repoNameProblem} first. `resolve` passes
142
+ * no options.
143
+ */
144
+ find(name: string, opts?: AdmissionFindOptions): Promise<AdmissionLookup>;
145
+ }
146
+
147
+ /** Options of {@link AdmissionService.find}. */
148
+ export interface AdmissionFindOptions {
149
+ /**
150
+ * QA round 1 (Phase 3 lot 1, F4): asked for every candidate directory named X before anything else runs on it (no `.git` probe,
151
+ * no `realpath`, no git). A candidate it rejects, or for which it throws, is skipped and noted in `refused`. The caller's own
152
+ * admission test, for example the read set.
153
+ */
154
+ readonly eligible?: (candidatePath: string) => boolean;
155
+ }
156
+
157
+ /** What a `repo=X` lookup saw: the matches, the refusal notes, the places searched, and whether the scan was capped. */
158
+ export interface AdmissionLookup {
159
+ /** One location per repository named X and per linked worktree whose directory is named X, in scan order. */
160
+ readonly found: RepoLocation[];
161
+ /** Why each candidate directory named X was not admitted. */
162
+ readonly refused: string[];
163
+ /** The patterns searched, `<parent>\X` then `<parent>\*\X` while the depth allows. */
164
+ readonly searched: string[];
165
+ /** The scan stopped after {@link LOOKUP_MAX_DIRS} directories. */
166
+ readonly capped: boolean;
167
+ }
168
+
169
+ /** How long a `show-toplevel`, common-dir or worktree-list result is reused, per normalised path. */
170
+ export const ADMISSION_CACHE_MS = 5_000;
171
+ const CACHE_MAX = 256;
172
+ /** QA round 1 (F7): a `repo=` lookup visits at most this many directories, across all parents and levels. */
173
+ export const LOOKUP_MAX_DIRS = 2_000;
174
+ /** QA round 1 (F7): a `repo=` refusal quotes at most this many notes, then counts the rest. */
175
+ export const LOOKUP_MAX_NOTES = 10;
176
+
177
+ /**
178
+ * The entries of `git worktree list --porcelain`: blocks separated by blank lines, the first block the main worktree. Unlike
179
+ * `parseWorktreeList` (dispatch.ts) prunable entries are kept, flagged; `locked` and unknown lines are ignored.
180
+ */
181
+ export function parseWorktreeEntries(porcelain: string): WorktreeEntry[] {
182
+ const out: WorktreeEntry[] = [];
183
+ let current: { path: string; head: string | null; branch: string | null; detached: boolean; bare: boolean; prunable: boolean } | undefined;
184
+ const flush = (): void => {
185
+ if (current !== undefined) out.push({ ...current });
186
+ current = undefined;
187
+ };
188
+ for (const raw of porcelain.split("\n")) {
189
+ const line = raw.replace(/\r$/, "");
190
+ if (line === "") {
191
+ flush();
192
+ } else if (line.startsWith("worktree ")) {
193
+ flush();
194
+ const path = line.slice("worktree ".length);
195
+ if (path !== "") current = { path, head: null, branch: null, detached: false, bare: false, prunable: false };
196
+ } else if (current === undefined) {
197
+ continue;
198
+ } else if (line.startsWith("HEAD ")) {
199
+ const head = line.slice("HEAD ".length).trim();
200
+ current.head = head === "" ? null : head;
201
+ } else if (line.startsWith("branch ")) {
202
+ const ref = line.slice("branch ".length).trim();
203
+ current.branch = ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
204
+ } else if (line === "detached") {
205
+ current.detached = true;
206
+ } else if (line === "bare") {
207
+ current.bare = true;
208
+ } else if (line === "prunable" || line.startsWith("prunable ")) {
209
+ current.prunable = true;
210
+ }
211
+ }
212
+ flush();
213
+ return out;
214
+ }
215
+
216
+ /** The spawn {@link gitBounded} runs git with: `spawnBounded` (git-tools.ts) unless a test injects another. */
217
+ export type GitSpawn = (
218
+ executable: string,
219
+ args: readonly string[],
220
+ cwd: string,
221
+ options: { readonly env: NodeJS.ProcessEnv; readonly timeoutMs: number; readonly maxBytes: number; readonly settleOnFailure: true },
222
+ ) => Promise<{ readonly code: number | null; readonly output: Buffer; readonly truncated: boolean; readonly failure?: string }>;
223
+
224
+ /** Options of {@link gitBounded}. */
225
+ export interface GitBoundedOptions {
226
+ /** Total bound in ms, the `safe.directory` probe included (default {@link GIT_BOUND_MS}). */
227
+ readonly timeoutMs?: number;
228
+ /** Output cap in bytes (default 64 KiB); a longer answer is a failure (`truncated`). */
229
+ readonly maxBytes?: number;
230
+ /** Tests only: replaces `spawnBounded`. The hardening (executable, arguments, environment) is computed as without it. */
231
+ readonly spawn?: GitSpawn;
232
+ }
233
+
234
+ /** What {@link gitBounded} returns: git's raw stdout, or why there is none. */
235
+ export type GitBoundedResult =
236
+ | { readonly ok: true; readonly stdout: string }
237
+ | { readonly ok: false; readonly failure: "timeout" | "exit" | "truncated" | "spawn"; readonly code?: number | null; readonly detail?: string };
238
+
239
+ /** Default bound of {@link gitBounded}: 5 s, the `safe.directory` probe included. */
240
+ export const GIT_BOUND_MS = 5_000;
241
+
242
+ /**
243
+ * How long past its bound {@link gitBounded} waits before it gives up on its own: `spawnBounded` normally stops git at the bound
244
+ * and kills its process tree first; this deadline only covers a spawn that never settles.
245
+ */
246
+ const GIT_BOUND_GRACE_MS = 500;
247
+
248
+ /** One hardened git run ({@link gitBounded}), without the outer deadline. Never rejects. */
249
+ async function runGitBounded(cwd: string, args: readonly string[], bound: number, maxBytes: number, spawn: GitSpawn | undefined): Promise<GitBoundedResult> {
250
+ try {
251
+ const run: GitSpawn = spawn ?? spawnBounded;
252
+ const started = performance.now();
253
+ const executable = gitExecutable(workRootGuards(cwd));
254
+ const trusted = await inheritedSafeDirectoryArgs(executable, bound);
255
+ const above = dirname(cwd);
256
+ const result = await run(executable, [...hardeningArgs(), ...trusted, ...args], cwd, {
257
+ env: gitEnvironment(above === cwd ? {} : { GIT_CEILING_DIRECTORIES: above }),
258
+ timeoutMs: Math.max(1, bound - (performance.now() - started)),
259
+ maxBytes,
260
+ settleOnFailure: true,
261
+ });
262
+ if (result.failure !== undefined) return { ok: false, failure: "timeout", code: result.code, detail: result.failure };
263
+ if (result.truncated) return { ok: false, failure: "truncated", code: result.code };
264
+ if (result.code !== 0) return { ok: false, failure: "exit", code: result.code };
265
+ return { ok: true, stdout: result.output.toString("utf8") };
266
+ } catch (error) {
267
+ return { ok: false, failure: "spawn", detail: error instanceof Error ? error.message : String(error) };
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Hardened `git <args>` in `cwd`, as `gitWorktreeList` (dispatch.ts) spawns git: the absolute executable selected outside
273
+ * `workRootGuards(cwd)`, `hardeningArgs()`, the user's `safe.directory` values, `gitEnvironment()`, no shell, bounded to
274
+ * {@link GIT_BOUND_MS} (the `safe.directory` probe included) and 64 KiB. `GIT_CEILING_DIRECTORIES` stops discovery at `cwd`'s
275
+ * parent, so a directory inside a repository never reports that repository. Never rejects: git's raw stdout, or a typed failure
276
+ * (`timeout`, `exit` = a non-zero exit code, `truncated` = more than `maxBytes`, `spawn` = git could not run, `cwd` included).
277
+ */
278
+ export async function gitBounded(cwd: string, args: readonly string[], opts: GitBoundedOptions = {}): Promise<GitBoundedResult> {
279
+ const bound = opts.timeoutMs ?? GIT_BOUND_MS;
280
+ const maxBytes = opts.maxBytes ?? 64 * 1024;
281
+ let timer: NodeJS.Timeout | undefined;
282
+ const deadline = new Promise<GitBoundedResult>((resolve) => {
283
+ timer = setTimeout(() => resolve({ ok: false, failure: "timeout", detail: `git did not settle within ${String(bound + GIT_BOUND_GRACE_MS)} ms` }), bound + GIT_BOUND_GRACE_MS);
284
+ });
285
+ try {
286
+ return await Promise.race([runGitBounded(cwd, args, bound, maxBytes, opts.spawn), deadline]);
287
+ } finally {
288
+ clearTimeout(timer);
289
+ }
290
+ }
291
+
292
+ /** Hardened `git rev-parse <args>` in `cwd` ({@link gitBounded}), trimmed. Undefined on any failure or an empty answer. */
293
+ async function gitRevParse(cwd: string, args: readonly string[], opts?: GitBoundedOptions): Promise<string | undefined> {
294
+ const result = await gitBounded(cwd, ["rev-parse", ...args], opts);
295
+ if (!result.ok) return undefined;
296
+ const out = result.stdout.trim();
297
+ return out === "" ? undefined : out;
298
+ }
299
+
300
+ /** Hardened `git rev-parse --show-toplevel` in `cwd` ({@link gitRevParse}). Undefined on any failure. */
301
+ export function gitShowToplevel(cwd: string, opts?: GitBoundedOptions): Promise<string | undefined> {
302
+ return gitRevParse(cwd, ["--show-toplevel"], opts);
303
+ }
304
+
305
+ /** Hardened `git rev-parse --git-common-dir` in `cwd` ({@link gitRevParse}); a relative answer is joined to `cwd`. */
306
+ export async function gitCommonDir(cwd: string, opts?: GitBoundedOptions): Promise<string | undefined> {
307
+ const dir = await gitRevParse(cwd, ["--git-common-dir"], opts);
308
+ return dir === undefined ? undefined : isAbsolute(dir) ? dir : join(cwd, dir);
309
+ }
310
+
311
+ /** A full object name as git prints it: 40 (SHA-1) or 64 (SHA-256) lower-case hex digits. */
312
+ const FULL_OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
313
+
314
+ /**
315
+ * The root commits reachable from `HEAD` in `cwd`, sorted and unique: hardened `git --no-replace-objects rev-list
316
+ * --max-parents=0 HEAD --` ({@link gitBounded}; replace refs cannot stand in for history, `--` keeps a file named `HEAD` from
317
+ * making the revision ambiguous). Undefined on any failure, for a repository without commits, and when a line is not a full
318
+ * object name.
319
+ */
320
+ export async function gitRootCommits(cwd: string, opts?: GitBoundedOptions): Promise<string[] | undefined> {
321
+ const result = await gitBounded(cwd, ["--no-replace-objects", "rev-list", "--max-parents=0", "HEAD", "--"], opts);
322
+ if (!result.ok) return undefined;
323
+ const lines = result.stdout.split("\n").map((line) => line.trim()).filter((line) => line !== "");
324
+ if (lines.length === 0 || !lines.every((line) => FULL_OID.test(line))) return undefined;
325
+ return [...new Set(lines)].sort();
326
+ }
327
+
328
+ /**
329
+ * `remote.origin.url` in `cwd`: hardened `git config --get remote.origin.url` ({@link gitBounded}; system and global config are
330
+ * off), raw apart from git's line end. Not sanitised: a caller that shows it sanitises it. Undefined when it is unset or empty,
331
+ * and on any failure.
332
+ */
333
+ export async function gitOrigin(cwd: string, opts?: GitBoundedOptions): Promise<string | undefined> {
334
+ const result = await gitBounded(cwd, ["config", "--get", "remote.origin.url"], opts);
335
+ if (!result.ok) return undefined;
336
+ const url = result.stdout.replace(/\r?\n$/, "");
337
+ return url === "" ? undefined : url;
338
+ }
339
+
340
+ /** What {@link gitHeadInfo} reports about `HEAD`. */
341
+ export interface GitHeadInfo {
342
+ /** Short branch name (`refs/heads/` stripped); undefined when `HEAD` is detached. */
343
+ readonly branch: string | undefined;
344
+ /** Full object name of the commit `HEAD` names. */
345
+ readonly head: string;
346
+ }
347
+
348
+ /**
349
+ * `HEAD` in `cwd`: hardened `git rev-parse --verify --quiet HEAD` and `git symbolic-ref --quiet HEAD` ({@link gitBounded}, run
350
+ * together). A `symbolic-ref` exit code 1 means detached. Undefined on any other failure, for a repository without commits, and
351
+ * when `HEAD` names something other than a branch.
352
+ */
353
+ export async function gitHeadInfo(cwd: string, opts?: GitBoundedOptions): Promise<GitHeadInfo | undefined> {
354
+ const [commit, ref] = await Promise.all([
355
+ gitBounded(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"], opts),
356
+ gitBounded(cwd, ["symbolic-ref", "--quiet", "HEAD"], opts),
357
+ ]);
358
+ if (!commit.ok) return undefined;
359
+ const head = commit.stdout.trim();
360
+ if (!FULL_OID.test(head)) return undefined;
361
+ if (!ref.ok) return ref.failure === "exit" && ref.code === 1 ? { branch: undefined, head } : undefined;
362
+ const name = ref.stdout.trim();
363
+ if (!name.startsWith("refs/heads/") || name.length === "refs/heads/".length) return undefined;
364
+ return { branch: name.slice("refs/heads/".length), head };
365
+ }
366
+
367
+ /** The real I/O of {@link createAdmission}; `approvalDays` is `routing.repoApprovalDays` for {@link AdmissionDeps.approvals}. */
368
+ export function defaultAdmissionDeps(opts: { readonly approvalDays?: number | undefined } = {}): AdmissionDeps {
369
+ return {
370
+ approvals: () => validApprovals(opts.approvalDays ?? DEFAULT_REPO_APPROVAL_DAYS),
371
+ rootCommits: (cwd) => gitRootCommits(cwd),
372
+ headInfo: (cwd) => gitHeadInfo(cwd),
373
+ lstat: (path) => lstatSync(path),
374
+ listWorktrees: gitWorktreeList,
375
+ showToplevel: gitShowToplevel,
376
+ commonDir: gitCommonDir,
377
+ gitEntry: (dir) => {
378
+ try {
379
+ lstatSync(join(dir, ".git"));
380
+ return true;
381
+ } catch {
382
+ return false;
383
+ }
384
+ },
385
+ realpath: (path) => realpathSync.native(path),
386
+ isDirectory: (path) => {
387
+ try {
388
+ return statSync(path).isDirectory();
389
+ } catch {
390
+ return false;
391
+ }
392
+ },
393
+ readdir: (path) => {
394
+ try {
395
+ return readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
396
+ } catch {
397
+ return [];
398
+ }
399
+ },
400
+ platform: process.platform,
401
+ now: () => Date.now(),
402
+ };
403
+ }
404
+
405
+ /**
406
+ * Why `path` can never be a work root, judged on its text alone (no filesystem call), or undefined: empty, a control
407
+ * character, a network or device path, not absolute (win32: no drive letter), a colon after the drive (a stream or device
408
+ * name), a `..` segment, or an 8.3 short-name segment.
409
+ */
410
+ export function rootTextProblem(path: string, platform: NodeJS.Platform = process.platform): string | undefined {
411
+ const text = path.trim();
412
+ if (text === "") return "is empty";
413
+ if (/[\u0000-\u001f]/.test(text)) return "contains a control character";
414
+ if (/^[\\/]{2}/.test(text)) return "is a network or device path (\\\\host, //host, \\\\?\\ or \\\\.\\); name a local directory";
415
+ const win = platform === "win32";
416
+ if (win) {
417
+ if (!/^[A-Za-z]:[\\/]/.test(text)) return "is not an absolute path with a drive letter";
418
+ if (text.slice(2).includes(":")) return "contains a colon after the drive letter (a stream or device name)";
419
+ } else if (!text.startsWith("/")) {
420
+ return "is not an absolute path";
421
+ }
422
+ const segments = text.split(win ? /[\\/]/ : /\//);
423
+ if (segments.some((segment) => segment === "..")) return "contains a .. segment";
424
+ if (segments.some((segment) => /~\d/.test(segment))) return "contains an 8.3 short-name component; use the long form of the path";
425
+ return undefined;
426
+ }
427
+
428
+ /** Why `name` is not a bare repository name for `repo=` (empty, a separator, a drive, . / .., a wildcard, an 8.3 short name); undefined when it is. */
429
+ export function repoNameProblem(name: string): string | undefined {
430
+ if (name === "") return "is empty";
431
+ if (/[\u0000-\u001f]/.test(name)) return "contains a control character";
432
+ if (/[\\/:]/.test(name) || name === "." || name === "..") return "is not a bare repository name (no separator, drive or . / ..)";
433
+ if (/[*?[\]{}]/.test(name)) return "contains a wildcard";
434
+ if (/~\d/.test(name)) return "contains an 8.3 short-name component; use the long name";
435
+ return undefined;
436
+ }
437
+
438
+ interface CacheEntry<T> { readonly at: number; readonly value: Promise<T> }
439
+
440
+ export function createAdmission(cfg: AdmissionConfig, deps: AdmissionDeps = defaultAdmissionDeps({ approvalDays: cfg.approvalDays })): AdmissionService {
441
+ const platform = deps.platform;
442
+ const win = platform === "win32";
443
+ const sep = win ? "\\" : "/";
444
+ const paths = win ? win32 : posix;
445
+ const depth = Number.isInteger(cfg.depth) && cfg.depth >= 1 ? cfg.depth : 1;
446
+ const text = (path: string): string => normalizeRootText(path, platform);
447
+ // Parents are sanitised by the config layer; one that is unsafe as text is ignored here as well.
448
+ const parents = cfg.parents.map((parent) => parent.trim()).filter((parent) => rootTextProblem(parent, platform) === undefined);
449
+ const parentList = parents.length === 0 ? "none configured" : parents.join(", ");
450
+ const range = depth === 1 ? "1 level" : `1 to ${String(depth)} levels`;
451
+ const refuse = (reason: string): Admission => ({ ok: false, reason });
452
+ /** QA round 1 (F1, F2): refusals no later rule may overturn (an exclusion, a link out of a parent, the parent itself). */
453
+ const finals = new WeakSet<Admission>();
454
+ const refuseFinal = (reason: string): Admission => {
455
+ const result = refuse(reason);
456
+ finals.add(result);
457
+ return result;
458
+ };
459
+ const sameName = (a: string, b: string): boolean => (win ? a.toLowerCase() === b.toLowerCase() : a === b);
460
+ const short = (sha: string | null): string => (sha === null ? "unknown" : sha.slice(0, 7));
461
+
462
+ const canonical = (path: string): string | null => {
463
+ try {
464
+ const resolved = deps.realpath(path);
465
+ return typeof resolved === "string" && resolved !== "" ? resolved : null;
466
+ } catch {
467
+ return null;
468
+ }
469
+ };
470
+ /** A git-listed path for messages: its canonical form, or git's text with native separators. */
471
+ const display = (path: string): string => canonical(path) ?? (win ? path.replace(/\//g, "\\") : path);
472
+ const describeEntry = (entry: WorktreeEntry): string =>
473
+ entry.bare ? "bare" : entry.branch !== null ? entry.branch : `detached at ${short(entry.head)}`;
474
+ const listing = (entries: readonly WorktreeEntry[]): string => entries.map((entry) => `${display(entry.path)} → ${describeEntry(entry)}`).join("; ");
475
+ const joinAnd = (items: readonly string[]): string =>
476
+ items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1] ?? ""}`;
477
+ /** `git`'s path or a canonical one equals `real` (canonical): text first, `realpath` only when the text differs. */
478
+ const samePath = (listed: string, real: string): boolean => {
479
+ if (text(listed) === text(real)) return true;
480
+ const resolved = canonical(listed);
481
+ return resolved !== null && text(resolved) === text(real);
482
+ };
483
+ /** Segments `child` lies below `parent` (both normalised text); 0 = the same; undefined = not below. */
484
+ const levelsBelow = (child: string, parent: string): number | undefined => {
485
+ if (child === parent) return 0;
486
+ const prefix = parent.endsWith(sep) ? parent : parent + sep;
487
+ if (!child.startsWith(prefix)) return undefined;
488
+ const rest = child.slice(prefix.length);
489
+ return rest === "" ? 0 : rest.split(sep).length;
490
+ };
491
+ const excludedBy = (path: string): string | undefined => {
492
+ const input = win ? path.toLowerCase() : path;
493
+ return cfg.exclude.find((pattern) => pattern.trim() !== "" && permissionMatches(input, win ? pattern.toLowerCase() : pattern));
494
+ };
495
+ /** {@link excludedBy} on the path as given and, on win32, with native separators (git prints `/`). */
496
+ const excludedText = (path: string): string | undefined =>
497
+ excludedBy(path) ?? (win && path.includes("/") ? excludedBy(path.replace(/\//g, "\\")) : undefined);
498
+ /**
499
+ * QA round 1 (Phase 3 lot 1, F3): why `shown` is refused when `routing.repoExclude` matches the repository it belongs to (its
500
+ * canonical main worktree `repository`, or git's text `listed` of it): a linked worktree never opens an excluded repository.
501
+ */
502
+ const repositoryExcluded = (shown: string, repository: string, listed: string = repository): string | undefined => {
503
+ const pattern = excludedText(listed) ?? excludedText(repository);
504
+ return pattern === undefined ? undefined : `root=${shown} is a worktree of ${repository}, which is excluded by routing.repoExclude (${pattern}): no work root.`;
505
+ };
506
+ const unique = (items: readonly string[]): string[] => {
507
+ const seen = new Set<string>();
508
+ const out: string[] = [];
509
+ for (const item of items) {
510
+ const key = text(item);
511
+ if (item.trim() === "" || seen.has(key)) continue;
512
+ seen.add(key);
513
+ out.push(item);
514
+ }
515
+ return out;
516
+ };
517
+
518
+ // ── 5 s caches keyed by normalised path ──────────────────────────────────────────────────────────────────────────────
519
+ const toplevels = new Map<string, CacheEntry<string | undefined>>();
520
+ const commons = new Map<string, CacheEntry<string | undefined>>();
521
+ const lists = new Map<string, CacheEntry<string>>();
522
+ const cached = <T>(cache: Map<string, CacheEntry<T>>, key: string, load: () => Promise<T>): Promise<T> => {
523
+ const now = deps.now();
524
+ const hit = cache.get(key);
525
+ if (hit !== undefined && now >= hit.at && now - hit.at < ADMISSION_CACHE_MS) return hit.value;
526
+ let value: Promise<T>;
527
+ try {
528
+ value = load();
529
+ } catch (error) {
530
+ value = Promise.reject(error instanceof Error ? error : new Error(String(error)));
531
+ }
532
+ cache.delete(key);
533
+ cache.set(key, { at: now, value });
534
+ while (cache.size > CACHE_MAX) {
535
+ const oldest = cache.keys().next().value;
536
+ if (oldest === undefined) break;
537
+ cache.delete(oldest);
538
+ }
539
+ // A failure is not reused.
540
+ value.catch(() => {
541
+ if (cache.get(key)?.value === value) cache.delete(key);
542
+ });
543
+ return value;
544
+ };
545
+ const toplevel = (cwd: string): Promise<string | undefined> =>
546
+ cached(toplevels, text(cwd), async () => {
547
+ try {
548
+ return await deps.showToplevel(cwd);
549
+ } catch {
550
+ return undefined;
551
+ }
552
+ });
553
+ const commonDirOf = (cwd: string): Promise<string | undefined> =>
554
+ cached(commons, text(cwd), async () => {
555
+ try {
556
+ return await deps.commonDir(cwd);
557
+ } catch {
558
+ return undefined;
559
+ }
560
+ });
561
+ const worktrees = async (cwd: string): Promise<WorktreeEntry[]> =>
562
+ parseWorktreeEntries(await cached(lists, text(cwd), () => deps.listWorktrees(cwd)));
563
+
564
+ /** Whether hardened git prints `real` (canonical) as the top level of the repository in `real`; no git without a `.git` entry (F7). */
565
+ const isToplevel = async (real: string): Promise<boolean> => {
566
+ if (!deps.gitEntry(real)) return false;
567
+ const top = (await toplevel(real))?.trim();
568
+ return top !== undefined && top !== "" && samePath(top, real);
569
+ };
570
+
571
+ /** QA round 1 (F2): git run in the canonical work root `real` names the repository git names in `repository` (common dir). */
572
+ const sameRepository = async (real: string, repository: string): Promise<boolean> => {
573
+ const [mine, theirs] = await Promise.all([commonDirOf(real), commonDirOf(repository)]);
574
+ if (mine === undefined || theirs === undefined) return false;
575
+ const a = canonical(mine);
576
+ const b = canonical(theirs);
577
+ return a !== null && b !== null && text(a) === text(b);
578
+ };
579
+
580
+ /** The location of the canonical work root `real`, from the worktree list run in `listFrom`. */
581
+ const locate = async (shown: string, real: string, listFrom: string): Promise<Admission> => {
582
+ let entries: WorktreeEntry[];
583
+ try {
584
+ entries = await worktrees(listFrom);
585
+ } catch {
586
+ return refuse(`root=${shown}: git worktree list failed in ${listFrom}: no work root.`);
587
+ }
588
+ const main = entries[0];
589
+ const repository = main === undefined ? null : canonical(main.path);
590
+ if (main === undefined || repository === null) return refuse(`root=${shown}: the main worktree of its repository does not resolve: no work root.`);
591
+ // QA round 1 (Phase 3 lot 1, F3): every admission ends here, the `find` candidates included; an exclusion is final.
592
+ const excludedRepo = repositoryExcluded(shown, repository, main.path);
593
+ if (excludedRepo !== undefined) return refuseFinal(excludedRepo);
594
+ const live = entries.filter((entry) => !entry.prunable);
595
+ const matched = live.find((entry) => text(entry.path) === text(real)) ?? live.find((entry) => samePath(entry.path, real));
596
+ if (matched === undefined) return refuse(`root=${shown} is not listed by git worktree list of ${repository}: no work root.`);
597
+ return {
598
+ ok: true,
599
+ location: { repository, name: paths.basename(repository), worktree: real, branch: matched.branch, head: matched.head, worktrees: live },
600
+ };
601
+ };
602
+
603
+ // ── Cross-repo Phase 4: repositories outside the parents that a human approved (SD-P4-5, -6) ───────────────────────────
604
+ /** The approvals that apply now: [] with no parents (I9: the store is not read), without `deps.approvals`, or when it throws. */
605
+ const approvedNow = (): readonly RepoApproval[] => {
606
+ if (parents.length === 0 || deps.approvals === undefined) return [];
607
+ try {
608
+ const list = deps.approvals();
609
+ return Array.isArray(list) ? list : [];
610
+ } catch {
611
+ return [];
612
+ }
613
+ };
614
+ /** The approval whose path equals `path` as text (case-insensitive on win32, separators normalised); no filesystem call (I11). */
615
+ const approvalFor = (path: string, approvals: readonly RepoApproval[]): RepoApproval | undefined => {
616
+ if (approvals.length === 0) return undefined;
617
+ const key = text(path);
618
+ return approvals.find((entry) => text(entry.path) === key);
619
+ };
620
+ /** The identity check's I/O: these deps, the show-toplevel and common-dir answers through the 5 s caches. */
621
+ const identityDeps: IdentityDeps = {
622
+ realpath: (path) => deps.realpath(path),
623
+ showToplevel: (cwd) => toplevel(cwd),
624
+ commonDir: (cwd) => commonDirOf(cwd),
625
+ ...(deps.lstat !== undefined ? { lstat: deps.lstat.bind(deps) } : {}),
626
+ ...(deps.rootCommits !== undefined ? { rootCommits: deps.rootCommits.bind(deps) } : {}),
627
+ ...(deps.headInfo !== undefined ? { headInfo: deps.headInfo.bind(deps) } : {}),
628
+ platform,
629
+ now: () => deps.now(),
630
+ };
631
+ /** SD-P4-6: why `entry` no longer names the approved repository (a phrase after "it"), or undefined. */
632
+ const identityProblem = (entry: RepoApproval): Promise<string | undefined> => verifyIdentity(entry, identityDeps);
633
+
634
+ /**
635
+ * Rule 3 (SD-P4-5, -6): undefined unless parents are configured and the text equals an approved path; nothing else is looked
636
+ * at before that text match. Then, without git, the protected locations; then the identity check; then `locate`. `admit` runs
637
+ * the gate on an admission (exclusion and the parent rules win); a refusal here ends admission (rule 2 never overturns it).
638
+ */
639
+ const ruleThree = async (shown: string): Promise<Admission | undefined> => {
640
+ const entry = approvalFor(shown, approvedNow());
641
+ if (entry === undefined) return undefined;
642
+ const real = canonical(shown);
643
+ if (real === null) return refuseFinal(`root=${shown} is the approved repository ${entry.path}, but it no longer resolves: no work root.`);
644
+ const placed = protectedProblem(shown, real);
645
+ if (placed !== undefined) return refuseFinal(`root=${shown} is the approved repository ${entry.path}, but it ${placed}: no work root.`);
646
+ const problem = await identityProblem(entry);
647
+ if (problem !== undefined) {
648
+ return refuseFinal(`root=${shown} is the approved repository ${entry.path}, but it ${problem}: no work root. Only the user can approve it again (/router approve ${entry.path}).`);
649
+ }
650
+ // Phase 4 QA (m1): both are `realpath` outputs; the directory verified above is the one bound below, byte for byte (a case
651
+ // variant on a case-sensitive NTFS folder is another directory).
652
+ if (real !== entry.path) return refuseFinal(`root=${shown} is the approved repository ${entry.path}, but it now resolves to ${real}: no work root.`);
653
+ const located = await locate(shown, entry.path, entry.path);
654
+ if (!located.ok) return located;
655
+ return { ok: true, location: { ...located.location, approval: entry.path } };
656
+ };
657
+
658
+ /** Rule 1 for `shown`, already placed 1..depth below `parent` by its text. */
659
+ const belowParent = async (shown: string, parent: string): Promise<Admission> => {
660
+ const textExcluded = excludedText(shown);
661
+ if (textExcluded !== undefined) return refuseFinal(`root=${shown} is excluded by routing.repoExclude (${textExcluded}): no work root.`);
662
+ const realParent = canonical(parent);
663
+ if (realParent === null) return refuse(`root=${shown}: the routing.repoParents entry ${parent} does not resolve: no work root.`);
664
+ if (!deps.isDirectory(shown)) return refuse(`root=${shown} is not a directory: no work root.`);
665
+ const real = canonical(shown);
666
+ if (real === null) return refuse(`root=${shown} does not resolve: no work root.`);
667
+ const levels = levelsBelow(text(real), text(realParent));
668
+ if (levels === undefined || levels === 0) return refuseFinal(`root=${shown} leads outside ${parent} through a link (it resolves to ${real}): no work root.`);
669
+ const excluded = excludedText(real);
670
+ if (excluded !== undefined) return refuseFinal(`root=${shown} is excluded by routing.repoExclude (${excluded}): no work root.`);
671
+ if (!(await isToplevel(real))) return refuse(`root=${shown} is not the top level of a git repository: no work root.`);
672
+ return locate(shown, real, real);
673
+ };
674
+
675
+ /** Rule 1: undefined when the text lies below no parent. A final refusal under any parent ends the rule. */
676
+ const ruleOne = async (shown: string): Promise<Admission | undefined> => {
677
+ const rootText = text(shown);
678
+ let first: Admission | undefined;
679
+ for (const parent of parents) {
680
+ const levels = levelsBelow(rootText, text(parent));
681
+ if (levels === undefined) continue;
682
+ let result: Admission;
683
+ if (levels === 0) result = refuseFinal(`root=${shown} is itself a parent in routing.repoParents; repositories are admitted ${range} below a parent: no work root.`);
684
+ else if (levels > depth) result = refuse(`root=${shown} is ${String(levels)} levels below ${parent}; repositories are admitted ${range} below a parent (routing.repoDepth).`);
685
+ else result = await belowParent(shown, parent);
686
+ if (result.ok || finals.has(result)) return result;
687
+ first ??= result;
688
+ }
689
+ return first;
690
+ };
691
+
692
+ /**
693
+ * Phase 4 QA (M1): whether the canonical `repository` lies 1..depth segments below a parent (the parent's text or its canonical
694
+ * form). False with no parents.
695
+ */
696
+ const insideParents = (repository: string): boolean => {
697
+ const repoText = text(repository);
698
+ return parents.some((parent) => {
699
+ const realParent = canonical(parent);
700
+ const forms = realParent === null ? [text(parent)] : [text(parent), text(realParent)];
701
+ return forms.some((form) => {
702
+ const levels = levelsBelow(repoText, form);
703
+ return levels !== undefined && levels >= 1 && levels <= depth;
704
+ });
705
+ });
706
+ };
707
+
708
+ /**
709
+ * Rule 2: undefined when no repository in `known` lists `shown` as text (or none that may: see below).
710
+ *
711
+ * Phase 4 QA (M1): what backs the admission is the repository that LISTS `shown` (git's main worktree, canonical), never the
712
+ * known entry's text: a known linked worktree of an approved repository lists that repository. Unless that repository is the
713
+ * session repository (`session`, or the known entry is the session repository itself), it must be an approved path whose
714
+ * approval applies now and whose identity holds (`verifyIdentity`), and the binding is then tagged with it; or it must lie
715
+ * below a parent. Anything else skips the known entry: with no parents, only the session repository lists admissible worktrees.
716
+ */
717
+ const ruleTwo = async (shown: string, known: readonly string[], session: string | undefined): Promise<Admission | undefined> => {
718
+ const rootText = text(shown);
719
+ const approvals = approvedNow();
720
+ const sessionForms = session === undefined || rootTextProblem(session, platform) !== undefined
721
+ ? []
722
+ : [...new Set([text(session), text(canonical(session) ?? session)])];
723
+ for (const repo of unique(known)) {
724
+ if (rootTextProblem(repo, platform) !== undefined) continue;
725
+ let entries: WorktreeEntry[];
726
+ try {
727
+ entries = await worktrees(repo);
728
+ } catch {
729
+ continue;
730
+ }
731
+ const hit = entries.find((entry) => !entry.prunable && !entry.bare && text(entry.path) === rootText);
732
+ if (hit === undefined) continue;
733
+ const main = entries[0];
734
+ const repository = main === undefined ? null : canonical(main.path);
735
+ // `ruleTwoAt` refuses a main worktree that does not resolve.
736
+ if (repository === null) return ruleTwoAt(shown, rootText, entries);
737
+ const ofSession = sessionForms.includes(text(repo)) || sessionForms.includes(text(repository));
738
+ if (!ofSession) {
739
+ // Phase 4 (SD-P4-6, -12): an approved repository lists worktrees only while its approval applies and its identity holds.
740
+ const approved = approvalFor(repository, approvals);
741
+ if (approved !== undefined) {
742
+ if ((await identityProblem(approved)) !== undefined) continue;
743
+ const backed = await ruleTwoAt(shown, rootText, entries);
744
+ return backed.ok ? { ok: true, location: { ...backed.location, approval: approved.path } } : backed;
745
+ }
746
+ if (!insideParents(repository)) continue;
747
+ }
748
+ return ruleTwoAt(shown, rootText, entries);
749
+ }
750
+ return undefined;
751
+ };
752
+
753
+ /** Rule 2 once a known repository's worktree list (`entries`) lists `shown` as text. */
754
+ const ruleTwoAt = async (shown: string, rootText: string, entries: readonly WorktreeEntry[]): Promise<Admission> => {
755
+ // Only now, on a text match: the filesystem, then git.
756
+ const main = entries[0];
757
+ const repository = main === undefined ? null : canonical(main.path);
758
+ if (repository === null) return refuse(`root=${shown}: the main worktree of the repository that lists it does not resolve: no work root.`);
759
+ // QA round 1 (Phase 3 lot 1, F3): a worktree of an excluded repository is refused before git runs in it.
760
+ const excludedRepo = repositoryExcluded(shown, repository, main?.path);
761
+ if (excludedRepo !== undefined) return refuseFinal(excludedRepo);
762
+ const real = canonical(shown);
763
+ if (real === null) return refuse(`root=${shown} is a worktree of ${repository} but does not resolve: no work root.`);
764
+ let again: WorktreeEntry[];
765
+ try {
766
+ again = await worktrees(repository);
767
+ } catch {
768
+ return refuse(`root=${shown}: git worktree list failed in ${repository}: no work root.`);
769
+ }
770
+ if (!again.some((entry) => !entry.prunable && !entry.bare && samePath(entry.path, real))) {
771
+ return refuse(`root=${shown} is no longer a worktree of ${repository}: no work root.`);
772
+ }
773
+ if (!(await isToplevel(real))) return refuse(`root=${shown} is not the top level of a git repository: no work root.`);
774
+ // QA round 1 (F2): the re-check above resolves the listed path through the same link; confirm from the worktree side.
775
+ if (!(await sameRepository(real, repository))) {
776
+ const where = text(real) === rootText ? "but the directory there" : `but it leads through a link to ${real}, which`;
777
+ return refuseFinal(`root=${shown} is listed by git worktree list of ${repository}, ${where} belongs to another repository (git rev-parse --git-common-dir differs): no work root.`);
778
+ }
779
+ return locate(shown, real, repository);
780
+ };
781
+
782
+ /**
783
+ * QA round 1 (F1, F2, F4): the last check on every admission, whichever rule admitted it. Refuses when `routing.repoExclude`
784
+ * matches the text or the canonical work root, when the canonical work root is or contains a canonical parent, and when the
785
+ * text lies below a parent whose canonical form does not hold the canonical work root.
786
+ */
787
+ const gate = (shown: string, result: Admission): Admission => {
788
+ if (!result.ok) return result;
789
+ const real = result.location.worktree;
790
+ const excluded = excludedText(shown) ?? excludedText(real);
791
+ if (excluded !== undefined) return refuse(`root=${shown} is excluded by routing.repoExclude (${excluded}): no work root.`);
792
+ // QA round 1 (Phase 3 lot 1, F3): `locate` already refuses this; the gate keeps it whatever produced the location.
793
+ const excludedRepo = repositoryExcluded(shown, result.location.repository);
794
+ if (excludedRepo !== undefined) return refuse(excludedRepo);
795
+ const shownText = text(shown);
796
+ const realText = text(real);
797
+ for (const parent of parents) {
798
+ const parentText = text(parent);
799
+ const realParent = canonical(parent);
800
+ const realParentText = realParent === null ? parentText : text(realParent);
801
+ if (levelsBelow(parentText, shownText) !== undefined || levelsBelow(realParentText, realText) !== undefined) {
802
+ return refuse(`root=${shown} resolves to ${real}, which is or contains the routing.repoParents entry ${parent}; repositories are admitted ${range} below a parent: no work root.`);
803
+ }
804
+ if (levelsBelow(shownText, parentText) === undefined) continue;
805
+ if (realParent === null) return refuse(`root=${shown}: the routing.repoParents entry ${parent} does not resolve: no work root.`);
806
+ const levels = levelsBelow(realText, realParentText);
807
+ if (levels === undefined || levels === 0) return refuse(`root=${shown} leads outside ${parent} through a link (it resolves to ${real}): no work root.`);
808
+ }
809
+ return result;
810
+ };
811
+
812
+ const admit = async (root: string, known: readonly string[] = [], sessionRepository?: string): Promise<Admission> => {
813
+ const shown = root.trim();
814
+ const problem = rootTextProblem(shown, platform);
815
+ if (problem !== undefined) return refuse(`root=${shown} ${problem}: no work root.`);
816
+ // QA round 1 (F1): an excluded text is refused before any call, whichever rule would admit it.
817
+ const textExcluded = excludedText(shown);
818
+ if (textExcluded !== undefined) return refuse(`root=${shown} is excluded by routing.repoExclude (${textExcluded}): no work root.`);
819
+ const one = await ruleOne(shown);
820
+ if (one !== undefined && (one.ok || finals.has(one))) return gate(shown, one);
821
+ // Phase 4 (SD-P4-5): rule 3 runs before rule 2 for an approved path, so a replaced folder always meets the identity check.
822
+ const three = await ruleThree(shown);
823
+ if (three !== undefined) return gate(shown, three);
824
+ const two = await ruleTwo(shown, known, sessionRepository);
825
+ if (two !== undefined) return gate(shown, two);
826
+ if (one !== undefined) return one;
827
+ const hint = parents[0] === undefined ? "" : ` Clone it or add a worktree below ${parents[0]}.`;
828
+ return refuseOutside(shown, `root=${shown} is not below routing.repoParents (${parentList}) and is not a worktree of a repository in this session: no work root.${hint}`);
829
+ };
830
+
831
+ /**
832
+ * Phase 4: the final refusal of a text that no rule admitted and that lies below no parent. Only with parents configured, and
833
+ * only now, the canonical form is looked at (no git): another spelling of an approved path is refused naming that path, and a
834
+ * candidate outside every parent that passes the text checks carries `approvable`. With no parents, `reason` alone (I9).
835
+ */
836
+ const refuseOutside = (shown: string, reason: string): Admission => {
837
+ if (parents.length === 0) return refuse(reason);
838
+ const real = canonical(shown);
839
+ if (real === null || !deps.isDirectory(real)) return refuse(reason);
840
+ const approved = approvalFor(real, approvedNow());
841
+ if (approved !== undefined) {
842
+ return refuse(`root=${shown} resolves to the approved repository ${approved.path}, but only its approved path admits it: use root=${approved.path}: no work root.`);
843
+ }
844
+ if (rootTextProblem(real, platform) !== undefined || excludedText(real) !== undefined) return refuse(reason);
845
+ const forms = [text(shown), text(real)];
846
+ for (const parent of parents) {
847
+ const realParent = canonical(parent);
848
+ const parentForms = realParent === null ? [text(parent)] : [text(parent), text(realParent)];
849
+ for (const form of parentForms) {
850
+ if (forms.some((candidate) => levelsBelow(candidate, form) !== undefined || levelsBelow(form, candidate) !== undefined)) return refuse(reason);
851
+ }
852
+ }
853
+ return { ok: false, reason, approvable: real };
854
+ };
855
+
856
+ /** The directories a `repo=` scan descends into below `dir`: no dot-directories, no `node_modules`, nothing excluded (F7). */
857
+ const scanned = (dir: string): string[] =>
858
+ deps.readdir(dir)
859
+ .filter((child) => !child.startsWith(".") && !sameName(child, "node_modules"))
860
+ .map((child) => paths.join(dir, child))
861
+ .filter((path) => excludedText(path) === undefined);
862
+
863
+ /**
864
+ * `repo=X`: `<parent>\X`, then `<parent>\*\X` while the depth allows (one listing per level); admitted by rule 1, named X.
865
+ * At most {@link LOOKUP_MAX_DIRS} directories are visited (`capped`).
866
+ */
867
+ const lookup = async (name: string, opts: AdmissionFindOptions = {}): Promise<AdmissionLookup> => {
868
+ const { eligible } = opts;
869
+ /** QA round 1 (Phase 3 lot 1, F4): the caller's test, asked before anything runs on the candidate; a throw rejects. */
870
+ const allowed = (candidate: string): boolean => {
871
+ if (eligible === undefined) return true;
872
+ try {
873
+ return eligible(candidate) === true;
874
+ } catch {
875
+ return false;
876
+ }
877
+ };
878
+ const found: RepoLocation[] = [];
879
+ const refused: string[] = [];
880
+ const searched: string[] = [];
881
+ const seen = new Set<string>();
882
+ let visited = 0;
883
+ let capped = false;
884
+ for (const parent of parents) {
885
+ let frontier = [parent];
886
+ for (let level = 1; level <= depth; level++) {
887
+ searched.push(paths.join(parent, ...Array.from({ length: level - 1 }, () => "*"), name));
888
+ for (const dir of frontier) {
889
+ if (visited >= LOOKUP_MAX_DIRS) {
890
+ capped = true;
891
+ break;
892
+ }
893
+ visited++;
894
+ const candidate = paths.join(dir, name);
895
+ if (!deps.isDirectory(candidate)) continue;
896
+ if (!allowed(candidate)) {
897
+ refused.push(`root=${candidate} is not eligible for this lookup: skipped before any git call.`);
898
+ continue;
899
+ }
900
+ const result = await ruleOne(candidate);
901
+ if (result === undefined) continue;
902
+ if (!result.ok) {
903
+ refused.push(result.reason);
904
+ continue;
905
+ }
906
+ // Q10: the repository is named X, or the directory of this (linked) worktree is.
907
+ const byName = sameName(result.location.name, name);
908
+ if (!byName && !sameName(paths.basename(result.location.worktree), name)) continue;
909
+ // A repository counts once; a worktree directory counts once per worktree (two of them are ambiguous).
910
+ const key = byName ? text(result.location.repository) : `worktree:${text(result.location.worktree)}`;
911
+ if (seen.has(key)) continue;
912
+ seen.add(key);
913
+ found.push(result.location);
914
+ }
915
+ if (capped || level === depth) break;
916
+ frontier = frontier.flatMap(scanned);
917
+ }
918
+ if (capped) break;
919
+ }
920
+ return { found, refused, searched, capped };
921
+ };
922
+
923
+ /** The worktree of a repository (`worktrees`, git's order) for `branch`, or the only one; admitted (and gated) by `admit`. */
924
+ const pick = async (label: string, view: { readonly repository: string; readonly name: string; readonly worktrees: readonly WorktreeEntry[] }, branch: string | undefined, known: readonly string[], session: string): Promise<Admission> => {
925
+ const usable = view.worktrees.filter((entry) => !entry.bare && !entry.prunable);
926
+ const knownHere = unique([...known, view.repository]);
927
+ if (branch !== undefined) {
928
+ const on = usable.find((entry) => entry.branch === branch);
929
+ if (on === undefined) {
930
+ return refuse(`${label} branch=${branch}: no worktree of ${view.name} is on ${branch} (${listing(usable)}): no work root. Add a worktree on ${branch}, or name one with root="<path>".`);
931
+ }
932
+ return admit(on.path, knownHere, session);
933
+ }
934
+ if (usable.length === 0) return refuse(`${label}: ${view.name} has no worktree: no work root.`);
935
+ if (usable.length > 1) {
936
+ return refuse(`${label} has ${String(usable.length)} worktrees: ${listing(usable)}: no work root. Add branch=<name>, or name one with root="<path>".`);
937
+ }
938
+ return admit(usable[0]?.path ?? view.repository, knownHere, session);
939
+ };
940
+
941
+ const branchMismatch = (shown: string, location: RepoLocation, branch: string): string => {
942
+ const state = location.branch !== null ? `on ${location.branch} (HEAD ${short(location.head)})` : `detached at ${short(location.head)}`;
943
+ const on = location.worktrees.find((entry) => !entry.bare && entry.branch === branch);
944
+ const hint = on !== undefined
945
+ ? ` The worktree on ${branch} is ${display(on.path)} — use repo=${location.name} branch=${branch}.`
946
+ : ` No worktree of ${location.name} is on ${branch} (${listing(location.worktrees.filter((entry) => !entry.bare))}).`;
947
+ return `root=${shown} declares branch=${branch}, but that worktree is ${state}: no work root.${hint}`;
948
+ };
949
+
950
+ const resolve = async (decl: Declaration, ctx: DeclarationContext): Promise<Admission> => {
951
+ const root = decl.root?.trim() || undefined;
952
+ const repo = decl.repo?.trim() || undefined;
953
+ const rawBranch = decl.branch?.trim() || undefined;
954
+ const branch = rawBranch?.startsWith("refs/heads/") === true ? rawBranch.slice("refs/heads/".length) : rawBranch;
955
+ if (root === undefined && repo === undefined && branch === undefined) return refuse("no root=, repo= or branch= was declared: no work root.");
956
+ if (root !== undefined) {
957
+ const problem = rootTextProblem(root, platform);
958
+ if (problem !== undefined) return refuse(`root=${root} ${problem}: no work root.`);
959
+ }
960
+ if (repo !== undefined) {
961
+ const problem = repoNameProblem(repo);
962
+ if (problem !== undefined) return refuse(`repo=${repo} ${problem}: no work root.`);
963
+ }
964
+ if (branch !== undefined && (branch === "" || /[\u0000-\u001f]/.test(branch))) return refuse(`branch=${rawBranch ?? ""} is not a branch name: no work root.`);
965
+ const known = unique([ctx.sessionRepository, ...(ctx.known ?? [])]);
966
+
967
+ if (root !== undefined) {
968
+ // The named repository joins the known ones, so a worktree of it outside the parents is admitted (rule 2).
969
+ const named = repo === undefined ? [] : (await lookup(repo)).found;
970
+ const admitted = await admit(root, unique([...known, ...named.map((location) => location.repository)]), ctx.sessionRepository);
971
+ if (!admitted.ok) return admitted;
972
+ const location = admitted.location;
973
+ // Q10: repo= agrees with the repository's name or with the directory name of this very worktree.
974
+ if (repo !== undefined && !sameName(location.name, repo) && !sameName(paths.basename(location.worktree), repo)) {
975
+ const [only] = named;
976
+ let hint = ` Use repo=${location.name}, or name a worktree of ${repo} with root="<path>".`;
977
+ if (named.length === 1 && only !== undefined) {
978
+ hint = sameName(only.name, repo)
979
+ ? ` The repository ${repo} is ${only.repository} — use repo=${repo}${branch === undefined ? "" : ` branch=${branch}`}.`
980
+ : ` repo=${repo} is the work root ${only.worktree} (repository ${only.name}) — use root=${only.worktree}, or repo=${location.name} for this worktree.`;
981
+ }
982
+ return refuse(`root=${root} declares repo=${repo}, but that worktree belongs to repo=${location.name} (${location.repository}): no work root.${hint}`);
983
+ }
984
+ if (branch !== undefined && location.branch !== branch) return refuse(branchMismatch(root, location, branch));
985
+ return admitted;
986
+ }
987
+
988
+ if (repo !== undefined) {
989
+ const { found, refused, searched, capped } = await lookup(repo);
990
+ if (found.length === 0) {
991
+ const quoted = refused.slice(0, LOOKUP_MAX_NOTES);
992
+ const more = refused.length - quoted.length;
993
+ const notes = `${quoted.length === 0 ? "" : ` ${quoted.join(" ")}`}${more > 0 ? ` … and ${String(more)} more.` : ""}`;
994
+ const stopped = capped ? ` The search stopped after ${String(LOOKUP_MAX_DIRS)} directories.` : "";
995
+ return refuse(`repo=${repo} matches no repository below routing.repoParents (searched ${searched.length === 0 ? "nothing: none configured" : searched.join(", ")}): no work root.${notes}${stopped}`);
996
+ }
997
+ if (found.length > 1) {
998
+ // Q10: a match by a worktree's directory name is a work root, not a repository: list each as path, repository and branch.
999
+ if (found.some((location) => !sameName(location.name, repo))) {
1000
+ const roots = found.map((location) => `${location.worktree} (repository ${location.name}, ${location.branch !== null ? `branch ${location.branch}` : `detached at ${short(location.head)}`})`);
1001
+ return refuse(`repo=${repo} matches ${String(found.length)} work roots: ${joinAnd(roots)}: no work root. Name one with root="<path>".`);
1002
+ }
1003
+ return refuse(`repo=${repo} matches ${String(found.length)} repositories: ${joinAnd(found.map((location) => location.repository))}: no work root. Name one with root="<path>".`);
1004
+ }
1005
+ const [location] = found;
1006
+ if (location === undefined) return refuse(`repo=${repo}: no work root.`);
1007
+ // Q10: repo=X matched the directory of a linked worktree, not a repository name. Without branch= that worktree is the work root;
1008
+ // with branch= the repository it belongs to decides (`pick`): the worktree on that branch, whatever its directory is called.
1009
+ if (branch === undefined && !sameName(location.name, repo)) return admit(location.worktree, unique([...known, location.repository]), ctx.sessionRepository);
1010
+ return pick(`repo=${repo}`, location, branch, known, ctx.sessionRepository);
1011
+ }
1012
+
1013
+ // branch= alone: the session repository's worktree on that branch.
1014
+ let entries: WorktreeEntry[];
1015
+ try {
1016
+ entries = await worktrees(ctx.sessionRepository);
1017
+ } catch {
1018
+ return refuse(`branch=${branch ?? ""}: git worktree list failed in the session repository ${ctx.sessionRepository}: no work root.`);
1019
+ }
1020
+ const main = entries[0];
1021
+ const repository = main === undefined ? null : canonical(main.path);
1022
+ if (repository === null) return refuse(`branch=${branch ?? ""}: the session repository ${ctx.sessionRepository} does not resolve: no work root.`);
1023
+ const view = { repository, name: paths.basename(repository), worktrees: entries.filter((entry) => !entry.prunable) };
1024
+ return pick(`repo=${view.name}`, view, branch, known, ctx.sessionRepository);
1025
+ };
1026
+
1027
+ return { admit, resolve, find: lookup };
1028
+ }