@diffci.com/diffci 0.3.14 → 0.3.16

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 (100) hide show
  1. package/LICENSE +20 -661
  2. package/README.md +1 -1
  3. package/dist-client/src/client/agent-selection.js +20 -0
  4. package/dist-client/src/client/cli.js +155 -12
  5. package/dist-client/src/client/context.js +1 -1
  6. package/dist-client/src/client/enforce-misses-collect.js +157 -0
  7. package/dist-client/src/client/enforce-misses.js +229 -0
  8. package/dist-client/src/client/enforce-policy.js +169 -0
  9. package/dist-client/src/client/feedback-prompt.js +42 -0
  10. package/dist-client/src/client/hook.js +94 -0
  11. package/dist-client/src/client/mcp.js +12 -4
  12. package/dist-client/src/client/observe.js +8 -3
  13. package/dist-client/src/client/telemetry.js +46 -0
  14. package/dist-client/src/client/usage-signal.js +17 -10
  15. package/dist-client/src/client/verify.js +48 -6
  16. package/node_modules/@diffci.com/core/LICENSE +21 -661
  17. package/node_modules/@diffci.com/core/NOTICE +2 -2
  18. package/node_modules/@diffci.com/core/README.md +21 -3
  19. package/node_modules/@diffci.com/core/dist/analyze.js +1 -1
  20. package/node_modules/@diffci.com/core/dist/analyze.js.map +1 -1
  21. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +1 -1
  22. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js +1 -1
  24. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js.map +1 -1
  25. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +1 -1
  26. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  27. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +1 -1
  28. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  29. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +1 -1
  30. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +1 -1
  32. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/ci-inference/schema.js +1 -1
  34. package/node_modules/@diffci.com/core/dist/ci-inference/schema.js.map +1 -1
  35. package/node_modules/@diffci.com/core/dist/cli.js +1 -1
  36. package/node_modules/@diffci.com/core/dist/cli.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +29 -4
  38. package/node_modules/@diffci.com/core/dist/git/git-diff.js +136 -22
  39. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/git/types.d.ts +7 -0
  41. package/node_modules/@diffci.com/core/dist/index.js +1 -1
  42. package/node_modules/@diffci.com/core/dist/index.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/measurement.js +1 -1
  44. package/node_modules/@diffci.com/core/dist/measurement.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js +1 -1
  46. package/node_modules/@diffci.com/core/dist/repo/compiled-projects.js.map +1 -1
  47. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +32 -0
  48. package/node_modules/@diffci.com/core/dist/repo/file-references.js +180 -9
  49. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +4 -0
  51. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +19 -0
  52. package/node_modules/@diffci.com/core/dist/repo/impact.js +105 -3
  53. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  54. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.d.ts +27 -0
  55. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.js +116 -0
  56. package/node_modules/@diffci.com/core/dist/repo/npm-lockfile.js.map +1 -0
  57. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  58. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +1 -1
  60. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/repo/workspaces.js +1 -1
  62. package/node_modules/@diffci.com/core/dist/repo/workspaces.js.map +1 -1
  63. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +1 -1
  64. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  65. package/node_modules/@diffci.com/core/dist/research/baseline/test-activity.js +1 -1
  66. package/node_modules/@diffci.com/core/dist/research/baseline/test-activity.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +1 -1
  68. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  69. package/node_modules/@diffci.com/core/package.json +1 -1
  70. package/node_modules/@diffci.com/core/src/analyze.ts +1 -1
  71. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +1 -1
  72. package/node_modules/@diffci.com/core/src/ci-inference/causal.ts +1 -1
  73. package/node_modules/@diffci.com/core/src/ci-inference/evidence.ts +1 -1
  74. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +1 -1
  75. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +1 -1
  76. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +1 -1
  77. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +1 -1
  78. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +1 -1
  79. package/node_modules/@diffci.com/core/src/ci-inference/reference-graph.ts +1 -1
  80. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +1 -1
  81. package/node_modules/@diffci.com/core/src/ci-inference/schema.ts +1 -1
  82. package/node_modules/@diffci.com/core/src/cli.ts +1 -1
  83. package/node_modules/@diffci.com/core/src/git/git-diff.ts +127 -21
  84. package/node_modules/@diffci.com/core/src/git/types.ts +7 -0
  85. package/node_modules/@diffci.com/core/src/index.ts +1 -1
  86. package/node_modules/@diffci.com/core/src/measurement.ts +1 -1
  87. package/node_modules/@diffci.com/core/src/repo/compiled-projects.ts +1 -1
  88. package/node_modules/@diffci.com/core/src/repo/file-references.ts +170 -9
  89. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +4 -0
  90. package/node_modules/@diffci.com/core/src/repo/impact.ts +115 -2
  91. package/node_modules/@diffci.com/core/src/repo/npm-lockfile.ts +109 -0
  92. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  93. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +1 -1
  94. package/node_modules/@diffci.com/core/src/repo/workspaces.ts +1 -1
  95. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +1 -1
  96. package/node_modules/@diffci.com/core/src/research/baseline/path-baseline.ts +1 -1
  97. package/node_modules/@diffci.com/core/src/research/baseline/registry.ts +1 -1
  98. package/node_modules/@diffci.com/core/src/research/baseline/test-activity.ts +1 -1
  99. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +1 -1
  100. package/package.json +6 -4
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  /**
3
3
  * The reference graph — what an execution step DEPENDS ON in order to be reproducible.
4
4
  *
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  /**
3
3
  * Reference resolution — follows what a step depends on, and says plainly what it could not follow.
4
4
  *
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  /**
3
3
  * CI configuration inference — the evidence and learning schema.
4
4
  *
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // SPDX-License-Identifier: AGPL-3.0-only
2
+ // SPDX-License-Identifier: MIT
3
3
  import { parseArgs } from "node:util";
4
4
  import { analyzeCheckout } from "./analyze.js";
5
5
 
@@ -12,6 +12,7 @@ import {
12
12
  } from "./types.js";
13
13
  import { infrastructureRole, testScriptClosure } from "../repo/file-references.js";
14
14
  import { workflowMayRunTests } from "../repo/workflow-test-steps.js";
15
+ import { npmLockAffectedDependencies } from "../repo/npm-lockfile.js";
15
16
 
16
17
  export const EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
17
18
  export const ZERO_SHA = "0000000000000000000000000000000000000000";
@@ -274,37 +275,109 @@ function scriptRecord(value: unknown): Record<string, string> | undefined {
274
275
  return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
275
276
  }
276
277
 
278
+ const TEST_FILE_WORD = /^(?:\.\/)?[A-Za-z0-9._@+\-/]+\.(?:test|spec)\.[cm]?[jt]sx?$/;
279
+
280
+ /**
281
+ * The test files a test-closure script edit adds to or removes from an explicit file list, or
282
+ * undefined when the edit is anything else (2026-10-28). One dogfood repository's `test` script lists ~60 test
283
+ * files by path; agents add one to it in most commits that add a test, and every such edit forced the
284
+ * full suite (5 of the first 42 replayed commits). Only an insertion or removal of whole words that are
285
+ * test-file paths, inside an `&&` phase that runs `--test`, qualifies: the remaining words, in order,
286
+ * must be identical, so no flag, runner or other argument changed.
287
+ */
288
+ export function testListEdit(oldBody: string, newBody: string): { added: string[]; removed: string[] } | undefined {
289
+ const phases = (body: string) => body.split("&&").map((phase) => phase.trim().split(/\s+/).filter(Boolean));
290
+ const oldPhases = phases(oldBody);
291
+ const newPhases = phases(newBody);
292
+ if (oldPhases.length !== newPhases.length) return undefined;
293
+ const added: string[] = [];
294
+ const removed: string[] = [];
295
+ for (let i = 0; i < oldPhases.length; i++) {
296
+ const before = oldPhases[i]!;
297
+ const after = newPhases[i]!;
298
+ const beforeSet = new Set(before);
299
+ const afterSet = new Set(after);
300
+ const phaseAdded = after.filter((word) => !beforeSet.has(word));
301
+ const phaseRemoved = before.filter((word) => !afterSet.has(word));
302
+ if (phaseAdded.length === 0 && phaseRemoved.length === 0) {
303
+ if (before.join(" ") !== after.join(" ")) return undefined; // reordered or duplicated words
304
+ continue;
305
+ }
306
+ if (!before.includes("--test") || !after.includes("--test")) return undefined;
307
+ if (![...phaseAdded, ...phaseRemoved].every((word) => TEST_FILE_WORD.test(word))) return undefined;
308
+ const kept = (words: string[], dropped: string[]) => words.filter((word) => !dropped.includes(word)).join(" ");
309
+ if (kept(before, phaseRemoved) !== kept(after, phaseAdded)) return undefined;
310
+ added.push(...phaseAdded.map((word) => word.replace(/^\.\//, "")));
311
+ removed.push(...phaseRemoved.map((word) => word.replace(/^\.\//, "")));
312
+ }
313
+ return { added, removed };
314
+ }
315
+
316
+ const DEPENDENCY_FIELDS = new Set(["dependencies", "devDependencies", "optionalDependencies"]);
317
+
318
+ export interface PackageJsonChange {
319
+ kind: "metadata" | "data" | "dependencies" | "behavioral";
320
+ /** Test files a test-list edit added to the test script; they are now part of the suite. */
321
+ testScriptAddedPaths: string[];
322
+ /** Dependency names whose entry changed, when `kind` is `dependencies`. */
323
+ changedDependencies: string[];
324
+ }
325
+
277
326
  /**
278
327
  * How a modified package.json changed:
279
328
  * - `metadata`: only descriptive fields (hasRelevantPackageJsonChange is false);
280
- * - `data`: only PACKAGE_JSON_DATA_FIELDS and scripts outside the test closure (`test`, its
281
- * lifecycle hooks, install hooks, and every script they name) on either side - tests may read the
282
- * file, so it is resolved by reference rather than ignored;
283
- * - `behavioral`: anything else, including dependencies, engines, type, exports and unparseable JSON.
329
+ * - `data`: only PACKAGE_JSON_DATA_FIELDS, scripts outside the test closure (`test`, its lifecycle
330
+ * hooks, install hooks, and every script they name) on either side, and test-list edits (see
331
+ * testListEdit) - tests may read the file, so it is resolved by reference rather than ignored;
332
+ * - `dependencies`: as `data`, plus changed entries in dependencies, devDependencies or
333
+ * optionalDependencies. Which tests that affects depends on the lockfile and on who imports each
334
+ * package, so the caller decides, and stays behavioral when it cannot;
335
+ * - `behavioral`: anything else, including peerDependencies, overrides, engines, type, exports,
336
+ * workspaces and unparseable JSON.
284
337
  */
285
- export function packageJsonChangeKind(oldContent: string | undefined, newContent: string | undefined): "metadata" | "data" | "behavioral" {
286
- if (!hasRelevantPackageJsonChange(oldContent, newContent)) return "metadata";
338
+ export function packageJsonChange(oldContent: string | undefined, newContent: string | undefined): PackageJsonChange {
339
+ const result = (kind: PackageJsonChange["kind"], testScriptAddedPaths: string[] = [], changedDependencies: string[] = []): PackageJsonChange =>
340
+ ({ kind, testScriptAddedPaths, changedDependencies });
341
+ if (!hasRelevantPackageJsonChange(oldContent, newContent)) return result("metadata");
287
342
  let oldJson: Record<string, unknown>;
288
343
  let newJson: Record<string, unknown>;
289
344
  try {
290
345
  oldJson = JSON.parse(oldContent!);
291
346
  newJson = JSON.parse(newContent!);
292
347
  } catch {
293
- return "behavioral";
348
+ return result("behavioral");
294
349
  }
295
350
  const oldScripts = scriptRecord(oldJson.scripts);
296
351
  const newScripts = scriptRecord(newJson.scripts);
297
- if (!oldScripts || !newScripts) return "behavioral";
352
+ if (!oldScripts || !newScripts) return result("behavioral");
298
353
  const closure = new Set([...testScriptClosure(oldScripts), ...testScriptClosure(newScripts)]);
354
+ const added = new Set<string>();
355
+ const dependencies = new Set<string>();
299
356
  for (const field of new Set([...Object.keys(oldJson), ...Object.keys(newJson)])) {
300
357
  if (PACKAGE_JSON_METADATA_FIELDS.has(field) || PACKAGE_JSON_DATA_FIELDS.has(field)) continue;
301
358
  if (JSON.stringify(oldJson[field]) === JSON.stringify(newJson[field])) continue;
302
- if (field !== "scripts") return "behavioral";
359
+ if (DEPENDENCY_FIELDS.has(field)) {
360
+ const before = scriptRecord(oldJson[field]);
361
+ const after = scriptRecord(newJson[field]);
362
+ if (!before || !after) return result("behavioral");
363
+ for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) if (before[name] !== after[name]) dependencies.add(name);
364
+ continue;
365
+ }
366
+ if (field !== "scripts") return result("behavioral");
303
367
  for (const name of new Set([...Object.keys(oldScripts), ...Object.keys(newScripts)])) {
304
- if (oldScripts[name] !== newScripts[name] && closure.has(name)) return "behavioral";
368
+ if (oldScripts[name] === newScripts[name] || !closure.has(name)) continue;
369
+ const edit = oldScripts[name] !== undefined && newScripts[name] !== undefined ? testListEdit(oldScripts[name]!, newScripts[name]!) : undefined;
370
+ if (!edit) return result("behavioral");
371
+ for (const path of edit.added) added.add(path);
305
372
  }
306
373
  }
307
- return "data";
374
+ return result(dependencies.size > 0 ? "dependencies" : "data", [...added].sort(), [...dependencies].sort());
375
+ }
376
+
377
+ /** packageJsonChange's kind, with a dependency change reported as behavioral. */
378
+ export function packageJsonChangeKind(oldContent: string | undefined, newContent: string | undefined): "metadata" | "data" | "behavioral" {
379
+ const { kind } = packageJsonChange(oldContent, newContent);
380
+ return kind === "dependencies" ? "behavioral" : kind;
308
381
  }
309
382
 
310
383
  /** Reads a file's content at a specific commit via `git show <sha>:<path>`, without touching the
@@ -488,15 +561,47 @@ export async function analyzeGitDelta(
488
561
  // hasRelevantPackageJsonChange()'s own doc comment) and only ever narrows true -> false.
489
562
  const narrowed = new Set<ChangedFile>();
490
563
  const referenceResolvedPaths: string[] = [];
491
- if (analysis.dependencyManifestChanged) {
492
- const changedPackageJson = filesWithBinary.find((f) => f.path === "package.json" && f.changeType === "modified");
493
- if (changedPackageJson) {
494
- const oldContent = readFileAtSha(baseSha, "package.json", repoPath);
495
- const newContent = readFileAtSha(headSha, "package.json", repoPath);
496
- const kind = packageJsonChangeKind(oldContent, newContent);
497
- analysis.dependencyManifestChanged = kind === "behavioral";
498
- if (kind !== "behavioral") narrowed.add(changedPackageJson);
499
- if (kind === "data") referenceResolvedPaths.push("package.json");
564
+ const changedPackageJson = filesWithBinary.find((f) => f.path === "package.json" && f.changeType === "modified");
565
+ const oldPackageJson = readFileAtSha(baseSha, "package.json", repoPath);
566
+ const newPackageJson = readFileAtSha(headSha, "package.json", repoPath);
567
+ const packageChange = changedPackageJson ? packageJsonChange(oldPackageJson, newPackageJson) : undefined;
568
+ if (analysis.dependencyManifestChanged && changedPackageJson && packageChange) {
569
+ analysis.dependencyManifestChanged = packageChange.kind === "behavioral" || packageChange.kind === "dependencies";
570
+ if (packageChange.kind === "metadata" || packageChange.kind === "data") narrowed.add(changedPackageJson);
571
+ if (packageChange.kind === "data") referenceResolvedPaths.push("package.json");
572
+ if (packageChange.kind === "data" && packageChange.testScriptAddedPaths.length > 0) analysis.testScriptAddedPaths = packageChange.testScriptAddedPaths;
573
+ }
574
+ // 2026-10-28: a dependency change is narrowed to the direct dependencies whose installed tree the
575
+ // npm lockfile shows changed (src/repo/npm-lockfile.ts); ImpactAnalyzer selects the tests that
576
+ // import them, or falls back. Both files must agree: a manifest dependency change without a
577
+ // matching lockfile change stays global.
578
+ const changedLockfile = filesWithBinary.find((f) => f.path === "package-lock.json" && f.changeType === "modified");
579
+ const dependencyEdit = packageChange?.kind === "dependencies" || (!changedPackageJson && analysis.lockfileChanged);
580
+ const onlyNpmLock = (analysis.signalPaths?.lockfile ?? []).every((p) => p === "package-lock.json");
581
+ if (dependencyEdit && changedLockfile && onlyNpmLock) {
582
+ const manifests = [oldPackageJson, newPackageJson].map((content) => { try { return JSON.parse(content ?? "") as Record<string, unknown>; } catch { return undefined; } });
583
+ const direct = new Set<string>();
584
+ let modelled = manifests.every((manifest) => manifest && manifest.workspaces === undefined);
585
+ for (const manifest of manifests) {
586
+ for (const field of ["dependencies", "devDependencies", "optionalDependencies"]) {
587
+ const record = scriptRecord(manifest?.[field]);
588
+ if (!record) { modelled = false; continue; }
589
+ for (const name of Object.keys(record)) direct.add(name);
590
+ }
591
+ }
592
+ const affected = modelled
593
+ ? npmLockAffectedDependencies(readFileAtSha(baseSha, "package-lock.json", repoPath), readFileAtSha(headSha, "package-lock.json", repoPath), [...direct])
594
+ : undefined;
595
+ if (affected && (packageChange?.changedDependencies ?? []).every((name) => affected.includes(name))) {
596
+ analysis.dependencyManifestChanged = false;
597
+ analysis.lockfileChanged = false;
598
+ analysis.changedDependencies = affected;
599
+ narrowed.add(changedLockfile);
600
+ if (changedPackageJson) {
601
+ narrowed.add(changedPackageJson);
602
+ referenceResolvedPaths.push("package.json");
603
+ if (packageChange!.testScriptAddedPaths.length > 0) analysis.testScriptAddedPaths = packageChange!.testScriptAddedPaths;
604
+ }
500
605
  }
501
606
  }
502
607
  // 2026-10-21: a workflow that cannot run tests (deploy, publish, scan) cannot change a test
@@ -522,7 +627,8 @@ export async function analyzeGitDelta(
522
627
  analysis.configChanged = remaining.configChanged;
523
628
  analysis.workflowChanged = remaining.workflowChanged;
524
629
  analysis.signalPaths = { ...analysis.signalPaths, config: remaining.signalPaths?.config, workflow: remaining.signalPaths?.workflow,
525
- ...(analysis.dependencyManifestChanged ? {} : { dependencyManifest: [] }) };
630
+ ...(analysis.dependencyManifestChanged ? {} : { dependencyManifest: [] }),
631
+ ...(analysis.lockfileChanged ? {} : { lockfile: [] }) };
526
632
  }
527
633
  if (referenceResolvedPaths.length > 0) analysis.referenceResolvedPaths = referenceResolvedPaths.sort();
528
634
 
@@ -44,6 +44,13 @@ export interface GitDeltaAnalysis {
44
44
  * did not set a global flag above. Tests may still read them, so ImpactAnalyzer resolves their
45
45
  * readers by reference and falls back to full validation when it cannot (2026-10-21). */
46
46
  referenceResolvedPaths?: string[];
47
+ /** Test files a package.json test-list edit added to the test script (2026-10-28). They are part of
48
+ * the suite from this change on, so ImpactAnalyzer selects them. */
49
+ testScriptAddedPaths?: string[];
50
+ /** Direct dependencies whose installed tree changed, when a package.json/package-lock.json change was
51
+ * narrowed to them (src/repo/npm-lockfile.ts, 2026-10-28). ImpactAnalyzer selects the tests that
52
+ * import each one, and falls back when it cannot. Absent when no such narrowing happened. */
53
+ changedDependencies?: string[];
47
54
  /** The changed paths behind each flag above, so a fallback reason can name its files (2026-10-21:
48
55
  * "Configuration file(s) changed" was the most frequent reason in both telemetry cohorts and never
49
56
  * said which file). Absent on analyses produced before this field existed. */
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  export { analyzeGitDelta, EMPTY_TREE_SHA } from "./git/git-diff.js";
3
3
  export { analyzeRepository } from "./repo/analyzer.js";
4
4
  export { buildDependencyGraph, graphToJson } from "./repo/graph.js";
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  import { performance } from "node:perf_hooks";
3
3
 
4
4
  /** Local process measurements, not host/container billing or hardware energy measurements. */
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  /**
3
3
  * Tests that observe code by compiling it (2026-10-21).
4
4
  *
@@ -1,4 +1,4 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
1
+ // SPDX-License-Identifier: MIT
2
2
  /**
3
3
  * Who reads this file? (2026-10-21, telemetry from two dogfood repositories.)
4
4
  *
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import { readFileSync, statSync } from "node:fs";
35
35
  import { join, posix } from "node:path";
36
+ import { matchesGlob } from "./test-discovery.js";
36
37
 
37
38
  const MAX_READ_BYTES = 1_048_576;
38
39
 
@@ -141,6 +142,13 @@ export interface ReferenceResolutionInput {
141
142
  /** Changed files whose content analyzeGitDelta proved cannot change how tests run
142
143
  * (GitDeltaAnalysis.referenceResolvedPaths); a workflow reading them does not block. */
143
144
  contentCleared?: ReadonlySet<string>;
145
+ /** Treat a reader that tooling loads implicitly (wrangler config, Dockerfile, `*.config.*`) as
146
+ * unresolvable. Used for code: such a reader can run the file without anything naming it. */
147
+ implicitReadersUnresolvable?: boolean;
148
+ /** Resolve a file the root test script runs directly (`node scripts/test-security.js`) to that phase
149
+ * of the script instead of failing closed (ReferenceResolution.phases). Off by default: a caller
150
+ * that does not run the returned phases must keep the fallback. */
151
+ testPhases?: boolean;
144
152
  }
145
153
 
146
154
  export interface ReferenceResolution {
@@ -152,6 +160,9 @@ export interface ReferenceResolution {
152
160
  unresolvable: string[];
153
161
  /** Every reader found, for evidence. */
154
162
  readers: Array<{ path: string; kind: ReaderKind; via: string }>;
163
+ /** Phases of the root test script, verbatim, that run a reader directly; the caller must run them.
164
+ * Only produced with `testPhases`. */
165
+ phases: string[];
155
166
  }
156
167
 
157
168
  const MAX_DEPTH = 5;
@@ -180,20 +191,163 @@ export function testScriptClosure(scripts: Readonly<Record<string, string>>): Se
180
191
  return closure;
181
192
  }
182
193
 
183
- function packageJsonNames(content: string, pattern: RegExp): "yes" | "no" | "unparseable" {
194
+ const GLOB_CHARS = /[*?[\]{}]/;
195
+ const PATH_WORD = /^[A-Za-z0-9._\-/@+~*?[\]{}!,]+$/;
196
+
197
+ /**
198
+ * Whether a script body names `target`, judged word by word (2026-10-28). The reference pattern alone
199
+ * matched a test script that lists `ops/cloudflare/src/a.test.mjs` as naming every file under
200
+ * `ops/cloudflare/`, because the directory is a prefix of the listed file - in one dogfood repository, whose
201
+ * `test` script lists ~60 files, that made every data file under `scripts/` and `ops/` unresolvable.
202
+ * A word that is a different concrete path names that file, not its directories. Anything the check
203
+ * cannot read as a plain path or glob (inline code, variables, quotes inside a word) still counts as
204
+ * naming the target whenever the reference pattern matches it.
205
+ */
206
+ export function scriptNamesPath(body: string, target: string, pattern: RegExp, { ancestors = true, cwd = "" }: { ancestors?: boolean; cwd?: string } = {}): boolean {
207
+ if (!pattern.test(body)) return false;
208
+ const targetBase = posix.basename(target);
209
+ const dirs: string[] = [];
210
+ for (let dir = posix.dirname(target); ancestors && dir !== "." && dir !== "/"; dir = posix.dirname(dir)) dirs.push(dir);
211
+ for (const raw of body.split(/\s+/)) {
212
+ const word = raw.replace(/^["']+|["']+$/g, "");
213
+ if (!word) continue;
214
+ for (const candidate of word.includes("=") ? [word, word.slice(word.indexOf("=") + 1)] : [word]) {
215
+ if (!candidate) continue;
216
+ if (!PATH_WORD.test(candidate)) {
217
+ if (pattern.test(candidate) || pattern.test(raw)) return true;
218
+ continue;
219
+ }
220
+ if (candidate.startsWith("../") || candidate.startsWith("/") || candidate.startsWith("~")) {
221
+ if (posix.basename(candidate) === targetBase || pattern.test(` ${candidate} `)) return true;
222
+ continue;
223
+ }
224
+ const resolved = posix.normalize(posix.join(cwd || ".", candidate)).replace(/\/+$/, "");
225
+ if (GLOB_CHARS.test(candidate)) {
226
+ // Character classes are widened to any character, so an unsupported class syntax can only
227
+ // over-match. A glob naming a directory (`ops/*`) reaches the files inside it.
228
+ const widened = resolved.replace(/\[[^\]]*\]/g, "?");
229
+ if ([target, ...dirs].some((path) => matchesGlob(path, widened))) return true;
230
+ continue;
231
+ }
232
+ if (resolved === target || dirs.includes(resolved)) return true;
233
+ if (!candidate.includes("/") && (candidate === targetBase || dirs.some((dir) => posix.basename(dir) === candidate))) return true;
234
+ }
235
+ }
236
+ return false;
237
+ }
238
+
239
+ const CONTENT_PATH_WORD = /[A-Za-z0-9._\-/@+~*?{}[\]!,$]+/g;
240
+
241
+ /**
242
+ * Whether `content`, read from `readerPath`, names `target` (or, with `ancestors`, one of its
243
+ * directories), once each matching word is read as a whole path (2026-10-28). The reference pattern
244
+ * matches on the basename, so every `wrangler.jsonc` with `"main": "./src/index.js"` named every
245
+ * `src/index.js` in the repository, and `ops/cloudflare/src/a.js` named `ops/cloudflare/src/b.json` by
246
+ * sharing its directory. A word that resolves - from the reader's directory or the repository root - to
247
+ * a different file names that file. Bare names, globs and variables keep the conservative answer.
248
+ */
249
+ export function contentNamesPath(content: string, readerPath: string, target: string, pattern: RegExp, ancestors: boolean): boolean {
250
+ if (!pattern.test(content)) return false;
251
+ const dirs: string[] = [];
252
+ for (let dir = posix.dirname(target); ancestors && dir !== "." && dir !== "/"; dir = posix.dirname(dir)) dirs.push(dir);
253
+ const names = [target, ...dirs];
254
+ const readerDir = posix.dirname(readerPath);
255
+ for (const match of content.matchAll(CONTENT_PATH_WORD)) {
256
+ const word = match[0].replace(/[,.]+$/, "");
257
+ if (!pattern.test(`"${word}"`)) continue;
258
+ if (!word.includes("/") || /[*?{}[\]!$]/.test(word)) return true;
259
+ const trimmed = word.replace(/\/+$/, "");
260
+ const resolved = [posix.normalize(posix.join(readerDir, trimmed))];
261
+ if (!trimmed.startsWith("../")) resolved.push(posix.normalize(trimmed.replace(/^\/+/, "")));
262
+ if (resolved.some((path) => names.includes(path))) return true;
263
+ if (trimmed.startsWith(".")) continue;
264
+ // Relative to an unknown working directory, or an absolute path: any suffix relation counts.
265
+ if (names.some((name) => name === trimmed || name.endsWith(`/${trimmed}`) || trimmed.endsWith(`/${name}`))) return true;
266
+ }
267
+ return false;
268
+ }
269
+
270
+ /** Configs that tooling loads by their default name and that can run a repository file - a Worker
271
+ * entry point, a container command, a test setup file, a bundler plugin - without a test naming
272
+ * either. `tsconfig.json`, `.gitignore` and lint or style configs list paths but run nothing; a
273
+ * non-default `wrangler.validation.json` is used only when a command names it. */
274
+ const RUNS_FILES_WITHOUT_NAMING = /^(?:wrangler\.(?:toml|json|jsonc)|dockerfile.*|docker-compose.*|compose\.ya?ml|procfile|makefile|justfile|taskfile\.ya?ml|(?:vitest|vite|jest|playwright|cypress|ava|babel|webpack|rollup|esbuild|vue|nuxt|svelte|astro|next)\.config\..+|\.mocharc.*|\.babelrc.*|\.c8rc.*|\.nycrc.*)$/i;
275
+
276
+ function loadsWithoutNaming(path: string): boolean {
277
+ return RUNS_FILES_WITHOUT_NAMING.test(posix.basename(path));
278
+ }
279
+
280
+ const ENV_TEMPLATE = /^\.env(?:\.[^.]+)*\.(?:example|sample|template|dist)$|^env\.(?:example|sample|template)$/i;
281
+ /** Packages that load `.env.example` without being told its name. */
282
+ const IMPLICIT_ENV_TEMPLATE_LOADERS = /["'](?:dotenv-safe|dotenv-extended|dotenv-mono)["']/;
283
+
284
+ /**
285
+ * Files whose only loader is outside the test process, so with no reader at all the suite cannot
286
+ * observe them (2026-10-28):
287
+ * - a workflow analyzeGitDelta already showed runs no tests (contentCleared) - GitHub runs it, a test
288
+ * only sees it by naming it;
289
+ * - an environment template (`.env.example`) - a person copies it; dotenv loads `.env`, never the
290
+ * template, unless the repository depends on a loader that reads the template by default.
291
+ * Every other file with no reader stays unknown: absence of a reference is not proof in general.
292
+ */
293
+ function loadedOnlyOutsideTests(filePath: string, input: ReferenceResolutionInput, read: (path: string) => string | undefined): boolean {
294
+ if (/^\.github\/workflows\/[^/]+\.ya?ml$/.test(filePath)) return input.contentCleared?.has(filePath) === true;
295
+ if (!ENV_TEMPLATE.test(posix.basename(filePath))) return false;
296
+ const manifest = read("package.json");
297
+ return manifest !== undefined && !IMPLICIT_ENV_TEMPLATE_LOADERS.test(manifest);
298
+ }
299
+
300
+ const PHASE_INTERPRETERS = new Set(["node", "tsx"]);
301
+ const PHASE_VALUE_FLAGS = new Set(["--conditions", "-C", "--import", "--require", "-r", "--loader", "--experimental-loader", "--env-file", "--tsconfig"]);
302
+
303
+ /**
304
+ * The `&&` phases of the root test closure that run `target` directly with an interpreter
305
+ * (`node scripts/test-security.js`, `tsx --import ./setup.mjs scripts/x.ts`), when those phases
306
+ * are the only way the closure names it; undefined otherwise (2026-10-28). Such a phase is a test in
307
+ * all but name: one dogfood repository's `npm test` ends with two, one of which reads every file under `src/`
308
+ * and `scripts/`, and every data file there fell back to the full suite for it. Running the phase
309
+ * itself covers it.
310
+ */
311
+ function directTestPhases(content: string, target: string, pattern: RegExp, ancestors: boolean): string[] | undefined {
312
+ let record: Record<string, string>;
313
+ try {
314
+ const scripts = (JSON.parse(content) as { scripts?: unknown }).scripts;
315
+ if (!scripts || typeof scripts !== "object") return undefined;
316
+ record = Object.fromEntries(Object.entries(scripts).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
317
+ } catch {
318
+ return undefined;
319
+ }
320
+ const found: string[] = [];
321
+ for (const name of testScriptClosure(record)) {
322
+ const rest: string[] = [];
323
+ for (const phase of (record[name] ?? "").split("&&").map((part) => part.trim())) {
324
+ const words = phase.split(/\s+/);
325
+ const runs = words.length >= 2 && PHASE_INTERPRETERS.has(words[0]!)
326
+ && posix.normalize(words[words.length - 1]!) === target
327
+ && words.slice(1, -1).every((word, index, middle) => word.startsWith("-") || PHASE_VALUE_FLAGS.has(middle[index - 1] ?? ""))
328
+ && !/[|;<>`$(]/.test(phase);
329
+ if (runs) found.push(phase); else rest.push(phase);
330
+ }
331
+ if (scriptNamesPath(rest.join(" && "), target, pattern, { ancestors })) return undefined;
332
+ }
333
+ return found.length > 0 ? found : undefined;
334
+ }
335
+
336
+ function packageJsonNames(content: string, pattern: RegExp, target: string, ancestors: boolean, cwd: string): "yes" | "no" | "unparseable" {
184
337
  let parsed: unknown;
185
338
  try { parsed = JSON.parse(content); } catch { return "unparseable"; }
186
339
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "unparseable";
187
340
  const scripts = (parsed as { scripts?: unknown }).scripts;
188
341
  if (!scripts || typeof scripts !== "object") return "no";
189
342
  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";
343
+ for (const name of testScriptClosure(record)) if (scriptNamesPath(record[name] ?? "", target, pattern, { ancestors, cwd })) return "yes";
191
344
  return "no";
192
345
  }
193
346
 
194
347
  /** Resolves who reads `filePath`. See the module comment for the rule and its limits. */
195
348
  export function resolveFileReferences(filePath: string, input: ReferenceResolutionInput): ReferenceResolution {
196
- const resolution: ReferenceResolution = { tests: [], code: [], unresolvable: [], readers: [] };
349
+ const resolution: ReferenceResolution = { tests: [], code: [], unresolvable: [], readers: [], phases: [] };
350
+ const phases = new Set<string>();
197
351
  const tests = new Set<string>();
198
352
  const code = new Set<string>();
199
353
  const visited = new Set<string>([filePath]);
@@ -209,26 +363,32 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
209
363
  // directory. A reader reached through the changed file (a script, a manifest) matters only if
210
364
  // something runs or reads it by name; matching its directories as well made `"tests"` and
211
365
  // `"fixtures"` match nearly every file and no generic name (package.json) could resolve.
212
- const pattern = referencePattern(referenceTokens(target.path, { ancestors: target.path === filePath }));
366
+ const ancestors = target.path === filePath;
367
+ const pattern = referencePattern(referenceTokens(target.path, { ancestors }));
213
368
  for (const candidate of input.files) {
214
369
  if (visited.has(candidate) || candidate === target.path || LOCKFILES.has(posix.basename(candidate))) continue;
215
370
  const base = posix.basename(candidate);
216
371
  if (base === "package.json") {
217
372
  const content = read(candidate);
218
373
  if (content === undefined) continue;
219
- const named = packageJsonNames(content, pattern);
374
+ const named = packageJsonNames(content, pattern, target.path, ancestors, posix.dirname(candidate));
220
375
  if (named === "no") continue;
221
376
  visited.add(candidate);
222
377
  if (named === "unparseable") { resolution.unresolvable.push(`${candidate} could not be parsed`); continue; }
223
378
  resolution.readers.push({ path: candidate, kind: "package-script", via: target.path });
379
+ const direct = input.testPhases && candidate === "package.json" ? directTestPhases(content, target.path, pattern, ancestors) : undefined;
380
+ if (direct) { for (const phase of direct) phases.add(phase); continue; }
224
381
  resolution.unresolvable.push(`${candidate} runs ${target.path} as part of its test script`);
225
382
  continue;
226
383
  }
227
384
  if (input.isDocumentation(candidate)) continue;
228
385
  const content = read(candidate);
229
- if (content === undefined || !pattern.test(content)) continue;
386
+ if (content === undefined || !contentNamesPath(content, candidate, target.path, pattern, ancestors)) continue;
230
387
  visited.add(candidate);
231
- if (candidate.startsWith(".github/")) {
388
+ if (input.implicitReadersUnresolvable && loadsWithoutNaming(candidate)) {
389
+ resolution.readers.push({ path: candidate, kind: "unresolvable", via: target.path });
390
+ resolution.unresolvable.push(`${candidate} is loaded by tooling and names ${target.path}`);
391
+ } else if (candidate.startsWith(".github/")) {
232
392
  // A workflow step that comes before a test step in its job, or a composite action, may feed
233
393
  // the file to the suite's environment; issue templates and standalone CI checks do not.
234
394
  // A change content inspection already showed cannot alter how tests run (a version bump)
@@ -266,9 +426,10 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
266
426
  // script or test-feeding workflow step reaches: the suite cannot observe the file. Finding no such
267
427
  // reader at all is different - the file's reader is unknown, so it stays unknown.
268
428
  const executableReaders = resolution.readers.some((reader) => reader.kind === "transitive");
269
- if (resolution.unresolvable.length === 0 && tests.size === 0 && code.size === 0 && !executableReaders) {
429
+ if (resolution.unresolvable.length === 0 && tests.size === 0 && code.size === 0 && !executableReaders && !loadedOnlyOutsideTests(filePath, input, read)) {
270
430
  resolution.unresolvable.push(`no test or source file names ${filePath}`);
271
431
  }
432
+ resolution.phases = resolution.unresolvable.length === 0 ? [...phases].sort() : [];
272
433
  resolution.tests = [...tests].sort();
273
434
  resolution.code = [...code].sort();
274
435
  return resolution;
@@ -88,6 +88,10 @@ export interface ImpactResult {
88
88
  /** Affected tests that the test script does not run. Not part of the selection, which stays a
89
89
  * subset of the full suite, but still worth running. Present only with `fullSuiteTestCount`. */
90
90
  testsOutsideFullSuite?: TestImpact[];
91
+ /** Phases of the root test script, verbatim, that a selective run must execute besides the selected
92
+ * test files (`node scripts/test-security.js`). Only produced with `selectTestPhases`; present
93
+ * whenever the selection relies on them. */
94
+ testPhases?: string[];
91
95
  affectedEntryPoints: EntryPointImpact[];
92
96
  affectedScripts: string[];
93
97