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
@@ -275,8 +275,19 @@ function restrict(
275
275
  return { actions: kept, notes: [...new Set([...notes, ...extra])], workRoot: root };
276
276
  }
277
277
 
278
+ /** Cross-repo (P1.4): a grant's repository location travels with its work root, and only with a validated (non-null) one. */
279
+ function locationOf(from: Pick<DispatchGrant, "workRoot" | "location">, workRoot: string | null): Pick<DispatchGrant, "location"> {
280
+ return workRoot !== null && workRoot === from.workRoot && from.location !== undefined ? { location: from.location } : {};
281
+ }
282
+
283
+ /** {@link restrict} of a stored grant, keeping its location (P1.4). */
284
+ function withLocation(grant: DispatchGrant, from: DispatchGrant): DispatchGrant {
285
+ const kept = locationOf(from, grant.workRoot);
286
+ return kept.location === undefined ? grant : { ...grant, ...kept };
287
+ }
288
+
278
289
  function copyGrant(grant: DispatchGrant): DispatchGrant {
279
- return { actions: ordered(grant.actions), notes: [...grant.notes], workRoot: grant.workRoot };
290
+ return { actions: ordered(grant.actions), notes: [...grant.notes], workRoot: grant.workRoot, ...locationOf(grant, grant.workRoot) };
280
291
  }
281
292
 
