@diffci.com/diffci 0.3.13 → 0.3.14

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 (65) hide show
  1. package/dist-client/src/client/agent-selection.js +4 -1
  2. package/dist-client/src/client/cli.js +4 -49
  3. package/dist-client/src/client/command-batches.js +80 -0
  4. package/dist-client/src/client/failure-baseline.js +99 -0
  5. package/dist-client/src/client/observe.js +11 -3
  6. package/dist-client/src/client/pilot-packet.js +0 -31
  7. package/dist-client/src/client/verify-savings.js +12 -1
  8. package/dist-client/src/client/verify.js +53 -5
  9. package/dist-client/src/client/workflow-templates.js +80 -0
  10. package/node_modules/@diffci.com/core/README.md +13 -7
  11. package/node_modules/@diffci.com/core/dist/analyze.js +2 -1
  12. package/node_modules/@diffci.com/core/dist/analyze.js.map +1 -1
  13. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  14. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  15. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +9 -0
  16. package/node_modules/@diffci.com/core/dist/git/git-diff.js +122 -19
  17. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  18. package/node_modules/@diffci.com/core/dist/git/types.d.ts +9 -0
  19. package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -3
  20. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  21. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +99 -42
  22. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.d.ts +16 -0
  24. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js +101 -0
  25. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js.map +1 -0
  26. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +68 -0
  27. package/node_modules/@diffci.com/core/dist/repo/file-references.js +278 -0
  28. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -0
  29. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -2
  30. package/node_modules/@diffci.com/core/dist/repo/graph.js +107 -31
  31. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +7 -1
  33. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +32 -0
  34. package/node_modules/@diffci.com/core/dist/repo/impact.js +241 -20
  35. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  36. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +9 -3
  37. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  38. package/node_modules/@diffci.com/core/dist/repo/script-universe.d.ts +16 -0
  39. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +173 -0
  40. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -0
  41. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +12 -0
  42. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +54 -7
  43. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  44. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +8 -0
  45. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.d.ts +15 -0
  46. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +157 -0
  47. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -0
  48. package/node_modules/@diffci.com/core/package.json +5 -0
  49. package/node_modules/@diffci.com/core/src/analyze.ts +2 -1
  50. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  51. package/node_modules/@diffci.com/core/src/git/git-diff.ts +106 -20
  52. package/node_modules/@diffci.com/core/src/git/types.ts +9 -0
  53. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -3
  54. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +120 -30
  55. package/node_modules/@diffci.com/core/src/repo/compiled-projects.ts +108 -0
  56. package/node_modules/@diffci.com/core/src/repo/file-references.ts +275 -0
  57. package/node_modules/@diffci.com/core/src/repo/graph.ts +104 -31
  58. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +10 -0
  59. package/node_modules/@diffci.com/core/src/repo/impact.ts +243 -18
  60. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +6 -3
  61. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +158 -0
  62. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +62 -7
  63. package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
  64. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +117 -0
  65. package/package.json +2 -2
