Skip to content

fix(global): switch global installs over atomically - #13633

Merged
zkochan merged 14 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/global-install-publication
Aug 11, 2026
Merged

zkochan merged 14 commits into
pnpm:mainfrom
YESHYUNGSEOK:fix/global-install-publication

Conversation

@YESHYUNGSEOK

@YESHYUNGSEOK YESHYUNGSEOK commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Activating a global install used to rewrite every command shim in the shared global bin directory. The shims embedded the path of the directory a particular install produced, so switching versions meant removing all of the commands, relinking them, and only then moving the hash link. Every command was missing from PATH for the duration — on success as much as on failure — and a linker or hash-link failure could leave the previous global package unusable.

  • Generate the shims from the group's hash link instead of the install directory it points at. The link name is a stable cache key over the group's aliases, so the shim text no longer changes between versions.
  • Move the hash link before linking rather than after, and move it with a rename. Activating a new install is then a single operation that switches every already-linked command over at once; both linkers' idempotency checks find the shims already correct and leave the files untouched.
  • Restore the previous bins and hash link when a step that does write fails — a new group, a changed set of commands, or a shim migrated from the old form.
  • Defer stale package and bin cleanup until activation succeeds, preserving bins that still belong to an installed package, attempting every removal, and reporting diagnostics without hiding the original failure.

Verified end to end: across pnpm add -g of a new version, the shim keeps the same inode and mtime while the command goes from the old version to the new one.

Squash Commit Body

Switch global installs over atomically in both implementations. Generate the command shims from the group's stable hash link rather than the install directory it points at, and move that link with a rename before linking rather than after, so activating a new install is a single operation and the shims are left byte-identical.

Restore the previous bins and hash link when a step that does write fails, and defer destructive cleanup until activation succeeds. Cleanup preserves bins that still belong to an installed package, attempts every artifact removal, and reports diagnostics without hiding the original failure.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust pnpm/ port.
  • Added a changeset (pnpm changeset) for the affected published packages and CLIs.
  • Added or updated tests.
  • Updated the documentation if needed.

Written by an agent (Codex, GPT-5), reshaped by an agent (Claude Code, claude-fable-5).


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes

    • Global package replacements now preserve the previous installation if publishing the replacement fails.
    • Global bin updates use rollback and recovery handling to prevent incomplete installations.
    • Windows bin cleanup now attempts all removals and reports multiple failures together.
    • Existing bins owned by other global packages are preserved during updates.
    • Failed replacements no longer trigger cleanup of the existing installation.
  • Tests

    • Expanded coverage for publication failures, rollback, cleanup errors, symlink handling, protected bins, and Windows behavior.

@YESHYUNGSEOK
YESHYUNGSEOK requested a review from zkochan as a code owner August 4, 2026 07:14
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; the previously reported cleanup, enumeration-error, failed-bin-removal, and committed-backup-cleanup paths are addressed at the current head.

Reviews (11): Last reviewed commit: "test(global): cover replacing a group wi..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 4, 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

Walkthrough

Global add and update now publish replacement installations transactionally. Existing bins and hash links are restored when publication fails. Replaced installations are cleaned up only after successful publication. Windows shim removal now reports all deletion failures.

Changes

Global publication flow

Layer / File(s) Summary
Rust publication and rollback
pnpm/crates/cli/src/cli_args/global/publication.rs, pnpm/crates/cli/src/cli_args/global/publication/tests.rs
Adds transactional publication, cross-platform bin backups, rollback, hash-link restoration, cleanup diagnostics, and failure-injection tests.
Rust global add and update integration
pnpm/crates/cli/src/cli_args/global.rs
Publishes new installations before removing replaced groups and preserves protected and newly published bins.
TypeScript publication and cleanup
pnpm11/global/commands/src/globalPublication.ts, pnpm11/global/commands/test/globalPublication.test.ts
Adds transactional bin and hash-link publication, rollback, cleanup, platform-specific slot handling, and aggregate errors.
TypeScript command integration and validation
pnpm11/global/commands/src/globalAdd.ts, pnpm11/global/commands/src/globalUpdate.ts, pnpm11/global/commands/test/globalAdd.test.ts, pnpm11/global/commands/test/globalUpdate.test.ts, .changeset/safe-global-bin-publication.md
Routes global add and update through publication, validates ordering and failure behavior, and documents the patch release.
Windows bin removal settlement
pnpm11/bins/remover/src/removeBins.ts, pnpm11/global/commands/test/removeBinWindows.test.ts
Waits for all Windows shim removals before reporting one failure or an AggregateError.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant GlobalCommand
  participant GlobalPublication
  participant BinDirectory
  participant HashLink
  participant Cleanup
  GlobalCommand->>GlobalPublication: publish replacement installation
  GlobalPublication->>BinDirectory: back up and replace bin slots
  GlobalPublication->>HashLink: publish new hash link
  GlobalPublication-->>GlobalCommand: return published bins
  GlobalCommand->>Cleanup: remove replaced groups
  Cleanup->>BinDirectory: remove obsolete unprotected bins
  Cleanup->>HashLink: remove stale hash links
Loading

Possibly related PRs

  • pnpm/pnpm#13138: Both changes address global installation integrity and broken global bin links.
  • pnpm/pnpm#13246: Both changes modify the global-add flow in global.rs.
  • pnpm/pnpm#13731: Both changes modify global bin publication in global.rs.

Suggested labels: product: pacquet, product: pnpm@11

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov-commenter

codecov-commenter commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.26168% with 127 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.19%. Comparing base (e33e400) to head (f42423f).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/cli/src/cli_args/global/activation.rs 82.29% 71 Missing ⚠️
pnpm/crates/cli/src/cli_args/global.rs 58.20% 56 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13633      +/-   ##
==========================================
- Coverage   88.21%   88.19%   -0.02%     
==========================================
  Files         624      625       +1     
  Lines      101592   102311     +719     
==========================================
+ Hits        89623    90237     +614     
- Misses      11969    12074     +105     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

🧹 Nitpick comments (5)
pnpm/crates/cli/src/cli_args/global/publication.rs (1)

413-418: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify io_error_report and drop the unreachable panic path.

The function round-trips through Result only to reach IntoDiagnostic, then adds an unreachable! arm that cannot execute. unwrap_err expresses the same intent without the extra arm.

♻️ Proposed simplification
 fn io_error_report(error: io::Error, context: String) -> miette::Report {
-    match Err::<(), _>(error).into_diagnostic().wrap_err(context) {
-        Err(report) => report,
-        Ok(()) => unreachable!("an explicitly constructed error cannot become Ok"),
-    }
+    Err::<(), _>(error).into_diagnostic().wrap_err(context).unwrap_err()
 }
🤖 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 `@pnpm/crates/cli/src/cli_args/global/publication.rs` around lines 413 - 418,
Update io_error_report to extract the diagnostic report with unwrap_err() after
applying into_diagnostic().wrap_err(context), removing the match expression and
unreachable! panic arm while preserving the existing error context.
pnpm/crates/cli/src/cli_args/global.rs (1)

480-526: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider making remove_group delegate to this function.

remove_group at lines 564-580 now duplicates the same three cleanup steps: bin removal with a protected-name filter, hash-link removal, and is_subdir-guarded install-dir removal. Two differences can cause divergent behavior:

  • remove_group discards every error with let _ =, so a failed removal is invisible.
  • remove_group uses fs::remove_file on the hash link, while this function uses remove_symlink_dir. On Windows, remove_file fails on a directory symlink.

Confirm the remaining callers of remove_group and whether they can use cleanup_replaced_global_installs with an empty published_bins set.

#!/bin/bash
# Find callers of remove_group and compare with the new cleanup function.
rg -nP -C6 '\bremove_group\s*\(' --type=rust
# Inspect remove_symlink_dir semantics for hash links.
ast-grep run --pattern 'pub fn remove_symlink_dir($$$) { $$$ }' --lang rust pnpm/crates
🤖 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 `@pnpm/crates/cli/src/cli_args/global.rs` around lines 480 - 526, Update
remove_group to reuse cleanup_replaced_global_installs instead of duplicating
bin, hash-link, and install-directory cleanup. Inspect all remove_group callers
and pass an empty published_bins set where their cleanup semantics allow, while
preserving protected-bin handling and the active hash. Propagate the helper’s
diagnostics and use remove_symlink_dir so hash-link removal works on Windows;
retain or adjust callers only where their required behavior differs.
pnpm11/global/commands/test/globalPublication.test.ts (2)

125-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the unsupported bin slot type.

backupBinSlot in pnpm11/global/commands/src/globalPublication.ts throws GLOBAL_BIN_UNSUPPORTED_TYPE when a bin slot is neither a regular file nor a symlink. No test in this file reaches that branch. The review guide requires tests that prove unsupported link types, so this branch and its cleanup behavior are unverified.

Seed a directory at a bin slot name that the manifest declares, then assert publishGlobalInstall rejects with ERR_PNPM_GLOBAL_BIN_UNSUPPORTED_TYPE, that the fresh install directory is removed, and that no backup directory remains.

As per path instructions, REVIEW_GUIDE.md states: "Tests must prove failure rollback, cleanup ordering, error aggregation, unsupported link types, and Windows behavior with meaningful cross-platform coverage."

🤖 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 `@pnpm11/global/commands/test/globalPublication.test.ts` at line 125, Add a
test in the global publication test suite that creates a directory at a
manifest-declared bin slot, then verifies publishGlobalInstall rejects with
ERR_PNPM_GLOBAL_BIN_UNSUPPORTED_TYPE, removes the fresh install directory, and
leaves no backup directory. Exercise the backupBinSlot unsupported-type branch
while preserving the existing rollback assertions.

Source: Path instructions


500-508: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the cleanup fixture setup.

The three cleanup tests repeat the same setup: fs.mkdtemp, assign testRoot, derive globalDir and globalBinDir, then mkdir the directories. A small createCleanupFixture() helper alongside createFixture would remove the repetition and keep each test focused on the behavior it asserts.

Also applies to: 531-542, 563-572

🤖 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 `@pnpm11/global/commands/test/globalPublication.test.ts` around lines 500 -
508, Extract the repeated temporary-directory setup from the three cleanup tests
into a shared createCleanupFixture helper alongside createFixture. Have it
create and assign testRoot, derive globalDir and globalBinDir, create the
required directories including old-install, and return the fixture values needed
by each test; replace the duplicated setup in all three cleanup tests while
preserving their existing behavior.
pnpm11/global/commands/src/globalPublication.ts (1)

77-97: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider aggregating cleanup failures so cleanup completes.

Publication already succeeded when cleanupReplacedGlobalInstalls runs. A single removeBin rejection at Line 89 aborts the remaining work: the other stale bins, the stale hash link, and the replaced install directory all stay on disk, and later groups are never cleaned. Promise.allSettled over the bin removals, plus an aggregated error per group, would leave less residue after a partial failure.

This is optional for this PR. The prior code had the same sequential abort behavior.

🤖 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 `@pnpm11/global/commands/src/globalPublication.ts` around lines 77 - 97, Update
cleanupReplacedGlobalInstall to aggregate failures from all bin removals rather
than aborting on the first removeBin rejection, while preserving sequential
removal if required. Ensure stale hash-link and install-directory cleanup still
runs, and throw an aggregated error for the group after all cleanup attempts
complete so later groups can continue.
🤖 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 `@pnpm/crates/cli/src/cli_args/global.rs`:
- Around line 247-263: Update the error-context strings on the
`publish_global_install` and `cleanup_replaced_global_installs` calls in the
global install replacement path to match the established wording used by the
corresponding add path. Replace the outdated publish context with the shared
term describing bin/hash-link publishing, and use the add path’s cleanup
terminology for the cleanup call.

