@diffci.com/diffci 0.3.13 → 0.3.15

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 (75) hide show
  1. package/LICENSE +20 -661
  2. package/README.md +1 -1
  3. package/dist-client/src/client/agent-selection.js +4 -1
  4. package/dist-client/src/client/cli.js +143 -59
  5. package/dist-client/src/client/command-batches.js +80 -0
  6. package/dist-client/src/client/context.js +1 -1
  7. package/dist-client/src/client/enforce-misses-collect.js +157 -0
  8. package/dist-client/src/client/enforce-misses.js +229 -0
  9. package/dist-client/src/client/enforce-policy.js +169 -0
  10. package/dist-client/src/client/failure-baseline.js +99 -0
  11. package/dist-client/src/client/feedback-prompt.js +42 -0
  12. package/dist-client/src/client/mcp.js +1 -1
  13. package/dist-client/src/client/observe.js +12 -4
  14. package/dist-client/src/client/pilot-packet.js +0 -31
  15. package/dist-client/src/client/telemetry.js +46 -0
  16. package/dist-client/src/client/usage-signal.js +17 -10
  17. package/dist-client/src/client/verify-savings.js +12 -1
  18. package/dist-client/src/client/verify.js +81 -9
  19. package/dist-client/src/client/workflow-templates.js +80 -0
  20. package/node_modules/@diffci.com/core/README.md +13 -7
  21. package/node_modules/@diffci.com/core/dist/analyze.js +2 -1
  22. package/node_modules/@diffci.com/core/dist/analyze.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  24. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  25. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +9 -0
  26. package/node_modules/@diffci.com/core/dist/git/git-diff.js +122 -19
  27. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  28. package/node_modules/@diffci.com/core/dist/git/types.d.ts +9 -0
  29. package/node_modules/@diffci.com/core/dist/planner/test-command.js +16 -3
  30. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +99 -42
  32. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.d.ts +16 -0
  34. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js +101 -0
  35. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js.map +1 -0
  36. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +68 -0
  37. package/node_modules/@diffci.com/core/dist/repo/file-references.js +278 -0
  38. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -0
  39. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +4 -2
  40. package/node_modules/@diffci.com/core/dist/repo/graph.js +107 -31
  41. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  42. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +7 -1
  43. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +32 -0
  44. package/node_modules/@diffci.com/core/dist/repo/impact.js +241 -20
  45. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  46. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +9 -3
  47. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  48. package/node_modules/@diffci.com/core/dist/repo/script-universe.d.ts +16 -0
  49. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +173 -0
  50. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -0
  51. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +12 -0
  52. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +54 -7
  53. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  54. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +8 -0
  55. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.d.ts +15 -0
  56. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +157 -0
  57. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -0
  58. package/node_modules/@diffci.com/core/package.json +5 -0
  59. package/node_modules/@diffci.com/core/src/analyze.ts +2 -1
  60. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  61. package/node_modules/@diffci.com/core/src/git/git-diff.ts +106 -20
  62. package/node_modules/@diffci.com/core/src/git/types.ts +9 -0
  63. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -3
  64. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +120 -30
  65. package/node_modules/@diffci.com/core/src/repo/compiled-projects.ts +108 -0
  66. package/node_modules/@diffci.com/core/src/repo/file-references.ts +275 -0
  67. package/node_modules/@diffci.com/core/src/repo/graph.ts +104 -31
  68. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +10 -0
  69. package/node_modules/@diffci.com/core/src/repo/impact.ts +243 -18
  70. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +6 -3
  71. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +158 -0
  72. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +62 -7
  73. package/node_modules/@diffci.com/core/src/repo/types.ts +5 -0
  74. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +117 -0
  75. package/package.json +6 -4
@@ -18,6 +18,10 @@ export type ImpactReason =
18
18
  | "INFRASTRUCTURE_GLOBAL"
19
19
  | "DATABASE_GLOBAL"
20
20
  | "UNKNOWN_FILE"
21
+ | "FILE_REFERENCE"
22
+ | "COMPILED_PROJECT"
23
+ | "COMPUTED_IMPORT"
24
+ | "OUTSIDE_FULL_SUITE"
21
25
  | "TEST_FIXTURE_OWNER"
22
26
  | "ALWAYS_RUN_POLICY"
23
27
  | "DELETED_FILE_LEGACY_DEPENDENTS"
@@ -78,6 +82,12 @@ export interface ImpactResult {
78
82
  affectedSourceFiles: string[];
79
83
  affectedAssets: string[];
80
84
  affectedTests: TestImpact[];
85
+ /** Number of test files the repository's test script runs, when src/repo/script-universe.ts could
86
+ * model it completely; absent otherwise (2026-10-21). */
87
+ fullSuiteTestCount?: number;
88
+ /** Affected tests that the test script does not run. Not part of the selection, which stays a
89
+ * subset of the full suite, but still worth running. Present only with `fullSuiteTestCount`. */
90
+ testsOutsideFullSuite?: TestImpact[];
81
91
  affectedEntryPoints: EntryPointImpact[];
82
92
  affectedScripts: string[];
83
93
 
@@ -6,13 +6,19 @@ import type { DependencyGraph, DependencyGraphNode, DependencyGraphResult, Entry
6
6
  import type { ChangedImpact, EntryPointImpact, ImpactEvidence, ImpactEvidencePath, ImpactReason, ImpactResult, ImpactRiskSignal, TestImpact } from "./impact-types.js";
7
7
  import { refineConfidenceForDelta } from "./graph.js";
8
8
  import { repositoryLayout, UNKNOWN_REPOSITORY_LAYOUT, type RepositoryLayout } from "./layout.js";
9
- import { DEFAULT_TEST_FILE_MATCHER, matchesGlob as matchesTestGlob, testFileMatcherForProfile } from "./test-discovery.js";
9
+ import { DEFAULT_TEST_FILE_MATCHER, matchesGlob as matchesTestGlob, testDiscoveryErrors, testFileMatcherForProfile } from "./test-discovery.js";
10
10
  import { resolveTestFixtureOwners } from "./test-fixture-ownership.js";
11
+ import { infrastructureRole, isImplicitlyLoadedFile, resolveFileReferences } from "./file-references.js";
12
+ import { workflowFeedsTests } from "./workflow-test-steps.js";
13
+ import { modelTestScriptUniverse, type ScriptUniverse } from "./script-universe.js";
14
+ import { compiledProjects, type CompiledProject } from "./compiled-projects.js";
11
15
 
12
16
  const SOURCE_EXTENSIONS = new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".go",".java",".kt"]);
