@diffci.com/diffci 0.3.38 → 0.3.40

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 (64) hide show
  1. package/README.md +3 -3
  2. package/dist-client/src/client/agent-setup.d.ts +1 -1
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/node_modules/@diffci.com/core/README.md +15 -4
  5. package/node_modules/@diffci.com/core/dist/cache/economics-context.d.ts +4 -1
  6. package/node_modules/@diffci.com/core/dist/cache/economics-context.js +7 -3
  7. package/node_modules/@diffci.com/core/dist/cache/economics-context.js.map +1 -1
  8. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  9. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +5 -1
  10. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  11. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js +1 -1
  12. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js.map +1 -1
  13. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +4 -0
  14. package/node_modules/@diffci.com/core/dist/git/git-diff.js +20 -7
  15. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  16. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +33 -7
  17. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  18. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +8 -0
  19. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/repo/analyzer.js +16 -1
  21. package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
  22. package/node_modules/@diffci.com/core/dist/repo/export-reach.d.ts +16 -0
  23. package/node_modules/@diffci.com/core/dist/repo/export-reach.js +113 -0
  24. package/node_modules/@diffci.com/core/dist/repo/export-reach.js.map +1 -0
  25. package/node_modules/@diffci.com/core/dist/repo/file-references.js +2 -1
  26. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  27. package/node_modules/@diffci.com/core/dist/repo/graph.d.ts +5 -0
  28. package/node_modules/@diffci.com/core/dist/repo/graph.js +512 -41
  29. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +1 -1
  31. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +51 -0
  32. package/node_modules/@diffci.com/core/dist/repo/impact.js +296 -9
  33. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/lockfiles.d.ts +5 -0
  35. package/node_modules/@diffci.com/core/dist/repo/lockfiles.js +12 -0
  36. package/node_modules/@diffci.com/core/dist/repo/lockfiles.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/repo/repo-config.d.ts +5 -0
  38. package/node_modules/@diffci.com/core/dist/repo/repo-config.js +3 -1
  39. package/node_modules/@diffci.com/core/dist/repo/repo-config.js.map +1 -1
  40. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +134 -3
  41. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  42. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +35 -1
  43. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.d.ts +35 -0
  44. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.js +292 -0
  45. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.js.map +1 -0
  46. package/node_modules/@diffci.com/core/package.json +1 -1
  47. package/node_modules/@diffci.com/core/src/cache/economics-context.ts +7 -3
  48. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +5 -1
  49. package/node_modules/@diffci.com/core/src/ci-inference/evidence.ts +1 -1
  50. package/node_modules/@diffci.com/core/src/git/git-diff.ts +22 -7
  51. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +32 -7
  52. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +5 -0
  53. package/node_modules/@diffci.com/core/src/repo/analyzer.ts +15 -1
  54. package/node_modules/@diffci.com/core/src/repo/export-reach.ts +92 -0
  55. package/node_modules/@diffci.com/core/src/repo/file-references.ts +2 -1
  56. package/node_modules/@diffci.com/core/src/repo/graph.ts +439 -37
  57. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +2 -0
  58. package/node_modules/@diffci.com/core/src/repo/impact.ts +267 -9
  59. package/node_modules/@diffci.com/core/src/repo/lockfiles.ts +13 -0
  60. package/node_modules/@diffci.com/core/src/repo/repo-config.ts +8 -1
  61. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +107 -3
  62. package/node_modules/@diffci.com/core/src/repo/types.ts +32 -1
  63. package/node_modules/@diffci.com/core/src/repo/workspace-sources.ts +273 -0
  64. package/package.json +3 -3
@@ -1,15 +1,18 @@
1
1
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
2
  import { createTestFileMatcher, DEFAULT_TEST_FILE_MATCHER, testFileMatcherForProfile, type TestFileMatcher } from "./test-discovery.js";
3
3
  import { isBuiltin } from "node:module";
4
- import { dirname, extname, join, normalize, relative, resolve, sep } from "node:path";
4
+ import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
5
5
  import ts from "typescript";
6
6
  import { adapterFiles, REPOSITORY_ADAPTERS } from "./adapters/index.js";
7
7
  import { pythonAdapter } from "./adapters/python.js";
8
8
  import { analyzeRepository, type AnalyzeRepositoryOptions } from "./analyzer.js";
9
9
  import { applyVueScope, inVuePackage } from "./vue-scope.js";
10
10
  import { declaredWorkspaceRoots } from "./workspaces.js";
11
+ import { infrastructureRole } from "./file-references.js";
12
+ import { WorkspaceSources } from "./workspace-sources.js";
11
13
  import type {
12
14
  DependencyEdge,
15
+ ModuleBindings,
13
16
  DependencyEdgeKind,
14
17
  DependencyGraph,
15
18
  DependencyGraphNode,
@@ -40,6 +43,15 @@ interface ImportRef {
40
43
  /** A `vi.mock("./x")` / `jest.mock("./x")` target. Vitest counts these as dependencies of the test;
41
44
  * an unresolvable one (a virtual or aliased module) is dropped rather than made unsafe. */
42
45
  mock?: boolean;
46
+ /** Runtime names an `import` statement binds (`default` for a default import); absent means the whole
47
+ * module (namespace and side-effect imports, dynamic imports, require, mocks). */
48
+ names?: string[];
49
+ /** For `export ... from`: the names it forwards as [exported, imported] pairs, `star` for `export *`,
50
+ * or `namespace` for `export * as ns`. */
51
+ reexport?: { pairs?: [string, string][]; star?: boolean; namespace?: string };
52
+ /** A computed load outside any function body (or in an immediately invoked one): it runs when the
53
+ * module loads, so a test that merely loads the module may run it. */
54
+ atLoad?: boolean;
43
55
  }
44
56
 
45
57
  /** Test-runner calls whose literal first argument names a module the test depends on. */
@@ -128,9 +140,42 @@ function specifierParts(expression: ts.Expression, consts: ReadonlyMap<string, t
128
140
  const initializer = consts.get(expression.text);
129
141
  if (initializer) return specifierParts(initializer, consts, depth + 1);
130
142
  }
143
+ // `url.href` or `url.toString()` of a URL resolved against the importer's own location names the same file
144
+ // as a relative specifier (Paperclip, 2026-11-12: server/src/vendor/paperclip-runner/index.ts does
145
+ // `const sourceUrl = new URL("../../../../packages/paperclip-runner/src/index.ts", import.meta.url);
146
+ // await import(sourceUrl.href)`, and about 1,900 tests were selected for every change through it).
147
+ const urlTarget = ts.isPropertyAccessExpression(expression) && expression.name.text === "href" ? expression.expression
148
+ : ts.isCallExpression(expression) && expression.arguments.length === 0 && ts.isPropertyAccessExpression(expression.expression)
149
+ && expression.expression.name.text === "toString" ? expression.expression.expression : undefined;
150
+ if (urlTarget) {
151
+ const relativeParts = moduleRelativeUrlParts(urlTarget, consts, depth + 1);
152
+ if (relativeParts) return join(relativeParts);
153
+ }
131
154
  return [undefined];
132
155
  }
