@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,13 +1,15 @@
1
1
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
2
  import { createTestFileMatcher, DEFAULT_TEST_FILE_MATCHER, testFileMatcherForProfile } 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 } 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
  /** Test-runner calls whose literal first argument names a module the test depends on. */
12
14
  const MOCK_MODULE_CALLS = new Set([
13
15
  "vi.mock", "vi.doMock", "vi.unmock", "vi.doUnmock", "vi.importActual", "vi.importMock",
@@ -108,8 +110,46 @@ function specifierParts(expression, consts, depth = 0) {
108
110
  if (initializer)
109
111
  return specifierParts(initializer, consts, depth + 1);
110
112
  }
113
+ // `url.href` or `url.toString()` of a URL resolved against the importer's own location names the same file
114
+ // as a relative specifier (Paperclip, 2026-11-12: server/src/vendor/paperclip-runner/index.ts does
115
+ // `const sourceUrl = new URL("../../../../packages/paperclip-runner/src/index.ts", import.meta.url);
116
+ // await import(sourceUrl.href)`, and about 1,900 tests were selected for every change through it).
117
+ const urlTarget = ts.isPropertyAccessExpression(expression) && expression.name.text === "href" ? expression.expression
118
+ : ts.isCallExpression(expression) && expression.arguments.length === 0 && ts.isPropertyAccessExpression(expression.expression)
119
+ && expression.expression.name.text === "toString" ? expression.expression.expression : undefined;
120
+ if (urlTarget) {
121
+ const relativeParts = moduleRelativeUrlParts(urlTarget, consts, depth + 1);
122
+ if (relativeParts)
123
+ return join(relativeParts);
124
+ }
111
125
  return [undefined];
112
126
  }
127
+ /** The specifier parts of `new URL(<parts>, import.meta.url)`, directly or through a single `const`, as a
128
+ * relative specifier ("x.ts" becomes "./x.ts"). Undefined for any other base, or a first argument that is
129
+ * absolute, has a scheme, starts with an unknown part or carries a fragment. */
130
+ function moduleRelativeUrlParts(expression, consts, depth) {
131
+ if (depth > 8)
132
+ return undefined;
133
+ while (ts.isParenthesizedExpression(expression))
134
+ expression = expression.expression;
135
+ if (ts.isIdentifier(expression)) {
136
+ const initializer = consts.get(expression.text);
137
+ return initializer ? moduleRelativeUrlParts(initializer, consts, depth + 1) : undefined;
138
+ }
139
+ if (!ts.isNewExpression(expression) || !ts.isIdentifier(expression.expression) || expression.expression.text !== "URL"
140
+ || expression.arguments?.length !== 2 || consts.has("URL"))
141
+ return undefined;
142
+ const base = expression.arguments[1];
143
+ if (!(ts.isPropertyAccessExpression(base) && base.name.text === "url" && ts.isMetaProperty(base.expression)
144
+ && base.expression.keywordToken === ts.SyntaxKind.ImportKeyword))
145
+ return undefined;
146
+ const parts = specifierParts(expression.arguments[0], consts, depth + 1);
147
+ const head = parts[0];
148
+ if (typeof head !== "string" || head === "" || head.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(head)
149
+ || parts.some((part) => typeof part === "string" && part.includes("#")))
150
+ return undefined;
151
+ return head.startsWith("./") || head.startsWith("../") ? parts : [`./${head}`, ...parts.slice(1)];
152
+ }
113
153
  /** A folded specifier: its literal text, or the patterns bounding it. A query (`?v=...`) selects no file
114
154
  * of its own: Vite and Node strip it before resolving, so text after the first `?` is dropped. */
115
155
  function foldedSpecifier(parts) {
@@ -251,10 +291,24 @@ function extractImportRefs(sourceFile) {
251
291
  const refs = [];
252
292
  let shadowDepth = 0;
253
293
  let consts;
294
+ // A function body runs when called, not when the module loads; an immediately invoked one runs at load.
295
+ // Program source files have no parent pointers, so a call marks the function it invokes on the way down.
296
+ let functionDepth = 0;
297
+ const invokedAtOnce = new Set();
254
298
  function visit(node) {
255
299
  const shadows = scopeShadowsRequire(node);
256
300
  if (shadows)
257
301
  shadowDepth++;
302
+ if (ts.isCallExpression(node)) {
303
+ let callee = node.expression;
304
+ while (ts.isParenthesizedExpression(callee))
305
+ callee = callee.expression;
306
+ if (ts.isFunctionLike(callee))
307
+ invokedAtOnce.add(callee);
308
+ }
309
+ const body = ts.isFunctionLike(node) && !invokedAtOnce.has(node);
310
+ if (body)
311
+ functionDepth++;
258
312
  if (ts.isImportDeclaration(node)) {
259
313
  const specifier = node.moduleSpecifier;
260
314
  if (ts.isStringLiteral(specifier)) {
@@ -263,7 +317,11 @@ function extractImportRefs(sourceFile) {
263
317
  const kind = isTypeOnly ? "type-import" : "import";
264
318
  const inlineTypeOnly = !isTypeOnly && !!clause && !clause.name && !!clause.namedBindings
265
319
  && ts.isNamedImports(clause.namedBindings) && allInlineType(clause.namedBindings.elements);
266
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
320
+ const bindings = clause && !(clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
321
+ ? [...(clause.name ? ["default"] : []), ...(clause.namedBindings && ts.isNamedImports(clause.namedBindings)
322
+ ? clause.namedBindings.elements.filter((el) => !el.isTypeOnly).map((el) => (el.propertyName ?? el.name).text) : [])]
323
+ : undefined;
324
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), ...(bindings ? { names: bindings } : {}) });
267
325
  }
268
326
  }
269
327
  else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
@@ -277,7 +335,11 @@ function extractImportRefs(sourceFile) {
277
335
  if (ts.isStringLiteral(specifier)) {
278
336
  const kind = node.isTypeOnly ? "type-import" : "re-export";
279
337
  const inlineTypeOnly = !node.isTypeOnly && !!node.exportClause && ts.isNamedExports(node.exportClause) && allInlineType(node.exportClause.elements);
280
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
338
+ const clause = node.exportClause;
339
+ const reexport = !clause ? { star: true }
340
+ : ts.isNamespaceExport(clause) ? { namespace: clause.name.text }
341
+ : { pairs: clause.elements.filter((el) => !el.isTypeOnly).map((el) => [el.name.text, (el.propertyName ?? el.name).text]) };
342
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), reexport });
281
343
  }
282
344
  }
