Skip to content

audit: apply --audit-level and --ignore filters to --json output - #31013

Closed
robobun wants to merge 6 commits into
mainfrom
farm/63b997f9/audit-json-filter
Closed

robobun wants to merge 6 commits into
mainfrom
farm/63b997f9/audit-json-filter

Conversation

@robobun

@robobun robobun commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Repro

bun audit --json --audit-level=critical

Returns every advisory in the response, regardless of severity.

Cause

src/runtime/cli/audit_command.rs's JSON branch wrote response_text — the
raw registry body — straight to stdout. Only the enhanced/text branch forwarded
audit_level / ignore_list down to the filter (print_enhanced_audit_report),
so with --json every advisory came through.

Fix

Parse the JSON response, drop advisories whose severity is below audit_level
(and those matching the --ignore list), drop packages whose array becomes
empty, then re-serialize with bun_js_printer::print_json (2-space indent;
npm-audit-compatible shape). Exit code is now based on the post-filter
advisory count — matches the enhanced output's behavior.

The filter is a no-op fast path when neither --audit-level nor --ignore
is set, so the common case stays cheap.

Tests

test/cli/install/bun-audit.test.ts gains four regressions:

  • --json + --audit-level high → only high/critical advisories remain
  • --json + --audit-level critical → only critical advisories remain
  • --json + --ignore GHSA-… → that advisory is gone, output still parses
  • --json + --audit-level critical on a fixture with only moderate/high
    advisories → output is {}, exit 0

All four fail against main (raw response passes through); all 20 tests in the
suite pass with the fix.

Fixes #31009

@robobun

robobun commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 10:27 PM PT - Jul 1st, 2026

❌ @robobun, your commit 307e827 has 6 failures in Build #67756 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 31013

That installs a local version of the PR into your bun-31013 executable, so you can run:

bun-31013 --bun

@coderabbitai

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a160f8d8-8892-46ff-ad70-162c62228d8c

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0ac42 and 307e827.

📒 Files selected for processing (1)
  • docs/pm/cli/audit.mdx

Walkthrough

bun audit --json now parses and filters the registry response using --audit-level and --ignore, re-serializes the filtered JSON, and sets exit codes from the remaining advisories. Tests and docs were updated to match the new JSON behavior.

Changes

JSON audit filtering and output

Layer / File(s) Summary
JSON filtering utilities and imports
src/runtime/cli/audit_command.rs
Introduces helpers to extract vulnerability severity with moderate fallback, match ignore rules by ID and URL substring, filter vulnerabilities in-place while dropping empty packages, and imports bun_js_printer for JSON serialization.
JSON output path with filtering
src/runtime/cli/audit_command.rs
Replaces --json behavior to parse registry JSON, apply audit-level and ignore filtering, serialize the filtered AST with 2-space indentation, and set exit code based on remaining vulnerable items; parse/serialize failures print raw response.
JSON audit filtering tests
test/cli/install/bun-audit.test.ts
Adds regression tests verifying --json combined with --audit-level and --ignore correctly filters advisories, and that packages with no remaining advisories produce {} output.
Documentation clarification for --json
docs/pm/cli/audit.mdx
Clarifies --json outputs the filtered audit report as JSON and that --audit-level and --ignore apply to JSON output.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: applying audit filters to bun audit --json output.
Description check ✅ Passed The description explains the bug, fix, and verification, though it uses custom headings instead of the template labels.
Linked Issues check ✅ Passed The change satisfies #31009 by making --audit-level filtering apply to JSON output and keeping behavior consistent with ignore filtering.
Out of Scope Changes check ✅ Passed The docs and tests are directly tied to the JSON audit filtering fix, with no clear unrelated changes.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/runtime/cli/audit_command.rs (1)

293-343: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Function signature prevents in-place mutation.

The function takes expr: &Expr (immutable reference) but attempts to mutate the AST in-place. The pattern let ExprData::EObject(mut obj) = expr.data at line 298 and let ExprData::EArray(mut arr) = value.data at line 322 bind copies of the enum payloads, not mutable references. Mutations via retain_mut/retain affect these local copies, not the original expression tree.