133
156
 
157
+ /** The specifier parts of `new URL(<parts>, import.meta.url)`, directly or through a single `const`, as a
158
+ * relative specifier ("x.ts" becomes "./x.ts"). Undefined for any other base, or a first argument that is
159
+ * absolute, has a scheme, starts with an unknown part or carries a fragment. */
160
+ function moduleRelativeUrlParts(expression: ts.Expression, consts: ReadonlyMap<string, ts.Expression>, depth: number): SpecifierParts | undefined {
161
+ if (depth > 8) return undefined;
162
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression;
163
+ if (ts.isIdentifier(expression)) {
164
+ const initializer = consts.get(expression.text);
165
+ return initializer ? moduleRelativeUrlParts(initializer, consts, depth + 1) : undefined;
166
+ }
167
+ if (!ts.isNewExpression(expression) || !ts.isIdentifier(expression.expression) || expression.expression.text !== "URL"
168
+ || expression.arguments?.length !== 2 || consts.has("URL")) return undefined;
169
+ const base = expression.arguments[1]!;
170
+ if (!(ts.isPropertyAccessExpression(base) && base.name.text === "url" && ts.isMetaProperty(base.expression)
171
+ && base.expression.keywordToken === ts.SyntaxKind.ImportKeyword)) return undefined;
172
+ const parts = specifierParts(expression.arguments[0]!, consts, depth + 1);
173
+ const head = parts[0];
174
+ if (typeof head !== "string" || head === "" || head.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(head)
175
+ || parts.some((part) => typeof part === "string" && part.includes("#"))) return undefined;
176
+ return head.startsWith("./") || head.startsWith("../") ? parts : [`./${head}`, ...parts.slice(1)];
177
+ }
178
+
134
179
  /** A folded specifier: its literal text, or the patterns bounding it. A query (`?v=...`) selects no file
135
180
  * of its own: Vite and Node strip it before resolving, so text after the first `?` is dropped. */
136
181
  function foldedSpecifier(parts: SpecifierParts): { literal: string } | { patterns: ImportRef["patterns"] } {
@@ -274,9 +319,20 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
274
319
  let shadowDepth = 0;
275
320
  let consts: Map<string, ts.Expression> | undefined;
276
321
 
322
+ // A function body runs when called, not when the module loads; an immediately invoked one runs at load.
323
+ // Program source files have no parent pointers, so a call marks the function it invokes on the way down.
324
+ let functionDepth = 0;
325
+ const invokedAtOnce = new Set<ts.Node>();
277
326
  function visit(node: ts.Node) {
278
327
  const shadows = scopeShadowsRequire(node);
279
328
  if (shadows) shadowDepth++;
329
+ if (ts.isCallExpression(node)) {
330
+ let callee: ts.Expression = node.expression;
331
+ while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
332
+ if (ts.isFunctionLike(callee)) invokedAtOnce.add(callee);
333
+ }
334
+ const body = ts.isFunctionLike(node) && !invokedAtOnce.has(node);
335
+ if (body) functionDepth++;
280
336
  if (ts.isImportDeclaration(node)) {
281
337
  const specifier = node.moduleSpecifier;
282
338
  if (ts.isStringLiteral(specifier)) {
@@ -285,7 +341,11 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
285
341
  const kind: DependencyEdgeKind = isTypeOnly ? "type-import" : "import";
286
342
  const inlineTypeOnly = !isTypeOnly && !!clause && !clause.name && !!clause.namedBindings
287
343
  && ts.isNamedImports(clause.namedBindings) && allInlineType(clause.namedBindings.elements);
288
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
344
+ const bindings = clause && !(clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
345
+ ? [...(clause.name ? ["default"] : []), ...(clause.namedBindings && ts.isNamedImports(clause.namedBindings)
346
+ ? clause.namedBindings.elements.filter((el) => !el.isTypeOnly).map((el) => (el.propertyName ?? el.name).text) : [])]
347
+ : undefined;
348
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), ...(bindings ? { names: bindings } : {}) });
289
349
  }
290
350
  } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
291
351
  const specifier = node.moduleReference.expression;
@@ -297,7 +357,11 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
297
357
  if (ts.isStringLiteral(specifier)) {
298
358
  const kind: DependencyEdgeKind = node.isTypeOnly ? "type-import" : "re-export";
299
359
  const inlineTypeOnly = !node.isTypeOnly && !!node.exportClause && ts.isNamedExports(node.exportClause) && allInlineType(node.exportClause.elements);
300
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
360
+ const clause = node.exportClause;
361
+ const reexport = !clause ? { star: true }
362
+ : ts.isNamespaceExport(clause) ? { namespace: clause.name.text }
363
+ : { pairs: clause.elements.filter((el) => !el.isTypeOnly).map((el): [string, string] => [el.name.text, (el.propertyName ?? el.name).text]) };
364
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), reexport });
301
365
  }
302
366
  } else if (ts.isCallExpression(node)) {
303
367
  const firstArg = node.arguments[0];
@@ -314,6 +378,7 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
314
378
  dynamic: isImport || !syntaxLiteral,
315
379
  computed: !literal,
316
380
  ...(patterns ? { patterns } : {}),
381
+ ...(!literal && functionDepth === 0 ? { atLoad: true } : {}),
317
382
  });
318
383
  } else if (firstArg && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
319
384
  && MOCK_MODULE_CALLS.has(`${node.expression.expression.text}.${node.expression.name.text}`)
@@ -330,11 +395,13 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
330
395
  dynamic: true,
331
396
  computed: true,
332
397
  ...(patterns.length && patterns.every(Boolean) ? { patterns: patterns as NonNullable<ImportRef["patterns"]> } : {}),
398
+ ...(functionDepth === 0 ? { atLoad: true } : {}),
333
399
  });
334
400
  }
335
401
  }
336
402
 
337
403
  ts.forEachChild(node, visit);
404
+ if (body) functionDepth--;
338
405
  if (shadows) shadowDepth--;
339
406
  }
340
407
 
@@ -342,6 +409,103 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
342
409
  return refs;
343
410
  }
