opencode-model-router 2.7.0 → 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 (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -0,0 +1,817 @@
1
+ /**
2
+ * src/verify/edges.ts
3
+ *
4
+ * Cross-repo P3c.1 (docs/design/cross-repo-phase3-plan.md, item (c), SD-P3c-1..10, owner decision D24 = Tier A): the dependency
5
+ * edges a root DECLARES outside `node_modules`, read as text (I11) and never evaluated (SD-P3c-7). Nothing here touches git,
6
+ * realpaths a target or decides admission: a spec is returned as written (relative to the declaring file's directory), and the
7
+ * caller admits it (P3c.2b). Tier A only:
8
+ * - A1 `package.json` `file:`/`link:`/`portal:` specs (root and workspace manifests);
9
+ * - A2 `tsconfig.json`, `tsconfig.*.json`, `jsconfig.json` (root) and each workspace `tsconfig.json`, as JSONC;
10
+ * - A3 Python editable installs in an in-repo venv (`.venv`/`venv` with `pyvenv.cfg`);
11
+ * - A4 Go `replace … => <local path>` in `go.mod`/`go.work` and `go.work` `use`.
12
+ * Bounded (SD-P3c-4): every file is stat'ed before it is read, at most `EDGE_FILE_BYTES_MAX` bytes; at most `EDGE_FILES_MAX`
13
+ * files and `EDGES_MAX` distinct targets per root; `incomplete` is set when a bound cuts. Malformed files are skipped.
14
+ * Not read (outside Tier A or later tiers): `pnpm-workspace.yaml` (workspaces come from `package.json` only, perimeter.ts rules),
15
+ * bare-path dependency specs without a protocol (`"../x"`), tsconfig outputs (`outDir`, `declarationDir`, `tsBuildInfoFile`).
16
+ */
17
+ import { opendirSync, readFileSync, statSync } from "node:fs";
18
+ import * as path from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { perimeterKey } from "./git-top";
21
+
22
+ /** SD-P3c-4: a file larger than this is skipped (and the result is `incomplete`). */
23
+ export const EDGE_FILE_BYTES_MAX = 1024 * 1024;
24
+ /** SD-P3c-4: at most this many files are read per root (every manifest, tsconfig, venv and Go file counts). */
25
+ export const EDGE_FILES_MAX = 128;
26
+ /** SD-P3c-4: at most this many distinct targets per root. */
27
+ export const EDGES_MAX = 64;
28
+ /**
29
+ * QA-1 M1: a spec longer than this is never walked, and is unadmitted (perimeter.ts `resolveEdgeTarget`, which re-exports it).
30
+ * QA-2 F-2: such a spec never takes its target's place either: a later spelling of the same target is still kept.
31
+ */
32
+ export const EDGE_SPEC_MAX = 4096;
33
+ /** SD-P3c-4: at most this many workspace packages are read per root. */
34
+ export const EDGE_WORKSPACES_MAX = 64;
35
+ /** SD-P3c-4: a tsconfig `extends` chain is followed at most this deep, and only inside the declaring root. */
36
+ export const EDGE_EXTENDS_DEPTH_MAX = 4;
37
+ /** QA-1 M2: at most this many entries of one tsconfig `extends` array are read (each may cost a stat); past it, `incomplete`. */
38
+ export const EDGE_EXTENDS_ENTRIES_MAX = 8;
39
+ /** QA-1 M2: at most this many `workspaces` patterns are read (each wildcard one costs a directory listing); past it, `incomplete`. */
40
+ export const EDGE_WORKSPACE_PATTERNS_MAX = 64;
41
+ /** QA-1 M2: the directory entries the `workspaces` wildcard listings read in total, per root; past it, `incomplete`. */
42
+ export const EDGE_WORKSPACE_ENTRIES_MAX = 8000;
43
+ /** A2: at most this many root `tsconfig.*.json` variants are read. */
44
+ export const EDGE_TSCONFIG_VARIANTS_MAX = 8;
45
+ /** A1: npm `overrides` string leaves are read at most this deep. */
46
+ export const EDGE_OVERRIDES_DEPTH_MAX = 4;
47
+ /** SD-P3c-4: one site-packages listing reads at most this many entries. */
48
+ export const SITE_PACKAGES_ENTRIES_MAX = 4000;
49
+ /** SD-P3c-4: at most this many `.pth`, editable finder and `.egg-link` files are read. */
50
+ export const SITE_PACKAGES_FILES_MAX = 64;
51
+
52
+ /** The bounds of one `declaredEdges` call (SD-P3c-4); injectable for tests. */
53
+ export interface EdgeLimits {
54
+ readonly bytes: number;
55
+ readonly files: number;
56
+ readonly edges: number;
57
+ readonly workspaces: number;
58
+ readonly extendsDepth: number;
59
+ readonly tsconfigVariants: number;
60
+ /** One directory listing (site-packages, the root, a workspace wildcard's parent, a venv's `lib`) reads at most this many names. */
61
+ readonly entries: number;
62
+ readonly siteFiles: number;
63
+ }
64
+
65
+ /** The default `declaredEdges` bounds. */
66
+ export const EDGE_LIMITS: EdgeLimits = Object.freeze({
67
+ bytes: EDGE_FILE_BYTES_MAX,
68
+ files: EDGE_FILES_MAX,
69
+ edges: EDGES_MAX,
70
+ workspaces: EDGE_WORKSPACES_MAX,
71
+ extendsDepth: EDGE_EXTENDS_DEPTH_MAX,
72
+ tsconfigVariants: EDGE_TSCONFIG_VARIANTS_MAX,
73
+ entries: SITE_PACKAGES_ENTRIES_MAX,
74
+ siteFiles: SITE_PACKAGES_FILES_MAX,
75
+ });
76
+
77
+ /** Tier A edge kinds (D24): A1 `package`, A2 `tsconfig`, A3 `python`, A4 `go`. */
78
+ export type EdgeKind = "package" | "tsconfig" | "python" | "go";
79
+
80
+ /** A1: the `package.json` fields read, `pnpm.overrides` spelled as a path. */
81
+ export const PACKAGE_EDGE_FIELDS = [
82
+ "dependencies",
83
+ "devDependencies",
84
+ "optionalDependencies",
85
+ "peerDependencies",
86
+ "overrides",
87
+ "resolutions",
88
+ "pnpm.overrides",
89
+ ] as const;
90
+ export type PackageEdgeField = (typeof PACKAGE_EDGE_FIELDS)[number];
91
+
92
+ /** A1: the path protocols read (`file://` URLs count as `file:`). */
93
+ export const PACKAGE_EDGE_PROTOCOLS = ["file:", "link:", "portal:"] as const;
94
+ export type PackageEdgeProtocol = (typeof PACKAGE_EDGE_PROTOCOLS)[number];
95
+
96
+ /** A2: the tsconfig/jsconfig keys read. */
97
+ export const TSCONFIG_EDGE_KEYS = ["extends", "references", "paths", "baseUrl", "rootDirs", "typeRoots", "include", "files"] as const;
98
+ export type TsconfigEdgeKey = (typeof TSCONFIG_EDGE_KEYS)[number];
99
+
100
+ /** SD-P3c-5: the fixed vocabulary an edge is described with (never the raw spec). */
101
+ export type EdgeVia =
102
+ | `package.json ${PackageEdgeField} (${PackageEdgeProtocol})`
103
+ | `tsconfig ${TsconfigEdgeKey}`
104
+ | "python editable install"
105
+ | "go.mod replace"
106
+ | "go.work use"
107
+ | "go.work replace";
108
+
109
+ /** SD-P3c-5: every `via` label, in a fixed order. */
110
+ export const EDGE_VIAS: readonly EdgeVia[] = Object.freeze([
111
+ ...PACKAGE_EDGE_FIELDS.flatMap(field => PACKAGE_EDGE_PROTOCOLS.map(protocol => `package.json ${field} (${protocol})` as const)),
112
+ ...TSCONFIG_EDGE_KEYS.map(key => `tsconfig ${key}` as const),
113
+ "python editable install" as const,
114
+ "go.mod replace" as const,
115
+ "go.work use" as const,
116
+ "go.work replace" as const,
117
+ ]);
118
+
119
+ /** One declared dependency edge of a root. */
120
+ export interface DeclaredEdge {
121
+ readonly kind: EdgeKind;
122
+ /**
123
+ * The target as declared, a path to resolve against the declaring file's directory (`path.dirname(path.join(root, from))`):
124
+ * the protocol stripped, a `file://` URL converted, a tsconfig glob cut to its static prefix and joined to `baseUrl`. Never
125
+ * echoed to users (SD-P3c-5).
126
+ */
127
+ readonly spec: string;
128
+ readonly via: EdgeVia;
129
+ /** The declaring file, relative to the root, "/" separated. */
130
+ readonly from: string;
131
+ /** The spec names a UNC share or a device path: it was never resolved, and is never admitted (SD-P3c-3). */
132
+ readonly unc?: true;
133
+ }
134
+
135
+ /** The result of `declaredEdges`: `incomplete` when a bound cut the reading. */
136
+ export interface DeclaredEdges {
137
+ readonly edges: DeclaredEdge[];
138
+ readonly incomplete: boolean;
139
+ }
140
+
141
+ /** The file primitives `declaredEdges` uses, synchronous (it runs at dispatch start, F9); injectable for tests. */
142
+ export interface EdgeIO {
143
+ /** Follows links; throws when absent. */
144
+ readonly stat: (p: string) => { isFile(): boolean; isDirectory(): boolean; readonly size: number };
145
+ readonly readFile: (p: string) => string;
146
+ /** The names in `dir`, in directory order, at most `max + 1` of them (so a caller sees a cut); throws when unreadable. */
147
+ readonly readdir: (dir: string, max: number) => string[];
148
+ }
149
+
150
+ function boundedNames(dir: string, max: number): string[] {
151
+ const handle = opendirSync(dir);
152
+ try {
153
+ const names: string[] = [];
154
+ for (let entry = handle.readSync(); entry !== null && names.length <= max; entry = handle.readSync()) names.push(entry.name);
155
+ return names;
156
+ } finally {
157
+ handle.closeSync();
158
+ }
159
+ }
160
+
161
+ /** The default `EdgeIO`: `node:fs`, synchronous. */
162
+ export const defaultEdgeIO: EdgeIO = {
163
+ stat: (p) => statSync(p),
164
+ readFile: (p) => readFileSync(p, "utf8"),
165
+ readdir: (dir, max) => boundedNames(dir, max),
166
+ };
167
+
168
+ /**
169
+ * SD-P3c-7: JSON with comments (tsconfig, jsconfig), parsed without evaluating anything: a leading BOM is dropped, `//` and
170
+ * `/* … *\/` comments outside strings are removed, a trailing comma before `}` or `]` is removed, then `JSON.parse`. Invalid
171
+ * text (an unterminated comment or string included) gives `undefined`.
172
+ */
173
+ export function parseJsonc(text: string): unknown {
174
+ const out: string[] = [];
175
+ /** The index in `out` of a comma that is, so far, the last significant token. */
176
+ let comma = -1;
177
+ const n = text.length;
178
+ let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
179
+ while (i < n) {
180
+ const c = text[i]!;
181
+ if (c === '"') {
182
+ const start = i++;
183
+ while (i < n && text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
184
+ if (i >= n) return undefined;
185
+ i++;
186
+ out.push(text.slice(start, i));
187
+ comma = -1;
188
+ continue;
189
+ }
190
+ if (c === "/" && text[i + 1] === "/") {
191
+ while (i < n && text[i] !== "\n" && text[i] !== "\r") i++;
192
+ continue;
193
+ }
194
+ if (c === "/" && text[i + 1] === "*") {
195
+ const end = text.indexOf("*/", i + 2);
196
+ if (end < 0) return undefined;
197
+ out.push(" ");
198
+ i = end + 2;
199
+ continue;
200
+ }
201
+ if ((c === "}" || c === "]") && comma >= 0) out[comma] = "";
202
+ if (c === ",") comma = out.length;
203
+ else if (!/\s/.test(c)) comma = -1;
204
+ out.push(c);
205
+ i++;
206
+ }
207
+ try {
208
+ return JSON.parse(out.join(""));
209
+ } catch {
210
+ return undefined;
211
+ }
212
+ }
213
+
214
+ /** A spec naming a UNC share or a device path (`\\server\share`, `\\?\…`, `//server/share`): never resolved (QA-1 #3). */
215
+ export function isUncSpec(spec: string): boolean {
216
+ return /^[\\/]{2}/.test(spec);
217
+ }
218
+
219
+ function isRecord(value: unknown): value is Record<string, unknown> {
220
+ return typeof value === "object" && value !== null && !Array.isArray(value);
221
+ }
222
+
223
+ function insideOrEqual(child: string, parent: string): boolean {
224
+ const c = perimeterKey(child);
225
+ const p = perimeterKey(parent);
226
+ return c === p || c.startsWith(`${p}/`);
227
+ }
228
+
229
+ function byCodeUnit(a: string, b: string): number {
230
+ return a < b ? -1 : a > b ? 1 : 0;
231
+ }
232
+
233
+ /** An absolute spelling on either platform: `/x`, `\x`, `C:\x`, `C:/x`, UNC. */
234
+ function isAbsoluteSpec(spec: string): boolean {
235
+ return path.isAbsolute(spec) || /^[\\/]/.test(spec) || /^[A-Za-z]:[\\/]/.test(spec);
236
+ }
237
+
238
+ /** A relative (`./`, `../`, `.`, `..`) or absolute spelling, not a package name. */
239
+ function isPathSpec(spec: string): boolean {
240
+ return /^\.\.?(?:[\\/]|$)/.test(spec) || isAbsoluteSpec(spec);
241
+ }
242
+
243
+ /**
244
+ * The `workspaces` patterns of a `package.json` (an array, or `{ packages: [...] }`), strings only. Shared with the consumer
245
+ * discovery in perimeter.ts.
246
+ */
247
+ export function workspacePatterns(manifest: Record<string, unknown>): string[] {
248
+ const field = manifest.workspaces;
249
+ const packages = typeof field === "object" && field !== null && !Array.isArray(field)
250
+ ? (field as { packages?: unknown }).packages
251
+ : field;
252
+ return Array.isArray(packages) ? packages.filter((entry): entry is string => typeof entry === "string") : [];
253
+ }
254
+
255
+ /**
256
+ * One code unit as a case-insensitive, non-unicode regular expression compares it (ECMA-262 Canonicalize): its upper case
257
+ * when that is one code unit, and not an ASCII one for a non-ASCII unit; else itself.
258
+ */
259
+ function foldUnit(unit: string): string {
260
+ const upper = unit.toUpperCase();
261
+ return upper.length === 1 && !(unit.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128) ? upper : unit;
262
+ }
263
+
264
+ /** `text` with every code unit folded by `foldUnit` (one unit each, so the length and every `*` position are kept). */
265
+ function foldUnits(text: string): string {
266
+ let out = "";
267
+ for (let i = 0; i < text.length; i++) out += foldUnit(text.charAt(i));
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * Cross-repo P3c QA-2 F-1: a directory entry name is at most 255 code units (posix NAME_MAX, NTFS's 255 UTF-16 units), so a
273
+ * `workspaces` segment with more literal (non-`*`) characters matches no entry, and its directory is never listed.
274
+ */
275
+ export const WORKSPACE_SEGMENT_LITERALS_MAX = 255;
276
+
277
+ /** A one-segment `workspaces` pattern prepared once (QA-2 F-1): whether one directory entry name matches it. */
278
+ export type WorkspaceSegmentMatcher = (name: string) => boolean;
279
+
280
+ /**
281
+ * The matcher of `pattern`, the pattern scanned once (separator check, literal count, case folding); `undefined` when it holds
282
+ * a separator or more than `maxLiterals` literal characters (it matches nothing). Each name is folded once per call.
283
+ */
284
+ function compileSegment(pattern: string, ignoreCase: boolean, maxLiterals: number): WorkspaceSegmentMatcher | undefined {
285
+ if (/[\\/]/.test(pattern)) return undefined;
286
+ let literals = 0;
287
+ for (let i = 0; i < pattern.length; i++) if (pattern.charCodeAt(i) !== 42) literals += 1;
288
+ if (literals > maxLiterals) return undefined;
289
+ const folded = ignoreCase ? foldUnits(pattern) : pattern;
290
+ return (name: string): boolean => {
291
+ if (literals > name.length || /[\\/]/.test(name)) return false;
292
+ const subject = ignoreCase ? foldUnits(name) : name;
293
+ let p = 0;
294
+ let n = 0;
295
+ let star = -1;
296
+ let mark = 0;
297
+ while (n < subject.length) {
298
+ if (p < folded.length && folded.charCodeAt(p) === 42) {
299
+ star = p;
300
+ p += 1;
301
+ mark = n;
302
+ } else if (p < folded.length && folded.charCodeAt(p) === subject.charCodeAt(n)) {
303
+ p += 1;
304
+ n += 1;
305
+ } else if (star >= 0) {
306
+ // The last `*` takes one more character (never a separator: `name` holds none), and the rest is matched again.
307
+ p = star + 1;
308
+ mark += 1;
309
+ n = mark;
310
+ } else {
311
+ return false;
312
+ }
313
+ }
314
+ while (p < folded.length && folded.charCodeAt(p) === 42) p += 1;
315
+ return p === folded.length;
316
+ };
317
+ }
318
+
319
+ /**
320
+ * Cross-repo P3c QA-2 F-1: the matcher of the one-segment `workspaces` pattern `pattern` (`workspaceSegmentMatches` rules),
321
+ * prepared once for a whole directory listing; `undefined` when no directory entry can match it (a separator, or more than
322
+ * `WORKSPACE_SEGMENT_LITERALS_MAX` literal characters), so the caller lists nothing.
323
+ */
324
+ export function prepareWorkspaceSegment(
325
+ pattern: string,
326
+ ignoreCase: boolean = process.platform === "win32",
327
+ ): WorkspaceSegmentMatcher | undefined {
328
+ return compileSegment(pattern, ignoreCase, WORKSPACE_SEGMENT_LITERALS_MAX);
329
+ }
330
+
331
+ /**
332
+ * Cross-repo P3c QA-1 C1: whether the directory entry `name` matches the one-segment `workspaces` pattern `pattern`, whose only
333
+ * wildcard is `*` (`**` is one), a run of any characters but a separator; case-insensitive on win32 (`ignoreCase`), as the
334
+ * regular expression it replaces. No regular expression is built from repository text: two pointers, the last `*` the only
335
+ * backtracking point, so the time is at most quadratic in `name` (a directory entry) and linear in `pattern`. A pattern holding
336
+ * a separator matches nothing (a segment never holds one). One-shot: a listing prepares the pattern once
337
+ * (`prepareWorkspaceSegment`, QA-2 F-1).
338
+ */
339
+ export function workspaceSegmentMatches(pattern: string, name: string, ignoreCase: boolean = process.platform === "win32"): boolean {
340
+ return compileSegment(pattern, ignoreCase, Number.POSITIVE_INFINITY)?.(name) ?? false;
341
+ }
342
+
343
+ /** The directories of one `workspaces` pattern, whether the listing was cut at `entries` names, and how many names it read. */
344
+ function matchWorkspace(
345
+ w: string,
346
+ pattern: string,
347
+ limit: number,
348
+ io: EdgeIO,
349
+ entries: number,
350
+ ): { dirs: string[]; cut: boolean; listed: number } {
351
+ if (pattern.startsWith("!") || path.isAbsolute(pattern) || /^[\\/]/.test(pattern)) return { dirs: [], cut: false, listed: 0 };
352
+ const segments = pattern.split(/[\\/]/).filter((segment) => segment !== "" && segment !== ".");
353
+ if (segments.length === 0 || segments.some((segment) => segment === "..")) return { dirs: [], cut: false, listed: 0 };
354
+ const last = segments[segments.length - 1] ?? "";
355
+ const head = segments.slice(0, -1);
356
+ if (head.some((segment) => segment.includes("*"))) return { dirs: [], cut: false, listed: 0 };
357
+ if (!last.includes("*")) return { dirs: [path.join(w, ...segments)], cut: false, listed: 0 };
358
+ // QA-2 F-1: the segment is prepared once, before the listing; one no entry name can match is not listed at all.
359
+ const matches = prepareWorkspaceSegment(last);
360
+ if (matches === undefined) return { dirs: [], cut: false, listed: 0 };
361
+ const base = path.join(w, ...head);
362
+ let children: string[];
363
+ try {
364
+ children = io.readdir(base, entries);
365
+ } catch {
366
+ return { dirs: [], cut: false, listed: 0 };
367
+ }
368
+ // Code-unit order: fs.readdir's (libuv sorts with strcmp) on posix, and NTFS order for same-case names on win32.
369
+ const dirs = children
370
+ .slice(0, entries)
371
+ .sort(byCodeUnit)
372
+ .filter((child) => !child.startsWith(".") && child !== "node_modules" && matches(child))
373
+ .slice(0, limit)
374
+ .map((child) => path.join(base, child));
375
+ return { dirs, cut: children.length > entries, listed: Math.min(children.length, entries + 1) };
376
+ }
377
+
378
+ /**
379
+ * The synchronous twin of perimeter.ts `workspaceDirs` (same rules): the directories of one `workspaces` pattern, inside W
380
+ * only: literal segments, and a wildcard (`*`, `**`) in the last segment only, matched one level deep. Negations, absolute
381
+ * paths, `..` and inner wildcards give none. At most `limit` directories from a wildcard.
382
+ */
383
+ export function workspaceDirsSync(w: string, pattern: string, limit: number, io: EdgeIO = defaultEdgeIO): string[] {
384
+ return matchWorkspace(w, pattern, limit, io, SITE_PACKAGES_ENTRIES_MAX).dirs;
385
+ }
386
+
387
+ const TARBALL = /\.(?:tgz|tar\.gz|tar)$/i;
388
+
389
+ /** A1: the path of a `file:`/`link:`/`portal:` spec (a `file://` URL converted), or `undefined` for every other spec. */
390
+ function packagePathSpec(raw: string): { protocol: PackageEdgeProtocol; path: string } | undefined {
391
+ const spec = raw.trim();
392
+ const match = /^(file|link|portal):/.exec(spec);
393
+ if (match === null) return undefined;
394
+ const protocol = `${match[1]}:` as PackageEdgeProtocol;
395
+ let target = spec.slice(match[0].length);
396
+ if (protocol === "file:" && target.startsWith("//")) {
397
+ try {
398
+ target = fileURLToPath(spec);
399
+ } catch {
400
+ return undefined;
401
+ }
402
+ }
403
+ if (target.trim() === "" || TARBALL.test(target)) return undefined;
404
+ return { protocol, path: target };
405
+ }
406
+
407
+ /** A2: a glob's static prefix: the directory part before the first `*` or `?` (`../lib/*` → `../lib/`, `*` → `.`). */
408
+ function staticPrefix(glob: string): string {
409
+ const wild = glob.search(/[*?]/);
410
+ if (wild < 0) return glob;
411
+ const head = glob.slice(0, wild);
412
+ const cut = Math.max(head.lastIndexOf("/"), head.lastIndexOf("\\"));
413
+ return cut < 0 ? "." : head.slice(0, cut + 1);
414
+ }
415
+
416
+ /** A2: a `paths` prefix against `baseUrl` (itself relative to the declaring file), or the prefix alone without one. */
417
+ function joinBaseUrl(baseUrl: string | undefined, prefix: string): string {
418
+ if (baseUrl === undefined || isAbsoluteSpec(prefix)) return prefix;
419
+ if (isUncSpec(baseUrl)) return `${baseUrl.replace(/[\\/]+$/, "")}/${prefix}`;
420
+ return path.join(baseUrl, prefix);
421
+ }
422
+
423
+ /** A4: a line without its `//` comment (a `//` inside a quoted or raw string is kept). */
424
+ function stripGoComment(line: string): string {
425
+ let quote: string | undefined;
426
+ for (let i = 0; i < line.length; i++) {
427
+ const c = line[i];
428
+ if (quote !== undefined) {
429
+ if (c === "\\" && quote === '"') i++;
430
+ else if (c === quote) quote = undefined;
431
+ continue;
432
+ }
433
+ if (c === '"' || c === "`") quote = c;
434
+ else if (c === "/" && line[i + 1] === "/") return line.slice(0, i);
435
+ }
436
+ return line;
437
+ }
438
+
439
+ /** A4: the tokens of a directive's arguments: interpreted (`"…"`) and raw (`` `…` ``) strings, or bare words. */
440
+ function goTokens(args: string): string[] {
441
+ const tokens: string[] = [];
442
+ for (const match of args.matchAll(/"((?:\\.|[^"\\])*)"|`([^`]*)`|(\S+)/g)) {
443
+ tokens.push(match[1] !== undefined ? match[1].replace(/\\(.)/g, "$1") : (match[2] ?? match[3] ?? ""));
444
+ }
445
+ return tokens;
446
+ }
447
+
448
+ /** A4: a local replacement path (`./`, `../`, `/`, a drive); anything else is a module path. */
449
+ function isLocalGoPath(token: string): boolean {
450
+ return /^\.\.?(?:[\\/]|$)/.test(token) || isAbsoluteSpec(token);
451
+ }
452
+
453
+ /** A3: one `'…'` or `"…"` Python string literal's text, with `\\`, `\'` and `\"` unescaped. */
454
+ function pythonString(body: string): string {
455
+ return body.replace(/\\(['"\\])/g, "$1");
456
+ }
457
+
458
+ /** A3: the files of a site-packages directory that declare editable installs. */
459
+ const SITE_FILE = /(?:\.pth|\.egg-link)$|^__editable___.*_finder\.py$/i;
460
+
461
+ const LINE_TERMINATORS = "\n\r\u2028\u2029";
462
+ const WHITESPACE = /\s/;
463
+
464
+ /**
465
+ * A3, QA-1 M2: the body of an editable finder's `MAPPING` dict literal, as the multiline regular expression
466
+ * `^MAPPING\s*(?::[^=\n]*)?=\s*\{([^}]*)\}` finds it first (group 1), in linear time: each `MAPPING` at a line start is parsed
467
+ * forward once; a `MAPPING` whose annotation starts before where the previous one's stopped fails as that one did, and once
468
+ * no `}` follows a `{` none follows any later one either. Undefined when there is none.
469
+ */
470
+ export function finderMappingBody(text: string): string | undefined {
471
+ let stopped = -1; // Where the last annotation scan stopped: a later scan starting before it ends there too, as that one did.
472
+ for (let at = text.indexOf("MAPPING"); at >= 0; at = text.indexOf("MAPPING", at + 7)) {
473
+ if (at > 0 && !LINE_TERMINATORS.includes(text[at - 1]!)) continue;
474
+ let i = at + 7;
475
+ while (i < text.length && WHITESPACE.test(text[i]!)) i += 1;
476
+ if (text[i] === ":") {
477
+ if (i < stopped) continue;
478
+ i += 1;
479
+ while (i < text.length && text[i] !== "=" && text[i] !== "\n") i += 1;
480
+ stopped = i;
481
+ }
482
+ if (text[i] !== "=") continue;
483
+ i += 1;
484
+ while (i < text.length && WHITESPACE.test(text[i]!)) i += 1;
485
+ if (text[i] !== "{") continue;
486
+ const close = text.indexOf("}", i + 1);
487
+ if (close < 0) return undefined; // No `}` after this `{`: none after a later one either.
488
+ return text.slice(i + 1, close);
489
+ }
490
+ return undefined;
491
+ }
492
+
493
+ /**
494
+ * A3, QA-1 M2: the values of the `'key': 'value'` pairs of a finder `MAPPING` body (each value's text, still escaped), in
495
+ * linear time. It replaces the regular expression `(['"])(?:\\.|(?!\1)[^\\])*\1\s*:\s*(['"])((?:\\.|(?!\2)[^\\])*)\2`, which
496
+ * retried at every quote and so was quadratic on `'\'\'\'…`: string literals are read left to right as Python reads them, each
497
+ * once (a quote inside a literal opens none); a literal followed by `:` and another literal is a pair. The two agree on the
498
+ * `repr` text setuptools writes. An unclosed literal ends the reading (the file is no valid Python past it).
499
+ */
500
+ export function finderMappingValues(body: string): string[] {
501
+ const values: string[] = [];
502
+ /** The end (after the closing quote) of the string literal opening at `start`, or -1 when it is not closed. */
503
+ const literalEnd = (start: number): number => {
504
+ const quote = body[start];
505
+ for (let i = start + 1; i < body.length; i++) {
506
+ if (body[i] === "\\") i += 1;
507
+ else if (body[i] === quote) return i + 1;
508
+ }
509
+ return -1;
510
+ };
511
+ const isQuote = (c: string | undefined): boolean => c === "'" || c === '"';
512
+ let i = 0;
513
+ while (i < body.length) {
514
+ if (!isQuote(body[i])) {
515
+ i += 1;
516
+ continue;
517
+ }
518
+ const keyEnd = literalEnd(i);
519
+ if (keyEnd < 0) return values; // Unclosed: no valid Python past it.
520
+ let j = keyEnd;
521
+ while (j < body.length && WHITESPACE.test(body[j]!)) j += 1;
522
+ if (body[j] !== ":") {
523
+ i = keyEnd;
524
+ continue;
525
+ }
526
+ j += 1;
527
+ while (j < body.length && WHITESPACE.test(body[j]!)) j += 1;
528
+ if (!isQuote(body[j])) {
529
+ i = j;
530
+ continue;
531
+ }
532
+ const valueEnd = literalEnd(j);
533
+ if (valueEnd < 0) return values;
534
+ values.push(body.slice(j + 1, valueEnd - 1));
535
+ i = valueEnd;
536
+ }
537
+ return values;
538
+ }
539
+
540
+ /**
541
+ * Cross-repo P3c.1 (SD-P3c-1..10, D24): the dependency edges `root` declares outside `node_modules`, Tier A only (see the
542
+ * module comment). Targets lexically inside `root` are not edges and are dropped; the others are de-duplicated (first
543
+ * declaration wins) and capped at `limits.edges`. Synchronous, never throws, never evaluates repository code; every file is
544
+ * stat'ed (size checked) before it is read, and read at most once.
545
+ */
546
+ export function declaredEdges(root: string, io: EdgeIO = defaultEdgeIO, limits: EdgeLimits = EDGE_LIMITS): DeclaredEdges {
547
+ const edges: DeclaredEdge[] = [];
548
+ if (isUncSpec(root)) return { edges, incomplete: true }; // A UNC root is never read.
549
+ const base = path.resolve(root);
550
+ const targets = new Set<string>();
551
+ const seen = new Set<string>();
552
+ let files = 0;
553
+ let incomplete = false;
554
+
555
+ const isFile = (file: string): boolean => {
556
+ try {
557
+ return io.stat(file).isFile();
558
+ } catch {
559
+ return false;
560
+ }
561
+ };
562
+ const isDirectory = (dir: string): boolean => {
563
+ try {
564
+ return io.stat(dir).isDirectory();
565
+ } catch {
566
+ return false;
567
+ }
568
+ };
569
+ const list = (dir: string): string[] => {
570
+ let names: string[];
571
+ try {
572
+ names = io.readdir(dir, limits.entries);
573
+ } catch {
574
+ return [];
575
+ }
576
+ if (names.length <= limits.entries) return names;
577
+ incomplete = true;
578
+ return names.slice(0, limits.entries);
579
+ };
580
+ /** Stat (size check), then read: `undefined` when absent, not a file, already read, too large or past the file cap. */
581
+ const readText = (file: string): string | undefined => {
582
+ const key = perimeterKey(file);
583
+ if (seen.has(key)) return undefined;
584
+ let size: number;
585
+ try {
586
+ const stat = io.stat(file);
587
+ if (!stat.isFile()) return undefined;
588
+ size = stat.size;
589
+ } catch {
590
+ return undefined;
591
+ }
592
+ seen.add(key);
593
+ if (size > limits.bytes || files >= limits.files) {
594
+ incomplete = true;
595
+ return undefined;
596
+ }
597
+ files += 1;
598
+ let text: string;
599
+ try {
600
+ text = io.readFile(file);
601
+ } catch {
602
+ return undefined;
603
+ }
604
+ if (text.length > limits.bytes) {
605
+ incomplete = true;
606
+ return undefined;
607
+ }
608
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
609
+ };
610
+ const add = (kind: EdgeKind, raw: string, via: EdgeVia, file: string): void => {
611
+ const spec = raw.trim();
612
+ if (spec === "" || spec.includes("\0")) return;
613
+ if (kind === "tsconfig" && spec.includes("${configDir}")) return; // The config's own directory.
614
+ const unc = isUncSpec(spec);
615
+ let key: string;
616
+ if (unc) {
617
+ key = `unc:${spec.replace(/\\/g, "/").toLowerCase()}`;
618
+ } else {
619
+ const target = path.resolve(path.dirname(file), spec);
620
+ if (insideOrEqual(target, base)) return;
621
+ // QA-2 F-2: an overlong spec (never walked, so unadmitted) keys apart: it never drops a later spelling of its target.
622
+ key = spec.length > EDGE_SPEC_MAX ? `overlong:${perimeterKey(target)}` : perimeterKey(target);
623
+ }
624
+ if (targets.has(key)) return;
625
+ if (targets.size >= limits.edges) {
626
+ incomplete = true;
627
+ return;
628
+ }
629
+ targets.add(key);
630
+ const from = path.relative(base, file).split(path.sep).join("/");
631
+ edges.push(unc ? { kind, spec, via, from, unc: true } : { kind, spec, via, from });
632
+ };
633
+
634
+ /** A1: one `package.json`; returns the manifest (for `workspaces`). */
635
+ const packageJson = (dir: string): Record<string, unknown> | undefined => {
636
+ const file = path.join(dir, "package.json");
637
+ const text = readText(file);
638
+ if (text === undefined) return undefined;
639
+ let manifest: unknown;
640
+ try {
641
+ manifest = JSON.parse(text);
642
+ } catch {
643
+ return undefined;
644
+ }
645
+ if (!isRecord(manifest)) return undefined;
646
+ const overrides = (value: unknown, depth: number, out: string[]): string[] => {
647
+ if (!isRecord(value)) return out;
648
+ for (const entry of Object.values(value)) {
649
+ if (typeof entry === "string") out.push(entry);
650
+ else if (isRecord(entry) && depth > 1) overrides(entry, depth - 1, out);
651
+ else if (isRecord(entry)) incomplete = true;
652
+ }
653
+ return out;
654
+ };
655
+ for (const field of PACKAGE_EDGE_FIELDS) {
656
+ const value = field === "pnpm.overrides" ? (isRecord(manifest.pnpm) ? manifest.pnpm.overrides : undefined) : manifest[field];
657
+ const specs = field === "overrides"
658
+ ? overrides(value, EDGE_OVERRIDES_DEPTH_MAX, [])
659
+ : isRecord(value) ? Object.values(value).filter((entry): entry is string => typeof entry === "string") : [];
660
+ for (const spec of specs) {
661
+ const target = packagePathSpec(spec);
662
+ if (target !== undefined) add("package", target.path, `package.json ${field} (${target.protocol})`, file);
663
+ }
664
+ }
665
+ return manifest;
666
+ };
667
+
668
+ /** A2: one tsconfig/jsconfig (JSONC), and the `extends` chain inside the root up to `limits.extendsDepth`. */
669
+ const tsconfig = (file: string, depth: number): void => {
670
+ const text = readText(file);
671
+ if (text === undefined) return;
672
+ const config = parseJsonc(text);
673
+ if (!isRecord(config)) return;
674
+ const dir = path.dirname(file);
675
+ const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
676
+ const extendsSpecs = typeof config.extends === "string" ? [config.extends] : strings(config.extends);
677
+ // QA-1 M2: at most EDGE_EXTENDS_ENTRIES_MAX entries, each followed (a stat or two) only while the file cap has room.
678
+ if (extendsSpecs.length > EDGE_EXTENDS_ENTRIES_MAX) incomplete = true;
679
+ for (const spec of extendsSpecs.slice(0, EDGE_EXTENDS_ENTRIES_MAX)) {
680
+ if (!isPathSpec(spec)) continue; // A package name: resolved through node_modules, not an edge.
681
+ add("tsconfig", spec, "tsconfig extends", file);
682
+ if (isUncSpec(spec)) continue;
683
+ const target = path.resolve(dir, spec);
684
+ if (!insideOrEqual(target, base)) continue;
685
+ if (depth >= limits.extendsDepth) {
686
+ incomplete = true;
687
+ continue;
688
+ }
689
+ if (files >= limits.files) {
690
+ // Past the file cap: not stat'ed at all (a cut), unless it was read already (a cycle, no cut).
691
+ if (!seen.has(perimeterKey(target)) && !seen.has(perimeterKey(`${target}.json`))) incomplete = true;
692
+ continue;
693
+ }
694
+ tsconfig(isFile(target) || target.toLowerCase().endsWith(".json") ? target : `${target}.json`, depth + 1);
695
+ }
696
+ for (const reference of Array.isArray(config.references) ? config.references : []) {
697
+ if (isRecord(reference) && typeof reference.path === "string") add("tsconfig", reference.path, "tsconfig references", file);
698
+ }
699
+ const options = isRecord(config.compilerOptions) ? config.compilerOptions : {};
700
+ const baseUrl = typeof options.baseUrl === "string" ? options.baseUrl : undefined;
701
+ if (baseUrl !== undefined) add("tsconfig", baseUrl, "tsconfig baseUrl", file);
702
+ if (isRecord(options.paths)) {
703
+ for (const values of Object.values(options.paths)) {
704
+ for (const value of strings(values)) add("tsconfig", joinBaseUrl(baseUrl, staticPrefix(value)), "tsconfig paths", file);
705
+ }
706
+ }
707
+ for (const value of strings(options.rootDirs)) add("tsconfig", value, "tsconfig rootDirs", file);
708
+ for (const value of strings(options.typeRoots)) add("tsconfig", value, "tsconfig typeRoots", file);
709
+ for (const value of strings(config.include)) add("tsconfig", staticPrefix(value), "tsconfig include", file);
710
+ for (const value of strings(config.files)) add("tsconfig", staticPrefix(value), "tsconfig files", file);
711
+ };
712
+
713
+ /** A4: `go.mod` (`replace`) or `go.work` (`use`, `replace`), single and block forms. */
714
+ const goFile = (file: string, work: boolean): void => {
715
+ const text = readText(file);
716
+ if (text === undefined) return;
717
+ const directive = (verb: string, args: string): void => {
718
+ if (verb === "replace") {
719
+ const arrow = args.indexOf("=>");
720
+ const target = arrow < 0 ? undefined : goTokens(args.slice(arrow + 2))[0];
721
+ if (target !== undefined && isLocalGoPath(target)) add("go", target, work ? "go.work replace" : "go.mod replace", file);
722
+ } else if (verb === "use" && work) {
723
+ const target = goTokens(args)[0];
724
+ if (target !== undefined) add("go", target, "go.work use", file);
725
+ }
726
+ };
727
+ let block: string | undefined;
728
+ for (const raw of text.split(/\r?\n|\r/)) {
729
+ const line = stripGoComment(raw).trim();
730
+ if (line === "") continue;
731
+ if (block !== undefined) {
732
+ if (line === ")") block = undefined;
733
+ else directive(block, line);
734
+ continue;
735
+ }
736
+ const open = /^(\w+)\s*\($/.exec(line);
737
+ if (open !== null) {
738
+ block = open[1];
739
+ continue;
740
+ }
741
+ const single = /^(\w+)\s+(.+)$/.exec(line);
742
+ if (single !== null) directive(single[1]!, single[2]!);
743
+ }
744
+ };
745
+
746
+ /** A3: the editable installs of the root's venv (`.venv`, else `venv`, holding `pyvenv.cfg`). */
747
+ const venv = (): void => {
748
+ const home = [".venv", "venv"].map((name) => path.join(base, name)).find((dir) => isFile(path.join(dir, "pyvenv.cfg")));
749
+ if (home === undefined) return;
750
+ const candidates = [path.join(home, "Lib", "site-packages")];
751
+ for (const name of list(path.join(home, "lib")).filter((entry) => entry.startsWith("python3.")).sort(byCodeUnit)) {
752
+ candidates.push(path.join(home, "lib", name, "site-packages"));
753
+ }
754
+ const site = candidates.find(isDirectory);
755
+ if (site === undefined) return;
756
+ const names = list(site).filter((name) => SITE_FILE.test(name)).sort(byCodeUnit);
757
+ if (names.length > limits.siteFiles) incomplete = true;
758
+ for (const name of names.slice(0, limits.siteFiles)) {
759
+ const file = path.join(site, name);
760
+ const text = readText(file);
761
+ if (text === undefined) continue;
762
+ const lower = name.toLowerCase();
763
+ if (lower.endsWith(".pth")) {
764
+ for (const line of text.split(/\r?\n|\r/)) {
765
+ const entry = line.trim();
766
+ if (entry === "" || entry.startsWith("#") || /^import[ \t]/.test(entry)) continue; // `import` lines run code: skipped.
767
+ add("python", entry, "python editable install", file);
768
+ }
769
+ } else if (lower.endsWith(".egg-link")) {
770
+ add("python", text.split(/\r?\n|\r/)[0] ?? "", "python editable install", file);
771
+ } else {
772
+ // setuptools >= 64 editable finder: the `MAPPING` dict literal, read as text in linear time (QA-1 M2), never executed.
773
+ const mapping = finderMappingBody(text);
774
+ if (mapping === undefined) continue;
775
+ for (const value of finderMappingValues(mapping)) add("python", pythonString(value), "python editable install", file);
776
+ }
777
+ }
778
+ };
779
+
780
+ const manifest = packageJson(base);
781
+ tsconfig(path.join(base, "tsconfig.json"), 0);
782
+ tsconfig(path.join(base, "jsconfig.json"), 0);
783
+ const variants = list(base).filter((name) => /^tsconfig\..+\.json$/i.test(name)).sort(byCodeUnit);
784
+ if (variants.length > limits.tsconfigVariants) incomplete = true;
785
+ for (const name of variants.slice(0, limits.tsconfigVariants)) tsconfig(path.join(base, name), 0);
786
+ goFile(path.join(base, "go.mod"), false);
787
+ goFile(path.join(base, "go.work"), true);
788
+ venv();
789
+ if (manifest !== undefined) {
790
+ const dirs = new Map<string, string>();
791
+ // QA-1 M2: at most EDGE_WORKSPACE_PATTERNS_MAX patterns, their listings reading EDGE_WORKSPACE_ENTRIES_MAX names in total.
792
+ const patterns = workspacePatterns(manifest);
793
+ if (patterns.length > EDGE_WORKSPACE_PATTERNS_MAX) incomplete = true;
794
+ let listed = 0;
795
+ for (const pattern of patterns.slice(0, EDGE_WORKSPACE_PATTERNS_MAX)) {
796
+ if (dirs.size > limits.workspaces) break;
797
+ const budget = Math.max(0, Math.min(limits.entries, EDGE_WORKSPACE_ENTRIES_MAX - listed));
798
+ if (budget === 0 && pattern.includes("*")) {
799
+ incomplete = true; // A wildcard needs a listing, and the total is spent; a literal pattern lists nothing.
800
+ continue;
801
+ }
802
+ const found = matchWorkspace(base, pattern, limits.workspaces + 1 - dirs.size, io, budget);
803
+ listed += found.listed;
804
+ if (found.cut) incomplete = true;
805
+ for (const dir of found.dirs) {
806
+ const key = perimeterKey(dir);
807
+ if (key !== perimeterKey(base) && !dirs.has(key)) dirs.set(key, dir);
808
+ }
809
+ }
810
+ if (dirs.size > limits.workspaces) incomplete = true;
811
+ for (const dir of [...dirs.values()].slice(0, limits.workspaces)) {
812
+ packageJson(dir);
813
+ tsconfig(path.join(dir, "tsconfig.json"), 0);
814
+ }
815
+ }
816
+ return { edges, incomplete };
817
+ }