13
17
  const ASSET_EXTENSIONS = new Set([".css",".scss",".sass",".less",".json",".jsonc",".svg",".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".woff",".woff2",".ttf",".otf",".eot",".wasm",".md",".txt"]);
14
18
  const NEXT_ENTRY_NAMES = new Set(["page","layout","route","api","loading","error","template","not-found","middleware","generatemetadata","generatestaticparams"]);
15
19
 
20
+ // Lockfiles are reported by the lockfile rule; resolving their readers would only repeat it.
21
+ function isLockfile(filePath: string): boolean { return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(filePath); }
16
22
  function isSourceFilePath(filePath: string): boolean { return SOURCE_EXTENSIONS.has(extname(filePath).toLowerCase()); }
17
23
  function isAssetFilePath(filePath: string): boolean { return ASSET_EXTENSIONS.has(extname(filePath).toLowerCase()); }
18
24
  // "Is this a test?" is answered by the profile's test patterns (src/repo/test-discovery.ts) - one shared
@@ -40,14 +46,15 @@ function isConfigFile(filePath: string): boolean {
40
46
  if (base.startsWith("jest.config")) return true;
41
47
  if (base.startsWith("prettier.config")) return true;
42
48
  if (base.startsWith(".prettierrc")) return true;
43
- if (filePath.startsWith(".github/")) return true;
49
+ if (/^\.github\/(?:workflows|actions)\//.test(filePath)) return true;
44
50
  if (filePath.includes("/Dockerfile")) return true;
45
51
  if (filePath.startsWith("docker")) return true;
46
52
  return false;
47
53
  }
48
- // The "ops" prefix test that used to lead this was redundant - "ops" is in the set below - and it
49
- // was the shape a hardcoded layout assumption takes, so the set alone now decides.
50
- function isInfrastructureFile(filePath: string): boolean { const INFRA_DIRS = new Set(["ops","terraform","cloudformation","pulumi","cdktf","deploy","deployments","kubernetes","k8s","helm","docker"]); const first = filePath.split("/")[0]; if (first && INFRA_DIRS.has(first)) return true; if (posix.basename(filePath).includes("Dockerfile")) return true; return false; }
54
+ // Only conventionally-loaded deployment definitions are global (src/repo/file-references.ts,
55
+ // infrastructureRole). Code, documentation and data under ops/ and its siblings are classified like
56
+ // the same files anywhere else (2026-10-21).
57
+ function isInfrastructureFile(filePath: string): boolean { return infrastructureRole(filePath) === "definition"; }
51
58
  function isDatabaseFile(filePath: string): boolean { const DATABASE_DIRS = new Set(["database","migrations","prisma","drizzle","supabase","schema"]); const first = filePath.split("/")[0]; return first ? DATABASE_DIRS.has(first) : false; }
52
59
  /**
53
60
  * Next.js file-name conventions, applied ONLY to repositories that are Next.js applications.
@@ -102,11 +109,15 @@ function shortestDependentPathToTest(graph: DependencyGraph, changedFilePath: st
102
109
  function collectScriptsAmong(candidates: Iterable<string>, isTestFile: IsTestFile, layout: RepositoryLayout): string[] { const result: string[] = []; for (const path of candidates) { if (isScriptFile(path, layout) && !isTestFile(path)) result.push(path); } return result.sort(); }
103
110
  function makeEvidence(reason: ImpactReason, changedFile: string, message: string, affectedFile?: string, path?: ImpactEvidencePath): ImpactEvidence { return { reason, changedFile, affectedFile, message, path }; }
104
111
 
105
- function classifyChangedFile(file: ChangedFile, isTestFile: IsTestFile, layout: RepositoryLayout, repositoryFiles?: ReadonlySet<string>): ChangedImpact["category"] {
112
+ function classifyChangedFile(file: ChangedFile, isTestFile: IsTestFile, layout: RepositoryLayout, repositoryFiles?: ReadonlySet<string>, referenceResolved: ReadonlySet<string> = new Set()): ChangedImpact["category"] {
106
113
  const path = file.path;
107
114
  const oldPath = file.oldPath;
115
+ // Content inspection in analyzeGitDelta showed these cannot change how tests run; who reads them is
116
+ // resolved by reference (2026-10-21).
117
+ if (referenceResolved.has(path)) return "unknown";
108
118
  if (isConfigFile(path) || (oldPath && isConfigFile(oldPath))) return "config";
109
119
  if (isInfrastructureFile(path) || (oldPath && isInfrastructureFile(oldPath))) return "infrastructure";
120
+ if (infrastructureRole(path) === "data") return "unknown";
110
121
  if (isDatabaseFile(path) || (oldPath && isDatabaseFile(oldPath))) return "database";
111
122
  if (isSourceFilePath(path)) {
112
123
  if (isTestFile(path)) return "test";
@@ -177,6 +188,10 @@ export interface ImpactAnalyzeOptions {
177
188
  * Enables relationship-based classification (see isTranslatedDocumentationCompanion). Optional -
178
189
  * omitting it disables those rules and keeps prior behavior exactly. */
179
190
  repositoryFiles?: ReadonlySet<string>;
191
+ /** Reads a repo-relative file at HEAD (undefined when unreadable, binary or too large). Together with
192
+ * `repositoryFiles` it enables resolving the readers of non-code files by reference
193
+ * (src/repo/file-references.ts). Omitting it keeps such files unknown, exactly as before. */
194
+ readRepositoryFile?: (path: string) => string | undefined;
180
195
  }
181
196
 
182
197
  function changedFileReasons(file: ChangedFile): ImpactReason[] {
@@ -232,6 +247,11 @@ export class ImpactAnalyzer {
232
247
  private isTestFile: IsTestFile = DEFAULT_TEST_FILE_MATCHER;
233
248
  private layout: RepositoryLayout = UNKNOWN_REPOSITORY_LAYOUT;
234
249
  private repositoryFiles: ReadonlySet<string> | undefined;
250
+ private contentCleared: ReadonlySet<string> = new Set();
251
+ private readRepositoryFile: ((path: string) => string | undefined) | undefined;
252
+ private sortedRepositoryFiles: string[] = [];
253
+ private compiledProjectCache: CompiledProject[] | undefined;
254
+ private goEmbedPaths = new Set<string>();
235
255
  constructor(alwaysRunChecks: AlwaysRunCheck[] = DEFAULT_ALWAYS_RUN_CHECKS) { this.alwaysRunChecks = alwaysRunChecks; }
236
256
 
237
257
  analyze(delta: GitDelta, graphResult: DependencyGraphResult, profile: RepositoryProfile, options: ImpactAnalyzeOptions = {}): ImpactResult {
@@ -240,17 +260,39 @@ export class ImpactAnalyzer {
240
260
  this.isTestFile = testFileMatcherForProfile(profile);
241
261
  this.layout = repositoryLayout(profile);
242
262
  this.repositoryFiles = options.repositoryFiles;
243
- const changedImpacts: ChangedImpact[] = delta.files.map((file) => ({ file, category: classifyChangedFile(file, this.isTestFile, this.layout, options.repositoryFiles), reasons: changedFileReasons(file) }));
263
+ this.sortedRepositoryFiles = options.repositoryFiles ? [...options.repositoryFiles].sort() : [];
264
+ this.compiledProjectCache = undefined;
265
+ // One read per file per analysis, however many changed files ask who reads them.
266
+ const read = options.readRepositoryFile;
267
+ const contents = new Map<string, string | undefined>();
268
+ this.readRepositoryFile = read && ((path: string) => {
269
+ if (!contents.has(path)) contents.set(path, read(path));
270
+ return contents.get(path);
271
+ });
272
+ const referenceResolved = new Set(delta.analysis.referenceResolvedPaths ?? []);
273
+ this.contentCleared = referenceResolved;
274
+ const changedImpacts: ChangedImpact[] = delta.files.map((file) => ({ file, category: classifyChangedFile(file, this.isTestFile, this.layout, options.repositoryFiles, referenceResolved), reasons: changedFileReasons(file) }));
244
275
  const evidence: ImpactEvidence[] = [];
245
276
  const riskSignals: ImpactRiskSignal[] = [];
246
- const fallbackReasons: string[] = [...(graphResult.adapterBlockers ?? [])];
277
+ const fallbackReasons: string[] = [...(graphResult.adapterBlockers ?? []), ...testDiscoveryErrors(profile)];
247
278
  if (profile.vueScope) {
248
279
  const scope = profile.vueScope;
249
280
  if (delta.files.some(file => allChangePaths(file).some(path => !inVuePackage(path, scope.packageRoot)))) fallbackReasons.push("Changes outside the declared Vue package require full validation");
250
281
  const setupDependencies = new Set((profile.vueSetupPaths ?? []).flatMap(path => [path, ...graph.transitiveDependenciesOf(path)]));
251
282
  if (delta.files.some(file => allChangePaths(file).some(path => setupDependencies.has(path)))) fallbackReasons.push("Vue suite configuration or shared setup dependency changed; full validation required");
252
283
  }
253
- if (profile.adapters?.some(adapter => adapter.id === "go") && delta.files.some(file => allChangePaths(file).some(isGoDiscoveryIgnoredPath))) {
284
+ const hasGoAdapter = profile.adapters?.some(adapter => adapter.id === "go");
285
+ this.goEmbedPaths = new Set(hasGoAdapter ? profile.goDependencyPaths?.embeds : []);
286
+ if (hasGoAdapter) {
287
+ // go list models package sources and embeds, not arbitrary runtime reads. Neither a
288
+ // familiar extension/directory nor membership in another adapter's graph proves ownership.
289
+ // Check both identities of renames/copies, including files absent from the HEAD inventory.
290
+ // Missing metadata in older cached profiles deliberately fails closed as well.
291
+ const modeledPaths = new Set([...(profile.goDependencyPaths?.sources ?? []), ...this.goEmbedPaths]);
292
+ const unmodeledPaths = [...new Set(delta.files.flatMap(allChangePaths))].filter(path => !modeledPaths.has(path));
293
+ if (unmodeledPaths.length) fallbackReasons.push(`Go runtime inputs outside source/embed metadata require full validation: ${unmodeledPaths.slice(0, 20).join(", ")}`);
294
+ }
295
+ if (hasGoAdapter && delta.files.some(file => allChangePaths(file).some(isGoDiscoveryIgnoredPath))) {
254
296
  fallbackReasons.push("Changes in Go discovery-excluded paths require full validation, including runtime test data");
255
297
  }
256
298
  const excludedGoRoots = profile.goExcludedModuleRoots ?? [];
@@ -309,6 +351,7 @@ export class ImpactAnalyzer {
309
351
  this.handleStructuralNextLayout(changedImpacts, profile, affectedEntryPoints, affectedSources, evidence);
310
352
  this.handleAddedEntryPoints(delta, affectedEntryPoints, affectedSources, affectedTests, evidence, fallbackReasons);
311
353
  this.collectAlwaysRunTests(profile, graph, affectedTests, evidence, graphResult.profile.vueRuntimeAlwaysRunPaths ?? []);
354
+ this.collectComputedImportTests(graphResult, graph, changedImpacts, affectedTests, evidence, riskSignals, fallbackReasons);
312
355
 
313
356
  // Changed-test self-selection invariant (2026-08-24): every executable directly-changed test
314
357
  // (added / modified / renamed-destination / copied-destination) MUST be present in the final
@@ -323,6 +366,21 @@ export class ImpactAnalyzer {
323
366
  if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
324
367
  }
325
368
 
369
+ // 2026-10-21: affected tests that `npm test` never runs are not part of the full suite, so they are
370
+ // reported beside the selection rather than inside it (src/repo/script-universe.ts). They have
371
+ // already satisfied the changed-test invariant above and are still meant to be run.
372
+ const fullSuite = this.fullSuiteUniverse(profile, graph);
373
+ const testsOutsideFullSuite: TestImpact[] = [];
374
+ if (fullSuite?.complete) {
375
+ const inside = new Set(fullSuite.tests);
376
+ for (const [path, impact] of affectedTests) {
377
+ if (inside.has(path)) continue;
378
+ testsOutsideFullSuite.push(impact);
379
+ affectedTests.delete(path);
380
+ evidence.push(makeEvidence("OUTSIDE_FULL_SUITE", path, `${path} is not run by the test script; reported outside the full suite`));
381
+ }
382
+ }
383
+
326
384
  const fallbackRequired = effectiveGraphConfidence === "UNSAFE" || fallbackReasons.length > 0;
327
385
  const analysisStatus: ImpactResult["analysisStatus"] = fallbackRequired ? "FALLBACK" : "SAFE_TO_PROPOSE";
328
386
  const dedupedRiskSignals = Array.from(
@@ -334,6 +392,10 @@ export class ImpactAnalyzer {
334
392
  affectedSourceFiles: Array.from(affectedSources.keys()).sort(),
335
393
  affectedAssets: Array.from(affectedAssets.keys()).sort(),
336
394
  affectedTests: Array.from(affectedTests.values()).sort((a, b) => a.path.localeCompare(b.path)),
395
+ ...(fullSuite?.complete ? {
396
+ fullSuiteTestCount: fullSuite.tests.length,
397
+ testsOutsideFullSuite: testsOutsideFullSuite.sort((a, b) => a.path.localeCompare(b.path)),
398
+ } : {}),
337
399
  affectedEntryPoints: Array.from(affectedEntryPoints.values()).sort((a, b) => a.path.localeCompare(b.path)),
338
400
  affectedScripts: Array.from(affectedScripts.keys()).sort(),
339
401
  riskSignals: dedupedRiskSignals,
@@ -347,18 +409,24 @@ export class ImpactAnalyzer {
347
409
  }
348
410
 
349
411
  private applyGlobalRiskRules(delta: GitDelta, riskSignals: ImpactRiskSignal[], fallbackReasons: string[]): void {
350
- const reasons: Array<{ reason: ImpactReason; message: string; check: (a: GitDelta["analysis"]) => boolean }> = [
351
- { reason: "CONFIG_GLOBAL", message: "Configuration file(s) changed; full validation required", check: (a) => a.configChanged },
352
- { reason: "DEPENDENCY_MANIFEST", message: "Dependency manifest changed; full validation required", check: (a) => a.dependencyManifestChanged },
353
- { reason: "LOCKFILE_GLOBAL", message: "Lockfile changed; full validation required", check: (a) => a.lockfileChanged },
354
- { reason: "WORKFLOW_GLOBAL", message: "GitHub workflow definition(s) changed; full validation required", check: (a) => a.workflowChanged },
355
- { reason: "INFRASTRUCTURE_GLOBAL", message: "Infrastructure definition(s) changed; full validation required", check: (a) => a.infrastructureChanged },
356
- { reason: "DATABASE_GLOBAL", message: "Database definition(s) changed; full validation required", check: (a) => a.databaseChanged },
412
+ type SignalKey = keyof NonNullable<GitDelta["analysis"]["signalPaths"]>;
413
+ const reasons: Array<{ reason: ImpactReason; message: string; signal: SignalKey; check: (a: GitDelta["analysis"]) => boolean }> = [
414
+ { reason: "CONFIG_GLOBAL", message: "Configuration file(s) changed; full validation required", signal: "config", check: (a) => a.configChanged },
415
+ { reason: "DEPENDENCY_MANIFEST", message: "Dependency manifest changed; full validation required", signal: "dependencyManifest", check: (a) => a.dependencyManifestChanged },
416
+ { reason: "LOCKFILE_GLOBAL", message: "Lockfile changed; full validation required", signal: "lockfile", check: (a) => a.lockfileChanged },
417
+ { reason: "WORKFLOW_GLOBAL", message: "GitHub workflow definition(s) changed; full validation required", signal: "workflow", check: (a) => a.workflowChanged },
418
+ { reason: "INFRASTRUCTURE_GLOBAL", message: "Infrastructure definition(s) changed; full validation required", signal: "infrastructure", check: (a) => a.infrastructureChanged },
419
+ { reason: "DATABASE_GLOBAL", message: "Database definition(s) changed; full validation required", signal: "database", check: (a) => a.databaseChanged },
357
420
  ];
358
421
  for (const rule of reasons) {
359
422
  if (rule.check(delta.analysis)) {
360
- riskSignals.push({ level: "critical", reason: rule.reason, message: rule.message });
361
- if (!fallbackReasons.includes(rule.message)) fallbackReasons.push(rule.message);
423
+ // The stable sentence stays a prefix, so consumers that categorise by it keep working; the
424
+ // files that triggered it follow (2026-10-21).
425
+ const paths = delta.analysis.signalPaths?.[rule.signal] ?? [];
426
+ const message = paths.length === 0 ? rule.message
427
+ : `${rule.message}: ${paths.slice(0, 5).join(", ")}${paths.length > 5 ? ` (+${paths.length - 5} more)` : ""}`;
428
+ riskSignals.push({ level: "critical", reason: rule.reason, message, ...(paths.length ? { paths: [...paths] } : {}) });
429
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
362
430
  }
363
431
  }
364
432
  }
@@ -377,6 +445,12 @@ export class ImpactAnalyzer {
377
445
  riskSignals: ImpactRiskSignal[],
378
446
  fallbackReasons: string[],
379
447
  ): void {
448
+ // Go's embed metadata is ownership evidence regardless of suffix or documentation naming.
449
+ // Traverse it before generic unknown/docs classification can discard the dependency.
450
+ if (this.goEmbedPaths.has(changedPath)) {
451
+ this.processAssetChange(changedPath, graph, profile, affectedAssets, affectedEntryPoints, affectedTests, affectedSources, evidence);
452
+ return;
453
+ }
380
454
  const category = changedImpact.category;
381
455
  if (category === "test-fixture") {
382
456
  // Resolved per change PATH (a rename's old path resolves independently); an unresolvable side
@@ -391,6 +465,7 @@ export class ImpactAnalyzer {
391
465
  }
392
466
  }
393
467
  if (category === "unknown" || category === "test-fixture") {
468
+ if (this.resolveByReference(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
394
469
  const message = `Unknown changed file: ${changedPath}`;
395
470
  evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
396
471
  riskSignals.push({ level: "critical", reason: "UNKNOWN_FILE", message, paths: [changedPath] });
@@ -398,7 +473,25 @@ export class ImpactAnalyzer {
398
473
  return;
399
474
  }
400
475
  if (category === "docs") return;
476
+ if (isAssetFilePath(changedPath) && !hasNode(graph, changedPath) && changedImpact.file.changeType !== "deleted" && !isDocumentationFile(changedPath, this.layout) && !isLockfile(changedPath)) {
477
+ // An asset no module imports can still be read from disk by a test. It used to select nothing
478
+ // and require nothing, which is a silent skip; it now needs reader evidence like any other
479
+ // non-code file (2026-10-21).
480
+ if (this.resolveByReference(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
481
+ const message = `Unknown changed file: ${changedPath}`;
482
+ evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
483
+ riskSignals.push({ level: "critical", reason: "UNKNOWN_FILE", message, paths: [changedPath] });
484
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
485
+ return;
486
+ }
401
487
  if (isAssetFilePath(changedPath)) {
488
+ if (changedImpact.file.changeType === "deleted" && !hasNode(graph, changedPath)) {
489
+ const message = `Deleted source/asset ${changedPath} not present in HEAD dependency graph; legacy dependents cannot be determined`;
490
+ evidence.push(makeEvidence("DELETED_FILE_UNKNOWABLE_GRAPH", changedPath, message));
491
+ riskSignals.push({ level: "critical", reason: "DELETED_FILE_UNKNOWABLE_GRAPH", message, paths: [changedPath] });
492
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
493
+ return;
494
+ }
402
495
  this.processAssetChange(changedPath, graph, profile, affectedAssets, affectedEntryPoints, affectedTests, affectedSources, evidence);
403
496
  return;
404
497
  }
@@ -406,6 +499,14 @@ export class ImpactAnalyzer {
406
499
  evidence.push(makeEvidence("CONFIG_GLOBAL", changedPath, `Global ${category} change at ${changedPath}`));
407
500
  return;
408
501
  }
502
+ if (infrastructureRole(changedPath) === "code" && !hasNode(graph, changedPath) && changedImpact.file.changeType !== "deleted") {
503
+ // Code under ops/ is classified like code anywhere else only while the graph can see it.
504
+ const message = `Infrastructure code ${changedPath} is outside the dependency graph; full validation required`;
505
+ evidence.push(makeEvidence("INFRASTRUCTURE_GLOBAL", changedPath, message));
506
+ riskSignals.push({ level: "critical", reason: "INFRASTRUCTURE_GLOBAL", message, paths: [changedPath] });
507
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
508
+ return;
509
+ }
409
510
  if (category === "test") {
410
511
  this.processTestChange(changedPath, changedImpact, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence, riskSignals, fallbackReasons);
411
512
  return;
@@ -420,6 +521,90 @@ export class ImpactAnalyzer {
420
521
  this.processSourceChange(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence);
421
522
  }
422
523
 
524
+ /** Projects some test compiles (src/repo/compiled-projects.ts), computed once per analysis and only
525
+ * when file contents are available. */
526
+ private compiledProjectsFor(graph: DependencyGraph): CompiledProject[] {
527
+ if (this.compiledProjectCache) return this.compiledProjectCache;
528
+ this.compiledProjectCache = !this.repositoryFiles || !this.readRepositoryFile ? [] : compiledProjects({
529
+ files: this.sortedRepositoryFiles,
530
+ read: this.readRepositoryFile,
531
+ isTestFile: this.isTestFile,
532
+ dependenciesOf: (path) => (hasNode(graph, path) ? graph.transitiveDependenciesOf(path) : []),
533
+ });
534
+ return this.compiledProjectCache;
535
+ }
536
+
537
+ /** The files the repository's test script runs, when that can be modelled completely. Only plain
538
+ * JavaScript/TypeScript profiles are modelled: workspaces, Vue scopes and Go/Maven adapters own
539
+ * their own universes. */
540
+ private fullSuiteUniverse(profile: RepositoryProfile, graph: DependencyGraph): ScriptUniverse | undefined {
541
+ if (!this.repositoryFiles || !this.readRepositoryFile) return undefined;
542
+ const owned = (record: Record<string, string> | undefined) => Object.keys(record ?? {}).length > 0;
543
+ if (profile.workspaceTestPackages?.length || profile.vueScope || owned(profile.goTestPackages) || owned(profile.mavenTestModules)) return undefined;
544
+ if (typeof profile.packageJson.scripts.test !== "string") return undefined;
545
+ const files = this.repositoryFiles;
546
+ return modelTestScriptUniverse({
547
+ scripts: profile.packageJson.scripts,
548
+ discoveredTests: profile.testFilePaths,
549
+ dependenciesOf: (path) => (hasNode(graph, path) ? graph.transitiveDependenciesOf(path) : []),
550
+ read: this.readRepositoryFile,
551
+ exists: (path) => files.has(path) || [...files].some((file) => file.startsWith(`${path.replace(/\/$/, "")}/`)),
552
+ });
553
+ }
554
+
555
+ /**
556
+ * Narrows an otherwise-unknown changed file to the tests that read it, when every reader resolves
557
+ * (src/repo/file-references.ts). Returns false, leaving the caller's full-validation fallback in
558
+ * place, when the inputs are unavailable, the file is loaded implicitly by tooling, or any reader
559
+ * cannot be resolved.
560
+ */
561
+ private resolveByReference(
562
+ changedPath: string,
563
+ graph: DependencyGraph,
564
+ profile: RepositoryProfile,
565
+ affectedSources: Map<string, ImpactEvidence[]>,
566
+ affectedEntryPoints: Map<string, EntryPointImpact>,
567
+ affectedTests: Map<string, TestImpact>,
568
+ affectedScripts: Map<string, ImpactEvidence[]>,
569
+ evidence: ImpactEvidence[],
570
+ ): boolean {
571
+ if (!this.repositoryFiles || !this.readRepositoryFile || isImplicitlyLoadedFile(changedPath)) return false;
572
+ const layout = this.layout;
573
+ const scripts = profile.packageJson.scripts;
574
+ const resolution = resolveFileReferences(changedPath, {
575
+ files: this.sortedRepositoryFiles,
576
+ read: this.readRepositoryFile,
577
+ isTestFile: this.isTestFile,
578
+ isDocumentation: (path) => layout.isDocumentationPath(path),
579
+ inGraph: (path) => hasNode(graph, path),
580
+ isCodeFile: isSourceFilePath,
581
+ workflowFeedsTests: (content, names) => workflowFeedsTests(content, names, scripts),
582
+ contentCleared: this.contentCleared,
583
+ });
584
+ if (resolution.unresolvable.length > 0) {
585
+ evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, `References to ${changedPath} could not be resolved: ${resolution.unresolvable[0]}`));
586
+ return false;
587
+ }
588
+ for (const reader of resolution.readers) {
589
+ if (reader.kind !== "test" && reader.kind !== "graph-code") continue;
590
+ evidence.push(makeEvidence("FILE_REFERENCE", changedPath, `${reader.path} names ${reader.via}`, reader.path));
591
+ }
592
+ for (const test of resolution.tests) this.addAffectedTest(changedPath, test, graph, affectedTests, "FILE_REFERENCE", evidence);
593
+ for (const code of resolution.code) {
594
+ if (!affectedSources.has(code)) affectedSources.set(code, []);
595
+ affectedSources.get(code)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${code} reads ${changedPath}`, code));
596
+ for (const dependent of graph.transitiveDependentsOf(code)) {
597
+ if (this.isTestFile(dependent)) this.addAffectedTest(changedPath, dependent, graph, affectedTests, "FILE_REFERENCE", evidence);
598
+ else if (nodeByPath(graph, dependent)?.isEntryPoint) this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "FILE_REFERENCE", changedPath, evidence);
599
+ }
600
+ for (const scriptPath of collectScriptsAmong([code, ...graph.transitiveDependentsOf(code)], this.isTestFile, this.layout)) {
601
+ if (!affectedScripts.has(scriptPath)) affectedScripts.set(scriptPath, []);
602
+ affectedScripts.get(scriptPath)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${changedPath} is read by script ${scriptPath}`, scriptPath));
603
+ }
604
+ }
605
+ return true;
606
+ }
607
+
423
608
  private processAssetChange(
424
609
  assetPath: string,
425
610
  graph: DependencyGraph,
@@ -458,6 +643,13 @@ export class ImpactAnalyzer {
458
643
  affectedScripts: Map<string, ImpactEvidence[]>,
459
644
  evidence: ImpactEvidence[],
460
645
  ): void {
646
+ for (const project of this.compiledProjectsFor(graph)) {
647
+ if (!project.files.has(sourcePath)) continue;
648
+ for (const test of project.tests) {
649
+ this.addAffectedTest(sourcePath, test, graph, affectedTests, "COMPILED_PROJECT", evidence);
650
+ evidence.push(makeEvidence("COMPILED_PROJECT", sourcePath, `${test} compiles ${project.config}, which includes ${sourcePath}`, test));
651
+ }
652
+ }
461
653
  if (!hasNode(graph, sourcePath)) {
462
654
  if (isPotentialNextEntryPoint(sourcePath, this.layout) || isScriptFile(sourcePath, this.layout)) {
463
655
  this.addAffectedEntryPoint(sourcePath, profile, affectedEntryPoints, "NEW_ENTRY_POINT", sourcePath, evidence);
@@ -642,6 +834,39 @@ export class ImpactAnalyzer {
642
834
  return result;
643
835
  }
644
836
 
837
+ /**
838
+ * A computed `import(name)` or `require(path)` can load any file, so no graph edge says which changed
839
+ * file it reaches. It can only change what a test observes if that test runs the importer, so every
840
+ * test that does - the importer itself when it is a test, and each test depending on it - is
841
+ * selected whenever anything other than documentation changed. An importer outside the dependency
842
+ * graph has no known runners and requires full validation (2026-10-22, narrowing PR #32's global
843
+ * block: one repository's four computed imports had turned every analysis into a full run).
844
+ */
845
+ private collectComputedImportTests(
846
+ graphResult: DependencyGraphResult,
847
+ graph: DependencyGraph,
848
+ changedImpacts: ChangedImpact[],
849
+ affectedTests: Map<string, TestImpact>,
850
+ evidence: ImpactEvidence[],
851
+ riskSignals: ImpactRiskSignal[],
852
+ fallbackReasons: string[],
853
+ ): void {
854
+ const importers = [...new Set(graphResult.unresolved.filter((ref) => ref.computed).map((ref) => ref.importer))].sort();
855
+ if (importers.length === 0 || !changedImpacts.some((impact) => impact.category !== "docs")) return;
856
+ for (const importer of importers) {
857
+ if (!hasNode(graph, importer)) {
858
+ const message = `Computed module load in ${importer} is outside the dependency graph; full validation required`;
859
+ evidence.push(makeEvidence("COMPUTED_IMPORT", importer, message));
860
+ riskSignals.push({ level: "critical", reason: "COMPUTED_IMPORT", message, paths: [importer] });
861
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
862
+ continue;
863
+ }
864
+ const runners = [importer, ...graph.transitiveDependentsOf(importer)].filter((path) => this.isTestFile(path));
865
+ for (const test of runners) this.addAffectedTest(importer, test, graph, affectedTests, "COMPUTED_IMPORT", evidence);
866
+ evidence.push(makeEvidence("COMPUTED_IMPORT", importer, `${importer} loads a computed module specifier; the ${runners.length} test(s) that run it are selected`));
867
+ }
868
+ }
869
+
645
870
  private collectAlwaysRunTests(
646
871
  profile: RepositoryProfile,
647
872
  graph: DependencyGraph,
@@ -208,8 +208,11 @@ export function extractTestPatterns(source: string): ExtractedTestPatterns {
208
208
 
209
209
  const includes: string[] = [];
210
210
  for (const raw of [...(rawInclude ?? []), ...(rawTestMatch ?? [])]) {
211
- // Negations and non-globs (env names and the like) are not part of the universe.
212
- if (raw.startsWith("!") || !/[*/]/.test(raw)) continue;
211
+ // A literal filename is a valid include too. Dropping it while retaining another
212
+ // wildcard would incorrectly mark a partial test universe as complete.
213
+ // Negations are omitted conservatively: retaining their positive matches is wider.
214
+ if (raw.startsWith("!")) continue;
215
+ if (!raw.length) { complete = false; continue; }
213
216
  const value = stripRootDir(raw);
214
217
  if (value.includes(ROOT_DIR)) {
215
218
  // `<rootDir>` somewhere other than the front - not resolvable without evaluating the config.
@@ -228,7 +231,7 @@ export function extractTestPatterns(source: string): ExtractedTestPatterns {
228
231
 
229
232
  return {
230
233
  includes: Array.from(new Set(includes)),
231
- excludeGlobs: Array.from(new Set((readKey("exclude") ?? []).map(stripRootDir).filter((g) => /[*/]/.test(g) && !g.includes(ROOT_DIR)))),
234
+ excludeGlobs: Array.from(new Set((readKey("exclude") ?? []).map(stripRootDir).filter((g) => g.length > 0 && !g.includes(ROOT_DIR)))),
232
235
  ignoreRegexSources: Array.from(new Set(readKey("testPathIgnorePatterns") ?? [])),
233
236
  roots,
234
237
  declaresTests,
@@ -0,0 +1,158 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Which discovered test files does `npm test` actually run? (2026-10-21, dogfood telemetry.)
4
+ *
5
+ * WHY. Discovery reports every `*.test.*` file. One dogfood repository has 725; its `npm test` runs 548. The
6
+ * other 177 are real tests owned by other scripts (`test:d1-migration`, `test:ci-evidence`). DiffCI
7
+ * selected them, so 13 of 53 paired runs failed with "Selection falls outside the frozen full
8
+ * universe": the selective arm executed files the full arm never runs, which is not a comparison of
9
+ * two ways to run one suite. The receipts also over-reported the suite size.
10
+ *
11
+ * THE MODEL. The test script (with pretest/posttest, and any `npm run x` it calls) is split into `&&`
12
+ * phases. Each phase must be one of:
13
+ * - a node:test runner (`node --test`, `tsx --test`, with flags): its positional paths, directories
14
+ * and globs name the files it runs; with none, node's default discovery runs everything;
15
+ * - an interpreter running one repository file (`node scripts/test-security.js`): an OPAQUE phase.
16
+ * It runs a discovered test only by importing it (its graph closure) or by handing it to an
17
+ * import()/require()/spawn/exec/Worker call whose argument names the test or one of its
18
+ * directories;
19
+ * - a recognised tool that executes no repository tests (`tsc`, `eslint`, `prettier`).
20
+ * Anything else - another runner, a pipeline, `||`, a subshell, an unknown binary - leaves the model
21
+ * incomplete, and an incomplete model narrows nothing.
22
+ *
23
+ * THE SAFETY DIRECTION is the one src/repo/runner-universe.ts states: hiding a test the full command
24
+ * runs is the dangerous error, so every ambiguity widens the universe or abandons the model. A test the
25
+ * model excludes is not dropped either. It is reported as outside the full suite and still run when
26
+ * affected; it just is not presented as part of the full suite.
27
+ */
28
+ import { matchesGlob } from "./test-discovery.js";
29
+ import { referencePattern, referenceTokens } from "./file-references.js";
30
+
31
+ export interface ScriptUniverseInput {
32
+ scripts: Readonly<Record<string, string>>;
33
+ discoveredTests: readonly string[];
34
+ /** Transitive imports of a repository file, from the dependency graph. */
35
+ dependenciesOf: (path: string) => readonly string[];
36
+ read: (path: string) => string | undefined;
37
+ exists: (path: string) => boolean;
38
+ }
39
+
40
+ export interface ScriptUniverse {
41
+ /** False when any phase was not understood; `tests` is then every discovered test. */
42
+ complete: boolean;
43
+ reason?: string;
44
+ tests: string[];
45
+ }
46
+
47
+ const NODE_TEST_VALUE_FLAGS = new Set(["--conditions", "-C", "--import", "--require", "-r", "--loader", "--experimental-loader", "--test-reporter", "--test-reporter-destination", "--test-name-pattern", "--test-skip-pattern", "--test-concurrency", "--test-timeout", "--env-file", "--tsconfig"]);
48
+ const NON_EXECUTING_TOOLS = new Set(["tsc", "eslint", "prettier", "biome", "stylelint", "markdownlint", "cspell", "knip", "publint", "attw"]);
49
+ const INTERPRETERS = new Set(["node", "tsx", "ts-node", "bun"]);
50
+ const EXECUTING_CALL = /\b(?:import|require|spawn|spawnSync|exec|execSync|execFile|execFileSync|fork|execa|execaNode|Worker)\s*\(/g;
51
+
52
+ function shellWords(phase: string): string[] | undefined {
53
+ if (/[|;`<>\n]|\$\(|\|\|/.test(phase.replace(/"[^"]*"|'[^']*'/g, ""))) return undefined;
54
+ const words: string[] = [];
55
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g;
56
+ for (const match of phase.matchAll(pattern)) words.push(match[1] ?? match[2] ?? match[3] ?? "");
57
+ return words;
58
+ }
59
+
60
+ function expandScript(name: string, scripts: Readonly<Record<string, string>>, depth = 0): string[] | undefined {
61
+ if (depth > 5) return undefined;
62
+ const body = scripts[name];
63
+ if (typeof body !== "string") return undefined;
64
+ const phases: string[] = [];
65
+ for (const hook of [`pre${name}`, name, `post${name}`]) {
66
+ if (hook !== name && typeof scripts[hook] !== "string") continue;
67
+ for (const phase of (hook === name ? body : scripts[hook]!).split(/\s*&&\s*/)) {
68
+ const words = shellWords(phase.trim());
69
+ const nested = words && /^(?:npm|pnpm|yarn|bun)$/.test(words[0] ?? "")
70
+ ? (words[1] === "run" || words[1] === "run-script" ? words[2] : words[1] === "test" || words[1] === "t" ? "test" : undefined)
71
+ : undefined;
72
+ if (nested && words!.length <= (words![1] === "run" || words![1] === "run-script" ? 3 : 2)) {
73
+ if (nested === name) return undefined;
74
+ const expanded = expandScript(nested, scripts, depth + 1);
75
+ if (!expanded) return undefined;
76
+ phases.push(...expanded);
77
+ } else phases.push(phase.trim());
78
+ }
79
+ }
80
+ return phases;
81
+ }
82
+
83
+ /** Arguments of every call that could execute another module, from one file's text. */
84
+ function executingArguments(text: string): string[] {
85
+ const args: string[] = [];
86
+ for (const match of text.matchAll(EXECUTING_CALL)) {
87
+ let depth = 1;
88
+ let index = (match.index ?? 0) + match[0].length;
89
+ const start = index;
90
+ while (index < text.length && depth > 0 && index - start < 2000) {
91
+ const ch = text[index++];
92
+ if (ch === "(") depth++;
93
+ else if (ch === ")") depth--;
94
+ }
95
+ args.push(text.slice(start, index));
96
+ }
97
+ return args;
98
+ }
99
+
100
+ /** Models the files `npm test` runs. See the module comment for the rules and their direction. */
101
+ export function modelTestScriptUniverse(input: ScriptUniverseInput): ScriptUniverse {
102
+ const everything = (reason: string): ScriptUniverse => ({ complete: false, reason, tests: [...input.discoveredTests].sort() });
103
+ const phases = expandScript("test", input.scripts);
104
+ if (!phases) return everything("the test script could not be expanded into && phases");
105
+ const discovered = new Set(input.discoveredTests);
106
+ const universe = new Set<string>();
107
+ for (const phase of phases) {
108
+ const words = shellWords(phase);
109
+ if (!words || words.length === 0) return everything(`phase not understood: ${phase}`);
110
+ while (words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0]!)) words.shift();
111
+ if (words[0] === "cross-env") { words.shift(); while (words.length && /=/.test(words[0]!)) words.shift(); }
112
+ if (words[0] === "npx" && words[1] === "--no-install") words.splice(0, 2);
113
+ else if (words[0] === "npx") words.shift();
114
+ const executable = words[0] ?? "";
115
+ if (NON_EXECUTING_TOOLS.has(executable)) continue;
116
+ if (!INTERPRETERS.has(executable)) return everything(`phase runs ${executable || "nothing"}, which is not modelled`);
117
+ const positional: string[] = [];
118
+ let isTestRunner = false;
119
+ for (let i = 1; i < words.length; i++) {
120
+ const word = words[i]!;
121
+ if (word === "--test") { isTestRunner = true; continue; }
122
+ if (word.startsWith("-")) {
123
+ if (!word.includes("=") && NODE_TEST_VALUE_FLAGS.has(word)) i++;
124
+ continue;
125
+ }
126
+ positional.push(word.replace(/^\.\//, ""));
127
+ }
128
+ if (isTestRunner) {
129
+ if (positional.length === 0) return { complete: true, tests: [...input.discoveredTests].sort() };
130
+ for (const arg of positional) {
131
+ const matched = input.discoveredTests.filter((path) => path === arg || path.startsWith(`${arg.replace(/\/$/, "")}/`) || (/[*?{[]/.test(arg) && matchesGlob(path, arg)));
132
+ if (matched.length === 0 && !/[*?{[]/.test(arg) && input.exists(arg) && !discovered.has(arg)) {
133
+ return everything(`the test script runs ${arg}, which discovery does not recognise as a test`);
134
+ }
135
+ for (const path of matched) universe.add(path);
136
+ }
137
+ continue;
138
+ }
139
+ // An opaque phase: one repository file run by an interpreter.
140
+ const script = positional[0];
141
+ if (!script || positional.length > 1 && !input.exists(script)) return everything(`phase not understood: ${phase}`);
142
+ if (!input.exists(script)) return everything(`phase runs ${script}, which does not exist`);
143
+ const closure = [script, ...input.dependenciesOf(script)];
144
+ for (const path of closure) if (discovered.has(path)) universe.add(path);
145
+ const callArguments = closure.flatMap((path) => executingArguments(input.read(path) ?? ""));
146
+ if (callArguments.length === 0) continue;
147
+ // Spawning a test runner can run files no argument names (node --test with default discovery).
148
+ if (callArguments.some((args) => /--test\b|\b(?:vitest|jest|mocha|ava|playwright)\b/.test(args))) {
149
+ return everything(`${script} starts a test runner`);
150
+ }
151
+ for (const test of input.discoveredTests) {
152
+ if (universe.has(test)) continue;
153
+ const pattern = referencePattern(referenceTokens(test));
154
+ if (callArguments.some((args) => pattern.test(args))) universe.add(test);
155
+ }
156
+ }
157
+ return { complete: true, tests: [...universe].sort() };
158
+ }