@diffci.com/diffci 0.3.48 → 0.3.49

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 (47) hide show
  1. package/node_modules/@diffci.com/core/README.md +1 -1
  2. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  3. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +2 -1
  4. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  5. package/node_modules/@diffci.com/core/dist/git/git-diff.js +3 -1
  6. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  7. package/node_modules/@diffci.com/core/dist/planner/rust-command.d.ts +5 -0
  8. package/node_modules/@diffci.com/core/dist/planner/rust-command.js +92 -0
  9. package/node_modules/@diffci.com/core/dist/planner/rust-command.js.map +1 -0
  10. package/node_modules/@diffci.com/core/dist/planner/test-command.js +3 -0
  11. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  12. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js +5 -3
  13. package/node_modules/@diffci.com/core/dist/repo/adapters/index.js.map +1 -1
  14. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.d.ts +3 -0
  15. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js +97 -0
  16. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js.map +1 -0
  17. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.d.ts +51 -1
  18. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +528 -16
  19. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +11 -0
  21. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  22. package/node_modules/@diffci.com/core/dist/repo/graph.js +31 -5
  23. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  24. package/node_modules/@diffci.com/core/dist/repo/impact.js +45 -2
  25. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  26. package/node_modules/@diffci.com/core/dist/repo/runner-setup-files.d.ts +11 -0
  27. package/node_modules/@diffci.com/core/dist/repo/runner-setup-files.js +181 -0
  28. package/node_modules/@diffci.com/core/dist/repo/runner-setup-files.js.map +1 -0
  29. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +1 -0
  30. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +4 -3
  31. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  32. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +13 -0
  33. package/node_modules/@diffci.com/core/package.json +1 -0
  34. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +2 -1
  35. package/node_modules/@diffci.com/core/src/git/git-diff.ts +3 -1
  36. package/node_modules/@diffci.com/core/src/planner/rust-command.ts +89 -0
  37. package/node_modules/@diffci.com/core/src/planner/test-command.ts +2 -0
  38. package/node_modules/@diffci.com/core/src/repo/adapters/index.ts +5 -3
  39. package/node_modules/@diffci.com/core/src/repo/adapters/rust-invocation.ts +87 -0
  40. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +447 -16
  41. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +5 -0
  42. package/node_modules/@diffci.com/core/src/repo/graph.ts +29 -5
  43. package/node_modules/@diffci.com/core/src/repo/impact.ts +43 -2
  44. package/node_modules/@diffci.com/core/src/repo/runner-setup-files.ts +164 -0
  45. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +5 -3
  46. package/node_modules/@diffci.com/core/src/repo/types.ts +7 -0
  47. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { dirname, isAbsolute, relative, resolve } from "node:path";
2
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, posix, relative, resolve } from "node:path";
4
5
  import { contribution, type AdapterContext, type AdapterContribution, type RepositoryAdapter } from "./types.js";
5
6
 
