@diffci.com/diffci 0.3.54 → 0.3.55

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 (124) hide show
  1. package/dist-client/src/client/agent-selection.d.ts +9 -2
  2. package/dist-client/src/client/agent-selection.js +20 -8
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/dist-client/src/client/cli.js +15 -4
  5. package/dist-client/src/client/command-batches.js +3 -2
  6. package/dist-client/src/client/context.js +32 -2
  7. package/dist-client/src/client/coverage-map.js +6 -1
  8. package/dist-client/src/client/full-command.js +19 -14
  9. package/dist-client/src/client/hook.d.ts +17 -0
  10. package/dist-client/src/client/hook.js +53 -1
  11. package/dist-client/src/client/install.d.ts +6 -0
  12. package/dist-client/src/client/install.js +29 -1
  13. package/dist-client/src/client/mcp.js +4 -0
  14. package/dist-client/src/client/observe.js +3 -2
  15. package/dist-client/src/client/report.d.ts +1 -1
  16. package/dist-client/src/client/shared-graph-cache.js +4 -2
  17. package/dist-client/src/client/telemetry.js +2 -1
  18. package/dist-client/src/client/usage-signal.d.ts +1 -1
  19. package/dist-client/src/client/verify-savings.d.ts +6 -0
  20. package/dist-client/src/client/verify-savings.js +15 -3
  21. package/dist-client/src/client/verify.js +124 -22
  22. package/node_modules/@diffci.com/core/README.md +17 -10
  23. package/node_modules/@diffci.com/core/dist/ci-inference/expression.d.ts +5 -0
  24. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js +38 -5
  25. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +26 -6
  27. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  28. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.d.ts +2 -1
  29. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +7 -2
  30. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js +15 -8
  32. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +6 -2
  34. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  35. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +19 -4
  36. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +13 -1
  38. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -1
  39. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +5 -0
  40. package/node_modules/@diffci.com/core/dist/git/git-diff.js +22 -20
  41. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  42. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js +22 -1
  43. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js.map +1 -1
  44. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.d.ts +6 -0
  45. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js +14 -2
  46. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js.map +1 -1
  47. package/node_modules/@diffci.com/core/dist/planner/planner.js +65 -14
  48. package/node_modules/@diffci.com/core/dist/planner/planner.js.map +1 -1
  49. package/node_modules/@diffci.com/core/dist/planner/rust-command.js +43 -1
  50. package/node_modules/@diffci.com/core/dist/planner/rust-command.js.map +1 -1
  51. package/node_modules/@diffci.com/core/dist/planner/script-reads.js +5 -2
  52. package/node_modules/@diffci.com/core/dist/planner/script-reads.js.map +1 -1
  53. package/node_modules/@diffci.com/core/dist/planner/test-command.js +17 -2
  54. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/planner/type-program.js +27 -1
  56. package/node_modules/@diffci.com/core/dist/planner/type-program.js.map +1 -1
  57. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +5 -1
  58. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +21 -2
  60. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +9 -1
  62. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +158 -14
  63. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -1
  64. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.d.ts +1 -0
  65. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +180 -15
  66. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +7 -0
  68. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  69. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +16 -0
  70. package/node_modules/@diffci.com/core/dist/repo/file-references.js +76 -5
  71. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  72. package/node_modules/@diffci.com/core/dist/repo/graph.js +100 -29
  73. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  74. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  75. package/node_modules/@diffci.com/core/dist/repo/impact.js +55 -8
  76. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  77. package/node_modules/@diffci.com/core/dist/repo/layout.js +4 -1
  78. package/node_modules/@diffci.com/core/dist/repo/layout.js.map +1 -1
  79. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +10 -1
  80. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  81. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  82. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  83. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +5 -1
  84. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  85. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +3 -0
  86. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +3 -3
  87. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  88. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +65 -13
  89. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  90. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +47 -2
  91. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  92. package/node_modules/@diffci.com/core/package.json +1 -0
  93. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +38 -5
  94. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +21 -6
  95. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +7 -2
  96. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +15 -8
  97. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +6 -2
  98. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +18 -4
  99. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +8 -1
  100. package/node_modules/@diffci.com/core/src/git/git-diff.ts +20 -21
  101. package/node_modules/@diffci.com/core/src/planner/check-narrowing.ts +22 -1
  102. package/node_modules/@diffci.com/core/src/planner/pipeline-steps.ts +13 -2
  103. package/node_modules/@diffci.com/core/src/planner/planner.ts +42 -14
  104. package/node_modules/@diffci.com/core/src/planner/rust-command.ts +37 -1
  105. package/node_modules/@diffci.com/core/src/planner/script-reads.ts +5 -1
  106. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -2
  107. package/node_modules/@diffci.com/core/src/planner/type-program.ts +25 -1
  108. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +5 -1
  109. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +20 -2
  110. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +133 -14
  111. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +136 -16
  112. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +7 -1
  113. package/node_modules/@diffci.com/core/src/repo/file-references.ts +70 -5
  114. package/node_modules/@diffci.com/core/src/repo/graph.ts +81 -20
  115. package/node_modules/@diffci.com/core/src/repo/impact.ts +56 -7
  116. package/node_modules/@diffci.com/core/src/repo/layout.ts +5 -1
  117. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +11 -1
  118. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  119. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +4 -1
  120. package/node_modules/@diffci.com/core/src/repo/types.ts +3 -1
  121. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +3 -3
  122. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +43 -13
  123. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +44 -2
  124. package/package.json +2 -2
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import { posix } from "node:path";
24
+ import ts from "typescript";
24
25
  import { projectRoots } from "../repo/compiled-projects.js";
25
26
  import { LOCKFILE } from "../repo/lockfiles.js";
26
27
  import type { NarrowingInput } from "./check-narrowing.js";
@@ -40,6 +41,28 @@ function escape(text: string): string {
40
41
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
42
  }
42
43
 