282
293
  /**
@@ -288,7 +299,7 @@ function view(binding: Binding, max: ReadonlySet<AuthorityAction>): Binding {
288
299
  const { actions, notes, workRoot } = binding.grant;
289
300
  return {
290
301
  ...binding,
291
- grant: restrict(actions, notes, workRoot, max, binding.kind !== "unknown"),
302
+ grant: withLocation(restrict(actions, notes, workRoot, max, binding.kind !== "unknown"), binding.grant),
292
303
  candidates: [...binding.candidates],
293
304
  };
294
305
  }
@@ -404,7 +415,9 @@ export function registerPending(entry: PendingDispatch): void {
404
415
  }
405
416
  const keepClaim = previous !== undefined && previous.entry.nonce === entry.nonce;
406
417
  if (previous !== undefined && !keepClaim) remember(reg.retired, previous.entry.nonce, now, RETIRED_MAX);
407
- const grant: DispatchGrant = { ...copyGrant(entry.grant), workRoot: rootOrNull(entry.grant.workRoot) };
418
+ const { actions: copiedActions, notes: copiedNotes } = copyGrant(entry.grant);
419
+ const enteredRoot = rootOrNull(entry.grant.workRoot);
420
+ const grant: DispatchGrant = { actions: copiedActions, notes: copiedNotes, workRoot: enteredRoot, ...locationOf(entry.grant, enteredRoot) };
408
421
  const stored: PendingDispatch = Object.freeze({ ...entry, grant });
409
422
  remember(reg.pending, key, { entry: stored, start, claimedBy: keepClaim ? previous.claimedBy : undefined }, Infinity);
410
423
  for (const [oldestKey, oldest] of reg.pending) {
@@ -493,7 +506,7 @@ export function widen(
493
506
  added.push(action);
494
507
  }
495
508
  if (added.length > 0) notes.push(BINDING_NOTES.widened(added));
496
- const grant: DispatchGrant = { actions: ordered(next), notes: [...new Set(notes)], workRoot: before.workRoot };
509
+ const grant: DispatchGrant = { actions: ordered(next), notes: [...new Set(notes)], workRoot: before.workRoot, ...locationOf(slot.binding.grant, before.workRoot) };
497
510
  remember(reg.bound, childSessionID, { ...slot, binding: { ...slot.binding, grant } }, BOUND_MAX);
498
511
  return copyGrant(grant);
499
512
  }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Cross-repo P2.2 (docs/design/cross-repo-phase2-plan.md SD3, SD4): where each check of a role dispatch runs. A check's
3
+ * `cwd=` and `scope=` keys (parsed by `verify/dod.ts`) become a {@link CheckPlacement}; nothing calls this yet.
4
+ *
5
+ * - Inert for a tier dispatch (no work root W) and for a DoD whose checks carry neither key: `{}`.
6
+ * - `scope=`: `affected` or `full`, case-insensitive; anything else refuses (`why: "scope"`).
7
+ * - `cwd=` is refused first, before any filesystem probe, when it is a UNC path, has a `.git` segment (case-insensitive, with
8
+ * any trailing dots/spaces: `.git.`, `.git ` name `.git` on win32) or, on win32 only, an 8.3 short-name segment
9
+ * ({@link SHORT_NAME_SEGMENT}; `my-library~2` and a POSIX `backup~1` are ordinary names). A relative `cwd=` is resolved against
10
+ * W with {@link canonicalAuthorityPath} and must stay inside W ({@link insideWorkRoot}); one that leaves W refuses even when it
11
+ * lands in the read set R. An absolute `cwd=` is canonicalised and accepted inside W, else only when `deps.inReadSet` holds it
12
+ * (R is injected: `work-root.ts` must not import `read-set.ts`). A canonical path with a `.git` segment refuses too.
13
+ * - A check with only `scope=` is placed at the block base (`scope.cwd`).
14
+ * - `top` is the git top level of the placement (a `.git` walk, no git process). A placement inside W is never `foreign` (a
15
+ * nested `.git` in W — a vendored repository, a fixture — does not make it foreign; its own `top` is still reported); outside
16
+ * W, `foreign` = its top differs from W's top, or is unknown.
17
+ *
18
+ * The first offending check in index order refuses the whole DoD; no top is looked up for a refused DoD.
19
+ */
20
+ import { isAbsolute } from "node:path";
21
+ import type { DoD } from "../../verify/dod";
22
+ import { gitTopOf } from "../../verify/git-top";
23
+ import type { CheckPlacement, PlacementResolution } from "../../verify/types";
24
+ import { isSlash, trimEndWhile } from "../../util/linear-trim";
25
+ import { canonicalAuthorityPath, insideWorkRoot, SHORT_NAME_SEGMENT, type VerificationScope } from "./work-root";
26
+
27
+ /** What the resolver needs beyond the DoD and the scope; every member is a seam for tests. */
28
+ export interface CheckPlacementDeps {
29
+ /** The read-set predicate R (`read-set.ts` `readSetPredicate`) on a canonical absolute path. Absent: only W is allowed. */
30
+ readonly inReadSet?: (absPath: string) => boolean;
31
+ readonly canonical?: typeof canonicalAuthorityPath;
32
+ /** The git top level of a directory; default {@link gitTopOf}. */
33
+ readonly topOf?: (dir: string) => string | undefined;
34
+ }
35
+
36
+ /** A `.git` segment, case-insensitive, with any trailing dots/spaces (win32 strips them: `.git.` and `.git ` name `.git`). */
37
+ const GIT_SEGMENT = /(?:^|[\\/])\.git[. ]*(?=[\\/]|$)/i;
38
+
39
+ /** Refused before any filesystem probe: a UNC/device path, a `.git` segment, on win32 an 8.3 short-name segment. */
40
+ function lexicallyRefused(text: string): boolean {
41
+ if (/^[\\/]{2}/.test(text)) return true;
42
+ if (GIT_SEGMENT.test(text)) return true;
43
+ return process.platform === "win32" && SHORT_NAME_SEGMENT.test(text);
44
+ }
45
+
46
+ /** A comparison key for a top level: "/" separators, no trailing separator, case-folded on win32. */
47
+ function topKey(top: string): string {
48
+ const normalized = trimEndWhile(top.replace(/\\/g, "/"), isSlash); // linear: no `/\/+$/` (polynomial on a run of "/")
49
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
50
+ }
51
+
52
+ /** The canonical directory of a `cwd=` text, or undefined when it is refused. */
53
+ function placeCwd(
54
+ text: string,
55
+ workRoot: string,
56
+ canonical: typeof canonicalAuthorityPath,
57
+ inReadSet: ((absPath: string) => boolean) | undefined,
58
+ ): string | undefined {
59
+ if (lexicallyRefused(text)) return undefined;
60
+ const target = canonical(text, workRoot);
61
+ if (target === undefined || GIT_SEGMENT.test(target)) return undefined; // `.git.`, a link or a junction can land in `.git`
62
+ if (insideWorkRoot(target, workRoot)) return target;
63
+ if (!isAbsolute(text)) return undefined; // a relative path that leaves W, even into R
64
+ return inReadSet?.(target) === true ? target : undefined;
65
+ }
66
+
67
+ /**
68
+ * The placements of `dod.checks` for a dispatch verified in `scope`, index-aligned (undefined for a check with neither key),
69
+ * or the first refused check. `{}` for a tier scope or when no check carries a key.
70
+ */
71
+ export function resolveCheckPlacements(dod: DoD, scope: VerificationScope, deps: CheckPlacementDeps = {}): PlacementResolution {
72
+ const workRoot = scope.workRoot;
73
+ if (workRoot === undefined) return {};
74
+ if (!dod.checks.some((check) => check.cwd !== undefined || check.scope !== undefined)) return {};
75
+ const canonical = deps.canonical ?? canonicalAuthorityPath;
76
+ const topOf = deps.topOf ?? gitTopOf;
77
+ const base = scope.cwd ?? workRoot;
78
+
79
+ // Pass 1: validate every key in index order; the first offending check refuses, before any top lookup.
80
+ const resolved: ({ readonly cwd: string; readonly scope?: "affected" | "full" } | undefined)[] = [];
81
+ for (let index = 0; index < dod.checks.length; index++) {
82
+ const check = dod.checks[index]!;
83
+ if (check.cwd === undefined && check.scope === undefined) {
84
+ resolved.push(undefined);
85
+ continue;
86
+ }
87
+ let checkScope: "affected" | "full" | undefined;
88
+ if (check.scope !== undefined) {
89
+ const lower = check.scope.toLowerCase();
90
+ if (lower !== "affected" && lower !== "full") return { refused: { index, kind: check.kind, text: check.scope, why: "scope" } };
91
+ checkScope = lower;
92
+ }
93
+ let cwd = base;
94
+ if (check.cwd !== undefined) {
95
+ const placed = placeCwd(check.cwd, workRoot, canonical, deps.inReadSet);
96
+ if (placed === undefined) return { refused: { index, kind: check.kind, text: check.cwd, why: "outside" } };
97
+ cwd = placed;
98
+ }
99
+ resolved.push(checkScope === undefined ? { cwd } : { cwd, scope: checkScope });
100
+ }
101
+
102
+ // Pass 2: the top level of each placement, compared with W's. Inside W is never foreign, whatever `.git` lies below W.
103
+ const workTop = topOf(workRoot);
104
+ const workKey = workTop === undefined ? undefined : topKey(workTop);
105
+ const placements: (CheckPlacement | undefined)[] = resolved.map((entry) => {
106
+ if (entry === undefined) return undefined;
107
+ const top = topOf(entry.cwd);
108
+ const foreign = !insideWorkRoot(entry.cwd, workRoot) && (top === undefined || topKey(top) !== workKey);
109
+ return entry.scope === undefined ? { cwd: entry.cwd, top, foreign } : { cwd: entry.cwd, top, foreign, scope: entry.scope };
110
+ });
111
+ return { placements };
112
+ }
@@ -0,0 +1,500 @@
1
+ /**
2
+ * The `root` argument of `router_git_*` for role agents (`docs/design/cross-repo-phase3-plan.md`, item (b), "Contract:
3
+ * resolution order and texts", SD-3b-2..SD-3b-9; Phase 3 task 3b.2). `root` names another repository the dispatch may read: its
4
+ * absolute top-level path, or its bare name below `routing.repoParents` with the route-line `repo=` semantics (D20, no branch).
5
+ *
6
+ * Pure: every filesystem and git access goes through {@link GitRootDeps}. The session gates (step 1: a role session with an exact
7
+ * binding, a local read action in the grant, parents configured) belong to the caller; this module starts at step 2.
8
+ *
9
+ * 2. Text checks, no call: surrounding whitespace, more than {@link GIT_ROOT_MAX_LENGTH} characters, `rootTextProblem` (a path)
10
+ * or `repoNameProblem` (a name), any `.git` segment.
11
+ * 3. Text gate, no call on the value: equal to W → `{ ok: true, inWorkRoot: true }`; inside W → a `path=` hint; below a parent
12
+ * as configured, below a parent's canonical form (QA round 1 F1: a parent that is a junction, symlink or subst drive; the
13
+ * parents are trusted configuration, resolved once per call) or equal to a working-set worktree → continue; anything else is
14
+ * outside the read set. A junction from outside the parents into R is therefore refused without resolving it (SD-3b-3).
15
+ * 4. `realpath` and a directory; the canonical path is re-checked against W.
16
+ * 5. The canonical path must be in the read set R (filesystem only, no git: SD-3b-2).
17
+ * 6. It must be the top level of its checkout (`nearestCheckout`), else a `root=<top> path=<rel>` hint.
18
+ * 7. Admission (`admit`, with `known`; a path below a parent's canonical form is passed in the parent's configured form, the one
19
+ * admission's rule 1 knows); its reason keeps its text with `: no work root.` → `; nothing ran.` (SD-3b-9), control characters
20
+ * replaced, the leading value display-safe (N1) and every absolute path outside the read set replaced by
21
+ * {@link GIT_ROOT_OUTSIDE_PLACEHOLDER} (F6). The admitted worktree must be the canonical path (F6 of 3b: the git cwd is
22
+ * admission's `location.worktree`, never R's main worktree).
23
+ * 8. A name goes through `admission.find(name, { eligible })` first (F4: `eligible` is the text gate and R, so git never runs on a
24
+ * candidate outside R): no match (with the cap note when the lookup was capped, N2), several repositories or several worktrees
25
+ * are refused; the one worktree then goes through steps 3–7. A single match in a capped lookup is kept, as `repo=` does.
26
+ * 9. The deadline and the abort signal are checked before the filesystem steps and bound every admission call.
27
+ *
28
+ * Refusal reasons start at `root=<v> …`; the tool adds `[router_git] error: refused: ` (3b.3). Echoed values go through
29
+ * `displaySafe`; an admission sentence (step 7) goes through {@link sanitiseReason} instead, its leading value through `displaySafe`. On success the provenance line has the format of the read-provenance line (`index.ts`), built here so that
30
+ * `git-tools.ts` never imports `read-set.ts` (SD-3b-7). Nothing in `src/router/git-tools.ts` may import this module.
31
+ */
32
+ import { normalizeRootText } from "../wire/dispatch";
33
+ import { LOOKUP_MAX_DIRS, repoNameProblem, rootTextProblem, type Admission, type AdmissionService, type RepoLocation, type WorktreeEntry } from "./admission";
34
+ import { displaySafe, gitMetadataSegment } from "./read-set";
35
+
36
+ /** Step 2: the longest `root` accepted, in UTF-16 code units. */
37
+ export const GIT_ROOT_MAX_LENGTH = 4096;
38
+
39
+ // ── Text fragments (pinned by the docs-drift test, 3b.6) ─────────────────────────────────────────────────────────────────
40
+ /** Step 1 (the caller's session gates, `index.ts`): not a role session (D21). */
41
+ export const GIT_ROOT_ROLE_ONLY = "root is only for role agents (roles mode); this session inspects its own repository: omit root";
42
+ /** Step 1: no exact binding, no work root or no `router_git` in the grant: the tool's existing I9 text (`git-tools.ts`). */
43
+ export const GIT_ROOT_NO_WORK_ROOT = "this role session has no bound work root (I9)";
44
+ /** Step 1: the grant has `router_git` but no local read action (SD-3b-5); `<actions>` goes between the two parts. */
45
+ export const GIT_ROOT_NEEDS_READ = "root reads another repository and needs read, glob or grep in this dispatch's grant";
46
+ export const GIT_ROOT_GIT_ALONE = "router_git alone stays in the work root";
47
+ /** Step 1: `routing.repoParents` emptied by a hot reload after start. */
48
+ export const GIT_ROOT_NO_PARENTS = "root needs routing.repoParents (cross-repo is not configured); nothing ran";
49
+
50
+ /** Step 1: the refusal for a grant without a local read action. */
51
+ export function gitRootNeedsRead(actions: readonly string[]): string {
52
+ return `${GIT_ROOT_NEEDS_READ} (${actions.map(displaySafe).join(", ")}); ${GIT_ROOT_GIT_ALONE}`;
53
+ }
54
+
55
+ /** Step 2: closes every text refusal. */
56
+ export const GIT_ROOT_TEXT_HINT = "; pass the absolute top level of a repository or its name";
57
+ export const GIT_ROOT_WHITESPACE = "has leading or trailing whitespace";
58
+ export const GIT_ROOT_TOO_LONG = `is longer than ${String(GIT_ROOT_MAX_LENGTH)} characters`;
59
+ export const GIT_ROOT_GIT_SEGMENT = "names a .git directory";
60
+ /** Step 3. */
61
+ export const GIT_ROOT_INSIDE_WORK_ROOT = "is inside your work root";
62
+ export const GIT_ROOT_OMIT_ROOT = "omit root and pass path=";
63
+ export const GIT_ROOT_OUTSIDE_READ_SET = "is outside this dispatch's read set (the work root, the session's repositories and the repositories below";
64
+ /** Step 4. */
65
+ export const GIT_ROOT_NOT_DIRECTORY = "is not a directory; nothing ran";
66
+ /** Step 5. */
67
+ export const GIT_ROOT_RESOLVES_OUTSIDE = "outside this dispatch's read set; nothing ran";
68
+ /** Step 6. */
69
+ export const GIT_ROOT_INSIDE_REPOSITORY = "is inside the repository at";
70
+ /** Step 7: the admission phrase replaced, and its replacement. */
71
+ export const GIT_ROOT_ADMISSION_PHRASE = ": no work root.";
72
+ export const GIT_ROOT_NOTHING_RAN = "; nothing ran.";
73
+ export const GIT_ROOT_ADMITTED_WORKTREE = "the admitted worktree";
74
+ /** Step 8. */
75
+ export const GIT_ROOT_NO_MATCH = "matches no repository below routing.repoParents";
76
+ export const GIT_ROOT_PASS_ONE = "nothing ran. Pass root as one of these absolute paths";
77
+ /** Step 9. */
78
+ export const GIT_ROOT_TIMED_OUT = "resolving the repository timed out; nothing ran";
79
+ export const GIT_ROOT_ABORTED = "resolving the repository was aborted; nothing ran";
80
+ /** An admission call that rejected (it never should): fail closed. */
81
+ export const GIT_ROOT_FAILED = "resolving the repository failed; nothing ran";
82
+ /** Step 7 (QA round 1, F6): replaces an absolute path in an admission reason that is not in the read set. */
83
+ export const GIT_ROOT_OUTSIDE_PLACEHOLDER = "<outside the read set>";
84
+ /** Step 8 (QA round 1, N2): appended when the name lookup visited its maximum of directories (the route-line wording). */
85
+ export function gitRootCappedNote(maxDirs: number): string {
86
+ return `The search stopped after ${String(maxDirs)} directories`;
87
+ }
88
+ /** Success: the read-provenance line's fixed parts. */
89
+ export const GIT_ROOT_PROVENANCE_PREFIX = "[router: read from ";
90
+ export const GIT_ROOT_PROVENANCE_SUFFIX = " — read-only in this dispatch]";
91
+
92
+ /** Every fragment above, for the docs-drift test. */
93
+ export const GIT_ROOT_TEXTS: readonly string[] = [
94
+ GIT_ROOT_ROLE_ONLY,
95
+ GIT_ROOT_NEEDS_READ,
96
+ GIT_ROOT_GIT_ALONE,
97
+ GIT_ROOT_NO_PARENTS,
98
+ GIT_ROOT_TEXT_HINT,
99
+ GIT_ROOT_WHITESPACE,
100
+ GIT_ROOT_TOO_LONG,
101
+ GIT_ROOT_GIT_SEGMENT,
102
+ GIT_ROOT_INSIDE_WORK_ROOT,
103
+ GIT_ROOT_OMIT_ROOT,
104
+ GIT_ROOT_OUTSIDE_READ_SET,
105
+ GIT_ROOT_NOT_DIRECTORY,
106
+ GIT_ROOT_RESOLVES_OUTSIDE,
107
+ GIT_ROOT_INSIDE_REPOSITORY,
108
+ GIT_ROOT_NOTHING_RAN,
109
+ GIT_ROOT_ADMITTED_WORKTREE,
110
+ GIT_ROOT_NO_MATCH,
111
+ GIT_ROOT_PASS_ONE,
112
+ GIT_ROOT_TIMED_OUT,
113
+ GIT_ROOT_ABORTED,
114
+ GIT_ROOT_FAILED,
115
+ ];
116
+
117
+ export interface GitRootContext {
118
+ /** The dispatch's work root W. */
119
+ readonly workRoot: string;
120
+ /** `routing.repoParents`. */
121
+ readonly parents: readonly string[];
122
+ /** The worktrees of the orchestrator session's working set. */
123
+ readonly workingSet: readonly string[];
124
+ }
125
+
126
+ export interface GitRootDeps {
127
+ /** `realpathSync.native`; throws when the path does not resolve. */
128
+ realpath(path: string): string;
129
+ isDirectory(path: string): boolean;
130
+ /** The top of the nearest checkout holding `path` (canonical), or undefined. Filesystem only, no git. */
131
+ nearestCheckout(path: string): string | undefined;
132
+ /** Whether the canonical `path` lies in the dispatch's read set R. Filesystem only, no git. */
133
+ inReadSet(path: string): boolean;
134
+ readonly admission: Pick<AdmissionService, "admit" | "find">;
135
+ /** Repositories whose worktrees admission's rule 2 may admit: the session directory, the grant's repository, the working set. */
136
+ readonly known: readonly string[];
137
+ readonly platform: NodeJS.Platform;
138
+ readonly signal?: AbortSignal;
139
+ /** `Date.now()` value after which resolution stops (SD-3b-8: one deadline per call). */
140
+ readonly deadlineAt?: number;
141
+ }
142
+
143
+ export type GitRootResolution =
144
+ | { readonly ok: false; readonly reason: string }
145
+ | { readonly ok: true; readonly inWorkRoot: true }
146
+ | {
147
+ readonly ok: true;
148
+ readonly inWorkRoot: false;
149
+ /** The git cwd: admission's `location.worktree`. */
150
+ readonly root: string;
151
+ readonly repository: string;
152
+ readonly name: string;
153
+ /** null: detached. */
154
+ readonly branch: string | null;
155
+ /** W, for the executable guards (`workRootGuards(root) ∪ workRootGuards(W)`). */
156
+ readonly workRoot: string;
157
+ /** The first line of the tool's output. */
158
+ readonly provenance: string;
159
+ };
160
+
161
+ const IN_WORK_ROOT: GitRootResolution = { ok: true, inWorkRoot: true };
162
+
163
+ /** The read-provenance line for an admitted location (same format as `read`, `glob` and `grep`). */
164
+ export function gitRootProvenance(location: Pick<RepoLocation, "name" | "branch" | "worktree">): string {
165
+ return `${GIT_ROOT_PROVENANCE_PREFIX}${displaySafe(location.name)} (${displaySafe(location.branch ?? "detached")}) at ${displaySafe(location.worktree)}${GIT_ROOT_PROVENANCE_SUFFIX}`;
166
+ }
167
+
168
+ /** SD-3b-9: an admission reason with `: no work root.` replaced by `; nothing ran.`, or `; nothing ran.` appended. */
169
+ export function mapAdmissionReason(reason: string): string {
170
+ if (reason.includes(GIT_ROOT_ADMISSION_PHRASE)) return reason.replace(GIT_ROOT_ADMISSION_PHRASE, GIT_ROOT_NOTHING_RAN);
171
+ return `${reason.trimEnd().replace(/\.$/, "")}${GIT_ROOT_NOTHING_RAN}`;
172
+ }
173
+
174
+ /**
175
+ * QA round 1 (N1): admission's reasons are router-authored sentences that echo raw values; quoting the whole sentence would wrap
176
+ * it in `"…"` for one `[` in a path. Only the characters `displaySafe` treats as unsafe apart from `[` and `]` (control and format
177
+ * characters, newlines and line separators included, unassigned, private-use and surrogate code points) are replaced, by `?`, so
178
+ * the refusal stays one plain line.
179
+ */
180
+ export function sanitiseReason(reason: string): string {
181
+ return reason.replace(/[\p{Cc}\p{Cf}\p{Cn}\p{Co}\p{Cs}\u2028\u2029]/gu, "?");
182
+ }
183
+
184
+ /** A value with no path separator and no drive is a name. */
185
+ function isName(value: string): boolean {
186
+ return !/[\\/]/.test(value) && !/^[A-Za-z]:/.test(value);
187
+ }
188
+
189
+ /** Step 2: why `value` is refused on its text alone, or undefined. */
190
+ function textProblem(value: string, platform: NodeJS.Platform): string | undefined {
191
+ if (value !== value.trim()) return GIT_ROOT_WHITESPACE;
192
+ if (value.length > GIT_ROOT_MAX_LENGTH) return GIT_ROOT_TOO_LONG;
193
+ if (isName(value)) return repoNameProblem(value) ?? (gitMetadataSegment(value) ? GIT_ROOT_GIT_SEGMENT : undefined);
194
+ return rootTextProblem(value, platform) ?? (value.split(/[\\/]/).some(gitMetadataSegment) ? GIT_ROOT_GIT_SEGMENT : undefined);
195
+ }
196
+
197
+ /** Why step 9 stopped. */
198
+ export type GitRootStop = "timed out" | "aborted" | "failed";
199
+ type Stop = GitRootStop;
200
+
201
+ /** Step 9's refusal for `value` (shown as step 2 shows it). Also the caller's, for its own bounded calls (`index.ts`, QA F5). */
202
+ export function gitRootStopReason(value: string, stop: GitRootStop): string {
203
+ const shown = value.length > GIT_ROOT_MAX_LENGTH ? `${displaySafe(value.slice(0, 80))}…` : displaySafe(value);
204
+ return `root=${shown}: ${stop === "aborted" ? GIT_ROOT_ABORTED : stop === "timed out" ? GIT_ROOT_TIMED_OUT : GIT_ROOT_FAILED}`;
205
+ }
206
+
207
+ /**
208
+ * Step 9: `work`, unless the deadline passes or the signal aborts first; a rejection (or a throw) fails closed as `failed`.
209
+ * Exported for the caller's own asynchronous steps (`index.ts`: the orchestrator lookup, QA F5).
210
+ */
211
+ export function gitRootBounded<T>(
212
+ work: () => Promise<T>,
213
+ limits: { readonly signal?: AbortSignal; readonly deadlineAt?: number },
214
+ ): Promise<{ readonly value: T } | { readonly stop: GitRootStop }> {
215
+ if (limits.signal?.aborted === true) return Promise.resolve({ stop: "aborted" });
216
+ if (limits.deadlineAt !== undefined && Date.now() >= limits.deadlineAt) return Promise.resolve({ stop: "timed out" });
217
+ return new Promise((resolve) => {
218
+ let timer: ReturnType<typeof setTimeout> | undefined;
219
+ let settled = false;
220
+ const finish = (result: { readonly value: T } | { readonly stop: GitRootStop }): void => {
221
+ if (settled) return;
222
+ settled = true;
223
+ if (timer !== undefined) clearTimeout(timer);
224
+ limits.signal?.removeEventListener("abort", onAbort);
225
+ resolve(result);
226
+ };
227
+ const onAbort = (): void => finish({ stop: "aborted" });
228
+ if (limits.deadlineAt !== undefined) timer = setTimeout(() => finish({ stop: "timed out" }), Math.max(0, limits.deadlineAt - Date.now()));
229
+ limits.signal?.addEventListener("abort", onAbort, { once: true });
230
+ let started: Promise<T>;
231
+ try {
232
+ started = work();
233
+ } catch (error) {
234
+ started = Promise.reject(error instanceof Error ? error : new Error(String(error)));
235
+ }
236
+ started.then((result) => finish({ value: result }), () => finish({ stop: "failed" }));
237
+ });
238
+ }
239
+
240
+ export async function resolveGitRoot(value: string, ctx: GitRootContext, deps: GitRootDeps): Promise<GitRootResolution> {
241
+ const platform = deps.platform;
242
+ const win = platform === "win32";
243
+ const sep = win ? "\\" : "/";
244
+ const text = (path: string): string => normalizeRootText(path, platform);
245
+ const show = (path: string): string => displaySafe(path);
246
+ const refuse = (reason: string): GitRootResolution => ({ ok: false, reason });
247
+ const sameName = (a: string, b: string): boolean => (win ? a.toLowerCase() === b.toLowerCase() : a === b);
248
+ const native = (path: string): string => (win ? path.replace(/\//g, "\\") : path);
249
+ /** The segments of a path's text, separators unified, empty and `.` segments dropped (as `normalizeRootText`, case kept). */
250
+ const segments = (path: string): string[] => native(path.trim()).split(sep).filter((part) => part !== "" && part !== ".");
251
+ /** Whether `child` lies strictly below `parent` (both normalised text). */
252
+ const below = (child: string, parent: string): boolean =>
253
+ child !== parent && child.startsWith(parent.endsWith(sep) ? parent : parent + sep);
254
+ /** `child` relative to `parent` (native separators, `child`'s case), or undefined when it does not lie strictly below. */
255
+ const relativeBelow = (child: string, parent: string): string | undefined =>
256
+ below(text(child), text(parent)) ? segments(child).slice(segments(parent).length).join(sep) : undefined;
257
+
258
+ // Step 2.
259
+ const problem = textProblem(value, platform);
260
+ if (problem !== undefined) {
261
+ const shown = value.length > GIT_ROOT_MAX_LENGTH ? `${show(value.slice(0, 80))}…` : show(value);
262
+ return refuse(`root=${shown} ${problem}${GIT_ROOT_TEXT_HINT}`);
263
+ }
264
+ const label = show(value);
265
+ const stopped = (): Stop | undefined => {
266
+ if (deps.signal?.aborted === true) return "aborted";
267
+ if (deps.deadlineAt !== undefined && Date.now() >= deps.deadlineAt) return "timed out";
268
+ return undefined;
269
+ };
270
+ const stopReason = (stop: Stop): GitRootResolution => refuse(gitRootStopReason(value, stop));
271
+ /** Step 9: `work`, unless the deadline passes or the signal aborts first; a rejection fails closed. */
272
+ const bounded = <T>(work: () => Promise<T>): Promise<{ readonly value: T } | { readonly stop: Stop }> =>
273
+ gitRootBounded(work, {
274
+ ...(deps.signal === undefined ? {} : { signal: deps.signal }),
275
+ ...(deps.deadlineAt === undefined ? {} : { deadlineAt: deps.deadlineAt }),
276
+ });
277
+
278
+ /** The configured parents whose text is a usable path. */
279
+ const parents = ctx.parents.map((parent) => parent.trim()).filter((parent) => rootTextProblem(parent, platform) === undefined);
280
+ /**
281
+ * QA round 1 (F1): each parent's canonical form, when it differs from its text (a junction, symlink or subst drive). The parents
282
+ * are trusted configuration: resolved once per call, on first need; a parent that does not resolve keeps its text form only.
283
+ * The value itself is never resolved before the text gate.
284
+ */
285
+ let realParentsMemo: Array<{ readonly parent: string; readonly real: string }> | undefined;
286
+ const realParents = (): ReadonlyArray<{ readonly parent: string; readonly real: string }> => {
287
+ if (realParentsMemo !== undefined) return realParentsMemo;
288
+ const resolved: Array<{ readonly parent: string; readonly real: string }> = [];
289
+ for (const parent of parents) {
290
+ try {
291
+ const real = deps.realpath(parent);
292
+ if (typeof real === "string" && real !== "" && text(real) !== text(parent)) resolved.push({ parent, real });
293
+ } catch {
294
+ // The parent does not resolve: its text form only.
295
+ }
296
+ }
297
+ realParentsMemo = resolved;
298
+ return resolved;
299
+ };
300
+ type Gate =
301
+ | { readonly kind: "work-root" }
302
+ | { readonly kind: "inside"; readonly rel: string }
303
+ | { readonly kind: "outside" }
304
+ /** `admitAs`: the form admission's rule 1 knows (below a parent as configured). */
305
+ | { readonly kind: "member"; readonly admitAs: string };
306
+ /** Step 3: text only for `path`; at most the parents are resolved (F1). */
307
+ const textGate = (path: string): Gate => {
308
+ const pathText = text(path);
309
+ if (pathText === text(ctx.workRoot)) return { kind: "work-root" };
310
+ const insideW = relativeBelow(path, ctx.workRoot);
311
+ if (insideW !== undefined) return { kind: "inside", rel: insideW };
312
+ if (parents.some((parent) => below(pathText, text(parent)))) return { kind: "member", admitAs: path };
313
+ if (ctx.workingSet.some((worktree) => text(worktree) === pathText)) return { kind: "member", admitAs: path };
314
+ for (const { parent, real } of realParents()) {
315
+ const rel = relativeBelow(path, real);
316
+ if (rel !== undefined) return { kind: "member", admitAs: `${native(parent).replace(/[\\/]+$/, "")}${sep}${rel}` };
317
+ }
318
+ return { kind: "outside" };
319
+ };
320
+ /**
321
+ * QA round 1 (F4): the name lookup's `eligible`, asked before admission runs anything on a candidate: the text gate, then R on
322
+ * the canonical path (filesystem only, as step 5). The work root and paths inside it stay eligible (steps 3–4 answer them).
323
+ */
324
+ const eligible = (candidate: string): boolean => {
325
+ const gate = textGate(candidate);
326
+ if (gate.kind === "outside") return false;
327
+ if (gate.kind !== "member") return true;
328
+ const real = deps.realpath(candidate);
329
+ if (typeof real !== "string" || real === "") return false;
330
+ if (text(real) === text(ctx.workRoot) || relativeBelow(real, ctx.workRoot) !== undefined) return true;
331
+ return deps.inReadSet(real) === true;
332
+ };
333
+ /** QA round 1 (F6): absolute paths in a router-authored sentence (win32: drive or UNC; posix: rooted), after a boundary. */
334
+ const ABSOLUTE = win ? /(?<![^\s(=,;"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s,;()"'<>|]*/g : /(?<![^\s(=,;"'])\/[^\s,;()"'<>|]*/g;
335
+ /** A following space-separated chunk that holds a separator continues a path with spaces. */
336
+ const CONTINUED = /^ +[^\s,;()"'<>|]*[\\/][^\s,;()"'<>|]*/;
337
+ /** F6: `body` with every absolute path that is not in `safe`, not W or inside it, and not in R replaced by the placeholder. */
338
+ const redactOutside = (body: string, safe: readonly string[]): string => {
339
+ const safeTexts = new Set([...safe, ...parents, ...realParents().map((entry) => entry.real), ...ctx.workingSet, ...deps.known].map(text));
340
+ const keep = (path: string): boolean => {
341
+ if (safeTexts.has(text(path))) return true;
342
+ if (text(path) === text(ctx.workRoot) || relativeBelow(path, ctx.workRoot) !== undefined) return true;
343
+ try {
344
+ return deps.inReadSet(path) === true;
345
+ } catch {
346
+ return false;
347
+ }
348
+ };
349
+ const pattern = new RegExp(ABSOLUTE.source, "g");
350
+ let out = "";
351
+ let last = 0;
352
+ for (let match = pattern.exec(body); match !== null; match = pattern.exec(body)) {
353
+ let end = match.index + match[0].length;
354
+ for (let more = CONTINUED.exec(body.slice(end)); more !== null; more = CONTINUED.exec(body.slice(end))) end += more[0].length;
355
+ const token = body.slice(match.index, end).replace(/[.:]+$/, "");
356
+ end = match.index + token.length;
357
+ pattern.lastIndex = Math.max(end, match.index + 1);
358
+ if (token === "" || keep(token)) continue;
359
+ out += `${body.slice(last, match.index)}${GIT_ROOT_OUTSIDE_PLACEHOLDER}`;
360
+ last = end;
361
+ }
362
+ return `${out}${body.slice(last)}`;
363
+ };
364
+ /**
365
+ * Step 7's refusal (SD-3b-9, QA round 1 N1/F6): the admission reason mapped, control characters replaced, its leading
366
+ * `root=<the form admitted>` shown as the value passed (display-safe), every other absolute path outside R redacted.
367
+ */
368
+ const admissionRefusal = (reason: string, path: string, admitAs: string, real: string): string => {
369
+ const mapped = sanitiseReason(mapAdmissionReason(reason));
370
+ for (const form of admitAs === path ? [path] : [admitAs, path]) {
371
+ const prefix = `root=${form}`;
372
+ const next = mapped.charAt(prefix.length);
373
+ if (mapped.startsWith(prefix) && (next === "" || /[\s:;,.]/.test(next))) {
374
+ return `root=${show(path)}${redactOutside(mapped.slice(prefix.length), [path, admitAs, real])}`;
375
+ }
376
+ }
377
+ return redactOutside(mapped, [path, admitAs, real]);
378
+ };
379
+
380
+ /** Steps 3–7 for an absolute path; `extraKnown` joins `deps.known` for admission. */
381
+ const throughPath = async (path: string, extraKnown: readonly string[]): Promise<GitRootResolution> => {
382
+ const shown = show(path);
383
+ // Step 3: text only for the value (the parents may be resolved, F1).
384
+ const gate = textGate(path);
385
+ if (gate.kind === "work-root") return IN_WORK_ROOT;
386
+ if (gate.kind === "inside") return refuse(`root=${shown} ${GIT_ROOT_INSIDE_WORK_ROOT} ${show(ctx.workRoot)}; ${GIT_ROOT_OMIT_ROOT}${show(gate.rel)}`);
387
+ if (gate.kind === "outside") {
388
+ const list = parents.length === 0 ? "routing.repoParents (none configured)" : parents.map(show).join(", ");
389
+ return refuse(`root=${shown} ${GIT_ROOT_OUTSIDE_READ_SET} ${list}); nothing ran`);
390
+ }
391
+ const admitAs = gate.admitAs;
392
+
393
+ // Step 4: the filesystem, from here on.
394
+ const early = stopped();
395
+ if (early !== undefined) return stopReason(early);
396
+ let real: string;
397
+ try {
398
+ real = deps.realpath(path);
399
+ } catch {
400
+ return refuse(`root=${shown} ${GIT_ROOT_NOT_DIRECTORY}`);
401
+ }
402
+ let directory = false;
403
+ try {
404
+ directory = typeof real === "string" && real !== "" && deps.isDirectory(real);
405
+ } catch {
406
+ directory = false;
407
+ }
408
+ if (!directory) return refuse(`root=${shown} ${GIT_ROOT_NOT_DIRECTORY}`);
409
+ const realText = text(real);
410
+ const workForms = [ctx.workRoot];
411
+ if (realText !== text(ctx.workRoot) && relativeBelow(real, ctx.workRoot) === undefined) {
412
+ try {
413
+ const workReal = deps.realpath(ctx.workRoot);
414
+ if (typeof workReal === "string" && workReal !== "") workForms.push(workReal);
415
+ } catch {
416
+ // W does not resolve: its text form is the only one.
417
+ }
418
+ }
419
+ for (const form of workForms) {
420
+ if (realText === text(form)) return IN_WORK_ROOT;
421
+ const inside = relativeBelow(real, form);
422
+ if (inside !== undefined) return refuse(`root=${shown} ${GIT_ROOT_INSIDE_WORK_ROOT} ${show(ctx.workRoot)}; ${GIT_ROOT_OMIT_ROOT}${show(inside)}`);
423
+ }
424
+
425
+ // Step 5: R, filesystem only.
426
+ let member = false;
427
+ try {
428
+ member = deps.inReadSet(real);
429
+ } catch {
430
+ member = false;
431
+ }
432
+ if (!member) return refuse(`root=${shown} resolves to ${show(real)}, ${GIT_ROOT_RESOLVES_OUTSIDE}`);
433
+
434
+ // Step 6: the top level of its checkout.
435
+ let top: string | undefined;
436
+ try {
437
+ top = deps.nearestCheckout(real);
438
+ } catch {
439
+ top = undefined;
440
+ }
441
+ if (top !== undefined && text(top) !== realText) {
442
+ const rel = relativeBelow(real, top);
443
+ if (rel !== undefined) return refuse(`root=${shown} ${GIT_ROOT_INSIDE_REPOSITORY} ${show(top)}; pass root=${show(top)} and path=${show(rel)}`);
444
+ }
445
+
446
+ // Step 7: admission (git), then the admitted worktree must be this directory.
447
+ const known = [...deps.known];
448
+ for (const repository of extraKnown) if (!known.some((entry) => text(entry) === text(repository))) known.push(repository);
449
+ const answer = await bounded<Admission>(() => deps.admission.admit(admitAs, known));
450
+ if ("stop" in answer) return stopReason(answer.stop);
451
+ const admitted = answer.value;
452
+ if (!admitted.ok) return refuse(admissionRefusal(admitted.reason, path, admitAs, real));
453
+ const location = admitted.location;
454
+ if (text(location.worktree) !== realText) {
455
+ return refuse(`root=${shown}: ${GIT_ROOT_ADMITTED_WORKTREE} ${show(location.worktree)} resolves to ${show(real)}; nothing ran`);
456
+ }
457
+ return {
458
+ ok: true,
459
+ inWorkRoot: false,
460
+ root: location.worktree,
461
+ repository: location.repository,
462
+ name: location.name,
463
+ branch: location.branch,
464
+ workRoot: ctx.workRoot,
465
+ provenance: gitRootProvenance(location),
466
+ };
467
+ };
468
+
469
+ if (!isName(value)) return throughPath(value, []);
470
+
471
+ // Step 8: a name, through the `repo=` lookup.
472
+ const answer = await bounded(() => deps.admission.find(value, { eligible }));
473
+ if ("stop" in answer) return stopReason(answer.stop);
474
+ const { found, searched, capped } = answer.value;
475
+ if (found.length === 0) {
476
+ const where = searched.length === 0 ? "nothing: none configured" : searched.map(show).join(", ");
477
+ // QA round 1 (N2): the route line's cap note. A single match in a capped lookup is kept below, as `repo=` keeps it.
478
+ const stoppedNote = capped === true ? `. ${gitRootCappedNote(LOOKUP_MAX_DIRS)}` : "";
479
+ return refuse(`root=${label} ${GIT_ROOT_NO_MATCH} (searched ${where}); nothing ran${stoppedNote}`);
480
+ }
481
+ if (found.length > 1) {
482
+ return refuse(`root=${label} matches ${String(found.length)} repositories: ${found.map((location) => show(location.worktree)).join(", ")}; ${GIT_ROOT_PASS_ONE}`);
483
+ }
484
+ const [location] = found;
485
+ if (location === undefined) return refuse(`root=${label} ${GIT_ROOT_NO_MATCH}; nothing ran`);
486
+ let target = location.worktree;
487
+ // A repository named `value` (not the directory of one of its linked worktrees): its only usable worktree, or a refusal.
488
+ if (sameName(location.name, value)) {
489
+ const usable = location.worktrees.filter((entry) => !entry.bare && !entry.prunable);
490
+ const describe = (entry: WorktreeEntry): string =>
491
+ entry.branch !== null ? show(entry.branch) : entry.head === null ? "detached" : `detached at ${show(entry.head.slice(0, 7))}`;
492
+ if (usable.length > 1) {
493
+ const listing = usable.map((entry) => `${show(native(entry.path))} → ${describe(entry)}`).join("; ");
494
+ return refuse(`root=${label} has ${String(usable.length)} worktrees: ${listing}; ${GIT_ROOT_PASS_ONE}`);
495
+ }
496
+ const [only] = usable;
497
+ if (only !== undefined && text(only.path) !== text(location.worktree)) target = native(only.path);
498
+ }
499
+ return throughPath(target, [location.repository]);
500
+ }