Skip to content

install: honor --recursive and --filter in non-interactive bun update - #33182

Closed
robobun wants to merge 11 commits into
mainfrom
farm/cfbe70a2/update-recursive-workspaces
Closed

robobun wants to merge 11 commits into
mainfrom
farm/cfbe70a2/update-recursive-workspaces

Conversation

@robobun

@robobun robobun commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

What

bun update --recursive (and bun update --filter <pattern>) only rewrote the root/cwd package.json. Workspace members, including their peerDependencies, were left untouched: the flags were effectively ignored by the non-interactive update path.

Closes #33176.

Also implements the --recursive/--filter portion of #23507. Catalog-definition updates for workspace members are out of scope here and remain a follow-up, so that issue is linked rather than auto-closed.

Repro (before this PR)

// package.json
{ "name": "root", "private": true, "workspaces": ["packages/*"] }
// packages/pkg-a/package.json
{ "name": "pkg-a", "dependencies": { "dep": "^1.0.0" }, "peerDependencies": { "peer": "^1.0.0" } }
$ bun install
$ bun update --recursive
# packages/pkg-a/package.json unchanged: dep and peer still ^1.0.0

Only the root updated; every workspace member was skipped.

Cause

--recursive set Do::RECURSIVE and --filter populated filter_patterns, but only update --interactive and outdated ever read them. The non-interactive update path (updatePackageJSONAndInstall.rs) edited a single package.json (the cwd's), and the installer's update gate (PackageManagerEnqueue.rs) re-resolved dependencies only when they belonged to the root workspace (is_root_dependency). Nothing fanned the update out to the other workspaces.

Fix

When bun update is run with --recursive or --filter and no package names:

  • Resolve the target workspace set from the lockfile (all workspaces for --recursive, matched workspaces for --filter), mirroring how update --interactive / outdated already resolve it.
  • Set an install-time update gate (is_update_target_dependency, keyed on stable workspace name hashes so it survives the lockfile remap during install) so the resolver re-resolves dependencies of every selected workspace, not just the root.
  • Run the same pre-install / post-install package.json edit pass on each selected member, so all four dependency groups (including peerDependencies) are rewritten with the resolved versions and original pin style preserved.

Each member gets its own scratch map, so two workspaces can pin the same dependency differently, and a member the update didn't change is not rewritten. Named updates (bun update <pkg> --recursive) are intentionally left on the existing path and unchanged. The default bun update (no flags) takes an early return and is byte-for-byte unchanged.

Tests

test/cli/install/bun-update.test.ts (in-process registry):

  • --recursive updates a member's dependencies and another member's peerDependencies (same dependency name in both, exercising the per-workspace maps).
  • --recursive --latest bumps a member's exact-pinned dependency to the latest version.
  • --filter <name> updates only the matched workspace and leaves sibling workspaces and the root untouched.

Verified fail-before / pass-after: with src/ reverted the new tests fail (member stays ~0.0.3); with the fix they pass. Existing update tests and the non-network workspace tests continue to pass.


[review] gate passed · iteration 3 · 6 files touched

fails on main (without fix)
ASAN without fix: 5 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-update.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (3be51a23e)

test/cli/install/bun-update.test.ts:
(pass) should update to latest version of dependency (~) [490.92ms]
(pass) should update to latest versions of dependencies (~) [420.72ms]
(pass) lockfile should not be modified when there are no version changes, issue#5888 [1282.98ms]
(pass) should support catalog versions in update [263.81ms]
(pass) should support --recursive flag [337.76ms]
528 |   expect(await new Response(stderr).text()).not.toContain("error:");
529 |   expect(await exited).toBe(0);
530 | 
531 |   const a = await file(join(package_dir, "packages", "pkg-a", "package.json")).json();
532 |   const b = await file(join(package_dir, "packages", "pkg-b", "package.json")).json();
533 |   expect(a.dependencies.baz).toBe
... (truncated)

release without fix: 5 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/cli/install/bun-update.test.ts:
(pass) should update to latest version of dependency (~) [28.05ms]
(pass) should update to latest versions of dependencies (~) [12.08ms]
(pass) lockfile should not be modified when there are no version changes, issue#5888 [32.45ms]
(pass) should support catalog versions in update [5.68ms]
(pass) should support --recursive flag [7.16ms]
528 |   expect(await new Response(stderr).text()).not.toContain("error:");
529 |   expect(await exited).toBe(0);
530 | 
531 |   const a = await file(join(package_dir, "packages", "pkg-a", "package.json")).json();
532 |   const b = await file(join(package_dir, "packages", "pkg-b", "package.json")).json();
533 |   expect(a.dependencies.baz).toBe("~0.0.5");
                                   ^
error: expect(received).toBe(expected)

Expected: "~0.0.5"
Received: "~0.0.3"

      at <anonymous> (/workspace/bun/test/cli/install/bun-update.test.ts:533:30)
(fail) --recursive updates dependencies and peerDependencies in workspace members [10.79ms]
572 |   });
573 |   expect(await new Response(stderr).text()).not.toContain("error:");
574 |   expect(await exited).toBe(0);

... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/bun-update.test.ts
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
bun test v1.4.0 (3be51a23e)

test/cli/install/bun-update.test.ts:
(pass) should update to latest version of dependency (~) [482.42ms]
(pass) should update to latest versions of dependencies (~) [501.22ms]
(pass) lockfile should not be modified when there are no version changes, issue#5888 [1301.17ms]
(pass) should support catalog versions in update [260.26ms]
(pass) should support --recursive flag [268.16ms]
(pass) --recursive updates dependencies and peerDependencies in workspace members [378.64ms]
(pass) --recursive --latest updates workspace members to the latest version [439.88ms]
(pass) --filter updates only matching workspaces, leaving siblings and root untouched [440.13ms]
(pass) named update with --recursive only updates the named package 
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
info: syncing channel updates for nightly-2026-05-06-x86_64-unknown-linux-gnu
info: latest update on 2026-05-06 for version 1.97.0-nightly (e95e73209 2026-05-05)
info: component rust-src is up to date
info: checking for self-update (current version: 1.29.0)
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     3be51a23e8
  features     (none)

22 deps, 106 codegen, 1168 objects in 787ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1231] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b77)

Checked 124 installs across 170 packages (no changes) [12.00ms]
[2/1231] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b77)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1231] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b77)

Checked 129 installs across 147 packages (no changes) [11.00ms]
[4/1231] gen ErrorCode+*.h
[5/1231] gen bindgenv2
[6/1231] fetch picohttpparser
[picohttpparser] up to date
[7/1231] fetch libjpeg-turbo
[libjpeg-turbo] up to date

... (truncated)
diff hotspot
src/install/PackageManager.rs                      |   7 +
 src/install/PackageManager/PackageJSONEditor.rs    |  33 +-
 .../PackageManager/PackageManagerEnqueue.rs        |  12 +-
 .../PackageManager/updatePackageJSONAndInstall.rs  | 448 ++++++++++++++++++++-
 src/install/lockfile.rs                            |  19 +
 test/cli/install/bun-update.test.ts                | 363 +++++++++++++++++
 6 files changed, 850 insertions(+), 32 deletions(-)

gate history · 1 passed · 0 rejected · iteration 3

evidence per changed file
file                                                      reads  edits  tests
src/install/PackageManager.rs                                 3      2      0
src/install/PackageManager/PackageJSONEditor.rs               7      9      0
src/install/PackageManager/PackageManagerEnqueue.rs           3      2      0
…c/install/PackageManager/updatePackageJSONAndInstall.rs     19     23      0
src/install/lockfile.rs                                       3      3      0
test/cli/install/bun-update.test.ts                           5      4      0

root cause · written by the author bot