To fix this, the function should either:

  1. Take expr: &mut Expr and use mutable pattern matching, or
  2. Build and return a new filtered Expr instead of mutating in-place.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/cli/audit_command.rs` around lines 293 - 343,
filter_audit_response currently takes expr: &Expr but tries to mutate the AST by
pattern-matching ExprData::EObject(mut obj) and using obj.properties.retain_mut
/ arr.items.retain, which only mutates local copies; change the API to accept
expr: &mut Expr and update the match arms to destructure mutable references
(e.g., match &mut expr.data to handle ExprData::EObject(obj) and
ExprData::EArray(arr)) so retain_mut/retain operate on the real tree, or
alternatively rewrite the function to construct and return a new filtered Expr
instead of attempting in-place mutation; update all call sites of
filter_audit_response accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@src/runtime/cli/audit_command.rs`:
- Around line 293-343: filter_audit_response currently takes expr: &Expr but
tries to mutate the AST by pattern-matching ExprData::EObject(mut obj) and using
obj.properties.retain_mut / arr.items.retain, which only mutates local copies;
change the API to accept expr: &mut Expr and update the match arms to
destructure mutable references (e.g., match &mut expr.data to handle
ExprData::EObject(obj) and ExprData::EArray(arr)) so retain_mut/retain operate
on the real tree, or alternatively rewrite the function to construct and return
a new filtered Expr instead of attempting in-place mutation; update all call
sites of filter_audit_response accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e5b11e82-9905-4e16-b73b-2a7c4a7ce456

📥 Commits

Reviewing files that changed from the base of the PR and between 4c8a21b and e5d5992.

📒 Files selected for processing (2)
  • src/runtime/cli/audit_command.rs
  • test/cli/install/bun-audit.test.ts

Comment thread src/runtime/cli/audit_command.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No bugs found, but this is ~160 lines of new Rust touching arena-backed AST mutation and changes bun audit --json to always re-serialize the registry response (not just when filters are set), so a human should sanity-check the output-format change and the in-place Expr filtering.

Extended reasoning...

Overview