44
+ /** Repository files `config` extends by a relative path, transitively, whatever they are named
45
+ * (`"extends": "./config/base.json"`). Their compiler options are the program's own. */
46
+ function extendedConfigs(config: string, input: NarrowingInput): Set<string> {
47
+ const found = new Set<string>();
48
+ const queue = [config];
49
+ while (queue.length > 0 && found.size < 50) {
50
+ const current = queue.shift()!;
51
+ const text = input.read(current);
52
+ if (text === undefined) continue;
53
+ const extended: unknown = ts.parseConfigFileTextToJson(current, text).config?.extends;
54
+ for (const value of Array.isArray(extended) ? extended : [extended]) {
55
+ if (typeof value !== "string" || !value.startsWith(".")) continue;
56
+ const base = posix.normalize(posix.join(posix.dirname(current), value));
57
+ const path = [base, `${base}.json`].find((candidate) => input.read(candidate) !== undefined) ?? base;
58
+ if (found.has(path) || path === config) continue;
59
+ found.add(path);
60
+ queue.push(path);
61
+ }
62
+ }
63
+ return found;
64
+ }
65
+
43
66
  /** The name an import of `path` would end with: its stem, or its directory for an index file. */
44
67
  function importName(path: string): string {
45
68
  const stem = posix.basename(path).replace(/\.(?:d\.)?[^.]+$/, "");
@@ -49,7 +72,8 @@ function importName(path: string): string {
49
72
  export function programMembership(config: string, input: NarrowingInput, cache: RootTextCache = new Map()): ProgramMembership {
50
73
  const configText = input.read(config);
51
74
  if (configText === undefined) return { inProgram: true, reason: `${config} could not be read` };
52
- const global = input.changes.find(({ path }) => CONFIG.test(path) || path === "package.json" || LOCKFILE.test(posix.basename(path)) || path.endsWith(".d.ts"));
75
+ const bases = extendedConfigs(config, input);
76
+ const global = input.changes.find(({ path }) => CONFIG.test(path) || bases.has(path) || path === "package.json" || LOCKFILE.test(posix.basename(path)) || path.endsWith(".d.ts"));
53
77
  if (global) return { inProgram: true, reason: `${global.path} changed, which affects every file's types` };
54
78
 
55
79
  // Added and deleted paths are matched too: they enter or leave the program.
@@ -134,7 +134,11 @@ export const goAdapter: RepositoryAdapter = {
134
134
  detect: ({ files }) => files.some((file) => file === "go.mod" || file.endsWith(".go")),
135
135
  analyze(context) {
136
136
  const failure = contribution(this);
137
- const nestedRoots = context.files.filter(f => f.endsWith("/go.mod")).map(f => f.slice(0, -"go.mod".length));
137
+ // With a root module, a go.mod under testdata/, _x/ or .x/ is a fixture: `go list ./...` never
138
+ // enters those directories, so it is not a nested module of the build.
139
+ const rooted = context.files.includes("go.mod");
140
+ const nestedRoots = context.files.filter(f => f.endsWith("/go.mod") && !(rooted && isGoDiscoveryIgnoredPath(f)))
141
+ .map(f => f.slice(0, -"go.mod".length));
138
142
  const scoped = context.profile.diffciConfig?.go?.scope === "root-module";
139
143
  // No root module and no workspace, and every Go file sits inside a nested module: those modules are
140
144
  // tools beside a repository written in another language (Paperclip's tools/agent-shim, 2026-11-11).
@@ -23,7 +23,24 @@ function tags(xml: string, name: string): string[] {
23
23
 
24
24
  function first(xml: string, name: string): string | undefined { return tags(xml, name)[0]; }
25
25
 
26
- function parsePom(path: string, xml: string): Pom {
26
+ /** Drops `<!-- ... -->` comments in one left-to-right pass. An unterminated comment is kept, as before. */
27
+ function stripXmlComments(source: string): string {
28
+ let out = "";
29
+ let i = 0;
30
+ for (;;) {
31
+ const start = source.indexOf("<!--", i);
32
+ if (start === -1) return out + source.slice(i);
33
+ const end = source.indexOf("-->", start + 4);
34
+ if (end === -1) return out + source.slice(start);
35
+ out += source.slice(i, start);
36
+ i = end + 3;
37
+ }
38
+ }
39
+
40
+ function parsePom(path: string, source: string): Pom {
41
+ // Commented-out elements are not part of the model: an old <artifactId> in a comment must not
42
+ // become the module's identity.
43
+ const xml = stripXmlComments(source);
27
44
  const dir = posix.dirname(path) === "." ? "" : posix.dirname(path);
28
45
  const parent = first(xml, "parent");
29
46
  const own = xml.replace(/<parent\b[^>]*>[\s\S]*?<\/parent>/, "");
@@ -48,9 +65,10 @@ function under(dir: string, path: string): boolean { return !dir || path === dir
48
65
  function owningPom(poms: Pom[], file: string): Pom | undefined {
49
66
  return poms.filter(pom => under(pom.dir, file)).sort((a, b) => b.dir.length - a.dir.length)[0];
50
67
  }
68
+ /** Surefire's default includes (Test*, *Test, *Tests, *TestCase) and Failsafe's (IT*, *IT, *ITCase). */
51
69
  function isTest(path: string): boolean {
52
70
  return /\/src\/test\/(?:java|kotlin)\//.test("/" + path) &&
53
- /^(?:Test.*|.*(?:Test|Tests|TestCase|IT))\.(?:java|kt)$/.test(posix.basename(path));
71
+ /^(?:Test.*|IT.*|.*(?:Test|Tests|TestCase|IT|ITCase))\.(?:java|kt)$/.test(posix.basename(path));
54
72
  }
55
73
 
56
74
  export function analyzeMaven(context: AdapterContext): AdapterContribution {
@@ -13,10 +13,11 @@ import { contribution, type AdapterContext, type AdapterContribution, type Repos
13
13
  * WHAT. The import graph comes from Python's own `ast` module, run once over every `.py` file (a short
14
14
  * script on stdin; no repository code is imported or executed, unlike `pytest --collect-only`, which runs
15
15
  * conftest.py). DiffCI resolves each import against the repository root, `src/`, pytest's `pythonpath`
16
- * and, for a file in a directory without `__init__.py`, that directory (pytest's default `prepend`
17
- * import mode puts it on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
16
+ * and each file's basedir: its own directory when that has no `__init__.py`, otherwise the first
17
+ * directory above its package (pytest's default `prepend` import mode puts the basedir on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
18
18
  * which run on import. Tests follow pytest's `python_files` and `testpaths`; each test also depends on
19
- * every `conftest.py` from its directory up to the root, which pytest loads before it.
19
+ * every `conftest.py` from its directory up to the root, which pytest loads before it, and on every
20
+ * plugin module that `addopts` loads with `-p`.
20
21
  *
21
22
  * Full validation instead, as global blockers: no Python interpreter, a file that does not parse, an
22
23
  * `importlib.import_module` / `__import__` / `pytest_plugins` entry whose name is computed, a first-party
@@ -64,15 +65,23 @@ export type PythonImport = [module: string, level: number, names: string[]];
64
65
  export interface PythonFileImports { imports?: PythonImport[]; dynamic?: boolean; error?: string }
65
66
 
66
67
  const EXCLUDED_DIRS = new Set([".venv", "venv", "env", ".env", ".tox", ".nox", "site-packages", "__pycache__", ".eggs", ".mypy_cache", ".pytest_cache", ".ruff_cache"]);
67
- const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", "tox.ini", "conftest.py"];
68
+ const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", ".pytest.ini", "tox.ini", "conftest.py"];
68
69
 
69
70
  export function isPythonSource(path: string): boolean {
70
71
  return path.endsWith(".py") && !path.split("/").some((part) => EXCLUDED_DIRS.has(part) || part.endsWith(".egg-info"));
71
72
  }
72
73
 
73
- /** The first interpreter that runs: `python3`, `python`, then the Windows launcher `py -3`. */
74
+ /** The interpreters `pythonInterpreter()` tries, in order: `python3`, `python`, then the Windows launcher `py -3`. */
75
+ export const PYTHON_INTERPRETER_CANDIDATES: readonly (readonly string[])[] = [["python3"], ["python"], ["py", "-3"]];
76
+
77
+ /**
78
+ * The first of `PYTHON_INTERPRETER_CANDIDATES` that runs Python 3. Each call probes again, so two calls
79
+ * can disagree when a launcher is slow or flaky (a Windows `python3` alias stub); use the interpreter
80
+ * the analysis recorded (`profile.pythonInterpreter`) rather than a second probe (#304).
81
+ */
74
82
  export function pythonInterpreter(cwd: string): string[] | undefined {
75
- for (const candidate of [["python3"], ["python"], ["py", "-3"]]) {
83
+ for (const entry of PYTHON_INTERPRETER_CANDIDATES) {
84
+ const candidate = [...entry];
76
85
  const result = spawnSync(candidate[0]!, [...candidate.slice(1), "-c", "import sys; print(sys.version_info[0])"], { cwd, encoding: "utf8", timeout: 10_000, windowsHide: true });
77
86
  if (result.status === 0 && result.stdout.trim() === "3") return candidate;
78
87
  }
@@ -83,6 +92,8 @@ export interface PytestSettings {
83
92
  pythonFiles: string[];
84
93
  testpaths: string[];
85
94
  pythonpath: string[];
95
+ /** Plugin modules `addopts` loads with `-p`; every test depends on them. */
96
+ plugins?: string[];
86
97
  /** A key that is present but could not be read; its file makes the analysis fall back. */
87
98
  unreadable?: string;
88
99
  }
@@ -91,24 +102,93 @@ function splitList(value: string): string[] {
91
102
  return value.split(/[\s,]+/).map((entry) => entry.replace(/^["']|["']$/g, "")).filter(Boolean);
92
103
  }
93
104
 
105
+ /**
106
+ * The strings of a TOML array of strings that starts with `[` at `start`. Comments, commas and line breaks
107
+ * between the strings are skipped, and a `]`, `,` or `#` inside a quoted string stays part of the value.
108
+ * Anything else (a nested array, a number, a multi-line string, an escape it cannot read, no closing `]`)
109
+ * returns undefined, so the caller can fall back instead of guessing.
110
+ */
111
+ function readTomlStringArray(text: string, start: number): string[] | undefined {
112
+ const values: string[] = [];
113
+ const escapes: Record<string, string> = { "\\": "\\", '"': '"', b: "\b", t: "\t", n: "\n", f: "\f", r: "\r" };
114
+ let index = start + 1;
115
+ let expectValue = true;
116
+ while (index < text.length) {
117
+ const char = text[index]!;
118
+ if (char === " " || char === "\t" || char === "\r" || char === "\n") index += 1;
119
+ else if (char === "#") {
120
+ const end = text.indexOf("\n", index);
121
+ index = end === -1 ? text.length : end;
122
+ } else if (char === "]") return values;
123
+ else if (char === ",") {
124
+ if (expectValue) return undefined;
125
+ expectValue = true;
126
+ index += 1;
127
+ } else if ((char === '"' || char === "'") && expectValue) {
128
+ if (text.startsWith(char.repeat(3), index)) return undefined;
129
+ let value = "";
130
+ index += 1;
131
+ for (;;) {
132
+ const next = text[index];
133
+ if (next === undefined || next === "\n") return undefined;
134
+ if (next === char) break;
135
+ if (next === "\\" && char === '"') {
136
+ const escaped = escapes[text[index + 1] ?? ""];
137
+ if (escaped === undefined) return undefined;
138
+ value += escaped;
139
+ index += 2;
140
+ } else {
141
+ value += next;
142
+ index += 1;
143
+ }
144
+ }
145
+ index += 1;
146
+ values.push(value);
147
+ expectValue = false;
148
+ } else return undefined;
149
+ }
150
+ return undefined;
151
+ }
152
+
94
153
  /** pytest's own configuration, from the first file pytest would use. Only the keys selection depends on. */
95
154
  export function readPytestSettings(read: (path: string) => string | undefined): PytestSettings {
96
155
  const settings: PytestSettings = { pythonFiles: ["test_*.py", "*_test.py"], testpaths: [], pythonpath: [] };
97
- const keys = ["python_files", "testpaths", "pythonpath"] as const;
156
+ const keys = ["python_files", "testpaths", "pythonpath", "addopts"] as const;
98
157
  const apply = (key: (typeof keys)[number], values: string[]) => {
99
158
  if (key === "python_files") settings.pythonFiles = values;
100
- else settings[key] = values;
159
+ else if (key === "addopts") {
160
+ // `-p name` and `-pname` import a plugin module before collection; `-p no:name` disables one.
161
+ const plugins = values.flatMap((value, index) => value === "-p" ? [values[index + 1] ?? ""] : value.startsWith("-p") && !value.startsWith("--") ? [value.slice(2)] : [])
162
+ .filter((name) => !name.startsWith("no:"));
163
+ if (plugins.length) settings.plugins = plugins;
164
+ } else settings[key] = values;
101
165
  };
102
- for (const [file, header] of [["pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const) {
166
+ // pytest's search order. `pytest.ini` and `.pytest.ini` match even when empty or without a `[pytest]`
167
+ // section, and then pytest uses its defaults; the other files only match with their section. The first
168
+ // match wins and options are never merged.
169
+ for (const [file, header] of [["pytest.ini", "pytest"], [".pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const) {
103
170
  const text = read(file);
104
171
  if (text === undefined) continue;
105
172
  const section = new RegExp(`^\\[${header.replace(/[.:]/g, "\\$&")}\\]\\s*$([\\s\\S]*?)(?=^\\[|(?![\\s\\S]))`, "m").exec(text);
106
- if (!section) continue;
173
+ if (!section) {
174
+ if (file === "pytest.ini" || file === ".pytest.ini") return settings;
175
+ continue;
176
+ }
107
177
  const body = section[1]!;
108
178
  for (const key of keys) {
109
179
  if (file === "pyproject.toml") {
110
- const match = new RegExp(`^${key}\\s*=\\s*(\\[[\\s\\S]*?\\]|"[^"]*"|'[^']*')`, "m").exec(body);
111
- if (match) apply(key, splitList(match[1]!.replace(/^\[|\]$/g, "")));
180
+ const match = new RegExp(`^${key}\\s*=\\s*("[^"]*"|'[^']*')`, "m").exec(body);
181
+ const array = new RegExp(`^${key}\\s*=\\s*(?=\\[)`, "m").exec(body);
182
+ // A multi-line string would otherwise match as an empty one. Its contents are read as one string;
183
+ // a basic string's line-ending backslash only joins lines. An unterminated one cannot be read.
184
+ const multiline = new RegExp(`^${key}\\s*=\\s*("""|'{3})([\\s\\S]*?)\\1`, "m").exec(body);
185
+ if (multiline) apply(key, splitList(multiline[1] === '"""' ? multiline[2]!.replace(/\\\r?\n/g, " ") : multiline[2]!));
186
+ else if (new RegExp(`^${key}\\s*=\\s*(?:"""|'{3})`, "m").test(body)) settings.unreadable = `${file} ${key}`;
187
+ else if (array) {
188
+ const values = readTomlStringArray(body, array.index + array[0].length);
189
+ if (values) apply(key, key === "addopts" ? values.flatMap(splitList) : values);
190
+ else settings.unreadable = `${file} ${key}`;
191
+ } else if (match) apply(key, splitList(match[1]!));
112
192
  else if (new RegExp(`^${key}\\s*=`, "m").test(body)) settings.unreadable = `${file} ${key}`;
113
193
  } else {
114
194
  // INI values continue on indented lines.
@@ -125,13 +205,30 @@ function globToRegExp(glob: string): RegExp {
125
205
  return new RegExp(`^${glob.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
126
206
  }
127
207
 
208
+ /** One path segment against one shell-style glob segment, as Python's `fnmatch` reads it. */
209
+ function segmentMatches(glob: string, segment: string): boolean {
210
+ const source = glob.replace(/\[!/g, "[^").replace(/[.+${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]");
211
+ try { return new RegExp(`^${source}$`).test(segment); } catch { return glob === segment; }
212
+ }
213
+
214
+ /** Whether `segments` starts with directories (or is a file) that `glob` names; `**` spans any depth. */
215
+ function globPrefixMatches(glob: readonly string[], segments: readonly string[]): boolean {
216
+ if (!glob.length) return true;
217
+ const [head, ...rest] = glob;
218
+ if (head === "**") return segments.some((_, index) => globPrefixMatches(rest, segments.slice(index))) || globPrefixMatches(rest, []);
219
+ return segments.length > 0 && segmentMatches(head!, segments[0]!) && globPrefixMatches(rest, segments.slice(1));
220
+ }
221
+
128
222
  export function isPytestFile(path: string, settings: PytestSettings): boolean {
129
223
  const base = posix.basename(path);
130
224
  if (!settings.pythonFiles.some((glob) => globToRegExp(glob).test(base))) return false;
131
225
  if (!settings.testpaths.length) return true;
132
226
  return settings.testpaths.some((root) => {
133
227
  const clean = root.replace(/^\.\//, "").replace(/\/$/, "");
134
- return clean === "." || clean === "" || path === clean || path.startsWith(`${clean}/`);
228
+ if (clean === "." || clean === "") return true;
229
+ // pytest expands each testpaths entry with glob.iglob(entry, recursive=True).
230
+ if (/[*?[]/.test(clean)) return globPrefixMatches(clean.split("/"), path.split("/"));
231
+ return path === clean || path.startsWith(`${clean}/`);
135
232
  });
136
233
  }
137
234
 
@@ -172,12 +269,24 @@ export function resolvePythonGraph(files: readonly string[], parsed: Record<stri
172
269
  return [candidate, ...inits];
173
270
  };
174
271
  const isPackageDir = (dir: string) => known.has(dir ? `${dir}/__init__.py` : "__init__.py");
272
+ // pytest's default `prepend` import mode puts the basedir on sys.path: the file's own directory when
273
+ // it is not in a package, otherwise the first directory above its package (the nearest ancestor
274
+ // without `__init__.py`). Undefined when the package reaches the repository root.
275
+ const basedirOf = (dir: string): string | undefined => {
276
+ let base = dir;
277
+ while (isPackageDir(base)) {
278
+ if (!base) return undefined;
279
+ base = posix.dirname(base) === "." ? "" : posix.dirname(base);
280
+ }
281
+ return base;
282
+ };
175
283
  for (const file of files) {
176
284
  const entry = parsed[file];
177
285
  if (!entry || entry.error) { blockers.push(`Python file could not be parsed (${entry?.error ?? "no result"}): ${file}`); continue; }
178
286
  if (entry.dynamic) blockers.push(`Python computed import in ${file}; full validation required`);
179
287
  const dir = posix.dirname(file) === "." ? "" : posix.dirname(file);
180
- const fileRoots = isPackageDir(dir) ? roots : [...roots, dir];
288
+ const basedir = basedirOf(dir);
289
+ const fileRoots = basedir === undefined || roots.includes(basedir) ? roots : [...roots, basedir];
181
290
  const add = (targets: string[] | undefined) => { for (const to of targets ?? []) edge(file, to); };
182
291
  for (const [module, level, names] of entry.imports ?? []) {
183
292
  if (level > 0) {
@@ -203,6 +312,16 @@ export function resolvePythonGraph(files: readonly string[], parsed: Record<stri
203
312
  }
204
313
  // pytest loads every conftest.py from the rootdir down to the test's directory first.
205
314
  if (tests.has(file)) {
315
+ // Plugins named by `-p` in addopts are imported before any test is collected.
316
+ for (const plugin of settings.plugins ?? []) {
317
+ const parts = plugin.split(".");
318
+ const target = roots.map((root) => moduleFiles(root, parts)).find(Boolean);
319
+ if (target) add(target);
320
+ else if (!plugin || firstParty.has(parts[0]!)) {
321
+ const blocker = `Unresolved pytest plugin in addopts: -p ${plugin}`;
322
+ if (!blockers.includes(blocker)) blockers.push(blocker);
323
+ }
324
+ }
206
325
  const segments = dir ? dir.split("/") : [];
207
326
  for (let depth = 0; depth <= segments.length; depth += 1) {
208
327
  const conftest = [...segments.slice(0, depth), "conftest.py"].join("/");
@@ -16,6 +16,7 @@ export interface CargoTarget {
16
16
  export interface CargoPackage {
17
17
  id: string;
18
18
  name: string;
19
+ version?: string;
19
20
  manifest_path: string;
20
21
  targets: CargoTarget[];
21
22
  source?: string | null;
@@ -124,7 +125,8 @@ export function parseCargoMetadata(output: string): CargoMetadata {
124
125
  if (!object(pkg) || typeof pkg.id !== "string" || !pkg.id || typeof pkg.name !== "string"
125
126
  || !/^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(pkg.name) || typeof pkg.manifest_path !== "string"
126
127
  || !isAbsolute(pkg.manifest_path) || !Array.isArray(pkg.targets) || !pkg.targets.length
127
- || (pkg.source !== undefined && pkg.source !== null && typeof pkg.source !== "string")) {
128
+ || (pkg.source !== undefined && pkg.source !== null && typeof pkg.source !== "string")
129
+ || (pkg.version !== undefined && typeof pkg.version !== "string")) {
128
130
  throw new Error("Invalid Cargo package metadata");
129
131
  }
130
132
  for (const target of pkg.targets) {
@@ -197,7 +199,7 @@ function completeRustInventory(root: string, files: ReadonlySet<string>, trees:
197
199
 
198
200
  /** A small lexer, not a Rust parser: ignore comments/strings, but never guess
199
201
  * a computed include. Nested comments and raw strings must not hide an input. */
200
- function rustInputs(source: string): { inputs: Array<{ path: string; code: boolean }>; paths: string[]; compiles: boolean; navigates: boolean; documentation: boolean } | undefined {
202
+ function rustInputs(source: string): { inputs: Array<{ path: string; code: boolean }>; paths: string[]; compiles: boolean; navigates: boolean; documentation: boolean; runsPrograms: boolean } | undefined {
201
203
  const tokens: Array<{ value: string; literal?: string }> = [];
202
204
  for (let i = 0; i < source.length;) {
203
205
  if (/\s/.test(source[i]!)) { i++; continue; }
@@ -212,7 +214,9 @@ function rustInputs(source: string): { inputs: Array<{ path: string; code: boole
212
214
  if (depth) return undefined;
213
215
  continue;
214
216
  }
215
- const raw = /^r(#{0,255})"/.exec(source.slice(i));
217
+ // Byte and C raw strings (`br"\"`, `cr#"say "hi""#`) take no escapes either; read as a `b`/`c`
218
+ // identifier and an ordinary string, a backslash or quote inside would hide the code after them.
219
+ const raw = /^[bc]?r(#{0,255})"/.exec(source.slice(i));
216
220
  if (raw) {
217
221
  const start = i + raw[0].length, end = source.indexOf(`"${raw[1]}`, start);
218
222
  if (end < 0) return undefined;
@@ -241,6 +245,7 @@ function rustInputs(source: string): { inputs: Array<{ path: string; code: boole
241
245
  const inputs: Array<{ path: string; code: boolean }> = [];
242
246
  const paths: string[] = [];
243
247
  let compiles = false;
248
+ let runsPrograms = false;
244
249
  const includeArguments = new Set<number>();
245
250
  for (let i = 0; i < tokens.length; i++) {
246
251
  if (tokens[i]!.value === "mod" && tokens[i + 1]?.value === "target" && tokens[i + 2]?.value === ";") return undefined;
@@ -266,6 +271,13 @@ function rustInputs(source: string): { inputs: Array<{ path: string; code: boole
266
271
  }
267
272
  if (tokens[i]!.value === "Command" && tokens[i + 1]?.value === ":" && tokens[i + 2]?.value === ":" && tokens[i + 3]?.value === "new"
268
273
  && tokens[i + 4]?.value === "(" && /^(?:cargo|rustc|rustdoc)(?:\.exe)?$|^cargo-/.test(tokens[i + 5]?.literal ?? "")) compiles = true;
274
+ // Any other program (a script, a shell, a tool) could read files no Rust edge shows. Running the
275
+ // package's own binary (`env!("CARGO_BIN_EXE_name")`) is Rust code Cargo already models. This is a
276
+ // token heuristic: clap's `Command::new("app")` counts too, which only fails closed.
277
+ if (tokens[i]!.value === "Command" && tokens[i + 1]?.value === ":" && tokens[i + 2]?.value === ":" && tokens[i + 3]?.value === "new"
278
+ && tokens[i + 4]?.value === "(" && !/^(?:cargo|rustc|rustdoc)(?:\.exe)?$|^cargo-/.test(tokens[i + 5]?.literal ?? "")
279
+ && !(tokens[i + 5]?.value === "env" && tokens[i + 6]?.value === "!" && tokens[i + 7]?.value === "(" && /^CARGO_BIN_EXE_/.test(tokens[i + 8]?.literal ?? ""))) runsPrograms = true;
280
+ if (["duct", "xshell", "subprocess"].includes(tokens[i]!.value) || (tokens[i]!.value === "cmd" && tokens[i + 1]?.value === "!")) runsPrograms = true;
269
281
  // `env!("CARGO")`, `env::var("RUSTC")` and similar name the toolchain a test is about to run.
270
282
  if (["CARGO", "RUSTC", "RUSTDOC", "RUSTC_WRAPPER"].includes(tokens[i]!.literal ?? "")) compiles = true;
271
283
  if (!["include", "include_str", "include_bytes"].includes(tokens[i]!.value) || tokens[i + 1]?.value !== "!") continue;
@@ -288,7 +300,7 @@ function rustInputs(source: string): { inputs: Array<{ path: string; code: boole
288
300
  });
289
301
  const navigates = navigatesUpward(tokens);
290
302
  // Code that climbs out of its crate can walk to README or docs without naming them.
291
- return { inputs, paths, compiles, navigates, documentation: documentation || navigates };
303
+ return { inputs, paths, compiles, navigates, documentation: documentation || navigates, runsPrograms };
292
304
  }
293
305
 
294
306
  /** Code that climbs out of its crate directory in code (`.parent()`, `.ancestors()`, `PathBuf::pop`,
@@ -307,6 +319,89 @@ function navigatesUpward(tokens: ReadonlyArray<{ value: string; literal?: string
307
319
  });
308
320
  }
309
321
 
322
+ /** Doc-comment words that keep a fenced block Rust (rustdoc's doctest attributes). Any other word
323
+ * (`text`, `toml`, `sh`, ...) makes the block another language unless `rust` is also given. */
324
+ const DOCTEST_ATTRIBUTE = /^(?:rust|ignore(?:-\S+)?|should_panic|no_run|compile_fail|edition\d{4}|standalone_crate|test_harness|allow_fail|E\d{4})$/;
325
+
326
+ /** Rustdoc compiles and runs the code blocks in doc comments (`///`, `//!`, `/** *\/`, `/*! *\/`)
327
+ * as doctests, from the crate directory. The input scan skips comments, so this returns the code of
328
+ * every block that may be Rust: fenced blocks with no other language and indented blocks, with
329
+ * rustdoc's hidden-line `# ` prefix removed. */
330
+ function doctestCode(source: string): string {
331
+ const code: string[] = [];
332
+ for (const group of docComments(source)) {
333
+ const indent = Math.min(...group.filter(line => line.trim()).map(line => /^\s*/.exec(line)![0].length));
334
+ let fence: string | undefined; let rust = false; let previousBlank = true; let indented = false;
335
+ for (const raw of group) {
336
+ const line = raw.slice(Number.isFinite(indent) ? indent : 0);
337
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
338
+ if (fence === undefined && marker) {
339
+ const words = marker[2]!.split(/[\s,{}.]+/).filter(Boolean);
340
+ fence = marker[1]!; rust = !words.length || words.includes("rust") || words.every(word => DOCTEST_ATTRIBUTE.test(word));
341
+ } else if (fence !== undefined && marker && marker[1]!.startsWith(fence) && !marker[2]!.trim()) fence = undefined;
342
+ else if (fence !== undefined) { if (rust) code.push(line.replace(/^\s*#(?: |$)/, "")); }
343
+ // An indented block (four spaces after a blank line) is a doctest too.
344
+ else if (/^ {4}/.test(line) && (previousBlank || indented)) { code.push(line.slice(4).replace(/^\s*#(?: |$)/, "")); indented = true; continue; }
345
+ if (line.trim()) indented = false;
346
+ previousBlank = !line.trim();
347
+ }
348
+ }
349
+ return code.join("\n");
350
+ }
351
+
352
+ /** The text of each doc comment in a file, as lines: a run of `///` or `//!` lines, or one `/** *\/`
353
+ * or `/*! *\/` block (leading `*` removed). Strings, character literals and plain comments are skipped
354
+ * the way the input scan skips them, so a `"/**"` glob or a commented-out `///` is not a doc comment. */
355
+ function docComments(source: string): string[][] {
356
+ const groups: string[][] = [];
357
+ let lineGroup: string[] | undefined; let lineGroupEnd = -1;
358
+ for (let i = 0; i < source.length;) {
359
+ if (source.startsWith("//", i)) {
360
+ const end = source.indexOf("\n", i) < 0 ? source.length : source.indexOf("\n", i);
361
+ const doc = /^\/\/(?:\/(?!\/)|!)(.*)$/.exec(source.slice(i, end).replace(/\r$/, ""));
362
+ if (doc) {
363
+ if (!lineGroup || !/^[ \t]*\r?\n[ \t]*$/.test(source.slice(lineGroupEnd, i))) groups.push(lineGroup = []);
364
+ lineGroup.push(doc[1]!); lineGroupEnd = end;
365
+ }
366
+ i = end; continue;
367
+ }
368
+ if (source.startsWith("/*", i)) {
369
+ const start = i; let depth = 1; i += 2;
370
+ while (i < source.length && depth) {
371
+ if (source.startsWith("/*", i)) { depth++; i += 2; }
372
+ else if (source.startsWith("*/", i)) { depth--; i += 2; }
373
+ else i++;
374
+ }
375
+ if (/^\/\*(?:\*(?![*/])|!)/.test(source.slice(start, start + 4))) {
376
+ const lines = source.slice(start + 3, depth ? i : i - 2).split(/\r?\n/);
377
+ const starred = lines.slice(1).filter(line => line.trim()).every(line => /^\s*\*/.test(line));
378
+ groups.push(starred ? lines.map((line, index) => index ? line.replace(/^\s*\*/, "") : line) : lines);
379
+ }
380
+ continue;
381
+ }
382
+ const raw = /^[bc]?r(#{0,255})"/.exec(source.slice(i, i + 260));
383
+ if (raw) { const end = source.indexOf(`"${raw[1]}`, i + raw[0].length); i = end < 0 ? source.length : end + raw[1]!.length + 1; continue; }
384
+ if (source[i] === '"') { for (i++; i < source.length && source[i] !== '"'; i++) if (source[i] === "\\") i++; i++; continue; }
385
+ const character = /^'(?:\\.|[^'\\\n])'/.exec(source.slice(i, i + 4));
386
+ if (character) { i += character[0].length; continue; }
387
+ const identifier = /^[A-Za-z0-9_]+/.exec(source.slice(i, i + 256));
388
+ i += identifier ? identifier[0].length : 1;
389
+ }
390
+ return groups;
391
+ }
392
+
393
+ /** The inputs of a Rust file's code and of its doctests. */
394
+ function rustSourceInputs(source: string): ReturnType<typeof rustInputs> {
395
+ const code = rustInputs(source);
396
+ const docs = code && rustInputs(doctestCode(source));
397
+ if (!code || !docs) return undefined;
398
+ const merged: Record<string, unknown> = { ...code, inputs: [...code.inputs, ...docs.inputs], paths: [...code.paths, ...docs.paths] };
399
+ // Each flag is set when either scan sets it. Combining them by key keeps that true for a flag
400
+ // rustInputs gains later (such as one #250 adds), instead of silently dropping the doctests' value.
401
+ for (const [key, value] of Object.entries(docs)) if (typeof value === "boolean") merged[key] = merged[key] === true || value;
402
+ return merged as NonNullable<ReturnType<typeof rustInputs>>;
403
+ }
404
+
310
405
  /** A string that names a file or directory rather than ordinary text. */
311
406
  function pathLike(value: string): boolean {
312
407
  if (!value || value.length > 4096 || /[\0\r\n]/.test(value)) return false;
@@ -338,6 +433,18 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
338
433
  result.blockers.push("Ambiguous Cargo workspace package names require full validation");
339
434
  return result;
340
435
  }
436
+ // `cargo test -p NAME` and `cargo tree -p NAME` stop with "specification is ambiguous" when a
437
+ // dependency has a member's name (an older release of the same crate, say). Name such a member
438
+ // NAME@VERSION, which Cargo accepts, or fall back when even that cannot tell them apart.
439
+ const specs = new Map<string, string>();
440
+ for (const pkg of members) {
441
+ const named = metadata.packages.filter(other => other.name === pkg.name);
442
+ if (named.length === 1) specs.set(pkg.id, pkg.name);
443
+ else if (pkg.version && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version) && named.filter(other => other.version === pkg.version).length === 1) {
444
+ specs.set(pkg.id, `${pkg.name}@${pkg.version}`);
445
+ } else result.blockers.push(`Cargo package ${pkg.name} has no unambiguous package specification; full validation required`);
446
+ }
447
+ const spec = (pkg: CargoPackage) => specs.get(pkg.id) ?? pkg.name;
341
448
  const packages: Array<{ pkg: CargoPackage; directory: string; manifest: string }> = [];
342
449
  for (const pkg of members) {
343
450
  const manifest = repositoryPath(root, pkg.manifest_path, known);
@@ -412,8 +519,14 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
412
519
  continue;
413
520
  }
414
521
  result.testFiles.push(path);
415
- result.testPackages[path] = pkg.name;
416
- result.rustTestTargets[path] = { name: target.name, kind };
522
+ result.testPackages[path] = spec(pkg);
523
+ // Plain `cargo test` builds and runs a target with `required-features` only when Cargo enabled
524
+ // those features for its package, and skips it silently otherwise. The planner keeps such a
525
+ // package whole (`-p name`, never `--test name`), so Cargo makes the same decision for the
526
+ // selected command as for the full run: the feature check below gives the package the full
527
+ // run's features.
528
+ const requiredFeatures = target["required-features"]?.length ? [...target["required-features"]].sort() : undefined;
529
+ result.rustTestTargets[path] = { name: target.name, kind, ...(requiredFeatures ? { requiredFeatures } : {}) };
417
530
  }
418
531
  }
419
532
  const moduleTrees = packages.flatMap(({ pkg }) => pkg.targets.map(target => resolvedPath(root, target.src_path)))
@@ -470,13 +583,10 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
470
583
  const anchor = anchors.get(id)!;
471
584
  for (const other of packages) if (other.manifest !== anchor) result.edges.push({ from: anchor, to: other.manifest, kind: "import" });
472
585
  }
473
- if (packages.some(({ pkg }) => pkg.targets.some(target => target["required-features"]?.length))) {
474
- result.blockers.push("Cargo targets requiring features need an explicitly supported test invocation; full validation required");
475
- }
476
586
  for (const source of result.sourcePaths.filter(path => path.endsWith(".rs"))) {
477
587
  const sourceOwner = owner(source);
478
588
  if (!sourceOwner) continue;
479
- const scanned = rustInputs(readFileSync(resolve(root, source), "utf8"));
589
+ const scanned = rustSourceInputs(readFileSync(resolve(root, source), "utf8"));
480
590
  if (scanned === undefined) {
481
591
  result.blockers.push(`Rust computed includes or path attributes require full validation: ${source}`);
482
592
  continue;
@@ -486,16 +596,21 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
486
596
  // file). Code that climbs out of its crate in code can reach any crate, like code that compiles.
487
597
  // Model these as dependencies of this crate instead of blocking the repository.
488
598
  if (scanned.documentation) (result.rustDocumentationReaders ??= []).push(source);
599
+ if (scanned.runsPrograms) result.rustRunsPrograms = true;
489
600
  const reached = new Set<string>();
490
601
  if (scanned.compiles || scanned.navigates) for (const other of packages) reached.add(other.manifest);
491
602
  for (const literal of scanned.paths) {
492
603
  const clean = literal.replace(/\\/g, "/").replace(/^(?:[A-Za-z]:)?\/+/, "");
493
604
  const glob = clean.search(/[*?[{]/);
494
605
  const prefix = glob < 0 ? clean : clean.slice(0, clean.lastIndexOf("/", glob) + 1);
495
- for (const base of new Set([sourceOwner.directory, dirname(source) === "." ? "" : dirname(source)])) {
606
+ // Also from the workspace root: rustc and proc macros run there, and `[env]` paths such as
607
+ // CARGO_WORKSPACE_DIR start there. From the root, only a path below it names a crate.
608
+ const bases = [sourceOwner.directory, dirname(source) === "." ? "" : dirname(source)];
609
+ for (const [index, base] of [...bases, ""].entries()) {
496
610
  const joined = posix.normalize(posix.join(base || ".", prefix || "."));
497
611
  if (joined === ".." || joined.startsWith("../")) continue;
498
612
  const rel = joined === "." ? "" : joined.replace(/\/+$/, "");
613
+ if (index === bases.length && !rel) continue;
499
614
  const inside = rel ? owner(rel) ?? owner(`${rel}/`) : packages.find(pkg => pkg.directory === "");
500
615
  if (inside) reached.add(inside.manifest);
501
616
  for (const other of packages) if (other.directory && (rel === "" || under(other.directory, rel) || other.directory === rel)) reached.add(other.manifest);
@@ -518,22 +633,24 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
518
633
  }
519
634
  }
520
635
  result.assetPaths = [...new Set(result.assetPaths)].sort();
636
+ result.rustCrateDirectories = [...new Set(packages.map(({ directory }) => directory))].sort();
637
+ result.rustRunsPrograms ??= false;
521
638
  // Selective commands must give every package the features the full invocation gives it. Cargo
522
639
  // resolves each tested crate alone and with its dependents (what a change to it selects); the
523
640
  // planner checks each selected set against those units.
524
641
  if (!cargoFeaturesVary(metadata)) result.rustFeatureCoverage = { deficits: {}, units: [] };
525
642
  else {
526
- const testedNames = packages.filter(({ pkg }) => tested.has(pkg.id)).map(({ pkg }) => pkg.name);
643
+ const testedNames = packages.filter(({ pkg }) => tested.has(pkg.id)).map(({ pkg }) => spec(pkg));
527
644
  const dependents = new Map<string, string[]>();
528
645
  for (const edge of result.edges) {
529
646
  if (edge.from.endsWith("Cargo.toml") && edge.to.endsWith("Cargo.toml") && edge.from !== edge.to) {
530
647
  dependents.set(edge.to, [...(dependents.get(edge.to) ?? []), edge.from]);
531
648
  }
532
649
  }
533
- const byManifest = new Map(packages.map(({ pkg, manifest }) => [manifest, pkg.name]));
650
+ const byManifest = new Map(packages.map(({ pkg, manifest }) => [manifest, spec(pkg)]));
534
651
  const units = new Map<string, string[]>();
535
652
  for (const { pkg, manifest } of packages) {
536
- if (tested.has(pkg.id)) units.set(pkg.name, [pkg.name]);
653
+ if (tested.has(pkg.id)) units.set(spec(pkg), [spec(pkg)]);
537
654
  const seen = new Set([manifest]); const pending = [manifest];
538
655
  while (pending.length) for (const next of dependents.get(pending.pop()!) ?? []) if (!seen.has(next)) { seen.add(next); pending.push(next); }
539
656
  const closure = [...seen].map(path => byManifest.get(path)).filter((name): name is string => name !== undefined && testedNames.includes(name)).sort();
@@ -568,11 +685,14 @@ function cargoFeatureResolver(repoPath: string): CargoFeatureResolver {
568
685
  /** Configuration keys that change how crates are compiled, which code is compiled or what runs the
569
686
  * tests. Aliases, registries, network, terminal, `[env]` and target-dir settings apply equally to
570
687
  * the selected and the full invocation, so they do not block. */
571
- const BUILD_CONFIG = /^\s*(?:build\s*\.\s*)?(?:rustflags|rustdocflags|target|rustc|rustdoc|rustc-wrapper|rustc-workspace-wrapper)\s*=|^\s*\[\s*(?:target|patch|unstable)\b|^\s*(?:target|patch|unstable)\s*\.|^\s*(?:paths|include)\s*=/m;
688
+ const BUILD_CONFIG = /^\s*(?:build\s*\.\s*)?(?:rustflags|rustdocflags|target|rustc|rustdoc|rustc-wrapper|rustc-workspace-wrapper)\s*=|^\s*\[\s*(?:target|patch|unstable)\b|^\s*(?:target|patch|unstable)\s*\.|^\s*(?:paths|include)\s*=|^\s*(?:build|patch|unstable)\s*=/m;
572
689
  const COMPILER_ENVIRONMENT = /^(?:RUSTFLAGS|RUSTDOCFLAGS|CARGO_ENCODED_RUST(?:DOC)?FLAGS|CARGO_BUILD_RUST(?:DOC)?FLAGS|CARGO_BUILD_TARGET|RUSTC|RUSTDOC|RUSTC_WRAPPER|RUSTC_WORKSPACE_WRAPPER|CARGO_BUILD_RUSTC(?:_WRAPPER|_WORKSPACE_WRAPPER)?|CARGO_BUILD_RUSTDOC|CARGO_TARGET_.+_(?:RUNNER|RUSTFLAGS))$/;
573
690
 
691
+ /** TOML spells the same key bare, quoted (`"build".rustflags`) or as an inline table
692
+ * (`build = { rustflags = [...] }`); Cargo reads them all. Unquote simple keys before matching, and
693
+ * treat a whole `build`, `patch` or `unstable` inline table as build-changing. */
574
694
  function changesBuild(path: string): boolean {
575
- try { return BUILD_CONFIG.test(readFileSync(path, "utf8")); }
695
+ try { return BUILD_CONFIG.test(readFileSync(path, "utf8").replace(/(["'])([A-Za-z0-9_-]+)\1/g, "$2")); }
576
696
  catch { return existsSync(path); }
577
697
  }
578
698
 
@@ -21,10 +21,16 @@ export interface AdapterContribution {
21
21
  testFiles: string[];
22
22
  testPackages: Record<string, string>;
23
23
  /** Cargo target roots; a lib/bin root represents the crate's unit tests. */
24
- rustTestTargets?: Record<string, { name: string; kind: "lib" | "bin" | "test" | "bench" | "example" }>;
24
+ rustTestTargets?: Record<string, { name: string; kind: "lib" | "bin" | "test" | "bench" | "example"; requiredFeatures?: string[] }>;
25
25
  /** Rust files that may read documentation: workspace build scripts, and sources naming a
26
26
  * documentation path in a string literal. */
27
27
  rustDocumentationReaders?: string[];
28
+ /** Directories of the workspace's Cargo packages ("" for a root package), for confining blockers on
29
+ * non-Rust files to the crate that owns them. */
30
+ rustCrateDirectories?: string[];
31
+ /** Whether any workspace Rust source starts an external program other than Cargo, rustc or the
32
+ * package's own binaries. Such a program could read any file, so nothing can be confined to a crate. */
33
+ rustRunsPrograms?: boolean;
28
34
  /** Packages whose Cargo features change when a tested crate runs without the rest of the full invocation. */
29
35
  rustFeatureCoverage?: { deficits: Record<string, string[]>; units: Array<{ crates: string[]; covers: string[] }> };
30
36
  executionEnv?: Record<string, string>;