The root cause was that non-interactive bun update only applied version updates to the root package.json, so with --recursive or --filter the manifests of workspace members, including their peerDependencies, were never rewritten. The fix makes the update path fan out across all matched workspace packages, editing each member's package.json alongside the root. It also preserves catalog: protocol specifiers during that rewrite so catalog references are not clobbered with concrete versions.

@robobun

robobun commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:32 AM PT - Aug 10th, 2026

@robobun, your commit 7b7f291 is building: #91533

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. support --recursive/--filter and catalogs in bun update (non interactive) #23507 - Requests --recursive/--filter support in non-interactive bun update, which is exactly what this PR implements

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #23507

🤖 Generated with Claude Code

@robobun

robobun commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. Linked #23507 in the description rather than using Fixes: this PR implements the --recursive/--filter part, but that issue also asks for catalog-definition updates in workspace members, which this PR does not cover yet. Keeping it open so the catalog follow-up is tracked.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR adds workspace-targeted handling for unnamed bun update commands with --recursive and --filter. It tracks selected workspace hashes, updates dependency eligibility, edits selected manifests before installation, reapplies resolved versions afterward, and adds regression tests.

Changes

Workspace-targeted bun update

Layer / File(s) Summary
PackageManager workspace targeting field
src/install/PackageManager.rs
Adds update_workspace_name_hashes and initializes it to None in both construction paths.
PackageJSONEditor per-workspace update state
src/install/PackageManager/PackageJSONEditor.rs
edit_update_no_args now receives per-workspace update state and an optional workspace hash. It records and consumes updates through the supplied map.
Lockfile dependency targeting
src/install/lockfile.rs, src/install/PackageManager/PackageManagerEnqueue.rs
Adds workspace-aware dependency targeting and uses it for update eligibility. catalog: dependencies remain root-scoped.
Workspace update planning and manifest commits
src/install/PackageManager/updatePackageJSONAndInstall.rs
Selects workspaces from recursive or filter options, prepares selected manifests before installation, reapplies resolved versions afterward, preserves formatting, and writes only selected changed files.
CLI regression coverage
test/cli/install/bun-update.test.ts
Tests recursive updates, --latest, named-package scoping, catalog preservation, path filters, and negated filters.

Possibly related PRs

  • oven-sh/bun#36360: Extends the same workspace-targeted bun update implementation and update-state flow.
  • oven-sh/bun#36379: Also changes update eligibility and catalog: dependency handling.
  • oven-sh/bun#36446: Modifies bun update handling for catalog: references.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: supporting recursive and filtered non-interactive bun update behavior.
Description check ✅ Passed The description explains the problem, cause, fix, scope, linked issues, and verification results, although its headings differ from the template.
Linked Issues check ✅ Passed The changes satisfy issue #33176 by updating workspace member peerDependencies during bun update --recursive.
Out of Scope Changes check ✅ Passed The implementation and tests remain related to workspace update behavior and do not introduce 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.

Actionable comments posted: 3

🤖 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 `@src/install/PackageManager/updatePackageJSONAndInstall.rs`:
- Around line 837-841: The workspace update flow in updatePackageJSONAndInstall
should only fall back to WorkspaceUpdatePlan::cwd_only() when
manager.load_lockfile_from_cwd::<true>() returns LoadResult::NotFound, not when
it returns LoadResult::Err(_). Update the logic around load_lockfile_from_cwd
and WorkspaceUpdatePlan::cwd_only() so parse/read failures are propagated as
command failures while preserving the fallback only for a missing lockfile.
- Around line 1013-1015: The `get_or_resolve` path in
`updatePackageJSONAndInstall` is silently skipping selected workspaces when
their package.json cannot be read or parsed, which can leave the lockfile
updated without rewriting that workspace. Change the `GetResult::ParseErr(_) |
GetResult::ReadErr(_)` branch to fail the command instead of returning
`Ok(None)`, and propagate an error from the workspace rewrite flow so any
selected workspace in `manager.update_workspace_name_hashes` must be readable
and parseable. Keep the behavior localized around `updatePackageJSONAndInstall`
and the `GetResult` match arm so the selected workspace update either completes
fully or aborts.

In `@test/cli/install/bun-update.test.ts`:
- Around line 486-635: The new workspace update tests cover flag-only
recursive/filter behavior, but they miss the named-package path that should
still keep its existing behavior. Add coverage around bun update baz --recursive
(and, if relevant, bun update baz --filter pkg-a) using the same test setup and
symbols like WorkspaceUpdatePlan and MemberUpdate to verify the refactor still
resolves and writes the target package correctly without unexpectedly fanning
out to every workspace or changing untouched members.
🪄 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: 6635a5ee-8d69-4cdf-8ade-0d96e00c4e7b

📥 Commits

Reviewing files that changed from the base of the PR and between d816daf and ae26585.

📒 Files selected for processing (6)
  • src/install/PackageManager.rs
  • src/install/PackageManager/PackageJSONEditor.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • src/install/lockfile.rs
  • test/cli/install/bun-update.test.ts

Comment thread test/cli/install/bun-update.test.ts Resolved

@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 `@src/install/PackageManager/updatePackageJSONAndInstall.rs`:
- Around line 835-839: The multi-line comment near the workspace-member probing
logic is too verbose and exceeds the repo’s 3-line comment limit. Condense the
explanation around the probe without lockfile and the follow-up
install_with_manager behavior into at most 3 lines, keeping the intent clear
while preserving the key symbols and flow context in
updatePackageJSONAndInstall.
🪄 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: 59c166b5-2ef8-4c25-ba84-78489957ace9

📥 Commits

Reviewing files that changed from the base of the PR and between 35286cc and 8a9be1d.

📒 Files selected for processing (2)
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • test/cli/install/bun-update.test.ts

@robobun

robobun commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status for reviewers (build 72411, after the rebase onto current main): 285 of 287 jobs pass, including every build step and all but one x64-asan test-bun shard. The earlier unrelated failures (darwin artifact-download timeout, alpine test-http-max-http-headers.js gap) no longer occur on the rebased base.

