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