This PR makes bun audit --json honor --audit-level and --ignore by parsing the registry response into the JS AST, filtering advisories in place, and re-serializing via bun_js_printer::print_json. It adds four helper functions (vulnerability_severity, vulnerability_matches_ignore, filter_audit_response, serialize_audit_json) to src/runtime/cli/audit_command.rs, rewrites the json_output branch, updates the audit() doc comment (addressing my earlier nit), and adds four regression tests in test/cli/install/bun-audit.test.ts. An unrelated one-line build fix (#include <cassert>) is bundled into src/jsc/bindings/wtf-bindings.cpp.

Security risks

None apparent. The code only reads the npm registry's bulk-advisory response and filters/re-prints it; no new external inputs, auth, or filesystem writes. The --ignore substring match against url mirrors the existing enhanced-output path exactly.

Level of scrutiny

Moderate. This is not a mechanical change: it introduces arena-pointer mutation through Copy Expr handles (let ExprData::EObject(mut obj) = expr.data → obj.properties.retain_mut(...)), which is an established pattern in this codebase but subtle enough that a maintainer should confirm it. More importantly, the --json output is now always round-tripped through print_json with 2-space indentation — even when no --audit-level/--ignore is set — whereas previously it was the registry's raw bytes. The fast path only skips filtering, not re-serialization. That is a user-visible format change for every bun audit --json invocation; the existing snapshot test parses before comparing so it won't catch byte-level differences. This is probably fine (and arguably an improvement), but it's a product decision a human should sign off on.

Other factors

  • The new tests cover the filtering behavior well and the PR claims all 20 tests in the suite pass.
  • The one CI failure (node-http-backpressure.test.ts SIGKILL on aarch64) is unrelated.
  • The bundled <cassert> include is a trivial build fix but is out-of-scope for the stated change.
  • No CODEOWNERS entries cover these paths.

@robobun

robobun commented May 19, 2026

Copy link
Copy Markdown
Collaborator Author

CI has been flaking on unrelated Windows tests (spawn-pipe-leak, test-timers-interval-throw, bun-run-dir) — my diff only touches src/runtime/cli/audit_command.rs + the audit test file + a one-line <cassert> include. The Rust changes compile and the audit test suite (all 20) passes locally. Needs a maintainer to merge — I've used my one CI re-roll.

@robobun
robobun force-pushed the farm/63b997f9/audit-json-filter branch from 122bf0a to 4da0389 Compare May 21, 2026 21:45
Comment thread src/runtime/cli/audit_command.rs Resolved
@robobun

robobun commented May 21, 2026

Copy link
Copy Markdown
Collaborator Author

CI flaky again on unrelated lanes (complex-workspace, s3-stream-cancel-leak SIGABRT, spawn-pipe-leak on Windows). Diff touches only audit_command.rs + the audit test + a docs line. All 20 audit tests pass locally after rebase. Already used my re-roll — needs a maintainer to merge.

@robobun
robobun force-pushed the farm/63b997f9/audit-json-filter branch from 843fb99 to 5a9c3df Compare May 24, 2026 14:09
@robobun

robobun commented May 24, 2026

Copy link
Copy Markdown
Collaborator Author

Post-rebase CI still flaking on unrelated lanes (complex-workspace migration, s3.test.ts). Diff touches only audit_command.rs, the audit test, and one docs line. All 20 audit tests pass locally. Re-roll already spent — needs a maintainer.

@robobun

robobun commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI still flaking on unrelated lanes after rebase (issue/30205 flaky; @duckdb/node-api third-party native segfault). Diff is only audit_command.rs + the audit test + one docs line; all 20 audit tests pass locally. Re-roll budget spent — needs a maintainer to merge.

robobun and others added 4 commits July 1, 2026 22:35
The JSON branch of `bun audit` used to write the raw registry response
straight to stdout. `--audit-level` and `--ignore` were only consulted
by the enhanced printer, so `bun audit --json --audit-level=critical`
still emitted every low/moderate/high advisory.

Parse the response, drop advisories below the threshold (and those
matched by `--ignore`), drop packages whose array becomes empty, then
re-serialize through the shared JSON printer. Exit code now reflects the
post-filter count — matches the enhanced output path.

Fixes #31009
@robobun
robobun force-pushed the farm/63b997f9/audit-json-filter branch from 51b2fa5 to f7d767b Compare July 1, 2026 22:44
@robobun

robobun commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased on main past the SIMD JSON parser rewrite (#33032). Non-trivial resolution: that PR removed the generic bun_json::parse::<true> and made E::Number.value a private field. Since the --json filter mutates the AST in place (retain/retain_mut), I ported to bun_json::parse_utf8 (the classic mutable-AST entry point), switched num.value to num.value(), and re-added the Expr + VecExt imports the new immutable-API code had dropped. All 20 audit tests pass locally.

@mintlify

mintlify Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
bun 🟢 Ready View Preview Jul 1, 2026, 11:03 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/pm/cli/audit.mdx`:
- Around line 44-48: Broaden the `--ignore` option description in the audit docs
because it is not limited to CVEs; update the wording around the `--ignore`
entry in audit.mdx to reflect that the `bun audit` flag can match advisory IDs
and URL substrings as well. Keep the example command, but make the label and
supporting text around `--ignore` accurate and generic enough to cover all
supported ignore targets.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4db4a3d0-7f66-4d85-93c1-4238901950b3

📥 Commits

Reviewing files that changed from the base of the PR and between 843fb99 and 4c0ac42.

📒 Files selected for processing (1)
  • docs/pm/cli/audit.mdx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/pm/cli/audit.mdx`:
- Around line 44-48: Broaden the `--ignore` option description in the audit docs
because it is not limited to CVEs; update the wording around the `--ignore`
entry in audit.mdx to reflect that the `bun audit` flag can match advisory IDs
and URL substrings as well. Keep the example command, but make the label and
supporting text around `--ignore` accurate and generic enough to cover all
supported ignore targets.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4db4a3d0-7f66-4d85-93c1-4238901950b3

📥 Commits

Reviewing files that changed from the base of the PR and between 843fb99 and 4c0ac42.

📒 Files selected for processing (1)
  • docs/pm/cli/audit.mdx
🛑 Comments failed to post (1)
docs/pm/cli/audit.mdx (1)

44-48: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Broaden the --ignore wording.

--ignore does not just accept CVEs here; the implementation also matches advisory IDs and URL substrings, so this description is too narrow and will mislead users.

♻️ Suggested doc tweak
-**`--ignore <CVE>`** - Ignore specific CVEs (repeat the flag to ignore several):
+**`--ignore <ID>`** - Ignore specific advisories (repeat the flag to ignore several):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

**`--ignore <ID>`** - Ignore specific advisories (repeat the flag to ignore several):

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/pm/cli/audit.mdx` around lines 44 - 48, Broaden the `--ignore` option
description in the audit docs because it is not limited to CVEs; update the
wording around the `--ignore` entry in audit.mdx to reflect that the `bun audit`
flag can match advisory IDs and URL substrings as well. Keep the example
command, but make the label and supporting text around `--ignore` accurate and
generic enough to cover all supported ignore targets.

@robobun
robobun force-pushed the farm/63b997f9/audit-json-filter branch from 2c28b7c to 307e827 Compare July 1, 2026 22:57
@robobun

robobun commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the --ignore docs wording in 307e827: it matches against the advisory ID or a substring of the advisory URL (e.g. a GHSA ID), not CVEs specifically, so the label and example were updated to GHSA IDs (which is also what the regression test uses).

Comment thread src/runtime/cli/audit_command.rs Resolved
@robobun

robobun commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Build is green now: all build-rust/build-cpp jobs pass on every platform after the Expr/VecExt import fix (4c0ac42). The only remaining red is one Windows test-bun lane with two unrelated failures: test/cli/install/bun-install.test.ts (flagged flaky by CI) and test/bake/dev/production.test.ts (bake dev server). Neither touches bun audit. Diff is limited to audit_command.rs + the audit test + docs; ready for a maintainer to merge.

@robobun

robobun commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

Closing. #38333 keeps the current bun audit --json contract on purpose: the JSON document stays the full registry report, as with npm, and --audit-level / --ignore decide the exit code (that part is implemented in #38333). Filtering the document itself is not going to change, so this PR is not needed. The exit code half of #31009 is covered by #38333.

@robobun robobun closed this Aug 14, 2026
Jarred-Sumner added a commit that referenced this pull request Aug 14, 2026
…ilter/--catalog, nested overrides, transitive update, and workspace fixes (#38333)

Brings Bun's package manager to parity with pnpm for monorepo workflows,
and fixes the bugs found while checking every command against pnpm's
implementation, pnpm's test suites, pnpm's open issue tracker, pnpm's
docs, npm's arborist fixtures, and — for `bun update` — running real
pnpm and Bun side by side on the same projects.

### What does this PR do?

#### New commands

- **`bun dedupe [--check]`** — collapses duplicate versions in
`bun.lock` onto the smallest set that still satisfies every dependent's
range, using only versions already in the lockfile, then installs. Never
downgrades a direct dependency unless that is the only way to drop a
version; keeps patched versions (and anything needed to reach them, and
says so); refuses to run on a lockfile that is behind `package.json`.
`--check` exits 1 without writing.
- **`bun prune [--production | --omit=…] [--dry-run] [--filter <ws>]`**
— removes everything in `node_modules` that the lockfile does not put
there; `--production` leaves exactly what `bun install --production`
would. Hoisted and isolated layouts, Windows junctions and shims,
workspace links, bundled deps; refuses when `package.json` and
`bun.lock` disagree or when `node_modules` was laid out by a different
linker; understands turbo-pruned checkouts.
- **`bun pm licenses [--json] [--prod|--dev] [--long] [--filter <ws>]`**
— installed packages grouped by license, with a `(dev)` marker and
`paths`/`license`/`description` in `--json`.
- **`bun audit fix [--latest] [--dry-run] [--json]`** — moves each
vulnerable package to the lowest safe version its dependents accept, per
installed instance; rewrites exact pins when that is the only way;
`--latest` also rewrites your own declared ranges (root, workspace,
catalog) so a semver-major fix can be taken, and every blocked or
unfixable item is followed by the command that resolves it (`bun audit
fix --latest`, `bun audit --ignore GHSA-…`); re-audits the tree it
actually installed and reports/exits from that second response (npm's
`_submitQuickAudit`), so an advisory that starts at the version it moved
to is not missed; works across registries; security fixes bypass
`minimumReleaseAge` with an annotation. `bun audit --json` honors
`--audit-level`/`--ignore` for its exit code; `--omit` is honored by
`audit` and `licenses`.

#### `bun update` semantics (pnpm's model)

- A bare `bun update` re-resolves **transitive** packages too — every
edge moves to the newest version its own range (or dist-tag) allows, per
dependent, so `bun.lock` no longer stays stale after an update;
overrides/catalogs changed since the last install are honored. From a
workspace member or `--filter`, only what the selected workspaces reach
is re-resolved; from the root, everything.
- `bun update <name>` reaches any depth, matches `npm:` aliases by real
name, updates in place, never adds to `package.json`, and errors on a
name nothing selected depends on. `-r`/`--filter` fan a named update out
across workspaces. `--latest` never downgrades a locked version that is
ahead of the tag, and `update <name> --latest` also refreshes that
package's own dependencies.
- Plain updates keep dist-tag literals and non-caret ranges (`*`, `1.x`,
`^1 || ^2`) exactly as written and only move the lockfile; `--latest`
rewrites them to the resolved version as before. `bun update -i` applies
only what you selected. New: positional patterns (`bun update
'@types/*'`), `--dev`/`--prod`/`--no-optional`, `-L`, `bun up`.
- `package.json` is written after resolution and `bun.lock`'s declared
ranges, overrides and catalogs are re-derived from the final
`package.json`, replacing the per-command literal rewriting; a no-op
update leaves the file byte-identical.

#### Overrides

- **Nested overrides** (#6608): npm's nested objects, yarn's `a/b` paths
and pnpm's `a>b` selectors, applied to the direct parent→child edge;
**version-scoped targets** (`"lodash@<4.17.21": "4.17.21"`, the shape
`pnpm audit --fix` writes), matched against the dependent's declared
range as pnpm does. Rules persist inside the `overrides` section and the
file is stamped `lockfileVersion: 3` **only when such rules exist** —
existing lockfiles are byte-identical. Flat overrides additionally fix
`$ref` to workspace-member deps, catalog-valued rules going stale, and
warn on pnpm's `-` / `pkg@` forms.

#### Workspaces and filters

- `bun add|remove|update … --filter <ws>` (also `-F`, also `bun install
<pkg> --filter`) edits the selected workspaces' `package.json` files and
**links only those workspaces**, like `bun install --filter`. Filters
gain pnpm's relation selectors (`foo...`, `...foo`, `foo^...`,
`...^foo`) and `{dir}` subtrees, for the install family **and** `bun run
--filter`; `--filter` may precede the subcommand; every command warns
about patterns that match nothing; `add`/`remove` no longer select the
root implicitly.
- `bun add <pkg> --catalog[=name]` reuses an existing catalog entry,
keeps a range an explicit version fits, catalogs the range a package
already declares, decides per target, and refuses workspace names and
local paths; a plain `bun add` uses a default-catalog entry when one
exists. A package defined in both `catalog` and `catalogs.default` is an
error. `catalog:` peers of registry packages bind to the importer's copy
instead of the root catalog.
- `--frozen-lockfile` / `bun ci` on turbo-pruned monorepos: pruned-away
workspaces are tolerated, a survivor depending on a pruned workspace is
an error, catalog subsets are accepted, and an overrides/catalogs change
is a frozen failure.

#### One output vocabulary

Every command here prints the install family's shapes: header, glyph
rows (`+`/`-`/`↑`, dedupe's `↳ name old → new`), exactly one noun-first
summary line with counts and a duration (`2 duplicate versions removed,
3 packages installed (checked 5 packages) [12ms]`, `N packages removed
(checked C) [t]`), no-ops that say what was checked, remedies printed as
copy-pasteable command lines, warnings as `warn:`, `--silent` printing
nothing, and errors with their remedy together on stderr. Transitive and
named updates render as the summary's `↑` rows (once per package;
`--dry-run` prints the same rows plus `N packages would be updated`);
dedupe reports after the install it triggers, so lifecycle-script output
never splits it. A lockfile whose bytes did not change is no longer
rewritten (`Saved lockfile` only prints on a real write;
`--lockfile-only` no-ops print `Done! Checked N packages (no changes)`).
This came out of running every command against fixtures and comparing
with `install`/`add`/`remove` (95 findings, all fixed).

#### Config precedence

A project's `bunfig.toml` now beats any `.npmrc` (project or user-level)
for the same key (npmrc files → bunfig's set fields → CLI); npmrc-only
settings such as `//host/:_authToken` still attach to bunfig-declared
registries, matched by host and path regardless of how either file
spells the trailing slash.

#### Lockfile migration

- `package-lock.json`: rebuilt around a reachability walk that derives
each resolution from the entry itself. Fixes `git+https://github.com/…`
resolutions being written unparseably (the next install threw the
lockfile away), root `bundleDependencies` migrating to an **empty**
lockfile, lockfileVersion 1 (and npm's upcoming 4) making `bun install`
exit 1 instead of resolving fresh, dependency-level bundles,
`dependencies`+`optionalDependencies` double edges, unreferenced entries
aborting the migration, duplicate packages for identical `name@version`
at nested paths, lost `optionalPeers`, lost integrity when a bundled
copy was seen first, and `overrides` not being carried over. All 57 of
arborist's v2/v3 fixture projects are vendored and migrated under
snapshot.
- `pnpm-lock.yaml` v9: bare-hash `patchedDependencies`, snapshot
aliases, `catalog:default`, recorded tarball URLs, git `path:`,
multi-document files, `runtime:` entries, named registries,
peer-suffixed keys chosen per importer, injected workspaces,
manifest-only importer deps.

#### Isolated linker

- An existing store entry whose dependencies re-resolved (override,
dedupe, update) now has its links refreshed on the next install
(measured cost below). `bun prune` builds the same store the installer
builds, so stale `name@version+<peerhash>` variants left by peer bumps
are removed and a kept package's real entry never is (whether it was
installed with full or `--production` features); on the hoisted linker,
dedupe / audit fix / update delete the nested copies whose rows they
collapsed instead of leaving the old copy loadable.
- Blocked entries resume through per-entry intrusive waiter lists
instead of a scan of every store entry after each completion (robobun's
#25983/#28425 attempted this). Measured on the reporter's repro from
#25799 (2,259 store entries) and a synthetic 6,425-entry monorepo, PR
build vs merge-base build: main-thread CPU in the link phase drops 0.85
→ 0.33 s and 5.5 → 0.85 s (the removed work grows quadratically); wall
time is unchanged with spare cores and 16% / 26% faster pinned to one
CPU, the CI/Docker shape in those reports. (The minute-long installs
originally reported were peer resolution, fixed before this PR's base.)
- Two pre-existing leaks surfaced by the new LSan-enabled tests are
fixed: the header buffer of every authenticated registry request, and
the per-entry lifecycle-script lists.

#### Other bug fixes

`bun add x@npm:pkg` writes a range; `bun add --trust a b` no longer
drops `b` when `a` was already trusted; `bun add x --dev` no longer
rewrote every group in `bun.lock`; `catalog:` peer hoisting;
`dependency::Version::eql` treated all `catalog:` specifiers as equal; a
`file:` package whose dependencies reach itself (its own name, an `npm:`
alias under its own name, two link targets depending on each other — the
shapes a `package-lock.json` migration produces, and #25202's
`workspace:.` self-reference) hung `bun install` forever in the hoisting
tree — the migration shapes now install, and #25202's literal shape now
terminates with `Workspace dependency "foo" not found` rather than
installing as npm does; a peer of a `file:` package that was only placed
nested was also written to `optionalPeers` in a migrated bun.lock, so
the next `--frozen-lockfile` failed and a plain install rewrote the
lockfile; `catalog:` literals in `bun update`; alias output in the
install summary; help/completions for everything above.

#### Behavior changes to note in the release notes

- `bun update` moves transitive packages; `bun update <name>` no longer
adds an undeclared package (exit 1); `--production`/`--prod` on update
means "only update `dependencies` and `optionalDependencies`" (a group
filter like `--dev`, not the install flag) and `-r`+names with no match
is an error; `-i` updates only the selection.
- Project `bunfig.toml` overrides any `.npmrc`.
- `bun install <pkg> --filter x` edits `x` (not the root); `bun add y
--filter x` no longer installs a package named `x`; `add`/`remove
--filter '*'` no longer includes the root.
- A plain `bun add x` in a workspace whose default catalog lists `x`
writes `catalog:`; `audit fix` may rewrite exact pins;
`--frozen-lockfile --lockfile-only` writes nothing; overrides/catalog
changes fail frozen installs.
- One-time lockfile churn after upgrading for projects with `catalog:`
peers or dead `pkg@range` override rows; lockfiles that use
nested/scoped overrides are v3 and unreadable by older Bun (only when
opted in). Turborepo, Nx and Dependabot have been checked; the needed
upstream changes are open (nrwl/nx#36666 covers v2 and v3;
vercel/turborepo#13740 accepts v3 and preserves the object rows through
prune — turborepo main today parses v2 and rejects v3; dependabot needs
nothing). Note v2 itself only exists on the 1.4 line.
- `bun audit --json` keeps npm's contract: `--audit-level`/`--ignore`
decide the exit code, the JSON document is the full registry report
(closes #31013 as won't-change). Automatic removal of stale
`node_modules` entries on plain `bun install` (#32974) is separate from
this PR: `bun prune` is the manual form, and dedupe / audit fix / update
now clean up the nested copies they collapse on the hoisted linker;
#32974 should reuse prune's planner, and #29512 (sbom) is sequenced
after this so it can build on `reachable.rs` instead of carrying its own
walk.
- Deliberately kept where we differ from pnpm: root `bun update` covers
the whole workspace; dependents whose ranges allow follow a moved
version (one copy, not two); `--latest` works on transitive names;
`--no-save` touches neither file; prune deletion failures exit 1; audit
requests stay per-registry.

#### Performance

Measured on a 1,113-package Next/Prisma/MUI app (PR build vs a PR build
of the merge base, interleaved, plus canary and 1.3.14): every hoisted
cell is within noise except no-op install, +0.8 ms (+2%, identical
syscalls); isolated no-op is +1.9 ms (+3.9%) — the deliberate cost of
re-checking existing entries' links every install rather than persisting
a stamp file. Everything added is otherwise off the plain-install path
(gated on the feature being used or on a diff), and id-indexed sets are
bitsets.

### How did you verify your code works?

~1,100 new or ported test cases across the install suites (designed
behavior, cases ported from pnpm's suites, pinning tests for pnpm bugs
this implementation is immune to, arborist's fixtures, and the CI review
findings), all `toStrictEqual`; the whole `test/cli/install` directory
passes locally and the existing suites are unchanged except where a
pre-existing expectation was deliberately changed (each listed above).
`bun update` was additionally verified with a rerunnable differential
harness that runs pnpm 11 and this branch on 26 scenario families
against one registry and diffs the resulting resolutions edge by edge —
after this PR only the deliberate differences above remain. Ecosystem:
Turborepo, Nx and Dependabot were checked against the new lockfile
output.

Co-authored work absorbed with credit: @kjanat's #38190 (alias handling,
co-author on the commit), @charpeni's #31143 and @crystalin's #34407
(both superseded), and the tests of the earlier `bun update` PRs (#31752
by @zlotnika, #33127, #36381, #36729, #38224). robobun's #34688
(folder-dependency cycles; its tests are lifted, co-author on the
commit) and #37289 (migrated optionalPeers; its test is lifted,
co-author on the commit) were fixed independently here and are closed by
this PR. #28422's quadratic scan is fixed here as well (already closed).

Related but not closed — `bun prune` gives these a manual fix while the
automatic-cleanup asks stay open: #8662, #26305, #29793, #21216, #16176.
Also related: #10930, #26970, #26751.

Fixes #1343
Fixes #3605
Fixes #14719
Fixes #24122
Fixes #18612
Fixes #20238
Fixes #25826
Fixes #23615
Fixes #26973
Fixes #20593
Closes #31013
Fixes #28959
Fixes #28402
Fixes #27897
Fixes #26675
Fixes #10949
Fixes #18504
Fixes #13388
Fixes #24523
Fixes #6608
Fixes #19059
Fixes #16569
Fixes #8262
Fixes #11901
Fixes #13469
Fixes #25202
Closes #29664
Closes #31143
Closes #34407
Closes #34688
Closes #37289
Closes #38190

---------

Co-authored-by: Kaj Kowalski <info@kajkowalski.nl>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Thanks for this PR — closing it in favor of #38333, which fixes the exit code but keeps the full JSON report. Thanks @embooglement for the report in #31009.

The scenario there is a CI job running bun audit --json --audit-level=critical and getting every low/moderate/high advisory back too. The part that was actually broken was the exit code: --json exited 1 whenever the response had anything in it.

$ bun audit --json --audit-level=critical; echo "exit: $?"
{ ...full registry report... }
exit: 0

$ bun audit --json | jq 'map_values(map(select(.severity == "critical"))) | with_entries(select(.value | length > 0))'
  • bun audit --json keeps the npm audit --json contract: --audit-level and --ignore decide the exit code, the document stays the full report.
  • --ignore GHSA-… works the same way with --json; --prod/--omit still narrow what is sent.
  • Tests cover the --json + --audit-level / --ignore combinations, and the --json section of the bun audit docs now spells this out.

The exit-code fix will be in the next canary (bun upgrade --canary) and in Bun v1.4. If a tool of yours cannot sit behind jq and needs the filtered body, say so here — a concrete case would change this.

(This comment was written by Claude, on behalf of the Bun team.)

This branch was successfully deployed

1 active deployment
staging - docs — 307e8277 Deployed Jul 1, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--json flag overrides --audit-level in bun audit

2 participants