In `@pnpm11/global/commands/src/globalPublication.ts`:
- Around line 197-200: Update getSymlinkType to tolerate a missing symlink
target on Windows: handle the ENOENT rejection from fs.promises.stat(link) by
returning 'file', while preserving directory detection and non-Windows undefined
behavior. Add coverage to the Windows publication test setup that creates a
dangling symlink in globalBinDir and verifies publication succeeds.

---

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/global.rs`:
- Around line 480-526: Update remove_group to reuse
cleanup_replaced_global_installs instead of duplicating bin, hash-link, and
install-directory cleanup. Inspect all remove_group callers and pass an empty
published_bins set where their cleanup semantics allow, while preserving
protected-bin handling and the active hash. Propagate the helper’s diagnostics
and use remove_symlink_dir so hash-link removal works on Windows; retain or
adjust callers only where their required behavior differs.

In `@pnpm/crates/cli/src/cli_args/global/publication.rs`:
- Around line 413-418: Update io_error_report to extract the diagnostic report
with unwrap_err() after applying into_diagnostic().wrap_err(context), removing
the match expression and unreachable! panic arm while preserving the existing
error context.

In `@pnpm11/global/commands/src/globalPublication.ts`:
- Around line 77-97: Update cleanupReplacedGlobalInstall to aggregate failures
from all bin removals rather than aborting on the first removeBin rejection,
while preserving sequential removal if required. Ensure stale hash-link and
install-directory cleanup still runs, and throw an aggregated error for the
group after all cleanup attempts complete so later groups can continue.

In `@pnpm11/global/commands/test/globalPublication.test.ts`:
- Line 125: Add a test in the global publication test suite that creates a
directory at a manifest-declared bin slot, then verifies publishGlobalInstall
rejects with ERR_PNPM_GLOBAL_BIN_UNSUPPORTED_TYPE, removes the fresh install
directory, and leaves no backup directory. Exercise the backupBinSlot
unsupported-type branch while preserving the existing rollback assertions.
- Around line 500-508: Extract the repeated temporary-directory setup from the
three cleanup tests into a shared createCleanupFixture helper alongside
createFixture. Have it create and assign testRoot, derive globalDir and
globalBinDir, create the required directories including old-install, and return
the fixture values needed by each test; replace the duplicated setup in all
three cleanup tests while preserving their existing behavior.
🪄 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: CHILL

Plan: Pro Plus

Run ID: 48fe51f1-5694-4d8f-b050-2162df295b4b

📥 Commits

Reviewing files that changed from the base of the PR and between 46d7d3e and bec87d5.

📒 Files selected for processing (12)
  • .changeset/safe-global-bin-publication.md
  • pnpm/crates/cli/src/cli_args/global.rs
  • pnpm/crates/cli/src/cli_args/global/publication.rs
  • pnpm/crates/cli/src/cli_args/global/publication/tests.rs
  • pnpm11/bins/remover/src/removeBins.ts
  • pnpm11/global/commands/src/globalAdd.ts
  • pnpm11/global/commands/src/globalPublication.ts
  • pnpm11/global/commands/src/globalUpdate.ts
  • pnpm11/global/commands/test/globalAdd.test.ts
  • pnpm11/global/commands/test/globalPublication.test.ts
  • pnpm11/global/commands/test/globalUpdate.test.ts
  • pnpm11/global/commands/test/removeBinWindows.test.ts

Comment thread pnpm/crates/cli/src/cli_args/global.rs Resolved
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: f42423f2540e

Regular scenarios report direct and pnpr installs. The peer-heavy resolver scenario compares current Rust, main Rust, and TypeScript pnpm. Bencher consumes pacquet@HEAD and pnpr@HEAD.

The tables below show mean ± σ; Bencher thresholds on the minimum latency, which is far less perturbed by shared-runner contention (noise only adds time).

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.488 ± 0.121 2.375 2.777 1.60 ± 0.15
pacquet@main 2.582 ± 0.168 2.373 2.813 1.66 ± 0.17
pnpr@HEAD 1.608 ± 0.145 1.399 1.790 1.04 ± 0.12
pnpr@main 1.552 ± 0.124 1.396 1.698 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.4881775909200003,
      "stddev": 0.12114503467970668,
      "median": 2.44901310432,
      "user": 1.78737332,
      "system": 1.4432537799999998,
      "min": 2.3747655238200003,
      "max": 2.77654330482,
      "times": [
        2.45126863582,
        2.44675757282,
        2.50514246482,
        2.77654330482,
        2.40253090682,
        2.61628758882,
        2.4216390918200004,
        2.42728057282,
        2.3747655238200003,
        2.45956024682
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.5816975149200005,
      "stddev": 0.1684211294455156,
      "median": 2.57534119482,
      "user": 1.7350085199999998,
      "system": 1.37406358,
      "min": 2.37273930382,
      "max": 2.81257547582,
      "times": [
        2.46072408782,
        2.76931672682,
        2.6711537738200004,
        2.64641124282,
        2.5042711468200003,
        2.75668380382,
        2.81257547582,
        2.38170386082,
        2.44139572682,
        2.37273930382
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.6079985242200003,
      "stddev": 0.14493009669503823,
      "median": 1.62355701082,
      "user": 1.1653313199999995,
      "system": 1.1812077799999998,
      "min": 1.39941220182,
      "max": 1.7903083598199998,
      "times": [
        1.73786629082,
        1.67701106482,
        1.7903083598199998,
        1.6027009968200001,
        1.40158972182,
        1.4674274698199998,
        1.64441302482,
        1.77097526282,
        1.39941220182,
        1.58828084882
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.55228666972,
      "stddev": 0.12372826287672922,
      "median": 1.59322159782,
      "user": 1.1610708199999995,
      "system": 1.26431098,
      "min": 1.39573143182,
      "max": 1.69842017082,
      "times": [
        1.42974909482,
        1.64242778682,
        1.43682966482,
        1.68586065782,
        1.5774905318199999,
        1.65043040182,
        1.60895266382,
        1.39697429282,
        1.39573143182,
        1.69842017082
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 268.7 ± 5.4 261.3 280.6 1.00
pacquet@main 275.7 ± 17.7 256.6 307.2 1.03 ± 0.07
pnpr@HEAD 277.2 ± 7.8 261.9 285.2 1.03 ± 0.04
pnpr@main 281.8 ± 6.5 275.0 297.8 1.05 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.2686767979200001,
      "stddev": 0.005448302096683166,
      "median": 0.26913015862000006,
      "user": 0.24175909999999998,
      "system": 0.5496346599999999,
      "min": 0.26126673462000005,
      "max": 0.28058003462000003,
      "times": [
        0.26644136662000006,
        0.26883143562000006,
        0.27178550662000006,
        0.28058003462000003,
        0.26942888162000006,
        0.26986825762000005,
        0.27073693362000006,
        0.26537810462000005,
        0.26245072362000005,
        0.26126673462000005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.27572824772000004,
      "stddev": 0.017700252682407915,
      "median": 0.27154717912000004,
      "user": 0.2450253,
      "system": 0.55505416,
      "min": 0.25656022462000005,
      "max": 0.30716534562000003,
      "times": [
        0.26297037262000006,
        0.27898130462000004,
        0.28733331862000006,
        0.30716534562000003,
        0.29919989962000004,
        0.26411305362000004,
        0.25871409862000005,
        0.26280908862,
        0.27943577062,
        0.25656022462000005
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.27716678362,
      "stddev": 0.007772460990721254,
      "median": 0.27873514162,
      "user": 0.23947729999999998,
      "system": 0.53181036,
      "min": 0.26185969062000003,
      "max": 0.28521717462000007,
      "times": [
        0.27625494262000005,
        0.28037044962,
        0.28490642862000004,
        0.28178667662000006,
        0.28521717462000007,
        0.28374250862000006,
        0.26185969062000003,
        0.26773045262000006,
        0.27709983362000007,
        0.27269967862000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.28183716852,
      "stddev": 0.006494325281211835,
      "median": 0.28088949762000004,
      "user": 0.2395229,
      "system": 0.5477593599999999,
      "min": 0.27504173862000003,
      "max": 0.29780344062,
      "times": [
        0.28054017962000005,
        0.27870776062,
        0.27504173862000003,
        0.27763700362000004,
        0.29780344062,
        0.28283336662,
        0.28123881562,
        0.28134761962000004,
        0.27672839262000004,
        0.28649336762000005
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.638 ± 0.067 2.603 2.828 1.65 ± 0.13
pacquet@main 2.627 ± 0.025 2.583 2.665 1.64 ± 0.12
pnpr@HEAD 1.603 ± 0.117 1.464 1.856 1.00
pnpr@main 1.681 ± 0.141 1.450 1.888 1.05 ± 0.12
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.6379855700799997,
      "stddev": 0.06719483834090817,
      "median": 2.61870058788,
      "user": 1.60798636,
      "system": 1.4253223199999998,
      "min": 2.6028303188799997,
      "max": 2.8275159238799996,
      "times": [
        2.62366011488,
        2.8275159238799996,
        2.60627924988,
        2.62490263088,
        2.63173897888,
        2.6028303188799997,
        2.61442851788,
        2.6110987898799998,
        2.61443897688,
        2.62296219888
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.62679201278,
      "stddev": 0.02450039515527258,
      "median": 2.63585967838,
      "user": 1.65718016,
      "system": 1.3981140200000002,
      "min": 2.58307210188,
      "max": 2.66459930088,
      "times": [
        2.58307210188,
        2.6359225408799998,
        2.63579681588,
        2.6226001698799997,
        2.59465218288,
        2.63852773588,
        2.63644814088,
        2.66459930088,
        2.64564271088,
        2.61065842788
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.60252624578,
      "stddev": 0.11704865498233026,
      "median": 1.5757510833800001,
      "user": 1.12201316,
      "system": 1.17722682,
      "min": 1.46431617288,
      "max": 1.8555783658800002,
      "times": [
        1.5102595468800002,
        1.56313839588,
        1.46431617288,
        1.6017380058800001,
        1.62959864088,
        1.53816826188,
        1.5883637708800002,
        1.74344992488,
        1.5306513718800001,
        1.8555783658800002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.6814983435800002,
      "stddev": 0.14077556188373264,
      "median": 1.6899775483800001,
      "user": 1.11479536,
      "system": 1.31297972,
      "min": 1.4495586528800002,
      "max": 1.8878003808800001,
      "times": [
        1.6714292128800001,
        1.4495586528800002,
        1.85978532488,
        1.74706701388,
        1.74668831088,
        1.7085258838800002,
        1.50152797988,
        1.8878003808800001,
        1.6457874948800002,
        1.5968131808800001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 423.5 ± 24.6 396.6 470.1 1.37 ± 0.09
pacquet@main 455.3 ± 66.5 410.4 638.7 1.47 ± 0.22
pnpr@HEAD 309.3 ± 6.8 301.3 320.6 1.00
pnpr@main 328.0 ± 12.0 310.5 344.5 1.06 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.42346397456000007,
      "stddev": 0.024630184802442782,
      "median": 0.41718822236,
      "user": 0.5594263799999999,
      "system": 0.70462752,
      "min": 0.39664162586,
      "max": 0.47013496186000003,
      "times": [
        0.41170199886000003,
        0.39841548486,
        0.44247489286,
        0.39664162586,
        0.43379394886,
        0.40796247786,
        0.42267444586,
        0.44865493686,
        0.40218497186,
        0.47013496186000003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.4552728180600001,
      "stddev": 0.06653793021372034,
      "median": 0.43506105936,
      "user": 0.6375326799999999,
      "system": 0.7297282199999999,
      "min": 0.41042136586,
      "max": 0.63865158186,
      "times": [
        0.63865158186,
        0.41042136586,
        0.43562950886,
        0.42537978886,
        0.44230541486,
        0.42271565486,
        0.47452126886,
        0.43722859986,
        0.43449260986,
        0.43138238686
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.30930997705999996,
      "stddev": 0.0068382358391130185,
      "median": 0.30986183485999996,
      "user": 0.21149788000000003,
      "system": 0.52843342,
      "min": 0.30131304986,
      "max": 0.32062304386,
      "times": [
        0.30131304986,
        0.31016461986,
        0.31040112386,
        0.31387698686,
        0.30955904986,
        0.32062304386,
        0.30282897386,
        0.30152591986,
        0.30452179986,
        0.31828520286
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.32795755696,
      "stddev": 0.012025574371997541,
      "median": 0.32572373336,
      "user": 0.22202848,
      "system": 0.5615186200000001,
      "min": 0.31054126886,
      "max": 0.34454258386000003,
      "times": [
        0.31829960986,
        0.32584798686,
        0.31359176986,
        0.31054126886,
        0.32559947986,
        0.34193840086,
        0.34454258386000003,
        0.33808499986,
        0.33770102586,
        0.32342844386
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.761 ± 0.036 1.726 1.833 5.57 ± 0.35
pacquet@main 1.766 ± 0.040 1.722 1.844 5.58 ± 0.35
pnpr@HEAD 0.316 ± 0.019 0.292 0.352 1.00
pnpr@main 0.324 ± 0.006 0.316 0.337 1.03 ± 0.06
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.76135616726,
      "stddev": 0.03580127543846231,
      "median": 1.75147622216,
      "user": 0.86842902,
      "system": 0.78724184,
      "min": 1.72553802216,
      "max": 1.83287133916,
      "times": [
        1.83287133916,
        1.79797018016,
        1.76166861916,
        1.73679630716,
        1.79428171516,
        1.72885023716,
        1.74739167216,
        1.72553802216,
        1.75556077216,
        1.73263280816
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.76612545906,
      "stddev": 0.04023340064538459,
      "median": 1.75422209816,
      "user": 0.8499429199999999,
      "system": 0.8354431400000001,
      "min": 1.72201279516,
      "max": 1.84378013116,
      "times": [
        1.75440883216,
        1.73167839116,
        1.77405434416,
        1.74311249716,
        1.84378013116,
        1.8233323971600002,
        1.78093207616,
        1.75403536416,
        1.7339077621599999,
        1.72201279516
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.31625763486,
      "stddev": 0.01852191980910362,
      "median": 0.31339833015999996,
      "user": 0.22451012,
      "system": 0.5252052400000001,
      "min": 0.29227768515999997,
      "max": 0.35199867516,
      "times": [
        0.35199867516,
        0.33197276416,
        0.30924446816,
        0.31251655516,
        0.31428010516,
        0.29404076215999997,
        0.29227768515999997,
        0.30441408616,
        0.31882249316,
        0.33300875416
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.32429858176000004,
      "stddev": 0.005949549128433733,
      "median": 0.32457394916000004,
      "user": 0.22876462000000003,
      "system": 0.5519426399999999,
      "min": 0.31602366616,
      "max": 0.33657076716,
      "times": [
        0.32760692716,
        0.32506156716,
        0.32005525415999997,
        0.33657076716,
        0.31602366616,
        0.32046937416,
        0.32408633116,
        0.32885077816,
        0.32567525216,
        0.31858590016
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 214.2 ± 15.5 195.4 247.0 2.41 ± 0.19
pacquet@main 226.6 ± 18.6 203.8 253.1 2.55 ± 0.22
pnpr@HEAD 88.9 ± 2.6 85.1 95.0 1.00
pnpr@main 90.2 ± 4.1 85.8 101.6 1.01 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.21415335276461536,
      "stddev": 0.015520477377543944,
      "median": 0.20831829338000002,
      "user": 0.18246351230769225,
      "system": 0.06624001384615384,
      "min": 0.19538333438000002,
      "max": 0.24698411138,
      "times": [
        0.21778669938,
        0.19538333438000002,
        0.19598379438000002,
        0.22829314738,
        0.20440170038000002,
        0.22581223738,
        0.20831829338000002,
        0.23229027138000002,
        0.24698411138,
        0.20028489238000002,
        0.20608805738000002,
        0.21608961438000002,
        0.20627743238000001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.22663927513,
      "stddev": 0.01859534023954589,
      "median": 0.22322711538,
      "user": 0.17966140333333333,
      "system": 0.06322619333333333,
      "min": 0.20377502238,
      "max": 0.25307893538000004,
      "times": [
        0.23583104838000002,
        0.20505901938,
        0.22896584338,
        0.21020327338,
        0.20905874738000002,
        0.24604993338,
        0.21748838738,
        0.21613020038,
        0.25307893538000004,
        0.25179393538,
        0.20377502238,
        0.24223695538
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.08892500573483869,
      "stddev": 0.0026056914025045824,
      "median": 0.08822706438,
      "user": 0.021085271612903227,
      "system": 0.010870606451612906,
      "min": 0.08514119538,
      "max": 0.09495697338,
      "times": [
        0.08991640438000001,
        0.09235980438000001,
        0.09495697338,
        0.09110835838,
        0.08541210538,
        0.08815195338000001,
        0.08708451338,
        0.08728609338,
        0.08649245038,
        0.08775257238,
        0.08822706438,
        0.08590038538,
        0.08808627038,
        0.08619654138,
        0.08952661038,
        0.09153101538,
        0.09092539438,
        0.09191070938,
        0.08697621038,
        0.08533292638000001,
        0.08946931438,
        0.08539689638,
        0.08965237738000001,
        0.09375702538,
        0.09008529238,
        0.09128932038,
        0.08514119538,
        0.08801615738,
        0.08722868438,
        0.09018510138000001,
        0.09131945638
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.09016035221870967,
      "stddev": 0.004073518984638894,
      "median": 0.08833289438,
      "user": 0.021772110322580647,
      "system": 0.011225154838709674,
      "min": 0.08580902238,
      "max": 0.10158512138,
      "times": [
        0.09117254938000001,
        0.08695638238,
        0.08615273038,
        0.08770293838,
        0.09058028438,
        0.09615872538,
        0.09418432938,
        0.09402663238,
        0.10158512138,
        0.10037455138000001,
        0.08864639438000001,
        0.08612068938,
        0.08745302738,
        0.08745493138,
        0.08833289438,
        0.08808633938,
        0.08580902238,
        0.08634990238000001,
        0.08735761838,
        0.08776302038,
        0.08628721338,
        0.09247328838,
        0.09499461538000001,
        0.09073356338,
        0.09215396738000001,
        0.09202373138,
        0.09134387038,
        0.08776050738,
        0.09018646538,
        0.08713886438,
        0.08760674738
      ]
    }
  ]
}

Scenario: Isolated linker: peer-heavy resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 851.4 ± 128.7 716.3 1073.1 1.00
pacquet@main 928.9 ± 315.2 630.9 1475.4 1.09 ± 0.41
pnpm@HEAD 3347.9 ± 159.6 3096.8 3535.5 3.93 ± 0.62
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.85135448164,
      "stddev": 0.1286787690933821,
      "median": 0.77851180864,
      "user": 0.8219187133333333,
      "system": 0.12881348444444443,
      "min": 0.71629708664,
      "max": 1.07311385164,
      "times": [
        1.0183278126400002,
        1.07311385164,
        0.7641158706400001,
        0.8941285076400001,
        0.90891745664,
        0.77851180864,
        0.71629708664,
        0.74206766664,
        0.76671027364
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.9289498015288891,
      "stddev": 0.31519176811011645,
      "median": 0.73981806264,
      "user": 0.9046259355555555,
      "system": 0.15939748444444443,
      "min": 0.6309098026400001,
      "max": 1.4753555466400001,
      "times": [
        1.3560621376400002,
        0.73981806264,
        0.6309098026400001,
        0.7288012636400001,
        1.1651669636400002,
        0.79434894164,
        0.73295750664,
        0.7371279886400001,
        1.4753555466400001
      ]
    },
    {
      "command": "pnpm@HEAD",
      "mean": 3.347888693973333,
      "stddev": 0.15955091326700566,
      "median": 3.41529113664,
      "user": 5.073586935555555,
      "system": 0.33156959555555554,
      "min": 3.0968468436400003,
      "max": 3.5355394966400002,
      "times": [
        3.49497735964,
        3.36012935864,
        3.0968468436400003,
        3.14130998164,
        3.41529113664,
        3.20815393164,
        3.5355394966400002,
        3.44800746764,
        3.4307426696400003
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.589 ± 0.035 4.525 4.633 1.27 ± 0.05
pacquet@main 4.585 ± 0.119 4.494 4.909 1.27 ± 0.06
pnpr@HEAD 3.608 ± 0.151 3.491 3.987 1.00
pnpr@main 3.658 ± 0.163 3.509 3.934 1.01 ± 0.06
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.588646603979999,
      "stddev": 0.03522066171102139,
      "median": 4.590034641179999,
      "user": 2.41622014,
      "system": 1.7284277799999999,
      "min": 4.52474895418,
      "max": 4.63299763818,
      "times": [
        4.53860580918,
        4.62603865918,
        4.52474895418,
        4.63299763818,
        4.60693228318,
        4.5922522911799994,
        4.58190718618,
        4.579429783179999,
        4.5878169911799995,
        4.6157364441799995
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.58471577778,
      "stddev": 0.11852219447254057,
      "median": 4.56618095468,
      "user": 2.1992392400000003,
      "system": 1.64987798,
      "min": 4.494172832179999,
      "max": 4.90890005018,
      "times": [
        4.57429799318,
        4.59065958118,
        4.55806391618,
        4.57701353618,
        4.90890005018,
        4.523235157179999,
        4.57576111718,
        4.50484020318,
        4.54021339118,
        4.494172832179999
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.60776951248,
      "stddev": 0.1513983761844863,
      "median": 3.5570783186800004,
      "user": 1.4268682400000001,
      "system": 1.4383825799999999,
      "min": 3.49130453318,
      "max": 3.9874981431800003,
      "times": [
        3.73490408718,
        3.5268217221800002,
        3.5550010691800003,
        3.50126082518,
        3.6015014931800002,
        3.9874981431800003,
        3.55915556818,
        3.5113995511800002,
        3.60884813218,
        3.49130453318
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.6582625495800003,
      "stddev": 0.16275781027895603,
      "median": 3.59685958568,
      "user": 1.4639069399999998,
      "system": 1.4932791799999996,
      "min": 3.50915347918,
      "max": 3.93360827918,
      "times": [
        3.92768516818,
        3.50915347918,
        3.57654683318,
        3.93360827918,
        3.61717233818,
        3.53145767518,
        3.53765555218,
        3.7323767931800003,
        3.5127412021800004,
        3.7042281751800004
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13633
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
2,602.83 ms
(-2.18%)Baseline: 2,660.73 ms
3,192.88 ms
(81.52%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,725.54 ms
(-3.69%)Baseline: 1,791.74 ms
2,150.09 ms
(80.25%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
396.64 ms
(-11.18%)Baseline: 446.57 ms
535.88 ms
(74.02%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
195.38 ms
(-13.84%)Baseline: 226.77 ms
272.12 ms
(71.80%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,374.77 ms
(-1.69%)Baseline: 2,415.68 ms
2,898.81 ms
(81.92%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,524.75 ms
(+0.33%)Baseline: 4,509.84 ms
5,411.81 ms
(83.61%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
261.27 ms
(-8.88%)Baseline: 286.74 ms
344.09 ms
(75.93%)
isolated-linker.peer-heavy-resolve.hot-cache.offline📈 view plot
🚷 view threshold
716.30 ms
(+2.98%)Baseline: 695.57 ms
834.68 ms
(85.82%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13633
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,464.32 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
292.28 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
301.31 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
85.14 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,399.41 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,491.30 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
261.86 ms
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan force-pushed the fix/global-install-publication branch from bec87d5 to 0e16e61 Compare August 7, 2026 14:02
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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

🧹 Nitpick comments (2)
pnpm11/global/commands/test/globalPublication.test.ts (2)

500-508: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated cleanup fixture setup.

Lines 500-508, 531-542, and 563-572 repeat the same scaffold: mkdtemp, assign testRoot, derive globalDir and globalBinDir, then create directories. Add a createCleanupFixture helper next to createFixture and return the paths. This removes the duplication and keeps the temp-root bookkeeping in one place.

The path instructions ask for depth on missed reuse and duplication.

♻️ Proposed helper
interface CleanupFixture {
  root: string
  globalDir: string
  globalBinDir: string
}

async function createCleanupFixture (): Promise<CleanupFixture> {
  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'pnpm-global-cleanup-'))
  testRoot = root
  const globalDir = path.join(root, 'global')
  const globalBinDir = path.join(root, 'bin')
  await Promise.all([
    fs.mkdir(globalDir, { recursive: true }),
    fs.mkdir(globalBinDir, { recursive: true }),
  ])
  return { root, globalDir, globalBinDir }
}
🤖 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 `@pnpm11/global/commands/test/globalPublication.test.ts` around lines 500 -
508, Add a CleanupFixture type and createCleanupFixture helper beside
createFixture to centralize temporary-root creation, testRoot assignment, path
derivation, and directory setup. Replace the duplicated setup blocks in all
three cleanup tests with this helper and reuse its returned root, globalDir, and
globalBinDir paths.

Source: Path instructions


51-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Return only the packages whose bins the mock actually wrote.

When skipMissingBinSources is true, the loop skips a command at Line 52, but Line 65 still returns that command's pkgName. The mock then reports a package as linked when it wrote nothing. The current tests do not depend on this value, so this is a fidelity gap only. Track the written packages to keep the mock aligned with the real linkBinsOfPackages contract.

♻️ Proposed change to track written packages
+  const writtenPkgNames: string[] = []
   for (const { command } of commands) {
     if (skipMissingBinSources && !existsSync(command.path)) continue
     const slot = path.join(globalBinDir, command.name)
     await fs.rm(slot, { force: true, recursive: true })
     await fs.copyFile(command.path, slot)
     const sourceStat = await fs.stat(command.path)
     await fs.chmod(slot, sourceStat.mode & 0o777)
     linkedBinNames.push(command.name)
+    writtenPkgNames.push(command.name)
     writes++
     if (linkFailure != null && writes === linkFailure.afterWrites) {
       throw linkFailure.error
     }
   }
   /* eslint-enable no-await-in-loop */
-  return commands.map(({ pkgName }) => pkgName)
+  return commands.filter(({ command }) => writtenPkgNames.includes(command.name)).map(({ pkgName }) => pkgName)
🤖 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 `@pnpm11/global/commands/test/globalPublication.test.ts` around lines 51 - 65,
Update the mock’s loop to track package names only after a bin is successfully
written, including the existing skip behavior for missing sources. Return this
written-package collection instead of mapping all input commands, while
preserving the current bin write and failure-injection flow.
🤖 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 `@pnpm11/global/commands/test/globalPublication.test.ts`:
- Around line 292-293: Guard the direct symlink creation in the test setup
around the two fs.symlink calls, reusing the existing EPERM handling pattern
from seedSymlinkOrRegularFile. On Windows when symlink creation is unavailable,
apply the established fallback or skip behavior so the test remains valid on
hosts without Developer Mode or elevation.

---

Nitpick comments:
In `@pnpm11/global/commands/test/globalPublication.test.ts`:
- Around line 500-508: Add a CleanupFixture type and createCleanupFixture helper
beside createFixture to centralize temporary-root creation, testRoot assignment,
path derivation, and directory setup. Replace the duplicated setup blocks in all
three cleanup tests with this helper and reuse its returned root, globalDir, and
globalBinDir paths.
- Around line 51-65: Update the mock’s loop to track package names only after a
bin is successfully written, including the existing skip behavior for missing
sources. Return this written-package collection instead of mapping all input
commands, while preserving the current bin write and failure-injection flow.
🪄 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: CHILL

Plan: Pro Plus

Run ID: db01cbfa-b6ae-43be-96a9-55f5b6aa1663

📥 Commits

Reviewing files that changed from the base of the PR and between 97f20b0 and 0e16e61.

📒 Files selected for processing (12)
  • .changeset/safe-global-bin-publication.md
  • pnpm/crates/cli/src/cli_args/global.rs
  • pnpm/crates/cli/src/cli_args/global/publication.rs
  • pnpm/crates/cli/src/cli_args/global/publication/tests.rs
  • pnpm11/bins/remover/src/removeBins.ts
  • pnpm11/global/commands/src/globalAdd.ts
  • pnpm11/global/commands/src/globalPublication.ts
  • pnpm11/global/commands/src/globalUpdate.ts
  • pnpm11/global/commands/test/globalAdd.test.ts
  • pnpm11/global/commands/test/globalPublication.test.ts
  • pnpm11/global/commands/test/globalUpdate.test.ts
  • pnpm11/global/commands/test/removeBinWindows.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • pnpm11/bins/remover/src/removeBins.ts
  • pnpm11/global/commands/src/globalUpdate.ts
  • pnpm/crates/cli/src/cli_args/global.rs
  • pnpm11/global/commands/src/globalAdd.ts
  • pnpm11/global/commands/test/removeBinWindows.test.ts
  • pnpm/crates/cli/src/cli_args/global/publication/tests.rs
  • .changeset/safe-global-bin-publication.md
  • pnpm/crates/cli/src/cli_args/global/publication.rs
  • pnpm11/global/commands/test/globalUpdate.test.ts
  • pnpm11/global/commands/test/globalAdd.test.ts

@qodo-code-review

qodo-code-review Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to f42423f

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent staged-link concurrency collisions

Use uniquely created temporary directories for staged links instead of
PID-derived paths. This prevents spurious failures and race conditions during
concurrent activations.

pnpm/crates/cli/src/cli_args/global/activation.rs [45-54]

-let staged = link.with_extension(format!("{}.tmp", std::process::id()));
-match fs::remove_file(&staged) {
-    Ok(()) => {}
-    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
-    Err(error) => return Err(error),
-}
+let staging_dir = tempfile::Builder::new()
+    .prefix(".pnpm-hash-link-")
+    .tempdir_in(parent)?;
+let staged = staging_dir.path().join("link");
 symlink_dir_entry(&relative_path(parent, target), &staged)?;
-fs::rename(&staged, link).inspect_err(|_| {
-    let _ = fs::remove_file(&staged);
-})
+fs::rename(&staged, link)

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: This suggestion addresses a severe concurrency bug by preventing race conditions caused by predictable, shared temporary file paths across threads.

High
Complete rollback despite partial failures

Enhance rollback resilience by continuing operations upon individual failures
and throwing an AggregateError.

pnpm11/global/commands/src/globalActivation.ts [322-336]

 async function restoreGlobalInstall (opts: ActivateGlobalInstallOptions & PreparedGlobalInstall): Promise<void> {
+  const errors: unknown[] = []
   for (const name of opts.actualBinNames) {
-    // eslint-disable-next-line no-await-in-loop -- Rollback mutation must settle before the next step or return.
-    await removeBin(path.join(opts.globalBinDir, name))
+    try {
+      // eslint-disable-next-line no-await-in-loop -- Rollback mutations are intentionally ordered.
+      await removeBin(path.join(opts.globalBinDir, name))
+    } catch (err) {
+      errors.push(err)
+    }
   }
   for (const { original, backup } of opts.savedBinSlots) {
-    // eslint-disable-next-line no-await-in-loop -- Rollback mutation must settle before the next step or return.
-    await fs.promises.rename(backup, original)
+    try {
+      // eslint-disable-next-line no-await-in-loop -- Rollback mutations are intentionally ordered.
+      await fs.promises.rename(backup, original)
+    } catch (err) {
+      errors.push(err)
+    }
   }
-  if (opts.oldHashTarget == null) {
-    await fs.promises.rm(opts.hashLink, { force: true, recursive: true })
-  } else {
-    await swapHashLink(opts.oldHashTarget, opts.hashLink)
+  try {
+    if (opts.oldHashTarget == null) {
+      await fs.promises.rm(opts.hashLink, { force: true, recursive: true })
+    } else {
+      await swapHashLink(opts.oldHashTarget, opts.hashLink)
+    }
+  } catch (err) {
+    errors.push(err)
+  }
+  if (errors.length === 1) throw errors[0]
+  if (errors.length > 1) {
+    throw new AggregateError(errors, 'Failed to fully restore the previous global install')
   }
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: Collecting rollback errors into an AggregateError ensures that a single failure doesn't abort the entire rollback process, improving the reliability of the recovery mechanism.

Medium
Isolate concurrent staging links

Use a uniquely generated temporary directory for staging the hashLink to avoid
concurrency collisions.

pnpm11/global/commands/src/globalActivation.ts [171-179]

-const stagedLink = `${hashLink}.${process.pid}.tmp`
-await fs.promises.rm(stagedLink, { force: true, recursive: true })
-await fs.promises.symlink(path.relative(path.dirname(hashLink), target), stagedLink, 'dir')
+const stagingDir = await fs.promises.mkdtemp(`${hashLink}.${process.pid}.`)
+const stagedLink = path.join(stagingDir, 'hash-link')
 try {
+  await fs.promises.symlink(path.relative(stagingDir, target), stagedLink, 'dir')
   await fs.promises.rename(stagedLink, hashLink)
-} catch (err) {
-  await fs.promises.rm(stagedLink, { force: true, recursive: true })
-  throw err
+} finally {
+  await fs.promises.rm(stagingDir, { force: true, recursive: true })
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why: Using a temporary directory ensures atomic swapping even if there are concurrent attempts to update the exact same hashLink, avoiding edge-case race conditions.

Low
Security
Reject escaping global bin paths

Validate the generated bin paths to ensure they don't escape globalBinDir.

pnpm11/global/commands/src/globalActivation.ts [260]

-const original = path.join(opts.globalBinDir, `${name}${extension}`)
+const original = path.resolve(opts.globalBinDir, `${name}${extension}`)
+if (path.dirname(original) !== path.resolve(opts.globalBinDir)) {
+  throw new PnpmError(
+    'GLOBAL_BIN_INVALID_NAME',
+    `Cannot activate global bin with an unsafe name: ${name}`
+  )
+}

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: Validating that the computed bin path is actually contained within globalBinDir provides an important defense-in-depth mechanism against path traversal vulnerabilities originating from malicious package manifests.

Medium
  • Update

Previous suggestions

Suggestions up to commit 078a4d0
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use unique atomic staging paths

Use a unique staging path with a retry mechanism.

pnpm/crates/cli/src/cli_args/global/activation.rs [45-54]

-    let staged = link.with_extension(format!("{}.tmp", std::process::id()));
-    match fs::remove_file(&staged) {
-        Ok(()) => {}
-        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
-        Err(error) => return Err(error),
+    let relative_target = relative_path(parent, target);
+    for attempt in 0_u64.. {
+        let staged = link.with_extension(format!(
+            "{}-{}-{attempt}.tmp",
+            std::process::id(),
+            std::thread::current().name().unwrap_or("activation"),
+        ));
+        match symlink_dir_entry(&relative_target, &staged) {
+            Ok(()) => {
+                return fs::rename(&staged, link).inspect_err(|_| {
+                    let _ = fs::remove_file(&staged);
+                });
+            }
+            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
+            Err(error) => return Err(error),
+        }
     }
-    symlink_dir_entry(&relative_path(parent, target), &staged)?;
-    fs::rename(&staged, link).inspect_err(|_| {
-        let _ = fs::remove_file(&staged);
-    })
+    unreachable!()
Suggestion importance[1-10]: 8

__

Why: This prevents race conditions between concurrent activations in the same process by using unique staging paths instead of just the process ID.

Medium
Preserve targets after unlink failures

Skip deleting the installation directory if removing its hash link fails.

pnpm/crates/cli/src/cli_args/global.rs [646-661]

-        match remove_symlink_dir(&hash_link) {
-            Ok(()) => {}
-            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+        let hash_link_removed = match remove_symlink_dir(&hash_link) {
+            Ok(()) => true,
+            Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
             Err(error) => {
                 cleanup_reports.push(ArtifactCleanupError {
                     context: format!(
                         "remove replaced global hash link at {}",
                         hash_link.display(),
                     ),
                     source: error,
                 });
+                false
             }
+        };
+        if !hash_link_removed {
+            continue;
         }
     }
     if is_subdir(global_pkg_dir, &group.install_dir) {
         match fs::remove_dir_all(&group.install_dir) {
Suggestion importance[1-10]: 7

__

Why: This prevents creating a dangling symlink by skipping the deletion of the target directory if removing its symlink fails.

Medium
Isolate concurrent link swaps

Append a unique identifier to the staged link path. This prevents file
collisions and unintended deletions during concurrent link swaps within the same
process.

pnpm11/global/commands/src/globalActivation.ts [171-173]

-  const stagedLink = `${hashLink}.${process.pid}.tmp`
-  await fs.promises.rm(stagedLink, { force: true, recursive: true })
+  const stagedLink = `${hashLink}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
   await fs.promises.symlink(path.relative(path.dirname(hashLink), target), stagedLink, 'dir')
