Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(dep-audit): improve lockfile handling, dependency analysis, and reporting

Steven Enamakelc0cc2a8d74fe
diff --git a/scripts/dep-audit/README.md b/scripts/dep-audit/README.md
index 08d8e65709..5410c45934 100644
--- a/scripts/dep-audit/README.md
+++ b/scripts/dep-audit/README.md
@@ -13,11 +13,15 @@ pnpm dep:audit --targets '^(root|tinyagents)$' --top 25
A full sweep of 24 targets takes about 20 seconds; nothing is compiled, the
tool only runs `cargo metadata` and parses source.
-The run has no side effects on the tree: `cargo metadata` rewrites a
+The run avoids side effects on the tree: `cargo metadata` rewrites a
`Cargo.lock` that is stale relative to its manifest (`crates/openhuman-app`'s
-lockfile in particular), so `run.sh` snapshots every target's lockfile before
-analyzing it and restores it afterwards, printing which ones it had to put
-back. Refresh those deliberately if you want them refreshed.
+lockfile in particular), or creates one where a target had none, so `run.sh`
+records each target's lockfile state (present, with its exact contents, or
+absent) before analyzing it and restores that state afterwards — restoring on
+interruption too — printing which lockfiles it had to put back or remove. It
+refuses to analyze a target whose `Cargo.lock` is a symlink rather than
+backing up and writing through it. Refresh a lockfile deliberately (`cargo
+update` / `cargo generate-lockfile`) if you want it refreshed.
## Files
@@ -57,40 +61,63 @@ siblings. `--keep-nested` analyzes every checkout regardless.
### Targets
One row per target with its commit and headline counts. "Crates in graph" is
-the *full* `cargo metadata` resolve — every platform and every optional
-feature — which is why Windows-only crates appear on a Linux run and why a
-duplicate listed here may not show in `cargo tree` on your host.
+the `cargo metadata` resolve for every platform (no `--filter-platform`),
+using each package's **default features** (tinyanalyzer does not pass
+`--all-features`) — which is why Windows-only crates appear on a Linux run,
+why a duplicate listed here may not show in `cargo tree` on your host, and
+why a crate reachable only through a non-default optional feature will not
+appear at all.
### 1. Declared dependencies no source file names
tinyanalyzer's check is textual: a dependency is "unused" if no `.rs` file in
-the package mentions the crate. That misses crate names inside attributes
-(`#[tokio::test]`, `#[derive(thiserror::Error)]`), so `report.mjs` re-checks
-every flag with a grep over the package's own sources, **including
-`[[test]]` / `[[example]]` targets declared by `path =` in its `Cargo.toml`**
-(the root crate keeps its integration tests in `tests/` that way). Verdicts:
+the package mentions it *the way Rust code references a dependency* —
+`dep_name::…`, `use dep_name`, `extern crate dep_name`, or `dep_name!` (`_`
+for `-`; `dep_name` is the crate's rename alias when one is declared). That
+misses crate names inside attributes (`#[tokio::test]`,
+`#[derive(thiserror::Error)]`), so `report.mjs` re-checks every flag with a
+grep over the package's own sources — **the crate's own directory,
+recursively, plus the exact file (not directory) of every `[[test]]` /
+`[[example]]` / `[[bench]]` / `[[bin]]` / build-script target declared by
+`path =` in its `Cargo.toml`** (the root crate keeps its integration tests in
+`tests/` that way; scanning the file rather than the shared `tests/`
+directory keeps an unrelated sibling test from flipping the verdict).
+Verdicts:
| Verdict | Meaning | Action |
| --- | --- | --- |
-| **remove** | No `crate::…`, `use crate`, `#[crate…` or `crate!` anywhere. | Delete the line, `cargo check` (both feature-on and feature-off builds if it was `optional`), delete the `dep:` feature if one existed. |
+| **remove** | No `dep_name::…`, `use dep_name`, `extern crate dep_name`, `#[dep_name…` or `dep_name!` anywhere. | Delete the line, `cargo check` (both feature-on and feature-off builds if it was `optional`), delete the `dep:` feature if one existed. |
| **remove** (name only) | The bare word occurs in a comment or string but never as a path. | Same as above; the mention is not a use. |
| keep (attribute/macro path) | Used through an attribute or macro body. | Nothing. Listed so the tool's false positives stay visible. |
+The re-check is a grep over raw text, not a syntax-aware scan: a comment or
+string that happens to spell the exact reference pattern (`// dep_name::foo`)
+is misclassified as a real use, same as tinyanalyzer's own check. Treat a
+`keep` verdict as a strong signal, not a proof.
+
**Graph win** is the number of crates that leave the target's build if that
one line is deleted. It is `0 (kept by …)` when another package in the same
workspace still depends on the crate: the manifest gets cleaner, the build
does not get smaller. Sort your effort by graph win.
-A crate that is used *only* through attributes everywhere (currently
-`thiserror`) can be added to `ignore_unused` in `tinyanalyzer.toml` so it stops
-being reported. Do that only for crates that can never be a real finding;
-every entry hides the crate from the check in all 24 targets.
+`ignore_unused` in `tinyanalyzer.toml` is empty and should generally stay
+that way: it hides a crate from tinyanalyzer's own unused check in *every*
+target, so a genuinely unused occurrence in some other target goes
+unreported too. `report.mjs`'s own re-check already covers the false
+positive this list historically existed for (`#[derive(thiserror::Error)]`
+with no `use thiserror`) by scanning for the attribute form and reporting
+"keep" instead of "remove". Only add an entry here for a crate that is
+provably unreachable through any `use`/path/attribute/macro form
+tinyanalyzer or the re-check could ever see.
### 2. Crates resolved at more than one version
Each version is compiled and linked separately. **Only the `root` (and
`openhuman-app`) sections cost the shipped build**; submodule sections show
-where a requirement should move so the root can unify.
+where a requirement should move so the root can unify. Within a `root` /
+`openhuman-app` section, a duplicate reached only through a `development`
+dependency (see section 1's Kind column) costs test/CI build time, not the
+shipped binary — check the Kind before treating a row as production weight.
"Pulled in via" names the *direct* dependencies whose subtree carries that
version, walked from tinyanalyzer's edge list. `direct dep of <pkg>` means one
@@ -110,7 +137,10 @@ of our own packages declares it. To unify:
Per target, the direct dependencies with the largest **exclusive** transitive
footprint — crates that would leave the build entirely if this one were
dropped. "Reaches" is the raw transitive count, most of which something else
-pulls in anyway. "Source" is checked-out source size, not binary size.
+pulls in anyway. "Source" is checked-out source size, not binary size. Unlike
+section 1, this table excludes a dependency whose only edge kind is
+`development` (test/example/benchmark-only): those are never linked into the
+shipped binary, so they do not belong in a shipped-build weight ranking.
A high exclusive count usually means default features pulling in a subtree we
do not use. Try `default-features = false` plus the two or three features
diff --git a/scripts/dep-audit/report.mjs b/scripts/dep-audit/report.mjs
index 5cbd83e133..20dd95304c 100644
--- a/scripts/dep-audit/report.mjs
+++ b/scripts/dep-audit/report.mjs
@@ -126,34 +126,87 @@ function packageDir(data, packageName) {
);
if (!pkg) return null;
const m = /^path\+file:\/\/(.+?)(#.*)?$/.exec(pkg.id);
- return m ? m[1] : null;
+ return m ? decodeURIComponent(m[1]) : null;
}
/**
- * Directories whose `*.rs` files belong to a package: its own directory plus
- * the parent directory of every explicit `path = "..."` target in its
- * Cargo.toml (`[[test]]`, `[[example]]`, `[[bench]]`, `[[bin]]`, `[lib]`).
- * OpenHuman's root crate declares its integration tests as
- * `path = "../../tests/<name>.rs"`, which a scan of the crate dir alone misses.
+ * Sources that belong to a package: its own directory (scanned recursively,
+ * so an implicit `src/` or an implicit `build.rs` next to `Cargo.toml` are
+ * covered) plus the exact file for every explicit `path = "..."` target in
+ * its Cargo.toml (`[[test]]`, `[[example]]`, `[[bench]]`, `[[bin]]`, `[lib]`,
+ * `[package] build = "..."`).
+ *
+ * Explicit targets are tracked as single *files*, not their parent
+ * directory: OpenHuman's root crate declares its integration tests as
+ * `path = "../../tests/<name>.rs"`, and `tests/` holds one file per package
+ * (see AGENTS.md). Adding that whole directory would let an unrelated
+ * sibling test file reference a dependency and flip an actually-unused
+ * dependency to "keep".
*/
function packageSourceDirs(dir) {
const dirs = new Set([dir]);
+ const files = new Set();
const manifest = path.join(dir, "Cargo.toml");
- if (!fs.existsSync(manifest)) return [...dirs];
+ if (!fs.existsSync(manifest)) return { dirs: [...dirs], files: [...files] };
const toml = fs.readFileSync(manifest, "utf8");
let section = "";
for (const raw of toml.split("\n")) {
const line = raw.trim();
- const head = /^\[\[?([a-zA-Z.-]+)\]?\]/.exec(line);
+ const head = /^\[\[?([a-zA-Z0-9_.-]+)\]?\]/.exec(line);
if (head) {
section = head[1];
continue;
}
+ if (section === "package") {
+ const b = /^build\s*=\s*"([^"]+)"/.exec(line);
+ if (b) files.add(path.resolve(dir, b[1]));
+ continue;
+ }
if (!/^(test|example|bench|bin|lib)$/.test(section)) continue;
const m = /^path\s*=\s*"([^"]+)"/.exec(line);
- if (m) dirs.add(path.dirname(path.resolve(dir, m[1])));
+ if (m) files.add(path.resolve(dir, m[1]));
+ }
+ return { dirs: [...dirs], files: [...files] };
+}
+
+/**
+ * Alias -> real crate name for dependencies renamed with `package = "..."`,
+ * covering both `alias = { package = "real", ... }` and
+ * `[dependencies.alias]` / `package = "real"` table forms. tinyanalyzer's
+ * `unused[].dependency` (and the graph's `packages[].name`) disagree for a
+ * renamed dependency: the former is the manifest key (what code actually
+ * imports), the latter is the real crate name (what the resolved package is
+ * called), so callers matching a dependency against the graph need this map.
+ */
+function dependencyAliasMap(dir) {
+ const map = new Map();
+ const manifest = path.join(dir, "Cargo.toml");
+ if (!fs.existsSync(manifest)) return map;
+ const toml = fs.readFileSync(manifest, "utf8");
+ let section = "";
+ let tableDepKey = null;
+ for (const raw of toml.split("\n")) {
+ const line = raw.trim();
+ const head = /^\[([a-zA-Z0-9_.-]+)\]/.exec(line);
+ if (head) {
+ section = head[1];
+ const table = /^(dependencies|dev-dependencies|build-dependencies)\.([A-Za-z0-9_-]+)$/.exec(section);
+ tableDepKey = table ? table[2] : null;
+ continue;
+ }
+ if (tableDepKey) {
+ const pkg = /^package\s*=\s*"([^"]+)"/.exec(line);
+ if (pkg) map.set(tableDepKey, pkg[1]);
+ continue;
+ }
+ if (!/^(dependencies|dev-dependencies|build-dependencies)$/.test(section)) continue;
+ const inline = /^([A-Za-z0-9_-]+)\s*=\s*\{([^}]*)\}/.exec(line);
+ if (inline) {
+ const pkg = /package\s*=\s*"([^"]+)"/.exec(inline[2]);
+ if (pkg) map.set(inline[1], pkg[1]);
+ }
}
- return [...dirs];
+ return map;
}
/**
@@ -169,25 +222,31 @@ function packageSourceDirs(dir) {
*/
function textualUse(dir, dep) {
if (!dir || !fs.existsSync(dir)) return "unknown";
+ // Code imports a renamed dependency under its manifest alias (`dep`), not
+ // under the crate's real name, so the alias is the correct identifier to
+ // grep for here — see dependencyAliasMap's docstring for the name split.
const ident = dep.replace(/-/g, "_");
- const dirs = packageSourceDirs(dir);
+ const { dirs, files } = packageSourceDirs(dir);
const pathRe = `(\\b${ident}::|\\buse\\s+${ident}\\b|extern\\s+crate\\s+${ident}\\b|#\\[${ident}\\b|\\b${ident}!)`;
- if (grepAny(dirs, pathRe)) return "path";
- if (grepAny(dirs, `\\b${ident}\\b`)) return "word";
+ if (grepAny(dirs, files, pathRe)) return "path";
+ if (grepAny(dirs, files, `\\b${ident}\\b`)) return "word";
return "none";
}
-function grepAny(dirs, pattern) {
+function grepAny(dirs, files, pattern) {
+ const targets = [...dirs, ...files];
+ if (targets.length === 0) return false;
try {
const out = execFileSync(
"grep",
- ["-rlE", pattern, "--include=*.rs", "--exclude-dir=target", "--exclude-dir=vendor", ...dirs],
+ ["-rlE", pattern, "--include=*.rs", "--exclude-dir=target", "--exclude-dir=vendor", ...targets],
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
);
return out.trim().length > 0;
} catch (err) {
- // grep exits 1 when nothing matched; anything else is a real failure we
- // would rather surface as "used" than as a false removal.
+ // grep exits 1 when nothing matched (or a listed file does not exist);
+ // anything else is a real failure we would rather surface as "used" than
+ // as a false removal.
return err.status !== 1;
}
}
@@ -301,8 +360,12 @@ function unusedFor(target, data) {
seen.add(key);
const dir = packageDir(data, u.package);
const evidence = textualUse(dir, u.dependency);
- const pkg = resolvedDependency(data, u.package, u.dependency);
- const others = otherDependents(data, u.dependency, u.package);
+ // `u.dependency` is the manifest key; resolve a rename (`alias = {
+ // package = "real" }`) to the crate name the graph indexes packages by
+ // before looking anything up there.
+ const realName = dir ? (dependencyAliasMap(dir).get(u.dependency) ?? u.dependency) : u.dependency;
+ const pkg = resolvedDependency(data, u.package, realName);
+ const others = otherDependents(data, realName, u.package);
rows.push({
package: u.package,
dependency: u.dependency,
@@ -329,7 +392,16 @@ function unusedFor(target, data) {
function heavyFor(data, n) {
return data.dependencies.packages
- .filter((p) => p.is_direct && !p.is_workspace_member && !p.is_root_package)
+ // A package whose only edge kind is `development` is never linked into
+ // the shipped build, so it does not belong in a "heaviest shipped
+ // dependency" ranking even though `include_dev` charges it in section 1.
+ .filter(
+ (p) =>
+ p.is_direct &&
+ !p.is_workspace_member &&
+ !p.is_root_package &&
+ p.kinds.some((k) => k === "normal" || k === "build"),
+ )
.map((p) => ({
name: p.name,
version: p.version,
@@ -388,14 +460,22 @@ function driftAcross(reports) {
});
}
rows.sort((a, b) => b.versions.length - a.versions.length || a.name.localeCompare(b.name));
- rows.patch_only = patchOnly;
- return rows;
+ // `patch_only` must be a normal field, not a property tacked onto the
+ // array: JSON.stringify only serializes array elements, so a property
+ // like `rows.patch_only = n` is silently dropped from summary.json.
+ return { rows, patch_only: patchOnly };
}
-/** Semver compatibility bucket: `0.x.y` -> `0.x`, `x.y.z` -> `x`. */
+/**
+ * Semver compatibility bucket: `x.y.z` -> `x`, `0.x.y` -> `0.x`, and
+ * `0.0.z` -> `0.0.z` (kept per-patch: Cargo treats every `0.0.z` as its own
+ * incompatible version, so `0.0.1` and `0.0.2` must not collapse together).
+ */
function compatKey(v) {
- const [major, minor] = v.split(/[.+-]/);
- return major === "0" ? `0.${minor}` : major;
+ const [major, minor, patch] = v.split(/[.+-]/);
+ if (major !== "0") return major;
+ if (minor !== "0") return `0.${minor}`;
+ return `0.0.${patch}`;
}
function semverish(a, b) {
@@ -442,7 +522,7 @@ function renderMarkdown(summary, n) {
// --- Unused --------------------------------------------------------------
push(``, `## 1. Declared dependencies no source file names`, ``);
push(
- `Verdict ${code("remove")}: nothing in the package's ${code("*.rs")} files (including ${code("[[test]]")}/${code("[[example]]")} targets declared by path) references the crate as ${code("crate::…")}, ${code("use crate")}, ${code("#[crate…")} or ${code("crate!")}. Delete the line from ${code("Cargo.toml")} and build; if it was an optional dependency, drop the ${code("dep:")} feature too. "name only" means the word occurs in a comment or string, which is not a use.`,
+ `Verdict ${code("remove")}: nothing in the package's ${code("*.rs")} files (including ${code("[[test]]")}/${code("[[example]]")} targets, each scanned as the exact declared file rather than its whole directory) references the dependency the way Rust code references it: ${code("dep_name::…")}, ${code("use dep_name")}, ${code("extern crate dep_name")}, ${code("#[dep_name…")} or ${code("dep_name!")}, where ${code("dep_name")} is the crate's manifest name (its rename alias when one is declared with ${code('package = "…"')}) with ${code("-")} normalized to ${code("_")}. Delete the line from ${code("Cargo.toml")} and build; if it was an optional dependency, drop the ${code("dep:")} feature too. "name only" means the bare word occurs in a comment or string, which is not a use — but note this scan is textual, not syntax-aware, so a comment or string that happens to contain the exact reference pattern (${code("// dep_name::foo")}) is misclassified as a real use; treat "name only" rows with light suspicion too.`,
`Verdict ${code("keep")}: tinyanalyzer saw no ${code("use")}/path, but one exists inside an attribute or macro body (${code("#[tokio::test]")}, ${code("#[derive(thiserror::Error)]")}) — a false positive of the tool, listed so the count is honest.`,
`${code("Graph win")}: crates that leave this target's build if the line is deleted. It is 0 when another package in the same workspace still depends on the crate — the manifest still gets cleaner, the build does not get smaller.`,
`Crates listed in ${code("[dependencies].ignore_unused")} of ${code("scripts/dep-audit/tinyanalyzer.toml")} are not reported at all.`,
@@ -520,11 +600,11 @@ function renderMarkdown(summary, n) {
`Crates that two or more targets depend on *directly* but resolve to semver-incompatible versions. When the root workspace ${code("[patch]")}-es a submodule in, both versions end up in the root build (section 2), so aligning the submodule's requirement with the root's removes a duplicate for free. Rows are ordered by how many distinct versions are in play.`,
``,
);
- if (summary.drift.length === 0) {
+ if (summary.drift.rows.length === 0) {
push(`_None._`);
} else {
push(`| Crate | Version | Targets |`, `| --- | --- | --- |`);
- for (const d of summary.drift) {
+ for (const d of summary.drift.rows) {
d.by_version.forEach((bv, i) => {
push(`| ${i === 0 ? code(d.name) : ""} | ${code(bv.version)} | ${bv.targets.join(", ")} |`);
});
diff --git a/scripts/dep-audit/run.sh b/scripts/dep-audit/run.sh
index 7a10b38feb..6561da73f3 100755
--- a/scripts/dep-audit/run.sh
+++ b/scripts/dep-audit/run.sh
@@ -99,7 +99,12 @@ fi
declare -A seen_by_repo_sha=()
skipped_nested=()
while read -r sha path _; do
+ prefix="${sha:0:1}"
sha="${sha#[-+U]}"
+ if [[ "$prefix" == "-" ]]; then
+ echo "dep-audit: submodule not initialized: $path (run: git submodule update --init --recursive vendor/)" >&2
+ exit 1
+ fi
[[ -f "$path/Cargo.toml" ]] || continue
name="$(basename "$path")"
remote="$(git -C "$path" remote get-url origin 2>/dev/null || echo '')"
@@ -134,15 +139,34 @@ while IFS=$'\t' read -r name path sha remote; do
[[ $VERBOSE -eq 1 ]] && echo "dep-audit: tinyanalyzer $path -> $json"
# tinyanalyzer runs `cargo metadata`, which silently rewrites a Cargo.lock
# that is stale relative to its manifest (the app crate's lockfile is the
- # usual victim). An audit must not leave edits behind, so the lockfile is
- # snapshotted and put back if the run changed it.
+ # usual victim), or creates one where none existed. An audit must not leave
+ # edits behind, so the lockfile's prior state (absent, or its exact
+ # contents) is snapshotted and restored even if the run is interrupted.
lock="$path/Cargo.lock"
lock_backup=""
- if [[ -f "$lock" ]]; then
+ lock_existed=0
+ if [[ -e "$lock" || -L "$lock" ]]; then
+ if [[ -L "$lock" || ! -f "$lock" ]]; then
+ echo "dep-audit: refusing to analyze $name: $lock is a symlink or not a regular file" >&2
+ exit 1
+ fi
+ lock_existed=1
lock_backup="$OUT_DIR/.lock-backup/$name.Cargo.lock"
mkdir -p "$(dirname "$lock_backup")"
cp "$lock" "$lock_backup"
fi
+ restore_lock() {
+ if [[ $lock_existed -eq 1 ]]; then
+ if ! cmp -s "$lock" "$lock_backup"; then
+ cp "$lock_backup" "$lock"
+ rewritten_locks+=("$lock")
+ fi
+ elif [[ -f "$lock" ]]; then
+ rm -f "$lock"
+ rewritten_locks+=("$lock (newly created; removed)")
+ fi
+ }
+ trap restore_lock EXIT
# --no-dead-code and --hide-tests keep the run cheap; the dependency graph is
# what we are after and it does not depend on either.
if tinyanalyzer "$path" --config "$CONFIG" --output json --no-dead-code --hide-tests \
@@ -154,10 +178,8 @@ while IFS=$'\t' read -r name path sha remote; do
printf 'dep-audit: %-28s FAILED (see %s)\n' "$name" "$log" >&2
rm -f "$json"
fi
- if [[ -n "$lock_backup" ]] && ! cmp -s "$lock" "$lock_backup"; then
- cp "$lock_backup" "$lock"
- rewritten_locks+=("$lock")
- fi
+ restore_lock
+ trap - EXIT
done < "$TARGETS_TSV"
echo "dep-audit: analyzed $analyzed target(s) into $OUT_DIR"
diff --git a/scripts/dep-audit/tinyanalyzer.toml b/scripts/dep-audit/tinyanalyzer.toml
index 11e91eb941..2aba8c8d94 100644
--- a/scripts/dep-audit/tinyanalyzer.toml
+++ b/scripts/dep-audit/tinyanalyzer.toml
@@ -14,14 +14,12 @@ exclude = ["vendor/**", "worktrees/**", "target/**", "node_modules/**"]
# reflects what CI actually compiles.
include_dev = true
-# Crates that are reached exclusively through `#[derive(...)]` / attribute
-# macros and so never appear in a `use` or path. tinyanalyzer's unused check is
-# textual ("no source file names the crate"), so these are near-certain false
-# positives. Keep the list short and justified: every entry hides a real
-# finding for that crate everywhere.
-ignore_unused = [
- # `#[derive(Error)]` + `#[error("...")]` when imported via `use thiserror::Error`
- # is *named*; only fully qualified `#[derive(thiserror::Error)]` is not, and
- # the codebase mixes both, so hide the noise.
- "thiserror",
-]
+# `ignore_unused` would hide a crate from tinyanalyzer's own unused check in
+# every target, globally — including a target where the crate genuinely is
+# unused. `report.mjs`'s `textualUse` re-check already covers the one false
+# positive this list used to carry (`thiserror` reached only through
+# `#[derive(thiserror::Error)]`, never a `use`): it greps for `#[thiserror\b`
+# and reports "keep (attribute/macro path)" instead of "remove", so no global
+# suppression is needed here. Prefer that per-finding re-check over adding
+# entries below.
+ignore_unused = []