@diffci.com/diffci 0.3.55 → 0.3.56

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 (51) hide show
  1. package/dist-client/src/client/cli.js +4 -3
  2. package/dist-client/src/client/context.d.ts +2 -0
  3. package/dist-client/src/client/context.js +19 -0
  4. package/dist-client/src/client/full-command.js +5 -2
  5. package/dist-client/src/client/gate.js +24 -10
  6. package/dist-client/src/client/job-summary.d.ts +1 -1
  7. package/dist-client/src/client/job-summary.js +2 -1
  8. package/dist-client/src/client/observe.js +1 -1
  9. package/dist-client/src/client/report.d.ts +7 -0
  10. package/dist-client/src/client/report.js +11 -0
  11. package/dist-client/src/client/workflow-guard.js +27 -6
  12. package/dist-client/src/client/workflow-templates.d.ts +11 -1
  13. package/dist-client/src/client/workflow-templates.js +43 -2
  14. package/node_modules/@diffci.com/core/README.md +4 -4
  15. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +20 -2
  16. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  17. package/node_modules/@diffci.com/core/dist/git/git-diff.js +43 -12
  18. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  19. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +51 -8
  20. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  21. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +111 -14
  22. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.d.ts +3 -1
  24. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js +44 -6
  25. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +158 -9
  27. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  28. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +3 -0
  29. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/graph.js +1 -1
  31. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/repo/impact.js +1 -1
  33. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.d.ts +11 -0
  35. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js +208 -0
  36. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js.map +1 -0
  37. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.d.ts +3 -0
  38. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js +2 -2
  39. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js.map +1 -1
  40. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +20 -2
  41. package/node_modules/@diffci.com/core/src/git/git-diff.ts +38 -12
  42. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +55 -8
  43. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +86 -14
  44. package/node_modules/@diffci.com/core/src/repo/adapters/rust-invocation.ts +44 -6
  45. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +129 -9
  46. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +3 -0
  47. package/node_modules/@diffci.com/core/src/repo/graph.ts +1 -1
  48. package/node_modules/@diffci.com/core/src/repo/impact.ts +1 -1
  49. package/node_modules/@diffci.com/core/src/repo/yarn-berry-lockfile.ts +178 -0
  50. package/node_modules/@diffci.com/core/src/repo/yarn-lockfile.ts +2 -2
  51. package/package.json +2 -2
@@ -65,7 +65,7 @@ export type PythonImport = [module: string, level: number, names: string[]];
65
65
  export interface PythonFileImports { imports?: PythonImport[]; dynamic?: boolean; error?: string }
66
66
 
67
67
  const EXCLUDED_DIRS = new Set([".venv", "venv", "env", ".env", ".tox", ".nox", "site-packages", "__pycache__", ".eggs", ".mypy_cache", ".pytest_cache", ".ruff_cache"]);
68
- const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", ".pytest.ini", "tox.ini", "conftest.py"];
68
+ const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.toml", ".pytest.toml", "pytest.ini", ".pytest.ini", "tox.ini", "conftest.py"];
69
69
 
70
70
  export function isPythonSource(path: string): boolean {
71
71
  return path.endsWith(".py") && !path.split("/").some((part) => EXCLUDED_DIRS.has(part) || part.endsWith(".egg-info"));
@@ -163,35 +163,107 @@ export function readPytestSettings(read: (path: string) => string | undefined):
163
163
  if (plugins.length) settings.plugins = plugins;
164
164
  } else settings[key] = values;