6
7
  export interface CargoTarget {
@@ -9,6 +10,7 @@ export interface CargoTarget {
9
10
  src_path: string;
10
11
  test: boolean;
11
12
  doctest: boolean;
13
+ "required-features"?: string[];
12
14
  }
13
15
 
14
16
  export interface CargoPackage {
@@ -16,12 +18,91 @@ export interface CargoPackage {
16
18
  name: string;
17
19
  manifest_path: string;
18
20
  targets: CargoTarget[];
21
+ source?: string | null;
22
+ dependencies?: Array<{ name: string; features: string[]; uses_default_features: boolean }>;
23
+ features?: Record<string, string[]>;
19
24
  }
20
25
 
21
26
  export interface CargoMetadata {
22
27
  packages: CargoPackage[];
23
28
  workspace_members: string[];
29
+ /** The members plain `cargo test` at the root builds and tests (root package or `default-members`). */
30
+ workspace_default_members?: string[];
24
31
  workspace_root: string;
32
+ resolve?: { nodes: Array<{ id: string; dependencies: string[] }> } | null;
33
+ }
34
+
35
+ /** Cargo's own feature resolution (`cargo tree`, format `{p}|{f}`) for the full invocation and for
36
+ * sets of tested crates. Cargo decides features, including resolver 2 and host/target splits. */
37
+ export interface CargoFeatureEvidence {
38
+ workspace: string;
39
+ units: Array<{ crates: string[]; tree: string }>;
40
+ }
41
+
42
+ /** Runs Cargo for each set of crates; undefined when any run fails. */
43
+ export type CargoFeatureResolver = (units: string[][]) => CargoFeatureEvidence | undefined;
44
+
45
+ /** Packages whose features change when a tested crate runs without the rest of the full invocation,
46
+ * and the sets of tested crates (each crate alone, and each crate with its dependents) that give a
47
+ * package exactly the full invocation's features. */
48
+ export interface RustFeatureCoverage {
49
+ deficits: Record<string, string[]>;
50
+ units: Array<{ crates: string[]; covers: string[] }>;
51
+ }
52
+
53
+ export const CARGO_TREE_ARGS = ["tree", "--offline", "--locked", "--prefix", "none", "-e", "normal,build,dev", "-f", "{p}|{f}"];
54
+
55
+ /** Package (`name vX.Y.Z`) to the distinct feature sets Cargo resolved for it; undefined when the
56
+ * output is not a feature tree. A package built for both host and target can have two sets. */
57
+ export function parseCargoFeatureTree(output: string): Map<string, Set<string>> | undefined {
58
+ const packages = new Map<string, Set<string>>();
59
+ for (const line of output.split(/\r?\n/)) {
60
+ const separator = line.indexOf("|");
61
+ if (separator < 0) continue;
62
+ const name = /^(\S+) (v\S+)/.exec(line.slice(0, separator));
63
+ if (!name) return undefined;
64
+ const features = line.slice(separator + 1).replace(/\s*\(\*\)\s*$/, "").trim();
65
+ if (!/^[A-Za-z0-9_+.:/,-]*$/.test(features)) return undefined;
66
+ const key = `${name[1]} ${name[2]}`;
67
+ let sets = packages.get(key);
68
+ if (!sets) packages.set(key, sets = new Set());
69
+ sets.add(features.split(",").filter(Boolean).sort().join(","));
70
+ }
71
+ return packages.size ? packages : undefined;
72
+ }
73
+
74
+ /** Whether any declaration can make a package's features depend on which crates are selected. With
75
+ * no feature requests, no disabled defaults and no forwarding, every package always gets its default
76
+ * features, whatever subset of the workspace Cargo builds. */
77
+ export function cargoFeaturesVary(metadata: CargoMetadata): boolean {
78
+ return metadata.packages.some(pkg => pkg.dependencies?.some(dep => dep.features.length || !dep.uses_default_features)
79
+ || Object.values(pkg.features ?? {}).some(features => features.some(feature => feature.includes("/"))));
80
+ }
81
+
82
+ /** Feature resolution is monotonic in the crates Cargo is asked to build: a selected set gives every
83
+ * package at least the features of any subset and at most those of the full invocation. A package
84
+ * therefore keeps exactly the full invocation's features (per host/target build, since the sets
85
+ * compared are the same) whenever one unit inside the selection already resolves it that way. */
86
+ export function rustFeatureCoverage(evidence: CargoFeatureEvidence, members: readonly string[]): RustFeatureCoverage | undefined {
87
+ const full = parseCargoFeatureTree(evidence.workspace);
88
+ if (!full) return undefined;
89
+ const trees = evidence.units.map(unit => ({ crates: [...unit.crates].sort(), tree: parseCargoFeatureTree(unit.tree) }));
90
+ if (trees.some(unit => !unit.tree)) return undefined;
91
+ const same = (sets: Set<string>, key: string) => {
92
+ const expected = full.get(key);
93
+ return expected !== undefined && expected.size === sets.size && [...sets].every(set => expected.has(set));
94
+ };
95
+ const deficits: Record<string, string[]> = {};
96
+ for (const member of members) {
97
+ const alone = trees.find(unit => unit.crates.length === 1 && unit.crates[0] === member);
98
+ if (!alone) return undefined;
99
+ const missing = [...alone.tree!].filter(([key, sets]) => !same(sets, key)).map(([key]) => key).sort();
100
+ if (missing.length) deficits[member] = missing;
101
+ }
102
+ const needed = new Set(Object.values(deficits).flat());
103
+ const units = trees.map(unit => ({ crates: unit.crates, covers: [...unit.tree!].filter(([key, sets]) => needed.has(key) && same(sets, key)).map(([key]) => key).sort() }))
104
+ .filter(unit => unit.covers.length);
105
+ return { deficits, units };
25
106
  }
26
107
 
27
108
  function object(value: unknown): value is Record<string, unknown> {
@@ -42,20 +123,27 @@ export function parseCargoMetadata(output: string): CargoMetadata {
42
123
  for (const pkg of value.packages) {
43
124
  if (!object(pkg) || typeof pkg.id !== "string" || !pkg.id || typeof pkg.name !== "string"
44
125
  || !/^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(pkg.name) || typeof pkg.manifest_path !== "string"
45
- || !isAbsolute(pkg.manifest_path) || !Array.isArray(pkg.targets) || !pkg.targets.length) {
126
+ || !isAbsolute(pkg.manifest_path) || !Array.isArray(pkg.targets) || !pkg.targets.length
127
+ || (pkg.source !== undefined && pkg.source !== null && typeof pkg.source !== "string")) {
46
128
  throw new Error("Invalid Cargo package metadata");
47
129
  }
48
130
  for (const target of pkg.targets) {
49
131
  if (!object(target) || typeof target.name !== "string" || !/^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(target.name)
50
132
  || !strings(target.kind) || !target.kind.length || typeof target.src_path !== "string"
51
- || !isAbsolute(target.src_path) || typeof target.test !== "boolean" || typeof target.doctest !== "boolean") {
133
+ || !isAbsolute(target.src_path) || typeof target.test !== "boolean" || typeof target.doctest !== "boolean"
134
+ || (target["required-features"] !== undefined && !strings(target["required-features"]))) {
52
135
  throw new Error("Invalid Cargo target metadata");
53
136
  }
54
137
  }
138
+ if (!Array.isArray(pkg.dependencies) || pkg.dependencies.some(dependency => !object(dependency)
139
+ || typeof dependency.name !== "string" || !strings(dependency.features) || typeof dependency.uses_default_features !== "boolean")) throw new Error("Invalid Cargo dependency features");
140
+ if (!object(pkg.features) || Object.values(pkg.features).some(features => !strings(features))) throw new Error("Invalid Cargo features");
55
141
  }
56
142
  const ids = value.packages.map(pkg => (pkg as CargoPackage).id);
57
143
  if (new Set(ids).size !== ids.length || new Set(value.workspace_members).size !== value.workspace_members.length
58
144
  || value.workspace_members.some(id => !ids.includes(id))) throw new Error("Incomplete Cargo workspace membership");
145
+ if (value.workspace_default_members !== undefined && (!strings(value.workspace_default_members)
146
+ || value.workspace_default_members.some(id => !(value.workspace_members as string[]).includes(id)))) throw new Error("Invalid Cargo default members");
59
147
  return value as unknown as CargoMetadata;
60
148
  }
61
149
 
@@ -81,11 +169,156 @@ function under(path: string, directory: string): boolean {
81
169
  return directory === "" || path.startsWith(`${directory}/`);
82
170
  }
83
171
 
84
- export function analyzeRustMetadata(context: AdapterContext, output: string): AdapterContribution {
172
+ /** Cargo modules can live under names other adapters exclude. Never silently omit their contents
173
+ * or follow a symlink that aliases another crate's inputs. Without `#[path]` (which falls back),
174
+ * `mod` only loads files below a target root's directory, so only those trees are checked: a
175
+ * symlink or unlisted file elsewhere in the repository cannot become crate source, and neither can a
176
+ * linked non-Rust file inside them. */
177
+ function completeRustInventory(root: string, files: ReadonlySet<string>, trees: readonly string[]): boolean {
178
+ const pending = [...new Set(trees)].filter((tree, _, all) => !all.some(other => other !== tree && under(tree, other)));
179
+ while (pending.length) {
180
+ const directory = pending.pop()!;
181
+ for (const entry of readdirSync(resolve(root, directory), { withFileTypes: true })) {
182
+ const path = directory ? `${directory}/${entry.name}` : entry.name;
183
+ if (entry.isSymbolicLink()) {
184
+ // A linked directory or Rust file can alias module source; a linked LICENSE or README cannot.
185
+ if (path.endsWith(".rs")) return false;
186
+ try { if (statSync(resolve(root, path)).isDirectory()) return false; } catch { /* dangling, not source */ }
187
+ continue;
188
+ }
189
+ if (entry.isDirectory()) {
190
+ // Version control, dependency trees and Cargo's own output never hold module source.
191
+ if (![".git", "node_modules", "target"].includes(entry.name)) pending.push(path);
192
+ } else if (entry.isFile() && path.endsWith(".rs") && !files.has(path)) return false;
193
+ }
194
+ }
195
+ return true;
196
+ }
197
+
198
+ /** A small lexer, not a Rust parser: ignore comments/strings, but never guess
199
+ * 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 {
201
+ const tokens: Array<{ value: string; literal?: string }> = [];
202
+ for (let i = 0; i < source.length;) {
203
+ if (/\s/.test(source[i]!)) { i++; continue; }
204
+ if (source.startsWith("//", i)) { const end = source.indexOf("\n", i); i = end < 0 ? source.length : end + 1; continue; }
205
+ if (source.startsWith("/*", i)) {
206
+ let depth = 1; i += 2;
207
+ while (i < source.length && depth) {
208
+ if (source.startsWith("/*", i)) { depth++; i += 2; }
209
+ else if (source.startsWith("*/", i)) { depth--; i += 2; }
210
+ else i++;
211
+ }
212
+ if (depth) return undefined;
213
+ continue;
214
+ }
215
+ const raw = /^r(#{0,255})"/.exec(source.slice(i));
216
+ if (raw) {
217
+ const start = i + raw[0].length, end = source.indexOf(`"${raw[1]}`, start);
218
+ if (end < 0) return undefined;
219
+ tokens.push({ value: "string", literal: source.slice(start, end) }); i = end + raw[1]!.length + 1; continue;
220
+ }
221
+ if (source[i] === '"') {
222
+ const start = i++;
223
+ while (i < source.length && source[i] !== '"') { if (source[i] === "\\") i++; i++; }
224
+ if (i >= source.length) return undefined;
225
+ i++;
226
+ let literal: string | undefined;
227
+ try { literal = JSON.parse(source.slice(start, i)) as string; } catch { /* non-JSON Rust escapes stay unknown */ }
228
+ tokens.push({ value: "string", literal }); continue;
229
+ }
230
+ const character = /^'(?:\\.|[^'\\\n])'/.exec(source.slice(i));
231
+ if (character) { i += character[0].length; continue; }
232
+ const identifier = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
233
+ if (identifier) { tokens.push({ value: identifier[0] }); i += identifier[0].length; continue; }
234
+ tokens.push({ value: source[i++]! });
235
+ }
236
+ // Runtime file access is not a blocker by itself, matching the Go and Python adapters: a changed
237
+ // non-Rust file is never a modelled source, so it keeps the full suite whoever reads it. What a
238
+ // dependency edge cannot see is code that reaches another crate's modelled Rust inputs at run or
239
+ // build time. Report literal paths (the caller checks which crates they reach) and Cargo/rustc
240
+ // invocations; ordinary identifiers such as `fs`, `process`, `unsafe` or `metadata` are not inputs.
241
+ const inputs: Array<{ path: string; code: boolean }> = [];
242
+ const paths: string[] = [];
243
+ let compiles = false;
244
+ const includeArguments = new Set<number>();
245
+ for (let i = 0; i < tokens.length; i++) {
246
+ if (tokens[i]!.value === "mod" && tokens[i + 1]?.value === "target" && tokens[i + 2]?.value === ";") return undefined;
247
+ if (tokens[i]!.value === "#") {
248
+ let j = i + 1;
249
+ if (tokens[j]?.value === "!") j++;
250
+ if (tokens[j]?.value === "[") {
251
+ let depth = 1;
252
+ for (j++; j < tokens.length && depth; j++) {
253
+ if (tokens[j]!.value === "[") depth++;
254
+ if (tokens[j]!.value === "]") depth--;
255
+ if (tokens[j]!.value === "path" && tokens[j + 1]?.value === "=") return undefined;
256
+ }
257
+ if (depth) return undefined;
258
+ }
259
+ }
260
+ if (tokens[i]!.value === "use") {
261
+ // A renamed or re-exported include macro could be called under a name we cannot recognize.
262
+ for (let j = i + 1; j < tokens.length && tokens[j]!.value !== ";"; j++) {
263
+ if (["include", "include_str", "include_bytes"].includes(tokens[j]!.value)) return undefined;
264
+ }
265
+ continue;
266
+ }
267
+ if (tokens[i]!.value === "Command" && tokens[i + 1]?.value === ":" && tokens[i + 2]?.value === ":" && tokens[i + 3]?.value === "new"
268
+ && tokens[i + 4]?.value === "(" && /^(?:cargo|rustc|rustdoc)(?:\.exe)?$|^cargo-/.test(tokens[i + 5]?.literal ?? "")) compiles = true;
269
+ // `env!("CARGO")`, `env::var("RUSTC")` and similar name the toolchain a test is about to run.
270
+ if (["CARGO", "RUSTC", "RUSTDOC", "RUSTC_WRAPPER"].includes(tokens[i]!.literal ?? "")) compiles = true;
271
+ if (!["include", "include_str", "include_bytes"].includes(tokens[i]!.value) || tokens[i + 1]?.value !== "!") continue;
272
+ const close = new Map([["(", ")"], ["[", "]"], ["{", "}"]]).get(tokens[i + 2]?.value ?? "");
273
+ const literal = tokens[i + 3]?.literal;
274
+ let end = i + 4;
275
+ if (tokens[end]?.value === ",") end++;
276
+ if (!close || literal === undefined || tokens[end]?.value !== close || /[\0\r\n\\]/.test(literal)) return undefined;
277
+ inputs.push({ path: literal, code: tokens[i]!.value === "include" });
278
+ includeArguments.add(i + 3);
279
+ }
280
+ let documentation = false;
281
+ tokens.forEach((token, index) => {
282
+ if (token.literal === undefined || includeArguments.has(index)) return;
283
+ if (pathLike(token.literal)) paths.push(token.literal);
284
+ // A test that checks README or docs content at run time (version-sync, link checks and the like):
285
+ // a Markdown name or bare extension (`"md"` in an extension check), or a documentation directory
286
+ // anywhere in the path (`../docs`, `concat!(env!("CARGO_MANIFEST_DIR"), "/../docs")`).
287
+ if (/(?:^|\.)mdx?$|(?:^|[\\/])(?:docs?|documentation)(?:[\\/]|$)/i.test(token.literal)) documentation = true;
288
+ });
289
+ const navigates = navigatesUpward(tokens);
290
+ // 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 };
292
+ }
293
+
294
+ /** Code that climbs out of its crate directory in code (`.parent()`, `.ancestors()`, `PathBuf::pop`,
295
+ * or a formatted path with a `..` segment) can reach any crate without a literal naming it. Tests
296
+ * that check every crate's files (license headers, generated code) are written this way. Only fires
297
+ * where the file also works with paths, so `node.parent()` in a parser does not count. */
298
+ function navigatesUpward(tokens: ReadonlyArray<{ value: string; literal?: string }>): boolean {
299
+ const pathContext = tokens.some(token => ["Path", "PathBuf", "current_dir", "current_exe"].includes(token.value)
300
+ || ["CARGO_MANIFEST_DIR", "CARGO_WORKSPACE_DIR"].includes(token.literal ?? ""));
301
+ if (!pathContext) return false;
302
+ const pathBuf = tokens.some(token => token.value === "PathBuf");
303
+ return tokens.some((token, index) => {
304
+ if (token.literal !== undefined) return /\{[^}]*\}/.test(token.literal) && /(?:^|[\\/}])\.\.(?:[\\/{]|$)/.test(token.literal);
305
+ if (tokens[index - 1]?.value !== "." || tokens[index + 1]?.value !== "(") return false;
306
+ return token.value === "parent" || token.value === "ancestors" || (pathBuf && token.value === "pop");
307
+ });
308
+ }
309
+
310
+ /** A string that names a file or directory rather than ordinary text. */
311
+ function pathLike(value: string): boolean {
312
+ if (!value || value.length > 4096 || /[\0\r\n]/.test(value)) return false;
313
+ if (value === "." || value === "..") return true;
314
+ return /[\\/]/.test(value) && !/\s/.test(value) || /(?:^|[\\/])(?:Cargo\.(?:toml|lock)|[^\\/\s]+\.rs)$/.test(value);
315
+ }
316
+
317
+ export function analyzeRustMetadata(context: AdapterContext, output: string, resolveFeatures?: CargoFeatureResolver): AdapterContribution {
85
318
  const result = contribution(rustAdapter);
86
- // This first milestone only establishes ownership. Keep it fail-closed until
87
- // workspace dependency edges are added, even if called before registration.
88
- result.blockers.push("Rust crate dependency analysis is not available; full validation required");
319
+ if (context.files.some(file => /(?:^|\/)\.cargo\/config(?:\.toml)?$/.test(file) && changesBuild(resolve(context.repoPath, file)))) {
320
+ result.blockers.push("Custom Cargo configuration requires full validation");
321
+ }
89
322
  try {
90
323
  const metadata = parseCargoMetadata(output);
91
324
  const root = realpathSync(resolve(context.repoPath));
@@ -95,6 +328,12 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
95
328
  }
96
329
  const known = new Set(context.files);
97
330
  const members = metadata.packages.filter(pkg => metadata.workspace_members.includes(pkg.id));
331
+ // Plain `cargo test` tests only the root package of a non-virtual workspace, or `default-members`.
332
+ // Selecting another member would run tests the full invocation never runs, so only these crates'
333
+ // targets are tests; other members stay sources whose changes reach their tested dependents.
334
+ const defaults = metadata.workspace_default_members;
335
+ if (!defaults) result.blockers.push("Cargo metadata without default workspace members requires full validation; use Cargo 1.71 or later");
336
+ const tested = new Set(defaults ?? []);
98
337
  if (new Set(members.map(pkg => pkg.name)).size !== members.length) {
99
338
  result.blockers.push("Ambiguous Cargo workspace package names require full validation");
100
339
  return result;
@@ -115,7 +354,14 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
115
354
  const manifests = new Set(packages.map(pkg => pkg.manifest));
116
355
  const unmodeledManifests = context.files.filter(file => /(?:^|\/)Cargo\.toml$/.test(file)
117
356
  && file !== "Cargo.toml" && !manifests.has(file));
118
- if (unmodeledManifests.length) result.blockers.push(`Cargo manifests outside workspace membership require full validation: ${unmodeledManifests.join(", ")}`);
357
+ // Cargo metadata resolves every path dependency (all features, all platforms), so when no local
358
+ // package outside the workspace appears, no member depends on these crates: they are fixtures or
359
+ // excluded crates. Their files stay unmodelled, so changing one keeps the full suite (impact.ts)
360
+ // without blocking changes elsewhere. Otherwise the repository-wide fallback stays.
361
+ const localDependencyOutside = metadata.packages.some(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null));
362
+ const unmodeledBoundary = (file: string) => !localDependencyOutside
363
+ && unmodeledManifests.some(manifest => under(file, manifest.slice(0, -"/Cargo.toml".length)));
364
+ if (unmodeledManifests.length && localDependencyOutside) result.blockers.push(`Cargo manifests outside workspace membership require full validation: ${unmodeledManifests.join(", ")}`);
119
365
  if (manifests.size !== packages.length) result.blockers.push("Cargo packages share a manifest; ownership is ambiguous");
120
366
  const owner = (file: string) => {
121
367
  const candidate = packages.find(pkg => under(file, pkg.directory));
@@ -126,11 +372,13 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
126
372
  return candidate;
127
373
  };
128
374
  for (const file of context.files.filter(file => file.endsWith(".rs"))) {
375
+ if (!owner(file) && unmodeledBoundary(file)) continue;
129
376
  if (!owner(file) || !repositoryPath(root, resolve(root, file), known)) {
130
377
  result.blockers.push(`Rust file has no verified Cargo package: ${file}`);
131
378
  } else result.sourcePaths.push(file);
132
379
  }
133
380
  result.rustTestTargets = {};
381
+ const buildScriptCrates = new Set<string>();
134
382
  for (const { pkg } of packages) {
135
383
  for (const target of pkg.targets) {
136
384
  const path = repositoryPath(root, target.src_path, known);
@@ -138,7 +386,14 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
138
386
  result.blockers.push(`Rust target ${pkg.name}/${target.name} has an unavailable, external or differently owned source`);
139
387
  continue;
140
388
  }
141
- if (target.kind.includes("custom-build")) continue;
389
+ if (!path.endsWith(".rs")) result.blockers.push(`Cargo target with a non-Rust extension requires full validation: ${path}`);
390
+ if (target.kind.includes("custom-build")) {
391
+ // The build script is the crate's own source; what it reads is modelled below.
392
+ result.sourcePaths.push(path);
393
+ buildScriptCrates.add(pkg.id);
394
+ (result.rustDocumentationReaders ??= []).push(path);
395
+ continue;
396
+ }
142
397
  const kind = target.kind.includes("test") ? "test"
143
398
  : target.kind.includes("bin") ? "bin"
144
399
  : target.kind.includes("example") ? "example"
@@ -151,7 +406,7 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
151
406
  result.sourcePaths.push(path);
152
407
  // Cargo's test/doctest flags are authoritative. A crate's lib/bin root
153
408
  // represents its unit tests, including #[cfg(test)] modules in other files.
154
- if (!target.test && !target.doctest) continue;
409
+ if ((!target.test && !target.doctest) || !tested.has(pkg.id)) continue;
155
410
  if (Object.hasOwn(result.rustTestTargets, path)) {
156
411
  result.blockers.push(`Multiple Cargo test targets share a source path: ${path}`);
157
412
  continue;
@@ -161,17 +416,184 @@ export function analyzeRustMetadata(context: AdapterContext, output: string): Ad
161
416
  result.rustTestTargets[path] = { name: target.name, kind };
162
417
  }
163
418
  }
419
+ const moduleTrees = packages.flatMap(({ pkg }) => pkg.targets.map(target => resolvedPath(root, target.src_path)))
420
+ .filter((path): path is string => path !== undefined).map(path => dirname(path) === "." ? "" : dirname(path));
421
+ if (!completeRustInventory(root, known, moduleTrees)) result.blockers.push("Incomplete Rust source inventory or symlinked inputs require full validation");
164
422
  result.sourcePaths = [...new Set(result.sourcePaths)].sort();
165
423
  result.testFiles.sort();
166
424
  if (!result.testFiles.length) result.blockers.push("Cargo metadata found no supported test targets");
425
+ const anchors = new Map(packages.map(({ pkg, manifest }) => [pkg.id, manifest]));
426
+ // A parent crate can load Rust modules from a nested package directory
427
+ // without a Cargo dependency declaration. Keep that containment edge rather
428
+ // than assuming deepest ownership proves the parent never reads the child.
429
+ for (const parent of packages) for (const child of packages) {
430
+ if (parent !== child && under(child.manifest, parent.directory)) result.edges.push({ from: parent.manifest, to: child.manifest, kind: "import" });
431
+ }
432
+ for (const file of result.sourcePaths) {
433
+ const anchor = owner(file)?.manifest;
434
+ if (anchor && anchor !== file) result.edges.push({ from: anchor, to: file, kind: "import" }, { from: file, to: anchor, kind: "import" });
435
+ }
436
+ // Cargo resolves all target platforms unless --filter-platform is supplied.
437
+ // --all-features below unions optional dependencies too; cfg(feature) code
438
+ // stays crate-granular and does not itself make the graph unsafe.
439
+ const nodes = metadata.resolve?.nodes;
440
+ const packageIds = new Set(metadata.packages.map(pkg => pkg.id));
441
+ if (!Array.isArray(nodes) || nodes.some(node => !object(node) || typeof node.id !== "string"
442
+ || !packageIds.has(node.id) || !strings(node.dependencies) || node.dependencies.some(id => !packageIds.has(id)))
443
+ || new Set(nodes.map(node => node.id)).size !== nodes.length
444
+ || metadata.workspace_members.some(id => !nodes.some(node => node.id === id))) {
445
+ result.blockers.push("Cargo dependency resolution is missing or incomplete; full validation required");
446
+ } else {
447
+ for (const node of nodes) {
448
+ const anchor = anchors.get(node.id);
449
+ if (!anchor) continue;
450
+ for (const dependency of node.dependencies) {
451
+ const target = anchors.get(dependency);
452
+ if (target && target !== anchor) result.edges.push({ from: anchor, to: target, kind: "import" });
453
+ }
454
+ }
455
+ }
456
+ // Registry and Git dependencies are locked and immutable unless Cargo.lock changes, and a
457
+ // Cargo.lock change keeps the full suite. Their build scripts and procedural macros run the same
458
+ // code for the selected and the full invocation; anything they read from this repository outside
459
+ // modelled Rust sources is a changed path that keeps the full suite. A local path dependency that
460
+ // is not a workspace member has no modelled ownership, so it still blocks the repository.
461
+ const localOutside = metadata.packages.filter(pkg => !metadata.workspace_members.includes(pkg.id) && (pkg.source === undefined || pkg.source === null));
462
+ if (localOutside.length) {
463
+ result.blockers.push(`Local Cargo path dependencies outside the workspace require full validation: ${localOutside.map(pkg => pkg.name).sort().join(", ")}`);
464
+ }
465
+ // A workspace crate's build script can read any file. Its own source and every non-Rust input
466
+ // are already full-suite changes; what remains is another crate's Rust source or manifest, so
467
+ // such a crate depends on every workspace crate: it and its dependents run for any Rust change,
468
+ // while crates without build scripts still narrow.
469
+ for (const id of buildScriptCrates) {
470
+ const anchor = anchors.get(id)!;
471
+ for (const other of packages) if (other.manifest !== anchor) result.edges.push({ from: anchor, to: other.manifest, kind: "import" });
472
+ }
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
+ for (const source of result.sourcePaths.filter(path => path.endsWith(".rs"))) {
477
+ const sourceOwner = owner(source);
478
+ if (!sourceOwner) continue;
479
+ const scanned = rustInputs(readFileSync(resolve(root, source), "utf8"));
480
+ if (scanned === undefined) {
481
+ result.blockers.push(`Rust computed includes or path attributes require full validation: ${source}`);
482
+ continue;
483
+ }
484
+ // Code that runs Cargo or rustc can build any workspace crate; a literal path can reach another
485
+ // crate's sources at run or build time (relative to the crate, as under `cargo test`, or to the
486
+ // file). Code that climbs out of its crate in code can reach any crate, like code that compiles.
487
+ // Model these as dependencies of this crate instead of blocking the repository.
488
+ if (scanned.documentation) (result.rustDocumentationReaders ??= []).push(source);
489
+ const reached = new Set<string>();
490
+ if (scanned.compiles || scanned.navigates) for (const other of packages) reached.add(other.manifest);
491
+ for (const literal of scanned.paths) {
492
+ const clean = literal.replace(/\\/g, "/").replace(/^(?:[A-Za-z]:)?\/+/, "");
493
+ const glob = clean.search(/[*?[{]/);
494
+ 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)])) {
496
+ const joined = posix.normalize(posix.join(base || ".", prefix || "."));
497
+ if (joined === ".." || joined.startsWith("../")) continue;
498
+ const rel = joined === "." ? "" : joined.replace(/\/+$/, "");
499
+ const inside = rel ? owner(rel) ?? owner(`${rel}/`) : packages.find(pkg => pkg.directory === "");
500
+ if (inside) reached.add(inside.manifest);
501
+ for (const other of packages) if (other.directory && (rel === "" || under(other.directory, rel) || other.directory === rel)) reached.add(other.manifest);
502
+ }
503
+ }
504
+ reached.delete(sourceOwner.manifest);
505
+ for (const manifest of reached) result.edges.push({ from: sourceOwner.manifest, to: manifest, kind: "import" });
506
+ for (const input of scanned.inputs) {
507
+ const path = repositoryPath(root, resolve(root, dirname(source), input.path), known);
508
+ if (!path || owner(path)?.pkg.id !== sourceOwner.pkg.id) {
509
+ result.blockers.push(`Rust include outside its crate or unavailable requires full validation: ${source}`);
510
+ continue;
511
+ }
512
+ if (input.code && !path.endsWith(".rs")) {
513
+ result.blockers.push(`Rust include code with a non-Rust extension requires full validation: ${source}`);
514
+ continue;
515
+ }
516
+ if (!result.sourcePaths.includes(path)) result.assetPaths.push(path);
517
+ result.edges.push({ from: source, to: path, kind: "asset" });
518
+ }
519
+ }
520
+ result.assetPaths = [...new Set(result.assetPaths)].sort();
521
+ // Selective commands must give every package the features the full invocation gives it. Cargo
522
+ // resolves each tested crate alone and with its dependents (what a change to it selects); the
523
+ // planner checks each selected set against those units.
524
+ if (!cargoFeaturesVary(metadata)) result.rustFeatureCoverage = { deficits: {}, units: [] };
525
+ else {
526
+ const testedNames = packages.filter(({ pkg }) => tested.has(pkg.id)).map(({ pkg }) => pkg.name);
527
+ const dependents = new Map<string, string[]>();
528
+ for (const edge of result.edges) {
529
+ if (edge.from.endsWith("Cargo.toml") && edge.to.endsWith("Cargo.toml") && edge.from !== edge.to) {
530
+ dependents.set(edge.to, [...(dependents.get(edge.to) ?? []), edge.from]);
531
+ }
532
+ }
533
+ const byManifest = new Map(packages.map(({ pkg, manifest }) => [manifest, pkg.name]));
534
+ const units = new Map<string, string[]>();
535
+ for (const { pkg, manifest } of packages) {
536
+ if (tested.has(pkg.id)) units.set(pkg.name, [pkg.name]);
537
+ const seen = new Set([manifest]); const pending = [manifest];
538
+ while (pending.length) for (const next of dependents.get(pending.pop()!) ?? []) if (!seen.has(next)) { seen.add(next); pending.push(next); }
539
+ const closure = [...seen].map(path => byManifest.get(path)).filter((name): name is string => name !== undefined && testedNames.includes(name)).sort();
540
+ if (closure.length) units.set(closure.join(" "), closure);
541
+ }
542
+ const evidence = resolveFeatures?.([...units.values()]);
543
+ const coverage = evidence && rustFeatureCoverage(evidence, testedNames);
544
+ if (coverage) result.rustFeatureCoverage = coverage;
545
+ else result.blockers.push("Cargo feature resolution is unavailable; full validation required");
546
+ }
167
547
  } catch {
168
548
  result.blockers.push("Invalid or incomplete Cargo metadata requires full validation");
169
549
  }
