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,1180 @@
1
+ /**
2
+ * src/verify/perimeter.ts
3
+ *
4
+ * Cross-repo P1.8 (docs/design/cross-repo.md, invariants I4, I8, I13): the verification perimeter P of a role dispatch. P is W's
5
+ * repository (the dispatch's verification root), plus the working-set worktrees of the orchestrator session other than W, plus
6
+ * the admitted repositories W links to (package links in W's top-level `node_modules` whose real path is outside W and is not a
7
+ * package store). P is fixed when the dispatch starts (I13): the store snapshots each extra root next to the change baseline
8
+ * (dispatch.ts beginDispatch), and the wiring snapshots it again at the gate (wiring.ts observeChange).
9
+ *
10
+ * Inert by default (I9): only a routed role dispatch whose grant has a location (cross-repo admission bound it), or whose
11
+ * orchestrator session's working set holds a root other than W, or (I13, QA round 2) with `routing.repoParents` set, can have a
12
+ * perimeter; every other dispatch plans none, so nothing else is snapshotted and no reason changes.
13
+ *
14
+ * Link targets (QA round 1, I11, I12), all without running git:
15
+ * - a link whose real path is neither below a `routing.repoParents` entry nor inside a working-set worktree is not in P, but is
16
+ * kept as an "unadmitted" root named by its basename (I8, I12; QA round 2), never dropped;
17
+ * - otherwise its repository's top level is found by walking up to the nearest `.git` entry (F3), and links are de-duplicated
18
+ * by top level, so several links into one monorepo are one root and one snapshot;
19
+ * - a top level is admitted when it lies 1..`routing.repoDepth` segments below a parent and no `routing.repoExclude` glob
20
+ * matches it or a directory between the parent and it, or when it is a working-set worktree (F4). A top level that is not
21
+ * admitted, or a link target that is not in a git repository, is kept as an "unadmitted" root: never snapshotted, and named in
22
+ * I8 as not observed;
23
+ * - P holds at most PERIMETER_MAX snapshotted roots, W included; the roots beyond are kept as "unobserved" roots, never dropped
24
+ * (F2), so the gate refuses a dispatch that ran unattributable writers.
25
+ *
26
+ * Declared dependency edges (cross-repo P3c, docs/design/cross-repo-phase3-plan.md SD-P3c-1, SD-P3c-3): `dependencyTargets`
27
+ * is the union of W's package links and its declared edges (edges.ts), each edge admitted by its text first
28
+ * (`resolveEdgeTarget`) with the same admission as a link (`admissionContext`). `planPerimeter` adds them to P as seed origin
29
+ * "edge" (a working-set root an edge covers gets `edged`; a link and an edge into one repository stay one "link" seed);
30
+ * edge-only seeds are never pinned (SD-P3c-2, F3) and not frozen for S11 yet (P3c.4). Consumer discovery (§6, P3c.5,
31
+ * SD-P3c-4, SD-P3c-5) reads the same edges in reverse: a working-set root whose declared edge resolves, as text, inside W's top
32
+ * is a consumer `{root, name?, via}` (a `node_modules` consumer keeps `{root, name?, entry}`, F6).
33
+ *
34
+ * P3c QA round 1: a spec past EDGE_SPEC_MAX characters, or a target past EDGE_WALK_MAX segments below its parent, is unadmitted
35
+ * with no filesystem call (M1); an unadmitted edge's name is `displaySafe` and capped, and `displayEdgeText` is how a router
36
+ * line shows any other edge text (M5); `planPerimeter` returns how the forward bounds cut W's edges, for its caller to log (m4).
37
+ */
38
+ import { type Dirent, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
39
+ import { lstat, opendir, readFile, readdir, readlink, realpath } from "node:fs/promises";
40
+ import * as path from "node:path";
41
+ import { permissionMatches } from "../router/read-only";
42
+ import type { RepoLocation } from "../routing/roles/admission";
43
+ import { displaySafe } from "../routing/roles/read-set";
44
+ import { routedRoleOf } from "../routing/wire/dispatch";
45
+ import { workingSetOf } from "../routing/wire/working-set";
46
+ import type { DispatchPerimeter, PerimeterSeed } from "./dispatch";
47
+ import {
48
+ type DeclaredEdge,
49
+ type EdgeIO,
50
+ type EdgeLimits,
51
+ type EdgeVia,
52
+ EDGE_LIMITS,
53
+ EDGE_SPEC_MAX,
54
+ EDGE_WORKSPACE_ENTRIES_MAX,
55
+ EDGE_WORKSPACE_PATTERNS_MAX,
56
+ SITE_PACKAGES_ENTRIES_MAX,
57
+ declaredEdges,
58
+ defaultEdgeIO,
59
+ isUncSpec,
60
+ prepareWorkspaceSegment,
61
+ workspacePatterns,
62
+ } from "./edges";
63
+ import { depthBelow, gitTopOf, perimeterKey } from "./git-top";
64
+ import { isStoreLikeLink } from "./reference";
65
+
66
+ /** P holds at most this many snapshotted roots, W included. */
67
+ export const PERIMETER_MAX = 16;
68
+
69
+ /** Cross-repo P3c (SD-P3c-4): at most this many unadmitted declared-edge targets are named; the others are counted only. */
70
+ export const EDGE_UNADMITTED_NAMES_MAX = 8;
71
+
72
+ /**
73
+ * Cross-repo P3c QA-1 M1: a declared edge's spec longer than EDGE_SPEC_MAX characters is never walked: its target is
74
+ * unadmitted, named from its text, with no filesystem call. Defined in edges.ts (QA-2 F-2: `declaredEdges` keys such a spec
75
+ * apart), re-exported here.
76
+ */
77
+ export { EDGE_SPEC_MAX };
78
+
79
+ /**
80
+ * Cross-repo P3c QA-1 M1: `resolveEdgeTarget` walks at most this many segments up from a target looking for its nearest
81
+ * existing ancestor; a target deeper than that below its parent (or its worktree) is unadmitted, with no filesystem call.
82
+ */
83
+ export const EDGE_WALK_MAX = 32;
84
+
85
+ /** Cross-repo P3c QA-1 M5: an unadmitted edge seed's name (the last segment of its text) is at most this many characters. */
86
+ export const EDGE_NAME_MAX = 64;
87
+
88
+ /** Cross-repo P3c QA-1 M5: `displayEdgeText` shows at most this many characters of an edge target's text. */
89
+ export const EDGE_TEXT_DISPLAY_MAX = 256;
90
+
91
+ /**
92
+ * `displaySafe(text)` in at most `max` characters, the ellipsis included: past it, the longest prefix of `text` (whole code
93
+ * points, at most `max` of them, so a 1 MiB text is never quoted whole) whose `displaySafe` form fits with a trailing "…".
94
+ */
95
+ function cappedDisplay(text: string, max: number): string {
96
+ if (text.length <= max) {
97
+ const safe = displaySafe(text);
98
+ if (safe.length <= max) return safe;
99
+ }
100
+ const points = Array.from(text.slice(0, max));
101
+ // A surrogate pair the slice cut leaves a lone high surrogate last: drop it.
102
+ const last = points[points.length - 1];
103
+ if (last !== undefined && /^[\uD800-\uDBFF]$/.test(last)) points.pop();
104
+ while (points.length > 0) {
105
+ const safe = displaySafe(points.join(""));
106
+ if (safe.length + 1 <= max) return `${safe}…`;
107
+ // Quoting expands the text (up to 16 characters per code point): shrink in proportion, by one code point at least.
108
+ points.length = Math.max(0, Math.min(points.length - 1, Math.floor((points.length * (max - 1)) / safe.length)));
109
+ }
110
+ return "…";
111
+ }
112
+
113
+ /**
114
+ * Cross-repo P3c QA-1 M5: an edge target's text (a declared spec, a path resolved from one, an unadmitted top level) as a router
115
+ * line may show it: `displaySafe` (no control, format or bidi character, no `[` `]`), at most EDGE_TEXT_DISPLAY_MAX characters.
116
+ * The text itself stays a path (a seed's `at`, a comparison key); only its display goes through here.
117
+ */
118
+ export function displayEdgeText(text: string): string {
119
+ return cappedDisplay(text, EDGE_TEXT_DISPLAY_MAX);
120
+ }
121
+
122
+ /** What link admission needs: `routing.repoParents`, `routing.repoDepth` and `routing.repoExclude`. */
123
+ export interface PerimeterAdmission {
124
+ readonly parents: readonly string[];
125
+ readonly depth: number;
126
+ /** `routing.repoExclude`: absolute globs (the max policy's matcher, `permissionMatches`). Absent: none. */
127
+ readonly exclude?: readonly string[];
128
+ }
129
+
130
+ /** A comparison key (moved to `git-top.ts` with `gitTopOf`; re-exported for existing importers). */
131
+ export { perimeterKey };
132
+
133
+ function insideOrEqual(child: string, parent: string): boolean {
134
+ const c = perimeterKey(child);
135
+ const p = perimeterKey(parent);
136
+ return c === p || c.startsWith(`${p}/`);
137
+ }
138
+
139
+ function readNames(dir: string): string[] {
140
+ try {
141
+ return readdirSync(dir);
142
+ } catch {
143
+ return [];
144
+ }
145
+ }
146
+
147
+ function canonical(dir: string): string {
148
+ try {
149
+ return realpathSync.native(dir);
150
+ } catch {
151
+ return path.resolve(dir);
152
+ }
153
+ }
154
+
155
+ /** The package entries of `<w>/node_modules`: the top level, and one level under `@scope`. Dot-entries are tool state. */
156
+ function packageEntries(w: string): string[] {
157
+ const modules = path.join(w, "node_modules");
158
+ const entries: string[] = [];
159
+ for (const name of readNames(modules)) {
160
+ if (name.startsWith(".")) continue;
161
+ const full = path.join(modules, name);
162
+ if (!name.startsWith("@")) {
163
+ entries.push(full);
164
+ continue;
165
+ }
166
+ for (const sub of readNames(full)) if (!sub.startsWith(".")) entries.push(path.join(full, sub));
167
+ }
168
+ return entries;
169
+ }
170
+
171
+ /**
172
+ * QA-1 #3: a link's text naming a UNC share or a device path (`\\server\share`, `\\?\…`, `//server/share`). Such a target is
173
+ * never resolved (no `realpath` on it, so no network access from the gate or the store): the link is skipped, as unreadable.
174
+ */
175
+ export function isUncLinkText(text: string): boolean {
176
+ return /^[\\/]{2}/.test(text);
177
+ }
178
+
179
+ /** The link primitives `linkedTargets` uses; injectable for tests (QA-1 #3). */
180
+ export interface LinkIO {
181
+ readonly lstat: (p: string) => { isSymbolicLink(): boolean };
182
+ readonly readlink: (p: string) => string;
183
+ readonly realpath: (p: string) => string;
184
+ }
185
+
186
+ const defaultLinkIO: LinkIO = {
187
+ lstat: (p) => lstatSync(p),
188
+ readlink: (p) => readlinkSync(p),
189
+ realpath: (p) => realpathSync.native(p),
190
+ };
191
+
192
+ /** The real paths of W's package links (symlinks, junctions) that point outside W and are not store-like, de-duplicated. */
193
+ export function linkedTargets(w: string, io: LinkIO = defaultLinkIO): string[] {
194
+ const targets = new Map<string, string>();
195
+ for (const entry of packageEntries(w)) {
196
+ let real: string;
197
+ try {
198
+ if (!io.lstat(entry).isSymbolicLink()) continue;
199
+ // QA-1 #3: the link text first; a UNC or device target is never realpath'ed (not admitted, as an unreadable link).
200
+ if (isUncLinkText(io.readlink(entry))) continue;
201
+ real = io.realpath(entry);
202
+ } catch {
203
+ continue; // Unreadable or dangling: it loads nothing.
204
+ }
205
+ if (insideOrEqual(real, w) || insideOrEqual(w, real) || isStoreLikeLink(real, process.platform)) continue;
206
+ if (!targets.has(perimeterKey(real))) targets.set(perimeterKey(real), real);
207
+ }
208
+ return [...targets.values()];
209
+ }
210
+
211
+ /** Cross-repo P3c (SD-P3c-3): the primitives `resolveEdgeTarget` uses once a target passed the text gates; injectable for tests. */
212
+ export interface EdgeTargetIO {
213
+ /** The canonical path of an existing `p` (follows links and junctions); throws when absent. */
214
+ readonly realpath: (p: string) => string;
215
+ /** The git top level of `dir`, strictly below `ceiling` when given (`gitTopOf`, no git run). */
216
+ readonly gitTop: (dir: string, ceiling?: string) => string | undefined;
217
+ }
218
+
219
+ /** Cross-repo P3c: every primitive `dependencyTargets` uses (`linkedTargets`, `declaredEdges`, `resolveEdgeTarget`). */
220
+ export interface DependencyIO extends LinkIO, EdgeIO, EdgeTargetIO {}
221
+
222
+ const defaultDependencyIO: DependencyIO = { ...defaultLinkIO, ...defaultEdgeIO, gitTop: (dir, ceiling) => gitTopOf(dir, ceiling) };
223
+
224
+ /** What `resolveEdgeTarget` needs beyond link admission. */
225
+ export interface EdgeContext extends AdmissionContext {
226
+ /** The root whose files declare the edges (W): an edge's spec resolves against `path.dirname(path.join(root, edge.from))`. */
227
+ readonly root: string;
228
+ /** Whether a top level is another worktree of W's repository (the same git common directory, QA-1 F11). */
229
+ readonly sameRepository: (top: string) => boolean;
230
+ }
231
+
232
+ /**
233
+ * Where one declared edge leads (SD-P3c-3):
234
+ * - `admitted`: the repository top level `top`, admitted as a link's would be (`admitTop`);
235
+ * - `unadmitted`: not in P, named (I8, I12): `at` is the target as text (the spec itself for a UNC or device spec) or, past the
236
+ * filesystem gates, its top level; `name` is the last segment of that text, never the canonical path;
237
+ * - `skipped`: not a perimeter root at all: a `node_modules` segment (links cover them), W's own repository (at, inside or above
238
+ * W's top, or another worktree of it), or a Python path line outside every parent (dropped silently).
239
+ */
240
+ export type EdgeResolution =
241
+ | { readonly status: "admitted"; readonly top: string }
242
+ | { readonly status: "unadmitted"; readonly at: string; readonly name: string }
243
+ | { readonly status: "skipped"; readonly reason: "nodeModules" | "insideW" | "sameRepository" | "pythonOutside" };
244
+
245
+ /** The last non-empty segment of a path as text, either separator (a UNC spec is never resolved, even on posix). */
246
+ function textName(at: string): string {
247
+ const segments = at.split(/[\\/]/).filter((segment) => segment !== "");
248
+ return segments[segments.length - 1] ?? at;
249
+ }
250
+
251
+ /**
252
+ * QA-1 M5: an unadmitted edge seed's name, shown in the scope note and the S11 caveat: the last segment of its text, `displaySafe`
253
+ * and at most EDGE_NAME_MAX characters (repository text never reaches a router line raw).
254
+ */
255
+ function edgeName(at: string): string {
256
+ return cappedDisplay(textName(at), EDGE_NAME_MAX);
257
+ }
258
+
259
+ function hasNodeModulesSegment(at: string): boolean {
260
+ return at.split(/[\\/]/).some((segment) => segment.toLowerCase() === "node_modules");
261
+ }
262
+
263
+ /**
264
+ * Cross-repo P3c.2b (SD-P3c-3, I11): admit one declared edge of `ctx.root` by its text first. The spec is repository text: it
265
+ * is resolved against the declaring file's directory as text, and gated as text before any filesystem call: a UNC or device
266
+ * spec, or a target outside every parent (either spelling) and every working-set worktree, is unadmitted; a `node_modules`
267
+ * segment or a target at, inside or above `wTop` (W's top level) is skipped. Only then is the nearest existing ancestor of the
268
+ * target below the parent (or inside the worktree) realpath'ed (an unbuilt `dist/` resolves to its repository); its canonical
269
+ * path must still be below a parent or inside a working-set worktree (a junction leading out is unadmitted); then its top level
270
+ * (`gitTop`, the walk stopping at the parent) must be admitted by `admitTop`, as a link target's is.
271
+ */
272
+ export function resolveEdgeTarget(
273
+ edge: DeclaredEdge,
274
+ ctx: EdgeContext,
275
+ wTop: string,
276
+ io: EdgeTargetIO = defaultDependencyIO,
277
+ ): EdgeResolution {
278
+ const python = edge.kind === "python";
279
+ // A UNC share or a device path: never resolved (QA-1 #3), so no network access.
280
+ if (edge.unc === true || isUncSpec(edge.spec)) {
281
+ return python ? { status: "skipped", reason: "pythonOutside" } : { status: "unadmitted", at: edge.spec, name: edgeName(edge.spec) };
282
+ }
283
+ const target = path.resolve(path.dirname(path.join(ctx.root, edge.from)), edge.spec);
284
+ const unadmittedText: EdgeResolution = { status: "unadmitted", at: target, name: edgeName(target) };
285
+ // QA-1 M1: an overlong spec is never walked (each step of the walk below is a filesystem call plus passes over the text).
286
+ if (edge.spec.length > EDGE_SPEC_MAX) return unadmittedText;
287
+ if (isUncSpec(target)) return python ? { status: "skipped", reason: "pythonOutside" } : unadmittedText;
288
+ if (hasNodeModulesSegment(target)) return { status: "skipped", reason: "nodeModules" };
289
+ if (insideOrEqual(target, wTop) || insideOrEqual(wTop, target)) return { status: "skipped", reason: "insideW" };
290
+ const parent = ctx.parentOf(target);
291
+ const worktree = ctx.worktreeOf(target);
292
+ if (parent === undefined && worktree === undefined) return python ? { status: "skipped", reason: "pythonOutside" } : unadmittedText;
293
+ // QA-1 M1: the walk below takes one step per segment between the target and its parent (or its worktree, included); past
294
+ // EDGE_WALK_MAX steps the target is unadmitted, before any filesystem call.
295
+ const steps = Math.max(
296
+ parent !== undefined ? depthBelow(target, parent) : 0,
297
+ worktree !== undefined ? depthBelow(target, worktree.worktree) + 1 : 0,
298
+ );
299
+ if (steps > EDGE_WALK_MAX) return unadmittedText;
300
+
301
+ // The nearest existing ancestor, never at or above the parent (nor above the worktree).
302
+ const within = (dir: string): boolean =>
303
+ (parent !== undefined && depthBelow(dir, parent) >= 1) || (worktree !== undefined && insideOrEqual(dir, worktree.worktree));
304
+ let real: string | undefined;
305
+ for (let dir = target; real === undefined && within(dir); dir = path.dirname(dir)) {
306
+ try {
307
+ real = io.realpath(dir);
308
+ } catch {
309
+ if (path.dirname(dir) === dir) break; // Missing: try its parent directory.
310
+ }
311
+ }
312
+ if (real === undefined) return unadmittedText; // Nothing exists there: nothing to observe.
313
+ // The canonical path stays below a parent or inside a working-set worktree: a junction leading out is not admitted.
314
+ const realParent = ctx.parentOf(real);
315
+ const realWorktree = ctx.worktreeOf(real);
316
+ if (realParent === undefined && realWorktree === undefined) return unadmittedText;
317
+ if (insideOrEqual(real, wTop) || insideOrEqual(wTop, real)) return { status: "skipped", reason: "insideW" };
318
+
319
+ const top = io.gitTop(real, realWorktree !== undefined ? path.dirname(realWorktree.worktree) : realParent);
320
+ if (top === undefined) return unadmittedText; // Not in a git repository: nothing to observe.
321
+ if (insideOrEqual(top, wTop) || insideOrEqual(wTop, top)) return { status: "skipped", reason: "insideW" };
322
+ // QA-1 m7: admission first, as for a link: an unadmitted top level never has its `.git` read (`sameRepository`).
323
+ if (!ctx.admitTop(top)) return { status: "unadmitted", at: top, name: edgeName(top) };
324
+ if (ctx.sameRepository(top)) return { status: "skipped", reason: "sameRepository" };
325
+ return { status: "admitted", top };
326
+ }
327
+
328
+ /**
329
+ * One target W depends on: a package link's real path (`linkedTargets`, admitted by the caller as before), an admitted edge's
330
+ * repository top level, or an unadmitted edge target (named, never snapshotted).
331
+ */
332
+ export type DependencyTarget =
333
+ | { readonly origin: "link"; readonly at: string }
334
+ | { readonly origin: "edge"; readonly at: string; readonly via: EdgeVia; readonly from: string }
335
+ | { readonly origin: "edge"; readonly at: string; readonly via: EdgeVia; readonly from: string; readonly name: string; readonly fixed: "unadmitted" };
336
+
337
+ /** The result of `dependencyTargets`. */
338
+ export interface DependencyTargets {
339
+ /**
340
+ * Link targets first (`linkedTargets`, unchanged), then edge targets: each once (by top level, or by text when unadmitted),
341
+ * none repeating a link target.
342
+ */
343
+ readonly targets: DependencyTarget[];
344
+ /** Unadmitted edge targets past EDGE_UNADMITTED_NAMES_MAX: counted, not named (SD-P3c-4). */
345
+ readonly unadmittedMore: number;
346
+ /** A `declaredEdges` bound cut the reading (SD-P3c-4). */
347
+ readonly incomplete: boolean;
348
+ }
349
+
350
+ /**
351
+ * Cross-repo P3c.2b (SD-P3c-1): the targets W depends on, the union of its package links and its declared edges (`declaredEdges`,
352
+ * admitted by text first, `resolveEdgeTarget`). `ctx.sameRepository` defaults to "shares W's git common directory".
353
+ * `planPerimeter` reads W's links and edges through it (P3c.3).
354
+ */
355
+ export function dependencyTargets(
356
+ w: string,
357
+ ctx: AdmissionContext & { readonly sameRepository?: (top: string) => boolean },
358
+ io: DependencyIO = defaultDependencyIO,
359
+ ): DependencyTargets {
360
+ const targets: DependencyTarget[] = linkedTargets(w, io).map((at) => ({ origin: "link", at }));
361
+ const declared = declaredEdges(w, io);
362
+ if (declared.edges.length === 0) return { targets, unadmittedMore: 0, incomplete: declared.incomplete };
363
+ const wTop = io.gitTop(w) ?? w;
364
+ let sameRepository = ctx.sameRepository;
365
+ if (sameRepository === undefined) {
366
+ const wCommon = commonDirOf(wTop);
367
+ sameRepository = (top: string): boolean => wCommon !== undefined && commonDirOf(top) === wCommon;
368
+ }
369
+ const edgeContext: EdgeContext = { ...ctx, root: w, sameRepository };
370
+ // An edge whose top level is already a link target is that link (SD-P3c-2: links first, one target). QA-2 F-2: by kind, so an
371
+ // unadmitted spelling of a path (an overlong spec, say) never shadows an admitted top level at that path: the admitted target
372
+ // takes the unadmitted one's place (its name, or its count). An unadmitted spelling of an admitted path adds nothing.
373
+ const seen = new Map<string, "admitted" | "named" | "counted">(targets.map((target) => [perimeterKey(target.at), "admitted"]));
374
+ let named = 0;
375
+ let unadmittedMore = 0;
376
+ for (const edge of declared.edges) {
377
+ const resolved = resolveEdgeTarget(edge, edgeContext, wTop, io);
378
+ if (resolved.status === "skipped") continue;
379
+ const at = resolved.status === "admitted" ? resolved.top : resolved.at;
380
+ const key = perimeterKey(at);
381
+ const before = seen.get(key);
382
+ if (before === "admitted" || (before !== undefined && resolved.status !== "admitted")) continue;
383
+ if (resolved.status === "admitted") {
384
+ const admitted: DependencyTarget = { origin: "edge", at, via: edge.via, from: edge.from };
385
+ const index = before === "named"
386
+ ? targets.findIndex((target) => "fixed" in target && perimeterKey(target.at) === key)
387
+ : -1;
388
+ if (index >= 0) {
389
+ named -= 1;
390
+ targets[index] = admitted;
391
+ } else {
392
+ if (before === "counted") unadmittedMore -= 1;
393
+ targets.push(admitted);
394
+ }
395
+ seen.set(key, "admitted");
396
+ } else if (named < EDGE_UNADMITTED_NAMES_MAX) {
397
+ named += 1;
398
+ targets.push({ origin: "edge", at, via: edge.via, from: edge.from, name: resolved.name, fixed: "unadmitted" });
399
+ seen.set(key, "named");
400
+ } else {
401
+ unadmittedMore += 1;
402
+ seen.set(key, "counted");
403
+ }
404
+ }
405
+ return { targets, unadmittedMore, incomplete: declared.incomplete };
406
+ }
407
+
408
+ /** Cross-repo P3a: the link primitives `crossLinkAliases` uses; injectable for tests. */
409
+ export interface AliasIO extends LinkIO {
410
+ /** The JS (not native) realpath: on win32 it keeps a junction's stored target text, the spelling vite uses (spike C4). */
411
+ readonly jsRealpath: (p: string) => string;
412
+ }
413
+
414
+ const defaultAliasIO: AliasIO = { ...defaultLinkIO, jsRealpath: (p) => realpathSync(p) };
415
+
416
+ /** Cross-repo QA-1 M2: the bounds of one `crossLinkAliases` call, each a total over the whole call. */
417
+ export interface AliasBounds {
418
+ /** `node_modules` directories read: the consumer's, its ancestors' up to its git top, then W's. */
419
+ readonly dirs: number;
420
+ /** Directory entries looked at, in those directories, their `@scope` directories and pnpm's `.pnpm` store. */
421
+ readonly entries: number;
422
+ /** pnpm `.pnpm/<entry>` directories looked at. */
423
+ readonly pnpm: number;
424
+ }
425
+
426
+ /** Cross-repo QA-1 M2: the default `crossLinkAliases` bounds. */
427
+ export const ALIAS_BOUNDS: AliasBounds = { dirs: 64, entries: 4000, pnpm: 256 };
428
+
429
+ /**
430
+ * QA-1 M2: the `node_modules` directories whose links can spell W for a consumer, de-duplicated, in order: the consumer's own;
431
+ * each ancestor's up to and including the consumer's git top (hoisted links, a check `cwd=` set to a workspace sub-package),
432
+ * none when it has no git top or is a UNC path; then W's own (its workspace links into W, reached through a consumer link).
433
+ */
434
+ function aliasModuleDirs(consumer: string, w: string): string[] {
435
+ const dirs = [path.resolve(consumer)];
436
+ const top = isUncLinkText(consumer) ? undefined : gitTopOf(consumer);
437
+ if (top !== undefined && insideOrEqual(dirs[0]!, top)) {
438
+ for (let at = dirs[0]!; perimeterKey(at) !== perimeterKey(top); ) {
439
+ const up = path.dirname(at);
440
+ if (up === at) break;
441
+ dirs.push(up);
442
+ at = up;
443
+ }
444
+ }
445
+ dirs.push(path.resolve(w));
446
+ const seen = new Set<string>();
447
+ const modules: string[] = [];
448
+ for (const dir of dirs) {
449
+ if (seen.has(perimeterKey(dir))) continue;
450
+ seen.add(perimeterKey(dir));
451
+ modules.push(path.join(dir, "node_modules"));
452
+ }
453
+ return modules;
454
+ }
455
+
456
+ /**
457
+ * Cross-repo P3a (SD-P3a-2 amended by the spike; QA-1 M2): W's top as a consumer's package links spell it. The links read: the
458
+ * top level and `@scope/*` of `<consumer>/node_modules`, of each ancestor's `node_modules` up to the consumer's git top, and of
459
+ * `<W>/node_modules`; then pnpm's `.pnpm/<entry>/node_modules/<name>` (and `@scope/*`) under each of them. For each link whose native
460
+ * real path lies inside W, the JS `fs.realpathSync` of the link (it keeps a junction's stored target text, the id vite gives the
461
+ * module), walked up to W's top when the link targets a directory below it. Never a spelling holding the substring
462
+ * `node_modules` (vitest skips those ids, case-sensitively); case-only variants are kept. A UNC link target is never resolved.
463
+ * Bounded (`bounds`: directories, entries and `.pnpm` entries read; CONSUMER_SCAN_MAX links) and fail-soft: an unreadable link
464
+ * or directory is skipped (the zero guard is the backstop).
465
+ */
466
+ export function crossLinkAliases(consumer: string, w: string, io: AliasIO = defaultAliasIO, bounds: AliasBounds = ALIAS_BOUNDS): string[] {
467
+ const aliases: string[] = [];
468
+ let realW: string;
469
+ try {
470
+ realW = io.realpath(w);
471
+ } catch {
472
+ return aliases;
473
+ }
474
+ let entries = 0;
475
+ let links = 0;
476
+ let pnpm = 0;
477
+ const spent = (): boolean => links > CONSUMER_SCAN_MAX || entries >= bounds.entries;
478
+ /** The names in `dir`, at most `cap` and what the entry budget has left; each name taken costs one entry. */
479
+ const namesOf = (dir: string, cap = Number.POSITIVE_INFINITY): string[] => {
480
+ const room = Math.min(cap, bounds.entries - entries);
481
+ if (room <= 0 || spent()) return [];
482
+ const names = readNames(dir).slice(0, room);
483
+ entries += names.length;
484
+ return names;
485
+ };
486
+ const consider = (entry: string): void => {
487
+ try {
488
+ if (!io.lstat(entry).isSymbolicLink()) return;
489
+ if (++links > CONSUMER_SCAN_MAX) return;
490
+ if (isUncLinkText(io.readlink(entry))) return;
491
+ const real = io.realpath(entry);
492
+ if (!insideOrEqual(real, realW)) return;
493
+ const rel = path.relative(realW, real);
494
+ const up = rel === "" ? [] : rel.split(/[\\/]+/).filter(segment => segment !== "").map(() => "..");
495
+ const alias = path.resolve(io.jsRealpath(entry), ...up);
496
+ // vitest drops every module id holding the substring "node_modules" (case-sensitive), so such a spelling matches nothing.
497
+ if (alias.includes("node_modules")) return;
498
+ if (!aliases.includes(alias)) aliases.push(alias);
499
+ } catch {
500
+ // Unreadable or dangling: it spells nothing.
501
+ }
502
+ };
503
+ /** The package entries of one `node_modules` directory: the top level, and one level under `@scope`. Dot-entries are tool state. */
504
+ const scanPackages = (modules: string): void => {
505
+ for (const name of namesOf(modules)) {
506
+ if (spent()) return;
507
+ if (name.startsWith(".")) continue;
508
+ const full = path.join(modules, name);
509
+ if (!name.startsWith("@")) {
510
+ consider(full);
511
+ continue;
512
+ }
513
+ for (const sub of namesOf(full)) {
514
+ if (spent()) return;
515
+ if (!sub.startsWith(".")) consider(path.join(full, sub));
516
+ }
517
+ }
518
+ };
519
+ const dirs = aliasModuleDirs(consumer, w).slice(0, Math.max(0, bounds.dirs));
520
+ for (const modules of dirs) scanPackages(modules);
521
+ // pnpm: `<modules>/.pnpm/<entry>/node_modules/<name>`, after every top level (the likelier spellings first).
522
+ for (const modules of dirs) {
523
+ const store = path.join(modules, ".pnpm");
524
+ const names = namesOf(store, bounds.pnpm - pnpm);
525
+ pnpm += names.length;
526
+ for (const name of names) if (!name.startsWith(".")) scanPackages(path.join(store, name, "node_modules"));
527
+ }
528
+ return aliases;
529
+ }
530
+
531
+ /**
532
+ * Cross-repo P2b.3: one working-set worktree whose `node_modules` links into W (`entry`); cross-repo P3c.5 (SD-P3c-5, F6): or
533
+ * one whose declared dependency edge leads into W (`via`). Exactly one of `entry` and `via` is set: a `node_modules` consumer
534
+ * keeps its shape `{root, name?, entry}`, an edge consumer is `{root, name?, via}`.
535
+ */
536
+ export interface PerimeterConsumer {
537
+ readonly root: string;
538
+ readonly name?: string;
539
+ /** The link, relative to `<root>/node_modules` (for example `lib` or `@scope/lib`), "/" separated. */
540
+ readonly entry?: string;
541
+ /**
542
+ * P3c.5: the edge, as the declaring file relative to `root` ("/" separated) and its fixed `EDGE_VIAS` label, for example
543
+ * `package.json dependencies (file:)`. Never the raw spec.
544
+ */
545
+ readonly via?: string;
546
+ }
547
+
548
+ /** Cross-repo P2b.3: the bound on `node_modules` LINK entries checked by `discoverConsumers`, per root (QA-1 #2, M2: plain entries are free). */
549
+ export const CONSUMER_SCAN_MAX = 2000;
550
+
551
+ /** Cross-repo M2: the hard bound on all `node_modules` entries (links or not) read per root; past it the root is incomplete. */
552
+ export const CONSUMER_READ_MAX = 20000;
553
+
554
+ /** Cross-repo QA-1 #2: the bound on W's package names looked up directly (W's own, plus its workspace packages'). */
555
+ export const CONSUMER_NAMES_MAX = 64;
556
+
557
+ /** Cross-repo QA-1 #2: the bound on the workspace `package.json` files read to learn W's package names. */
558
+ const WORKSPACE_MANIFESTS_MAX = 256;
559
+
560
+ /**
561
+ * Cross-repo P3c.5 (SD-P3c-4): the bounds of a working-set root's declared edges read in reverse for consumer discovery: at
562
+ * most WORKSPACE_MANIFESTS_MAX workspace packages (a package.json and a tsconfig.json each, plus the root's own files).
563
+ */
564
+ const CONSUMER_EDGE_LIMITS: EdgeLimits = Object.freeze({
565
+ ...EDGE_LIMITS,
566
+ workspaces: WORKSPACE_MANIFESTS_MAX,
567
+ files: Math.max(EDGE_LIMITS.files, 2 * WORKSPACE_MANIFESTS_MAX + 16),
568
+ });
569
+
570
+ /**
571
+ * Cross-repo P3c.5 (SD-P3c-5): how an edge consumer names its edge in the caveat: the fixed `EDGE_VIAS` label, plus the declaring
572
+ * file (relative to the consumer root, "/" separated) when the label does not already start with it. Never the raw spec.
573
+ */
574
+ function consumerVia(edge: DeclaredEdge): string {
575
+ return edge.via === edge.from || edge.via.startsWith(`${edge.from} `) ? edge.via : `${edge.via} in ${edge.from}`;
576
+ }
577
+
578
+ /** A `package.json` larger than this is not read for names. */
579
+ const MANIFEST_BYTES_MAX = 1024 * 1024;
580
+
581
+ /** A package name usable as a `node_modules` path: `name` or `@scope/name`, no dot-leading segment, no separators besides one "/". */
582
+ const PACKAGE_NAME = /^(?:@[a-z0-9_~-][a-z0-9._~-]*\/)?[a-z0-9_~-][a-z0-9._~-]*$/i;
583
+
584
+ /** One working-set root handed to `discoverConsumers`. */
585
+ export interface ConsumerRoot {
586
+ readonly root: string;
587
+ readonly name?: string;
588
+ }
589
+
590
+ /** Cross-repo QA-1 #2/#13: what `discoverConsumers` found, and the roots it could not finish (budget or deadline). */
591
+ export interface ConsumerDiscovery {
592
+ readonly consumers: PerimeterConsumer[];
593
+ readonly incomplete: ConsumerRoot[];
594
+ }
595
+
596
+ async function readManifest(dir: string): Promise<Record<string, unknown> | undefined> {
597
+ try {
598
+ const text = await readFile(path.join(dir, "package.json"), "utf8");
599
+ if (text.length > MANIFEST_BYTES_MAX) return undefined;
600
+ const parsed: unknown = JSON.parse(text);
601
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
602
+ return parsed as Record<string, unknown>;
603
+ } catch {
604
+ return undefined;
605
+ }
606
+ }
607
+
608
+ /** QA-2 F-1: the names in `dir`, in directory order, at most `max + 1` of them (so a caller sees a cut); rejects when unreadable. */
609
+ async function boundedListing(dir: string, max: number): Promise<string[]> {
610
+ const handle = await opendir(dir);
611
+ try {
612
+ const names: string[] = [];
613
+ for (let entry = await handle.read(); entry !== null && names.length <= max; entry = await handle.read()) names.push(entry.name);
614
+ return names;
615
+ } finally {
616
+ await handle.close();
617
+ }
618
+ }
619
+
620
+ /**
621
+ * The directories of one `workspaces` pattern (`workspaceDirs` rules), whether the listing was cut at `entries` names, and how
622
+ * many names it read: the async twin of edges.ts `matchWorkspace`. QA-2 F-1: the segment is prepared once, before the listing
623
+ * (one no entry name can match lists nothing), and the listing reads at most `entries + 1` names, so one synchronous filter
624
+ * never runs over an uncapped listing.
625
+ */
626
+ export async function workspaceListing(
627
+ w: string,
628
+ pattern: string,
629
+ limit: number,
630
+ entries: number,
631
+ ): Promise<{ dirs: string[]; cut: boolean; listed: number }> {
632
+ if (pattern.startsWith("!") || path.isAbsolute(pattern) || /^[\\/]/.test(pattern)) return { dirs: [], cut: false, listed: 0 };
633
+ const segments = pattern.split(/[\\/]/).filter((segment) => segment !== "" && segment !== ".");
634
+ if (segments.length === 0 || segments.some((segment) => segment === "..")) return { dirs: [], cut: false, listed: 0 };
635
+ const last = segments[segments.length - 1] ?? "";
636
+ const head = segments.slice(0, -1);
637
+ if (head.some((segment) => segment.includes("*"))) return { dirs: [], cut: false, listed: 0 };
638
+ if (!last.includes("*")) return { dirs: [path.join(w, ...segments)], cut: false, listed: 0 };
639
+ const matches = prepareWorkspaceSegment(last);
640
+ if (matches === undefined) return { dirs: [], cut: false, listed: 0 };
641
+ const base = path.join(w, ...head);
642
+ let children: string[];
643
+ try {
644
+ children = await boundedListing(base, entries);
645
+ } catch {
646
+ return { dirs: [], cut: false, listed: 0 };
647
+ }
648
+ // QA-1 C1: the linear matcher of edges.ts, never a regular expression built from the pattern; code-unit order, as edges.ts.
649
+ const dirs = children
650
+ .slice(0, entries)
651
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
652
+ .filter((child) => !child.startsWith(".") && child !== "node_modules" && matches(child))
653
+ .slice(0, limit)
654
+ .map((child) => path.join(base, child));
655
+ return { dirs, cut: children.length > entries, listed: Math.min(children.length, entries + 1) };
656
+ }
657
+
658
+ /**
659
+ * The directories of one `workspaces` pattern, inside W only: literal segments, and a wildcard (`*`, `**`) in the last segment
660
+ * only, matched one level deep. Negations, absolute paths, `..` and inner wildcards give none. At most `limit` directories, from
661
+ * a listing of at most `entries` names (QA-2 F-1). Exported for the agreement test with its synchronous twin, edges.ts
662
+ * `workspaceDirsSync` (P3c.1).
663
+ */
664
+ export async function workspaceDirs(
665
+ w: string,
666
+ pattern: string,
667
+ limit: number,
668
+ entries: number = SITE_PACKAGES_ENTRIES_MAX,
669
+ ): Promise<string[]> {
670
+ return (await workspaceListing(w, pattern, limit, entries)).dirs;
671
+ }
672
+
673
+ /**
674
+ * Cross-repo QA-1 #2: W's package names, looked up directly in each root's `node_modules`: the `name` of `<W>/package.json`
675
+ * and, when W is a workspace root, the `name` of each workspace package its `workspaces` lists. Bounded (CONSUMER_NAMES_MAX
676
+ * names, WORKSPACE_MANIFESTS_MAX manifests); `stop` ends the reading early (the deadline).
677
+ */
678
+ async function packageNamesOf(w: string, stop: () => boolean, onCut: () => void = () => undefined): Promise<string[]> {
679
+ const names = new Set<string>();
680
+ const take = (manifest: Record<string, unknown> | undefined): void => {
681
+ const name = manifest?.name;
682
+ if (typeof name === "string" && PACKAGE_NAME.test(name) && names.size < CONSUMER_NAMES_MAX) names.add(name);
683
+ };
684
+ const manifest = await readManifest(w);
685
+ if (manifest === undefined) return [];
686
+ take(manifest);
687
+ let read = 0;
688
+ let listed = 0;
689
+ // QA-1 M2: at most EDGE_WORKSPACE_PATTERNS_MAX patterns (each wildcard one is a directory listing), as edges.ts reads them;
690
+ // QA-2 F-1: their listings read at most EDGE_WORKSPACE_ENTRIES_MAX names in total, each at most SITE_PACKAGES_ENTRIES_MAX, as
691
+ // edges.ts. Fail-closed, as edges.ts marks its result incomplete: each of those cuts calls `onCut` (W's names may be short).
692
+ const patterns = workspacePatterns(manifest);
693
+ if (patterns.length > EDGE_WORKSPACE_PATTERNS_MAX) onCut();
694
+ for (const pattern of patterns.slice(0, EDGE_WORKSPACE_PATTERNS_MAX)) {
695
+ if (stop() || names.size >= CONSUMER_NAMES_MAX || read >= WORKSPACE_MANIFESTS_MAX) break;
696
+ const budget = Math.max(0, Math.min(SITE_PACKAGES_ENTRIES_MAX, EDGE_WORKSPACE_ENTRIES_MAX - listed));
697
+ if (budget === 0 && pattern.includes("*")) {
698
+ onCut(); // A wildcard needs a listing, and the total is spent.
699
+ continue;
700
+ }
701
+ const listing = await workspaceListing(w, pattern, WORKSPACE_MANIFESTS_MAX - read, budget);
702
+ listed += listing.listed;
703
+ if (listing.cut) onCut();
704
+ for (const dir of listing.dirs) {
705
+ if (stop() || names.size >= CONSUMER_NAMES_MAX || read >= WORKSPACE_MANIFESTS_MAX) break;
706
+ read += 1;
707
+ take(await readManifest(dir));
708
+ }
709
+ }
710
+ return [...names];
711
+ }
712
+
713
+ /**
714
+ * Cross-repo P2b.3 (docs/design/cross-repo.md §6, consumer discovery): the roots among `roots` whose `node_modules` hold a
715
+ * link whose real path is inside W or W itself. Only the given roots are read; async fs, no git; never throws. Per root
716
+ * (QA-1 #2): first a direct lookup of each of W's package names (`<root>/node_modules/<name>`, scoped names included; one
717
+ * lookup per name, outside the budget), then a scan of the entries `packageEntries` reads, spending at most `opts.maxEntries`
718
+ * (default CONSUMER_SCAN_MAX) on link entries and reading at most `opts.maxRead` (default CONSUMER_READ_MAX) entries per root
719
+ * (QA-2 M2). A root whose scan stops on either bound without finding a consumer is incomplete; so is
720
+ * every root not finished when `opts.signal` aborts (QA-1 #13, the gate deadline). A link whose text names a UNC or device
721
+ * path is never resolved (QA-1 #3). One entry per consumer (the first link found); both lists follow the order of `roots`.
722
+ *
723
+ * Cross-repo P3c.5 (SD-P3c-3..5): then, for a root with no `node_modules` link into W, (c) its declared dependency edges
724
+ * (`declaredEdges`, read in reverse with CONSUMER_EDGE_LIMITS: at most WORKSPACE_MANIFESTS_MAX workspace packages, EDGES_MAX
725
+ * edges): an edge whose spec, resolved as text against its declaring file's directory, lies inside W's top (W as given or
726
+ * canonical, its git top level) and not under a `node_modules` segment makes the root a consumer `{root, name?, via}` (F6: a
727
+ * `node_modules` consumer keeps `{root, name?, entry}`). Edge text is never resolved on the filesystem (I11): an edge spelling
728
+ * W only through a junction is not seen, unless the junction is a spelling of W's parent given in `opts.parents` (QA-1 m5: W's
729
+ * top is matched under every spelling of its parent). A root inside W's top (W's own repository) reads no edges. A root with no consumer
730
+ * whose edge reading a bound cut is incomplete, as one whose scan stopped on its budget.
731
+ */
732
+ export async function discoverConsumers(
733
+ w: string,
734
+ roots: readonly ConsumerRoot[],
735
+ opts?: {
736
+ maxEntries?: number;
737
+ maxRead?: number;
738
+ signal?: AbortSignal;
739
+ edgeIO?: EdgeIO;
740
+ edgeLimits?: EdgeLimits;
741
+ /** QA-1 m5: the admission's parents in both spellings (`AdmissionData.parents`); edges are matched against W's top under each. */
742
+ parents?: readonly string[];
743
+ },
744
+ ): Promise<ConsumerDiscovery> {
745
+ const maxEntries = Math.max(0, Math.floor(opts?.maxEntries ?? CONSUMER_SCAN_MAX));
746
+ const readMax = Math.max(0, Math.floor(opts?.maxRead ?? CONSUMER_READ_MAX));
747
+ const edgeIO = opts?.edgeIO ?? defaultEdgeIO;
748
+ const edgeLimits = opts?.edgeLimits ?? CONSUMER_EDGE_LIMITS;
749
+ const signal = opts?.signal;
750
+ const stopped = (): boolean => signal?.aborted === true;
751
+ // Per root, by index: a consumer's entry (a link) or via (an edge), "incomplete", "none"; unset while the root is not finished.
752
+ // W (or a root around it) is never scanned, so never incomplete either: settled before any fs call, by text.
753
+ const outcomes: (string | { readonly via: string } | { readonly incomplete: true } | null | undefined)[] = roots.map(({ root }) =>
754
+ (insideOrEqual(root, w) || insideOrEqual(w, root) ? null : undefined));
755
+ const assemble = (): ConsumerDiscovery => {
756
+ const consumers: PerimeterConsumer[] = [];
757
+ const incomplete: ConsumerRoot[] = [];
758
+ roots.forEach(({ root, name }, index) => {
759
+ const outcome = outcomes[index];
760
+ const named = name !== undefined ? { name } : {};
761
+ if (typeof outcome === "string") consumers.push({ root, ...named, entry: outcome });
762
+ else if (outcome !== null && outcome !== undefined && "via" in outcome) consumers.push({ root, ...named, via: outcome.via });
763
+ else if (outcome !== null) incomplete.push({ root, ...named });
764
+ });
765
+ return { consumers, incomplete };
766
+ };
767
+ const work = async (): Promise<void> => {
768
+ // Link targets are real paths: W is matched as given and as its real path (a junction or 8.3 spelling of W).
769
+ const wReal = await realpath(w).catch(() => w);
770
+ const inW = (dir: string): boolean => insideOrEqual(dir, w) || insideOrEqual(dir, wReal);
771
+ // P3c.5: W's top level (W may be a folder of its repository), as found and canonical; edges are matched against them by text.
772
+ const wTop = gitTopOf(w) ?? w;
773
+ const wTopReal = await realpath(wTop).catch(() => wTop);
774
+ // QA-1 m5: W's top as every spelling of its parent spells it (`opts.parents`, the admission's parents as configured and
775
+ // canonical): an edge written through a junction-spelled parent still lies inside W's top, by text. Spellings of one parent
776
+ // are those with one canonical path.
777
+ const rewritten: string[] = [];
778
+ const parentSpellings = opts?.parents ?? [];
779
+ if (parentSpellings.length > 0) {
780
+ const groups = new Map<string, string[]>();
781
+ for (const spelling of parentSpellings) {
782
+ const key = perimeterKey(await realpath(spelling).catch(() => spelling));
783
+ groups.set(key, [...(groups.get(key) ?? []), spelling]);
784
+ }
785
+ for (const group of groups.values()) {
786
+ for (const from of group) {
787
+ for (const top of [wTop, wTopReal]) {
788
+ if (depthBelow(top, from) < 1) continue;
789
+ const below = path.relative(from, top);
790
+ for (const to of group) if (to !== from) rewritten.push(path.join(to, below));
791
+ }
792
+ }
793
+ }
794
+ }
795
+ const wSpellings = [...new Map([w, wReal, wTop, wTopReal, ...rewritten].map((at) => [perimeterKey(at), at])).values()];
796
+ const inWTop = (dir: string): boolean => insideOrEqual(dir, wTop) || insideOrEqual(dir, wTopReal);
797
+ /** By text only (I11): the edge's target, resolved against its declaring file's directory, lies inside W's top. */
798
+ const edgeIntoW = (root: string, edge: DeclaredEdge): boolean => {
799
+ if (edge.unc === true || isUncSpec(edge.spec)) return false;
800
+ const target = path.resolve(path.dirname(path.join(root, edge.from)), edge.spec);
801
+ if (isUncSpec(target)) return false;
802
+ return wSpellings.some((at) => insideOrEqual(target, at) && !hasNodeModulesSegment(path.relative(at, target)));
803
+ };
804
+ const linksIntoW = async (full: string): Promise<boolean> => {
805
+ try {
806
+ if (!(await lstat(full)).isSymbolicLink()) return false;
807
+ if (isUncLinkText(await readlink(full))) return false; // QA-1 #3: never resolved.
808
+ const real = await realpath(full);
809
+ return inW(real) && !isStoreLikeLink(real, process.platform);
810
+ } catch {
811
+ return false; // Unreadable or dangling: it loads nothing.
812
+ }
813
+ };
814
+ const entries = async (dir: string): Promise<Dirent[]> => {
815
+ try {
816
+ return await readdir(dir, { withFileTypes: true });
817
+ } catch {
818
+ return [];
819
+ }
820
+ };
821
+ // QA-2 F-1 (fail-closed): a bound cut W's workspace listing, so its names may be short; a root with no consumer is incomplete.
822
+ let namesCut = false;
823
+ const wNames = await packageNamesOf(w, stopped, () => {
824
+ namesCut = true;
825
+ });
826
+ for (const [index, { root }] of roots.entries()) {
827
+ if (outcomes[index] === null) continue;
828
+ if (inW(root) || insideOrEqual(w, root) || insideOrEqual(wReal, root)) {
829
+ outcomes[index] = null;
830
+ continue;
831
+ }
832
+ if (stopped()) return;
833
+ const modules = path.join(root, "node_modules");
834
+ let found: string | undefined;
835
+ // (a) The direct lookup: one per name, outside the budget.
836
+ for (const name of wNames) {
837
+ if (stopped()) return;
838
+ if (await linksIntoW(path.join(modules, ...name.split("/")))) {
839
+ found = name;
840
+ break;
841
+ }
842
+ }
843
+ // (b) The bounded scan, its budget per root.
844
+ // Only link entries spend `budget` (M2); every entry read counts toward the hard `readMax` cap.
845
+ let budget = maxEntries;
846
+ let read = 0;
847
+ let exhausted = false;
848
+ const check = async (full: string, entry: string, dirent: Dirent): Promise<void> => {
849
+ if (found !== undefined || exhausted) return;
850
+ read += 1;
851
+ if (read > readMax) {
852
+ exhausted = true;
853
+ return;
854
+ }
855
+ // A plain directory or file is no link: free. A type the fs did not report is checked by lstat, like a link.
856
+ if (!dirent.isSymbolicLink() && (dirent.isDirectory() || dirent.isFile())) return;
857
+ if (budget <= 0) {
858
+ exhausted = true;
859
+ return;
860
+ }
861
+ budget -= 1;
862
+ if (await linksIntoW(full)) found = entry;
863
+ };
864
+ if (found === undefined) {
865
+ for (const top of await entries(modules)) {
866
+ if (stopped()) return;
867
+ if (found !== undefined || exhausted) break;
868
+ if (top.name.startsWith(".")) continue;
869
+ if (!top.name.startsWith("@")) {
870
+ await check(path.join(modules, top.name), top.name, top);
871
+ continue;
872
+ }
873
+ read += 1;
874
+ if (read > readMax) {
875
+ exhausted = true;
876
+ break;
877
+ }
878
+ for (const sub of await entries(path.join(modules, top.name))) {
879
+ if (stopped()) return;
880
+ if (found !== undefined || exhausted) break;
881
+ if (sub.name.startsWith(".")) continue;
882
+ await check(path.join(modules, top.name, sub.name), `${top.name}/${sub.name}`, sub);
883
+ }
884
+ }
885
+ }
886
+ // (c) P3c.5: no link into W: the root's declared dependency edges, by text (never W's own repository).
887
+ let via: string | undefined;
888
+ let edgesCut = false;
889
+ if (found === undefined && !inWTop(root) && !insideOrEqual(wTop, root)) {
890
+ if (stopped()) return;
891
+ const declared = declaredEdges(root, edgeIO, edgeLimits);
892
+ const edge = declared.edges.find((candidate) => edgeIntoW(root, candidate));
893
+ if (edge !== undefined) via = consumerVia(edge);
894
+ else edgesCut = declared.incomplete;
895
+ }
896
+ // Stopped on a budget or a bound without a consumer: incomplete.
897
+ outcomes[index] = found !== undefined ? found : via !== undefined ? { via } : exhausted || edgesCut || namesCut ? { incomplete: true } : null;
898
+ }
899
+ };
900
+ if (signal === undefined) {
901
+ await work().catch(() => undefined);
902
+ return assemble();
903
+ }
904
+ if (signal.aborted) return assemble();
905
+ let onAbort: (() => void) | undefined;
906
+ const aborted = new Promise<void>((resolve) => {
907
+ onAbort = resolve;
908
+ signal.addEventListener("abort", onAbort, { once: true });
909
+ });
910
+ try {
911
+ await Promise.race([work().catch(() => undefined), aborted]);
912
+ } finally {
913
+ if (onAbort !== undefined) signal.removeEventListener("abort", onAbort);
914
+ }
915
+ return assemble();
916
+ }
917
+
918
+ /** QA-1 F11: the git common directory of the repository whose top level is `top`, read without git; undefined when unknown. */
919
+ function commonDirOf(top: string | undefined): string | undefined {
920
+ if (top === undefined) return undefined;
921
+ const dotGit = path.join(top, ".git");
922
+ try {
923
+ if (lstatSync(dotGit).isDirectory()) return perimeterKey(canonical(dotGit));
924
+ const named = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotGit, "utf8").slice(0, 4096))?.[1];
925
+ if (named === undefined) return undefined;
926
+ const gitDir = path.resolve(top, named);
927
+ let common = gitDir;
928
+ try {
929
+ common = path.resolve(gitDir, readFileSync(path.join(gitDir, "commondir"), "utf8").trim());
930
+ } catch {
931
+ // No `commondir`: a submodule's (or a relocated) git directory is its own common directory.
932
+ }
933
+ return perimeterKey(canonical(common));
934
+ } catch {
935
+ return undefined;
936
+ }
937
+ }
938
+
939
+ /** Link admission (QA-1 F4, I11, I12): `routing.repoParents`, `routing.repoDepth`, `routing.repoExclude` and the working set. */
940
+ export interface AdmissionContext {
941
+ /** Both spellings of each parent: as configured, and canonical (link targets are real paths), one per comparison key. */
942
+ readonly parents: readonly string[];
943
+ /** The first parent `dir` lies at least one segment below, if any (admission by text, without touching `dir`). */
944
+ readonly parentOf: (dir: string) => string | undefined;
945
+ /** The working-set entry whose worktree holds `dir` (or is `dir`), if any. */
946
+ readonly worktreeOf: (dir: string) => AdmissionWorktree | undefined;
947
+ /**
948
+ * Whether the top level `top` is admitted: it is a working-set worktree, or it lies 1..`routing.repoDepth` segments below a
949
+ * parent and no `routing.repoExclude` glob matches it or a directory between that parent and it.
950
+ */
951
+ readonly admitTop: (top: string) => boolean;
952
+ }
953
+
954
+ /** A working-set entry as admission reads it: its worktree (and its name). A `RepoLocation` is one. */
955
+ export interface AdmissionWorktree {
956
+ readonly worktree: string;
957
+ readonly name?: string;
958
+ }
959
+
960
+ /**
961
+ * Cross-repo P3c.4 (SD-P3c-9): what an `AdmissionContext` is built from, as data: the parents in both spellings (as configured,
962
+ * and canonical, one per comparison key), `routing.repoDepth`, `routing.repoExclude` and the working set. A deferred perimeter
963
+ * freezes it at dispatch, so that `router_verify` admits W's dependency targets as the dispatch did, reading no configuration.
964
+ */
965
+ export interface AdmissionData {
966
+ readonly parents: readonly string[];
967
+ readonly depth: number;
968
+ readonly exclude?: readonly string[];
969
+ readonly workingSet: readonly AdmissionWorktree[];
970
+ }
971
+
972
+ /** P3c.4: the admission data of `config` and `workingSet`. Reads the filesystem only to canonicalise each parent. */
973
+ export function admissionData(config: PerimeterAdmission, workingSet: readonly AdmissionWorktree[]): AdmissionData {
974
+ // Both spellings of each parent: as configured, and canonical (link targets are real paths).
975
+ const parents = [...new Map(config.parents.flatMap((parent) => [parent, canonical(parent)]).map((p) => [perimeterKey(p), p])).values()];
976
+ return {
977
+ parents,
978
+ depth: config.depth,
979
+ ...(config.exclude !== undefined ? { exclude: [...config.exclude] } : {}),
980
+ workingSet: workingSet.map((entry) => ({ worktree: entry.worktree, ...(entry.name !== undefined ? { name: entry.name } : {}) })),
981
+ };
982
+ }
983
+
984
+ /**
985
+ * Cross-repo P3c.2a: the link admission of `planPerimeter`, factored out so that other admissions (the workspace edges, P3c.2b)
986
+ * read the same parents, depth, excludes and working set. Reads the filesystem only to canonicalise each parent.
987
+ */
988
+ export function admissionContext(config: PerimeterAdmission, workingSet: readonly AdmissionWorktree[]): AdmissionContext {
989
+ return admissionFromData(admissionData(config, workingSet));
990
+ }
991
+
992
+ /**
993
+ * Cross-repo P3c.4 (SD-P3c-9): the admission of frozen `data` (its parents already in both spellings). No filesystem call: the
994
+ * admission `router_verify` reads W's dependency targets with is the dispatch's.
995
+ */
996
+ export function admissionFromData(data: AdmissionData): AdmissionContext {
997
+ const depth = Math.max(1, Math.floor(data.depth));
998
+ const exclude = data.exclude ?? [];
999
+ const parents = data.parents;
1000
+ const workingSet = data.workingSet;
1001
+ const excluded = (parent: string, top: string): boolean => {
1002
+ if (exclude.length === 0) return false;
1003
+ const segments = path.relative(parent, top).split(/[\\/]/).filter((segment) => segment !== "");
1004
+ for (let level = 1; level <= segments.length; level++) {
1005
+ const dir = path.join(parent, ...segments.slice(0, level));
1006
+ if (exclude.some((glob) => permissionMatches(dir, glob))) return true;
1007
+ }
1008
+ return false;
1009
+ };
1010
+ const parentOf = (dir: string): string | undefined => parents.find((parent) => depthBelow(dir, parent) >= 1);
1011
+ const worktreeOf = (dir: string): AdmissionWorktree | undefined => workingSet.find((entry) => insideOrEqual(dir, entry.worktree));
1012
+ // QA-1 F4 (I11, I12): admission by top level, before any git call; the snapshot's top level is checked again at the gate.
1013
+ const admitTop = (top: string): boolean =>
1014
+ workingSet.some((entry) => perimeterKey(entry.worktree) === perimeterKey(top))
1015
+ || parents.some((parent) => {
1016
+ const below = depthBelow(top, parent);
1017
+ return below >= 1 && below <= depth && !excluded(parent, top);
1018
+ });
1019
+ return { parents, parentOf, worktreeOf, admitTop };
1020
+ }
1021
+
1022
+ /**
1023
+ * Cross-repo P3c QA-1 m4: what `planPerimeter` returns: P, plus how W's declared edges were cut on the way forward, for the
1024
+ * caller to log once per dispatch ("past a forward bound: logged", SD-P3c-4; perimeter.ts has no logger of its own).
1025
+ */
1026
+ export interface PlannedPerimeter extends DispatchPerimeter {
1027
+ /** A `declaredEdges` bound cut the reading of W's declared edges. */
1028
+ readonly edgesIncomplete?: true;
1029
+ /** Unadmitted edge targets past EDGE_UNADMITTED_NAMES_MAX: counted, not named. Absent when 0. */
1030
+ readonly unadmittedMore?: number;
1031
+ }
1032
+
1033
+ /**
1034
+ * The perimeter beyond W of the dispatch `dispatchID` (a native `task` dispatch, `task:<orchestrator>:<callID>`) verified at
1035
+ * `cwd`, or undefined when it has none (I9): not a routed role dispatch, or neither a grant location nor another working-set
1036
+ * root, or no extra root at all. W is the grant location's worktree, else `cwd`. `admission` is read for W's package links and
1037
+ * declared dependency edges only (P3c.3); `io` (tests) is what `dependencyTargets` reads them with.
1038
+ */
1039
+ export function planPerimeter(
1040
+ dispatchID: string,
1041
+ cwd: string,
1042
+ admission: () => PerimeterAdmission,
1043
+ io: DependencyIO = defaultDependencyIO,
1044
+ ): PlannedPerimeter | undefined {
1045
+ if (!dispatchID.startsWith("task:")) return undefined;
1046
+ const rest = dispatchID.slice("task:".length);
1047
+ const separator = rest.indexOf(":");
1048
+ if (separator <= 0) return undefined;
1049
+ const orchestrator = rest.slice(0, separator);
1050
+ const routed = routedRoleOf(rest.slice(separator + 1));
1051
+ if (routed === undefined || routed.parentSessionID !== orchestrator) return undefined;
1052
+ const location = routed.grant?.location;
1053
+ const w = location?.worktree ?? cwd;
1054
+ const workingSet = workingSetOf(orchestrator);
1055
+ const others = workingSet.filter((entry) => !insideOrEqual(w, entry.worktree) && !insideOrEqual(entry.worktree, w));
1056
+ // I13 (S1/S2): with cross-repo configured (`routing.repoParents`), W's admitted link targets are in P even when the dispatch has
1057
+ // no location and no working set. Without parents, such a dispatch has none (I9).
1058
+ const config = admission();
1059
+ if (location === undefined && others.length === 0 && config.parents.length === 0) return undefined;
1060
+
1061
+ // QA-1 F11: W's git common directory, to tell another worktree of W's own repository from another repository.
1062
+ const wCommon = commonDirOf(gitTopOf(w));
1063
+ const sameRepository = (top: string): boolean => wCommon !== undefined && commonDirOf(top) === wCommon;
1064
+
1065
+ const seeds: PerimeterSeed[] = [];
1066
+ const seen = new Set<string>([perimeterKey(w)]);
1067
+ let observed = 0;
1068
+ // QA-1 F2: past the cap a root is kept, unobserved (the gate refuses it with writers), never dropped.
1069
+ const add = (seed: PerimeterSeed): void => {
1070
+ const key = perimeterKey(seed.at);
1071
+ if (seen.has(key)) return;
1072
+ seen.add(key);
1073
+ if (seed.fixed !== undefined) {
1074
+ seeds.push(seed);
1075
+ return;
1076
+ }
1077
+ observed += 1;
1078
+ if (observed <= PERIMETER_MAX - 1) {
1079
+ seeds.push(seed);
1080
+ return;
1081
+ }
1082
+ seeds.push({
1083
+ at: seed.at,
1084
+ ...(seed.name !== undefined ? { name: seed.name } : {}),
1085
+ ...(seed.sameRepository === true ? { sameRepository: true } : {}),
1086
+ ...(seed.origin !== undefined ? { origin: seed.origin } : {}),
1087
+ fixed: "unobserved",
1088
+ });
1089
+ };
1090
+ for (const entry of others) {
1091
+ add({
1092
+ at: entry.worktree,
1093
+ name: entry.name,
1094
+ origin: "working-set",
1095
+ ...(sameRepository(entry.worktree) ? { sameRepository: true } : {}),
1096
+ });
1097
+ }
1098
+
1099
+ // P3c.2a: link admission (parents in both spellings, depth, excludes, working set), factored into `admissionContext`.
1100
+ // P3c.4 (SD-P3c-9): its data is returned with P, frozen with a deferred perimeter for router_verify.
1101
+ const frozenAdmission = admissionData(config, workingSet);
1102
+ const linkAdmission = admissionFromData(frozenAdmission);
1103
+ const { parentOf, worktreeOf, admitTop } = linkAdmission;
1104
+ // P3c.3 (SD-P3c-1): W's package links first (`linkedTargets`, unchanged), then its declared edges, read once.
1105
+ const dependencies = dependencyTargets(w, { ...linkAdmission, sameRepository }, io);
1106
+
1107
+ for (const dependency of dependencies.targets) {
1108
+ if (dependency.origin !== "link") continue;
1109
+ const real = dependency.at;
1110
+ // Admission by text first: a link outside every parent and every working-set worktree is not in P, but it is not dropped
1111
+ // either (I8, I12): kept as an unadmitted root named by its basename, without running git or touching the filesystem.
1112
+ const parent = parentOf(real);
1113
+ const worktree = worktreeOf(real);
1114
+ if (parent === undefined && worktree === undefined) {
1115
+ add({ at: real, name: path.basename(real), fixed: "unadmitted", origin: "link" });
1116
+ continue;
1117
+ }
1118
+ // QA-1 F3: the repository's top level, without git; the walk stops at the parent (or above the worktree).
1119
+ const top = gitTopOf(real, worktree !== undefined ? path.dirname(worktree.worktree) : parent);
1120
+ if (top === undefined) {
1121
+ add({ at: real, name: path.basename(real), fixed: "unadmitted", origin: "link" }); // Not in a git repository: nothing to observe.
1122
+ continue;
1123
+ }
1124
+ if (insideOrEqual(top, w) || insideOrEqual(w, top)) continue; // W's own repository: W's snapshot covers it.
1125
+ const covering = seeds.findIndex((seed) => seed.fixed === undefined && insideOrEqual(top, seed.at));
1126
+ if (covering >= 0) {
1127
+ // A root already in P covers it: one seed. QA-1 #9a: a working-set root covering it is marked as a link target too, so it
1128
+ // is pinned at dispatch; it keeps its working-set semantics (consumer discovery, I13). Its admission still accepts any
1129
+ // top level at, above or inside it at the gate (as without one), and admits its own links for the pin as a link's are.
1130
+ const seed = seeds[covering];
1131
+ if (seed !== undefined && seed.origin === "working-set" && seed.linked !== true) {
1132
+ const at = seed.at;
1133
+ seeds[covering] = {
1134
+ ...seed,
1135
+ linked: true,
1136
+ admit: (dir: string): boolean => insideOrEqual(dir, at) || insideOrEqual(at, dir) || admitTop(dir),
1137
+ };
1138
+ }
1139
+ continue;
1140
+ }
1141
+ if (!admitTop(top)) {
1142
+ add({ at: top, name: path.basename(top), fixed: "unadmitted", origin: "link" });
1143
+ continue;
1144
+ }
1145
+ add({ at: top, admit: admitTop, origin: "link", ...(sameRepository(top) ? { sameRepository: true } : {}) });
1146
+ }
1147
+
1148
+ // P3c.3 (SD-P3c-2): W's declared dependency edges outside `node_modules`, after the links, so that a link and an edge into one
1149
+ // repository are one "link" seed (pinned as before). An admitted edge is a seed of origin "edge", observed like a link target
1150
+ // (I4, I8), counted toward PERIMETER_MAX and frozen for S11 (P3c.4), but never pinned (F3). An unadmitted one is
1151
+ // named (`name (not admitted)`, at most EDGE_UNADMITTED_NAMES_MAX, `dependencyTargets`), never snapshotted (I11, I12).
1152
+ for (const dependency of dependencies.targets) {
1153
+ if (dependency.origin !== "edge") continue;
1154
+ if ("fixed" in dependency) {
1155
+ add({ at: dependency.at, name: dependency.name, fixed: "unadmitted", origin: "edge" });
1156
+ continue;
1157
+ }
1158
+ const top = dependency.at;
1159
+ const covering = seeds.findIndex((seed) => seed.fixed === undefined && insideOrEqual(top, seed.at));
1160
+ if (covering >= 0) {
1161
+ // A root already in P covers it: one seed. A working-set root keeps its semantics and is marked `edged`; unlike a `linked`
1162
+ // one it is not pinned (F3). A link seed, or a working-set root already `linked`, stays as it is.
1163
+ const seed = seeds[covering];
1164
+ if (seed !== undefined && seed.origin === "working-set" && seed.linked !== true && seed.edged !== true) {
1165
+ seeds[covering] = { ...seed, edged: true };
1166
+ }
1167
+ continue;
1168
+ }
1169
+ add({ at: top, admit: admitTop, origin: "edge" });
1170
+ }
1171
+ if (seeds.length === 0) return undefined;
1172
+ return {
1173
+ ...(location !== undefined ? { name: location.name } : {}),
1174
+ roots: seeds,
1175
+ admission: frozenAdmission,
1176
+ // QA-1 m4: the forward bounds' outcome, for the caller to log once per dispatch (this module has no logger).
1177
+ ...(dependencies.incomplete ? { edgesIncomplete: true as const } : {}),
1178
+ ...(dependencies.unadmittedMore > 0 ? { unadmittedMore: dependencies.unadmittedMore } : {}),
1179
+ };
1180
+ }