283
345
  else if (ts.isCallExpression(node)) {
@@ -295,6 +357,7 @@ function extractImportRefs(sourceFile) {
295
357
  dynamic: isImport || !syntaxLiteral,
296
358
  computed: !literal,
297
359
  ...(patterns ? { patterns } : {}),
360
+ ...(!literal && functionDepth === 0 ? { atLoad: true } : {}),
298
361
  });
299
362
  }
300
363
  else if (firstArg && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
@@ -313,16 +376,135 @@ function extractImportRefs(sourceFile) {
313
376
  dynamic: true,
314
377
  computed: true,
315
378
  ...(patterns.length && patterns.every(Boolean) ? { patterns: patterns } : {}),
379
+ ...(functionDepth === 0 ? { atLoad: true } : {}),
316
380
  });
317
381
  }
318
382
  }
319
383
  ts.forEachChild(node, visit);
384
+ if (body)
385
+ functionDepth--;
320
386
  if (shadows)
321
387
  shadowDepth--;
322
388
  }
323
389
  visit(sourceFile);
324
390
  return refs;
325
391
  }
392
+ /**
393
+ * Whether the nearest package.json at or above `path` (inside the repository) declares its JavaScript free of
394
+ * side effects: `"sideEffects": false`, or a list naming only stylesheets. This is the contract bundlers
395
+ * rely on to drop unused re-exports; without it a module's evaluation may matter, so imports stay whole.
396
+ */
397
+ function sideEffectFreePackage(repoPath, path, cache) {
398
+ let dir = dirname(path);
399
+ while (true) {
400
+ let declared = cache.get(dir);
401
+ if (!cache.has(dir)) {
402
+ declared = undefined;
403
+ try {
404
+ const pkg = JSON.parse(readFileSync(join(repoPath, dir, "package.json"), "utf8"));
405
+ const se = pkg.sideEffects;
406
+ declared = se === false || (Array.isArray(se) && se.length > 0 && se.every((glob) => typeof glob === "string" && /\.(s?css|sass|less|styl)$/.test(glob)));
407
+ }
408
+ catch (error) {
409
+ if (error.code !== "ENOENT")
410
+ declared = false;
411
+ }
412
+ cache.set(dir, declared);
413
+ }
414
+ if (declared !== undefined)
415
+ return declared;
416
+ if (dir === "." || dir === "" || dirname(dir) === dir)
417
+ return false;
418
+ dir = dirname(dir);
419
+ }
420
+ }
421
+ /**
422
+ * Runtime names a module defines itself, for export-level selection. `opaque` when they cannot be listed
423
+ * (CommonJS `module.exports`/`exports.x`, `export =`, destructured `export const { a } = ...`): an import of
424
+ * such a module always counts as the whole module.
425
+ */
426
+ function exportedLocals(sourceFile) {
427
+ const locals = new Set();
428
+ let opaque = false;
429
+ const has = (node, kind) => ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === kind);
430
+ for (const st of sourceFile.statements) {
431
+ if (ts.isExportDeclaration(st)) {
432
+ if (!st.moduleSpecifier && !st.isTypeOnly && st.exportClause && ts.isNamedExports(st.exportClause)) {
433
+ for (const el of st.exportClause.elements)
434
+ if (!el.isTypeOnly)
435
+ locals.add(el.name.text);
436
+ }
437
+ }
438
+ else if (ts.isExportAssignment(st)) {
439
+ locals.add("default");
440
+ if (st.isExportEquals)
441
+ opaque = true;
442
+ }
443
+ else if (has(st, ts.SyntaxKind.ExportKeyword)) {
444
+ if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st))
445
+ continue;
446
+ if (has(st, ts.SyntaxKind.DefaultKeyword))
447
+ locals.add("default");
448
+ else if (ts.isVariableStatement(st)) {
449
+ for (const d of st.declarationList.declarations) {
450
+ if (ts.isIdentifier(d.name))
451
+ locals.add(d.name.text);
452
+ else
453
+ opaque = true;
454
+ }
455
+ }
456
+ else if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isEnumDeclaration(st) || ts.isModuleDeclaration(st)) && st.name && ts.isIdentifier(st.name)) {
457
+ locals.add(st.name.text);
458
+ }
459
+ else
460
+ opaque = true;
461
+ }
462
+ }
463
+ const visit = (node) => {
464
+ if (opaque)
465
+ return;
466
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)
467
+ && (node.expression.text === "exports" || (node.expression.text === "module" && node.name.text === "exports")))
468
+ opaque = true;
469
+ else
470
+ ts.forEachChild(node, visit);
471
+ };
472
+ visit(sourceFile);
473
+ return { locals: [...locals].sort(), opaque };
474
+ }
475
+ /** A string that reads as a relative path to a code file: `./x`, `../x`, or a relative path ending in a code
476
+ * extension (`config.ts`, `jobs/handler.js`). */
477
+ const PATH_LITERAL = /^(?:\.{1,2}\/[^\s:*?"<>|]+|(?:[\w@.-]+\/)*[\w@.-]+\.[cm]?[jt]sx?)$/;
478
+ /**
479
+ * Strings that name a code file by path, outside import and require specifiers, which already are edges
480
+ * (2026-11-10). payloadcms/payload's integration tests pass `{ config: './config.ts' }` to a helper that
481
+ * `import()`s it; the string is the only trace of that dependency. Type positions are skipped.
482
+ */
483
+ function extractPathLiterals(sourceFile) {
484
+ const found = new Set();
485
+ const specifiers = new Set();
486
+ const visit = (node) => {
487
+ if (ts.isTypeNode(node))
488
+ return;
489
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)
490
+ specifiers.add(node.moduleSpecifier);
491
+ if (ts.isExternalModuleReference(node))
492
+ specifiers.add(node.expression);
493
+ if (ts.isCallExpression(node) && node.arguments[0]) {
494
+ const e = node.expression;
495
+ const loads = e.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(e) && e.text === "require")
496
+ || (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression) && MOCK_MODULE_CALLS.has(`${e.expression.text}.${e.name.text}`));
497
+ if (loads)
498
+ 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
+ }
326
508
  class DependencyGraphImpl {
327
509
  repoPath;
328
510
  nodes;
@@ -808,10 +990,13 @@ export async function buildDependencyGraph(options = {}) {
808
990
  markPhase("adapterInventory");
809
991
  const context = { repoPath, files, profile, vueAnalysisSession: {} };
810
992
  const cachedVue = options.vueAnalysisCache ? (await import("../cache/vue-analysis-cache.js")).analyzeVueCached : undefined;
811
- const contributions = REPOSITORY_ADAPTERS.filter((adapter) => adapter.detect(context)).map((adapter) => adapter.id === "vue" && cachedVue && options.vueAnalysisCache
993
+ const adapterResults = REPOSITORY_ADAPTERS.filter((adapter) => adapter.detect(context)).map((adapter) => adapter.id === "vue" && cachedVue && options.vueAnalysisCache
812
994
  ? cachedVue(context, options.vueAnalysisCache.directory, options.vueAnalysisCache.version) : adapter.analyze(context));
813
995
  markPhase("adapters");
814
- const adapterBlockers = [...scopeBlockers, ...contributions.flatMap((item) => item.blockers)];
996
+ // An adapter that only confines blockers to directories models nothing, so it is not an active adapter:
997
+ // it neither marks the repository as mixed-language nor adds that adapter's per-change checks.
998
+ const contributions = adapterResults.filter((item) => !item.confinedOnly);
999
+ const adapterBlockers = [...scopeBlockers, ...adapterResults.flatMap((item) => item.blockers)];
815
1000
  // The directories each narrowable blocker is confined to ("" when one of its files is not confined).
816
1001
  // Outside a declared Vue suite, a blocker confined to directories only is scoped to them below.
817
1002
  const blockerScopes = new Map();
@@ -826,9 +1011,31 @@ export async function buildDependencyGraph(options = {}) {
826
1011
  const packageDirectories = new Map();
827
1012
  const packageScope = (path) => nearestPackageDirectory(repoPath, path, packageDirectories);
828
1013
  const workspaceRoots = new Set(declaredWorkspaceRoots(repoPath));
1014
+ const workspaceSources = new WorkspaceSources(repoPath, workspaceRoots);
1015
+ // The package manager links workspace packages only into workspace members (and the root project).
1016
+ const inWorkspace = (rel) => { const directory = packageScope(rel); return directory === "" || workspaceRoots.has(directory); };
1017
+ let realRepoRoot;
1018
+ const physicalRelative = (file) => {
1019
+ try {
1020
+ realRepoRoot ??= realpathSync.native(repoPath);
1021
+ const rel = relative(realRepoRoot, realpathSync.native(file)).replace(/\\/g, "/");
1022
+ return rel && !rel.startsWith("../") && rel !== ".." && !isAbsolute(rel) ? rel : undefined;
1023
+ }
1024
+ catch {
1025
+ return undefined;
1026
+ }
1027
+ };
829
1028
  for (const item of contributions)
830
1029
  for (const { path, reason } of [...(item.fileBlockers ?? []), ...(item.subjectBlockers ?? [])])
831
1030
  addScope(reason, packageScope(path));
1031
+ for (const item of adapterResults) {
1032
+ for (const { directory, reason } of item.directoryBlockers ?? []) {
1033
+ if (!adapterBlockers.includes(reason))
1034
+ adapterBlockers.push(reason);
1035
+ // Inside a declared Vue suite nothing is scoped, so the blocker stays global (fails closed).
1036
+ addScope(reason, directory);
1037
+ }
1038
+ }
832
1039
  if (profile.diffciConfig?.configurationError && !adapterBlockers.includes(profile.diffciConfig.configurationError))
833
1040
  adapterBlockers.push(profile.diffciConfig.configurationError);
834
1041
  if (contributions.some((item) => item.id === "go") && files.some((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file))) {
@@ -899,7 +1106,36 @@ export async function buildDependencyGraph(options = {}) {
899
1106
  for (const path of item.sourcePaths)
900
1107
  internalSourcePaths.add(path);
901
1108
  const edgeKeys = new Set(edges.map((edge) => `${edge.from}|${edge.to}|${edge.kind}`));
902
- function addEdge(from, to, kind) {
1109
+ const bindings = {};
1110
+ const bindingsOf = (path) => (bindings[path] ??= { locals: [], imports: {}, reexports: {} });
1111
+ /** Records what a runtime edge binds; an edge without a parsed statement binds the whole module. */
1112
+ function recordBinding(from, to, kind, ref) {
1113
+ if (kind === "asset")
1114
+ return;
1115
+ const b = bindingsOf(from);
1116
+ if (kind === "type-import") {
1117
+ if (!(b.typeImports ??= []).includes(to))
1118
+ b.typeImports.push(to);
1119
+ return;
1120
+ }
1121
+ if (ref?.reexport) {
1122
+ const r = (b.reexports[to] ??= { pairs: [], star: false, namespaces: [] });
1123
+ if (ref.reexport.star)
1124
+ r.star = true;
1125
+ if (ref.reexport.namespace)
1126
+ r.namespaces.push(ref.reexport.namespace);
1127
+ for (const pair of ref.reexport.pairs ?? [])
1128
+ r.pairs.push(pair);
1129
+ return;
1130
+ }
1131
+ const current = b.imports[to];
1132
+ if (!ref?.names || current === "*")
1133
+ b.imports[to] = "*";
1134
+ else
1135
+ b.imports[to] = [...new Set([...(current ?? []), ...ref.names])];
1136
+ }
1137
+ function addEdge(from, to, kind, ref) {
1138
+ recordBinding(from, to, kind, ref);
903
1139
  const key = `${from}|${to}|${kind}`;
904
1140
  if (edgeKeys.has(key))
905
1141
  return;
@@ -1072,6 +1308,42 @@ export async function buildDependencyGraph(options = {}) {
1072
1308
  }
1073
1309
  return compilerOptions;
1074
1310
  }
1311
+ /** The existing code file a path string names, relative to the file holding it. */
1312
+ function pathLiteralTarget(importerRel, literal) {
1313
+ const base = posix.normalize(posix.join(posix.dirname(importerRel), literal));
1314
+ if (base.startsWith("../") || base === "..")
1315
+ return undefined;
1316
+ const stem = base.replace(/\.[cm]?jsx?$/, "");
1317
+ 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}`)];
1318
+ for (const candidate of candidates) {
1319
+ if (!isSourceFileName(candidate) || candidate.endsWith(".d.ts") || isExcludedPath(candidate, options.excludeDirs ?? []))
1320
+ continue;
1321
+ if (internalSourcePaths.has(candidate) || existsSync(join(repoPath, candidate)))
1322
+ return candidate;
1323
+ }
1324
+ return undefined;
1325
+ }
1326
+ /** Parses an implementation file an import reaches outside the initial walk, rather than silently dropping
1327
+ * the edge or loading every TypeScript declaration library again; false, with a blocker, past the budget. */
1328
+ function followImplementation(absolute, rel) {
1329
+ if (internalSourcePaths.has(rel))
1330
+ return true;
1331
+ try {
1332
+ if (isExcludedPath(rel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(absolute).size > 5 * 1024 * 1024)
1333
+ throw new Error("excluded or exceeds parse budget");
1334
+ const followed = ts.createSourceFile(absolute, readFileSync(absolute, "utf8"), ts.ScriptTarget.Latest, true);
1335
+ if (followed.parseDiagnostics?.length)
1336
+ throw new Error("invalid implementation syntax");
1337
+ sourceFiles.push(followed);
1338
+ followedImplementationFiles++;
1339
+ }
1340
+ catch {
1341
+ adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${rel}`);
1342
+ return false;
1343
+ }
1344
+ internalSourcePaths.add(rel);
1345
+ return true;
1346
+ }
1075
1347
  for (const sf of sourceFiles) {
1076
1348
  const importerRel = toRelativeInternal(repoPath, sf.fileName);
1077
1349
  if (!importerRel || !isSourceFileName(sf.fileName))
@@ -1081,17 +1353,36 @@ export async function buildDependencyGraph(options = {}) {
1081
1353
  const importerOptions = optionsFor(sf.fileName);
1082
1354
  const keepsTypeImports = keepsTypeOnlyImports(importerOptions);
1083
1355
  const refs = extractImportRefs(sf).map((ref) => ref.inlineTypeOnly && !keepsTypeImports ? { ...ref, kind: "type-import" } : ref);
1356
+ const { locals, opaque } = exportedLocals(sf);
1357
+ const own = bindingsOf(importerRel);
1358
+ own.locals = locals;
1359
+ if (opaque)
1360
+ own.opaque = true;
1361
+ for (const literal of extractPathLiterals(sf)) {
1362
+ const target = pathLiteralTarget(importerRel, literal);
1363
+ if (!target || target === importerRel)
1364
+ continue;
1365
+ // Infrastructure code outside the graph (ops/, a Worker entry) is resolved through the tests that read
1366
+ // it, and stays global when a deployment definition runs it (ImpactAnalyzer, INFRASTRUCTURE_GLOBAL); a
1367
+ // string naming it must not pull it into the graph and around that rule.
1368
+ if (!internalSourcePaths.has(target) && infrastructureRole(target) === "code")
1369
+ continue;
1370
+ if (followImplementation(join(repoPath, target), target))
1371
+ addEdge(importerRel, target, "path-literal");
1372
+ }
1084
1373
  if (scope && sf.referencedFiles.length)
1085
1374
  adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
1086
1375
  for (const ref of refs) {
1087
1376
  // Expression text is not a module name. In particular, import(name) must
1088
1377
  // not be classified as an external package called "name".
1378
+ if (ref.computed && ref.atLoad)
1379
+ bindingsOf(importerRel).computedAtLoad = true;
1089
1380
  if (ref.computed && ref.patterns) {
1090
1381
  const targets = resolvePatternTargets(sf.fileName, ref.patterns, importerOptions);
1091
1382
  if (targets) {
1092
1383
  for (const target of targets) {
1093
1384
  if (internalSourcePaths.has(target))
1094
- addEdge(importerRel, target, ref.kind);
1385
+ addEdge(importerRel, target, ref.kind, ref);
1095
1386
  else
1096
1387
  recordAssetEdge(importerRel, target);
1097
1388
  }
@@ -1115,13 +1406,26 @@ export async function buildDependencyGraph(options = {}) {
1115
1406
  }
1116
1407
  const specifierCategory = classifySpecifier(ref.specifier);
1117
1408
  const resolvableSpecifier = specifierCategory === "relative" || specifierCategory === "absolute" || specifierCategory === "alias" ? stripImportQuery(ref.specifier) : ref.specifier;
1409
+ // A relative path into an installed package (`../../ui/node_modules/vite/dist/node/index.js`) is a
1410
+ // dependency import spelled as a path. A clean checkout has no such file, and an installed one resolves
1411
+ // it into node_modules, which is outside the source inventory, so it was "unresolved" and every change
1412
+ // reaching the importer fell back (Paperclip, 2026-11-11: 7 of its 14 unresolved imports). Record it
1413
+ // under the package's own specifier so dependency changes still find the importer. A workspace package
1414
+ // linked into node_modules is repository source and keeps the normal handling.
1415
+ if (specifierCategory === "relative") {
1416
+ const installed = installedPackageSpecifier(importerRel, resolvableSpecifier);
1417
+ if (installed && !workspaceSources.packageFor(installed)) {
1418
+ recordReference("external-package", importerRel, { ...ref, specifier: installed });
1419
+ continue;
1420
+ }
1421
+ }
1118
1422
  // TypeScript may resolve a Vue import to a declaration shim. Preserve the actual SFC edge.
1119
1423
  if (resolvableSpecifier.endsWith(".vue")) {
1120
1424
  const compilerAliases = Object.entries(importerOptions.paths ?? {}).map(([pattern, substitutions]) => ({ pattern, substitutions }));
1121
1425
  const candidate = findAssetCandidate(sf.fileName, resolvableSpecifier, compilerAliases.length ? compilerAliases : profile.pathAliases, importerOptions.baseUrl ?? dirname(sf.fileName));
1122
1426
  const target = candidate && toRelativeInternal(repoPath, candidate);
1123
1427
  if (target && internalSourcePaths.has(target)) {
1124
- addEdge(importerRel, target, ref.kind);
1428
+ addEdge(importerRel, target, ref.kind, ref);
1125
1429
  recordReference("internal-source", importerRel, ref);
1126
1430
  continue;
1127
1431
  }
@@ -1130,6 +1434,39 @@ export async function buildDependencyGraph(options = {}) {
1130
1434
  continue;
1131
1435
  }
1132
1436
  const resolution = ts.resolveModuleName(resolvableSpecifier, sf.fileName, importerOptions, resolutionHost, moduleResolutionCache);
1437
+ // A workspace package's build output is not its source (2026-11-09, Sentry: `@sentry/server-utils`
1438
+ // resolves to nothing before a build and to build/types/index.d.ts after one). Map the import to the
1439
+ // package's source file, or leave it external so the workspace guard falls back.
1440
+ const workspaceImport = !scope && specifierCategory === "package" && workspaceSources.size && inWorkspace(importerRel)
1441
+ ? workspaceSources.packageFor(resolvableSpecifier)
1442
+ : undefined;
1443
+ if (workspaceImport) {
1444
+ const { pkg, subpath } = workspaceImport;
1445
+ const resolvedFile = resolution.resolvedModule?.resolvedFileName;
1446
+ // Through real paths: a workspace link, or a repository path spelled differently (a Windows 8.3
1447
+ // short name), must still land inside the package.
1448
+ const resolvedRel = resolvedFile ? physicalRelative(resolvedFile) : undefined;
1449
+ const insidePackage = resolvedRel !== undefined && resolvedRel.startsWith(`${pkg.root}/`);
1450
+ if (!resolvedFile || (insidePackage && (/\.d\.[mc]?ts$/.test(resolvedRel) || !internalSourcePaths.has(resolvedRel)))) {
1451
+ const source = (insidePackage ? workspaceSources.sourceForFile(pkg, resolvedRel) : undefined) ?? workspaceSources.sourceForSubpath(pkg, subpath);
1452
+ const asset = source ? undefined : workspaceSources.assetForSubpath(pkg, subpath);
1453
+ if (asset) {
1454
+ recordAssetEdge(importerRel, asset);
1455
+ recordReference("internal-asset", importerRel, ref);
1456
+ continue;
1457
+ }
1458
+ // The package's source may sit outside the tsconfig inventory (payloadcms/payload's solution tsconfig
1459
+ // references only some packages): parse it like any other followed implementation.
1460
+ if (source && (internalSourcePaths.has(source) || (!/\.d\.[mc]?ts$/.test(source) && followImplementation(join(repoPath, source), source)))) {
1461
+ addEdge(importerRel, source, ref.kind, ref);
1462
+ recordReference("internal-source", importerRel, ref);
1463
+ }
1464
+ else {
1465
+ recordReference("external-package", importerRel, ref);
1466
+ }
1467
+ continue;
1468
+ }
1469
+ }
1133
1470
  if (!resolution.resolvedModule || !resolution.resolvedModule.resolvedFileName) {
1134
1471
  const category = classifySpecifier(ref.specifier);
1135
1472
  if (category === "relative" || category === "absolute" || category === "alias") {
@@ -1142,6 +1479,19 @@ export async function buildDependencyGraph(options = {}) {
1142
1479
  continue;
1143
1480
  }
1144
1481
  }
1482
+ // Build output a fresh checkout does not have, inside a workspace package whose tsconfig maps it back:
1483
+ // payloadcms/payload's packages/payload/bin.js does `import('./dist/cli/index.js')`, compiled from
1484
+ // src/cli/index.ts. The import depends on that source, so follow it rather than leave it unresolved.
1485
+ if (category === "relative") {
1486
+ const built = posix.normalize(posix.join(posix.dirname(importerRel), resolvableSpecifier));
1487
+ const pkg = workspaceSources.packageContaining(built);
1488
+ const source = pkg ? workspaceSources.sourceForFile(pkg, built) : undefined;
1489
+ if (source && source !== built && followImplementation(join(repoPath, source), source)) {
1490
+ addEdge(importerRel, source, ref.kind, ref);
1491
+ recordReference("internal-source", importerRel, ref);
1492
+ continue;
1493
+ }
1494
+ }
1145
1495
  recordUnresolved(importerRel, ref, "unresolved internal module");
1146
1496
  recordReference("unresolved", importerRel, ref);
1147
1497
  }
@@ -1164,26 +1514,10 @@ export async function buildDependencyGraph(options = {}) {
1164
1514
  continue;
1165
1515
  }
1166
1516
  if (targetRel && isSourceFileName(resolved)) {
1167
- if (!resolved.endsWith(".d.ts") && !internalSourcePaths.has(targetRel)) {
1168
- // A real import can reach generated implementation excluded from the
1169
- // initial walk. Parse it (and its imports) rather than silently dropping
1170
- // the edge or loading every TypeScript declaration library again.
1171
- try {
1172
- if (isExcludedPath(targetRel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(resolved).size > 5 * 1024 * 1024)
1173
- throw new Error("excluded or exceeds parse budget");
1174
- const followed = ts.createSourceFile(resolved, readFileSync(resolved, "utf8"), ts.ScriptTarget.Latest, true);
1175
- if (followed.parseDiagnostics?.length)
1176
- throw new Error("invalid implementation syntax");
1177
- sourceFiles.push(followed);
1178
- followedImplementationFiles++;
1179
- }
1180
- catch {
1181
- adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${targetRel}`);
1182
- continue;
1183
- }
1184
- }
1517
+ if (!resolved.endsWith(".d.ts") && !followImplementation(resolved, targetRel))
1518
+ continue;
1185
1519
  internalSourcePaths.add(targetRel);
1186
- addEdge(importerRel, targetRel, ref.kind);
1520
+ addEdge(importerRel, targetRel, ref.kind, ref);
1187
1521
  recordReference("internal-source", importerRel, ref);
1188
1522
  continue;
1189
1523
  }
@@ -1270,7 +1604,30 @@ export async function buildDependencyGraph(options = {}) {
1270
1604
  if (scope && edges.some(edge => outsideScope(edge.from) || outsideScope(edge.to)))
1271
1605
  adapterBlockers.push("Vue asset or macro dependency crosses the declared package boundary");
1272
1606
  const scopedAdapterBlockers = scopeAdapterBlockers(adapterBlockers, blockerScopes);
1273
- scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots));
1607
+ // A type-only import of a subpath the package neither exports nor contains resolves nowhere, installed or not
1608
+ // (payloadcms/payload's stale `import type { ... } from 'payload/types'`): it hides no edge a change can reach.
1609
+ const namesNothing = (ref) => {
1610
+ if (ref.kind !== "type-import")
1611
+ return false;
1612
+ const target = workspaceSources.packageFor(stripImportQuery(ref.specifier));
1613
+ return target !== undefined && !workspaceSources.names(target.pkg, target.subpath);
1614
+ };
1615
+ // A file only path strings point at (payloadcms/payload's codemod fixtures `basic.input.ts`, read as text
1616
+ // and full of deliberately stale imports) may never run. Its unmapped workspace imports are unresolved
1617
+ // imports of that file, which matter to a change that reaches it (refineConfidenceForDelta), rather than a
1618
+ // blocker on every change that reaches the imported package.
1619
+ const testFiles = new Set(profile.testFilePaths);
1620
+ const incomingKinds = new Map();
1621
+ for (const edge of edges)
1622
+ (incomingKinds.get(edge.to) ?? incomingKinds.set(edge.to, new Set()).get(edge.to)).add(edge.kind);
1623
+ const pathLiteralOnly = new Set([...incomingKinds].filter(([file, kinds]) => !testFiles.has(file) && kinds.has("path-literal") && [...kinds].every((kind) => kind === "path-literal")).map(([file]) => file));
1624
+ const workspaceRefs = references.filter((ref) => inWorkspace(ref.importer) && !namesNothing(ref));
1625
+ for (const ref of workspaceRefs) {
1626
+ if (!pathLiteralOnly.has(ref.importer) || ref.resolution !== "external-package" || !workspaceSources.packageFor(stripImportQuery(ref.specifier)))
1627
+ continue;
1628
+ 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" });
1629
+ }
1630
+ scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, workspaceRefs.filter((ref) => !pathLiteralOnly.has(ref.importer)), workspaceRoots));
1274
1631
  profile.adapterBlockers = [...adapterBlockers];
1275
1632
  markPhase("importExtractionAndResolution");
1276
1633
  // Nested-package test visibility (2026-08-24, biomejs/biome finding): `internalSourcePaths` above is
@@ -1339,8 +1696,13 @@ export async function buildDependencyGraph(options = {}) {
1339
1696
  filesDiscovered: filesParsed,
1340
1697
  filesParsed: filesParsed,
1341
1698
  };
1699
+ const sideEffectsByDir = new Map();
1700
+ for (const [path, b] of Object.entries(bindings))
1701
+ if (sideEffectFreePackage(repoPath, path, sideEffectsByDir))
1702
+ b.sideEffectFree = true;
1342
1703
  return {
1343
1704
  graph,
1705
+ bindings,
1344
1706
  adapterBlockers,
1345
1707
  ...(scopedAdapterBlockers.length ? { scopedAdapterBlockers, confidenceWithoutScopedBlockers } : {}),
1346
1708
  profile,
@@ -1355,6 +1717,7 @@ export async function buildDependencyGraph(options = {}) {
1355
1717
  integrity,
1356
1718
  resolvedViaProjectReferences,
1357
1719
  runtimeTestSelection: runtimeTestSelectionEligible(repoPath, files, profile),
1720
+ typeTestGlobs: typeTestGlobs(repoPath, files),
1358
1721
  };
1359
1722
  }
1360
1723
  /** Product eligibility includes native adapters; legacy TS corpus classification stays separate. */
@@ -1512,10 +1875,10 @@ export function validateDependencyGraph(graph) {
1512
1875
  }
1513
1876
  /**
1514
1877
  * Whether an `import type` edge can be ignored when selecting tests (2026-11-03). Vitest transpiles
1515
- * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest, tsd,
1516
- * tstyche and Vitest's typecheck mode do check types. Any sign of them anywhere in the repository,
1517
- * including workspace packages, keeps type-only edges selecting tests. Type tests (`*.test-d.ts`) are
1518
- * selected through every edge either way (impact.ts).
1878
+ * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest and Vitest's
1879
+ * typecheck mode check every test's types. Vitest typecheck mode anywhere, or Jest at the repository root,
1880
+ * keeps type-only edges selecting every test. Jest in a sub-package, tsd and tstyche check only their own
1881
+ * files (typeTestGlobs), and those tests are selected through every edge either way (impact.ts).
1519
1882
  */
1520
1883
  function runtimeTestSelectionEligible(repoPath, files, profile) {
1521
1884
  const configs = profile.testRunnerConfigs ?? [];
@@ -1531,8 +1894,13 @@ function runtimeTestSelectionEligible(repoPath, files, profile) {
1531
1894
  if (file.split("/").includes("node_modules"))
1532
1895
  continue;
1533
1896
  const name = file.slice(file.lastIndexOf("/") + 1);
1534
- if (/^jest\.config\./.test(name))
1535
- return false;
1897
+ // Jest inside a sub-package governs that package's tests only (typeCheckedPackageDirs, typeTestGlobs).
1898
+ const atRoot = !file.includes("/");
1899
+ if (/^jest\.config\./.test(name)) {
1900
+ if (atRoot)
1901
+ return false;
1902
+ continue;
1903
+ }
1536
1904
  if (/^vit(?:e|est)[\w.-]*\.(?:config|workspace|projects)\.[cm]?[jt]s$/.test(name)) {
1537
1905
  const text = read(file);
1538
1906
  if (text === undefined || /\btypecheck\b/.test(text))
@@ -1547,14 +1915,97 @@ function runtimeTestSelectionEligible(repoPath, files, profile) {
1547
1915
  return false;
1548
1916
  }
1549
1917
  const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1550
- if (packages.some((name) => ["jest", "ts-jest", "tsd", "tstyche"].includes(name)))
1918
+ // tsd and tstyche check types only in their own test files (typeTestGlobs), which keep type edges;
1919
+ // Jest (ts-jest) and `--typecheck` type-check every test they run (2026-11-10: tstyche alone turned
1920
+ // off runtime selection for all of payloadcms/payload's Vitest tests).
1921
+ const scripts = Object.values(manifest.scripts ?? {});
1922
+ if (scripts.some((script) => typeof script !== "string" || /--typecheck/.test(script)))
1551
1923
  return false;
1552
- if (Object.values(manifest.scripts ?? {}).some((script) => typeof script !== "string" || /(?:^|[\s&;|(])(?:jest|tsd|tstyche)(?:\s|$)|--typecheck/.test(script)))
1924
+ if (atRoot && (packages.some((name) => ["jest", "ts-jest"].includes(name)) || scripts.some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script)))))
1553
1925
  return false;
1554
1926
  }
1555
1927
  }
1556
1928
  return true;
1557
1929
  }
1930
+ /** The files tstyche or tsd check, when either is installed: tstyche.json's `testFileMatch` or tstyche's
1931
+ * defaults, and tsd's `*.test-d.ts`. */
1932
+ function typeTestGlobs(repoPath, files) {
1933
+ const read = (path) => { try {
1934
+ return readFileSync(join(repoPath, path), "utf8");
1935
+ }
1936
+ catch {
1937
+ return undefined;
1938
+ } };
1939
+ let tstyche = false, tsd = false;
1940
+ for (const file of files) {
1941
+ if (file.split("/").includes("node_modules") || !file.endsWith("package.json"))
1942
+ continue;
1943
+ let manifest;
1944
+ try {
1945
+ manifest = JSON.parse(read(file) ?? "");
1946
+ }
1947
+ catch {
1948
+ continue;
1949
+ }
1950
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1951
+ const scripts = Object.values(manifest.scripts ?? {}).filter((script) => typeof script === "string");
1952
+ if (packages.includes("tstyche") || scripts.some((script) => /(?:^|[\s&;|(])tstyche(?:\s|$)/.test(script)))
1953
+ tstyche = true;
1954
+ if (packages.includes("tsd") || scripts.some((script) => /(?:^|[\s&;|(])tsd(?:\s|$)/.test(script)))
1955
+ tsd = true;
1956
+ }
1957
+ const globs = [];
1958
+ if (tstyche) {
1959
+ let match;
1960
+ for (const name of ["tstyche.config.json", "tstyche.json"]) {
1961
+ const text = read(name);
1962
+ if (text === undefined)
1963
+ continue;
1964
+ const parsed = ts.parseConfigFileTextToJson(name, text);
1965
+ match = parsed.config?.testFileMatch;
1966
+ break;
1967
+ }
1968
+ globs.push(...(Array.isArray(match) && match.every((glob) => typeof glob === "string") ? match
1969
+ : ["**/*.tst.*", "**/__typetests__/*.test.*", "**/typetests/*.test.*"]));
1970
+ }
1971
+ if (tsd)
1972
+ globs.push("**/*.test-d.ts", "**/*.test-d.tsx");
1973
+ for (const dir of typeCheckedPackageDirs(repoPath, files))
1974
+ globs.push(`${dir}/**`);
1975
+ return globs;
1976
+ }
1977
+ /**
1978
+ * Sub-package directories whose own tests Jest (or ts-jest) may type-check as they run: a jest.config there, or
1979
+ * a package.json depending on jest/ts-jest or running `jest`. 2026-11-10: payloadcms/payload's
1980
+ * `.github/actions/triage` (a GitHub Action with its own Jest setup) and `packages/payload-cloud` (a `jest`
1981
+ * test script) had turned off runtime selection for the whole Vitest suite. A repository-root signal still
1982
+ * turns it off everywhere (runtimeTestSelectionEligible).
1983
+ */
1984
+ function typeCheckedPackageDirs(repoPath, files) {
1985
+ const dirs = new Set();
1986
+ for (const file of files) {
1987
+ if (file.split("/").includes("node_modules") || !file.includes("/"))
1988
+ continue;
1989
+ const name = file.slice(file.lastIndexOf("/") + 1);
1990
+ const dir = file.slice(0, file.lastIndexOf("/"));
1991
+ if (/^jest\.config\./.test(name))
1992
+ dirs.add(dir);
1993
+ else if (name === "package.json") {
1994
+ let manifest;
1995
+ try {
1996
+ manifest = JSON.parse(readFileSync(join(repoPath, file), "utf8"));
1997
+ }
1998
+ catch {
1999
+ dirs.add(dir);
2000
+ continue;
2001
+ }
2002
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
2003
+ if (packages.some((pkg) => pkg === "jest" || pkg === "ts-jest") || Object.values(manifest.scripts ?? {}).some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script))))
2004
+ dirs.add(dir);
2005
+ }
2006
+ }
2007
+ return [...dirs].sort();
2008
+ }
1558
2009
  function computeConfidence(unresolvedCount, dynamicUnresolvedCount, integrityCriticalCount, sourceFileCount, resolvedViaProjectReferences) {
1559
2010
  // An empty graph has nothing to flag as unresolved and nothing to violate integrity
1560
2011
  // checks, so without this it would fall through to "COMPLETE" — the worst possible
@@ -1699,6 +2150,25 @@ function refineUnscopedConfidence(result, changedFiles) {
1699
2150
  // project-references cap, exactly as computeConfidence()'s own final two branches do).
1700
2151
  return result.resolvedViaProjectReferences ? "PARTIAL" : "COMPLETE";
1701
2152
  }
2153
+ /** The package specifier a relative import into a node_modules directory inside the repository names
2154
+ * (`vite/dist/node/index.js`, `@scope/pkg/dist/x.js`), or undefined when the path does not pass through
2155
+ * node_modules, leaves the repository, or names no package. The last node_modules segment wins, as Node's
2156
+ * resolution would land there. */
2157
+ export function installedPackageSpecifier(importerRel, specifier) {
2158
+ const target = posix.normalize(posix.join(posix.dirname(importerRel), specifier));
2159
+ if (target === ".." || target.startsWith("../") || posix.isAbsolute(target))
2160
+ return undefined;
2161
+ const parts = target.split("/");
2162
+ const index = parts.lastIndexOf("node_modules");
2163
+ if (index < 0)
2164
+ return undefined;
2165
+ const rest = parts.slice(index + 1);
2166
+ if (!rest.length || rest[0] === "" || rest[0] === "." || rest[0] === ".bin")
2167
+ return undefined;
2168
+ if (rest[0].startsWith("@") && (rest.length < 2 || !rest[1]))
2169
+ return undefined;
2170
+ return rest.join("/");
2171
+ }
1702
2172
  /** Nearest directory holding a package.json, relative to the repository; "" is the repository root. */
1703
2173
  function nearestPackageDirectory(repoPath, path, cache) {
1704
2174
  const visited = [];
@@ -1768,10 +2238,11 @@ function scopeAdapterBlockers(adapterBlockers, scopes) {
1768
2238
  adapterBlockers.splice(i, 1);
1769
2239
  return [...scoped].map(([reason, directories]) => ({ reason, directories: [...directories].sort() }));
1770
2240
  }
1771
- /** A declared workspace package imported by name that resolves to no repository file, typically because
1772
- * dependencies are not installed, hides every edge into that package (2026-11-08: in an uninstalled
1773
- * Sentry checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change
1774
- * reaching the package then falls back instead of skipping its dependents. */
2241
+ /** A declared workspace package imported by name from a workspace member whose import could not be mapped
2242
+ * to the package's source files hides every edge into that package (2026-11-08: in an uninstalled Sentry
2243
+ * checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change reaching
2244
+ * the package then falls back instead of skipping its dependents. Imports from outside the workspace get
2245
+ * the package from elsewhere (a registry or a tarball) and are left out by the caller. */
1775
2246
  function uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots) {
1776
2247
  const external = references.filter((ref) => ref.resolution === "external-package");
1777
2248
  if (!external.length)
@@ -1799,7 +2270,7 @@ function uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots) {
1799
2270
  set.add(ref.importer);
1800
2271
  }
1801
2272
  return [...importers].sort(([a], [b]) => a.localeCompare(b)).map(([name, files]) => ({
1802
- 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`,
2273
+ 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`,
1803
2274
  directories: [packages.get(name)],
1804
2275
  }));
1805
2276
  }