344
411
 
412
+ /**
413
+ * Whether the nearest package.json at or above `path` (inside the repository) declares its JavaScript free of
414
+ * side effects: `"sideEffects": false`, or a list naming only stylesheets. This is the contract bundlers
415
+ * rely on to drop unused re-exports; without it a module's evaluation may matter, so imports stay whole.
416
+ */
417
+ function sideEffectFreePackage(repoPath: string, path: string, cache: Map<string, boolean | undefined>): boolean {
418
+ let dir = dirname(path);
419
+ while (true) {
420
+ let declared = cache.get(dir);
421
+ if (!cache.has(dir)) {
422
+ declared = undefined;
423
+ try {
424
+ const pkg = JSON.parse(readFileSync(join(repoPath, dir, "package.json"), "utf8")) as { sideEffects?: unknown };
425
+ const se = pkg.sideEffects;
426
+ declared = se === false || (Array.isArray(se) && se.length > 0 && se.every((glob) => typeof glob === "string" && /\.(s?css|sass|less|styl)$/.test(glob)));
427
+ } catch (error) {
428
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") declared = false;
429
+ }
430
+ cache.set(dir, declared);
431
+ }
432
+ if (declared !== undefined) return declared;
433
+ if (dir === "." || dir === "" || dirname(dir) === dir) return false;
434
+ dir = dirname(dir);
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Runtime names a module defines itself, for export-level selection. `opaque` when they cannot be listed
440
+ * (CommonJS `module.exports`/`exports.x`, `export =`, destructured `export const { a } = ...`): an import of
441
+ * such a module always counts as the whole module.
442
+ */
443
+ function exportedLocals(sourceFile: ts.SourceFile): { locals: string[]; opaque: boolean } {
444
+ const locals = new Set<string>();
445
+ let opaque = false;
446
+ const has = (node: ts.Node, kind: ts.SyntaxKind) => ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === kind);
447
+ for (const st of sourceFile.statements) {
448
+ if (ts.isExportDeclaration(st)) {
449
+ if (!st.moduleSpecifier && !st.isTypeOnly && st.exportClause && ts.isNamedExports(st.exportClause)) {
450
+ for (const el of st.exportClause.elements) if (!el.isTypeOnly) locals.add(el.name.text);
451
+ }
452
+ } else if (ts.isExportAssignment(st)) {
453
+ locals.add("default");
454
+ if (st.isExportEquals) opaque = true;
455
+ } else if (has(st, ts.SyntaxKind.ExportKeyword)) {
456
+ if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st)) continue;
457
+ if (has(st, ts.SyntaxKind.DefaultKeyword)) locals.add("default");
458
+ else if (ts.isVariableStatement(st)) {
459
+ for (const d of st.declarationList.declarations) {
460
+ if (ts.isIdentifier(d.name)) locals.add(d.name.text);
461
+ else opaque = true;
462
+ }
463
+ } else if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isEnumDeclaration(st) || ts.isModuleDeclaration(st)) && st.name && ts.isIdentifier(st.name)) {
464
+ locals.add(st.name.text);
465
+ } else opaque = true;
466
+ }
467
+ }
468
+ const visit = (node: ts.Node): void => {
469
+ if (opaque) return;
470
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)
471
+ && (node.expression.text === "exports" || (node.expression.text === "module" && node.name.text === "exports"))) opaque = true;
472
+ else ts.forEachChild(node, visit);
473
+ };
474
+ visit(sourceFile);
475
+ return { locals: [...locals].sort(), opaque };
476
+ }
477
+
478
+ /** A string that reads as a relative path to a code file: `./x`, `../x`, or a relative path ending in a code
479
+ * extension (`config.ts`, `jobs/handler.js`). */
480
+ const PATH_LITERAL = /^(?:\.{1,2}\/[^\s:*?"<>|]+|(?:[\w@.-]+\/)*[\w@.-]+\.[cm]?[jt]sx?)$/;
481
+
482
+ /**
483
+ * Strings that name a code file by path, outside import and require specifiers, which already are edges
484
+ * (2026-11-10). payloadcms/payload's integration tests pass `{ config: './config.ts' }` to a helper that
485
+ * `import()`s it; the string is the only trace of that dependency. Type positions are skipped.
486
+ */
487
+ function extractPathLiterals(sourceFile: ts.SourceFile): string[] {
488
+ const found = new Set<string>();
489
+ const specifiers = new Set<ts.Node>();
490
+ const visit = (node: ts.Node): void => {
491
+ if (ts.isTypeNode(node)) return;
492
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) specifiers.add(node.moduleSpecifier);
493
+ if (ts.isExternalModuleReference(node)) specifiers.add(node.expression);
494
+ if (ts.isCallExpression(node) && node.arguments[0]) {
495
+ const e = node.expression;
496
+ const loads = e.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(e) && e.text === "require")
497
+ || (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression) && MOCK_MODULE_CALLS.has(`${e.expression.text}.${e.name.text}`));
498
+ if (loads) specifiers.add(node.arguments[0]);
499
+ }
500
+ if ((ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) && !specifiers.has(node) && node.text.length < 300 && PATH_LITERAL.test(node.text)) {
501
+ found.add(node.text);
502
+ }
503
+ ts.forEachChild(node, visit);
504
+ };
505
+ visit(sourceFile);
506
+ return [...found];
507
+ }
508
+
345
509
  class DependencyGraphImpl implements DependencyGraph {
346
510
  readonly nodes: DependencyGraphNode[];
347
511
  readonly edges: DependencyEdge[];
@@ -870,10 +1034,13 @@ export async function buildDependencyGraph(
870
1034
  markPhase("adapterInventory");
871
1035
  const context = { repoPath, files, profile, vueAnalysisSession: {} };
872
1036
  const cachedVue = options.vueAnalysisCache ? (await import("../cache/vue-analysis-cache.js")).analyzeVueCached : undefined;
873
- const contributions = REPOSITORY_ADAPTERS.filter((adapter) => adapter.detect(context)).map((adapter) => adapter.id === "vue" && cachedVue && options.vueAnalysisCache
1037
+ const adapterResults = REPOSITORY_ADAPTERS.filter((adapter) => adapter.detect(context)).map((adapter) => adapter.id === "vue" && cachedVue && options.vueAnalysisCache
874
1038
  ? cachedVue(context, options.vueAnalysisCache.directory, options.vueAnalysisCache.version) : adapter.analyze(context));
875
1039
  markPhase("adapters");
876
- const adapterBlockers = [...scopeBlockers, ...contributions.flatMap((item) => item.blockers)];
1040
+ // An adapter that only confines blockers to directories models nothing, so it is not an active adapter:
1041
+ // it neither marks the repository as mixed-language nor adds that adapter's per-change checks.
1042
+ const contributions = adapterResults.filter((item) => !item.confinedOnly);
1043
+ const adapterBlockers = [...scopeBlockers, ...adapterResults.flatMap((item) => item.blockers)];
877
1044
  // The directories each narrowable blocker is confined to ("" when one of its files is not confined).
878
1045
  // Outside a declared Vue suite, a blocker confined to directories only is scoped to them below.
879
1046
  const blockerScopes = new Map<string, Set<string>>();
@@ -886,7 +1053,25 @@ export async function buildDependencyGraph(
886
1053
  const packageDirectories = new Map<string, string>();
887
1054
  const packageScope = (path: string) => nearestPackageDirectory(repoPath, path, packageDirectories);
888
1055
  const workspaceRoots = new Set(declaredWorkspaceRoots(repoPath));
1056
+ const workspaceSources = new WorkspaceSources(repoPath, workspaceRoots);
1057
+ // The package manager links workspace packages only into workspace members (and the root project).
1058
+ const inWorkspace = (rel: string) => { const directory = packageScope(rel); return directory === "" || workspaceRoots.has(directory); };
1059
+ let realRepoRoot: string | undefined;
1060
+ const physicalRelative = (file: string): string | undefined => {
1061
+ try {
1062
+ realRepoRoot ??= realpathSync.native(repoPath);
1063
+ const rel = relative(realRepoRoot, realpathSync.native(file)).replace(/\\/g, "/");
1064
+ return rel && !rel.startsWith("../") && rel !== ".." && !isAbsolute(rel) ? rel : undefined;
1065
+ } catch { return undefined; }
1066
+ };
889
1067
  for (const item of contributions) for (const { path, reason } of [...(item.fileBlockers ?? []), ...(item.subjectBlockers ?? [])]) addScope(reason, packageScope(path));
1068
+ for (const item of adapterResults) {
1069
+ for (const { directory, reason } of item.directoryBlockers ?? []) {
1070
+ if (!adapterBlockers.includes(reason)) adapterBlockers.push(reason);
1071
+ // Inside a declared Vue suite nothing is scoped, so the blocker stays global (fails closed).
1072
+ addScope(reason, directory);
1073
+ }
1074
+ }
890
1075
  if (profile.diffciConfig?.configurationError && !adapterBlockers.includes(profile.diffciConfig.configurationError)) adapterBlockers.push(profile.diffciConfig.configurationError);
891
1076
  if (contributions.some((item) => item.id === "go") && files.some((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file))) {
892
1077
  adapterBlockers.push("Mixed Go/JavaScript repositories require explicit cross-language dependencies; full validation required");
@@ -961,8 +1146,31 @@ export async function buildDependencyGraph(
961
1146
  const assetPaths = new Set<string>(contributions.flatMap((item) => item.assetPaths));
962
1147
  for (const item of contributions) for (const path of item.sourcePaths) internalSourcePaths.add(path);
963
1148
  const edgeKeys = new Set<string>(edges.map((edge) => `${edge.from}|${edge.to}|${edge.kind}`));
1149
+ const bindings: Record<string, ModuleBindings> = {};
1150
+ const bindingsOf = (path: string): ModuleBindings => (bindings[path] ??= { locals: [], imports: {}, reexports: {} });
1151
+
1152
+ /** Records what a runtime edge binds; an edge without a parsed statement binds the whole module. */
1153
+ function recordBinding(from: string, to: string, kind: DependencyEdgeKind, ref?: ImportRef): void {
1154
+ if (kind === "asset") return;
1155
+ const b = bindingsOf(from);
1156
+ if (kind === "type-import") {
1157
+ if (!(b.typeImports ??= []).includes(to)) b.typeImports.push(to);
1158
+ return;
1159
+ }
1160
+ if (ref?.reexport) {
1161
+ const r = (b.reexports[to] ??= { pairs: [], star: false, namespaces: [] });
1162
+ if (ref.reexport.star) r.star = true;
1163
+ if (ref.reexport.namespace) r.namespaces.push(ref.reexport.namespace);
1164
+ for (const pair of ref.reexport.pairs ?? []) r.pairs.push(pair);
1165
+ return;
1166
+ }
1167
+ const current = b.imports[to];
1168
+ if (!ref?.names || current === "*") b.imports[to] = "*";
1169
+ else b.imports[to] = [...new Set([...(current ?? []), ...ref.names])];
1170
+ }
964
1171
 
965
- function addEdge(from: string, to: string, kind: DependencyEdgeKind): void {
1172
+ function addEdge(from: string, to: string, kind: DependencyEdgeKind, ref?: ImportRef): void {
1173
+ recordBinding(from, to, kind, ref);
966
1174
  const key = `${from}|${to}|${kind}`;
967
1175
  if (edgeKeys.has(key)) return;
968
1176
  edgeKeys.add(key);
@@ -1134,6 +1342,37 @@ export async function buildDependencyGraph(
1134
1342
  return compilerOptions;
1135
1343
  }
1136
1344
 
1345
+ /** The existing code file a path string names, relative to the file holding it. */
1346
+ function pathLiteralTarget(importerRel: string, literal: string): string | undefined {
1347
+ const base = posix.normalize(posix.join(posix.dirname(importerRel), literal));
1348
+ if (base.startsWith("../") || base === "..") return undefined;
1349
+ const stem = base.replace(/\.[cm]?jsx?$/, "");
1350
+ const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"].map((ext) => stem + ext), ...["index.ts", "index.tsx", "index.js"].map((name) => `${base}/${name}`)];
1351
+ for (const candidate of candidates) {
1352
+ if (!isSourceFileName(candidate) || candidate.endsWith(".d.ts") || isExcludedPath(candidate, options.excludeDirs ?? [])) continue;
1353
+ if (internalSourcePaths.has(candidate) || existsSync(join(repoPath, candidate))) return candidate;
1354
+ }
1355
+ return undefined;
1356
+ }
1357
+
1358
+ /** Parses an implementation file an import reaches outside the initial walk, rather than silently dropping
1359
+ * the edge or loading every TypeScript declaration library again; false, with a blocker, past the budget. */
1360
+ function followImplementation(absolute: string, rel: string): boolean {
1361
+ if (internalSourcePaths.has(rel)) return true;
1362
+ try {
1363
+ if (isExcludedPath(rel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(absolute).size > 5 * 1024 * 1024) throw new Error("excluded or exceeds parse budget");
1364
+ const followed = ts.createSourceFile(absolute, readFileSync(absolute, "utf8"), ts.ScriptTarget.Latest, true);
1365
+ if ((followed as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics?.length) throw new Error("invalid implementation syntax");
1366
+ sourceFiles.push(followed);
1367
+ followedImplementationFiles++;
1368
+ } catch {
1369
+ adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${rel}`);
1370
+ return false;
1371
+ }
1372
+ internalSourcePaths.add(rel);
1373
+ return true;
1374
+ }
1375
+
1137
1376
  for (const sf of sourceFiles) {
1138
1377
  const importerRel = toRelativeInternal(repoPath, sf.fileName);
1139
1378
  if (!importerRel || !isSourceFileName(sf.fileName)) continue;
@@ -1143,15 +1382,29 @@ export async function buildDependencyGraph(
1143
1382
 
1144
1383
  const keepsTypeImports = keepsTypeOnlyImports(importerOptions);
1145
1384
  const refs = extractImportRefs(sf).map((ref) => ref.inlineTypeOnly && !keepsTypeImports ? { ...ref, kind: "type-import" as const } : ref);
1385
+ const { locals, opaque } = exportedLocals(sf);
1386
+ const own = bindingsOf(importerRel);
1387
+ own.locals = locals;
1388
+ if (opaque) own.opaque = true;
1389
+ for (const literal of extractPathLiterals(sf)) {
1390
+ const target = pathLiteralTarget(importerRel, literal);
1391
+ if (!target || target === importerRel) continue;
1392
+ // Infrastructure code outside the graph (ops/, a Worker entry) is resolved through the tests that read
1393
+ // it, and stays global when a deployment definition runs it (ImpactAnalyzer, INFRASTRUCTURE_GLOBAL); a
1394
+ // string naming it must not pull it into the graph and around that rule.
1395
+ if (!internalSourcePaths.has(target) && infrastructureRole(target) === "code") continue;
1396
+ if (followImplementation(join(repoPath, target), target)) addEdge(importerRel, target, "path-literal");
1397
+ }
1146
1398
  if (scope && sf.referencedFiles.length) adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
1147
1399
  for (const ref of refs) {
1148
1400
  // Expression text is not a module name. In particular, import(name) must
1149
1401
  // not be classified as an external package called "name".
1402
+ if (ref.computed && ref.atLoad) bindingsOf(importerRel).computedAtLoad = true;
1150
1403
  if (ref.computed && ref.patterns) {
1151
1404
  const targets = resolvePatternTargets(sf.fileName, ref.patterns, importerOptions);
1152
1405
  if (targets) {
1153
1406
  for (const target of targets) {
1154
- if (internalSourcePaths.has(target)) addEdge(importerRel, target, ref.kind);
1407
+ if (internalSourcePaths.has(target)) addEdge(importerRel, target, ref.kind, ref);
1155
1408
  else recordAssetEdge(importerRel, target);
1156
1409
  }
1157
1410
  recordReference(targets.some((target) => internalSourcePaths.has(target)) ? "internal-source" : "internal-asset", importerRel, ref);
@@ -1176,13 +1429,26 @@ export async function buildDependencyGraph(
1176
1429
 
1177
1430
  const specifierCategory = classifySpecifier(ref.specifier);
1178
1431
  const resolvableSpecifier = specifierCategory === "relative" || specifierCategory === "absolute" || specifierCategory === "alias" ? stripImportQuery(ref.specifier) : ref.specifier;
1432
+ // A relative path into an installed package (`../../ui/node_modules/vite/dist/node/index.js`) is a
1433
+ // dependency import spelled as a path. A clean checkout has no such file, and an installed one resolves
1434
+ // it into node_modules, which is outside the source inventory, so it was "unresolved" and every change
1435
+ // reaching the importer fell back (Paperclip, 2026-11-11: 7 of its 14 unresolved imports). Record it
1436
+ // under the package's own specifier so dependency changes still find the importer. A workspace package
1437
+ // linked into node_modules is repository source and keeps the normal handling.
1438
+ if (specifierCategory === "relative") {
1439
+ const installed = installedPackageSpecifier(importerRel, resolvableSpecifier);
1440
+ if (installed && !workspaceSources.packageFor(installed)) {
1441
+ recordReference("external-package", importerRel, { ...ref, specifier: installed });
1442
+ continue;
1443
+ }
1444
+ }
1179
1445
  // TypeScript may resolve a Vue import to a declaration shim. Preserve the actual SFC edge.
1180
1446
  if (resolvableSpecifier.endsWith(".vue")) {
1181
1447
  const compilerAliases = Object.entries(importerOptions.paths ?? {}).map(([pattern, substitutions]) => ({ pattern, substitutions }));
1182
1448
  const candidate = findAssetCandidate(sf.fileName, resolvableSpecifier, compilerAliases.length ? compilerAliases : profile.pathAliases, importerOptions.baseUrl ?? dirname(sf.fileName));
1183
1449
  const target = candidate && toRelativeInternal(repoPath, candidate);
1184
1450
  if (target && internalSourcePaths.has(target)) {
1185
- addEdge(importerRel, target, ref.kind);
1451
+ addEdge(importerRel, target, ref.kind, ref);
1186
1452
  recordReference("internal-source", importerRel, ref);
1187
1453
  continue;
1188
1454
  }
@@ -1198,6 +1464,39 @@ export async function buildDependencyGraph(
1198
1464
  moduleResolutionCache,
1199
1465
  );
1200
1466
 
1467
+ // A workspace package's build output is not its source (2026-11-09, Sentry: `@sentry/server-utils`
1468
+ // resolves to nothing before a build and to build/types/index.d.ts after one). Map the import to the
1469
+ // package's source file, or leave it external so the workspace guard falls back.
1470
+ const workspaceImport = !scope && specifierCategory === "package" && workspaceSources.size && inWorkspace(importerRel)
1471
+ ? workspaceSources.packageFor(resolvableSpecifier)
1472
+ : undefined;
1473
+ if (workspaceImport) {
1474
+ const { pkg, subpath } = workspaceImport;
1475
+ const resolvedFile = resolution.resolvedModule?.resolvedFileName;
1476
+ // Through real paths: a workspace link, or a repository path spelled differently (a Windows 8.3
1477
+ // short name), must still land inside the package.
1478
+ const resolvedRel = resolvedFile ? physicalRelative(resolvedFile) : undefined;
1479
+ const insidePackage = resolvedRel !== undefined && resolvedRel.startsWith(`${pkg.root}/`);
1480
+ if (!resolvedFile || (insidePackage && (/\.d\.[mc]?ts$/.test(resolvedRel!) || !internalSourcePaths.has(resolvedRel!)))) {
1481
+ const source = (insidePackage ? workspaceSources.sourceForFile(pkg, resolvedRel!) : undefined) ?? workspaceSources.sourceForSubpath(pkg, subpath);
1482
+ const asset = source ? undefined : workspaceSources.assetForSubpath(pkg, subpath);
1483
+ if (asset) {
1484
+ recordAssetEdge(importerRel, asset);
1485
+ recordReference("internal-asset", importerRel, ref);
1486
+ continue;
1487
+ }
1488
+ // The package's source may sit outside the tsconfig inventory (payloadcms/payload's solution tsconfig
1489
+ // references only some packages): parse it like any other followed implementation.
1490
+ if (source && (internalSourcePaths.has(source) || (!/\.d\.[mc]?ts$/.test(source) && followImplementation(join(repoPath, source), source)))) {
1491
+ addEdge(importerRel, source, ref.kind, ref);
1492
+ recordReference("internal-source", importerRel, ref);
1493
+ } else {
1494
+ recordReference("external-package", importerRel, ref);
1495
+ }
1496
+ continue;
1497
+ }
1498
+ }
1499
+
1201
1500
  if (!resolution.resolvedModule || !resolution.resolvedModule.resolvedFileName) {
1202
1501
  const category = classifySpecifier(ref.specifier);
1203
1502
  if (category === "relative" || category === "absolute" || category === "alias") {
@@ -1215,6 +1514,19 @@ export async function buildDependencyGraph(
1215
1514
  continue;
1216
1515
  }
1217
1516
  }
1517
+ // Build output a fresh checkout does not have, inside a workspace package whose tsconfig maps it back:
1518
+ // payloadcms/payload's packages/payload/bin.js does `import('./dist/cli/index.js')`, compiled from
1519
+ // src/cli/index.ts. The import depends on that source, so follow it rather than leave it unresolved.
1520
+ if (category === "relative") {
1521
+ const built = posix.normalize(posix.join(posix.dirname(importerRel), resolvableSpecifier));
1522
+ const pkg = workspaceSources.packageContaining(built);
1523
+ const source = pkg ? workspaceSources.sourceForFile(pkg, built) : undefined;
1524
+ if (source && source !== built && followImplementation(join(repoPath, source), source)) {
1525
+ addEdge(importerRel, source, ref.kind, ref);
1526
+ recordReference("internal-source", importerRel, ref);
1527
+ continue;
1528
+ }
1529
+ }
1218
1530
  recordUnresolved(importerRel, ref, "unresolved internal module");
1219
1531
  recordReference("unresolved", importerRel, ref);
1220
1532
  } else {
@@ -1238,23 +1550,9 @@ export async function buildDependencyGraph(
1238
1550
  }
1239
1551
 
1240
1552
  if (targetRel && isSourceFileName(resolved)) {
1241
- if (!resolved.endsWith(".d.ts") && !internalSourcePaths.has(targetRel)) {
1242
- // A real import can reach generated implementation excluded from the
1243
- // initial walk. Parse it (and its imports) rather than silently dropping
1244
- // the edge or loading every TypeScript declaration library again.
1245
- try {
1246
- if (isExcludedPath(targetRel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(resolved).size > 5 * 1024 * 1024) throw new Error("excluded or exceeds parse budget");
1247
- const followed = ts.createSourceFile(resolved, readFileSync(resolved, "utf8"), ts.ScriptTarget.Latest, true);
1248
- if ((followed as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics?.length) throw new Error("invalid implementation syntax");
1249
- sourceFiles.push(followed);
1250
- followedImplementationFiles++;
1251
- } catch {
1252
- adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${targetRel}`);
1253
- continue;
1254
- }
1255
- }
1553
+ if (!resolved.endsWith(".d.ts") && !followImplementation(resolved, targetRel)) continue;
1256
1554
  internalSourcePaths.add(targetRel);
1257
- addEdge(importerRel, targetRel, ref.kind);
1555
+ addEdge(importerRel, targetRel, ref.kind, ref);
1258
1556
  recordReference("internal-source", importerRel, ref);
1259
1557
  continue;
1260
1558
  }
@@ -1323,7 +1621,27 @@ export async function buildDependencyGraph(
1323
1621
  if (scope && unresolved.length) adapterBlockers.push("Unresolved dependencies in the declared Vue suite require full validation");
1324
1622
  if (scope && edges.some(edge => outsideScope(edge.from) || outsideScope(edge.to))) adapterBlockers.push("Vue asset or macro dependency crosses the declared package boundary");
1325
1623
  const scopedAdapterBlockers = scopeAdapterBlockers(adapterBlockers, blockerScopes);
1326
- scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots));
1624
+ // A type-only import of a subpath the package neither exports nor contains resolves nowhere, installed or not
1625
+ // (payloadcms/payload's stale `import type { ... } from 'payload/types'`): it hides no edge a change can reach.
1626
+ const namesNothing = (ref: ResolutionReference) => {
1627
+ if (ref.kind !== "type-import") return false;
1628
+ const target = workspaceSources.packageFor(stripImportQuery(ref.specifier));
1629
+ return target !== undefined && !workspaceSources.names(target.pkg, target.subpath);
1630
+ };
1631
+ // A file only path strings point at (payloadcms/payload's codemod fixtures `basic.input.ts`, read as text
1632
+ // and full of deliberately stale imports) may never run. Its unmapped workspace imports are unresolved
1633
+ // imports of that file, which matter to a change that reaches it (refineConfidenceForDelta), rather than a
1634
+ // blocker on every change that reaches the imported package.
1635
+ const testFiles = new Set(profile.testFilePaths);
1636
+ const incomingKinds = new Map<string, Set<DependencyEdgeKind>>();
1637
+ for (const edge of edges) (incomingKinds.get(edge.to) ?? incomingKinds.set(edge.to, new Set()).get(edge.to)!).add(edge.kind);
1638
+ const pathLiteralOnly = new Set([...incomingKinds].filter(([file, kinds]) => !testFiles.has(file) && kinds.has("path-literal") && [...kinds].every((kind) => kind === "path-literal")).map(([file]) => file));
1639
+ const workspaceRefs = references.filter((ref) => inWorkspace(ref.importer) && !namesNothing(ref));
1640
+ for (const ref of workspaceRefs) {
1641
+ if (!pathLiteralOnly.has(ref.importer) || ref.resolution !== "external-package" || !workspaceSources.packageFor(stripImportQuery(ref.specifier))) continue;
1642
+ unresolved.push({ importer: ref.importer, specifier: ref.specifier, reason: "workspace import not mapped to source, in a file only path strings name", dynamic: ref.dynamic, typeOnly: ref.kind === "type-import" });
1643
+ }
1644
+ scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, workspaceRefs.filter((ref) => !pathLiteralOnly.has(ref.importer)), workspaceRoots));
1327
1645
  profile.adapterBlockers = [...adapterBlockers];
1328
1646
  markPhase("importExtractionAndResolution");
1329
1647
 
@@ -1408,8 +1726,12 @@ export async function buildDependencyGraph(
1408
1726
  filesParsed: filesParsed,
1409
1727
  };
1410
1728
 
1729
+ const sideEffectsByDir = new Map<string, boolean | undefined>();
1730
+ for (const [path, b] of Object.entries(bindings)) if (sideEffectFreePackage(repoPath, path, sideEffectsByDir)) b.sideEffectFree = true;
1731
+
1411
1732
  return {
1412
1733
  graph,
1734
+ bindings,
1413
1735
  adapterBlockers,
1414
1736
  ...(scopedAdapterBlockers.length ? { scopedAdapterBlockers, confidenceWithoutScopedBlockers } : {}),
1415
1737
  profile,
@@ -1424,6 +1746,7 @@ export async function buildDependencyGraph(
1424
1746
  integrity,
1425
1747
  resolvedViaProjectReferences,
1426
1748
  runtimeTestSelection: runtimeTestSelectionEligible(repoPath, files, profile),
1749
+ typeTestGlobs: typeTestGlobs(repoPath, files),
1427
1750
  };
1428
1751
  }
1429
1752
 
@@ -1595,10 +1918,10 @@ export function validateDependencyGraph(graph: DependencyGraph): GraphIntegrityR
1595
1918
 
1596
1919
  /**
1597
1920
  * Whether an `import type` edge can be ignored when selecting tests (2026-11-03). Vitest transpiles
1598
- * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest, tsd,
1599
- * tstyche and Vitest's typecheck mode do check types. Any sign of them anywhere in the repository,
1600
- * including workspace packages, keeps type-only edges selecting tests. Type tests (`*.test-d.ts`) are
1601
- * selected through every edge either way (impact.ts).
1921
+ * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest and Vitest's
1922
+ * typecheck mode check every test's types. Vitest typecheck mode anywhere, or Jest at the repository root,
1923
+ * keeps type-only edges selecting every test. Jest in a sub-package, tsd and tstyche check only their own
1924
+ * files (typeTestGlobs), and those tests are selected through every edge either way (impact.ts).
1602
1925
  */
1603
1926
  function runtimeTestSelectionEligible(repoPath: string, files: readonly string[], profile: RepositoryProfile): boolean {
1604
1927
  const configs = profile.testRunnerConfigs ?? [];
@@ -1607,7 +1930,9 @@ function runtimeTestSelectionEligible(repoPath: string, files: readonly string[]
1607
1930
  for (const file of files) {
1608
1931
  if (file.split("/").includes("node_modules")) continue;
1609
1932
  const name = file.slice(file.lastIndexOf("/") + 1);
1610
- if (/^jest\.config\./.test(name)) return false;
1933
+ // Jest inside a sub-package governs that package's tests only (typeCheckedPackageDirs, typeTestGlobs).
1934
+ const atRoot = !file.includes("/");
1935
+ if (/^jest\.config\./.test(name)) { if (atRoot) return false; continue; }
1611
1936
  if (/^vit(?:e|est)[\w.-]*\.(?:config|workspace|projects)\.[cm]?[jt]s$/.test(name)) {
1612
1937
  const text = read(file);
1613
1938
  if (text === undefined || /\btypecheck\b/.test(text)) return false;
@@ -1615,13 +1940,73 @@ function runtimeTestSelectionEligible(repoPath: string, files: readonly string[]
1615
1940
  let manifest: { scripts?: Record<string, unknown>; dependencies?: object; devDependencies?: object; peerDependencies?: object; optionalDependencies?: object };
1616
1941
  try { manifest = JSON.parse(read(file) ?? ""); } catch { return false; }
1617
1942
  const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1618
- if (packages.some((name) => ["jest", "ts-jest", "tsd", "tstyche"].includes(name))) return false;
1619
- if (Object.values(manifest.scripts ?? {}).some((script) => typeof script !== "string" || /(?:^|[\s&;|(])(?:jest|tsd|tstyche)(?:\s|$)|--typecheck/.test(script))) return false;
1943
+ // tsd and tstyche check types only in their own test files (typeTestGlobs), which keep type edges;
1944
+ // Jest (ts-jest) and `--typecheck` type-check every test they run (2026-11-10: tstyche alone turned
1945
+ // off runtime selection for all of payloadcms/payload's Vitest tests).
1946
+ const scripts = Object.values(manifest.scripts ?? {});
1947
+ if (scripts.some((script) => typeof script !== "string" || /--typecheck/.test(script))) return false;
1948
+ if (atRoot && (packages.some((name) => ["jest", "ts-jest"].includes(name)) || scripts.some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script))))) return false;
1620
1949
  }
1621
1950
  }
1622
1951
  return true;
1623
1952
  }
1624
1953
 
1954
+ /** The files tstyche or tsd check, when either is installed: tstyche.json's `testFileMatch` or tstyche's
1955
+ * defaults, and tsd's `*.test-d.ts`. */
1956
+ function typeTestGlobs(repoPath: string, files: readonly string[]): string[] {
1957
+ const read = (path: string) => { try { return readFileSync(join(repoPath, path), "utf8"); } catch { return undefined; } };
1958
+ let tstyche = false, tsd = false;
1959
+ for (const file of files) {
1960
+ if (file.split("/").includes("node_modules") || !file.endsWith("package.json")) continue;
1961
+ let manifest: { scripts?: Record<string, unknown>; dependencies?: object; devDependencies?: object; peerDependencies?: object; optionalDependencies?: object };
1962
+ try { manifest = JSON.parse(read(file) ?? ""); } catch { continue; }
1963
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1964
+ const scripts = Object.values(manifest.scripts ?? {}).filter((script): script is string => typeof script === "string");
1965
+ if (packages.includes("tstyche") || scripts.some((script) => /(?:^|[\s&;|(])tstyche(?:\s|$)/.test(script))) tstyche = true;
1966
+ if (packages.includes("tsd") || scripts.some((script) => /(?:^|[\s&;|(])tsd(?:\s|$)/.test(script))) tsd = true;
1967
+ }
1968
+ const globs: string[] = [];
1969
+ if (tstyche) {
1970
+ let match: unknown;
1971
+ for (const name of ["tstyche.config.json", "tstyche.json"]) {
1972
+ const text = read(name);
1973
+ if (text === undefined) continue;
1974
+ const parsed = ts.parseConfigFileTextToJson(name, text);
1975
+ match = (parsed.config as { testFileMatch?: unknown } | undefined)?.testFileMatch;
1976
+ break;
1977
+ }
1978
+ globs.push(...(Array.isArray(match) && match.every((glob) => typeof glob === "string") ? match as string[]
1979
+ : ["**/*.tst.*", "**/__typetests__/*.test.*", "**/typetests/*.test.*"]));
1980
+ }
1981
+ if (tsd) globs.push("**/*.test-d.ts", "**/*.test-d.tsx");
1982
+ for (const dir of typeCheckedPackageDirs(repoPath, files)) globs.push(`${dir}/**`);
1983
+ return globs;
1984
+ }
1985
+
1986
+ /**
1987
+ * Sub-package directories whose own tests Jest (or ts-jest) may type-check as they run: a jest.config there, or
1988
+ * a package.json depending on jest/ts-jest or running `jest`. 2026-11-10: payloadcms/payload's
1989
+ * `.github/actions/triage` (a GitHub Action with its own Jest setup) and `packages/payload-cloud` (a `jest`
1990
+ * test script) had turned off runtime selection for the whole Vitest suite. A repository-root signal still
1991
+ * turns it off everywhere (runtimeTestSelectionEligible).
1992
+ */
1993
+ function typeCheckedPackageDirs(repoPath: string, files: readonly string[]): string[] {
1994
+ const dirs = new Set<string>();
1995
+ for (const file of files) {
1996
+ if (file.split("/").includes("node_modules") || !file.includes("/")) continue;
1997
+ const name = file.slice(file.lastIndexOf("/") + 1);
1998
+ const dir = file.slice(0, file.lastIndexOf("/"));
1999
+ if (/^jest\.config\./.test(name)) dirs.add(dir);
2000
+ else if (name === "package.json") {
2001
+ let manifest: { scripts?: Record<string, unknown>; dependencies?: object; devDependencies?: object; peerDependencies?: object; optionalDependencies?: object };
2002
+ try { manifest = JSON.parse(readFileSync(join(repoPath, file), "utf8")); } catch { dirs.add(dir); continue; }
2003
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
2004
+ if (packages.some((pkg) => pkg === "jest" || pkg === "ts-jest") || Object.values(manifest.scripts ?? {}).some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script)))) dirs.add(dir);
2005
+ }
2006
+ }
2007
+ return [...dirs].sort();
2008
+ }
2009
+
1625
2010
  function computeConfidence(
1626
2011
  unresolvedCount: number,
1627
2012
  dynamicUnresolvedCount: number,
@@ -1756,6 +2141,22 @@ function refineUnscopedConfidence(result: DependencyGraphResult, changedFiles: s
1756
2141
  return result.resolvedViaProjectReferences ? "PARTIAL" : "COMPLETE";
1757
2142
  }
1758
2143
 
2144
+ /** The package specifier a relative import into a node_modules directory inside the repository names
2145
+ * (`vite/dist/node/index.js`, `@scope/pkg/dist/x.js`), or undefined when the path does not pass through
2146
+ * node_modules, leaves the repository, or names no package. The last node_modules segment wins, as Node's
2147
+ * resolution would land there. */
2148
+ export function installedPackageSpecifier(importerRel: string, specifier: string): string | undefined {
2149
+ const target = posix.normalize(posix.join(posix.dirname(importerRel), specifier));
2150
+ if (target === ".." || target.startsWith("../") || posix.isAbsolute(target)) return undefined;
2151
+ const parts = target.split("/");
2152
+ const index = parts.lastIndexOf("node_modules");
2153
+ if (index < 0) return undefined;
2154
+ const rest = parts.slice(index + 1);
2155
+ if (!rest.length || rest[0] === "" || rest[0] === "." || rest[0] === ".bin") return undefined;
2156
+ if (rest[0]!.startsWith("@") && (rest.length < 2 || !rest[1])) return undefined;
2157
+ return rest.join("/");
2158
+ }
2159
+
1759
2160
  /** Nearest directory holding a package.json, relative to the repository; "" is the repository root. */
1760
2161
  function nearestPackageDirectory(repoPath: string, path: string, cache: Map<string, string>): string {
1761
2162
  const visited: string[] = [];
@@ -1809,10 +2210,11 @@ function scopeAdapterBlockers(adapterBlockers: string[], scopes: Map<string, Set
1809
2210
  return [...scoped].map(([reason, directories]) => ({ reason, directories: [...directories].sort() }));
1810
2211
  }
1811
2212
 
1812
- /** A declared workspace package imported by name that resolves to no repository file, typically because
1813
- * dependencies are not installed, hides every edge into that package (2026-11-08: in an uninstalled
1814
- * Sentry checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change
1815
- * reaching the package then falls back instead of skipping its dependents. */
2213
+ /** A declared workspace package imported by name from a workspace member whose import could not be mapped
2214
+ * to the package's source files hides every edge into that package (2026-11-08: in an uninstalled Sentry
2215
+ * checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change reaching
2216
+ * the package then falls back instead of skipping its dependents. Imports from outside the workspace get
2217
+ * the package from elsewhere (a registry or a tarball) and are left out by the caller. */
1816
2218
  function uninstalledWorkspaceBlockers(repoPath: string, references: ResolutionReference[], workspaceRoots: ReadonlySet<string>): ScopedAdapterBlocker[] {
1817
2219
  const external = references.filter((ref) => ref.resolution === "external-package");
1818
2220
  if (!external.length) return [];
@@ -1834,7 +2236,7 @@ function uninstalledWorkspaceBlockers(repoPath: string, references: ResolutionRe
1834
2236
  set.add(ref.importer);
1835
2237
  }
1836
2238
  return [...importers].sort(([a], [b]) => a.localeCompare(b)).map(([name, files]) => ({
1837
- reason: `Workspace package ${name} is imported by ${files.size} file${files.size === 1 ? "" : "s"} but does not resolve to its repository sources; install and link dependencies before analysis`,
2239
+ reason: `Workspace package ${name} is imported by ${files.size} file${files.size === 1 ? "" : "s"} but DiffCI cannot map the import to the package's source files; point the package's types entry at a tsconfig outDir or declarationDir with a rootDir, or at source`,
1838
2240
  directories: [packages.get(name)!],
1839
2241
  }));
1840
2242
  }