@diffci.com/diffci 0.3.22 → 0.3.24

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 (55) hide show
  1. package/dist-client/src/client/agent-setup.d.ts +23 -0
  2. package/dist-client/src/client/agent-setup.js +111 -0
  3. package/dist-client/src/client/cli.js +33 -9
  4. package/dist-client/src/client/command-batches.d.ts +1 -0
  5. package/dist-client/src/client/command-batches.js +3 -2
  6. package/dist-client/src/client/failure-baseline.js +0 -0
  7. package/dist-client/src/client/full-command.d.ts +10 -0
  8. package/dist-client/src/client/full-command.js +22 -0
  9. package/dist-client/src/client/hook.d.ts +1 -0
  10. package/dist-client/src/client/hook.js +9 -0
  11. package/dist-client/src/client/mcp.js +10 -4
  12. package/dist-client/src/client/observe.js +10 -5
  13. package/dist-client/src/client/selected-coverage.d.ts +21 -1
  14. package/dist-client/src/client/selected-coverage.js +83 -10
  15. package/dist-client/src/client/verify-savings.d.ts +3 -1
  16. package/dist-client/src/client/verify-savings.js +1 -0
  17. package/dist-client/src/client/verify.js +50 -19
  18. package/dist-client/src/client/workflow-guard.js +14 -0
  19. package/node_modules/@diffci.com/core/README.md +4 -0
  20. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  21. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
  22. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +3 -0
  24. package/node_modules/@diffci.com/core/dist/git/git-diff.js +109 -8
  25. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/git/types.d.ts +6 -2
  27. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +4 -0
  28. package/node_modules/@diffci.com/core/dist/planner/test-command.js +140 -26
  29. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/analyzer.js +9 -2
  31. package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/repo/graph.js +231 -28
  33. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +5 -0
  35. package/node_modules/@diffci.com/core/dist/repo/impact.js +57 -7
  36. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.d.ts +6 -0
  38. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js +161 -0
  39. package/node_modules/@diffci.com/core/dist/repo/pnpm-lockfile.js.map +1 -0
  40. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +5 -1
  41. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +55 -6
  42. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +7 -0
  44. package/node_modules/@diffci.com/core/package.json +1 -1
  45. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
  46. package/node_modules/@diffci.com/core/src/git/git-diff.ts +91 -7
  47. package/node_modules/@diffci.com/core/src/git/types.ts +6 -2
  48. package/node_modules/@diffci.com/core/src/planner/test-command.ts +138 -22
  49. package/node_modules/@diffci.com/core/src/repo/analyzer.ts +9 -2
  50. package/node_modules/@diffci.com/core/src/repo/graph.ts +206 -30
  51. package/node_modules/@diffci.com/core/src/repo/impact.ts +53 -7
  52. package/node_modules/@diffci.com/core/src/repo/pnpm-lockfile.ts +147 -0
  53. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +52 -8
  54. package/node_modules/@diffci.com/core/src/repo/types.ts +7 -0
  55. package/package.json +2 -2