The single remaining failure is one :debian: 13 x64-asan - test-bun shard where test/js/node/test/parallel/test-worker-message-port-transfer-terminate.js exits with SIGABRT. That is a Worker/MessagePort teardown abort in node-compat worker code, unrelated to this change (which only touches src/install/** and test/cli/install/**; the other 231 files on that shard all pass, including the new update tests). It is a main-branch breakage and is already being fixed separately.

The change itself is complete and ready for review/merge.

@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

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/install/PackageManager/PackageJSONEditor.rs (1)

331-331: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Track update state per dependency occurrence, not just package name.

get_or_put(key_str) plus fetch_swap_remove(key_str) updates only the first matching dependency group. If a selected workspace has the same package in devDependencies and peerDependencies, the later group remains stale. Store entries by (group, name) or keep per-name entries for each occurrence so every dependency group preserves its own pin style and gets rewritten.

Also applies to: 408-408

🤖 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/install/PackageManager/PackageJSONEditor.rs` at line 331, Track update
state per dependency occurrence instead of only by package name in
PackageJSONEditor::update_dependencies (and the later fetch_swap_remove path).
The current use of updating_packages.get_or_put(key_str) and
fetch_swap_remove(key_str) collapses same-name entries across dependency groups,
so a package present in devDependencies and peerDependencies can leave one group
stale. Change the bookkeeping to key by both dependency group and name, or
otherwise store separate entries per occurrence, so each group keeps its own pin
style and is rewritten independently.
🤖 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.

Outside diff comments:
In `@src/install/PackageManager/PackageJSONEditor.rs`:
- Line 331: Track update state per dependency occurrence instead of only by
package name in PackageJSONEditor::update_dependencies (and the later
fetch_swap_remove path). The current use of
updating_packages.get_or_put(key_str) and fetch_swap_remove(key_str) collapses
same-name entries across dependency groups, so a package present in
devDependencies and peerDependencies can leave one group stale. Change the
bookkeeping to key by both dependency group and name, or otherwise store
separate entries per occurrence, so each group keeps its own pin style and is
rewritten independently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ca4cec85-4cb2-4e67-b8b7-559e4efaba77

📥 Commits

Reviewing files that changed from the base of the PR and between 8a9be1d and 51575fb.

📒 Files selected for processing (4)
  • src/install/PackageManager/PackageJSONEditor.rs
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • src/install/lockfile.rs
  • test/cli/install/bun-update.test.ts

@robobun

robobun commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

On the cross-group dedup finding (updating_packages keyed by name, so a package in two dependency groups of the same workspace updates only the first): this is pre-existing, intentional behavior in edit_update_no_args, not something this PR changes. The found_existing check is documented in place:

// If a dependency is present in more than one dependency group, only one of its versions
// will be updated. The group is determined by the order of `dependency_groups`, the same
// order used to choose which version to install.

That logic predates this PR (from the Rust rewrite, #30412). This PR only scopes that map per workspace so that different workspaces sharing a dependency name each update independently (covered by the --recursive deps+peerDependencies test); it does not touch the within-workspace cross-group semantics. Keying by (group, name) would change long-standing bun update behavior for the root as well (and would start bumping peer ranges on a regular-dep update, which is usually not wanted), so it is out of scope here. Happy to open a separate issue if that semantics change is desired.

@robobun
robobun force-pushed the farm/cfbe70a2/update-recursive-workspaces branch from c779304 to 3be51a2 Compare July 13, 2026 06:31

@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 new issues found; all prior inline findings have been addressed or explicitly deferred as follow-ups. Deferring to a human reviewer given the size and reach of the change — ~400 lines of new package-manager logic including a new resolver gate, per-workspace package.json rewriting via raw-pointer cache access, and a behavior change on the shared edit_update_no_args path (catalog handling).

What was reviewed:

  • Resolver gate: is_update_target_dependency falls back to is_root_dependency when no plan is set, so default bun update and named updates keep prior behavior.
  • Lockfile probe now uses <false> gated on do_.load_lockfile(), so no double-migration/banner; install_with_manager still owns the real load and error policy.
  • Root workspace routed through the member path now passes name_hash = None (matching the get_workspace_package_id convention) instead of relying on the fallback.
  • catalog: deps now early-continue in edit_update_no_args — verified this affects the cwd path too (intentional per the added catalog test), not just fanned-out members.
Extended reasoning...

Overview

Implements bun update --recursive / --filter for the non-interactive path. Adds update_workspace_name_hashes state on PackageManager, a new is_update_target_dependency gate in lockfile.rs (called from PackageManagerEnqueue.rs in place of is_root_dependency), and ~350 lines of new planning/commit logic in updatePackageJSONAndInstall.rs (WorkspaceUpdatePlan, MemberUpdate, prepare_workspace_update_plan, select_all_workspaces/select_filtered_workspaces, prepare_member_before_install, commit_workspace_member_update, print_package_json). Refactors edit_update_no_args in PackageJSONEditor.rs to accept an external per-workspace updating_packages map and workspace_name_hash, and changes its catalog handling to skip catalog: deps entirely rather than allowing them through the filter. Seven new tests in bun-update.test.ts.

Security risks

None identified. Inputs are workspace names/paths from the lockfile and CLI filter patterns, matched via the existing WorkspaceFilter/glob machinery already used by outdated and update --interactive. Member package.json paths are joined against top_level_dir from lockfile-recorded relative paths, not user-supplied strings. No network, auth, or crypto surface.

Level of scrutiny

High. This is a user-facing feature in the package manager touching the install-time resolver gate and multi-file package.json rewriting. It uses the file's established *mut MapEntry raw-pointer pattern to work around borrowck across workspace_package_json_cache.get_with_path (with SAFETY comments matching the cwd path's), but each new member iteration re-enters get_with_path, so the invariant that no prior entry pointer is held across calls needs to hold. The edit_update_no_args catalog change affects the default/cwd path as well as the new fan-out — the added test covers the member case, and the pre-existing --dry-run catalog test still passes, but a human should confirm the shared-path semantics change is intended.

Other factors

All prior inline findings from earlier review passes are resolved (double lockfile load/migration, root-as-member name_hash convention, comment-length nits, unreadable-member hard-fail) or explicitly acknowledged as follow-ups (third copy of the workspace-filter matcher; missing ^ old -> new summary lines for member-only deps). CI is reported green on the lanes this touches. The default no-flag bun update path early-returns WorkspaceUpdatePlan::cwd_only() before any lockfile probe, and named updates skip planning entirely, so the existing common paths are structurally unchanged. Given the scope, the raw-pointer usage, the shared-path behavior change, and the two acknowledged follow-up gaps, this warrants a human sign-off rather than bot approval.

robobun added a commit that referenced this pull request Jul 29, 2026
…ign named-update comment with consolidated semantics
robobun added a commit that referenced this pull request Jul 29, 2026
…ign named-update comment with consolidated semantics
Jarred-Sumner added a commit that referenced this pull request Jul 31, 2026
… workspace root (#36379)

Follow-up to #36304.

## Problem

`bun update` / `bun update -r` (no `--latest`) is a no-op for catalog
entries when run from the workspace root: a catalog entry `^1.0.0`
locked to 1.0.0 stays on 1.0.0 after 1.5.0 is published, while a direct
dependency with the identical range moves to 1.5.0. Only `--latest`
bumps catalogs.

```
# root package.json: workspaces.catalog = { "dep": "^1.0.0" }
# packages/app/package.json: dependencies = { "dep": "catalog:" }
# lockfile: dep@1.0.0, registry now has dep@1.5.0

bun update            # -> "no changes", catalog stays ^1.0.0, dep@1.0.0
bun update -r         # -> "no changes"
bun update -r --latest # -> catalog -> ^1.5.0 (works)
```

The only existing non-`--latest` test ran update from inside the
workspace package, where this already worked.

## Cause

`get_or_put_resolved_package_with_find_result` gates re-resolution on
`is_root_dependency(dependency_id)`, i.e. "is this a direct dependency
of the package in cwd". A `catalog:` reference lives in a workspace
package, so when running from the root it fails that check,
`should_update` is false, and `get_package_id` dedupes onto the locked
version instead of taking the manifest's best match. With `--latest` the
catalog text is rewritten to `latest` before install, which trips
`catalogs_changed` and clears the resolution, bypassing the dedupe.

(Separately, `-r` is not read anywhere in the non-interactive resolve
path, so it is equivalent to no flag here; that's #36360 / #33182.)

## Fix

In `should_update`, treat a `catalog:` reference
(`dependency.version.tag == Catalog`) as eligible for re-resolution
regardless of cwd. Catalog definitions are a root-level concept shared
across workspaces; re-resolving them matches what #36304 already does
for the package.json rewrite in `edit_catalogs_after_update`.

## Tests

New in `test/cli/install/catalogs.test.ts`: writes a lockfile pinning
`no-deps@1.0.0` with a catalog range `^1.0.0` (the registry has 1.1.0),
runs `bun update` / `bun update -r` from the root, asserts the catalog
is rewritten to `^1.1.0`, `node_modules/no-deps` is 1.1.0, and the
lockfile no longer contains `no-deps@1.0.0`.

Fail-before (release canary):
```
(fail) update > update without --latest from root moves catalogs within range (no args)
(fail) update > update without --latest from root moves catalogs within range (-r)
  expected catalog { "no-deps": "^1.1.0" }, received { "no-deps": "^1.0.0" }
```

With fix: `catalogs.test.ts` 18/18, `bun-update.test.ts` 6/6,
`bun-install-registry.test.ts -t update` 16 pass + 1 todo,
`bun-workspaces.test.ts` 63/63, `bun-add.test.ts` 54/54,
`bun-lock.test.ts` 13/13.

<!-- robobun:evidence:begin -->

---

**[review]** gate passed · iteration 2 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: BUILD FAILED (no junit output)
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/catalogs.test.ts
ninja: Entering directory `/workspace/bun/build/debug'
[1/104] gen ErrorCode+*.h
[2/45] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[3/45] gen cpp.rs (cppbind)
[4/45] gen JSSink.{cpp,h,lut.h,rs}
generated_jssink.rs: 6 sinks, 72 exported symbols
Generating /workspace/bun/build/debug/codegen/JSSink.lut.h from /workspace/bun/build/debug/codegen/JSSink.lut.txt
[5/45] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 239 extern-C blocks audited
[6/45] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (13 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (fcf2849)

test/cli/install/catalogs.test.ts:
(pass) basic > both catalog and catalogs in top-level [42.17ms]
(pass) basic > both catalog and catalogs in workspaces [16.31ms]
(pass) basic > detect changes (bun.lockb) [23.66ms]
(pass) basic > detect changes (bun.lock) [24.12ms]
(pass) update > --latest updates catalog versions in top-level [18.41ms]
(pass) update > --latest updates catalog versions in workspaces [19.24ms]
(pass) update > --latest updates catalog versions with -r [19.63ms]
(pass) update > --frozen-lockfile passes after --latest updates catalogs [22.89ms]
(pass) update > --latest run from inside a workspace package updates the root catalog [17.98ms]
(pass) update > --latest updates the same package independently per catalog [19.11ms]
(pass) update > --latest --dry-run does not modify any package.json (from root) [18.94ms]
(pass) update > --latest --dry-run does not modify any package.json (from workspace) [16.02ms]
(pass) update > update without --latest from root moves catalogs within range (no args) [7.38ms]
(pass) update > update without --latest from root moves catalogs within range (-r) [6.06ms]
(pass) update > update wi
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/cli/install/catalogs.test.ts
bun test v1.4.0 (02dc295)

test/cli/install/catalogs.test.ts:
(pass) basic > both catalog and catalogs in top-level [409.47ms]
(pass) basic > both catalog and catalogs in workspaces [333.92ms]
(pass) basic > detect changes (bun.lockb) [519.80ms]
(pass) basic > detect changes (bun.lock) [509.54ms]
(pass) update > --latest updates catalog versions in top-level [406.88ms]
(pass) update > --latest updates catalog versions in workspaces [372.94ms]
(pass) update > --latest updates catalog versions with -r [378.63ms]
(pass) update > --frozen-lockfile passes after --latest updates catalogs [544.80ms]
(pass) update > --latest run from inside a workspace package updates the root catalog [445.30ms]
(pass) update > --latest updates the same package independently per catalog [390.07ms]
(pass) update > --latest --dry-run does not modify any package.json (from root) [382.96ms]
(pass) update > --latest --dry-run does not modify any package.json (from workspace) [362.05ms]
(pass) update > update without --latest from
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 630ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/82] gen ErrorCode+*.h
[2/37] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[3/37] gen cpp.rs (cppbind)
[4/37] gen JSSink.{cpp,h,lut.h,rs}
generated_jssink.rs: 6 sinks, 72 exported symbols
Generating /workspace/bun/build/release/codegen/JSSink.lut.h from /workspace/bun/build/release/codegen/JSSink.lut.txt
[5/37] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 239 extern-C blocks audited
[6/37] gen ZigGeneratedClasses.{cpp,h,rs}
Found 2 classes from /workspace/bun/src/jsc/resolve_message.classes.ts
  - ResolveMessage (13 fields)
  - BuildMessage (10 fields)
Found 1 classes from /workspace/bun/src/runtime/api/Archive.classes.ts
  - Archive (4 fields, 1 class fields)
Found 2 classes from /workspace/bun/src/runtime/api/BunObject.classes.ts
  - ResourceUsage (8 fields)
  - Subprocess (20 fields)
Found 1 classes from /workspace/bun/src/runtime/api/cron.classes.ts
  - CronJob (5 fields)
Found 3 classes from /workspac
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
.../PackageManager/PackageManagerEnqueue.rs        |  7 ++-
 test/cli/install/catalogs.test.ts                  | 69 ++++++++++++++++++++++
 2 files changed, 73 insertions(+), 3 deletions(-)
```

</details>

**gate history** · 3 passed · 0 rejected · iteration 2

<details><summary>evidence per changed file</summary>

```
file                                                 reads  edits  tests
src/install/PackageManager/PackageManagerEnqueue.rs      9      4      0
test/cli/install/catalogs.test.ts                        1      3      0
```

</details>

<!-- robobun:evidence:end -->

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
robobun added a commit that referenced this pull request Jul 31, 2026
…-resolve every named-update target

Consolidates #33182 and #32947 on top of current main.

Fixes #23507
Fixes #33176
Fixes #29357

bun update --recursive/--filter (no named packages):
- Resolve the target workspace set from the lockfile via
  WorkspaceFilter::select_workspaces (union of positive patterns minus
  negations, shared with bun outdated / update -i).
- Store update_target_workspaces as (name_hash, name) pairs so the
  install-time should_update gate re-resolves dependencies of every
  selected workspace; membership is checked by hash then name.
- Under --latest, the manifest lookup uses dist-tag latest for an
  npm/dist-tag dep of a targeted workspace whose version was not
  substituted by a catalog: or overrides entry.
- After install, one loop writes resolved versions to each selected
  workspace's package.json via edit_update_no_args_in (split-borrow
  variant; no raw pointers added). catalog: references are preserved.

bun update <name>:
- should_update treats every dependency whose name matches a request
  as an update target.
- install_with_manager drops and re-enqueues every matching slot.

WorkspaceFilter::select_workspaces is extracted once and called from
bun outdated, bun update -i, and this path, replacing three local
copies; this also fixes bun outdated --filter a --filter b returning
nothing (the copies ANDed filters).
@juriadams

Copy link
Copy Markdown

Does this need a bump?

robobun and others added 4 commits August 10, 2026 12:42
`bun update --recursive` (and `--filter`) only rewrote the root/cwd
package.json. Workspace members, including their peerDependencies, were
left untouched because the non-interactive update path never fanned the
update out to the selected workspaces; `--recursive`/`--filter` were
effectively ignored.

Resolve the target workspace set from the lockfile (all workspaces for
`--recursive`, matched workspaces for `--filter`), set an install-time
update gate so the resolver re-resolves those workspaces' dependencies,
and run the package.json edit pass on each selected member. Each member
gets its own scratch map so two workspaces can pin the same dependency
differently, and an unchanged member is not rewritten. Named updates
(`bun update <pkg>`) keep their existing behavior.
Address review feedback on the recursive/filter update fan-out:

- When a workspace selected by --recursive/--filter has a package.json that
  cannot be read or parsed, fail the command (matching the cwd path) instead
  of silently skipping it. Its dependencies are already in the update gate, so
  skipping the rewrite would leave the lockfile and package.json inconsistent.
- Add a regression test asserting that a named update (`bun update <pkg>
  --recursive`) keeps its existing cwd-scoped behavior and does not fan out to
  workspace members.
…orkspace

Two refinements to the recursive/filter update fan-out:

- `prepare_workspace_update_plan` loaded the lockfile with migration enabled
  (`<true>`), and `install_with_manager` loads it again the same way. For a repo
  with only a foreign lockfile that meant migrating (and printing the "migrated
  lockfile" banner) twice. The plan only needs the workspace list, so probe with
  `<false>` and gate it on `do_.load_lockfile()`; install still performs the real
  migrating load and owns the lockfile-error policy.
- When `--recursive` runs from inside a workspace member, the root package
  (tag Root) is routed through the member path. Pass `None` as its workspace name
  hash (the convention `get_workspace_package_id` honors) instead of the root's
  hash, which only matched the "should not happen" fallback.
Comment thread src/install/lockfile.rs Resolved

@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: 4

🤖 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 `@src/install/lockfile.rs`:
- Around line 869-883: Replace the per-call workspace scan in
is_update_target_dependency and get_workspace_pkg_if_workspace_dep with a
precomputed DependencyID membership set for the selected workspaces. Build and
store this lookup alongside update_workspace_name_hashes when the update plan is
configured, rebuild it after clean_with_logger remaps dependency IDs using the
durable name-hash list, and have is_update_target_dependency perform a
constant-time membership check while preserving the existing root-dependency
fallback.

In `@src/install/PackageManager/PackageJSONEditor.rs`:
- Around line 366-367: Update clean_with_logger so a missing workspace member
hash from get_workspace_package_id is treated as an explicit miss before reading
resolutions or calling commit_workspace_member_update. Do not fall back to
package ID 0; return the existing appropriate error or absence result and
preserve normal processing for valid member IDs.

In `@src/install/PackageManager/updatePackageJSONAndInstall.rs`:
- Around line 895-901: Prevent the workspace-member commit loop around
commit_workspace_member_update from rewriting the root package.json from stale
plan-time contents after catalog updates. When the catalog path has already
written the root manifest, exclude the root member from this loop or re-read its
current manifest before committing it, while preserving commits for non-root
members.
- Around line 1257-1284: Refactor print_package_json_into_cache_entry to reuse
print_package_json for serialization instead of duplicating the BufferWriter
setup, print_json invocation, and crash handling. Preserve its existing
cache-entry content replacement and stale_contents update, passing the same
source, root, indent, and preserve_newline values to print_package_json.
🪄 Autofix

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: f1286d2f-99d2-4eee-b260-4dcf4222ee38

📥 Commits

Reviewing files that changed from the base of the PR and between 827475e and 87f6c09.

📒 Files selected for processing (6)
  • src/install/PackageManager.rs
  • src/install/PackageManager/PackageJSONEditor.rs
  • src/install/PackageManager/PackageManagerEnqueue.rs
  • src/install/PackageManager/updatePackageJSONAndInstall.rs
  • src/install/lockfile.rs
  • test/cli/install/bun-update.test.ts

Comment thread src/install/lockfile.rs Resolved
When `bun update --recursive` runs from inside a workspace, the root becomes a
fanned-out member. Its commit previously ran after the catalog pass and rewrote
the root package.json from the plan-time snapshot, reverting catalog-definition
updates whenever the root's own dependencies also changed. The member commit
loop now runs before the catalog pass and refreshes each written member's cache
entry, so the catalog pass composes on top of the dependency edits.

Also skip committing a member whose workspace vanished from the re-resolved
lockfile (a stale-lockfile edge where `get_workspace_package_id` would fall back
to the root id), and reuse `print_package_json` in
`print_package_json_into_cache_entry` instead of duplicating the printer setup.

@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.

Additional findings (outside current diff — PR may have been updated during review):

  • 🔴 src/install/PackageManager/updatePackageJSONAndInstall.rs:764-769 — bun update --filter <not-root> --latest from a root that defines a catalog now saves bun.lock with the catalog dep re-resolved to latest, but the new cwd_in_target write gate skips the root package.json — so on disk the catalog range stays at the old value while the lockfile holds a version outside it, and the next bun install silently re-resolves/downgrades it. edit_catalogs_before_update (and the Tag::Catalog resolver bypass) run regardless of cwd_in_target, so either gate the catalog --latest rewrite on the root being an update target, or write the root when editing_catalogs even if !plan.cwd_in_target.

    Extended reasoning...

    What the bug is

    With this PR, bun update --filter pkg-a --latest run from the workspace root where the root package.json defines a catalog (or workspaces.catalog) leaves the on-disk root package.json untouched while bun.lock is saved with the catalog dependency re-resolved to the actual latest. The result is a lockfile whose catalog resolution lies outside the catalog range still written in the root manifest. On the next bun install, the locked version no longer satisfies the on-disk catalog range and is re-resolved/downgraded — the update is silently undone.

    The specific code path

    1. prepare_workspace_update_plan selects only pkg-a. Root (cwd_pkg_id) is not in selected, so the for &pkg_id in &selected loop never sets cwd_in_target = true, and root is not pushed into plan.members either. → plan.cwd_in_target = false, plan.members = [pkg-a].
    2. edit_catalogs_before_update (updatePackageJSONAndInstall.rs ~L526) is gated only on subcommand == Update && update_requests.is_empty(), not on plan.cwd_in_target. With Do::UPDATE_TO_LATEST set, it rewrites every root catalog entry to the literal "latest" in the AST, then print_package_json_into_cache_entry + reparse_root push that into the workspace_package_json_cache entry for the root path.
    3. install_with_manager reads the root package.json from that same cache entry, so it parses catalog: { react: "latest" }. The resolver gate in PackageManagerEnqueue.rs short-circuits on dependency.version.tag == Tag::Catalog before is_update_target_dependency, so pkg-a's "react": "catalog:" re-resolves against the in-memory "latest" regardless of update_workspace_name_hashes. bun.lock is saved with (say) react@18.3.1.
    4. Post-install, the from-root branch editing_catalogs && manager.workspace_name_hash.is_none() runs edit_catalogs_after_update, which correctly computes ^18.3.1 into new_package_json, and that is printed into new_package_json_source.
    5. The disk write at L764–769 is now gated on plan.cwd_in_target || subcommand != Subcommand::Update → false || false → skipped. The alternate root-catalog write path (~L697) requires manager.workspace_name_hash.is_some() (running from a member), which is also false. Root is not in plan.members, so the member-commit loop doesn't touch it either. The updated catalog is never written anywhere.

    Why existing code doesn't prevent it

    The three post-install root-write paths are each gated in a way that excludes this case:

    • The cwd write (L767) requires plan.cwd_in_target — false when --filter excludes root.
    • The from-workspace catalog write (~L697) requires workspace_name_hash.is_some() — false when running from root.
    • The member-commit loop only visits plan.members — root is deliberately excluded (pkg_id == cwd_pkg_id → continue).

    Meanwhile the two paths that cause the lockfile to move — edit_catalogs_before_update's --latest rewrite and the Tag::Catalog bypass in the resolver gate — are not gated on the root being an update target. So the lockfile side updates, the manifest side doesn't.

    Impact

    Silent lockfile/manifest divergence introduced by this PR. Before this PR --filter was a no-op on the non-interactive update path, so bun update --filter pkg-a --latest behaved as bun update --latest and wrote the root (with the bumped catalog) unconditionally. This PR's new write gate desyncs from the ungated catalog rewrite. The trigger — --filter <workspace> --latest in a monorepo that uses catalogs — is a reasonable command in exactly the kind of repo catalogs are for, and the failure mode (next bun install quietly reverts the update) is confusing to diagnose.

    The non---latest case is milder: the lockfile still moves within the existing catalog range so the next install is stable, but the root's catalog literal is still not bumped to the resolved version even though edit_catalogs_after_update computed it.

    Step-by-step proof

    Setup at repo root:

    // package.json
    { "name": "root", "workspaces": ["packages/*"], "catalog": { "react": "^17.0.0" } }
    // packages/pkg-a/package.json
    { "name": "pkg-a", "dependencies": { "react": "catalog:" } }

    bun install → lockfile has react@17.0.2.

    bun update --filter pkg-a --latest from root:

    • plan: selected = [pkg-a], cwd_in_target = false, members = [pkg-a], update_workspace_name_hashes = Some([hash(pkg-a)]).
    • edit_catalogs_before_update: root cache entry becomes catalog: { react: "latest" }; editing_catalogs = true.
    • install: resolver sees pkg-a's react dep with Tag::Catalog → should_update = true (bypass) → catalog map returns "latest" → resolves react@18.3.1. Lockfile saved.
    • post-install: edit_catalogs_after_update(&new_package_json) writes catalog: { react: "^18.3.1" } into new_package_json; printed into new_package_json_source.
    • write gate: WRITE_PACKAGE_JSON && (false || false) → skipped. From-workspace catalog branch: workspace_name_hash.is_some() is false → skipped. Member loop: only pkg-a, whose file is unchanged (catalog: reference preserved).

    On disk: root package.json still catalog: { react: "^17.0.0" }; bun.lock has react@18.3.1. Next bun install: 18.3.1 does not satisfy ^17.0.0 → re-resolved to 17.x, undoing the update.

    Why not caught by tests

    The only catalog fan-out test (--recursive preserves a workspace member's catalog: reference) uses --recursive (root is always in target), does not use --latest, and its ^0.0.3 range cannot cross to 0.0.5 anyway. No test combines --filter <not-root> + --latest + a root catalog.

    Suggested fix

    Two consistent options:

    • Gate the cause: skip edit_catalogs_before_update's --latest rewrite (and/or drop the unconditional Tag::Catalog bypass in the resolver gate) when the root is not an update target — a filtered update that excludes root should leave root-scoped catalogs alone.
    • Un-gate the effect: when editing_catalogs && workspace_name_hash.is_none(), write the root package.json regardless of plan.cwd_in_target (mirroring how the from-workspace branch already writes root as a separate file).

    Either restores the invariant that the on-disk catalog range and the lockfile's catalog resolution stay in sync.

A filtered update that excludes the cwd/root skipped the root
package.json write, but the catalog pass had already moved root-scoped
catalog entries in the lockfile, so manifest and lockfile diverged.
Capture whether edit_catalogs_after_update changed anything and write
the root file when it did.
@robobun

robobun commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #36360, which consolidates this change with #32947 on top of current main, covers named updates as well, and is the PR the maintainers are iterating on. The two interaction fixes made here (member commits composing with the root catalog pass, a328905, and keeping the root catalog in sync under --filter --latest, f3ceb34) are noted on #36360 as suggested test coverage. Branch stays up if anything needs salvaging.

@robobun robobun closed this Aug 10, 2026
Comment on lines +1234 to +1238
ast,
member.indentation,
member.preserve_trailing_newline,
);

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.

🔴 The unchanged-guard here returns before the cache refresh below, so with --recursive --latest from a workspace subdir, if root's npm deps were already at latest (canonical print → new_source == original_contents) the root cache entry keeps the pre-install "latest" literals; the catalog pass then reads that stale entry, edit_catalogs_after_update fixes only the catalog keys, and pwrite_all writes root's dependencies to disk as the literal "latest", silently dropping the user's version pins. Refresh the cache to new_source before returning (or restrict this skip to member.name_hash.is_some(), since only the root member is read by the catalog pass).

Extended reasoning...

What the bug is

The a328905 fix reordered the member-commit loop before the catalog pass and added the cache refresh that follows this guard, with the explicit comment "Refresh the cache so later readers (the root catalog pass) compose on top of this write instead of a stale snapshot." But the if new_source == member.original_contents { return Ok(()); } early return skips that refresh entirely. When it fires for the root member under --latest, the root's cache entry retains the pre-install "latest" literals in its dependencies, and the catalog pass — which only edits catalog/catalogs keys — prints and pwrite_alls that stale content to disk.

The code path

Trigger: bun update --recursive --latest run from inside a workspace member (manager.workspace_name_hash.is_some(), so cwd_pkg_id != 0 and root lands in plan.members), where the root package.json has both npm dependencies and a catalog block, root's npm deps are already at their latest versions, root is in canonical printer format (true after any prior bun add/bun update wrote it), and at least one catalog entry admits a newer version.

  1. prepare_member_before_install(root): with UPDATE_TO_LATEST, edit_update_no_args(before_install=true) rewrites root's npm deps to the literal "latest", prints source_before_install (deps="latest", catalogs=original), and stores it into the root cache entry. member.original_contents = the original disk bytes.
  2. edit_catalogs_before_update (in the root_package_json_path block, gated on UPDATE_TO_LATEST): mutates the cached root AST's catalog entries to "latest", then print_package_json_into_cache_entry + reparse_root. Root cache is now deps="latest", catalogs="latest".
  3. Install resolves everything.
  4. commit_workspace_member_update(root): reparses member.source_before_install (deps="latest", catalogs=original), edit_update_no_args(before_install=false) restores each dep from updating_packages[..].original_version_literal via which_version_is_pinned. Since all root deps were already at latest, each restores to the same literal (e.g. ^1.0.0 → ^1.0.0). new_source = deps=original, catalogs=original — byte-identical to member.original_contents → early return here, cache NOT refreshed. Root cache still holds deps="latest", catalogs="latest".
  5. Catalog pass (editing_catalogs && workspace_name_hash.is_some()): get_with_path returns the cached entry as-is (WorkspacePackageJSONCache.rs:159-161, no re-read from disk). edit_catalogs_after_update iterates only for_each_catalog_object — never touches DEPENDENCY_GROUPS — so it fixes catalogs to resolved versions but leaves deps="latest". Since a catalog entry moved, root_catalogs_changed = true, so print_package_json_into_cache_entry prints the whole root (deps="latest" + catalogs=resolved) and pwrite_all writes it to disk.

Why the existing guard doesn't help

The unchanged-guard was intended to skip a disk write when nothing changed. But with --latest, the cache was already mutated in step 1 — the guard's job here is to restore it, not just to avoid a redundant write. Skipping the disk write is fine; skipping the cache restore is not.

Why the regression test misses it

--recursive from a workspace keeps both root dependency and catalog updates runs without --latest (so step 1's before-install pass doesn't rewrite dep values, and step 2's print_package_json_into_cache_entry is UPDATE_TO_LATEST-gated), and root's dep (baz: ~0.0.3) actually moves to ~0.0.5, so the unchanged-guard doesn't fire and the cache is refreshed.

Impact

Root's package.json on disk ends up with e.g. "dependencies": { "typescript": "latest" } where the user had "^5.4.5". On the next install / CI run, "latest" re-resolves to whatever is newest at that time — the exact non-reproducible behavior version pins exist to prevent. The failure is silent (no error, package.json still parses). This is easy to hit by running bun update --recursive --latest twice in a row from a workspace subdirectory: the first run brings root deps to latest, the second run trips the guard.

Step-by-step example

Root package.json (canonical printer format, e.g. after a prior bun add):

{
  "name": "root",
  "workspaces": ["packages/*"],
  "dependencies": { "foo": "^1.0.0" },
  "catalog": { "bar": "^1.0.0" }
}

Registry: foo latest is 1.0.0 (already at latest), bar latest is 2.0.0. From packages/pkg-a, run bun update --recursive --latest.

  • Step 1: root cache ← {"dependencies":{"foo":"latest"},"catalog":{"bar":"^1.0.0"}}; original_contents = disk bytes with foo:^1.0.0.
  • Step 2: root cache ← {"dependencies":{"foo":"latest"},"catalog":{"bar":"latest"}}.
  • Step 4: post-install restores foo from original_version_literal="^1.0.0" + resolved 1.0.0 → ^1.0.0. new_source = original disk bytes → early return.
  • Step 5: catalog pass reads stale cache, sets bar → ^2.0.0, prints {"dependencies":{"foo":"latest"},"catalog":{"bar":"^2.0.0"}}, writes to disk.

Result: root's "foo": "^1.0.0" pin is now "foo": "latest" on disk.

Fix

Either refresh the cache entry to new_source (== original_contents) before this early return, or restrict the unchanged-skip to non-root members (member.name_hash.is_some()), since only the root member's cache entry is read by the subsequent catalog pass. The former is the more direct expression of the invariant the cache-refresh comment already documents.

Comment on lines +756 to +761
// When `--filter` selects workspaces that don't include the cwd/root, the
// cwd package.json is not a target and must not be rewritten here. For the
// default and `--recursive` cases `cwd_in_target` is always true.
if manager.options.do_.contains(Do::WRITE_PACKAGE_JSON)
&& (plan.cwd_in_target || subcommand != Subcommand::Update)
{

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.

🔴 bun update --filter <ws> --latest run from the root, where <ws> doesn't match the root, leaves the on-disk root catalog at its original literal while the lockfile records the --latest resolution: edit_catalogs_before_update rewrites the catalog to "latest" in the cache regardless of cwd_in_target, install resolves against it (catalog deps bypass is_update_target_dependency at PackageManagerEnqueue.rs:1978), edit_catalogs_after_update's result lands in new_package_json_source — and this guard then discards it. Either gate the catalog before/after edits on the root being a write target, or write the root here when editing_catalogs && workspace_name_hash.is_none() even if !cwd_in_target (mirroring the from-workspace catalog block above, which isn't gated on cwd_in_target).

Extended reasoning...

What the bug is

Running bun update --filter pkg-a --latest from the workspace root, where the root has a catalog and pkg-a does not match the root package name, produces a lockfile that records the catalog dependency at its latest version while the on-disk root package.json keeps the original catalog literal. If that literal was an exact pin (e.g. "1.0.0") and latest is 2.0.0, the on-disk catalog no longer admits the lockfile's resolution — the next bun install sees the mismatch and re-resolves back to 1.0.0, silently undoing the update.

This is the from-root counterpart of the from-workspace catalog-clobber that a328905 fixed by reordering the member-commit loop before the catalog pass. That fix uses a different write path (the workspace_name_hash.is_some() block) and does not cover this case.

The code path

  1. prepare_workspace_update_plan — cwd is the root, so workspace_name_hash == None and cwd_pkg_id == 0. select_filtered_workspaces returns only pkg-a; the root's name doesn't match, so 0 ∉ selected → cwd_in_target = false. The root is also not in plan.members (only selected non-cwd workspaces go there).

  2. root_package_json_path block (line ~540) — runs unconditionally. edit_catalogs_before_update finds the root catalog and sets editing_catalogs = true. With UPDATE_TO_LATEST, it rewrites each catalog entry to "latest" in the AST, then print_package_json_into_cache_entry + reparse_root push that into the cache. The cache now holds catalog: { baz: "latest" }.

  3. install_with_manager — reads the root package.json from the cache, so the catalog map says baz: latest. In get_or_put_resolved_package_with_find_result (PackageManagerEnqueue.rs:1978), the Tag::Catalog check precedes is_update_target_dependency, so pkg-a's baz: "catalog:" dep sets should_update = true regardless of update_workspace_name_hashes. It resolves to e.g. 2.0.0 and the lockfile is saved with that.

  4. Post-install (line ~622) — editing_catalogs && workspace_name_hash.is_none() is true, so edit_catalogs_after_update runs on new_package_json (parsed from the pre-catalog-edit new_package_json_source) and computes the tightened literal (e.g. "2.0.0"). The result is printed back into new_package_json_source.

  5. Member-commit loop (line ~683) — root is not in plan.members, skipped.

  6. From-workspace catalog block (line ~689) — gated on workspace_name_hash.is_some(), false here, skipped.

  7. Cwd write (line 759) — plan.cwd_in_target == false and subcommand == Update → the whole block is skipped. new_package_json_source is dropped.

Result: disk has catalog: { baz: "1.0.0" }; lockfile has baz@2.0.0.

Why nothing else prevents it

Every writer of the root package.json is bypassed on this path: the root is not the cwd write target (cwd_in_target=false), not a member (not in selected), and the from-workspace catalog block requires workspace_name_hash.is_some(). The catalog before/after edits, however, are not gated on any of those — they key only on subcommand == Update && update_requests.is_empty() and workspace_name_hash.is_none() respectively. So the in-memory edit and the lockfile side effect both happen; only the disk write doesn't.

Pre-PR this couldn't happen: --filter was ignored by non-interactive update, so the cwd write was effectively unconditional and always persisted new_package_json_source. None of the new tests combine --filter (excluding root) with a root catalog, so this is uncovered.

Step-by-step proof (concrete)

// package.json (root)
{ "name": "root", "workspaces": ["packages/*"], "catalog": { "baz": "1.0.0" } }
// packages/pkg-a/package.json
{ "name": "pkg-a", "dependencies": { "baz": "catalog:" } }

Registry has baz@1.0.0 and baz@2.0.0 (latest).

$ bun install                          # lockfile: baz@1.0.0
$ bun update --filter pkg-a --latest   # from root
  • selected = [pkg-a], cwd_in_target = false.
  • edit_catalogs_before_update: cache root catalog → baz: "latest".
  • install: pkg-a's baz: catalog: re-resolves (Tag::Catalog short-circuits the target check) → baz@2.0.0 in lockfile.
  • edit_catalogs_after_update: new_package_json_source now has catalog: { baz: "2.0.0" }.
  • line 759: skipped. Disk still has catalog: { baz: "1.0.0" }.

Next bun install: catalog says baz@1.0.0 exact, lockfile says 2.0.0 — mismatch, re-resolves to 1.0.0, silently reverting the update.

Without --latest the divergence is milder (the on-disk range still admits the lockfile resolution; the literal just isn't tightened, unlike --recursive and plain bun update), but with --latest it's silent lockfile/manifest corruption.

Fix direction

Two consistent choices:

  • Don't touch the catalog when the root isn't a write target from root. Gate edit_catalogs_before_update (and the from-root edit_catalogs_after_update) on plan.cwd_in_target when workspace_name_hash.is_none(). This matches the "--filter pkg-a means only pkg-a" semantics — but note step 3: catalog deps still bypass is_update_target_dependency, so you'd also want to gate that short-circuit on the root being in update_workspace_name_hashes to keep the lockfile from moving.
  • Always persist the catalog edit. Write the root here whenever editing_catalogs && workspace_name_hash.is_none(), regardless of cwd_in_target — mirroring the workspace_name_hash.is_some() catalog block, which is already unconditional on cwd_in_target. This keeps the "catalogs are root-scoped and always update" semantics the enqueue code already assumes.

Either is fine; the current state (lockfile moves, manifest doesn't) is the one that isn't.

Jarred-Sumner pushed a commit that referenced this pull request Aug 22, 2026
### Problem
- GitHub closes only the first reference after a keyword, so "Fixes #1,
#2" leaves #2 open. "Supersedes #3" links nothing, and no reference
closes a pull request.
- The last 1000 merged PRs name 274 such references. PR #32292 is open
although merged #36135 says "Supersedes #32292".

### Fix
- `.github/workflows/close-linked-issues.yml` runs on
`pull_request_target` `closed` (a merge into the default branch of
`oven-sh/bun`) and on `workflow_dispatch` with a PR number and
`dry_run`. Everything is inline in one `actions/github-script` step,
with no checkout.
- Each open target is closed as `completed` with the comment "Closed as
completed by #N." or "Superseded by #N.". Closed or missing targets, the
PR itself and other repositories are skipped.
- The parser has no regex. A closing keyword (close, fix, resolve,
supersede, replace, any tense) must lead the reference, alone or in a
list. A negated, hedged or noun keyword, or one whose subject is another
reference, does not count ("may fix", "the rm fix #1", "#100 supersedes
#1").
- Verified: `test/internal/close-linked-issues.test.ts` (333 cases) runs
the YAML's script against fake `github`, `context` and `core`. Also the
1000-PR parse (Notes).

### Background
- GitHub's own keywords are close, fix and resolve (-s, -ed). Each links
one reference, and only a merge into the default branch closes it.
- `pull_request_target` runs in the base repository with a write token,
also for fork PRs. That is safe only when no PR-controlled code runs.
Here the description is the only PR input, parsed as text.

<details><summary>Notes</summary>

A close through the API does not create the "closed this in #N" timeline
link that GitHub makes for its own closes. The comment carries the PR
number instead.

How the parser was calibrated. I pulled the descriptions of the last
1000 merged PRs and listed every line with a keyword next to a
reference. The keyword families, list shapes and reference forms in the
script are the ones that appear there. A reference is `#1`,
`owner/repo#1`, an issue or pull URL (bare or in `<>`), or a markdown
link. Four lines would have been wrong with a plain
keyword-then-reference rule, and each led to a rule:

- "the open `rm` fix #37521" (#38379): "fix" as a noun. Base forms (fix,
close, resolve, supersede, replace) count only at the start of a
sentence or line, or after will, should, does, and, and a few similar
words. "to" is not one of them ("unable to fix #1", "how to fix #1").
- "May also fix #12318 / #10046, untested" (#38242): hedged. may, might,
could, would, partially and the negations disqualify the keyword,
looking past adverbs such as "also".
- "Supersedes the closed #26040" (#36289) and "a comment on closed
#35351" (#35365): "closed" as an adjective. A determiner or preposition
before the keyword disqualifies it.
- "supersedes #33130's optimisation" (#35843): a number that continues
into a word is not a reference.

Review added: a reference before the keyword is the subject ("#100
supersedes #1"), also through "which" or "that" ("reverts #100, which
fixed #1") and across a removed span ("#100 ~~also~~ fixes #1"). A hedge
two words before the keyword disqualifies it ("hopefully this fixes #1",
"could this fix #1?"). A clause that starts with if, when, once, until
or unless is not a statement. The tokenizer keeps a line break as a
token so that "Fixes #1" on one line and "Fixes #2" on the next stay two
statements. Code spans, fences, indented code, blockquotes, HTML
comments and strikethrough are skipped. The block stripping follows
CommonMark for fences (also inside a blockquote), indented code,
blockquotes with lazy continuation, setext underlines and HTML comments,
and GFM for `~~` flanking.

Result over the 1000 descriptions: 274 distinct references in 135 PRs. I
checked the current state of all of them through GraphQL. All but one
are closed (202 issues completed, 5 duplicates, 66 pull requests). The
one open target is PR #32292, superseded by merged #36135. No open
target is a false positive. Every review change kept this result.

Patterns that are deliberately not handled: a bulleted list under
"Closes:" on its own line (not seen in the sample), references separated
by whitespace only ("#1 #2"), "fix for #1", and GH-1 style references. A
`?` after the list is not treated as a question. The block parser tracks
no list containers, so a second paragraph of a list item indented by
four spaces is read as an indented code block and skipped. A removed
span or inline comment reads as one word, so "Fixes <!-- n --> #1" finds
nothing.

The test suite covers: the phrases above, stopping at the right place in
real sentences, CRLF descriptions, URLs with fragments or a `/files`
suffix, case-insensitive `Owner/Repo#1`, the fake API where a lookup, an
update or a comment fails, the `dry_run` input, an invalid `pr_number`
input, an unmerged PR, a PR merged into a non-default branch, the merge
event body against a later edit, and a description with no closing
statement.

The first revision of this PR checked out the repository and ran
`scripts/close-linked-issues.ts`. Jarred asked for no checkout and no
script file, so the script moved inline into the workflow and the test
now reads it out of the YAML.
</details>

<!-- robobun:evidence:begin -->

---

**[stamp-90s]** gate passed · iteration 9 · 2 files touched

<details><summary>passes on PR (with fix)</summary>

```console
Test-only change.

Debug/ASAN (expected pass):
$ bun bd test 'test/internal/close-linked-issues.test.ts'
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/internal/close-linked-issues.test.ts
bun test v1.4.1 (4448a2e)

test/internal/close-linked-issues.test.ts:
(pass) finds "Fixes #39852" [176.21ms]
(pass) finds "Closes #31772. Fixes #31771." [22.28ms]
(pass) finds "- Fixes #39930" [12.28ms]
(pass) finds "Fixes: #30429" [10.46ms]
(pass) finds "FIXES #1" [7.86ms]
(pass) finds "(Fixes #1)" [8.97ms]
(pass) finds "**Fixes #1**" [10.20ms]
(pass) finds "__Fixes #1__" [9.83ms]
(pass) finds "_Fixes #1_" [11.25ms]
(pass) finds "Fixes **#1**" [9.72ms]
(pass) finds "**Fixes** #1" [7.13ms]
(pass) finds "**Fixes:** #1" [8.11ms]
(pass) finds "Fixes #1 and **#2**" [11.47ms]
(pass) finds "Fixes **#1**, **#2**" [9.13ms]
(pass) finds "## Why (fixes #13771, closes #30543)" [16.08ms]
(pass) finds "Closes #11418" [19.46ms]
(pass) finds "Resolves #1. Resolved #2. Resolve #3." [12.09ms]
(pass) finds "Fixes #34055, #30327, #24394, #20816, #32403, #11898, #10056." [17.11ms]
(pass) finds "Fixes #18192 and #31675 as a consequence" [10.45ms]
(pass) finds "Fixes #1, #2, and #3" [10.96ms]
(pass) finds "Fixes #1 & #2" [7.63ms]
(pass) finds "Closes #33280,  Closes #32864 and Closes #29696 (the timer in #32949 is orthogonal)" [20.29ms]
(pass) finds "Closes #33182 and #32947 on top of current main (which already has #36304 for catalogs)." [16.12ms]
(pass) finds "Fixes #1,\n#2" [7.76ms]
(pass) finds "Fixes #1, #2,\nand #3" [9.27ms]
(pass) finds "Fixes #1\nand #2" [8.57ms]
(pass) finds "Fixes #1\n& #2" [6.80ms]
(pass) finds "Fixes #1 and\n#2" [7.31ms]
(pass) finds "Supersedes #39908 (same change, moved from a fork branch)" [13.21ms]
(pass) finds "Supersedes #38778 and #38391. Carries the entry point arm of #35053." [14.43ms]
(pass) finds "Supersedes #39193 and keeps its three tests." [11.48ms]
(pass) finds "This supersedes #33306 and #32803. Their tests are kept here." [13.73ms]
(pass) finds "- This replaces #33793. Its 
... (truncated)
Exit: 0
```

</details>

<details><summary>diff hotspot</summary>

```
.github/workflows/close-linked-issues.yml | 950 ++++++++++++++++++++++++++++++
 test/internal/close-linked-issues.test.ts | 598 +++++++++++++++++++
 2 files changed, 1548 insertions(+)
```

</details>

**gate history** · 29 passed · 0 rejected · iteration 9

<details><summary>evidence per changed file</summary>

```
file                                       reads  edits  tests
.github/workflows/close-linked-issues.yml      6     12      0
test/internal/close-linked-issues.test.ts      3     11      0
```

</details>

<!-- robobun:evidence:end -->
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.

bun update --recursive doesn't update peerDependencies in the monorepo

2 participants