opencode-model-router 2.7.0 → 2.9.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -11,6 +11,7 @@
11
11
  import type { AuthorityAction, RoleKind, RoleSpec } from "../../router/roles";
12
12
  import { DETECTIONS } from "../classify/types";
13
13
  import type { ClassifyResult, ClassifyTrace, Detection, Need, Risk, RouteLine, Scope, TaskFacts } from "../classify/types";
14
+ import type { RepoLocation } from "./admission";
14
15
 
15
16
  export interface DispatchGrant {
16
17
  actions: ReadonlySet<AuthorityAction>;
@@ -24,6 +25,11 @@ export interface DispatchGrant {
24
25
  * role max ∩ LOCAL — egress dropped too — and must never be granted through `grantFor(…, null)`.
25
26
  */
26
27
  workRoot: string | null;
28
+ /**
29
+ * Cross-repo (P1.4): where the work root lies — the repository, its name, the worktree and its branch — when admission bound it
30
+ * (`repo=` / `branch=`, or a `root=` below `routing.repoParents`). Absent when `workRoot` is null or the root was bound the old way.
31
+ */
32
+ readonly location?: RepoLocation;
27
33
  }
28
34
 
29
35
  /**
@@ -151,6 +157,7 @@ export function grantFor(
151
157
  widened: readonly AuthorityAction[],
152
158
  workRoot: string | null,
153
159
  routeLine?: Pick<RouteLine, "needs"> | null,
160
+ location?: RepoLocation,
154
161
  ): DispatchGrant {
155
162
  const denied = new Set<string>(role.authority.deny);
156
163
  const max = new Set<AuthorityAction>(role.authority.allow.filter((a) => KNOWN.has(a) && !denied.has(a)));
@@ -191,6 +198,8 @@ export function grantFor(
191
198
  actions: new Set(ACTION_ORDER.filter((a) => actions.has(a))),
192
199
  notes: [...notes, ...structural],
193
200
  workRoot,
201
+ // P1.4: the location travels only with a validated work root.
202
+ ...(workRoot !== null && location !== undefined ? { location } : {}),
194
203
  };
195
204
  }
196
205
 
@@ -212,9 +221,16 @@ function maxBuiltin(a: string, b: string): string {
212
221
  * - write without exec: deterministic → fast if risk low and scope single, else medium;
213
222
  * grader → medium; none → medium, heavy if risk high
214
223
  * - write + exec: deterministic → medium; grader / none → heavy
224
+ * Opt-in gated policy: grader → medium only below high risk with a gate at return.
215
225
  * An unknown detection is treated as `none` (the strictest column).
216
226
  */
217
- export function authorityFloor(grant: DispatchGrant, detection: Detection, risk: Risk, scope: Scope): string {
227
+ export function authorityFloor(
228
+ grant: DispatchGrant,
229
+ detection: Detection,
230
+ risk: Risk,
231
+ scope: Scope,
232
+ policy: { mode: "strict" | "gated"; gateAtReturn: boolean } = { mode: "strict", gateAtReturn: false },
233
+ ): string {
218
234
  const write = hasAny(grant.actions, WRITE);
219
235
  const exec = hasAny(grant.actions, EXEC);
220
236
  let floor = "fast";
@@ -224,7 +240,8 @@ export function authorityFloor(grant: DispatchGrant, detection: Detection, risk:
224
240
  else floor = risk === "high" ? "heavy" : "medium";
225
241
  }
226
242
  if (write && exec) {
227
- floor = maxBuiltin(floor, detection === "deterministic" ? "medium" : "heavy");
243
+ const gated = policy.mode === "gated" && detection === "grader" && risk !== "high" && policy.gateAtReturn;
244
+ floor = maxBuiltin(floor, detection === "deterministic" || gated ? "medium" : "heavy");
228
245
  }
229
246
  return floor;
230
247
  }
@@ -234,6 +251,8 @@ export function authorityFloor(grant: DispatchGrant, detection: Detection, risk:
234
251
  // ---------------------------------------------------------------------------
235
252
 
236
253
  export interface TierBoundsOptions {
254
+ /** Opt-in authority floor policy; absent keeps the strict floor and reasons unchanged. */
255
+ floorPolicy?: { mode: "strict" | "gated"; gateAtReturn: boolean };
237
256
  /** `enforcement.escalate.floorTier`, or null. */
238
257
  floorTier: string | null;
239
258
  /** The child's running tier on a resume (never move below it), or null. */
@@ -342,6 +361,7 @@ export function effectiveFactsOf(classified: ClassifiedDispatch): TaskFacts {
342
361
  * unknown ceiling or pin name is ignored.
343
362
  *
344
363
  * Reasons (deduplicated, in order of application):
364
+ * `gated:authority` the opt-in authority policy lowered the final floor compared with strict;
345
365
  * `floor:<source>` a source raised the floor (source = authority | floorTier | running);
346
366
  * `round:<source>:<from>-><to>` a built-in name missing from the order was rounded (source adds role | ceiling);
347
367
  * `unknown:<source>:<name>-><top>` an unknown floor name was placed at the top of the order (fail closed);
@@ -362,9 +382,11 @@ export function tierBounds(
362
382
  const reasons: string[] = [];
363
383
 
364
384
  const { risk, scope } = effectiveFactsOf(classified);
385
+ const authority = authorityFloor(grant, detection, risk, scope, opts.floorPolicy);
386
+ const strictAuthority = authorityFloor(grant, detection, risk, scope);
365
387
  const sources: Array<[FloorSource, string | null]> = [
366
388
  ["role", role.tierRange.floor],
367
- ["authority", authorityFloor(grant, detection, risk, scope)],
389
+ ["authority", authority],
368
390
  ["floorTier", opts.floorTier],
369
391
  ["running", opts.runningTier],
370
392
  ];
@@ -384,6 +406,11 @@ export function tierBounds(
384
406
  owner = source;
385
407
  }
386
408
  }
409
+ if (authority !== strictAuthority) {
410
+ const strictFloor = Math.max(0, ...sources.map(([source, tier]) =>
411
+ tier === null ? 0 : placeFloor(source === "authority" ? strictAuthority : tier, order).index));
412
+ if (floor < strictFloor) reasons.unshift("gated:authority");
413
+ }
387
414
  const lift = owner === "authority" ? "lift:authority" : "lift:floor";
388
415
 
389
416
  let ceiling = order.length - 1;
@@ -0,0 +1,325 @@
1
+ /**
2
+ * The read set R of a role dispatch beyond its work root W (`docs/design/cross-repo.md` §1 "R, read set", Phase 1 step P1.5):
3
+ * the worktrees of the orchestrator session's working set (P1.4), and every directory inside a repository whose top lies
4
+ * 1..`routing.repoDepth` segments below a `routing.repoParents` entry and that no `routing.repoExclude` glob matches.
5
+ *
6
+ * Synchronous on purpose: `roleAuthorityDecision` (compat/v2-hooks.ts) is pure and synchronous, so its predicate only uses
7
+ * `lstatSync` / `openSync` / `fstatSync`. A repository top is the nearest ancestor (below the parent, at most `repoDepth` deep)
8
+ * holding a `.git` with git's shape (QA-1 F3): a directory with a `HEAD` file and an `objects` directory or a `commondir` file, or
9
+ * a file (linked worktree, submodule) whose `gitdir:` target holds a `HEAD` file. No link counts (F5): `.git` and `HEAD` are
10
+ * checked with `lstat`, a `HEAD` is read from its opened descriptor only when `fstat` shows a regular file of at most 4 KiB, and a
11
+ * `gitdir:` is followed only when neither its text nor its `realpath` is a UNC or device path (no filesystem call may reach a
12
+ * remote host). A linked worktree is excluded with its main worktree (QA round 2 M1), found from the filesystem alone (I12: no git
13
+ * process): the gitdir's `commondir`, read and followed the same way; an unreadable or dangling one is no repository (fail closed).
14
+ * Its branch is best effort from `HEAD`: `ref: refs/heads/<x>` → `x` when `x` is a git ref name ("(unknown)"
15
+ * otherwise, F2), anything else → null (detached). Probes are cached 5 s per directory. Without parents and without a working set
16
+ * there is no predicate at all (I9: nothing beyond W).
17
+ */
18
+ import { closeSync, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
19
+ import { basename, dirname, join, resolve } from "node:path";
20
+ import { quoteGitPath } from "../../router/git-tools";
21
+ import { permissionMatches } from "../../router/read-only";
22
+ import type { RepoLocation } from "./admission";
23
+ import { insideWorkRoot } from "./work-root";
24
+ import { trimEndWhile } from "../../util/linear-trim";
25
+
26
+ /**
27
+ * QA-G-A2-2: a path segment that names git's metadata entry `.git` — compared case-insensitively (win32, and stricter
28
+ * elsewhere), with the trailing dots and spaces win32 drops and an NTFS `:stream` suffix removed (`.git.`, `.GIT`,
29
+ * `.git::$INDEX_ALLOCATION` all name `.git` there).
30
+ */
31
+ export function gitMetadataSegment(segment: string): boolean {
32
+ // Linear on purpose (CodeQL js/polynomial-redos): no `/[. ]+$/`, which is polynomial on a long run of " " or ".".
33
+ const colon = segment.indexOf(":");
34
+ const name = colon === -1 ? segment : segment.slice(0, colon);
35
+ return trimEndWhile(name, isDotOrSpace).toLowerCase() === ".git";
36
+ }
37
+
38
+ /** A trailing character win32 drops from a path segment: "." or " ". */
39
+ function isDotOrSpace(char: string): boolean {
40
+ return char === "." || char === " ";
41
+ }
42
+
43
+ /** A path written fully qualified: `X:\…` / `X:/…` on win32 (never drive- or root-relative), `/…` elsewhere. */
44
+ export function fullyQualifiedPath(path: string): boolean {
45
+ return process.platform === "win32" ? /^[A-Za-z]:[\\/]/.test(path) : path.startsWith("/");
46
+ }
47
+
48
+ /**
49
+ * QA-1 F1/F7: may a path reach R beyond W at all — `path` as the call names it, `target` its canonical form? Only a path written
50
+ * fully qualified (a relative one resolves against the session directory, which may itself be a repository of R: the role would
51
+ * read another checkout's file silently), unless `hostRelative` (the host's own Location-relative form of a path the call's
52
+ * `execute.before` already checked as written); and never `.git` or anything below it (its config can hold a credentialed remote).
53
+ * The decision (`roleAuthorityDecision`) and the read provenance line (index.ts) both use it.
54
+ */
55
+ export function readSetEligible(path: string, target: string, hostRelative = false): boolean {
56
+ if (!hostRelative && !fullyQualifiedPath(path)) return false;
57
+ return ![path, target].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
58
+ }
59
+
60
+ /** C0/C1 controls, format characters (bidi controls, zero-width), line/paragraph separators, unassigned, and `[` `]`. */
61
+ const UNSAFE_DISPLAY = /[\p{Cc}\p{Cf}\p{Cn}\p{Co}\p{Cs}\u2028\u2029[\]]/u;
62
+
63
+ /**
64
+ * QA-1 F2: text from the filesystem (a repository's name, its branch, a path) as it may be echoed into a refusal or a provenance
65
+ * line: unchanged when it holds nothing unsafe, else git's C-style quoting (`quoteGitPath`, every non-ASCII byte octal) with `[`
66
+ * and `]` as `\133` / `\135` too, so it can neither forge a `[router: …]` line nor reorder or hide the text around it.
67
+ */
68
+ export function displaySafe(text: string): string {
69
+ if (!UNSAFE_DISPLAY.test(text)) return text;
70
+ // `quoteGitPath` leaves a text with nothing it escapes unquoted (here: brackets only, no `"` or `\`): quote it, so `\133` is
71
+ // always an escape.
72
+ const quoted = quoteGitPath(text, true);
73
+ return (quoted.startsWith('"') ? quoted : `"${quoted}"`).replaceAll("[", "\\133").replaceAll("]", "\\135");
74
+ }
75
+
76
+ /**
77
+ * QA-1 F2: a branch name `git check-ref-format` accepts (`refs/heads/<x>`), restricted further to text without control, format or
78
+ * unassigned characters: no space, `~ ^ : ? * [ \`, `..`, `@{`, `//`; no component starting with `.` or ending with `.lock`;
79
+ * not ending with `/` or `.`; not `@`.
80
+ */
81
+ function refName(name: string): boolean {
82
+ if (name === "" || name === "@" || /[\s~^:?*[\\]|\.\.|@\{|\/\/|\/$|\.$/.test(name) || UNSAFE_DISPLAY.test(name)) return false;
83
+ return name.split("/").every((part) => part !== "" && !part.startsWith(".") && !part.endsWith(".lock"));
84
+ }
85
+
86
+ /** Where a path of R lies: the repository (its top directory), its name, and its checked-out branch (null: detached or unknown). */
87
+ export interface ReadSetRepository {
88
+ readonly repository: string;
89
+ readonly name: string;
90
+ readonly branch: string | null;
91
+ }
92
+
93
+ /** Membership in R beyond W of a CANONICAL target (`canonicalAuthorityPath`); undefined = not in R. */
94
+ export type InReadSet = (canonicalTarget: string) => ReadSetRepository | undefined;
95
+
96
+ /** The resolved `routing.repoParents` / `repoDepth` / `repoExclude`. */
97
+ export interface ReadSetConfig {
98
+ readonly parents: readonly string[];
99
+ readonly depth: number;
100
+ readonly exclude: readonly string[];
101
+ }
102
+
103
+ /** How long a `.git` probe or a parent's canonical form is reused, per directory. */
104
+ export const READ_SET_CACHE_MS = 5_000;
105
+ const CACHE_MAX = 256;
106
+ /** `HEAD` and a `.git` file are a line each; anything larger is not read. */
107
+ const SMALL_FILE_MAX = 4096;
108
+
109
+ export interface RepoProbeDeps {
110
+ /** The kind of the entry at `path` itself (`lstat`: a link is never followed, F5); undefined when there is none. */
111
+ entry(path: string): "file" | "directory" | "link" | undefined;
112
+ /**
113
+ * A small regular file's text, read from its opened descriptor (`fstat`: a regular file of at most 4 KiB, F5); undefined when
114
+ * missing, a link, not a regular file, or larger.
115
+ */
116
+ readSmall(path: string): string | undefined;
117
+ /** `realpathSync.native`; undefined when the path does not resolve. */
118
+ realpath(path: string): string | undefined;
119
+ now(): number;
120
+ }
121
+
122
+ export interface RepoProbe {
123
+ /** The repository whose top is `dir` (it holds `.git`), else undefined. Cached 5 s. */
124
+ repositoryAt(dir: string): ReadSetRepository | undefined;
125
+ /**
126
+ * QA round 2 (Phase 3 lot 1, M1): the canonical main worktree of the repository whose top is `dir` (`dir` itself unless its git
127
+ * directory names a `commondir`), else undefined. Cached 5 s with {@link repositoryAt}.
128
+ */
129
+ mainWorktreeAt(dir: string): string | undefined;
130
+ /** The canonical long form of a `routing.repoParents` entry, else undefined. Cached 5 s. */
131
+ canonicalParent(parent: string): string | undefined;
132
+ }
133
+
134
+ const remote = (path: string): boolean => /^[\\/]{2}/.test(path);
135
+
136
+ const defaultDeps: RepoProbeDeps = {
137
+ entry: (path) => {
138
+ try {
139
+ const stat = lstatSync(path);
140
+ return stat.isSymbolicLink() ? "link" : stat.isFile() ? "file" : stat.isDirectory() ? "directory" : undefined;
141
+ } catch {
142
+ return undefined;
143
+ }
144
+ },
145
+ readSmall: (path) => {
146
+ let fd: number | undefined;
147
+ try {
148
+ if (!lstatSync(path).isFile()) return undefined; // a link (junction, symlink) or anything but a regular file
149
+ fd = openSync(path, "r");
150
+ const stat = fstatSync(fd);
151
+ if (!stat.isFile() || stat.size > SMALL_FILE_MAX) return undefined;
152
+ const buffer = Buffer.alloc(stat.size);
153
+ const read = stat.size === 0 ? 0 : readSync(fd, buffer, 0, stat.size, 0);
154
+ return buffer.subarray(0, read).toString("utf8");
155
+ } catch {
156
+ return undefined;
157
+ } finally {
158
+ if (fd !== undefined) {
159
+ try {
160
+ closeSync(fd);
161
+ } catch {
162
+ // already closed
163
+ }
164
+ }
165
+ }
166
+ },
167
+ realpath: (path) => {
168
+ try {
169
+ return realpathSync.native(path);
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ },
174
+ now: () => Date.now(),
175
+ };
176
+
177
+ /** Shown for a `ref: refs/heads/<x>` whose `x` is not a git ref name (QA-1 F2): never echoed. */
178
+ export const UNKNOWN_BRANCH = "(unknown)";
179
+
180
+ /** `ref: refs/heads/<x>` → `x` when it is a ref name, else "(unknown)"; a detached or unreadable `HEAD` → null. */
181
+ function branchOf(head: string | undefined): string | null {
182
+ const line = head?.split(/\r?\n/, 1)[0]?.replace(/^[ \t]+|[ \t]+$/g, "");
183
+ const match = line === undefined ? null : /^ref:[ \t]*refs\/heads\/(.+)$/.exec(line);
184
+ if (match === null) return null;
185
+ return refName(match[1]!) ? match[1]! : UNKNOWN_BRANCH;
186
+ }
187
+
188
+ /** The synchronous, cached filesystem probe behind {@link readSetPredicate} (one per adapter instance). */
189
+ export function createRepoProbe(overrides: Partial<RepoProbeDeps> = {}): RepoProbe {
190
+ const deps: RepoProbeDeps = { ...defaultDeps, ...overrides };
191
+ const cache = new Map<string, { readonly at: number; readonly value: unknown }>();
192
+ const keyOf = (kind: string, path: string): string =>
193
+ `${kind}\u0000${process.platform === "win32" ? path.replaceAll("/", "\\").toLowerCase() : path}`;
194
+ const cached = <T>(key: string, compute: () => T): T => {
195
+ const hit = cache.get(key);
196
+ if (hit !== undefined && deps.now() - hit.at < READ_SET_CACHE_MS) return hit.value as T;
197
+ const value = compute();
198
+ cache.delete(key);
199
+ cache.set(key, { at: deps.now(), value });
200
+ while (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value!);
201
+ return value;
202
+ };
203
+ /** The first line of a small pointer file (`.git`, `commondir`), trimmed; undefined when unreadable (F5). */
204
+ const pointerLine = (path: string): string | undefined => deps.readSmall(path)?.split(/\r?\n/, 1)[0]?.trim();
205
+ /** `text` resolved against `base` and made canonical, never UNC or a device (no filesystem call may reach a remote host). */
206
+ const followed = (base: string, text: string): string | undefined => {
207
+ if (text === "" || remote(text)) return undefined;
208
+ const named = resolve(base, text);
209
+ if (remote(named)) return undefined;
210
+ const target = deps.realpath(named);
211
+ return target === undefined || remote(target) ? undefined : target;
212
+ };
213
+ /**
214
+ * QA round 2 (Phase 3 lot 1, M1): the main worktree of the checkout whose git directory is `gitDir`, from the filesystem alone
215
+ * (I12: no git process), as `mainWorktree()` (router/git-tools.ts) finds it: without a `commondir` file, `gitDir` is its own
216
+ * common directory; with one, the canonical directory it names. The main worktree is the directory holding that common
217
+ * directory when it is named `.git`, else the common directory itself (a bare repository, a submodule's git directory).
218
+ * Undefined (fail closed: not a repository of R) when the `commondir` is a link or unreadable, empty, remote, or names nothing.
219
+ */
220
+ const mainOf = (gitDir: string): string | undefined => {
221
+ const pointer = join(gitDir, "commondir");
222
+ const kind = deps.entry(pointer);
223
+ let common: string | undefined = gitDir;
224
+ if (kind !== undefined) {
225
+ const text = kind === "file" ? pointerLine(pointer) : undefined;
226
+ common = text === undefined ? undefined : followed(gitDir, text);
227
+ if (common === undefined || deps.entry(common) !== "directory") return undefined;
228
+ }
229
+ return basename(common).toLowerCase() === ".git" ? dirname(common) : common;
230
+ };
231
+ /**
232
+ * QA-1 F3/F5: the git directory of a repository whose top is `dir`, when its `.git` has git's shape and no link on the way — the
233
+ * `.git` directory itself (a `HEAD` file and an `objects` directory or a `commondir` file), or the `gitdir:` target of a `.git`
234
+ * file (canonical, never UNC or a device, holding a `HEAD` file) — and its main worktree (M1: `dir` itself for a `.git`
235
+ * directory without a `commondir`, else {@link mainOf}). Undefined: not a repository, or its main worktree is not found.
236
+ */
237
+ const gitDirOf = (dir: string): { readonly gitDir: string; readonly main: string } | undefined => {
238
+ const dotGit = join(dir, ".git");
239
+ const kind = deps.entry(dotGit);
240
+ if (kind === "directory") {
241
+ if (deps.entry(join(dotGit, "HEAD")) !== "file") return undefined;
242
+ const linked = deps.entry(join(dotGit, "commondir")) !== undefined;
243
+ if (!linked) return deps.entry(join(dotGit, "objects")) === "directory" ? { gitDir: dotGit, main: dir } : undefined;
244
+ const main = mainOf(dotGit);
245
+ return main === undefined ? undefined : { gitDir: dotGit, main };
246
+ }
247
+ if (kind !== "file") return undefined; // none, or a link (F5)
248
+ const line = pointerLine(dotGit);
249
+ const gitdir = line === undefined ? undefined : /^gitdir:\s*(.+)$/.exec(line)?.[1];
250
+ const target = gitdir === undefined ? undefined : followed(dir, gitdir);
251
+ if (target === undefined || deps.entry(join(target, "HEAD")) !== "file") return undefined;
252
+ const main = mainOf(target);
253
+ return main === undefined ? undefined : { gitDir: target, main };
254
+ };
255
+ const probed = (dir: string): { readonly repository: ReadSetRepository; readonly main: string } | undefined =>
256
+ cached(keyOf("repo", dir), () => {
257
+ if (remote(dir)) return undefined;
258
+ const git = gitDirOf(dir);
259
+ if (git === undefined) return undefined;
260
+ return { repository: { repository: dir, name: basename(dir), branch: branchOf(deps.readSmall(join(git.gitDir, "HEAD"))) }, main: git.main };
261
+ });
262
+ return {
263
+ repositoryAt: (dir) => probed(dir)?.repository,
264
+ mainWorktreeAt: (dir) => probed(dir)?.main,
265
+ canonicalParent: (parent) => cached(keyOf("parent", parent), () => (remote(parent) ? undefined : deps.realpath(parent))),
266
+ };
267
+ }
268
+
269
+ /**
270
+ * P1.5: the membership test of R beyond W, or undefined when R adds nothing (no parents, no working set: I9). A canonical target
271
+ * is in R when it lies inside a working-set worktree, or below a canonical parent inside a repository whose top is its nearest
272
+ * ancestor 1..`depth` segments below that parent, and no directory between that parent and the target — the target included —
273
+ * matches a `routing.repoExclude` glob (QA-1 F4: an excluded repository stays excluded through a repository nested in it; the
274
+ * max policy's matcher: separators unified, win32 case folding), nor its main worktree or a directory between a parent and that
275
+ * main worktree (QA round 2 M1: a linked worktree of an excluded repository is not in R, as admission refuses it).
276
+ */
277
+ export function readSetPredicate(config: ReadSetConfig, workingSet: readonly RepoLocation[], probe: RepoProbe): InReadSet | undefined {
278
+ if (config.parents.length === 0 && workingSet.length === 0) return undefined;
279
+ const depth = Math.max(1, Math.floor(config.depth));
280
+ const matches = (dir: string): boolean => config.exclude.some((glob) => permissionMatches(dir, glob));
281
+ const below = (parent: string, path: string): string[] =>
282
+ path.slice(parent.replace(/[\\/]+$/, "").length).split(/[\\/]/).filter((segment) => segment !== "");
283
+ const excluded = (parent: string, segments: readonly string[]): boolean => {
284
+ if (config.exclude.length === 0) return false;
285
+ for (let level = 1; level <= segments.length; level++) {
286
+ if (matches(join(parent, ...segments.slice(0, level)))) return true;
287
+ }
288
+ return false;
289
+ };
290
+ /**
291
+ * QA round 2 (Phase 3 lot 1, M1): a repository is excluded through its main worktree too — as admission refuses a work root in a
292
+ * linked worktree of an excluded repository (F3) — when a glob matches that main worktree, or a directory between a parent and
293
+ * it.
294
+ */
295
+ const mainExcluded = (main: string): boolean => {
296
+ if (config.exclude.length === 0) return false;
297
+ if (matches(main)) return true;
298
+ for (const text of config.parents) {
299
+ const parent = probe.canonicalParent(text);
300
+ if (parent !== undefined && insideWorkRoot(main, parent) && excluded(parent, below(parent, main))) return true;
301
+ }
302
+ return false;
303
+ };
304
+ return (target) => {
305
+ if (target === "" || /[*?\0]/.test(target) || remote(target)) return undefined;
306
+ for (const location of workingSet) {
307
+ if (insideWorkRoot(target, location.worktree)) return { repository: location.repository, name: location.name, branch: location.branch };
308
+ }
309
+ for (const text of config.parents) {
310
+ const parent = probe.canonicalParent(text);
311
+ if (parent === undefined || !insideWorkRoot(target, parent)) continue;
312
+ const segments = below(parent, target);
313
+ if (excluded(parent, segments)) continue;
314
+ for (let level = Math.min(depth, segments.length); level >= 1; level--) {
315
+ const top = join(parent, ...segments.slice(0, level));
316
+ const repository = probe.repositoryAt(top);
317
+ if (repository === undefined) continue;
318
+ const main = probe.mainWorktreeAt(top);
319
+ if (main === undefined || mainExcluded(main)) break; // M1: fail closed; never the enclosing repository instead
320
+ return repository;
321
+ }
322
+ }
323
+ return undefined;
324
+ };
325
+ }
@@ -7,9 +7,10 @@
7
7
  import { lstatSync, realpathSync } from "node:fs";
8
8
  import { join, posix, win32 } from "node:path";
9
9
  import { permissionMatches } from "../../router/read-only";
10
+ import { isPathSeparator, trimEndWhile } from "../../util/linear-trim";
10
11
 
11
12
  /** A win32 8.3 short-name segment (`PROGRA~1`, `MARQUI~1.TXT`): refused, never expanded (S11, P-11: fail closed). */
12
- const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})?(?=[\\/]|$)/;
13
+ export const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})?(?=[\\/]|$)/;
13
14
 
14
15
  /**
15
16
  * The canonical long form of a path a role session names (T2.3.1). The RAW path (a relative one joined to `base` as text) goes to
@@ -41,7 +42,8 @@ export function canonicalAuthorityPath(
41
42
  }
42
43
  if (!api.isAbsolute(text) && !api.isAbsolute(base)) return undefined;
43
44
  const sep = platform === "win32" ? "\\" : "/";
44
- let head = api.isAbsolute(text) ? text : `${base.replace(/[\\/]+$/, "")}${sep}${text}`;
45
+ let head = text;
46
+ if (!api.isAbsolute(text)) head = `${trimEndWhile(base, isPathSeparator)}${sep}${text}`;
45
47
  const tail: string[] = [];
46
48
  const missing = (error: unknown): boolean => {
47
49
  const code = (error as { code?: unknown } | null)?.code;
@@ -111,6 +113,14 @@ export interface VerificationScope {
111
113
  readonly refused?: string;
112
114
  }
113
115
 
116
+ /**
117
+ * Cross-repo P2.2 (SD2): the root the change capture of a dispatch observes — a role dispatch's work root W (even when the
118
+ * block's `cwd:` names a subdirectory of it, or was refused), else (a tier dispatch) the verification cwd, as before.
119
+ */
120
+ export function captureRootOf(scope: VerificationScope): string | undefined {
121
+ return scope.workRoot ?? scope.cwd;
122
+ }
123
+
114
124
  /**
115
125
  * #84 P3.3 DF2-F1: where a dispatch is verified. No root (a tier dispatch): the explicit `cwd`, exactly as before (I1). A role
116
126
  * dispatch's verification root (its bound work root, else its canonical session directory: QA-P33F1-1-1, 1-3): no `cwd` → the root;