@@ -16,6 +16,7 @@ import type {
16
16
  GraphIntegrityFinding,
17
17
  GraphIntegrityReport,
18
18
  GraphPerformanceMetrics,
19
+ RepositoryProfile,
19
20
  ResolutionReference,
20
21
  SourceRoot,
21
22
  UnresolvedDependency,
@@ -26,6 +27,76 @@ interface ImportRef {
26
27
  kind: DependencyEdgeKind;
27
28
  dynamic: boolean;
28
29
  computed?: boolean;
30
+ /** For a computed load whose target set is still bounded by literal text: `` import(`./x/${a}.json`) ``
31
+ * or `import.meta.glob("./x/*.json")`. `base` is the literal directory prefix (a specifier ending in
32
+ * "/"); `regex` matches paths relative to it. Unresolvable patterns keep the load computed. */
33
+ patterns?: { base: string; regex: string; negated: boolean }[];
34
+ /** `import { type A, type B }` or `export { type A } from`: every specifier is inline `type`, so the
35
+ * statement is erased unless the importer's tsconfig preserves imports (see `keepsTypeOnlyImports`). */
36
+ inlineTypeOnly?: boolean;
37
+ /** A `vi.mock("./x")` / `jest.mock("./x")` target. Vitest counts these as dependencies of the test;
38
+ * an unresolvable one (a virtual or aliased module) is dropped rather than made unsafe. */
39
+ mock?: boolean;
40
+ }
41
+
42
+ /** Test-runner calls whose literal first argument names a module the test depends on. */
43
+ const MOCK_MODULE_CALLS = new Set([
44
+ "vi.mock", "vi.doMock", "vi.unmock", "vi.doUnmock", "vi.importActual", "vi.importMock",
45
+ "jest.mock", "jest.doMock", "jest.unmock", "jest.dontMock", "jest.requireActual", "jest.requireMock", "jest.createMockFromModule",
46
+ ]);
47
+
48
+ /** Whether this importer's emit keeps statements whose specifiers are all inline `type`. Without these
49
+ * options TypeScript, esbuild and oxc drop the whole statement, so it never loads the target. */
50
+ function keepsTypeOnlyImports(options: ts.CompilerOptions): boolean {
51
+ return Boolean(options.verbatimModuleSyntax || options.preserveValueImports || options.importsNotUsedAsValues === ts.ImportsNotUsedAsValues.Preserve);
52
+ }
53
+
54
+ function allInlineType(elements: readonly (ts.ImportSpecifier | ts.ExportSpecifier)[]): boolean {
55
+ return elements.length > 0 && elements.every((element) => element.isTypeOnly);
56
+ }
57
+
58
+ const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
59
+ // A specifier may omit the extension or name a directory's index module.
60
+ const OPTIONAL_MODULE_SUFFIX = "(?:\\.[A-Za-z0-9]+|/index\\.[A-Za-z0-9]+)?";
61
+
62
+ /** `` `@/../locales/${lng}/${ns}.json` `` -> base "@/../locales/", each substitution matching any text. A
63
+ * substitution can hold "/" so it matches across directories, which can only over-select. */
64
+ function templatePattern(template: ts.TemplateExpression): ImportRef["patterns"] {
65
+ const head = template.head.text;
66
+ const cut = head.lastIndexOf("/");
67
+ if (cut < 0) return undefined;
68
+ const regex = escapeRegex(head.slice(cut + 1)) + template.templateSpans.map((span) => `.*${escapeRegex(span.literal.text)}`).join("");
69
+ return [{ base: head.slice(0, cut + 1), regex: `${regex}${OPTIONAL_MODULE_SUFFIX}`, negated: false }];
70
+ }
71
+
72
+ /** One Vite `import.meta.glob` pattern; `[...]` classes are not translated and keep the load computed. */
73
+ function globPattern(glob: string): NonNullable<ImportRef["patterns"]>[number] | undefined {
74
+ const negated = glob.startsWith("!");
75
+ const body = negated ? glob.slice(1) : glob;
76
+ const firstWild = body.search(/[*?{[]/);
77
+ const cut = body.lastIndexOf("/", firstWild < 0 ? body.length : firstWild);
78
+ if (cut < 0 || body.includes("[")) return undefined;
79
+ let regex = "";
80
+ const rest = body.slice(cut + 1);
81
+ for (let i = 0; i < rest.length; i++) {
82
+ const char = rest[i]!;
83
+ if (rest.startsWith("**/", i)) { regex += "(?:.*/)?"; i += 2; }
84
+ else if (rest.startsWith("**", i)) { regex += ".*"; i += 1; }
85
+ else if (char === "*") regex += "[^/]*";
86
+ else if (char === "?") regex += "[^/]";
87
+ else if (char === "{") {
88
+ const close = rest.indexOf("}", i);
89
+ if (close < 0) return undefined;
90
+ regex += `(?:${rest.slice(i + 1, close).split(",").map(escapeRegex).join("|")})`;
91
+ i = close;
92
+ } else regex += escapeRegex(char);
93
+ }
94
+ return { base: body.slice(0, cut + 1), regex, negated };
95
+ }
96
+
97
+ function isImportMetaGlob(expression: ts.Expression): boolean {
98
+ return ts.isPropertyAccessExpression(expression) && /^glob(?:Eager)?$/.test(expression.name.text)
99
+ && ts.isMetaProperty(expression.expression) && expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword;
29
100
  }
30
101
 
31
102
  const SOURCE_EXTENSIONS = new Set([
@@ -126,9 +197,12 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
126
197
  if (ts.isImportDeclaration(node)) {
127
198
  const specifier = node.moduleSpecifier;
128
199
  if (ts.isStringLiteral(specifier)) {
129
- const isTypeOnly = node.importClause?.isTypeOnly ?? false;
200
+ const clause = node.importClause;
201
+ const isTypeOnly = clause?.isTypeOnly ?? false;
130
202
  const kind: DependencyEdgeKind = isTypeOnly ? "type-import" : "import";
131
- refs.push({ specifier: specifier.text, kind, dynamic: false });
203
+ const inlineTypeOnly = !isTypeOnly && !!clause && !clause.name && !!clause.namedBindings
204
+ && ts.isNamedImports(clause.namedBindings) && allInlineType(clause.namedBindings.elements);
205
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
132
206
  }
133
207
  } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
134
208
  const specifier = node.moduleReference.expression;
@@ -139,7 +213,8 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
139
213
  const specifier = node.moduleSpecifier;
140
214
  if (ts.isStringLiteral(specifier)) {
141
215
  const kind: DependencyEdgeKind = node.isTypeOnly ? "type-import" : "re-export";
142
- refs.push({ specifier: specifier.text, kind, dynamic: false });
216
+ const inlineTypeOnly = !node.isTypeOnly && !!node.exportClause && ts.isNamedExports(node.exportClause) && allInlineType(node.exportClause.elements);
217
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
143
218
  }
144
219
  } else if (ts.isCallExpression(node)) {
145
220
  const firstArg = node.arguments[0];
@@ -147,11 +222,29 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
147
222
  const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require" && shadowDepth === 0;
148
223
  if ((isImport || isRequire) && firstArg) {
149
224
  const literal = ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg);
225
+ const patterns = ts.isTemplateExpression(firstArg) ? templatePattern(firstArg) : undefined;
150
226
  refs.push({
151
227
  specifier: literal ? firstArg.text : firstArg.getText(sourceFile).slice(0, 200),
152
228
  kind: isImport ? "dynamic-import" : "require",
153
229
  dynamic: isImport || !literal,
154
230
  computed: !literal,
231
+ ...(patterns ? { patterns } : {}),
232
+ });
233
+ } else if (firstArg && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
234
+ && MOCK_MODULE_CALLS.has(`${node.expression.expression.text}.${node.expression.name.text}`)
235
+ && (ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg))) {
236
+ refs.push({ specifier: firstArg.text, kind: "import", dynamic: false, mock: true });
237
+ } else if (isImportMetaGlob(node.expression) && firstArg) {
238
+ // Vite expands these at build time; without them a file loaded only through a glob had no edge.
239
+ const items = ts.isArrayLiteralExpression(firstArg) ? [...firstArg.elements] : [firstArg];
240
+ const globs = items.map((item) => ts.isStringLiteral(item) || ts.isNoSubstitutionTemplateLiteral(item) ? item.text : undefined);
241
+ const patterns = globs.every((glob) => glob !== undefined) ? globs.map((glob) => globPattern(glob!)) : [];
242
+ refs.push({
243
+ specifier: firstArg.getText(sourceFile).slice(0, 200),
244
+ kind: "dynamic-import",
245
+ dynamic: true,
246
+ computed: true,
247
+ ...(patterns.length && patterns.every(Boolean) ? { patterns: patterns as NonNullable<ImportRef["patterns"]> } : {}),
155
248
  });
156
249
  }
157
250
  }
@@ -169,6 +262,8 @@ class DependencyGraphImpl implements DependencyGraph {
169
262
  readonly edges: DependencyEdge[];
170
263
  readonly forward: Record<string, string[]> = {};
171
264
  readonly reverse: Record<string, string[]> = {};
265
+ /** `reverse` without `import type` edges, which TypeScript erases before anything runs. */
266
+ private readonly reverseRuntime: Record<string, string[]> = {};
172
267
 
173
268
  constructor(
174
269
  sourcePaths: ReadonlySet<string>,
@@ -199,6 +294,7 @@ class DependencyGraphImpl implements DependencyGraph {
199
294
  for (const node of this.nodes) {
200
295
  this.forward[node.path] = [];
201
296
  this.reverse[node.path] = [];
297
+ this.reverseRuntime[node.path] = [];
202
298
  }
203
299
 
204
300
  for (const edge of this.edges) {
@@ -207,14 +303,14 @@ class DependencyGraphImpl implements DependencyGraph {
207
303
  }
208
304
  if (this.reverse[edge.to] !== undefined) {
209
305
  this.reverse[edge.to]!.push(edge.from);
306
+ if (edge.kind !== "type-import") this.reverseRuntime[edge.to]!.push(edge.from);
210
307
  }
211
308
  }
212
309
 
213
- for (const key of Object.keys(this.forward)) {
214
- this.forward[key] = [...new Set(this.forward[key]!)].sort();
215
- }
216
- for (const key of Object.keys(this.reverse)) {
217
- this.reverse[key] = [...new Set(this.reverse[key]!)].sort();
310
+ for (const adjacency of [this.forward, this.reverse, this.reverseRuntime]) {
311
+ for (const key of Object.keys(adjacency)) {
312
+ adjacency[key] = [...new Set(adjacency[key]!)].sort();
313
+ }
218
314
  }
219
315
  }
220
316
 
@@ -237,34 +333,31 @@ class DependencyGraphImpl implements DependencyGraph {
237
333
  }
238
334
 
239
335
  transitiveDependenciesOf(filePath: string): string[] {
240
- return this.transitiveTraversal(filePath, "forward");
336
+ return this.transitiveTraversal(filePath, this.forward);
241
337
  }
242
338
 
243
339
  transitiveDependentsOf(filePath: string): string[] {
244
- return this.transitiveTraversal(filePath, "reverse");
340
+ return this.transitiveTraversal(filePath, this.reverse);
245
341
  }
246
342
 
247
- private transitiveTraversal(
248
- filePath: string,
249
- direction: "forward" | "reverse",
250
- ): string[] {
343
+ transitiveRuntimeDependentsOf(filePath: string): string[] {
344
+ return this.transitiveTraversal(filePath, this.reverseRuntime);
345
+ }
346
+
347
+ private transitiveTraversal(filePath: string, adjacency: Record<string, string[]>): string[] {
251
348
  const rel = this.normalizeQuery(filePath);
252
- const visited = new Set<string>();
349
+ const visited = new Set<string>([rel]);
350
+ // An index, not shift(): shift() is O(n) and made dependents of hub modules quadratic (2026-11-03,
351
+ // 379 s of impact analysis on one LobeHub commit whose changed files had ~14k dependents).
253
352
  const queue: string[] = [rel];
254
- const result: string[] = [];
255
- const adjacency = direction === "forward" ? this.forward : this.reverse;
256
-
257
- while (queue.length > 0) {
258
- const current = queue.shift()!;
259
- if (visited.has(current)) continue;
260
- visited.add(current);
261
- if (current !== rel) result.push(current);
262
- for (const next of adjacency[current] ?? []) {
263
- if (!visited.has(next)) queue.push(next);
353
+ for (let head = 0; head < queue.length; head++) {
354
+ for (const next of adjacency[queue[head]!] ?? []) {
355
+ if (visited.has(next)) continue;
356
+ visited.add(next);
357
+ queue.push(next);
264
358
  }
265
359
  }
266
-
267
- return result.sort();
360
+ return queue.slice(1).sort();
268
361
  }
269
362
 
270
363
  private normalizeQuery(filePath: string): string {
@@ -771,6 +864,7 @@ export async function buildDependencyGraph(
771
864
  ref: ImportRef,
772
865
  reason: string,
773
866
  ): void {
867
+ if (ref.mock) return;
774
868
  unresolved.push({
775
869
  importer: importerRel,
776
870
  specifier: ref.specifier,
@@ -786,6 +880,7 @@ export async function buildDependencyGraph(
786
880
  importer: string,
787
881
  ref: ImportRef,
788
882
  ): void {
883
+ if (ref.mock && resolution === "unresolved") return;
789
884
  references.push({
790
885
  resolution,
791
886
  specifier: ref.specifier,
@@ -800,6 +895,35 @@ export async function buildDependencyGraph(
800
895
  addEdge(importerRel, assetRel, "asset");
801
896
  }
802
897
 
898
+ /** Every repository file a bounded computed load can name, or undefined to keep it computed: the
899
+ * base directory does not resolve, nothing matches, or a match is neither analyzed source nor an
900
+ * asset. Alias directories resolve as in findAssetCandidate, and all candidates are unioned. */
901
+ function resolvePatternTargets(importerAbs: string, patterns: NonNullable<ImportRef["patterns"]>, importerOptions: ts.CompilerOptions): string[] | undefined {
902
+ const compilerAliases = Object.entries(importerOptions.paths ?? {}).map(([pattern, substitutions]) => ({ pattern, substitutions }));
903
+ const aliasRoot = importerOptions.baseUrl ?? (importerOptions as { pathsBasePath?: string }).pathsBasePath ?? repoPath;
904
+ const included = new Set<string>();
905
+ const excluded = new Set<string>();
906
+ for (const pattern of patterns) {
907
+ const base = pattern.base.replace(/\/+$/, "") || ".";
908
+ if (base.startsWith("/")) return undefined;
909
+ const directories = base.startsWith(".") ? [resolve(dirname(importerAbs), base)]
910
+ : [...expandAliasCandidates(base, compilerAliases, aliasRoot), ...expandAliasCandidates(base, profile.pathAliases, repoPath)];
911
+ const matcher = new RegExp(`^${pattern.regex}$`);
912
+ for (const directory of directories) {
913
+ const rel = toRelativeInternal(repoPath, directory);
914
+ if (rel === undefined) continue;
915
+ const prefix = rel === "." ? "" : `${rel}/`;
916
+ for (const file of files) {
917
+ if (file.startsWith(prefix) && matcher.test(file.slice(prefix.length))) (pattern.negated ? excluded : included).add(file);
918
+ }
919
+ }
920
+ }
921
+ const importerRel = toRelativeInternal(repoPath, importerAbs);
922
+ const targets = [...included].filter((file) => !excluded.has(file) && file !== importerRel).sort();
923
+ if (!targets.length || targets.some((file) => !internalSourcePaths.has(file) && !isAssetFileName(file))) return undefined;
924
+ return targets;
925
+ }
926
+
803
927
  let filesParsed = sourceFiles.length;
804
928
  let followedImplementationFiles = 0;
805
929
 
@@ -861,11 +985,23 @@ export async function buildDependencyGraph(
861
985
 
862
986
  const importerOptions = optionsFor(sf.fileName);
863
987
 
864
- const refs = extractImportRefs(sf);
988
+ const keepsTypeImports = keepsTypeOnlyImports(importerOptions);
989
+ const refs = extractImportRefs(sf).map((ref) => ref.inlineTypeOnly && !keepsTypeImports ? { ...ref, kind: "type-import" as const } : ref);
865
990
  if (scope && sf.referencedFiles.length) adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
866
991
  for (const ref of refs) {
867
992
  // Expression text is not a module name. In particular, import(name) must
868
993
  // not be classified as an external package called "name".
994
+ if (ref.computed && ref.patterns) {
995
+ const targets = resolvePatternTargets(sf.fileName, ref.patterns, importerOptions);
996
+ if (targets) {
997
+ for (const target of targets) {
998
+ if (internalSourcePaths.has(target)) addEdge(importerRel, target, ref.kind);
999
+ else recordAssetEdge(importerRel, target);
1000
+ }
1001
+ recordReference(targets.some((target) => internalSourcePaths.has(target)) ? "internal-source" : "internal-asset", importerRel, ref);
1002
+ continue;
1003
+ }
1004
+ }
869
1005
  if (ref.computed) {
870
1006
  recordUnresolved(importerRel, ref, "computed module specifier requires full validation");
871
1007
  recordReference("unresolved", importerRel, ref);
@@ -1123,6 +1259,7 @@ export async function buildDependencyGraph(
1123
1259
  confidence,
1124
1260
  integrity,
1125
1261
  resolvedViaProjectReferences,
1262
+ runtimeTestSelection: runtimeTestSelectionEligible(repoPath, files, profile),
1126
1263
  };
1127
1264
  }
1128
1265
 
@@ -1291,6 +1428,35 @@ export function validateDependencyGraph(graph: DependencyGraph): GraphIntegrityR
1291
1428
  };
1292
1429
  }
1293
1430
 
1431
+ /**
1432
+ * Whether an `import type` edge can be ignored when selecting tests (2026-11-03). Vitest transpiles
1433
+ * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest, tsd,
1434
+ * tstyche and Vitest's typecheck mode do check types. Any sign of them anywhere in the repository,
1435
+ * including workspace packages, keeps type-only edges selecting tests. Type tests (`*.test-d.ts`) are
1436
+ * selected through every edge either way (impact.ts).
1437
+ */
1438
+ function runtimeTestSelectionEligible(repoPath: string, files: readonly string[], profile: RepositoryProfile): boolean {
1439
+ const configs = profile.testRunnerConfigs ?? [];
1440
+ if (!configs.length || configs.some((config) => config.runner !== "vitest")) return false;
1441
+ const read = (path: string) => { try { return readFileSync(join(repoPath, path), "utf8"); } catch { return undefined; } };
1442
+ for (const file of files) {
1443
+ if (file.split("/").includes("node_modules")) continue;
1444
+ const name = file.slice(file.lastIndexOf("/") + 1);
1445
+ if (/^jest\.config\./.test(name)) return false;
1446
+ if (/^vit(?:e|est)[\w.-]*\.(?:config|workspace|projects)\.[cm]?[jt]s$/.test(name)) {
1447
+ const text = read(file);
1448
+ if (text === undefined || /\btypecheck\b/.test(text)) return false;
1449
+ } else if (name === "package.json") {
1450
+ let manifest: { scripts?: Record<string, unknown>; dependencies?: object; devDependencies?: object; peerDependencies?: object; optionalDependencies?: object };
1451
+ try { manifest = JSON.parse(read(file) ?? ""); } catch { return false; }
1452
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1453
+ if (packages.some((name) => ["jest", "ts-jest", "tsd", "tstyche"].includes(name))) return false;
1454
+ if (Object.values(manifest.scripts ?? {}).some((script) => typeof script !== "string" || /(?:^|[\s&;|(])(?:jest|tsd|tstyche)(?:\s|$)|--typecheck/.test(script))) return false;
1455
+ }
1456
+ }
1457
+ return true;
1458
+ }
1459
+
1294
1460
  function computeConfidence(
1295
1461
  unresolvedCount: number,
1296
1462
  dynamicUnresolvedCount: number,
@@ -1372,13 +1538,23 @@ export function refineConfidenceForDelta(result: DependencyGraphResult, changedF
1372
1538
  if (result.unresolved.length === 0) return result.confidence;
1373
1539
 
1374
1540
  const reachableFromChanged = new Set<string>();
1541
+ const dependents = new Set<string>();
1542
+ const runtimeDependents = new Set<string>();
1543
+ const runtimeOnly = result.runtimeTestSelection === true && typeof result.graph.transitiveRuntimeDependentsOf === "function";
1375
1544
  for (const file of changedFiles) {
1376
1545
  for (const dep of result.graph.transitiveDependenciesOf(file)) reachableFromChanged.add(dep);
1377
- for (const dep of result.graph.transitiveDependentsOf(file)) reachableFromChanged.add(dep);
1546
+ for (const dep of result.graph.transitiveDependentsOf(file)) { reachableFromChanged.add(dep); dependents.add(dep); }
1547
+ if (runtimeOnly) for (const dep of result.graph.transitiveRuntimeDependentsOf!(file)) runtimeDependents.add(dep);
1378
1548
  }
1379
1549
  const changedSet = new Set(changedFiles);
1380
1550
 
1381
- const relevantUnresolved = result.unresolved.some((u) => !u.computed && (changedSet.has(u.importer) || reachableFromChanged.has(u.importer)));
1551
+ // An importer that already depends on a changed file is affected, and so is everything depending on
1552
+ // it: whatever its missing edge points at, following that edge cannot reach a test that is not already
1553
+ // selected (2026-11-03: one broken `import type` in a LobeHub test file made 35 of 40 commits UNSAFE).
1554
+ // "Already depends" means through the edges that select tests: runtime edges when type-only ones do
1555
+ // not select (runtimeTestSelection), unless the missing edge is itself type-only.
1556
+ const alreadyAffected = (u: UnresolvedDependency) => (runtimeOnly && !u.typeOnly ? runtimeDependents : dependents).has(u.importer);
1557
+ const relevantUnresolved = result.unresolved.some((u) => !u.computed && !alreadyAffected(u) && (changedSet.has(u.importer) || reachableFromChanged.has(u.importer)));
1382
1558
  if (relevantUnresolved) return "UNSAFE";
1383
1559
 
1384
1560
  // None of the unresolved imports are reachable from this delta's changed files - narrow to what
@@ -21,6 +21,8 @@ const NEXT_ENTRY_NAMES = new Set(["page","layout","route","api","loading","error
21
21
  function isLockfile(filePath: string): boolean { return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(filePath); }
22
22
  function isSourceFilePath(filePath: string): boolean { return SOURCE_EXTENSIONS.has(extname(filePath).toLowerCase()); }
23
23
  function isAssetFilePath(filePath: string): boolean { return ASSET_EXTENSIONS.has(extname(filePath).toLowerCase()); }
24
+ /** Vitest's default `typecheck.include`: tests whose outcome is the type checker's. */
25
+ const TYPE_TEST_FILE = /\.(?:test|spec)-d\.[cm]?[jt]sx?$/;
24
26
  // "Is this a test?" is answered by the profile's test patterns (src/repo/test-discovery.ts) - one shared
25
27
  // definition with analyzer discovery and graph node flags. Module-level helpers receive it explicitly.
26
28
  type IsTestFile = (filePath: string) => boolean;
@@ -252,6 +254,7 @@ export class ImpactAnalyzer {
252
254
  private repositoryFiles: ReadonlySet<string> | undefined;
253
255
  private contentCleared: ReadonlySet<string> = new Set();
254
256
  private dependencyLockfile: string | undefined;
257
+ private packageJsonSpecifiersOnly = false;
255
258
  private readRepositoryFile: ((path: string) => string | undefined) | undefined;
256
259
  private sortedRepositoryFiles: string[] = [];
257
260
  private compiledProjectCache: CompiledProject[] | undefined;
@@ -259,6 +262,16 @@ export class ImpactAnalyzer {
259
262
  private selectTestPhases = false;
260
263
  private testPhases = new Set<string>();
261
264
  private workersOutsideSuite: boolean | undefined;
265
+ private runtimeTestSelection = false;
266
+
267
+ /** Dependents whose tests a change to `path` can affect. When the graph allows runtime selection
268
+ * (DependencyGraphResult.runtimeTestSelection) an `import type` edge selects only type tests. */
269
+ private testDependents(graph: DependencyGraph, path: string, dependents: readonly string[]): ReadonlySet<string> {
270
+ if (!this.runtimeTestSelection || !graph.transitiveRuntimeDependentsOf) return new Set(dependents);
271
+ const selected = new Set(graph.transitiveRuntimeDependentsOf(path));
272
+ for (const dependent of dependents) if (TYPE_TEST_FILE.test(dependent)) selected.add(dependent);
273
+ return selected;
274
+ }
262
275
 
263
276
  /** True when nothing in the repository runs a Worker (file-references.ts, suiteMayRunWorkers); false,
264
277
  * which keeps wrangler configs global, whenever repository contents are unavailable. */
@@ -280,6 +293,7 @@ export class ImpactAnalyzer {
280
293
  this.selectTestPhases = options.selectTestPhases === true;
281
294
  this.testPhases = new Set();
282
295
  this.workersOutsideSuite = undefined;
296
+ this.runtimeTestSelection = graphResult.runtimeTestSelection === true;
283
297
  this.sortedRepositoryFiles = options.repositoryFiles ? [...options.repositoryFiles].sort() : [];
284
298
  this.compiledProjectCache = undefined;
285
299
  // One read per file per analysis, however many changed files ask who reads them.
@@ -292,6 +306,7 @@ export class ImpactAnalyzer {
292
306
  const referenceResolved = new Set(delta.analysis.referenceResolvedPaths ?? []);
293
307
  this.contentCleared = referenceResolved;
294
308
  this.dependencyLockfile = delta.analysis.dependencyLockfile;
309
+ this.packageJsonSpecifiersOnly = delta.analysis.packageJsonSpecifiersOnly === true;
295
310
  const changedImpacts: ChangedImpact[] = delta.files.map((file) => ({ file, category: classifyChangedFile(file, this.isTestFile, this.layout, options.repositoryFiles, referenceResolved), reasons: changedFileReasons(file) }));
296
311
  const evidence: ImpactEvidence[] = [];
297
312
  const riskSignals: ImpactRiskSignal[] = [];
@@ -528,6 +543,14 @@ export class ImpactAnalyzer {
528
543
  .map((ref) => packageRoot(ref.specifier)).filter((name) => !packages.includes(name)))].sort();
529
544
  if (undeclared.length) fail(`Yarn lockfile changed and repository imports undeclared dependencies (${undeclared.join(", ")}); full validation required`);
530
545
  }
546
+ if (delta.analysis.dependencyLockfile === "pnpm-lock.yaml") {
547
+ // pnpm is strict by default, but `public-hoist-pattern` and a hoisted node-linker expose
548
+ // transitive packages at the root. An undeclared import of one is not attributed to a root.
549
+ const declared = new Set([...profile.packageJson.dependencies, ...profile.packageJson.devDependencies]);
550
+ const undeclared = [...new Set(graphResult.references.filter((ref) => ref.resolution === "external-package")
551
+ .map((ref) => packageRoot(ref.specifier)).filter((name) => !declared.has(name)))].sort();
552
+ if (undeclared.length) fail(`pnpm lockfile changed and repository imports undeclared dependencies (${undeclared.join(", ")}); full validation required`);
553
+ }
531
554
  const scripts = profile.packageJson.scripts;
532
555
  const closureBodies = [...testScriptClosure(scripts)].map((name) => scripts[name] ?? "");
533
556
  for (const name of packages) {
@@ -595,6 +618,18 @@ export class ImpactAnalyzer {
595
618
  if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
596
619
  return;
597
620
  }
621
+ // A workspace package's manifest edit beyond version and metadata fields (git-diff.ts clears those)
622
+ // changes what the package installs, runs or exports, which reaches every package importing it.
623
+ // Readers that name the file are only the package's own tests, so they cannot bound it (2026-11-03).
624
+ const workspaceManifest = changedPath.endsWith("/package.json") && !changedPath.split("/").includes("node_modules")
625
+ && !this.contentCleared.has(changedPath) && changedImpact.file.changeType !== "added";
626
+ if (workspaceManifest) {
627
+ const message = `Workspace package manifest changed dependencies, scripts or resolution fields: ${changedPath}; full validation required`;
628
+ evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
629
+ riskSignals.push({ level: "critical", reason: "DEPENDENCY_MANIFEST", message, paths: [changedPath] });
630
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
631
+ return;
632
+ }
598
633
  if (category === "test-fixture") {
599
634
  // Resolved per change PATH (a rename's old path resolves independently); an unresolvable side
600
635
  // degrades to the unknown-file fallback below rather than being silently dropped.
@@ -608,7 +643,12 @@ export class ImpactAnalyzer {
608
643
  }
609
644
  }
610
645
  if (category === "unknown" || category === "test-fixture") {
611
- if (this.resolveByReference(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
646
+ // A package.json edit limited to dependency requests is covered by dependency selection, like
647
+ // the lockfile above, so finding no reader is not a gap. Tooling that loads a file naming it
648
+ // still is (2026-11-02).
649
+ const specifiersOnly = changedPath === "package.json" && this.packageJsonSpecifiersOnly;
650
+ const options = specifiersOnly ? { allowNoReaders: true, implicitReadersUnresolvable: true } : {};
651
+ if (this.resolveByReference(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence, options)) return;
612
652
  const message = `Unknown changed file: ${changedPath}`;
613
653
  evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
614
654
  riskSignals.push({ level: "critical", reason: "UNKNOWN_FILE", message, paths: [changedPath] });
@@ -759,11 +799,13 @@ export class ImpactAnalyzer {
759
799
  for (const code of resolution.code) {
760
800
  if (!affectedSources.has(code)) affectedSources.set(code, []);
761
801
  affectedSources.get(code)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${code} reads ${changedPath}`, code));
762
- for (const dependent of graph.transitiveDependentsOf(code)) {
763
- if (this.isTestFile(dependent)) this.addAffectedTest(changedPath, dependent, graph, affectedTests, "FILE_REFERENCE", evidence);
802
+ const codeDependents = graph.transitiveDependentsOf(code);
803
+ const testDependents = this.testDependents(graph, code, codeDependents);
804
+ for (const dependent of codeDependents) {
805
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) this.addAffectedTest(changedPath, dependent, graph, affectedTests, "FILE_REFERENCE", evidence);
764
806
  else if (nodeByPath(graph, dependent)?.isEntryPoint) this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "FILE_REFERENCE", changedPath, evidence);
765
807
  }
766
- for (const scriptPath of collectScriptsAmong([code, ...graph.transitiveDependentsOf(code)], this.isTestFile, this.layout)) {
808
+ for (const scriptPath of collectScriptsAmong([code, ...codeDependents], this.isTestFile, this.layout)) {
767
809
  if (!affectedScripts.has(scriptPath)) affectedScripts.set(scriptPath, []);
768
810
  affectedScripts.get(scriptPath)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${changedPath} is read by script ${scriptPath}`, scriptPath));
769
811
  }
@@ -785,11 +827,12 @@ export class ImpactAnalyzer {
785
827
  affectedAssets.get(assetPath)!.push(makeEvidence("ASSET_DEPENDENCY", assetPath, `Changed asset: ${assetPath}`));
786
828
  if (!hasNode(graph, assetPath)) return;
787
829
  const dependents = graph.transitiveDependentsOf(assetPath);
830
+ const testDependents = this.testDependents(graph, assetPath, dependents);
788
831
  for (const dependent of dependents) {
789
832
  if (nodeByPath(graph, dependent)?.isEntryPoint) {
790
833
  this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "ASSET_DEPENDENCY", assetPath, evidence);
791
834
  }
792
- if (this.isTestFile(dependent)) {
835
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) {
793
836
  this.addAffectedTest(assetPath, dependent, graph, affectedTests, "ASSET_DEPENDENCY", evidence);
794
837
  }
795
838
  if (isSourceFilePath(dependent) && !this.isTestFile(dependent)) {
@@ -832,6 +875,7 @@ export class ImpactAnalyzer {
832
875
  }
833
876
 
834
877
  const dependents = graph.transitiveDependentsOf(sourcePath);
878
+ const testDependents = this.testDependents(graph, sourcePath, dependents);
835
879
  for (const dependent of dependents) {
836
880
  if (!this.isTestFile(dependent)) {
837
881
  if (!affectedSources.has(dependent)) affectedSources.set(dependent, []);
@@ -840,7 +884,7 @@ export class ImpactAnalyzer {
840
884
  if (nodeByPath(graph, dependent)?.isEntryPoint) {
841
885
  this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "DEPENDENCY", sourcePath, evidence);
842
886
  }
843
- if (this.isTestFile(dependent)) {
887
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) {
844
888
  this.addAffectedTest(sourcePath, dependent, graph, affectedTests, "DEPENDENCY", evidence);
845
889
  }
846
890
  }
@@ -1027,7 +1071,9 @@ export class ImpactAnalyzer {
1027
1071
  if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
1028
1072
  continue;
1029
1073
  }
1030
- const runners = [importer, ...graph.transitiveDependentsOf(importer)].filter((path) => this.isTestFile(path));
1074
+ const importerDependents = graph.transitiveDependentsOf(importer);
1075
+ const testDependents = this.testDependents(graph, importer, importerDependents);
1076
+ const runners = [importer, ...importerDependents.filter((path) => testDependents.has(path))].filter((path) => this.isTestFile(path));
1031
1077
  for (const test of runners) this.addAffectedTest(importer, test, graph, affectedTests, "COMPUTED_IMPORT", evidence);
1032
1078
  evidence.push(makeEvidence("COMPUTED_IMPORT", importer, `${importer} loads a computed module specifier; the ${runners.length} test(s) that run it are selected`));
1033
1079
  }