165
165
  };
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) {
166
+ const escape = (text: string) => text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
167
+ const isToml = (file: string) => file.endsWith(".toml");
168
+ // A table header may be indented and followed by a comment (`[pytest] # selection`). TOML also allows
169
+ // spaces inside the brackets and quoted keys (`[ pytest ]`, `[tool."pytest"]`), which this reader doesn't
170
+ // match: a header that only matches with spaces and quotes removed makes the file unreadable instead.
171
+ const section = (file: string, text: string, header: string): string | undefined => {
172
+ const comment = isToml(file) ? "#" : "#;";
173
+ return new RegExp(`^[ \\t]*\\[${escape(header)}\\][ \\t]*(?:[${comment}].*)?$([\\s\\S]*?)(?=^[ \\t]*\\[|(?![\\s\\S]))`, "m").exec(text)?.[1];
174
+ };
175
+ const looseHeader = (file: string, text: string, header: string): boolean =>
176
+ isToml(file) && [...text.matchAll(/^[ \t]*\[([^\]\n]*)\]/gm)].some((match) =>
177
+ match[1]!.replace(/[\s"']/g, "") === header && section(file, match[0]!.trim(), header) === undefined);
178
+ const hasEntries = (body: string) => /^[ \t]*[^\s#]/m.test(body);
179
+ const keyAt = (key: string) => `^[ \\t]*${key}[ \\t]*=`;
180
+ // A quoted or dotted key (`"testpaths" = …`, `ini_options.testpaths = …`) can't be told apart from the
181
+ // keys selection reads, so a TOML table with one is unreadable.
182
+ const unclassified = (body: string) => /^[ \t]*(?:"[^"\n]*"|'[^'\n]*'|[A-Za-z0-9_-]+)[ \t]*\./m.test(body) ||
183
+ /^[ \t]*(?:"[^"\n]*"|'[^'\n]*')[ \t]*=/m.test(body);
184
+ // pytest 9's native TOML mode (`pytest.toml`, `[tool.pytest]`): every key selection reads is a list of
185
+ // strings, and each `addopts` item is one argument. Any other type is an error in pytest, so it can't be read.
186
+ const readNative = (file: string, body: string) => {
187
+ if (unclassified(body)) { settings.unreadable = `${file} key DiffCI can't classify`; return settings; }
188
+ for (const key of keys) {
189
+ const array = new RegExp(`${keyAt(key)}[ \\t]*(?=\\[)`, "m").exec(body);
190
+ if (array) {
191
+ const values = readTomlStringArray(body, array.index + array[0].length);
192
+ if (values) apply(key, values);
193
+ else settings.unreadable = `${file} ${key}`;
194
+ } else if (new RegExp(keyAt(key), "m").test(body)) settings.unreadable = `${file} ${key}`;
195
+ }
196
+ return settings;
197
+ };
198
+ const order = [["pytest.toml", "pytest"], [".pytest.toml", "pytest"], ["pytest.ini", "pytest"], [".pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const;
199
+ // pytest before 9 ignores `pytest.toml`, `.pytest.toml` and `[tool.pytest]`, and uses the first of the
200
+ // other files that matches. When a native config wins and such a file also exists, the answer depends on
201
+ // the installed pytest, so it can't be read.
202
+ const olderPytestFile = (from: number): string | undefined => {
203
+ for (const [file, header] of order.slice(from)) {
204
+ const text = read(file);
205
+ if (text === undefined || file === ".pytest.toml") continue;
206
+ if (file === "pytest.ini" || file === ".pytest.ini" || section(file, text, header) !== undefined) return file;
207
+ }
208
+ return undefined;
209
+ };
210
+ const native = (file: string, body: string | undefined, index: number) => {
211
+ const older = olderPytestFile(index);
212
+ if (older) { settings.unreadable = `${file} is ignored before pytest 9, which reads ${older}`; return settings; }
213
+ return body === undefined ? settings : readNative(file, body);
214
+ };
215
+ // pytest's search order. `pytest.toml`, `.pytest.toml`, `pytest.ini` and `.pytest.ini` match even when
216
+ // empty or without their `[pytest]` table, and then pytest uses its defaults; the other files only match
217
+ // with their section. The first match wins and options are never merged.
218
+ for (const [index, [file, header]] of order.entries()) {
170
219
  const text = read(file);
171
220
  if (text === undefined) continue;
172
- const section = new RegExp(`^\\[${header.replace(/[.:]/g, "\\$&")}\\]\\s*$([\\s\\S]*?)(?=^\\[|(?![\\s\\S]))`, "m").exec(text);
173
- if (!section) {
221
+ if (looseHeader(file, text, "pytest") || looseHeader(file, text, "tool.pytest") || looseHeader(file, text, "tool.pytest.ini_options")) {
222
+ settings.unreadable = `${file} pytest table header DiffCI can't read`;
223
+ return settings;
224
+ }
225
+ if (file === "pytest.toml" || file === ".pytest.toml") {
226
+ const body = section(file, text, "pytest");
227
+ // pytest rejects options written above any table.
228
+ if (body === undefined && hasEntries(text.split(/^[ \t]*\[/m, 1)[0]!)) { settings.unreadable = `${file} options outside [pytest]`; return settings; }
229
+ return native(file, body, index + 1);
230
+ }
231
+ if (file === "pyproject.toml") {
232
+ // `[tool.pytest]` holds native TOML values, `[tool.pytest.ini_options]` INI-style ones. pytest refuses a
233
+ // file that sets both, and an `ini_options` key inside `[tool.pytest]` is a form this reader doesn't parse.
234
+ const nativeBody = section(file, text, "tool.pytest");
235
+ const ini = section(file, text, header);
236
+ if (nativeBody !== undefined && new RegExp(`^[ \\t]*ini_options[ \\t]*[.=]`, "m").test(nativeBody)) { settings.unreadable = `${file} [tool.pytest] ini_options`; return settings; }
237
+ if (nativeBody !== undefined && hasEntries(nativeBody)) {
238
+ if (ini !== undefined && hasEntries(ini)) { settings.unreadable = `${file} [tool.pytest] and [tool.pytest.ini_options]`; return settings; }
239
+ // An empty [tool.pytest.ini_options] beside it is what pytest 8 reads.
240
+ if (ini !== undefined) { settings.unreadable = `${file} [tool.pytest] is ignored before pytest 9, which reads [tool.pytest.ini_options]`; return settings; }
241
+ return native(file, nativeBody, index + 1);
242
+ }
243
+ }
244
+ const body = section(file, text, header);
245
+ if (body === undefined) {
174
246
  if (file === "pytest.ini" || file === ".pytest.ini") return settings;
175
247
  continue;
176
248
  }
177
- const body = section[1]!;
249
+ if (file === "pyproject.toml" && unclassified(body)) { settings.unreadable = `${file} key DiffCI can't classify`; return settings; }
178
250
  for (const key of keys) {
179
251
  if (file === "pyproject.toml") {
180
- const match = new RegExp(`^${key}\\s*=\\s*("[^"]*"|'[^']*')`, "m").exec(body);
181
- const array = new RegExp(`^${key}\\s*=\\s*(?=\\[)`, "m").exec(body);
252
+ const match = new RegExp(`${keyAt(key)}[ \\t]*("[^"]*"|'[^']*')`, "m").exec(body);
253
+ const array = new RegExp(`${keyAt(key)}[ \\t]*(?=\\[)`, "m").exec(body);
182
254
  // A multi-line string would otherwise match as an empty one. Its contents are read as one string;
183
255
  // 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);
256
+ const multiline = new RegExp(`${keyAt(key)}[ \\t]*("""|'{3})([\\s\\S]*?)\\1`, "m").exec(body);
185
257
  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}`;
258
+ else if (new RegExp(`${keyAt(key)}[ \\t]*(?:"""|'{3})`, "m").test(body)) settings.unreadable = `${file} ${key}`;
187
259
  else if (array) {
188
260
  const values = readTomlStringArray(body, array.index + array[0].length);
189
261
  if (values) apply(key, key === "addopts" ? values.flatMap(splitList) : values);
190
262
  else settings.unreadable = `${file} ${key}`;
191
263
  } else if (match) apply(key, splitList(match[1]!));
192
- else if (new RegExp(`^${key}\\s*=`, "m").test(body)) settings.unreadable = `${file} ${key}`;
264
+ else if (new RegExp(keyAt(key), "m").test(body)) settings.unreadable = `${file} ${key}`;
193
265
  } else {
194
- // INI values continue on indented lines.
266
+ // INI values continue on indented lines, so a key starts at the beginning of a line.
195
267
  const match = new RegExp(`^${key}\\s*=\\s*(.*(?:\\r?\\n[ \\t]+.*)*)`, "m").exec(body);
196
268
  if (match) apply(key, splitList(match[1]!));
197
269
  }
@@ -8,6 +8,11 @@ function record(value: unknown): value is Record<string, unknown> {
8
8
 
9
9
  const plain = (value: unknown): boolean => typeof value === "string" && value.trim() === "cargo test";
10
10
 
11
+ /** `--workspace` (or its old name `--all`) tests every member. That is plain `cargo test` exactly when
12
+ * plain `cargo test` already covers every member: a single crate, or a virtual workspace without
13
+ * `default-members`. The adapter says which. */
14
+ const wholeWorkspace = (value: unknown): boolean => typeof value === "string" && /^cargo test --(?:workspace|all)$/.test(value.trim());
15
+
11
16
  /** Steps that install a toolchain, restore caches or check out the code. They choose which compiler
12
17
  * runs, the same for the selected and the full command, but not which tests run or with what flags. */
13
18
  const SETUP_ACTION = /^(?:actions\/checkout|actions\/cache(?:\/restore)?|actions\/upload-artifact|Swatinem\/rust-cache|dtolnay\/rust-toolchain|actions-rust-lang\/setup-rust-toolchain|actions-rs\/toolchain)@[A-Za-z0-9._/-]+$/;
@@ -16,12 +21,44 @@ const SETUP_ACTION = /^(?:actions\/checkout|actions\/cache(?:\/restore)?|actions
16
21
  * per step: chaining, substitution or redirection could hide another invocation. */
17
22
  const NON_TEST_COMMAND = /^(?:cargo (?:build|check|clippy|fmt|doc)|rustup (?:component|target|toolchain|default|show|update))(?: [A-Za-z0-9_.,:=@+/-]+)*$/;
18
23
 
24
+ /** rustup commands chained with `&&` (`rustup default stable && rustup update --no-self-update`),
25
+ * where an argument may be a matrix value. Only rustup, so the chain cannot hide a test run. */
26
+ const RUSTUP_ARGUMENT = String.raw`(?:[A-Za-z0-9_.,:=@+/-]+|\$\{\{ ?matrix\.([A-Za-z0-9_-]+) ?\}\})`;
27
+ const RUSTUP_COMMAND = new RegExp(String.raw`^rustup (?:component|target|toolchain|default|show|update)(?: ${RUSTUP_ARGUMENT})*$`);
28
+
29
+ /** A matrix value is pasted into the script as text, so each one a rustup step uses must be a plain
30
+ * toolchain-like word, in the matrix and in every `include` entry. */
31
+ function plainMatrixValues(strategy: unknown, key: string): boolean {
32
+ if (!record(strategy) || !record(strategy.matrix)) return false;
33
+ const word = (value: unknown) => (typeof value === "string" || typeof value === "number") && /^[A-Za-z0-9_.-]+$/.test(String(value));
34
+ const values = strategy.matrix[key];
35
+ const include = strategy.matrix.include;
36
+ if (include !== undefined && (!Array.isArray(include) || include.some(entry => !record(entry) || (key in entry && !word(entry[key]))))) return false;
37
+ if (values === undefined) return Array.isArray(include) && include.some(entry => record(entry) && key in entry);
38
+ return Array.isArray(values) && values.length > 0 && values.every(word);
39
+ }
40
+
41
+ function setupCommand(run: string, strategy: unknown): boolean {
42
+ if (NON_TEST_COMMAND.test(run)) return true;
43
+ const parts = run.split(" && ");
44
+ return parts.every(part => {
45
+ if (!RUSTUP_COMMAND.test(part)) return false;
46
+ return [...part.matchAll(/\$\{\{ ?matrix\.([A-Za-z0-9_-]+) ?\}\}/g)].every(match => plainMatrixValues(strategy, match[1]!));
47
+ });
48
+ }
49
+
19
50
  /** Environment that changes output or retries, never what is compiled or tested. */
20
- const NEUTRAL_ENV = new Set(["CARGO_TERM_COLOR", "CARGO_INCREMENTAL", "CARGO_NET_RETRY", "CARGO_NET_GIT_FETCH_WITH_CLI",
51
+ const NEUTRAL_ENV = new Set(["CARGO_TERM_COLOR", "CARGO_TERM_VERBOSE", "CARGO_INCREMENTAL", "CARGO_NET_RETRY", "CARGO_NET_GIT_FETCH_WITH_CLI",
21
52
  "CARGO_REGISTRIES_CRATES_IO_PROTOCOL", "RUST_BACKTRACE", "RUSTUP_MAX_RETRIES", "CI"]);
22
53
 
54
+ /** `RUSTFLAGS: -Dwarnings` (and the same for rustdoc) turns warnings into errors. It changes neither
55
+ * what is compiled nor which tests run, and applies equally to the selected and the full command.
56
+ * Any other flag (cfg, codegen, target features, sanitizers) still makes the evidence advisory. */
57
+ const DENY_WARNINGS = /^\s*(?:(?:-D ?warnings|--deny[= ]warnings)\s*)+$/;
58
+
23
59
  const neutralEnv = (value: unknown): boolean => value === undefined || record(value)
24
- && Object.entries(value).every(([key, setting]) => NEUTRAL_ENV.has(key) && ["string", "number", "boolean"].includes(typeof setting) && !String(setting).includes("${{"));
60
+ && Object.entries(value).every(([key, setting]) => ["string", "number", "boolean"].includes(typeof setting) && !String(setting).includes("${{")
61
+ && (NEUTRAL_ENV.has(key) || ["RUSTFLAGS", "RUSTDOCFLAGS"].includes(key) && DENY_WARNINGS.test(String(setting))));
25
62
 
26
63
  /** Workflow and job keys with no effect on how a step's command runs. */
27
64
  const WORKFLOW_KEYS = new Set(["name", "run-name", "on", "true", "permissions", "concurrency", "env", "jobs"]);
@@ -31,8 +68,9 @@ const TEST_STEP_KEYS = new Set(["name", "id", "run", "env", "timeout-minutes"]);
31
68
 
32
69
  /** Evidence for the one invocation whose flags and execution context we can reproduce.
33
70
  * Do not turn a Cargo manifest, a wrapper or a feature-specific CI run into plain cargo test. */
34
- export function rustTestInvocation(repoPath: string, files: readonly string[]): "cargo test" | undefined {
71
+ export function rustTestInvocation(repoPath: string, files: readonly string[], options: { allMembersTested?: boolean } = {}): "cargo test" | undefined {
35
72
  let found = false;
73
+ const testCommand = (value: unknown) => plain(value) || options.allMembersTested === true && wholeWorkspace(value);
36
74
  if (files.includes("package.json")) {
37
75
  try {
38
76
  const manifest: unknown = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8"));
@@ -41,7 +79,7 @@ export function rustTestInvocation(repoPath: string, files: readonly string[]):
41
79
  if (!record(manifest.scripts)) return undefined;
42
80
  // A plain command under an unrelated script name is not evidence that the actual
43
81
  // test entrypoint has the same semantics. Unknown scripts may wrap additional suites.
44
- if (!plain(manifest.scripts.test) || Object.values(manifest.scripts).some(script => !plain(script))) return undefined;
82
+ if (!testCommand(manifest.scripts.test) || Object.values(manifest.scripts).some(script => !testCommand(script))) return undefined;
45
83
  if (Object.keys(manifest.scripts).some(name => /^(?:pre|post)/.test(name))) return undefined;
46
84
  found = true;
47
85
  }
@@ -61,11 +99,11 @@ export function rustTestInvocation(repoPath: string, files: readonly string[]):
61
99
  for (const step of job.steps) {
62
100
  if (!record(step)) return undefined;
63
101
  if ("run" in step) {
64
- if (plain(step.run)) {
102
+ if (testCommand(step.run)) {
65
103
  // The test step itself runs unconditionally, in the checkout root, with the default shell.
66
104
  if (Object.keys(step).some(key => !TEST_STEP_KEYS.has(key)) || !neutralEnv(step.env)) return undefined;
67
105
  found = true;
68
- } else if (typeof step.run !== "string" || !NON_TEST_COMMAND.test(step.run.trim())
106
+ } else if (typeof step.run !== "string" || !setupCommand(step.run.trim(), job.strategy)
69
107
  || Object.keys(step).some(key => !["name", "id", "run", "env", "if", "timeout-minutes", "continue-on-error"].includes(key)) || !neutralEnv(step.env)) {
70
108
  // Wrappers, nextest, cargo make, just, other `cargo test` flags and unknown scripts are
71
109
  // not reproduced, before or after the test and in any job.
@@ -199,7 +199,7 @@ function completeRustInventory(root: string, files: ReadonlySet<string>, trees:
199
199
 
200
200
  /** A small lexer, not a Rust parser: ignore comments/strings, but never guess
201
201
  * a computed include. Nested comments and raw strings must not hide an input. */
202
- function rustInputs(source: string): { inputs: Array<{ path: string; code: boolean }>; paths: string[]; compiles: boolean; navigates: boolean; documentation: boolean; runsPrograms: boolean } | undefined {
202
+ function rustInputs(source: string): { inputs: Array<{ path: string; code: boolean; module?: string[] }>; paths: string[]; compiles: boolean; navigates: boolean; documentation: boolean; runsPrograms: boolean } | undefined {
203
203
  const tokens: Array<{ value: string; literal?: string }> = [];
204
204
  for (let i = 0; i < source.length;) {
205
205
  if (/\s/.test(source[i]!)) { i++; continue; }
@@ -242,24 +242,54 @@ function rustInputs(source: string): { inputs: Array<{ path: string; code: boole
242
242
  // dependency edge cannot see is code that reaches another crate's modelled Rust inputs at run or
243
243
  // build time. Report literal paths (the caller checks which crates they reach) and Cargo/rustc
244
244
  // invocations; ordinary identifiers such as `fs`, `process`, `unsafe` or `metadata` are not inputs.
245
- const inputs: Array<{ path: string; code: boolean }> = [];
245
+ const inputs: Array<{ path: string; code: boolean; module?: string[] }> = [];
246
+ // Inline `mod name { ... }` blocks open around each token, for `#[path]` (null: any other brace).
247
+ const blocks: Array<string | null> = [];
246
248
  const paths: string[] = [];
247
249
  let compiles = false;
248
250
  let runsPrograms = false;
249
251
  const includeArguments = new Set<number>();
250
252
  for (let i = 0; i < tokens.length; i++) {
251
253
  if (tokens[i]!.value === "mod" && tokens[i + 1]?.value === "target" && tokens[i + 2]?.value === ";") return undefined;
254
+ if (tokens[i]!.value === "{") blocks.push(tokens[i - 2]?.value === "mod" && /^[A-Za-z_]/.test(tokens[i - 1]?.value ?? "") ? tokens[i - 1]!.value : null);
255
+ if (tokens[i]!.value === "}") blocks.pop();
252
256
  if (tokens[i]!.value === "#") {
253
257
  let j = i + 1;
254
258
  if (tokens[j]?.value === "!") j++;
255
259
  if (tokens[j]?.value === "[") {
256
260
  let depth = 1;
261
+ const paths: string[] = [];
257
262
  for (j++; j < tokens.length && depth; j++) {
258
263
  if (tokens[j]!.value === "[") depth++;
259
264
  if (tokens[j]!.value === "]") depth--;
260
- if (tokens[j]!.value === "path" && tokens[j + 1]?.value === "=") return undefined;
265
+ if (tokens[j]!.value === "path" && tokens[j + 1]?.value === "=") {
266
+ // `#[path = "x.rs"]` or `#[cfg_attr(pred, path = "x.rs")]` with a plain literal.
267
+ const literal = tokens[j + 2]?.literal;
268
+ if (tokens[i + 1]?.value === "!" || !["[", ","].includes(tokens[j - 1]?.value ?? "") || literal === undefined
269
+ || !["]", ",", ")"].includes(tokens[j + 3]?.value ?? "") || /[\0\r\n]/.test(literal)) return undefined;
270
+ paths.push(literal);
271
+ }
261
272
  }
262
273
  if (depth) return undefined;
274
+ if (paths.length) {
275
+ // Only on a file module (`mod name;`), after any other attributes and visibility: on an
276
+ // inline module the path would move every module declared inside it.
277
+ let k = j;
278
+ for (;;) {
279
+ if (tokens[k]?.value === "#" && tokens[k + 1]?.value === "[") {
280
+ let nested = 1;
281
+ for (k += 2; k < tokens.length && nested; k++) nested += tokens[k]!.value === "[" ? 1 : tokens[k]!.value === "]" ? -1 : 0;
282
+ } else if (tokens[k]?.value === "pub" && tokens[k + 1]?.value === "(") {
283
+ k = tokens.findIndex((token, index) => index > k && token.value === ")") + 1;
284
+ if (!k) return undefined;
285
+ } else if (tokens[k]?.value === "pub") k++;
286
+ else break;
287
+ }
288
+ if (tokens[k]?.value !== "mod" || !/^[A-Za-z_]/.test(tokens[k + 1]?.value ?? "") || tokens[k + 2]?.value !== ";") return undefined;
289
+ const module = blocks.filter((name): name is string => name !== null);
290
+ if (blocks.length !== module.length) return undefined;
291
+ for (const path of paths) inputs.push({ path, code: true, module });
292
+ }
263
293
  }
264
294
  }
265
295
  if (tokens[i]!.value === "use") {
@@ -429,6 +459,7 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
429
459
  const defaults = metadata.workspace_default_members;
430
460
  if (!defaults) result.blockers.push("Cargo metadata without default workspace members requires full validation; use Cargo 1.71 or later");
431
461
  const tested = new Set(defaults ?? []);
462
+ result.rustAllMembersTested = defaults !== undefined && metadata.workspace_members.every(id => tested.has(id));
432
463
  if (new Set(members.map(pkg => pkg.name)).size !== members.length) {
433
464
  result.blockers.push("Ambiguous Cargo workspace package names require full validation");
434
465
  return result;
@@ -465,7 +496,16 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
465
496
  // package outside the workspace appears, no member depends on these crates: they are fixtures or
466
497
  // excluded crates. Their files stay unmodelled, so changing one keeps the full suite (impact.ts)
467
498
  // without blocking changes elsewhere. Otherwise the repository-wide fallback stays.
468
- const localDependencyOutside = metadata.packages.some(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null));
499
+ // Local path packages that are not workspace members. Inside the repository they are unmodelled
500
+ // boundaries like fixture crates: a change to one keeps the full suite, and dependency edges
501
+ // through them are followed below. Outside the repository their changes are invisible to the diff.
502
+ const localNonMembers = metadata.packages.filter(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null));
503
+ const localInside = new Map<string, string>();
504
+ for (const pkg of localNonMembers) {
505
+ const manifest = repositoryPath(root, pkg.manifest_path, known);
506
+ if (manifest && /(?:^|\/)Cargo\.toml$/.test(manifest) && manifest !== "Cargo.toml" && unmodeledManifests.includes(manifest)) localInside.set(pkg.id, manifest);
507
+ }
508
+ const localDependencyOutside = localNonMembers.some(pkg => !localInside.has(pkg.id));
469
509
  const unmodeledBoundary = (file: string) => !localDependencyOutside
470
510
  && unmodeledManifests.some(manifest => under(file, manifest.slice(0, -"/Cargo.toml".length)));
471
511
  if (unmodeledManifests.length && localDependencyOutside) result.blockers.push(`Cargo manifests outside workspace membership require full validation: ${unmodeledManifests.join(", ")}`);
@@ -532,6 +572,9 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
532
572
  const moduleTrees = packages.flatMap(({ pkg }) => pkg.targets.map(target => resolvedPath(root, target.src_path)))
533
573
  .filter((path): path is string => path !== undefined).map(path => dirname(path) === "." ? "" : dirname(path));
534
574
  if (!completeRustInventory(root, known, moduleTrees)) result.blockers.push("Incomplete Rust source inventory or symlinked inputs require full validation");
575
+ // Crate roots, for `#[path]` inside inline modules; directories of `#[path]` modules, checked below.
576
+ const targetRoots = new Set(packages.flatMap(({ pkg }) => pkg.targets.map(target => resolvedPath(root, target.src_path))));
577
+ const pathModuleTrees: string[] = [];
535
578
  result.sourcePaths = [...new Set(result.sourcePaths)].sort();
536
579
  result.testFiles.sort();
537
580
  if (!result.testFiles.length) result.blockers.push("Cargo metadata found no supported test targets");
@@ -546,6 +589,46 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
546
589
  const anchor = owner(file)?.manifest;
547
590
  if (anchor && anchor !== file) result.edges.push({ from: anchor, to: file, kind: "import" }, { from: file, to: anchor, kind: "import" });
548
591
  }
592
+ // Every in-repository local package that is not a workspace member (a vendored or excluded
593
+ // "bridge" crate) is scanned up front, whether or not a member reaches it. Its build scripts and
594
+ // documentation readers count as readers, as members' do, so a docs change keeps the full suite;
595
+ // code that runs programs turns off crate scoping; and code that could read other crates' files
596
+ // makes the members that reach it depend on every workspace crate (below). What cannot be scanned
597
+ // counts as all three.
598
+ const bridgeOpaque = new Map<string, boolean>();
599
+ for (const [id, manifest] of localInside) {
600
+ const directory = manifest.slice(0, -"/Cargo.toml".length);
601
+ const pkg = localNonMembers.find(candidate => candidate.id === id)!;
602
+ const bridgeRoots = new Set(pkg.targets.map(target => resolvedPath(root, target.src_path)));
603
+ let isOpaque = false;
604
+ for (const target of pkg.targets.filter(target => target.kind.includes("custom-build"))) {
605
+ isOpaque = true;
606
+ (result.rustDocumentationReaders ??= []).push(repositoryPath(root, target.src_path, known) ?? manifest);
607
+ }
608
+ for (const file of context.files.filter(file => file.endsWith(".rs") && under(file, directory))) {
609
+ let scanned: ReturnType<typeof rustInputs>;
610
+ try { scanned = rustInputs(readFileSync(resolve(root, file), "utf8")); } catch { scanned = undefined; }
611
+ if (!scanned) {
612
+ isOpaque = true;
613
+ (result.rustDocumentationReaders ??= []).push(file);
614
+ result.rustRunsPrograms = true;
615
+ continue;
616
+ }
617
+ if (scanned.documentation) (result.rustDocumentationReaders ??= []).push(file);
618
+ if (scanned.runsPrograms) result.rustRunsPrograms = true;
619
+ // `#[path]` is relative to the file's directory, and inside inline modules to their names as
620
+ // well, which is only resolvable from a crate root or mod.rs (as for members, below).
621
+ const modRs = bridgeRoots.has(file) || /(?:^|\/)mod\.rs$/.test(file);
622
+ if (scanned.compiles || scanned.navigates || scanned.documentation || scanned.paths.length > 0
623
+ || scanned.inputs.some(input => {
624
+ if (input.module?.length && !modRs) return true;
625
+ const base = input.module ? posix.join(dirname(file), ...input.module) : dirname(file);
626
+ const path = repositoryPath(root, resolve(root, base, input.path), known);
627
+ return !path || !under(path, directory);
628
+ })) isOpaque = true;
629
+ }
630
+ bridgeOpaque.set(id, isOpaque);
631
+ }
549
632
  // Cargo resolves all target platforms unless --filter-platform is supplied.
550
633
  // --all-features below unions optional dependencies too; cfg(feature) code
551
634
  // stays crate-granular and does not itself make the graph unsafe.
@@ -557,21 +640,42 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
557
640
  || metadata.workspace_members.some(id => !nodes.some(node => node.id === id))) {
558
641
  result.blockers.push("Cargo dependency resolution is missing or incomplete; full validation required");
559
642
  } else {
643
+ // A member can depend on another member through packages outside the workspace (a local path
644
+ // package that itself depends on a member, or a `[patch]`ed crate). Follow dependencies through
645
+ // non-members until they reach members. An in-repository local package whose own code could
646
+ // read other crates' files (a build script, Cargo or program runs, climbing out of its
647
+ // directory, path literals or includes) makes the member depend on every workspace crate.
648
+ const byId = new Map(nodes.map(node => [node.id, node]));
649
+ const opaque = new Map([...localInside.keys()].map(id => [id, bridgeOpaque.get(id) === true]));
650
+ const opaqueLocal = (id: string) => opaque.get(id) === true;
560
651
  for (const node of nodes) {
561
652
  const anchor = anchors.get(node.id);
562
653
  if (!anchor) continue;
563
- for (const dependency of node.dependencies) {
654
+ const reached = new Set<string>();
655
+ let everything = false;
656
+ const seen = new Set<string>([node.id]);
657
+ const pending = [...node.dependencies];
658
+ while (pending.length) {
659
+ const dependency = pending.pop()!;
660
+ if (seen.has(dependency)) continue;
661
+ seen.add(dependency);
564
662
  const target = anchors.get(dependency);
565
- if (target && target !== anchor) result.edges.push({ from: anchor, to: target, kind: "import" });
663
+ if (target) { reached.add(target); continue; }
664
+ if (opaqueLocal(dependency)) everything = true;
665
+ pending.push(...(byId.get(dependency)?.dependencies ?? []));
566
666
  }
667
+ if (everything) for (const other of packages) reached.add(other.manifest);
668
+ reached.delete(anchor);
669
+ for (const target of reached) result.edges.push({ from: anchor, to: target, kind: "import" });
567
670
  }
568
671
  }
569
672
  // Registry and Git dependencies are locked and immutable unless Cargo.lock changes, and a
570
673
  // Cargo.lock change keeps the full suite. Their build scripts and procedural macros run the same
571
674
  // code for the selected and the full invocation; anything they read from this repository outside
572
675
  // modelled Rust sources is a changed path that keeps the full suite. A local path dependency that
573
- // is not a workspace member has no modelled ownership, so it still blocks the repository.
574
- const localOutside = metadata.packages.filter(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null));
676
+ // is not a workspace member and lives outside the repository can change without the diff showing it,
677
+ // so it still blocks the repository; one inside the repository is an unmodelled boundary (above).
678
+ const localOutside = localNonMembers.filter(pkg => !localInside.has(pkg.id));
575
679
  if (localOutside.length) {
576
680
  result.blockers.push(`Local Cargo path dependencies outside the workspace require full validation: ${localOutside.map(pkg => pkg.name).sort().join(", ")}`);
577
681
  }
@@ -619,7 +723,15 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
619
723
  reached.delete(sourceOwner.manifest);
620
724
  for (const manifest of reached) result.edges.push({ from: sourceOwner.manifest, to: manifest, kind: "import" });
621
725
  for (const input of scanned.inputs) {
622
- const path = repositoryPath(root, resolve(root, dirname(source), input.path), known);
726
+ // A `#[path]` is relative to the file's directory; inside inline modules, also to their
727
+ // names, below the file's stem unless it is a crate root or mod.rs.
728
+ const modRs = targetRoots.has(source) || /(?:^|\/)mod\.rs$/.test(source);
729
+ if (input.module?.length && !modRs) {
730
+ result.blockers.push(`Rust computed includes or path attributes require full validation: ${source}`);
731
+ continue;
732
+ }
733
+ const base = input.module ? posix.join(dirname(source), ...input.module) : dirname(source);
734
+ const path = repositoryPath(root, resolve(root, base, input.path), known);
623
735
  if (!path || owner(path)?.pkg.id !== sourceOwner.pkg.id) {
624
736
  result.blockers.push(`Rust include outside its crate or unavailable requires full validation: ${source}`);
625
737
  continue;
@@ -628,10 +740,18 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
628
740
  result.blockers.push(`Rust include code with a non-Rust extension requires full validation: ${source}`);
629
741
  continue;
630
742
  }
743
+ if (input.module) {
744
+ // Module source of the same crate: already a source of it. What it declares is looked up
745
+ // from its own directory, so that tree must be complete too.
746
+ pathModuleTrees.push(dirname(path) === "." ? "" : dirname(path));
747
+ result.edges.push({ from: source, to: path, kind: "import" });
748
+ continue;
749
+ }
631
750
  if (!result.sourcePaths.includes(path)) result.assetPaths.push(path);
632
751
  result.edges.push({ from: source, to: path, kind: "asset" });
633
752
  }
634
753
  }
754
+ if (pathModuleTrees.length && !completeRustInventory(root, known, pathModuleTrees)) result.blockers.push("Incomplete Rust source inventory or symlinked inputs require full validation");
635
755
  result.assetPaths = [...new Set(result.assetPaths)].sort();
636
756
  result.rustCrateDirectories = [...new Set(packages.map(({ directory }) => directory))].sort();
637
757
  result.rustRunsPrograms ??= false;
@@ -31,6 +31,9 @@ export interface AdapterContribution {
31
31
  /** Whether any workspace Rust source starts an external program other than Cargo, rustc or the
32
32
  * package's own binaries. Such a program could read any file, so nothing can be confined to a crate. */
33
33
  rustRunsPrograms?: boolean;
34
+ /** Cargo's default workspace members cover every member (so `--workspace`/`--all` is equivalent to
35
+ * plain `cargo test`). Missing evidence is deliberately false. */
36
+ rustAllMembersTested?: boolean;
34
37
  /** Packages whose Cargo features change when a tested crate runs without the rest of the full invocation. */
35
38
  rustFeatureCoverage?: { deficits: Record<string, string[]>; units: Array<{ crates: string[]; covers: string[] }> };
36
39
  executionEnv?: Record<string, string>;
@@ -1127,7 +1127,7 @@ export async function buildDependencyGraph(
1127
1127
  profile.rustTestTargets = { ...rustContribution.rustTestTargets };
1128
1128
  profile.rustSources = [...new Set(rustContribution.sourcePaths)].sort();
1129
1129
  profile.rustAssets = [...new Set(rustContribution.assetPaths)].sort();
1130
- profile.rustTestInvocation = rustTestInvocation(repoPath, files);
1130
+ profile.rustTestInvocation = rustTestInvocation(repoPath, files, { allMembersTested: rustContribution.rustAllMembersTested });
1131
1131
  if (rustContribution.rustFeatureCoverage) profile.rustFeatureCoverage = rustContribution.rustFeatureCoverage;
1132
1132
  profile.rustDocumentationReaders = [...new Set(rustContribution.rustDocumentationReaders ?? [])].sort();
1133
1133
  }
@@ -935,7 +935,7 @@ export class ImpactAnalyzer {
935
935
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!;
936
936
  };
937
937
  if (yarnCandidates) {
938
- // Classic can hoist transitive packages that repository code imports without declaring them.
938
+ // Yarn's node-modules linkers can hoist packages that repository code imports without declaring them.
939
939
  // All-root widening covers peers, but cannot attribute these additional importers to a root.
940
940
  const undeclared = [...new Set(graphResult.references.filter((ref) => ref.resolution === "external-package")
941
941
  .map((ref) => packageRoot(ref.specifier)).filter((name) => !packages.includes(name)))].sort();