@@ -0,0 +1,108 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Tests that observe code by compiling it (2026-10-21).
4
+ *
5
+ * WHY. A test can check a TypeScript project without importing any of it, by running the compiler on
6
+ * a named project and then executing the output: `execFileSync(node, [".../typescript/bin/tsc", "-p",
7
+ * "tsconfig.client.json"])`, then spawning the built CLI. The dependency graph has no edge from such a
8
+ * test to the files it compiles, so a change that breaks the build selected nothing that would notice.
9
+ * Replaying a dogfood repository's history found exactly this: a change to `src/client/cli.ts`
10
+ * selected 117 tests and left out the one that builds and runs the CLI.
11
+ *
12
+ * THE RULE. A test that both invokes the compiler (tsc, typescript/bin/tsc, createProgram, --project)
13
+ * and names a `tsconfig*.json` that exists at HEAD compiles that project. The project is its root files
14
+ * (`files`, `include` and `exclude`, inherited through `extends` when absent) and everything those
15
+ * roots import, which is what tsc compiles too. A change to any of those files selects the test.
16
+ *
17
+ * Over-inclusion is the safe direction: a test that merely writes a tsconfig.json fixture and calls
18
+ * createProgram on a temporary repository is also treated as compiling the real project.
19
+ */
20
+ import { posix } from "node:path";
21
+ import ts from "typescript";
22
+ import { referencePattern, referenceTokens } from "./file-references.js";
23
+ import { matchesGlob } from "./test-discovery.js";
24
+
25
+ const COMPILER_INVOCATION = /["'`/\s]tsc(?:\.cmd)?["'`\s]|typescript["'`/,\s]+bin["'`/,\s]+tsc|\bcreateProgram\b|--project\b|["'`]-p["'`]/;
26
+ const PROJECT_CONFIG = /(?:^|\/)tsconfig[^/]*\.json$/;
27
+ const COMPILABLE = /\.(?:[cm]?tsx?|[cm]?jsx?)$/;
28
+
29
+ export interface CompiledProjectInput {
30
+ files: readonly string[];
31
+ read: (path: string) => string | undefined;
32
+ isTestFile: (path: string) => boolean;
33
+ /** Every file a root transitively imports, from the dependency graph. */
34
+ dependenciesOf: (path: string) => readonly string[];
35
+ }
36
+
37
+ export interface CompiledProject {
38
+ config: string;
39
+ tests: string[];
40
+ files: ReadonlySet<string>;
41
+ }
42
+
43
+ interface RootSpec { files?: string[]; include?: string[]; exclude?: string[]; allowJs?: boolean }
44
+
45
+ function readSpec(config: string, read: CompiledProjectInput["read"], depth = 0): RootSpec | undefined {
46
+ const text = read(config);
47
+ if (text === undefined || depth > 5) return undefined;
48
+ const parsed = ts.parseConfigFileTextToJson(config, text);
49
+ if (parsed.error || !parsed.config || typeof parsed.config !== "object") return undefined;
50
+ const json = parsed.config as { files?: unknown; include?: unknown; exclude?: unknown; extends?: unknown; compilerOptions?: { allowJs?: unknown } };
51
+ const dir = posix.dirname(config);
52
+ const local = (values: unknown) => Array.isArray(values) ? values.filter((v): v is string => typeof v === "string").map((v) => posix.normalize(posix.join(dir, v))) : undefined;
53
+ let spec: RootSpec = { files: local(json.files), include: local(json.include), exclude: local(json.exclude), allowJs: json.compilerOptions?.allowJs === true ? true : undefined };
54
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends.filter((e): e is string => typeof e === "string") : [];
55
+ for (const parent of parents) {
56
+ if (!parent.startsWith(".")) continue;
57
+ const parentPath = posix.normalize(posix.join(dir, parent.endsWith(".json") ? parent : `${parent}.json`));
58
+ const inherited = readSpec(parentPath, read, depth + 1);
59
+ if (!inherited) continue;
60
+ spec = { files: spec.files ?? inherited.files, include: spec.include ?? inherited.include, exclude: spec.exclude ?? inherited.exclude, allowJs: spec.allowJs ?? inherited.allowJs };
61
+ }
62
+ return spec;
63
+ }
64
+
65
+ function asGlob(pattern: string): string {
66
+ if (/[*?]/.test(pattern) || posix.extname(pattern)) return pattern;
67
+ return `${pattern.replace(/\/$/, "")}/**/*`;
68
+ }
69
+
70
+ /** Root files of a project, as tsc would list them before following imports. */
71
+ export function projectRoots(config: string, input: Pick<CompiledProjectInput, "files" | "read">): string[] | undefined {
72
+ const spec = readSpec(config, input.read);
73
+ if (!spec) return undefined;
74
+ const dir = posix.dirname(config);
75
+ const roots = new Set(spec.files ?? []);
76
+ const include = spec.include ?? (spec.files ? [] : [posix.join(dir, "**/*")]);
77
+ const exclude = (spec.exclude ?? []).map(asGlob);
78
+ const extensions = spec.allowJs ? COMPILABLE : /\.(?:[cm]?tsx?)$/;
79
+ for (const pattern of include.map(asGlob)) {
80
+ for (const file of input.files) {
81
+ if (!extensions.test(file) || file.endsWith(".d.ts") || file.split("/").includes("node_modules")) continue;
82
+ if (matchesGlob(file, pattern) && !exclude.some((glob) => matchesGlob(file, glob))) roots.add(file);
83
+ }
84
+ }
85
+ return [...roots].sort();
86
+ }
87
+
88
+ /** Projects that some test compiles, with the tests and every file each compiles. */
89
+ export function compiledProjects(input: CompiledProjectInput): CompiledProject[] {
90
+ const configs = input.files.filter((file) => PROJECT_CONFIG.test(file));
91
+ if (configs.length === 0) return [];
92
+ const compilingTests = input.files.filter((file) => input.isTestFile(file) && COMPILABLE.test(file))
93
+ .map((file) => ({ file, text: input.read(file) ?? "" }))
94
+ .filter(({ text }) => COMPILER_INVOCATION.test(text));
95
+ const projects: CompiledProject[] = [];
96
+ for (const config of configs) {
97
+ const names = referencePattern(referenceTokens(config, { ancestors: false }));
98
+ const tests = compilingTests.filter(({ text }) => names.test(text)).map(({ file }) => file);
99
+ if (tests.length === 0) continue;
100
+ const roots = projectRoots(config, input);
101
+ if (!roots) continue;
102
+ const files = new Set<string>(roots);
103
+ for (const root of roots) for (const dependency of input.dependenciesOf(root)) files.add(dependency);
104
+ files.add(config);
105
+ projects.push({ config, tests: tests.sort(), files });
106
+ }
107
+ return projects;
108
+ }
@@ -0,0 +1,275 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Who reads this file? (2026-10-21, telemetry from two dogfood repositories.)
4
+ *
5
+ * WHY. A changed file that is not code - `site/docs/x.html`, `scripts/train.py`, `ops/.../blockers.json`,
6
+ * `.env.example` - previously meant "Unknown changed file" and a full run. Across 256 verification
7
+ * receipts this was the third most common fallback (76 receipts), and 138 of one repository's unknown files
8
+ * were site HTML whose only readers are two tests. The engine has no import edge for these, because tests
9
+ * reach them through the filesystem: `readFileSync(join(root, "site", ...))`, `readdirSync("fixtures")`,
10
+ * `spawn("python3", ["scripts/train.py"])`.
11
+ *
12
+ * THE RULE. A test suite can only observe a non-code file by naming it, or by naming a directory that
13
+ * contains it. So: collect every text file at HEAD that names the changed file's path, its basename, or
14
+ * one of its ancestor directories as a string, and resolve each reader:
15
+ *
16
+ * - a test reader is selected;
17
+ * - a code reader in the dependency graph selects the tests that depend on it;
18
+ * - a package.json reader counts only when the naming script runs as part of `npm test`;
19
+ * - a test-running workflow, a composite action or an unparseable package.json is unresolvable;
20
+ * - documentation names files constantly and executes nothing, so it is never a reader;
21
+ * - any other file - a shell script, a JSON manifest, or code no test imports (a standalone check
22
+ * script outside the dependency graph) - may itself be executed or read, so ITS readers are
23
+ * resolved in turn, to a bounded depth. A test can only run such a file by naming it.
24
+ *
25
+ * FAILING CLOSED. No reader at all, or any unresolvable reader, keeps the file unknown (full run).
26
+ * Evidence of who reads a file is required before anything narrows; the absence of a reference is never
27
+ * treated as proof that nothing reads it. Files that tools load implicitly, without any code naming them
28
+ * (`.gitignore`, `.env`, `tsconfig.json`, `wrangler.toml`, `Dockerfile`), never reach this resolver.
29
+ *
30
+ * RESIDUAL RISK. A reader that computes the path from parts that never appear as strings, or walks the
31
+ * whole repository from its root without naming a directory, is invisible here. Required CI stays
32
+ * authoritative for exactly that reason.
33
+ */
34
+ import { readFileSync, statSync } from "node:fs";
35
+ import { join, posix } from "node:path";
36
+
37
+ const MAX_READ_BYTES = 1_048_576;
38
+
39
+ /** Reads repo-relative text files from a checkout at HEAD, the same tree the dependency graph reads.
40
+ * Binary content (a NUL byte in the first 8 KiB) and files over 1 MiB are unreadable. */
41
+ export function repositoryFileReader(repoPath: string): (path: string) => string | undefined {
42
+ return (path) => {
43
+ try {
44
+ const full = join(repoPath, path);
45
+ if (statSync(full).size > MAX_READ_BYTES) return undefined;
46
+ const bytes = readFileSync(full);
47
+ if (bytes.subarray(0, 8192).includes(0)) return undefined;
48
+ return bytes.toString("utf8");
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ };
53
+ }
54
+
55
+ /** Names tools read without any code naming them. A change to one of these is never reference-resolved. */
56
+ const IMPLICIT_BASENAMES = new Set([
57
+ ".gitignore", ".gitattributes", ".gitmodules", ".npmrc", ".yarnrc", ".yarnrc.yml", ".nvmrc", ".node-version",
58
+ ".tool-versions", ".editorconfig", ".browserslistrc", ".babelrc", ".swcrc", ".mocharc", ".c8rc", ".nycrc",
59
+ "makefile", "procfile", "justfile", "taskfile.yml", "compose.yaml", "compose.yml", "turbo.json", "nx.json", "lerna.json",
60
+ ]);
61
+ const IMPLICIT_PREFIXES = ["tsconfig", "jsconfig", "wrangler.", "dockerfile", "docker-compose", ".dockerignore", ".mocharc.", ".c8rc.", ".nycrc.", "babel.config", ".babelrc."];
62
+ const ENV_TEMPLATE_SUFFIX = /\.(?:example|sample|template|dist)$/;
63
+
64
+ /** True when tooling may load `filePath` implicitly, so no reference to it would ever be written. */
65
+ export function isImplicitlyLoadedFile(filePath: string): boolean {
66
+ const base = posix.basename(filePath).toLowerCase();
67
+ if (IMPLICIT_BASENAMES.has(base)) return true;
68
+ if (IMPLICIT_PREFIXES.some((prefix) => base.startsWith(prefix))) return true;
69
+ if (/\.config\.[^.]+$/.test(base)) return true;
70
+ if (base === ".env" || (base.startsWith(".env.") && !ENV_TEMPLATE_SUFFIX.test(base))) return true;
71
+ return /\.(?:tf|tfvars|hcl)$/.test(base);
72
+ }
73
+
74
+ const INFRASTRUCTURE_DIRS = new Set(["ops", "terraform", "cloudformation", "pulumi", "cdktf", "deploy", "deployments", "kubernetes", "k8s", "helm", "docker"]);
75
+ const CODE_EXTENSIONS = /\.(?:[cm]?[jt]sx?|vue|go|java|kt)$/i;
76
+ const DOCUMENT_EXTENSIONS = /\.(?:md|mdx)$/i;
77
+
78
+ /**
79
+ * What a file under an infrastructure directory is (2026-10-21). Everything under `ops/` used to force
80
+ * full validation - 55 of one dogfood repository's 124 receipts - yet that tree holds tested Worker code, runbooks
81
+ * and JSON evidence manifests as well as deployment definitions. Only a definition that tooling loads by
82
+ * convention is global; code goes through the dependency graph, Markdown is documentation, and other
83
+ * files are data whose readers are resolved by reference. `undefined` outside infrastructure trees.
84
+ */
85
+ export function infrastructureRole(filePath: string): "definition" | "code" | "documentation" | "data" | undefined {
86
+ const base = posix.basename(filePath);
87
+ if (/dockerfile/i.test(base)) return "definition";
88
+ const first = filePath.split("/")[0];
89
+ if (!first || !INFRASTRUCTURE_DIRS.has(first) || !filePath.includes("/")) return undefined;
90
+ if (isImplicitlyLoadedFile(filePath)) return "definition";
91
+ if (CODE_EXTENSIONS.test(base)) return "code";
92
+ if (DOCUMENT_EXTENSIONS.test(base)) return "documentation";
93
+ return "data";
94
+ }
95
+
96
+ interface ReferenceToken { value: string; bare: boolean }
97
+
98
+ /** The strings whose appearance means a file names `filePath`: the path itself, its basename, and every
99
+ * ancestor directory (as a path and as a name). A bare name (no dot, no slash) must be delimited by
100
+ * quotes or slashes on both sides, so prose and identifiers do not match; anything else may also be
101
+ * delimited by whitespace, as in a shell command line.
102
+ *
103
+ * `ancestors: false` drops the directories. A script is run by naming it, so following who runs a code
104
+ * reader needs only its path and basename; in one dogfood repository the bare `"scripts"` matched nearly every
105
+ * file and no change under `site/` could ever resolve (2026-10-21 replay). */
106
+ export function referenceTokens(filePath: string, { ancestors = true }: { ancestors?: boolean } = {}): ReferenceToken[] {
107
+ const tokens = new Map<string, ReferenceToken>();
108
+ const add = (value: string) => { if (value && value !== ".") tokens.set(value, { value, bare: !/[./]/.test(value) }); };
109
+ add(filePath);
110
+ add(posix.basename(filePath));
111
+ let dir = posix.dirname(filePath);
112
+ while (ancestors && dir !== "." && dir !== "/") { add(dir); add(posix.basename(dir)); dir = posix.dirname(dir); }
113
+ return [...tokens.values()];
114
+ }
115
+
116
+ function escape(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
117
+
118
+ /** One regular expression matching any of `tokens` at a reference boundary. */
119
+ export function referencePattern(tokens: readonly ReferenceToken[]): RegExp {
120
+ const parts = tokens.map(({ value, bare }) => bare
121
+ ? `["'\`/]${escape(value)}(?=["'\`/])`
122
+ : `(?:^|["'\`/\\s=(])${escape(value)}(?=$|["'\`/\\s),;:])`);
123
+ return new RegExp(parts.join("|"), "m");
124
+ }
125
+
126
+ export type ReaderKind = "test" | "graph-code" | "package-script" | "documentation" | "transitive" | "unresolvable";
127
+
128
+ export interface ReferenceResolutionInput {
129
+ /** Repo-relative paths present at HEAD. */
130
+ files: readonly string[];
131
+ /** Reads a repo-relative file at HEAD; undefined for unreadable, binary or oversized content. */
132
+ read: (path: string) => string | undefined;
133
+ isTestFile: (path: string) => boolean;
134
+ isDocumentation: (path: string) => boolean;
135
+ /** Whether a code file is part of the dependency graph. */
136
+ inGraph: (path: string) => boolean;
137
+ isCodeFile: (path: string) => boolean;
138
+ /** Whether something a workflow names can reach the test suite through it, given a pattern matching
139
+ * the name (src/repo/workflow-test-steps.ts, workflowFeedsTests). */
140
+ workflowFeedsTests: (content: string, names: RegExp) => boolean;
141
+ /** Changed files whose content analyzeGitDelta proved cannot change how tests run
142
+ * (GitDeltaAnalysis.referenceResolvedPaths); a workflow reading them does not block. */
143
+ contentCleared?: ReadonlySet<string>;
144
+ }
145
+
146
+ export interface ReferenceResolution {
147
+ /** Tests that name the file, directly or through a chain of non-code readers. */
148
+ tests: string[];
149
+ /** Graph code that names the file; its dependent tests are selected by the caller. */
150
+ code: string[];
151
+ /** Why the file cannot be narrowed; empty when it can. */
152
+ unresolvable: string[];
153
+ /** Every reader found, for evidence. */
154
+ readers: Array<{ path: string; kind: ReaderKind; via: string }>;
155
+ }
156
+
157
+ const MAX_DEPTH = 5;
158
+ const MAX_TRANSITIVE_READERS = 50;
159
+ const LOCKFILES = new Set(["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock", "bun.lockb", "npm-shrinkwrap.json"]);
160
+ const TEST_LIFECYCLE = ["pretest", "test", "posttest", "prepare", "preinstall", "install", "postinstall"];
161
+ /** Non-code files that can run something or direct what code reads: shell and interpreter scripts,
162
+ * and structured manifests. Only these are followed to their own readers. */
163
+ const DIRECTING_EXTENSIONS = /\.(?:sh|bash|zsh|ps1|psm1|bat|cmd|py|rb|pl|json|jsonc|json5|ya?ml|toml|ini|cfg|conf)$/i;
164
+
165
+ /** Script names reachable from `npm test`, including lifecycle hooks and any script one of those bodies
166
+ * names. Over-inclusive by design: a script name appearing anywhere in a reachable body is followed. */
167
+ export function testScriptClosure(scripts: Readonly<Record<string, string>>): Set<string> {
168
+ const closure = new Set<string>();
169
+ const queue = TEST_LIFECYCLE.filter((name) => typeof scripts[name] === "string");
170
+ while (queue.length > 0) {
171
+ const name = queue.shift()!;
172
+ if (closure.has(name)) continue;
173
+ closure.add(name);
174
+ for (const hook of [`pre${name}`, `post${name}`]) if (typeof scripts[hook] === "string") queue.push(hook);
175
+ const body = scripts[name] ?? "";
176
+ for (const candidate of Object.keys(scripts)) {
177
+ if (!closure.has(candidate) && new RegExp(`(?:^|[\\s"'=&|;(])${escape(candidate)}(?=$|[\\s"'&|;)])`).test(body)) queue.push(candidate);
178
+ }
179
+ }
180
+ return closure;
181
+ }
182
+
183
+ function packageJsonNames(content: string, pattern: RegExp): "yes" | "no" | "unparseable" {
184
+ let parsed: unknown;
185
+ try { parsed = JSON.parse(content); } catch { return "unparseable"; }
186
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "unparseable";
187
+ const scripts = (parsed as { scripts?: unknown }).scripts;
188
+ if (!scripts || typeof scripts !== "object") return "no";
189
+ const record = Object.fromEntries(Object.entries(scripts).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
190
+ for (const name of testScriptClosure(record)) if (pattern.test(record[name] ?? "")) return "yes";
191
+ return "no";
192
+ }
193
+
194
+ /** Resolves who reads `filePath`. See the module comment for the rule and its limits. */
195
+ export function resolveFileReferences(filePath: string, input: ReferenceResolutionInput): ReferenceResolution {
196
+ const resolution: ReferenceResolution = { tests: [], code: [], unresolvable: [], readers: [] };
197
+ const tests = new Set<string>();
198
+ const code = new Set<string>();
199
+ const visited = new Set<string>([filePath]);
200
+ let frontier: Array<{ path: string; via: string }> = [{ path: filePath, via: filePath }];
201
+ let transitiveCount = 0;
202
+ const contents = new Map<string, string | undefined>();
203
+ const read = (path: string) => { if (!contents.has(path)) contents.set(path, input.read(path)); return contents.get(path); };
204
+
205
+ for (let depth = 0; depth < MAX_DEPTH && frontier.length > 0; depth++) {
206
+ const next: Array<{ path: string; via: string }> = [];
207
+ for (const target of frontier) {
208
+ // Directories are matched only for the changed file itself, which a test may find by listing its
209
+ // directory. A reader reached through the changed file (a script, a manifest) matters only if
210
+ // something runs or reads it by name; matching its directories as well made `"tests"` and
211
+ // `"fixtures"` match nearly every file and no generic name (package.json) could resolve.
212
+ const pattern = referencePattern(referenceTokens(target.path, { ancestors: target.path === filePath }));
213
+ for (const candidate of input.files) {
214
+ if (visited.has(candidate) || candidate === target.path || LOCKFILES.has(posix.basename(candidate))) continue;
215
+ const base = posix.basename(candidate);
216
+ if (base === "package.json") {
217
+ const content = read(candidate);
218
+ if (content === undefined) continue;
219
+ const named = packageJsonNames(content, pattern);
220
+ if (named === "no") continue;
221
+ visited.add(candidate);
222
+ if (named === "unparseable") { resolution.unresolvable.push(`${candidate} could not be parsed`); continue; }
223
+ resolution.readers.push({ path: candidate, kind: "package-script", via: target.path });
224
+ resolution.unresolvable.push(`${candidate} runs ${target.path} as part of its test script`);
225
+ continue;
226
+ }
227
+ if (input.isDocumentation(candidate)) continue;
228
+ const content = read(candidate);
229
+ if (content === undefined || !pattern.test(content)) continue;
230
+ visited.add(candidate);
231
+ if (candidate.startsWith(".github/")) {
232
+ // A workflow step that comes before a test step in its job, or a composite action, may feed
233
+ // the file to the suite's environment; issue templates and standalone CI checks do not.
234
+ // A change content inspection already showed cannot alter how tests run (a version bump)
235
+ // stays that way when a workflow reads the file.
236
+ const executes = candidate.startsWith(".github/actions/")
237
+ || (/^\.github\/workflows\//.test(candidate) && !input.contentCleared?.has(target.path) && input.workflowFeedsTests(content, pattern));
238
+ if (!executes) continue;
239
+ resolution.readers.push({ path: candidate, kind: "unresolvable", via: target.path });
240
+ resolution.unresolvable.push(`${candidate} names ${target.path}`);
241
+ } else if (input.isCodeFile(candidate) && input.isTestFile(candidate)) {
242
+ resolution.readers.push({ path: candidate, kind: "test", via: target.path });
243
+ tests.add(candidate);
244
+ } else if (input.isCodeFile(candidate) && input.inGraph(candidate)) {
245
+ resolution.readers.push({ path: candidate, kind: "graph-code", via: target.path });
246
+ code.add(candidate);
247
+ } else if (input.isCodeFile(candidate) || DIRECTING_EXTENSIONS.test(candidate)) {
248
+ resolution.readers.push({ path: candidate, kind: "transitive", via: target.path });
249
+ if (++transitiveCount > MAX_TRANSITIVE_READERS) { resolution.unresolvable.push(`more than ${MAX_TRANSITIVE_READERS} non-code files name ${filePath}`); break; }
250
+ next.push({ path: candidate, via: target.path });
251
+ } else {
252
+ // Markup, prose, images and licences name paths in links and URLs but execute nothing and
253
+ // direct no reads, so nothing reaches the suite through them.
254
+ resolution.readers.push({ path: candidate, kind: "documentation", via: target.path });
255
+ }
256
+ }
257
+ if (resolution.unresolvable.length > 0) break;
258
+ }
259
+ if (resolution.unresolvable.length > 0) break;
260
+ frontier = next;
261
+ }
262
+ if (resolution.unresolvable.length === 0 && frontier.length > 0) {
263
+ resolution.unresolvable.push(`reference chain from ${filePath} is deeper than ${MAX_DEPTH} files`);
264
+ }
265
+ // Found readers that something could run (check scripts, manifests), none of which any test, test
266
+ // script or test-feeding workflow step reaches: the suite cannot observe the file. Finding no such
267
+ // reader at all is different - the file's reader is unknown, so it stays unknown.
268
+ const executableReaders = resolution.readers.some((reader) => reader.kind === "transitive");
269
+ if (resolution.unresolvable.length === 0 && tests.size === 0 && code.size === 0 && !executableReaders) {
270
+ resolution.unresolvable.push(`no test or source file names ${filePath}`);
271
+ }
272
+ resolution.tests = [...tests].sort();
273
+ resolution.code = [...code].sort();
274
+ return resolution;
275
+ }
@@ -25,6 +25,7 @@ interface ImportRef {
25
25
  specifier: string;
26
26
  kind: DependencyEdgeKind;
27
27
  dynamic: boolean;
28
+ computed?: boolean;
28
29
  }
29
30
 
30
31
  const SOURCE_EXTENSIONS = new Set([
@@ -97,10 +98,31 @@ function isExcludedPath(rel: string, excludeDirs: string[]): boolean {
97
98
  );
98
99
  }
99
100
 
101
+ /**
102
+ * Whether `require` at this call names a local binding rather than the module loader, as in an
103
+ * assertion helper `const require = (condition, code) => ...`. Such calls load nothing, so treating
104
+ * their arguments as computed specifiers made every delta in one dogfood repository UNSAFE. A local
105
+ * `require` initialised from `createRequire(...)` is the loader and is not a shadow. Scopes are
106
+ * tracked during the walk: source files parsed by the Program have no parent pointers.
107
+ */
108
+ function scopeShadowsRequire(scope: ts.Node): boolean {
109
+ const declares = (name: ts.BindingName | ts.Identifier | undefined) => !!name && ts.isIdentifier(name) && name.text === "require";
110
+ const loaderInitializer = (init: ts.Expression | undefined) =>
111
+ !!init && ts.isCallExpression(init) && ts.isIdentifier(init.expression) && init.expression.text === "createRequire";
112
+ const statementShadows = (statement: ts.Statement) =>
113
+ (ts.isFunctionDeclaration(statement) && declares(statement.name)) ||
114
+ (ts.isVariableStatement(statement) && statement.declarationList.declarations.some((d) => declares(d.name) && !loaderInitializer(d.initializer)));
115
+ if ((ts.isBlock(scope) || ts.isSourceFile(scope) || ts.isModuleBlock(scope)) && scope.statements.some(statementShadows)) return true;
116
+ return ts.isFunctionLike(scope) && scope.parameters.some((p) => declares(p.name));
117
+ }
118
+
100
119
  function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
101
120
  const refs: ImportRef[] = [];
121
+ let shadowDepth = 0;
102
122
 
103
123
  function visit(node: ts.Node) {
124
+ const shadows = scopeShadowsRequire(node);
125
+ if (shadows) shadowDepth++;
104
126
  if (ts.isImportDeclaration(node)) {
105
127
  const specifier = node.moduleSpecifier;
106
128
  if (ts.isStringLiteral(specifier)) {
@@ -108,6 +130,11 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
108
130
  const kind: DependencyEdgeKind = isTypeOnly ? "type-import" : "import";
109
131
  refs.push({ specifier: specifier.text, kind, dynamic: false });
110
132
  }
133
+ } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
134
+ const specifier = node.moduleReference.expression;
135
+ if (specifier && ts.isStringLiteral(specifier)) {
136
+ refs.push({ specifier: specifier.text, kind: node.isTypeOnly ? "type-import" : "require", dynamic: false });
137
+ }
111
138
  } else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
112
139
  const specifier = node.moduleSpecifier;
113
140
  if (ts.isStringLiteral(specifier)) {
@@ -116,35 +143,21 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
116
143
  }
117
144
  } else if (ts.isCallExpression(node)) {
118
145
  const firstArg = node.arguments[0];
119
- if (node.expression.kind === ts.SyntaxKind.ImportKeyword && firstArg) {
120
- if (ts.isStringLiteral(firstArg)) {
121
- refs.push({
122
- specifier: firstArg.text,
123
- kind: "dynamic-import",
124
- dynamic: true,
125
- });
126
- } else {
127
- refs.push({
128
- specifier: firstArg.getText(sourceFile).slice(0, 200),
129
- kind: "dynamic-import",
130
- dynamic: true,
131
- });
132
- }
133
- } else if (
134
- ts.isIdentifier(node.expression) &&
135
- node.expression.text === "require" &&
136
- firstArg &&
137
- ts.isStringLiteral(firstArg)
138
- ) {
146
+ const isImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
147
+ const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require" && shadowDepth === 0;
148
+ if ((isImport || isRequire) && firstArg) {
149
+ const literal = ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg);
139
150
  refs.push({
140
- specifier: firstArg.text,
141
- kind: "require",
142
- dynamic: false,
151
+ specifier: literal ? firstArg.text : firstArg.getText(sourceFile).slice(0, 200),
152
+ kind: isImport ? "dynamic-import" : "require",
153
+ dynamic: isImport || !literal,
154
+ computed: !literal,
143
155
  });
144
156
  }
145
157
  }
146
158
 
147
159
  ts.forEachChild(node, visit);
160
+ if (shadows) shadowDepth--;
148
161
  }
149
162
 
150
163
  visit(sourceFile);
@@ -521,18 +534,47 @@ function createProgram(
521
534
  fileNames = [...new Set([...fileNames, ...additionalSources])];
522
535
  options = { module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, target: ts.ScriptTarget.ES2022, ...options, allowJs: true };
523
536
  }
537
+ // The graph extracts syntax and import edges; it never asks TypeScript for a type checker or
538
+ // semantic diagnostics. Letting the Program resolve imports made it load every lib and node_modules
539
+ // declaration file: 5.6s of a median 8.2s analysis across a dogfood repository's paired runs (2026-10-21
540
+ // telemetry). Imports are resolved explicitly below with the original options, and an implementation
541
+ // file the root list missed is parsed when an import reaches it, within a budget that fails closed.
542
+ // `syntaxOnly` (scoped analysis) used to be the only caller given these options.
543
+ void syntaxOnly;
524
544
  const program = ts.createProgram({
525
545
  rootNames: fileNames,
526
- // Scoped analysis already inventories every implementation file. It extracts
527
- // syntax/import edges, never asks TypeScript for semantic diagnostics. Keep
528
- // the original options below for explicit module resolution.
529
- options: syntaxOnly ? { ...options, noResolve: true, noLib: true, types: [] } : options,
546
+ options: { ...options, noResolve: true, noLib: true, types: [] },
530
547
  configFileParsingDiagnostics,
531
548
  });
532
549
 
533
550
  return { program, options, fileNames, resolvedViaProjectReferences };
534
551
  }
535
552
 
553
+ /**
554
+ * Module resolution asks whether the same `node_modules` directories and candidate files exist for
555
+ * every importer; the moduleResolutionCache does not cover those probes. They were the largest single
556
+ * cost of graph construction (2026-10-21 profile). The tree does not change during one analysis, so
557
+ * each answer is read from the disk once.
558
+ */
559
+ function memoizedResolutionHost(system: ts.System): ts.ModuleResolutionHost {
560
+ const memo = <T>(fn: (path: string) => T) => {
561
+ const answers = new Map<string, T>();
562
+ return (path: string) => {
563
+ if (!answers.has(path)) answers.set(path, fn(path));
564
+ return answers.get(path)!;
565
+ };
566
+ };
567
+ return {
568
+ fileExists: memo((path) => system.fileExists(path)),
569
+ directoryExists: memo((path) => system.directoryExists(path)),
570
+ readFile: memo((path) => system.readFile(path)),
571
+ realpath: system.realpath ? memo((path) => system.realpath!(path)) : undefined,
572
+ getCurrentDirectory: () => system.getCurrentDirectory(),
573
+ getDirectories: memo((path) => system.getDirectories(path)),
574
+ useCaseSensitiveFileNames: system.useCaseSensitiveFileNames,
575
+ };
576
+ }
577
+
536
578
  function classifySpecifier(specifier: string): "relative" | "absolute" | "alias" | "package" {
537
579
  if (specifier.startsWith("`./") || specifier.startsWith("`../")) return "relative";
538
580
  if (specifier.startsWith("./") || specifier.startsWith("../")) return "relative";
@@ -664,6 +706,11 @@ export async function buildDependencyGraph(
664
706
  profile.adapters = contributions.map(({ id, version, blockers }) => ({ id, version, blockers }));
665
707
  profile.goTestPackages = Object.assign({}, ...contributions.map((item) => item.testPackages));
666
708
  profile.goTestEnvironment = contributions.find((item) => item.id === "go")?.executionEnv;
709
+ const goContribution = contributions.find((item) => item.id === "go");
710
+ profile.goDependencyPaths = goContribution ? {
711
+ sources: [...new Set(goContribution.sourcePaths)].sort(),
712
+ embeds: [...new Set(goContribution.assetPaths)].sort(),
713
+ } : undefined;
667
714
  profile.mavenTestModules = Object.assign({}, ...contributions.filter((item) => item.id === "maven").map((item) => item.testPackages));
668
715
  const adapterTests = contributions.flatMap((item) => item.testFiles);
669
716
  profile.testFilePaths = [...new Set([...profile.testFilePaths, ...adapterTests])].sort();
@@ -729,6 +776,7 @@ export async function buildDependencyGraph(
729
776
  specifier: ref.specifier,
730
777
  reason,
731
778
  dynamic: ref.dynamic,
779
+ ...(ref.computed ? { computed: true } : {}),
732
780
  typeOnly: ref.kind === "type-import",
733
781
  });
734
782
  }
@@ -758,6 +806,7 @@ export async function buildDependencyGraph(
758
806
  // Resolve each importer with its own nearest project, never another package's
759
807
  // aliases. Invalid project configuration remains a hard safety blocker.
760
808
  const projectOptions = new Map<string, ts.CompilerOptions>();
809
+ const resolutionHost = memoizedResolutionHost(ts.sys);
761
810
  function hasUnavailableExternalBase(config: unknown, errors: readonly ts.Diagnostic[]): boolean {
762
811
  if (!config || typeof config !== "object") return false;
763
812
  const rawExtends = (config as { extends?: unknown }).extends;
@@ -772,7 +821,16 @@ export async function buildDependencyGraph(
772
821
  // aliases. Any other diagnostic remains a hard blocker.
773
822
  return errors.every(error => error.code === 18003 || error.code === 5083 || error.code === 6053);
774
823
  }
824
+ // Nearest tsconfig.json per importer directory. Probing the disk for every importer walked to the
825
+ // repository root once per file: about a third of graph build time on a 2,000-file repository (2026-10-21).
826
+ const nearestConfig = new Map<string, ts.CompilerOptions>();
775
827
  function optionsFor(file: string): ts.CompilerOptions {
828
+ const key = dirname(file);
829
+ let options = nearestConfig.get(key);
830
+ if (!options) { options = findOptionsFor(file); nearestConfig.set(key, options); }
831
+ return options;
832
+ }
833
+ function findOptionsFor(file: string): ts.CompilerOptions {
776
834
  let directory = dirname(file);
777
835
  while (toRelativeInternal(repoPath, directory) !== undefined) {
778
836
  const config = join(directory, "tsconfig.json");
@@ -806,6 +864,13 @@ export async function buildDependencyGraph(
806
864
  const refs = extractImportRefs(sf);
807
865
  if (scope && sf.referencedFiles.length) adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
808
866
  for (const ref of refs) {
867
+ // Expression text is not a module name. In particular, import(name) must
868
+ // not be classified as an external package called "name".
869
+ if (ref.computed) {
870
+ recordUnresolved(importerRel, ref, "computed module specifier requires full validation");
871
+ recordReference("unresolved", importerRel, ref);
872
+ continue;
873
+ }
809
874
  if (!ref.specifier) {
810
875
  recordUnresolved(importerRel, ref, "empty specifier");
811
876
  recordReference("unresolved", importerRel, ref);
@@ -837,7 +902,7 @@ export async function buildDependencyGraph(
837
902
  resolvableSpecifier,
838
903
  sf.fileName,
839
904
  importerOptions,
840
- ts.sys,
905
+ resolutionHost,
841
906
  moduleResolutionCache,
842
907
  );
843
908
 
@@ -1258,14 +1323,16 @@ function computeConfidence(
1258
1323
  * graph for EVERY delta, for as long as that one file's import stays unresolved, regardless of whether
1259
1324
  * the delta being analyzed has anything to do with it.
1260
1325
  *
1261
- * This narrows that: an unresolved import only makes THIS delta's confidence untrustworthy if the
1262
- * unresolved import's importer file is actually reachable from the delta's changed files (in either
1326
+ * For static unresolved references, this narrows that: an unresolved import makes THIS delta's
1327
+ * confidence untrustworthy if its importer is actually reachable from the changed files (in either
1263
1328
  * direction - the changed file might depend on the incomplete file, or something reachable from the
1264
1329
  * changed file might). If none of the graph's unresolved imports are anywhere near this delta, the
1265
1330
  * graph's real incompleteness elsewhere cannot plausibly affect what can safely be determined about
1266
1331
  * THIS specific change.
1267
1332
  *
1268
1333
  * Deliberately NOT narrowed - these remain hard, global blockers regardless of the delta:
1334
+ * - Unresolved runtime imports/requires: a computed target has no known graph edge, so lack of
1335
+ * reachability cannot establish that it does not load one of the changed files.
1269
1336
  * - `sourceFileCount === 0` (an empty graph gives no reachability information to reason about at all).
1270
1337
  * - `integrity.criticalCount > 0` (the graph's own internal structure is broken - a construction bug,
1271
1338
  * not a property of any one file, so no delta-specific narrowing is meaningful).
@@ -1278,6 +1345,12 @@ function computeConfidence(
1278
1345
  * sourceFileCount or integrity triggered it. */
1279
1346
  export function refineConfidenceForDelta(result: DependencyGraphResult, changedFiles: string[]): GraphConfidence {
1280
1347
  if (result.adapterBlockers?.length) return "UNSAFE";
1348
+ // A computed runtime target can be any file, so its missing edge proves nothing about which changed
1349
+ // file it loads. It cannot, however, change the behaviour of a test that never runs the importer:
1350
+ // ImpactAnalyzer selects every test that does (COMPUTED_IMPORT) and falls back when the importer is
1351
+ // outside the graph. Computed references are therefore excluded from reachability below rather
1352
+ // than blocking every delta. A literal dynamic import names its only possible target and is
1353
+ // narrowed like any other unresolved import.
1281
1354
  // Anything that was never UNSAFE in the first place passes through untouched - there is nothing to
1282
1355
  // narrow, and re-deriving sourceFileCount/integrity from raw fields here (rather than trusting the
1283
1356
  // already-computed confidence) would be both redundant and a real correctness risk: a caller's
@@ -1305,7 +1378,7 @@ export function refineConfidenceForDelta(result: DependencyGraphResult, changedF
1305
1378
  }
1306
1379
  const changedSet = new Set(changedFiles);
1307
1380
 
1308
- const relevantUnresolved = result.unresolved.some((u) => changedSet.has(u.importer) || reachableFromChanged.has(u.importer));
1381
+ const relevantUnresolved = result.unresolved.some((u) => !u.computed && (changedSet.has(u.importer) || reachableFromChanged.has(u.importer)));
1309
1382
  if (relevantUnresolved) return "UNSAFE";
1310
1383
 
1311
1384
  // None of the unresolved imports are reachable from this delta's changed files - narrow to what