170
550
  return result;
171
551
  }
172
552
 
553
+ /** Ask Cargo how it resolves features for the full invocation and for sets of tested crates.
554
+ * Read-only and offline like `cargo metadata`; any failure leaves the evidence missing. */
555
+ function cargoFeatureResolver(repoPath: string): CargoFeatureResolver {
556
+ return (units) => {
557
+ if (units.length > 400) return undefined;
558
+ try {
559
+ const tree = (extra: string[]) => execFileSync("cargo", [...CARGO_TREE_ARGS, ...extra], {
560
+ cwd: repoPath, encoding: "utf8", timeout: 60_000, maxBuffer: 64 * 1024 * 1024,
561
+ windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, RUSTUP_AUTO_INSTALL: "0" },
562
+ });
563
+ return { workspace: tree([]), units: units.map(crates => ({ crates, tree: tree(crates.flatMap(name => ["-p", name])) })) };
564
+ } catch { return undefined; }
565
+ };
566
+ }
567
+
568
+ /** Configuration keys that change how crates are compiled, which code is compiled or what runs the
569
+ * tests. Aliases, registries, network, terminal, `[env]` and target-dir settings apply equally to
570
+ * 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;
572
+ 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
+
574
+ function changesBuild(path: string): boolean {
575
+ try { return BUILD_CONFIG.test(readFileSync(path, "utf8")); }
576
+ catch { return existsSync(path); }
577
+ }
578
+
579
+ /** Every configuration file Cargo reads for a command run at the repository root: the root and each
580
+ * parent directory's `.cargo/config(.toml)`, then `$CARGO_HOME/config(.toml)`. */
581
+ function cargoConfigLocations(repoPath: string): string[] {
582
+ const directories: string[] = [];
583
+ let directory = resolve(repoPath);
584
+ try { directory = realpathSync(directory); } catch { /* metadata reports the missing root */ }
585
+ for (;;) {
586
+ directories.push(resolve(directory, ".cargo"));
587
+ const parent = dirname(directory);
588
+ if (parent === directory) break;
589
+ directory = parent;
590
+ }
591
+ directories.push(process.env.CARGO_HOME || resolve(homedir(), ".cargo"));
592
+ return directories.flatMap(home => [resolve(home, "config"), resolve(home, "config.toml")]).filter(path => existsSync(path));
593
+ }
594
+
173
595
  export const rustAdapter: RepositoryAdapter = {
174
- id: "rust", version: "1", kind: "language",
596
+ id: "rust", version: "2", kind: "language",
175
597
  detect: ({ files }) => files.some(file => /(?:^|\/)Cargo\.toml$/.test(file) || file.endsWith(".rs")),
176
598
  analyze(context) {
177
599
  const failure = contribution(this);
@@ -179,14 +601,23 @@ export const rustAdapter: RepositoryAdapter = {
179
601
  failure.blockers.push("Rust support requires a root Cargo.toml");
180
602
  return failure;
181
603
  }
604
+ const configs = [...context.files.filter(file => /(?:^|\/)\.cargo\/config(?:\.toml)?$/.test(file)).map(file => resolve(context.repoPath, file)),
605
+ ...cargoConfigLocations(context.repoPath)];
606
+ if (configs.some(changesBuild)
607
+ || Object.entries(process.env).some(([key, value]) => value && COMPILER_ENVIRONMENT.test(key))) {
608
+ failure.blockers.push("Custom Cargo configuration or compiler environment requires full validation");
609
+ return failure;
610
+ }
182
611
  try {
183
- // Metadata does not execute repository code. Offline + locked prevents
184
- // dependency downloads and changes to the repository's Cargo.lock.
185
- const output = execFileSync("cargo", ["metadata", "--format-version", "1", "--no-deps", "--offline", "--locked"], {
612
+ // No compilation, build scripts or tests. Offline + locked prevents
613
+ // dependency downloads and changes to the repository's Cargo.lock;
614
+ // rustup must not install a missing toolchain on this read-only path.
615
+ const output = execFileSync("cargo", ["metadata", "--format-version", "1", "--all-features", "--offline", "--locked"], {
186
616
  cwd: context.repoPath, encoding: "utf8", timeout: 60_000, maxBuffer: 64 * 1024 * 1024,
187
617
  windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
618
+ env: { ...process.env, RUSTUP_AUTO_INSTALL: "0" },
188
619
  });
189
- return analyzeRustMetadata(context, output);
620
+ return analyzeRustMetadata(context, output, cargoFeatureResolver(context.repoPath));
190
621
  } catch {
191
622
  failure.blockers.push("Cargo metadata unavailable: install Rust and repository dependencies; offline, locked metadata must succeed");
192
623
  return failure;
@@ -22,6 +22,11 @@ export interface AdapterContribution {
22
22
  testPackages: Record<string, string>;
23
23
  /** Cargo target roots; a lib/bin root represents the crate's unit tests. */
24
24
  rustTestTargets?: Record<string, { name: string; kind: "lib" | "bin" | "test" | "bench" | "example" }>;
25
+ /** Rust files that may read documentation: workspace build scripts, and sources naming a
26
+ * documentation path in a string literal. */
27
+ rustDocumentationReaders?: string[];
28
+ /** Packages whose Cargo features change when a tested crate runs without the rest of the full invocation. */
29
+ rustFeatureCoverage?: { deficits: Record<string, string[]>; units: Array<{ crates: string[]; covers: string[] }> };
25
30
  executionEnv?: Record<string, string>;
26
31
  /** The interpreter the adapter analysed with and its runner should use, such as ["python3"]. */
27
32
  interpreter?: string[];