Suggestion importance[1-10]: 7

__

Why: Adding uniqueness to the temporary staged link prevents potential race conditions if concurrent global installations target the same hash link.

Medium
Preserve valid duplicate commands

Modify the actualBins map to store an array of bin paths instead of a single
path. Update the missing check to only delete the slot if all of the registered
duplicate sources are missing.

pnpm11/global/commands/src/globalActivation.ts [227-244]

-  if (!opts.binsToSkip.has(name)) actualBins.set(name, binPath)
+  if (!opts.binsToSkip.has(name)) {
+    const binPaths = actualBins.get(name) ?? []
+    binPaths.push(binPath)
+    actualBins.set(name, binPaths)
+  }
 ...
-  const missing = (await Promise.all([...actualBins].map(async ([name, binPath]) => {
-    return await pathExists(binPath) ? [] : [name]
+  const missing = (await Promise.all([...actualBins].map(async ([name, binPaths]) => {
+    const sourceExists = (await Promise.all(binPaths.map(pathExists))).some(Boolean)
+    return sourceExists ? [] : [name]
   }))).flat()
Suggestion importance[1-10]: 7

__

Why: Storing multiple source paths for duplicate bin names prevents valid shims from being wrongly deleted when only a subset of the duplicate sources are missing.

Medium
Security
Reject unsafe command paths

Validate command names to prevent directory traversal attacks (e.g., via ../).
Reject unsafe bin names before mapping them or performing operations on the file
system.

pnpm11/global/commands/src/globalActivation.ts [226-228]

   for (const { name, path: binPath } of bins) {
+    if (path.basename(name) !== name || name === '.' || name === '..') {
+      throw new PnpmError(
+        'GLOBAL_BIN_INVALID_NAME',
+        `Cannot activate global bin with unsafe command name: ${name}`
+      )
+    }
     if (!opts.binsToSkip.has(name)) actualBins.set(name, binPath)
   }
Suggestion importance[1-10]: 8

__

Why: This security check prevents arbitrary path traversal if a malicious package attempts to write, back up, or remove files outside the designated globalBinDir.

Medium
Suggestions up to commit 3410313
CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid destructive staging-path collisions

Use a temporary directory for the staged hash link instead of a PID-based suffix
to prevent concurrency bugs and accidental deletions.

pnpm/crates/cli/src/cli_args/global/activation.rs [45-54]

-let staged = link.with_extension(format!("{}.tmp", std::process::id()));
-match fs::remove_file(&staged) {
-    Ok(()) => {}
-    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
-    Err(error) => return Err(error),
-}
+let staged_dir = tempfile::Builder::new()
+    .prefix(".pnpm-hash-link-")
+    .tempdir_in(parent)?;
+let staged = staged_dir.path().join("link");
 symlink_dir_entry(&relative_path(parent, target), &staged)?;
-fs::rename(&staged, link).inspect_err(|_| {
-    let _ = fs::remove_file(&staged);
-})
+fs::rename(&staged, link)?;
+// The committed link has moved out, so cleanup failure must not turn
+// a successful activation into a reported failure.
+let _ = staged_dir.close();
+Ok(())
Suggestion importance[1-10]: 8

__

Why: Using a predictable PID-based path for temporary files can lead to race conditions and unintended file deletions; using tempfile ensures uniqueness and avoids concurrency issues.

Medium
Isolate concurrent staged link swaps

Use a uniquely generated staging directory with fs.promises.mkdtemp instead of a
PID-based suffix. This isolates concurrent link swaps and prevents potential
race conditions.

pnpm11/global/commands/src/globalActivation.ts [167-175]

-const stagedLink = `${hashLink}.${process.pid}.tmp`
-await fs.promises.rm(stagedLink, { force: true, recursive: true })
-await fs.promises.symlink(path.relative(path.dirname(hashLink), target), stagedLink, 'dir')
+const stagingDir = await fs.promises.mkdtemp(path.join(path.dirname(hashLink), '.pnpm-hash-link-'))
+const stagedLink = path.join(stagingDir, 'link')
 try {
+  await fs.promises.symlink(path.relative(path.dirname(hashLink), target), stagedLink, 'dir')
   await fs.promises.rename(stagedLink, hashLink)
-} catch (err) {
-  await fs.promises.rm(stagedLink, { force: true, recursive: true })
-  throw err
+} finally {
+  await fs.promises.rm(stagingDir, { force: true, recursive: true })
 }
Suggestion importance[1-10]: 8

__

Why: Using a unique temporary directory per invocation prevents a race condition when multiple activations run concurrently in the same process, which could otherwise corrupt the hashLink.

Medium
Prevent dangling global hash links

Skip removing the old install directory if the removal of its corresponding hash
link fails. This prevents leaving dangling symlinks that could cause errors
later.

pnpm/crates/cli/src/cli_args/global.rs [636-666]

+let mut hash_link_removal_failed = false;
 if group.hash != active_hash {
     let hash_link = get_hash_link(global_pkg_dir, &group.hash);
     match remove_symlink_dir(&hash_link) {
         Ok(()) => {}
         Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
         Err(error) => {
             cleanup_reports.push(ArtifactCleanupError {
                 context: format!(
                     "remove replaced global hash link at {}",
                     hash_link.display(),
                 ),
                 source: error,
             });
+            hash_link_removal_failed = true;
         }
     }
 }
-if is_subdir(global_pkg_dir, &group.install_dir) {
+if !hash_link_removal_failed && is_subdir(global_pkg_dir, &group.install_dir) {
     match fs::remove_dir_all(&group.install_dir) {
         Ok(()) => {}
         Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
         Err(error) => {
             cleanup_reports.push(ArtifactCleanupError {
                 context: format!(
                     "remove replaced global install directory at {}",
                     group.install_dir.display(),
                 ),
                 source: error,
             });
         }
     }
 }
Suggestion importance[1-10]: 7

__

Why: Leaving a dangling symlink by deleting the target directory after failing to remove the link could break future commands that depend on it; retaining the install directory improves resilience.

Medium
Preserve installs after unlink failures

Return early and avoid deleting the installDir if the removal of the old hash
link fails. This preserves the group's state for a future cleanup retry.

pnpm11/global/commands/src/globalActivation.ts [125-138]

 if (group.hash !== opts.activeHash) {
   try {
     await fs.promises.rm(getHashLink(opts.globalDir, group.hash), { force: true })
   } catch (err) {
     errors.push(err)
+    return errors
   }
 }
 if (isSubdir(opts.globalDir, group.installDir)) {
   try {
     await fs.promises.rm(group.installDir, { recursive: true, force: true })
   } catch (err) {
     errors.push(err)
   }
 }
Suggestion importance[1-10]: 7

__

Why: Halting the deletion process if the hash link removal fails prevents leaving dangling symlinks and allows subsequent operations to retry the cleanup since the installDir and its manifests remain intact.

Medium
Suggestions up to commit cefde86
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent staging path collisions

Use tempfile to create a unique staging directory instead of relying on the
process ID. This prevents staging path collisions during concurrent operations.

pnpm/crates/cli/src/cli_args/global/activation.rs [45-54]

-let staged = link.with_extension(format!("{}.tmp", std::process::id()));
-match fs::remove_file(&staged) {
-    Ok(()) => {}
-    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
-    Err(error) => return Err(error),
-}
+let staging_dir = tempfile::Builder::new()
+    .prefix(".pnpm-hash-link-")
+    .tempdir_in(parent)?;
+let staged = staging_dir.path().join("link");
 symlink_dir_entry(&relative_path(parent, target), &staged)?;
-fs::rename(&staged, link).inspect_err(|_| {
-    let _ = fs::remove_file(&staged);
-})
+fs::rename(&staged, link)
Suggestion importance[1-10]: 9

__

Why: The suggestion identifies a critical race condition where concurrent tasks within the same process would overwrite each other's staged symlinks due to the identical PID-based names and extension replacement.

High
Complete rollback despite failures

Modify restoreGlobalInstall to catch errors during individual bin removals or
restorations and proceed with the remaining rollback steps. Throw an
AggregateError at the end if any operations failed.

pnpm11/global/commands/src/globalActivation.ts [313-327]

 async function restoreGlobalInstall (opts: ActivateGlobalInstallOptions & PreparedGlobalInstall): Promise<void> {
+  const errors: unknown[] = []
+
   for (const name of opts.actualBinNames) {
-    // eslint-disable-next-line no-await-in-loop -- Rollback mutation must settle before the next step or return.
-    await removeBin(path.join(opts.globalBinDir, name))
+    try {
+      await removeBin(path.join(opts.globalBinDir, name)) // eslint-disable-line no-await-in-loop
+    } catch (err) {
+      errors.push(err)
+    }
   }
   for (const { original, backup } of opts.savedBinSlots) {
-    // eslint-disable-next-line no-await-in-loop -- Rollback mutation must settle before the next step or return.
-    await fs.promises.rename(backup, original)
+    try {
+      await fs.promises.rm(original, { force: true, recursive: true }) // eslint-disable-line no-await-in-loop
+      await fs.promises.rename(backup, original) // eslint-disable-line no-await-in-loop
+    } catch (err) {
+      errors.push(err)
+    }
   }
-  if (opts.oldHashTarget == null) {
-    await fs.promises.rm(opts.hashLink, { force: true, recursive: true })
-  } else {
-    await swapHashLink(opts.oldHashTarget, opts.hashLink)
+  try {
+    if (opts.oldHashTarget == null) {
+      await fs.promises.rm(opts.hashLink, { force: true, recursive: true })
+    } else {
+      await swapHashLink(opts.oldHashTarget, opts.hashLink)
+    }
+  } catch (err) {
+    errors.push(err)
+  }
+
+  if (errors.length === 1) throw errors[0]
+  if (errors.length > 1) {
+    throw new AggregateError(errors, 'Failed to restore the previous global install')
   }
 }
Suggestion importance[1-10]: 7

__

Why: This improves the robustness of the rollback mechanism by using an AggregateError to ensure as many items as possible are restored even if one operation fails.

Medium
Isolate concurrent staged links

Change the temporary stagedLink filename to include randomness (e.g., Date.now()
and Math.random()) instead of just process.pid.

pnpm11/global/commands/src/globalActivation.ts [162-164]

-const stagedLink = `${hashLink}.${process.pid}.tmp`
-await fs.promises.rm(stagedLink, { force: true, recursive: true })
+const stagedLink = `${hashLink}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
 await fs.promises.symlink(path.relative(path.dirname(hashLink), target), stagedLink, 'dir')
Suggestion importance[1-10]: 6

__

Why: Using a unique temporary filename prevents race conditions if multiple activations for the same global install happen concurrently within the same Node process.

Low
Security
Reject escaping bin paths

Validate that resolved bin names do not contain path traversal sequences. Reject
paths that fall outside of the expected globalBinDir.

pnpm11/global/commands/src/globalActivation.ts [216-220]

+const resolvedGlobalBinDir = path.resolve(opts.globalBinDir)
 for (const bins of binsByPackage) {
   for (const { name, path: binPath } of bins) {
-    if (!opts.binsToSkip.has(name)) actualBins.set(name, binPath)
+    if (opts.binsToSkip.has(name)) continue
+    const slot = path.resolve(resolvedGlobalBinDir, name)
+    if (!isSubdir(resolvedGlobalBinDir, slot)) {
+      throw new PnpmError(
+        'GLOBAL_BIN_INVALID_NAME',
+        `Cannot create global bin outside ${opts.globalBinDir}: ${name}`
+      )
+    }
+    actualBins.set(name, binPath)
   }
 }
Suggestion importance[1-10]: 9

__

Why: This addresses a critical security vulnerability where malicious package manifests could use path traversal (e.g., ../) in bin names to manipulate arbitrary files outside the globalBinDir.

High
Suggestions up to commit eda831e
CategorySuggestion                                                                                                                                    Impact
Possible issue
Isolate concurrent hash-link staging

Use a uniquely generated temporary directory for staging the hash link instead
of relying on the process ID.

pnpm/crates/cli/src/cli_args/global/publication.rs [45-54]

-let staged = link.with_extension(format!("{}.tmp", std::process::id()));
-match fs::remove_file(&staged) {
-    Ok(()) => {}
-    Err(error) if error.kind() == io::ErrorKind::NotFound => {}
-    Err(error) => return Err(error),
-}
+let staging_dir = tempfile::Builder::new()
+    .prefix(".pnpm-hash-link-")
+    .tempdir_in(parent)?;
+let staged = staging_dir.path().join("link");
 symlink_dir_entry(&relative_path(parent, target), &staged)?;
-fs::rename(&staged, link).inspect_err(|_| {
-    let _ = fs::remove_file(&staged);
-})
+fs::rename(&staged, link)
Suggestion importance[1-10]: 8

__

Why: Using the process ID for temporary files is susceptible to race conditions during concurrent operations within the same process, which could corrupt the hash link or cause failures.

Medium
Prevent dangling hash links

Conditionally prevent deleting the install directory if the hash link fails to
be removed.

pnpm11/global/commands/src/globalPublication.ts [120-133]

+let canRemoveInstallDir = true
 if (group.hash !== opts.activeHash) {
   try {
     await fs.promises.rm(getHashLink(opts.globalDir, group.hash), { force: true })
   } catch (err) {
     errors.push(err)
+    canRemoveInstallDir = false
   }
 }
-if (isSubdir(opts.globalDir, group.installDir)) {
+if (canRemoveInstallDir && isSubdir(opts.globalDir, group.installDir)) {
   try {
     await fs.promises.rm(group.installDir, { recursive: true, force: true })
   } catch (err) {
     errors.push(err)
   }
 }
Suggestion importance[1-10]: 4

__

Why: Preventing a dangling symlink when hash link removal fails is a valid edge case, but it offers only a marginal improvement since a permission failure on the hash link would likely also cause the subsequent install directory deletion to fail.

Low
Security
Reject unsafe global bin paths

Validate that global bin names consist of a single normal path component to
prevent path traversal. Reject any malicious or malformed names.

pnpm/crates/cli/src/cli_args/global/publication.rs [486-498]

 fn get_actual_bins<Sys: FsWalkFiles>(
     packages: &[PackageBinSource],
     bins_to_skip: &HashSet<String>,
-) -> BTreeMap<String, PathBuf> {
+) -> miette::Result<BTreeMap<String, PathBuf>> {
     packages
         .iter()
         .flat_map(|package| {
             get_bins_from_package_manifest::<Sys>(&package.manifest, &package.location)
         })
         .filter(|command| !bins_to_skip.contains(&command.name))
-        .map(|command| (command.name, command.path))
+        .map(|command| {
+            let mut components = Path::new(&command.name).components();
+            match (components.next(), components.next()) {
+                (Some(std::path::Component::Normal(_)), None) => {
+                    Ok((command.name, command.path))
+                }
+                _ => Err(miette::miette!(
+                    "Invalid global bin name: {}",
+                    command.name
+                )),
+            }
+        })
         .collect()
 }
Suggestion importance[1-10]: 8

__

Why: Validating the bin name prevents potential path traversal vulnerabilities that could occur if a malicious package defines paths escaping the global bin directory.

Medium
Suggestions up to commit 8b8cecc
CategorySuggestion                                                                                                                                    Impact
Security
Reject path-traversing bin names

Validate bin names from package manifests to ensure they are single path
components before using them in filesystem operations.

pnpm/crates/cli/src/cli_args/global/publication.rs [400-412]

 fn get_actual_bin_names<Sys: FsWalkFiles>(
     packages: &[PackageBinSource],
     bins_to_skip: &HashSet<String>,
-) -> HashSet<String> {
+) -> miette::Result<HashSet<String>> {
     packages
         .iter()
         .flat_map(|package| {
             get_bins_from_package_manifest::<Sys>(&package.manifest, &package.location)
         })
-        .map(|command| command.name)
-        .filter(|name| !bins_to_skip.contains(name))
+        .map(|command| {
+            let name = command.name;
+            let mut components = Path::new(&name).components();
+            if !matches!(components.next(), Some(std::path::Component::Normal(_)))
+                || components.next().is_some()
+            {
+                return Err(miette::miette!("Invalid global bin name: {name:?}"));
+            }
+            Ok(name)
+        })
+        .filter(|result| {
+            result.as_ref().map_or(true, |name| !bins_to_skip.contains(name))
+        })
         .collect()
 }
 
+fn prepare_global_install<Sys: FsWalkFiles>(
+    ...
+) -> miette::Result<PreparedGlobalInstall> {
+    let actual_bin_names = get_actual_bin_names::<Sys>(packages, bins_to_skip)?;
+    ...
+}
+
Suggestion importance[1-10]: 10

__

Why: This addresses a critical security vulnerability by preventing potential path traversal attacks when joining untrusted package bin names with global_bin_dir.

High
Contain cleanup paths safely

Validate replaced bin names to be single path components before appending them
to global_bin_dir for deletion.

pnpm/crates/cli/src/cli_args/global.rs [602-608]

+let mut components = Path::new(&bin_name).components();
+if !matches!(components.next(), Some(std::path::Component::Normal(_)))
+    || components.next().is_some()
+{
+    cleanup_reports.push(ArtifactCleanupError {
+        context: format!("reject invalid replaced global bin name {bin_name:?}"),
+        source: std::io::Error::new(
+            std::io::ErrorKind::InvalidData,
+            "global bin name must be a single path component",
+        ),
+    });
+    continue;
+}
 let bin_path = global_bin_dir.join(&bin_name);
 if let Err(error) = remove_bin(&bin_path) {
     cleanup_reports.push(ArtifactCleanupError {
         context: format!("remove replaced global bin at {}", bin_path.display()),
         source: error,
     });
 }
Suggestion importance[1-10]: 10

__

Why: This prevents potential path traversal vulnerabilities during the cleanup process, ensuring that malformed bin names in existing manifests cannot cause arbitrary file deletion outside the target directory.

High
Prevent bin path traversal

Validate that resolved bin slots remain within the global bin directory. This
prevents directory traversal attacks that could overwrite or delete external
files.

pnpm11/global/commands/src/globalPublication.ts [48-51]

-for (const name of opts.actualBinNames) {
+for (const name of prepared.actualBinNames) {
+  const slot = path.resolve(opts.globalBinDir, name)
+  if (path.dirname(slot) !== path.resolve(opts.globalBinDir)) {
+    throw new PnpmError(
+      'GLOBAL_BIN_INVALID_NAME',
+      `Cannot publish global bin outside ${opts.globalBinDir}: ${name}`
+    )
+  }
   // eslint-disable-next-line no-await-in-loop -- Publication mutations must settle before linking or rollback starts.
-  await removeBin(path.join(opts.globalBinDir, name))
+  await removeBin(slot)
 }
Suggestion importance[1-10]: 8

__

Why: This addresses a valid security risk regarding path traversal, preventing potential arbitrary file deletion when maliciously crafted bin names are provided.

Medium
Possible issue
Preserve installs after cleanup failures

Skip removing the old hash link and installation directory if stale bin removal
encounters any failures. This prevents leaving broken commands on the PATH and
preserves artifacts for future cleanup attempts.

pnpm11/global/commands/src/globalPublication.ts [117-130]

-if (group.hash !== opts.activeHash) {
-  try {
-    await fs.promises.rm(getHashLink(opts.globalDir, group.hash), { force: true })
-  } catch (err) {
-    errors.push(err)
+if (errors.length === 0) {
+  if (group.hash !== opts.activeHash) {
+    try {
+      await fs.promises.rm(getHashLink(opts.globalDir, group.hash), { force: true })
+    } catch (err) {
+      errors.push(err)
+    }
   }
-}
-if (isSubdir(opts.globalDir, group.installDir)) {
-  try {
-    await fs.promises.rm(group.installDir, { recursive: true, force: true })
-  } catch (err) {
-    errors.push(err)
+  if (errors.length === 0 && isSubdir(opts.globalDir, group.installDir)) {
+    try {
+      await fs.promises.rm(group.installDir, { recursive: true, force: true })
+    } catch (err) {
+      errors.push(err)
+    }
   }
 }
Suggestion importance[1-10]: 7

__

Why: This is a smart edge-case handling improvement that prevents broken shim references on PATH in case binary removal fails.

Medium

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 7, 2026
@qodo-code-review

qodo-code-review Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (3) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Comment says used to 📘 Rule violation ⚙ Maintainability ⭐ New
Description
A new comment uses historical phrasing ("used to belong"), violating the requirement that comments
describe current behavior rather than past implementations. This can lead to stale or misleading
documentation as the code evolves, making the codebase harder to maintain.
Code

pnpm11/global/commands/test/globalActivation.test.ts[R743-745]

+  // Changing the set of packages changes the hash, so `shared` was rewritten
+  // to point at the new one just before this ran — unlinking the group it
+  // used to belong to must not take it away again.
Relevance

●●● Strong

Multiple recent PRs accepted rewording comments to avoid “used to”/historical phrasing per
comment-freshness policy.

PR-#13652
PR-#13138
PR-#13532

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 772199 forbids/prohibits historical or temporal phrasing in comments (e.g., using
phrases like "used to"). The newly added comment includes the phrase "used to belong," which frames
the behavior historically rather than stating the current invariant/guarantee, and therefore
violates the rule.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/global/commands/test/globalActivation.test.ts[743-745]
pnpm/crates/cli/src/cli_args/global/activation/tests.rs[610-612]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A comment uses historical phrasing ("used to" / "used to belong"), which is disallowed under PR Compliance ID 772199; comments must describe current behavior/guarantees in present tense.

## Issue Context
These are test comments explaining/asserting an invariant. They can be rewritten to state the invariant/required guarantee directly (e.g., that removing a replaced group’s artifacts must not remove bins that remain activated) without referring to prior membership/history.

## Fix Focus Areas
- pnpm11/global/commands/test/globalActivation.test.ts[743-745]
- pnpm/crates/cli/src/cli_args/global/activation/tests.rs[610-612]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Symlink removal misasserted 🐞 Bug ⚙ Maintainability ⭐ New
Description
The new cleanup test uses existsSync(oldHashLink) to assert the replaced group’s hash-link was
removed, but this can still return false if the symlink/junction entry remains while its target
directory was deleted, weakening coverage for stale-hash-link cleanup regressions.
Code

pnpm11/global/commands/test/globalActivation.test.ts[R748-749]

+  expect(existsSync(oldHashLink)).toBe(false)
+  expect(existsSync(oldInstallDir)).toBe(false)
Relevance

●●● Strong

Team often strengthens deletion assertions by avoiding exists/existsSync in favor of
lstat/symlink_metadata NotFound checks.

PR-#13707
PR-#13780
PR-#11904

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
oldHashLink is created as a symlink/junction, and the test file already uses fs.lstat()
elsewhere to assert entry removal; using existsSync here can conflate “link removed” with “link
target removed,” reducing the test’s ability to catch stale-link cleanup bugs.

pnpm11/global/commands/test/globalActivation.test.ts[720-750]
pnpm11/global/commands/test/globalActivation.test.ts[923-928]
pnpm11/global/commands/test/globalActivation.test.ts[911-917]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The test intends to verify that `cleanupReplacedGlobalInstalls()` removes the old hash-link entry (`oldHashLink`), but it currently uses `existsSync(oldHashLink)`. Because `oldHashLink` is created as a symlink/junction, `existsSync` can return `false` when the link is dangling (target deleted) even if the link entry still exists, allowing a cleanup regression to pass CI.

### Issue Context
`oldHashLink` is created via `replaceDirectorySymlink()` which calls `fs.symlink(...)`. In the same file, other “removed” assertions correctly use `fs.lstat()` to check the directory entry itself.

### Fix Focus Areas
- pnpm11/global/commands/test/globalActivation.test.ts[720-750]

### Suggested change
Replace:
- `expect(existsSync(oldHashLink)).toBe(false)`

With an entry-level check, e.g.:
- `await expect(fs.lstat(oldHashLink)).rejects.toMatchObject({ code: 'ENOENT' })`

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Silent backup cleanup failure ⊘ Outdated 🐞 Bug ◔ Observability
Description
After a global publication is committed, the code swallows failures when cleaning up the temporary
.pnpm-bin-backup-* backup directory (via TempDir::close() / delete guarded by catch {}), so
repeated cleanup failures can silently leak backup artifacts under the global bin dir and hide
underlying filesystem/permission problems.
Code

pnpm11/global/commands/src/globalPublication.ts[R70-74]

+  // Publication is already committed, so a leftover backup directory must
+  // not fail the command.
+  try {
+    await fs.promises.rm(prepared.backupDir, { recursive: true, force: true })
+  } catch {}
Relevance

●●● Strong

Team precedent: don’t silently ignore cleanup failures; warn while still succeeding after commit.

PR-#13340

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited implementation creates a temporary backup directory inside the global bin directory (named
like .pnpm-bin-backup-*) and populates it with backups of existing bin-slot state before
publishing; once publication succeeds, the only intended cleanup is removing that temp directory
(calling backup_dir.close() / performing deletion), but any error from that cleanup step is
explicitly discarded (catch {} / ignored result). Because the backup directory is meant to be
removed on success, dropping the error means leftover backup directories/files can accumulate with
no warning or diagnostic signal to users/operators that cleanup is failing (e.g., due to
EBUSY/EPERM/permissions).

pnpm11/global/commands/src/globalPublication.ts[70-75]
pnpm11/global/commands/src/globalPublication.ts[134-150]
pnpm11/global/commands/test/globalPublication.test.ts[354-379]
pnpm/crates/cli/src/cli_args/global/publication.rs[169-173]
pnpm/crates/cli/src/cli_args/global/publication.rs[334-350]
PR-#13340

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
After a successful (committed) global publication, cleanup of the temporary `.pnpm-bin-backup-*` backup directory suppresses/ignores errors (`catch {}` / dropped `TempDir::close()` result). This can leave backup artifacts behind under the global bin dir with no warning/diagnostic output, making persistent cleanup failures hard to detect and potentially accumulating junk.

## Issue Context
The code path is explicitly intended to not fail the command after publication is committed, but it should still surface cleanup failures (at least as a warning/debug diagnostic) and ideally include the backup directory path. Optionally, consider keeping the directory (e.g., via a `keep()`-style approach) so the user can inspect/clean it when cleanup fails, while preserving the “do not fail post-commit” behavior.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[70-74]
- pnpm/crates/cli/src/cli_args/global/publication.rs[169-173]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (1)
4. Duplicate bin resolution (TS) 🐞 Bug ➹ Performance
Description
In pnpm’s new global publication flow, bin commands are resolved up-front to compute
actualBinNames/actual_bin_names, then resolved a second time inside the bin-linking step
(linkBinsOfPackages / link_bins_of_packages_with_excludes), creating avoidable extra work per
global add/update and potentially repeating filesystem traversal or directory walking depending on
how bin resolution reads manifests.
Code

pnpm11/global/commands/src/globalPublication.ts[R164-167]

+async function getActualBinNames (opts: PublishGlobalInstallOptions): Promise<Set<string>> {
+  const actualBinNames = new Set<string>()
+  const binsByPackage = await Promise.all(opts.pkgs.map(async ({ manifest, location }) => {
+    return getBinsFromPackageManifest(manifest, location)
Relevance

●● Moderate

They accept some duplicate-work perf fixes, but this needs nontrivial refactor/behavior-safety;
outcome uncertain.

PR-#12491
PR-#13141

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited publication code paths first compute actualBinNames/actual_bin_names by resolving bins
from each package manifest (via getBinsFromPackageManifest() /
get_bins_from_package_manifest()), and then invoke the bin linker, which again resolves commands
from the same package manifests during linking. Because both stages independently perform
manifest-based bin resolution in the same publication operation, the flow necessarily incurs two
bin-resolution passes per global publication.

pnpm11/global/commands/src/globalPublication.ts[164-168]
pnpm11/bins/linker/src/index.ts[226-228]
pnpm/crates/cli/src/cli_args/global/publication.rs[351-360]
pnpm/crates/cmd-shim/src/link_bins.rs[339-359]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The global publication implementation resolves package bins once to compute `actualBinNames`/`actual_bin_names` (needed for backup/removal in the transactional flow) and then calls the bin-linking function, which resolves bins from the manifest again. This duplicates bin-resolution work for every global add/update and may re-walk directories / re-parse manifests unnecessarily.

## Issue Context
The transactional publication flow needs bin names early (e.g., for snapshot, backup, or removal decisions), but the linker currently performs its own bin resolution from package manifests when creating shims/links. As a result, the same bin-resolution logic runs twice in a single publication.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[164-173]
- pnpm11/bins/linker/src/index.ts[226-228]
- pnpm/crates/cli/src/cli_args/global/publication.rs[351-360]
- pnpm/crates/cmd-shim/src/link_bins.rs[339-359]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

5. Missing comma in AggregateError args 📘 Rule violation ⚙ Maintainability
Description
A multi-line new AggregateError(...) call is missing a trailing comma after the last argument,
violating the TypeScript trailing-comma requirement and causing inconsistent formatting.
Code

pnpm11/global/commands/src/globalPublication.ts[R295-298]

+  throw new AggregateError(
+    [publicationError, ...cleanupErrors],
+    `Failed to clean up after global bin publication failed.${remainingMessage}`,
+    { cause: publicationError }
Relevance

● Weak

Trailing-comma style nits in multi-line TS constructs were explicitly rejected in prior reviews.

PR-#13428
PR-#13600
PR-#13477

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript argument lists. The `new
AggregateError(...)` call ends its final argument without a trailing comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/global/commands/src/globalPublication.ts[295-298]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A multi-line `new AggregateError(...)` call is missing a trailing comma after the final argument.

## Issue Context
This repo requires trailing commas in TypeScript multi-line constructs for consistent formatting and cleaner diffs.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[295-298]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Missing trailing comma in PnpmError 📘 Rule violation ⚙ Maintainability
Description
In globalPublication.ts, multi-line constructor calls omit a trailing comma after the last
argument (e.g., { cause: publicationError }), which violates the TypeScript trailing-comma
requirement and causes inconsistent formatting/noisier diffs.
Code

pnpm11/global/commands/src/globalPublication.ts[R64-65]

+        { cause: publicationError }
+      )
Relevance

● Weak

Team has recent precedents rejecting trailing-comma-only formatting changes in multi-line TS
constructs.

PR-#13428
PR-#12876
PR-#13288

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs. The new
PnpmError call spans multiple lines but the final argument { cause: publicationError } does not
end with a comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/global/commands/src/globalPublication.ts[59-65]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pnpm11/global/commands/src/globalPublication.ts` contains multi-line constructor calls where the last argument does not end with a trailing comma (e.g., `new PnpmError(...)`). This violates the trailing-comma requirement for multi-line constructs.

## Issue Context
Rule requires trailing commas for multi-line constructs (argument lists, etc.) to keep formatting consistent.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[59-65]
- pnpm11/global/commands/src/globalPublication.ts[154-158]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context used
✅ Compliance rules (platform): 26 rules

Grey Divider

Tip of the day
💡 Did you know, you can group findings by type and pick your Finding display, from Minimal to Full

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous review results

Review updated until commit f42423f

Results up to commit 291e261 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Duplicate bin resolution (TS) 🐞 Bug ➹ Performance
Description
In pnpm’s new global publication flow, bin commands are resolved up-front to compute
actualBinNames/actual_bin_names, then resolved a second time inside the bin-linking step
(linkBinsOfPackages / link_bins_of_packages_with_excludes), creating avoidable extra work per
global add/update and potentially repeating filesystem traversal or directory walking depending on
how bin resolution reads manifests.
Code

pnpm11/global/commands/src/globalPublication.ts[R164-167]

+async function getActualBinNames (opts: PublishGlobalInstallOptions): Promise<Set<string>> {
+  const actualBinNames = new Set<string>()
+  const binsByPackage = await Promise.all(opts.pkgs.map(async ({ manifest, location }) => {
+    return getBinsFromPackageManifest(manifest, location)
Relevance

●● Moderate

They accept some duplicate-work perf fixes, but this needs nontrivial refactor/behavior-safety;
outcome uncertain.

PR-#12491
PR-#13141

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited publication code paths first compute actualBinNames/actual_bin_names by resolving bins
from each package manifest (via getBinsFromPackageManifest() /
get_bins_from_package_manifest()), and then invoke the bin linker, which again resolves commands
from the same package manifests during linking. Because both stages independently perform
manifest-based bin resolution in the same publication operation, the flow necessarily incurs two
bin-resolution passes per global publication.

pnpm11/global/commands/src/globalPublication.ts[164-168]
pnpm11/bins/linker/src/index.ts[226-228]
pnpm/crates/cli/src/cli_args/global/publication.rs[351-360]
pnpm/crates/cmd-shim/src/link_bins.rs[339-359]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The global publication implementation resolves package bins once to compute `actualBinNames`/`actual_bin_names` (needed for backup/removal in the transactional flow) and then calls the bin-linking function, which resolves bins from the manifest again. This duplicates bin-resolution work for every global add/update and may re-walk directories / re-parse manifests unnecessarily.

## Issue Context
The transactional publication flow needs bin names early (e.g., for snapshot, backup, or removal decisions), but the linker currently performs its own bin resolution from package manifests when creating shims/links. As a result, the same bin-resolution logic runs twice in a single publication.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[164-173]
- pnpm11/bins/linker/src/index.ts[226-228]
- pnpm/crates/cli/src/cli_args/global/publication.rs[351-360]
- pnpm/crates/cmd-shim/src/link_bins.rs[339-359]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational
2. Missing trailing comma in PnpmError 📘 Rule violation ⚙ Maintainability
Description
In globalPublication.ts, multi-line constructor calls omit a trailing comma after the last
argument (e.g., { cause: publicationError }), which violates the TypeScript trailing-comma
requirement and causes inconsistent formatting/noisier diffs.
Code

pnpm11/global/commands/src/globalPublication.ts[R64-65]

+        { cause: publicationError }
+      )
Relevance

● Weak

Team has recent precedents rejecting trailing-comma-only formatting changes in multi-line TS
constructs.

PR-#13428
PR-#12876
PR-#13288

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript constructs. The new
PnpmError call spans multiple lines but the final argument { cause: publicationError } does not
end with a comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/global/commands/src/globalPublication.ts[59-65]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`pnpm11/global/commands/src/globalPublication.ts` contains multi-line constructor calls where the last argument does not end with a trailing comma (e.g., `new PnpmError(...)`). This violates the trailing-comma requirement for multi-line constructs.

## Issue Context
Rule requires trailing commas for multi-line constructs (argument lists, etc.) to keep formatting consistent.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[59-65]
- pnpm11/global/commands/src/globalPublication.ts[154-158]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit b877d34 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Informational
1. Missing comma in AggregateError args 📘 Rule violation ⚙ Maintainability
Description
A multi-line new AggregateError(...) call is missing a trailing comma after the last argument,
violating the TypeScript trailing-comma requirement and causing inconsistent formatting.
Code

pnpm11/global/commands/src/globalPublication.ts[R295-298]

+  throw new AggregateError(
+    [publicationError, ...cleanupErrors],
+    `Failed to clean up after global bin publication failed.${remainingMessage}`,
+    { cause: publicationError }
Relevance

● Weak

Trailing-comma style nits in multi-line TS constructs were explicitly rejected in prior reviews.

PR-#13428
PR-#13600
PR-#13477

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas in multi-line TypeScript argument lists. The `new
AggregateError(...)` call ends its final argument without a trailing comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/global/commands/src/globalPublication.ts[295-298]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A multi-line `new AggregateError(...)` call is missing a trailing comma after the final argument.

## Issue Context
This repo requires trailing commas in TypeScript multi-line constructs for consistent formatting and cleaner diffs.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[295-298]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 8b8cecc ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Silent backup cleanup failure ⊘ Outdated 🐞 Bug ◔ Observability
Description
After a global publication is committed, the code swallows failures when cleaning up the temporary
.pnpm-bin-backup-* backup directory (via TempDir::close() / delete guarded by catch {}), so
repeated cleanup failures can silently leak backup artifacts under the global bin dir and hide
underlying filesystem/permission problems.
Code

pnpm11/global/commands/src/globalPublication.ts[R70-74]

+  // Publication is already committed, so a leftover backup directory must
+  // not fail the command.
+  try {
+    await fs.promises.rm(prepared.backupDir, { recursive: true, force: true })
+  } catch {}
Relevance

●●● Strong

Team precedent: don’t silently ignore cleanup failures; warn while still succeeding after commit.

PR-#13340

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited implementation creates a temporary backup directory inside the global bin directory (named
like .pnpm-bin-backup-*) and populates it with backups of existing bin-slot state before
publishing; once publication succeeds, the only intended cleanup is removing that temp directory
(calling backup_dir.close() / performing deletion), but any error from that cleanup step is
explicitly discarded (catch {} / ignored result). Because the backup directory is meant to be
removed on success, dropping the error means leftover backup directories/files can accumulate with
no warning or diagnostic signal to users/operators that cleanup is failing (e.g., due to
EBUSY/EPERM/permissions).

pnpm11/global/commands/src/globalPublication.ts[70-75]
pnpm11/global/commands/src/globalPublication.ts[134-150]
pnpm11/global/commands/test/globalPublication.test.ts[354-379]
pnpm/crates/cli/src/cli_args/global/publication.rs[169-173]
pnpm/crates/cli/src/cli_args/global/publication.rs[334-350]
PR-#13340

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
After a successful (committed) global publication, cleanup of the temporary `.pnpm-bin-backup-*` backup directory suppresses/ignores errors (`catch {}` / dropped `TempDir::close()` result). This can leave backup artifacts behind under the global bin dir with no warning/diagnostic output, making persistent cleanup failures hard to detect and potentially accumulating junk.

## Issue Context
The code path is explicitly intended to not fail the command after publication is committed, but it should still surface cleanup failures (at least as a warning/debug diagnostic) and ideally include the backup directory path. Optionally, consider keeping the directory (e.g., via a `keep()`-style approach) so the user can inspect/clean it when cleanup fails, while preserving the “do not fail post-commit” behavior.

## Fix Focus Areas
- pnpm11/global/commands/src/globalPublication.ts[70-74]
- pnpm/crates/cli/src/cli_args/global/publication.rs[169-173]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

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

🧹 Nitpick comments (1)
pnpm/crates/cli/src/cli_args/global/publication.rs (1)

32-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the imported fs alias.

Line 9 already imports fs. Line 34 qualifies the same function as std::fs::rename. Use fs::rename for consistency with the rest of the file.

The code style guide asks for merged explicit imports.

♻️ Proposed change
 impl FsRename for Host {
     fn rename(source: &Path, target: &Path) -> io::Result<()> {
-        std::fs::rename(source, target)
+        fs::rename(source, target)
     }
 }
🤖 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 `@pnpm/crates/cli/src/cli_args/global/publication.rs` around lines 32 - 36,
Update `Host::rename` to call the imported `fs::rename` alias instead of
qualifying the function through `std::fs`, preserving the existing arguments and
return behavior.

Source: Path instructions

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

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/global/publication.rs`:
- Around line 32-36: Update `Host::rename` to call the imported `fs::rename`
alias instead of qualifying the function through `std::fs`, preserving the
existing arguments and return behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 53e0dcbf-7333-49f4-9995-c53b39a93b69

📥 Commits

Reviewing files that changed from the base of the PR and between 0e16e61 and b877d34.

📒 Files selected for processing (5)
  • pnpm/crates/cli/src/cli_args/global.rs
  • pnpm/crates/cli/src/cli_args/global/publication.rs
  • pnpm/crates/cli/src/cli_args/global/publication/tests.rs
  • pnpm11/global/commands/src/globalPublication.ts
  • pnpm11/global/commands/test/globalPublication.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • pnpm11/global/commands/src/globalPublication.ts
  • pnpm/crates/cli/src/cli_args/global/publication/tests.rs
  • pnpm/crates/cli/src/cli_args/global.rs

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit b877d34

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit d7a0861

YESHYUNGSEOK and others added 5 commits August 11, 2026 00:03
Treat backup-directory removal after a committed publication as
best-effort in both stacks, so a failed removal no longer reports a
successful install as failed. Attempt every stale bin, hash-link, and
install-directory removal during cleanup and aggregate the failures
instead of aborting at the first error. Tolerate dangling Windows bin
symlinks when snapshotting slots so a broken global install can be
repaired by re-running the install.

Also align the global update error contexts with the add path, simplify
io_error_report, and fix dylint findings in the new publication code
(trailing commas, a single-letter generic, import collapse).

Co-Authored-By: Claude Fable 5 <[email protected]>
Seed test symlinks through a helper that bails out on Windows hosts
where symlink creation needs elevation, and make the linker mock report
only the packages whose bins it actually wrote.

Co-Authored-By: Claude Fable 5 <[email protected]>
zkochan and others added 3 commits August 11, 2026 00:03
Publication creates its backup directory inside the global bin
directory, which the bin linker used to be the first to create. A first
global install into a fresh bin directory therefore failed with ENOENT.

Also mock cmd-extension in the Windows bin removal test: the real
extension is derived from the host COMSPEC and is uppercase on Windows,
which made the expected shim paths host-dependent.

Co-Authored-By: Claude Fable 5 <[email protected]>
The install directory is the only record of which bins a group owns, so
removing it after the enumeration failed would strand those executables
on PATH with nothing left to associate them with. Report the failure and
leave the group for a later run to clean up.

Co-Authored-By: Claude Fable 5 <[email protected]>
@zkochan
zkochan force-pushed the fix/global-install-publication branch from d7a0861 to 8b8cecc Compare August 10, 2026 22:05
Comment thread pnpm/crates/cli/src/cli_args/global.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8b8cecc

zkochan and others added 2 commits August 11, 2026 00:45
Bin shims embedded the path of the install directory a particular
install produced, so activating a new version meant rewriting every
shim in the shared global bin directory: the commands were removed,
relinked, and only then was the hash link repointed. Every command was
missing from PATH for the duration, even when the install succeeded.

Generate the shims from the group's hash link instead, and repoint that
link before linking rather than after. The link name is a stable cache
key over the group's aliases, so the shim text no longer changes between
versions and both linkers' idempotency checks leave the files untouched;
activating a new install is then the single rename that repoints the
link. Prune the slot of a declared command whose file is missing, which
the removal pass used to cover.

Co-Authored-By: Claude Fable 5 <[email protected]>
@zkochan zkochan changed the title fix(global): preserve installs when publication fails fix(global): switch global installs over atomically Aug 10, 2026
The module publishes nothing: it makes a freshly installed group the
active one. "Publish" already means uploading a package to a registry
in this repo, and the word reached users through the error messages and
the release note.

Rename the modules, symbols, and messages to activation. The two error
codes are unchanged, so the stable contract does not move.

Co-Authored-By: Claude Fable 5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit cefde86

Cleanup aggregates removal failures and carries on, but it then deleted
the group's hash link and installation directory anyway. A bin left
behind by a failed removal is only discoverable through those manifests,
so deleting them stranded it on PATH with nothing left to retry from.

Remove every bin the group still owns, then keep the group when any of
those removals failed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3410313

A committed activation must not fail because its temporary backup
directory could not be removed, but discarding the error hid a real
filesystem problem and let backup directories accumulate under the
global bin directory unnoticed.

Report the failure on the global log channel instead. The TypeScript CLI
warns through globalWarn; the Rust CLI returns the leftover from the
activation so the command handler, which holds the reporter, emits the
same message on pnpm:global.

Co-Authored-By: Claude Fable 5 <[email protected]>
greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 10, 2026
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 078a4d0

Changing a group's packages changes its hash, so its commands are
rewritten to point at the new hash link and the old one is unlinked.
Every cleanup test so far used a group whose hash matched the active
one, leaving that combination untested: a command shared with the group
that just took over must survive the unlinking that removes the old hash
link and installation directory.

Verified both tests fail when the activated-bin guard is removed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@greptile-apps
greptile-apps Bot dismissed their stale review August 11, 2026 00:28

Dismissed because a newer commit was pushed; Greptile will re-review the current head.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit f42423f

@zkochan
zkochan merged commit 5571fa2 into pnpm:main Aug 11, 2026
46 of 48 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants