Skip to content

fix(self-update): discard an installed pnpm that cannot run - #13076

Merged
zkochan merged 7 commits into
mainfrom
self-update-verify
Jul 16, 2026
Merged

zkochan merged 7 commits into
mainfrom
self-update-verify

Conversation

@zkochan

@zkochan zkochan commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Summary

pnpm self-update could not tell a working install from a broken one. Upgrading onto @pnpm/[email protected] printed "Successfully updated pnpm to v11.13.0", exited 0, and left the user with no working pnpm at all — measured against the real registry, before this change:

failure mode self-update reported user's pnpm afterwards
crash mid-install (pnpm → 11.12.0) exit 1, real error 11.11.0, still working
silent bad artifact (@pnpm/exe → 11.13.0) exit 0, "Successfully updated" bricked — This: command not found

The crash case already fails safe: the install happens in a throwaway directory and installPnpmToGlobalDir removes it on throw, all before selfUpdate.ts relinks PNPM_HOME/bin. The second case is the gap — @pnpm/[email protected]'s platform package shipped without a native, setup.js exits 0 when the binary is missing, so the tarball's placeholder bin survived and nothing ever executed the result.

This runs the installed CLI before the caller makes it active. Because the relink is downstream and the existing catch already removes the install dir, a failure keeps the version that was working and needs no restore — verify-then-commit rather than commit-then-revert, so there is no window in which pnpm is broken.

Prior art. This is what the other self-updating toolchains do, and neither goes further:

  • Deno — check_exe() runs the downloaded binary with -V and bail!s ("Failed to validate Deno executable...") before replacing the current one.
  • rustup — get_new_rustup_version() does Command::new(path).arg("--version") on the downloaded binary.
  • npm doctor is prior art for a diagnostic command, but it checks the environment (registry reachability, permissions, cache checksums) and explicitly does no test install.

Only that it runs is asserted, not what it prints. Matching --version output exactly would fail on anything else a release writes to stdout — and this repo's own fixtures show why: selfUpdate.test.ts serves one pnpm-9.1.0.tgz for several mocked versions, so a strict check failed two legitimate downgrade tests.

A deeper "install a dependency and check it landed" test was considered and deliberately placed in the tag gate (#13072) instead: it would have caught no bug we have actually had (11.12.0's own binary runs fine — the fault is in the driver resolving its manifest), while adding a network dependency inside self-update where a registry blip would fail a good upgrade.

Parity

pacquet gets the same check, for native engines — which is the whole set that can install yet fail to execute. The legacy JS engine has no binary of its own to be missing, and running it would mean locating a Node.js first. Same ERR_PNPM_BROKEN_PNPM_INSTALL code and message on both stacks.

Verification

  • TS: 59 pass. The end-to-end test drives the real installPnpm — real tarball fetch, real headless install, real bin linking, real spawn — and asserts both the rejection and that the half-installed directory is removed. Confirmed it catches a regression: with assertPnpmRuns commented out it fails with "Received promise resolved instead of rejected".
  • Rust: 28 pass, including the exact placeholder (This file intentionally left blank) that @pnpm/exe ships when its platform package carries no native.
  • No false failures: two real upgrades against the live registry (11.11.0, then 11.13.0) succeed with the check in place.

This does not stop a broken release from reaching users — it stops one from taking their working pnpm with it. Rejecting it before publication is #13072.

Squash Commit Body

A self-update that installs a working pnpm and one that installs a broken
one were indistinguishable. Installing `@pnpm/[email protected]` printed
"Successfully updated pnpm to v11.13.0", exited 0, and left the user with
no working pnpm at all: its platform package shipped without a native, so
setup.js kept the tarball's placeholder bin, and nothing between the
download and the relink of PNPM_HOME ever executed the result.

Run the installed CLI before the caller makes it active. The install
already happens in a throwaway directory and the relink is downstream, so
failing here keeps the version that was working and removes the directory
rather than needing to restore anything. This is what deno's check_exe and
rustup's self-update do — they run the downloaded binary and refuse to
replace the current one if it does not start.

Only that it runs is asserted, not what it prints: matching --version
output exactly would fail on anything else a release writes to stdout, and
the test fixtures show why — one tarball stands in for several mocked
versions.

pacquet gets the same check for native engines, which is the whole set that
can install yet fail to execute: the legacy JS engine has no binary of its
own to be missing, and running it would mean locating a Node.js first.

A release that installs but cannot run still reaches users; this only stops
it from taking their working pnpm with it. Rejecting it before publication
is pnpm/pnpm#13072.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.
  • Updated the documentation if needed.

Written by an agent (Claude Code, claude-opus-4-8).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes

    • pnpm self-update now verifies the downloaded pnpm executable starts successfully before switching the active version.
    • If execution fails (spawn error, non-zero exit, or signal termination), the broken installation is discarded and the currently active pnpm is kept.
    • Added guards to block known problematic pnpm release versions with clearer, user-facing error codes and guidance.
  • Tests

    • Added coverage for executable run checks, broken-release blocking, error messaging, and cleanup behavior across platforms.

A self-update that installs a working pnpm and one that installs a broken
one were indistinguishable. Installing `@pnpm/[email protected]` printed
"Successfully updated pnpm to v11.13.0", exited 0, and left the user with
no working pnpm at all: its platform package shipped without a native, so
setup.js kept the tarball's placeholder bin, and nothing between the
download and the relink of PNPM_HOME ever executed the result.

Run the installed CLI before the caller makes it active. The install
already happens in a throwaway directory and the relink is downstream, so
failing here keeps the version that was working and removes the directory
rather than needing to restore anything. This is what deno's check_exe and
rustup's self-update do — they run the downloaded binary and refuse to
replace the current one if it does not start.

Only that it runs is asserted, not what it prints: matching --version
output exactly would fail on anything else a release writes to stdout, and
the test fixtures show why — one tarball stands in for several mocked
versions.

pacquet gets the same check for native engines, which is the whole set that
can install yet fail to execute: the legacy JS engine has no binary of its
own to be missing, and running it would mean locating a Node.js first.

A release that installs but cannot run still reaches users; this only stops
it from taking their working pnpm with it. Rejecting it before publication
is #13072.
Copilot AI review requested due to automatic review settings July 16, 2026 10:54

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 16, 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

pnpm self-update now executes newly installed pnpm versions before activation. Broken installations are discarded and reported with structured diagnostics, while Rust and TypeScript tests cover execution failures, release rejection, and cleanup.

Changes

Self-update verification

Layer / File(s) Summary
Rust installation validation
pnpm/crates/cli/src/cli_args/self_update.rs, pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
Rust self-update validates target releases, runs the newly linked executable, and reports structured errors for broken installations.
TypeScript installation verification
pnpm11/engine/pm/commands/src/self-updater/*, pnpm11/engine/pm/commands/src/index.ts
TypeScript self-update rejects known-bad releases, runs pnpm --version before registration, and exports assertPnpmRuns.
Verification tests and release contract
pnpm/crates/cli/src/cli_args/self_update/tests.rs, pnpm/crates/cli/src/cli_args/self_update/install_pnpm/tests.rs, pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts, .changeset/self-update-verify-installed-pnpm.md
Tests cover executable success and failure, exit codes, signals, configuration isolation, release rejection, diagnostics, cleanup, and the documented patch releases.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SelfUpdate as pnpm self-update
  participant InstallDir as New install directory
  participant Pnpm as Installed pnpm
  participant Active as Active pnpm

  SelfUpdate->>InstallDir: install and link target version
  SelfUpdate->>Pnpm: run pnpm --version
  Pnpm-->>SelfUpdate: success or execution failure
  alt executable succeeds
    SelfUpdate->>Active: activate installed version
  else executable fails
    SelfUpdate->>InstallDir: discard failed installation
    SelfUpdate-->>Active: keep current active version
  end
Loading

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

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: self-update now discards pnpm installs that fail to run.
Description check ✅ Passed The description follows the template with Summary, Squash Commit Body, and Checklist, and covers the required implementation and tests.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch self-update-verify

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.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Self-update: verify installed pnpm executable before activation

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Validate the freshly installed pnpm can execute before switching the active global pnpm.
• Discard broken installs with a dedicated error code and actionable user guidance.
• Add regression tests to ensure cleanup and correct error reporting for non-runnable installs.
Diagram

graph TD
  A["pnpm self-update"] --> T[("New install dir")] --> C["Link native binary"] --> D["Validate: run --version"] --> E["Activate (relink PNPM_HOME)"]
  D -->|fails| F["Delete install dir + error"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Heuristic validation (file existence / size / magic-bytes checks)
  • ➕ Avoids executing a potentially broken or untrusted binary during update.
  • ➕ Can be faster than spawning a process.
  • ➖ Brittle across OS/arch formats (ELF/PE/Mach-O) and packaging variants.
  • ➖ Misses real-world failures (codesigning, missing runtime deps, loader errors) that only appear at execution time.
2. Commit-then-rollback (activate new pnpm, then test, then revert on failure)
  • ➕ Validates the exact path users will run after activation.
  • ➖ Introduces a window where pnpm may be broken if activation succeeds but rollback fails.
  • ➖ Adds more state management and restore complexity vs. verify-then-commit.

Recommendation: Keep the PR’s verify-then-commit approach: executing the just-installed CLI before relinking avoids ever leaving users without a working pnpm, while staying robust against packaging faults that look “installed” but cannot start. The alternatives are either too brittle (heuristics) or add failure windows and rollback complexity.

Files changed (7) +253 / -3

Bug fix (4) +101 / -2
self_update.rsAdd BrokenPnpmInstall self-update error with guidance +9/-0

Add BrokenPnpmInstall self-update error with guidance

• Introduces a new 'SelfUpdateError::BrokenPnpmInstall' variant with a stable diagnostic code and a help message explaining the install was discarded and the active pnpm preserved.

pnpm/crates/cli/src/cli_args/self_update.rs

install_pnpm.rsExecute installed native engine before considering install successful +52/-1

Execute installed native engine before considering install successful

• Runs the freshly installed native pnpm ('pnpm(.exe) --version') after linking the platform binary, failing the install if execution fails. Ensures failures remove the temporary install dir so broken installs are not reused on the next run.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs

index.tsExport assertPnpmRuns as a test seam +1/-1

Export assertPnpmRuns as a test seam

• Re-exports the new 'assertPnpmRuns' helper so it can be tested directly from the package entrypoint.

pnpm11/engine/pm/commands/src/index.ts

installPnpm.tsValidate installed pnpm runs before switching PNPM_HOME +39/-0

Validate installed pnpm runs before switching PNPM_HOME

• Adds 'assertPnpmRuns()' and calls it after 'linkBins()' during global install, rejecting installs that cannot execute. Uses 'cross-spawn' and throws a 'PnpmError' with 'BROKEN_PNPM_INSTALL' (mapped to 'ERR_PNPM_BROKEN_PNPM_INSTALL') and a user-facing hint.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts

Tests (2) +145 / -1
tests.rsAdd Rust tests for executable validation failure modes +49/-0

Add Rust tests for executable validation failure modes

• Adds unix-only tests that seed executable files to simulate a runnable engine, a placeholder/non-program file, and a failing executable. Verifies 'assert_pnpm_runs' accepts runnable installs and reports meaningful errors for failures.

pnpm/crates/cli/src/cli_args/self_update/tests.rs

selfUpdate.test.tsAdd JS tests for broken installs and assertPnpmRuns behavior +96/-1

Add JS tests for broken installs and assertPnpmRuns behavior

• Adds a regression test that serves a tarball with no bin to simulate a broken pnpm artifact, asserting installation fails and temporary install dirs are cleaned up. Adds direct unit tests for 'assertPnpmRuns' covering success, non-zero exit, missing binary, and correct error code/hint.

pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts

Documentation (1) +7 / -0
self-update-verify-installed-pnpm.mdDocument self-update executable validation behavior +7/-0

Document self-update executable validation behavior

• Adds a changeset announcing that self-update now verifies the installed pnpm can run before activation. Notes that non-executable releases are discarded with an error instead of replacing a working install.

.changeset/self-update-verify-installed-pnpm.md

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts`:
- Around line 274-276: Update the failure-reason construction in the installPnpm
process handling so a null status, indicating signal termination, produces “a
signal” instead of “it exited with code null”; preserve the existing
error-message and non-null exit-code behavior, and mirror the same user-visible
handling in the corresponding Rust pacquet implementation.
🪄 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: aa2819b6-7c3c-4ad8-954e-595032ede405

📥 Commits

Reviewing files that changed from the base of the PR and between b0456c6 and 03e29ed.

📒 Files selected for processing (7)
  • .changeset/self-update-verify-installed-pnpm.md
  • pnpm/crates/cli/src/cli_args/self_update.rs
  • pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pnpm/crates/cli/src/cli_args/self_update/tests.rs
  • pnpm11/engine/pm/commands/src/index.ts
  • pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts
  • pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     12.3±0.35ms    30.5 MB/sec    1.12     13.8±1.79ms    27.2 MB/sec
packument/parse                1.02     38.1±0.54µs  1741.6 MB/sec    1.00     37.4±0.51µs  1773.1 MB/sec
tarball/download_dependency    1.04      2.6±0.23ms  1665.1 KB/sec    1.00      2.5±0.19ms  1736.0 KB/sec

@greptile-apps

greptile-apps Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — the new guards only run before the global bin is relinked, so a failure leaves the previously-working pnpm untouched. Cleanup on error was already in place; this PR only adds a check before the commit point.

Both stacks receive the same two guards, error codes match, and the verify-before-commit placement means a check failure is strictly non-destructive. One structural difference exists between the TypeScript and Rust implementations (TS runs the spawn check for all package types; Rust gates it on native binaries), but it produces no false failures in practice. Test coverage is thorough on both sides.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts — the unconditional assertPnpmRuns call diverges from the Rust gate on links_native_binary.

Reviews (7): Last reviewed commit: "docs(self-update): cut the prose down to..." | Re-trigger Greptile

@qodo-code-review

qodo-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Windows probe runs wrong shim ✗ Dismissed 🐞 Bug ≡ Correctness
Description
assertPnpmRuns() spawns an explicit binDir/pnpm path, which on Windows can execute the
non-.cmd shim rather than the .cmd wrapper users actually run. This can make pnpm self-update
wrongly reject a valid install on Windows (and discard it) even though pnpm.cmd would execute
successfully.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R289-307]

+ * Spawned through cross-spawn by the bare `pnpm` name the version switcher also
+ * uses, so the `.cmd` shim `linkBins` writes on Windows is resolved rather than
+ * executed as a script. Exported as a test seam: reaching it through an install
+ * would mean publishing a deliberately broken pnpm tarball as a fixture.
+ */
+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  // pnpm reaches `--version` only after loading config, switching versions and
+  // running pnpmfile hooks, so probing from the caller's directory would let an
+  // unrelated project decide the result: a pinned `packageManager` would report
+  // that version instead, and a project's pnpmfile would run. Probe from an
+  // empty directory, where startup finds nothing of the user's to act on.
+  const probeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pnpm-self-update-check-'))
+  let result: SpawnSyncReturns<string>
+  try {
+    result = spawn.sync(pnpmBinPath, ['--version'], {
+      encoding: 'utf8',
+      cwd: probeDir,
+    })
Evidence
The probe explicitly executes binDir/pnpm despite claiming it relies on bare-name resolution to
pick up the Windows .cmd shim; linkBins uses cmdShim which creates .cmd wrappers; and the
same file documents that cmd-shim’s Bash shim behavior on Windows is problematic—supporting that
bypassing .cmd resolution is not safe.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[289-307]
pnpm11/bins/linker/src/index.ts[331-350]
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[523-531]
pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[283-289]

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

## Issue description
`assertPnpmRuns()` claims it verifies the installed CLI via the Windows `.cmd` shim, but it actually spawns `path.join(binDir, 'pnpm')`. On Windows that can execute the non-`.cmd` shim (often a Bash/MSYS shim) instead of the `.cmd` wrapper, causing false failures on hosts without MSYS/Git Bash (or with the cmd-shim Bash wrapper quirks described elsewhere in this file).

## Issue Context
- `linkBins()` creates Windows shims via `cmdShim(...)`, producing a `.cmd` wrapper alongside a non-`.cmd` shim.
- This repository already documents Windows-specific problems with cmd-shim’s Bash shim when targeting `.cmd` wrappers.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[289-327]

## Suggested fix
- On Windows, spawn `pnpm.cmd` (or spawn the bare command name `pnpm` with `PATH` prefixed by `binDir`) so execution matches what users get from PATH resolution.
- Update the comment to match the actual behavior.
- Add/adjust a Windows regression test to ensure the probe uses the `.cmd` path (or PATH resolution) rather than the extensionless shim.

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


2. Version check runs full init ✓ Resolved 🐞 Bug ⛨ Security
Description
assertPnpmRuns() (and the Rust equivalent) validates via pnpm --version, but pnpm prints the
version only after loading config, installing configDependencies, and loading pnpmfile hooks, so the
check can fail due to unrelated repo/user config or network/auth problems rather than an un-runnable
binary. This also expands the side effects and cost of pnpm self-update beyond “can the binary
start”.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R270-273]

+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  const { status, error, stderr } = spawn.sync(pnpmBinPath, ['--version'], { encoding: 'utf8' })
+  if (error == null && status === 0) return
Evidence
The new validation runs pnpm --version. pnpm’s main() reaches the version-printing short-circuit
only after config + configDependencies/hooks processing, and configDependencies install throws by
default, so --version can exit nonzero for environment/config reasons unrelated to binary
executability.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-273]
pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[122-133]
pnpm11/pnpm/src/main.ts[100-176]
pnpm11/pnpm/src/getConfig.ts[45-98]

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 new validation executes `pnpm --version`, which triggers pnpm’s normal startup path (config loading, configDependencies install, pnpmfile/hooks loading) before it reaches the version-printing short-circuit. That means the validation can produce false negatives (rejecting a runnable pnpm) and can cause unexpected side effects (network/config-deps) during self-update.

## Issue Context
In pnpm’s CLI, `--version` is handled only after `getConfig()` and `installConfigDepsAndLoadHooks()` have already run.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-287]
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[122-155]
- pnpm11/pnpm/src/main.ts[100-176]
- pnpm11/pnpm/src/getConfig.ts[45-98]

### Suggested fix sketch
- Execute the validation command with an isolated working directory that cannot pick up repository-controlled config/hook state:
 - **TS:** pass `cwd: installDir` (or a freshly created empty temp dir under the install dir) in `spawn.sync(...)` options.
 - **Rust:** add `.current_dir(install_dir)` (or a fresh empty temp dir) to `Command::new(...).arg("--version")...`.
- (Optional, if available in pnpm) also pass/force settings that avoid pnpmfile/configDependencies for this check; if not available, isolating `cwd` is still a meaningful reduction in repo-controlled side effects.

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


3. Reused install skips validation ✓ Resolved 🐞 Bug ☼ Reliability
Description
Self-update can reuse an already-present pnpm install directory and activate it without running the
new “can it execute” check, so a previously cached broken install can still be linked back into the
global bin. This undermines the PR’s fail-safe intent and can prevent recovery when a broken install
dir already exists on disk.
Code

↗ pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs

    .await
Evidence
Both implementations return early when a matching install dir exists, bypassing the new validation;
then the top-level self-update flow activates that returned directory via linking.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[69-103]
pnpm/crates/cli/src/cli_args/self_update.rs[234-247]
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[197-200]
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[233-240]
pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[246-255]
pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[273-276]

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 new runnable validation (`assert_pnpm_runs` / `assertPnpmRuns`) only runs after a fresh install, but both implementations have an early-return reuse path for an existing install dir. That reuse path can hand a broken install back to the caller, and the caller will activate it.

### Issue Context
This PR’s goal is to prevent “successful” self-updates that leave the user with a non-executable pnpm. That safety property should apply equally to reused installs (especially for users who already have a broken cached install from the earlier faulty release).

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[69-109]
- pnpm/crates/cli/src/cli_args/self_update.rs[234-247]
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[188-240]
- pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[246-276]

### What to change
- **Rust:** In the `already_existed` early-return branch, if `links_native_binary` is true, run `assert_pnpm_runs(existing.install_dir, package_name, version)` before returning. If it fails, remove that install dir and fall through to a fresh install.
- **TS:** In `installPnpmToGlobalDir`, when `existingInstallDir != null`, run `assertPnpmRuns(path.join(existingInstallDir, 'bin'), version)` before returning; on failure, delete the existing dir and continue with a fresh install.
- Ensure failures still leave the current active pnpm untouched (same property as the fresh-install error path).

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



Remediation recommended

4. assertPnpmRuns uses sync FS 📘 Rule violation ➹ Performance ⭐ New
Description
assertPnpmRuns() uses fs.mkdtempSync() and fs.rmSync() from an async self-update flow, which
blocks the Node event loop and can unnecessarily degrade pnpm self-update responsiveness. Prefer
async filesystem APIs and make the validation helper async so the command remains non-blocking.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R288-298]

+  const probeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pnpm-self-update-check-'))
+  let result: SpawnSyncReturns<string>
+  try {
+    result = spawn.sync(pnpmBinPath, ['--version'], {
+      encoding: 'utf8',
+      cwd: probeDir,
+    })
+  } finally {
+    try {
+      fs.rmSync(probeDir, { recursive: true, force: true })
+    } catch {}
Evidence
PR Compliance ID 9 requires preferring async filesystem APIs and avoiding unnecessary blocking
operations. The new code creates and deletes the probe directory using synchronous FS calls in
assertPnpmRuns().

CLAUDE.md: Async/Loop Practices: Use async/await, Async FS, and Parallelize Independent Work Safely
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[288-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
`assertPnpmRuns()` uses synchronous filesystem calls (`fs.mkdtempSync`, `fs.rmSync`) while running inside an async self-update path. This blocks the Node event loop and is against the repo’s async/FS performance practices.

## Issue Context
`installPnpmToGlobalDir()` is async and calls `assertPnpmRuns()` before committing the new installation. Converting `assertPnpmRuns()` to async allows using `fs.promises.mkdtemp` and `fs.promises.rm` for non-blocking temp-dir management.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[288-298]

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


5. Overbroad broken-release gate 🐞 Bug ≡ Correctness
Description
The TypeScript self-update handler calls assertReleaseIsInstallable(targetVersion) unconditionally,
which blocks updating to 11.12.0/11.13.0 even when pnpmPackageNameToInstall() would install the JS
"pnpm" wrapper (which the code comment states can run those versions). This prevents
otherwise-working global-only updates and applies the “shared pin” rationale even when no pin is
being written.
Code

pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[R141-144]

+  // Before the pin below is written, not just before the install: that field is
+  // committed and shared, so pinning a release the running wrapper happens to
+  // survive would still break every teammate whose wrapper does not.
+  assertReleaseIsInstallable(targetVersion)
Evidence
The handler gates every self-update by version before checking whether it will update a project pin,
while installPnpm.ts explicitly documents that the broken releases are specific to @pnpm/exe and
that these versions can still run on the JS pnpm wrapper.

pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[134-166]
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[40-75]

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

### Issue description
`selfUpdate.ts` invokes `assertReleaseIsInstallable(targetVersion)` before determining whether the command will actually write a shared project pin (`packageManager` / `devEngines.packageManager`) vs only performing a global install. Because the denylist is keyed only by version, it blocks JS-wrapper installs of these versions even though the comment explicitly notes these versions do run on JS `pnpm`.

### Issue Context
- The denylist rationale is primarily about preventing a JS-wrapper user from pinning a version that would brick teammates on `@pnpm/exe`.
- For global-only updates (no pin write), blocking JS-wrapper installs is an unnecessary restriction.

### Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/selfUpdate.ts[140-170]
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[40-75]

### Suggested change
- Only call `assertReleaseIsInstallable(targetVersion)` when the handler is about to update the shared pin (i.e., inside the `if (opts.wantedPackageManager?.name === packageManager.name)` branch, before writing to the manifest).
- Optionally, for the global-update branch, keep a safeguard only when the wrapper being installed is `@pnpm/exe` (e.g., when `pnpmPackageNameToInstall(targetVersion)` resolves to `@pnpm/exe` for the running wrapper).

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


6. PnpmError calls missing trailing comma 📘 Rule violation ⚙ Maintainability
Description
New multi-line new PnpmError(...) calls omit the trailing comma after the final object argument,
violating the repo’s TypeScript style requirement for trailing commas. This increases style drift
and can cause lint/format failures depending on the project’s tooling.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R54-63]

+export function assertReleaseIsInstallable (version: string): void {
+  if (!BROKEN_RELEASES.has(version)) return
+  throw new PnpmError(
+    'BROKEN_PNPM_RELEASE',
+    `pnpm v${version} is a broken release and cannot be installed`,
+    {
+      hint: 'Its "@pnpm/exe" build shipped without a binary and does not run. Even where it does run, pinning it would break everyone on the project who uses "@pnpm/exe", because the pin is shared. Choose another version, or run "pnpm self-update latest".',
+    }
+  )
+}
Evidence
PR Compliance ID 9 requires trailing commas in TypeScript. In assertReleaseIsInstallable() and
assertPnpmRuns(), the final argument object passed to new PnpmError(...) is not followed by a
trailing comma before the closing ), despite being a multi-line call.

AGENTS.md: TypeScript Code Style: Trailing Commas, Prefer Functions, Hoisted Function Declarations, Small Parameter Lists
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[54-63]
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[323-329]

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

## Issue description
Multi-line `new PnpmError(...)` calls are missing the trailing comma after the final object argument.

## Issue Context
The repo TypeScript style requires trailing commas for consistency and to avoid formatter/linter churn.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[54-63]
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[323-329]

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


View more (5)
7. assertPnpmRuns swallows rmSync errors 📘 Rule violation ☼ Reliability
Description
assertPnpmRuns() silently ignores failures when removing its temporary probe directory, which can
hide unexpected filesystem problems and leave behind temp directories. This conflicts with the
repo’s error-handling expectations that user-reachable code should not broadly swallow errors
without scoping/handling.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R308-312]

+  } finally {
+    try {
+      fs.rmSync(probeDir, { recursive: true, force: true })
+    } catch {}
+  }
Evidence
PR Compliance ID 10 requires user-reachable errors not be swallowed and catches be scoped to
expected conditions. The added catch {} around fs.rmSync(probeDir, ...) ignores all errors
without filtering or reporting.

CLAUDE.md: Error Handling: Use PnpmError for User-Reachable Errors and Include Context
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[308-312]

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

## Issue description
`assertPnpmRuns()` removes a temp directory in a `finally` block but uses an empty `catch {}` which swallows any removal failure.

## Issue Context
This is user-reachable code in the self-update flow. Silently ignoring cleanup failures can mask real filesystem issues and leave behind temp directories.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[308-312]

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


8. Raw stderr in diagnostics 🐞 Bug ⛨ Security
Description
TypeScript assertPnpmRuns() and Rust assert_pnpm_runs() interpolate raw stderr and OS/error
messages from the spawned pnpm process directly into user-facing errors without escaping or
truncation. Because that output is untrusted and potentially huge or control-character-laden, it can
enable terminal/log spoofing and produce noisy or unbounded diagnostics.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R280-297]

+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  const { status, error, stderr } = spawn.sync(pnpmBinPath, ['--version'], { encoding: 'utf8' })
+  if (error == null && status === 0) return
+  // A signal leaves `status` null, which macOS produces for a binary its
+  // signature check rejects — the exact shape of an incorrectly signed release.
+  const exit = status != null ? `code ${status}` : 'a signal'
+  const reason = error != null
+    ? error.message
+    : `it exited with ${exit}${(stderr ?? '').trim() ? `: ${stderr.trim()}` : ''}`
+  throw new PnpmError(
+    'BROKEN_PNPM_INSTALL',
+    `The pnpm v${version} that was just installed cannot run: ${reason}`,
+    {
+      hint: `The installation at "${pnpmBinPath}" was discarded and the currently active pnpm was left in place, so pnpm still works. A release that installs but cannot run is a packaging fault — please report it at https://github.com/pnpm/pnpm/issues. To move to a different version meanwhile, pass one to "pnpm self-update".`,
+    }
+  )
+}
Evidence
In the TypeScript implementation, the code constructs a reason string from (stderr ?? '').trim()
and/or error.message and embeds it directly into the thrown PnpmError message, with no
intermediate sanitization or size limiting step. In the Rust implementation, the validation captures
output.stderr, formats it into a reason field, and surfaces it via
SelfUpdateError::BrokenPnpmInstall/BrokenPnpmInstall diagnostic shown to the user; similarly,
neither escaping of control characters nor any length cap is applied, so arbitrary child-process
stderr (and OS error strings) flows straight into user-visible output.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[266-297]
pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[121-154]
pnpm/crates/cli/src/cli_args/self_update.rs[82-90]

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

## Issue description
`assertPnpmRuns()` (TypeScript) and `assert_pnpm_runs()` (Rust) embed child-process `stderr` (and related error strings like `error.message` / `err.to_string()`) directly into user-facing errors without sanitization or bounded size. This allows untrusted output to include terminal control sequences or extremely large text, creating terminal/log spoofing risk and excessively large diagnostics.

## Issue Context
The spawned process is the freshly installed pnpm shim/wrapper/binary. In corruption/mispackaging or broken-install scenarios (even if not malicious), its stderr can be arbitrary, including control characters and large volumes of output, and those are currently propagated verbatim into the error message presented to users.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[280-297]
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[121-154]

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


9. Duplicate spawn-exit parsing logic 📘 Rule violation ⚙ Maintainability
Description
assertPnpmRuns() reimplements spawn/exit-status reasoning that already exists elsewhere in the
repo, increasing the risk of divergent behavior and future fixes being applied inconsistently. This
violates the repo guidance to reuse/extract shared utilities instead of duplicating similar logic.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R270-287]

+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  const { status, error, stderr } = spawn.sync(pnpmBinPath, ['--version'], { encoding: 'utf8' })
+  if (error == null && status === 0) return
+  // A signal leaves `status` null, which macOS produces for a binary its
+  // signature check rejects — the exact shape of a mis-signed release.
+  const exit = status != null ? `code ${status}` : 'a signal'
+  const reason = error != null
+    ? error.message
+    : `it exited with ${exit}${(stderr ?? '').trim() ? `: ${stderr.trim()}` : ''}`
+  throw new PnpmError(
+    'BROKEN_PNPM_INSTALL',
+    `The pnpm v${version} that was just installed cannot run: ${reason}`,
+    {
+      hint: `The installation at "${pnpmBinPath}" was discarded and the currently active pnpm was left in place, so pnpm still works. A release that installs but cannot run is a packaging fault — please report it at https://github.com/pnpm/pnpm/issues. To move to a different version meanwhile, pass one to "pnpm self-update".`,
+    }
+  )
+}
Evidence
PR Compliance ID 3 requires avoiding duplicated implementations when similar utilities/patterns
already exist. The newly added assertPnpmRuns() implements its own spawn/exit parsing, while
switchCliVersion.ts already contains a similar absolute-path spawn.sync(...) execution path and
failure handling logic, indicating a duplication opportunity that should be centralized.

CLAUDE.md: Avoid duplication by reusing existing repo utilities and extracting shared code
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-287]
pnpm11/pnpm/src/switchCliVersion.ts[126-155]

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

## Issue description
`assertPnpmRuns()` duplicates existing logic for spawning a pnpm binary by absolute path and interpreting failure modes (missing binary, non-zero exit, signal/no-exit-code). This duplication increases maintenance cost and can cause inconsistent error handling over time.

## Issue Context
Similar spawn/exit handling already exists in `pnpm11/pnpm/src/switchCliVersion.ts`. Prefer reusing a shared helper (or extracting one) so both call sites stay behaviorally aligned.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-287]
- pnpm11/pnpm/src/switchCliVersion.ts[126-155]

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


10. Blocking Command::output() call 📘 Rule violation ➹ Performance
Description
assert_pnpm_runs() executes the newly installed pnpm --version using synchronous
std::process::Command::output() from an async self-update install path, with no timeout. A broken
or malicious binary can hang indefinitely (blocking the async executor thread and preventing
self-update from completing) and, because output() buffers stdout/stderr, can also drive excessive
memory use during validation.
Code

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[R122-145]

+pub(super) fn assert_pnpm_runs(
+    install_dir: &Path,
+    package_name: &str,
+    version: &str,
+) -> miette::Result<()> {
+    let executable = package_dir(install_dir, package_name).join(if host_platform() == "win32" {
+        "pnpm.exe"
+    } else {
+        "pnpm"
+    });
+    let reason = match Command::new(&executable).arg("--version").output() {
+        Err(err) => err.to_string(),
+        Ok(output) if !output.status.success() => {
+            let stderr = String::from_utf8_lossy(&output.stderr);
+            let stderr = stderr.trim();
+            let code = output
+                .status
+                .code()
+                .map_or_else(|| "a signal".to_string(), |code| format!("code {code}"));
+            if stderr.is_empty() {
+                format!("it exited with {code}")
+            } else {
+                format!("it exited with {code}: {stderr}")
+            }
Evidence
PR Compliance ID 10 calls out the need for structured async behavior and to avoid unnecessary
blocking operations, yet the added self-update verification runs a child process via
Command::output() in the install flow. Because output() is a blocking wait with no deadline, the
validation can stall forever if the installed pnpm hangs, and because it collects the child’s full
stdout+stderr into memory, a misbehaving binary can emit unbounded output and amplify resource
impact during the self-update check.

CLAUDE.md: Async and Loops: Prefer async/await and Parallelize Independent Work Safely
pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[122-145]
pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[122-148]

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

## Issue description
`assert_pnpm_runs()` validates the freshly installed `pnpm` by running `pnpm --version` with synchronous `std::process::Command::output()` inside an async self-update install path, without any timeout and with unbounded stdout/stderr buffering. This can block the async executor indefinitely if the binary hangs and can increase memory usage if the process produces excessive output, preventing self-update from remaining fail-fast and resource-bounded.

## Issue Context
This verification step is meant to fail-safe on broken installs, but it introduces an additional failure mode (hang) that is not handled. Even if the user opted into installing that version, the self-update path should remain time-bounded and avoid unnecessary output capture to reduce the blast radius of a broken/malicious (registry-delivered) binary during validation.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[122-155]

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


11. Sync spawn in assertPnpmRuns 📘 Rule violation ➹ Performance
Description
assertPnpmRuns() validates the freshly installed pnpm by calling spawn.sync() without any
timeout, which blocks the Node event loop during pnpm self-update and can hang indefinitely if the
installed binary stalls or is broken/malicious. This introduces avoidable latency and a local
availability/DoS-style non-terminating failure mode in the update flow.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R270-276]

+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  const { status, error, stderr } = spawn.sync(pnpmBinPath, ['--version'], { encoding: 'utf8' })
+  if (error == null && status === 0) return
+  const reason = error != null
+    ? error.message
+    : `it exited with code ${status}${(stderr ?? '').trim() ? `: ${stderr.trim()}` : ''}`
Evidence
PR Compliance ID 10 requires preferring async/await patterns and avoiding unnecessary synchronous
work, yet the new assertPnpmRuns() validation helper runs spawn.sync(...) to execute the
installed pnpm (e.g., --version) and waits for completion while providing no timeout option.
Because the call is synchronous and unbounded, the self-update process can be stalled indefinitely
if the child process never exits, directly demonstrating the blocking behavior and hang risk
described.

CLAUDE.md: Async and Loops: Prefer async/await and Parallelize Independent Work Safely
pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-276]

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

## Issue description
`assertPnpmRuns()` performs validation using `spawn.sync()` (blocking) to run the installed `pnpm --version` and does not apply a timeout, so `pnpm self-update` can freeze indefinitely if the child process stalls or never exits.

## Issue Context
This check runs on the self-update path after installing/linking bins. Even though self-update is not a hot path, repo performance rules discourage unnecessary blocking operations, and this unbounded synchronous spawn introduces avoidable latency plus a local availability/DoS risk; the validation should be fast and bounded even under broken releases.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[270-283]

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



Informational

12. Duplicated broken-release list 🐞 Bug ⚙ Maintainability
Description
The broken-release denylist (11.12.0, 11.13.0) is hard-coded separately in TypeScript and Rust,
which increases future drift risk (one side updated, the other forgotten) and can lead to
inconsistent wrapper behavior later. This is a low-severity maintainability issue today, but it
makes incident response and policy updates more error-prone.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R40-63]

+/**
+ * Versions that must not be installed or pinned by any wrapper. Their
+ * `@pnpm/exe` published its platform packages with no binary, so that wrapper
+ * keeps the placeholder bin from its own tarball and cannot run.
+ *
+ * Keyed by version, not by package, because the pin is shared while the wrapper
+ * is not: `packageManager` / `devEngines.packageManager` is committed, so a
+ * developer on the JS `pnpm` — for which these versions do run — would pin one
+ * and break every teammate who uses `@pnpm/exe`. Both are immutable on npm and
+ * deprecated there, so the version alone settles it.
+ */
+const BROKEN_RELEASES: ReadonlySet<string> = new Set(['11.12.0', '11.13.0'])
+
+/** Throws when `version` is one of the {@link BROKEN_RELEASES}. */
+export function assertReleaseIsInstallable (version: string): void {
+  if (!BROKEN_RELEASES.has(version)) return
+  throw new PnpmError(
+    'BROKEN_PNPM_RELEASE',
+    `pnpm v${version} is a broken release and cannot be installed`,
+    {
+      hint: 'Its "@pnpm/exe" build shipped without a binary and does not run. Even where it does run, pinning it would break everyone on the project who uses "@pnpm/exe", because the pin is shared. Choose another version, or run "pnpm self-update latest".',
+    }
+  )
+}
Evidence
The denylist values are introduced in two different language implementations as independent sources
of truth.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[40-63]
pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[202-216]

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 same broken-release denylist is now duplicated in:
- TS: `BROKEN_RELEASES` in `installPnpm.ts`
- Rust: `matches!(version, ...)` in `install_pnpm.rs`

This creates a future drift risk when updating the list.

### Issue Context
This PR already needs the policy in two implementations; the goal is to reduce the chance they diverge over time.

### Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[40-63]
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[202-216]

### Suggested change
Pick one:
1) Create a small repo-owned data file (e.g. `tools/broken-pnpm-releases.json`) and load it from TS; in Rust, embed it via `include_str!` and parse at startup.
2) If sharing data is too heavy, add a CI/test-time consistency check that asserts both lists are identical (e.g. a script/test that parses the TS list and the Rust list in a lightweight way), plus a comment in both places pointing to the check.

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


13. Unnecessary regex for trimming 📘 Rule violation ⚙ Maintainability
Description
The new test code uses regexes for simple string checks/transformations (e.g., trimming a trailing
slash and checking numeric directory names) where simple string operations would suffice. This adds
avoidable parsing complexity against the repo’s TypeScript parsing guidance.
Code

pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[R1090-1117]

+  getMockAgent().get(registry.replace(/\/$/, ''))
+    .intercept({ path: '/pnpm', method: 'GET' })
+    .reply(200, {
+      name: 'pnpm',
+      'dist-tags': { latest: '9.1.0' },
+      versions: {
+        '9.1.0': {
+          name: 'pnpm',
+          version: '9.1.0',
+          dist: {
+            tarball: `${registry}pnpm/-/pnpm-9.1.0.tgz`,
+            integrity: `sha512-${createHash('sha512').update(tgzWithoutBin).digest('base64')}`,
+          },
+        },
+      },
+      time: {},
+    }).persist()
+  getMockAgent().get(registry.replace(/\/$/, ''))
+    .intercept({ path: '/pnpm/-/pnpm-9.1.0.tgz', method: 'GET' })
+    .reply(200, tgzWithoutBin)
+
+  await expect(installPnpm('9.1.0', opts)).rejects.toThrow(/cannot run/)
+
+  // The half-installed directory must not survive: leaving it behind would let
+  // findGlobalPnpmInstallDir hand the broken install to the next run.
+  const installDirs = fs.existsSync(opts.globalPkgDir)
+    ? fs.readdirSync(opts.globalPkgDir).filter((entry) => /^\d+$/.test(entry))
+    : []
Evidence
PR Compliance ID 12 requires preferring string operations over ad-hoc regex when regex is not
needed. The added test lines use regex for trailing-slash removal and digit-only checks, which are
simple operations that can be implemented without regex.

CLAUDE.md: TypeScript parsing: prefer string operations over custom regex; use existing parser-combinator pattern for structured parsing
pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[1090-1117]

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

## Issue description
New test code introduces regex usage for simple parsing tasks (`registry.replace(/\/$/, '')` and `/^\d+$/`). The repo guideline prefers plain string operations for such simple cases.

## Issue Context
This is not complex structured parsing; it can be expressed more readably with `endsWith('/') ? slice(...) : ...` and numeric checks via `Number(...)` + `Number.isInteger(...)` (or similar).

## Fix Focus Areas
- pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[1090-1117]

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


14. Helper declared before use 📘 Rule violation ⚙ Maintainability
Description
Inside the new describe('assertPnpmRuns') block, the helper linkFakePnpm() is declared before
its first use even though it is a hoisted function declaration. This conflicts with the repo
convention to place function declarations after their usage for readability.
Code

pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[R1457-1470]

+  async function linkFakePnpm (entry: string): Promise<string> {
+    const dir = tempDir(false)
+    const pkgDir = path.join(dir, 'node_modules', 'fake-pnpm')
+    fs.mkdirSync(pkgDir, { recursive: true })
+    fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify({
+      name: 'fake-pnpm',
+      version: '1.0.0',
+      bin: { pnpm: 'entry.js' },
+    }))
+    fs.writeFileSync(path.join(pkgDir, 'entry.js'), `${entry}\n`)
+    const binDir = path.join(dir, 'bin')
+    await linkBins(path.join(dir, 'node_modules'), binDir, { warn: () => {} })
+    return binDir
+  }
Evidence
PR Compliance ID 7 specifies that (when practical) function declarations should appear after the
code that uses them, relying on hoisting. In the new assertPnpmRuns tests, linkFakePnpm() is
declared before the first test that calls it, so the block does not follow the repo’s convention.

CLAUDE.md: TypeScript style: declare functions after they are used (rely on hoisting)
pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[1457-1477]

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

## Issue description
`linkFakePnpm()` is a hoisted function declaration but is placed before the tests that call it, contrary to the repo’s convention of placing function declarations after their first use.

## Issue Context
Within the `describe('assertPnpmRuns')` block, the tests read more top-down if the test cases come first and helper declarations are moved to the bottom.

## Fix Focus Areas
- pnpm11/engine/pm/commands/test/self-updater/selfUpdate.test.ts[1457-1477]

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


View more (1)
15. Misleading shim-resolution comment ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The comment in assertPnpmRuns() claims it spawns by the bare pnpm name to ensure Windows .cmd
shim resolution, but the implementation spawns an explicit path (binDir/pnpm). This mismatch is
likely to confuse future maintainers about the intended Windows execution semantics.
Code

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[R264-272]

+ * Spawned through cross-spawn, and by the same bare `pnpm` name the version
+ * switcher spawns, so that the `.cmd` shim `linkBins` writes on Windows is
+ * resolved rather than executed as a script. Exported as a test seam, since
+ * reaching it through an install would mean publishing a deliberately broken
+ * pnpm tarball as a fixture.
+ */
+export function assertPnpmRuns (binDir: string, version: string): void {
+  const pnpmBinPath = path.join(binDir, 'pnpm')
+  const { status, error, stderr } = spawn.sync(pnpmBinPath, ['--version'], { encoding: 'utf8' })
Evidence
The cited block contains both the statement about spawning by bare name and the actual spawn call
using an explicit path, showing the mismatch directly.

pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[264-273]

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 newly added comment describes behavior (“spawn by bare `pnpm` name so .cmd shim is resolved”) that the code does not implement (it spawns `path.join(binDir, 'pnpm')`).

## Issue Context
Even if the current implementation works on Windows, the comment is inaccurate and increases the risk of a future refactor breaking platform behavior.

## Fix Focus Areas
- pnpm11/engine/pm/commands/src/self-updater/installPnpm.ts[264-273]

### Suggested fix sketch
- Either update the comment to describe the actual behavior (spawning an explicit path and relying on cross-spawn’s resolution), or change the implementation to match the comment (spawn `'pnpm'` with `cwd: binDir` and a controlled `env/PATH`), ensuring tests cover Windows behavior.

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


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.80488% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.54%. Comparing base (b0456c6) to head (53209a1).

Files with missing lines Patch % Lines
...rates/cli/src/cli_args/self_update/install_pnpm.rs 90.00% 4 Missing ⚠️
pnpm/crates/cli/src/cli_args/self_update.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13076      +/-   ##
==========================================
- Coverage   85.54%   85.54%   -0.01%     
==========================================
  Files         499      499              
  Lines       79844    79884      +40     
==========================================
+ Hits        68304    68336      +32     
- Misses      11540    11548       +8     

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

The TypeScript check read the exit code straight into its message, so an
engine killed by a signal — where there is no code — was reported as "it
exited with code null". pacquet already says "a signal" for the same case,
so the two stacks disagreed on a message.

This is not a hypothetical branch: macOS kills a binary whose signature
check rejects it, which is exactly the shape a mis-signed release arrives
in, and one of the shapes this check exists to catch.

Say "a signal", matching pacquet's wording rather than naming it. Node
reports the name (SIGKILL) but Rust only has the number, and reaching parity
on a named signal would need a unix-only cfg plus a number-to-name table.

The new test fails with "it exited with code null" against the previous
code. It is POSIX-only: Windows has no real signals, so a killed process
still reports an exit code there and the branch is unreachable.
Copilot AI review requested due to automatic review settings July 16, 2026 11:05

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6c5eb71

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

The runtime check only guards a fresh install. A slot cached by an earlier
pnpm was handed straight back and relinked into the global bin without ever
running, so the one case the check exists for — an engine already on disk
that cannot execute — could still take out a working installation.

Reject the two releases known to be broken by version instead of spawning
the cached engine to find out. `@pnpm/exe` 11.12.0 and 11.13.0 published
their platform packages with no binary; both are immutable on npm and
deprecated there, and neither ships a working binary on any platform, so the
version alone settles it. The cache-hit path keeps its current cost: a
self-update that is already up to date does not spawn anything.

This is not a second safety net. The runtime check still catches a broken
release whether or not it is listed; the list only spares the ones already
known from having to be discovered at runtime.

The resolver already skips deprecated versions when a range or dist-tag
leaves it a choice, so only an explicit request for one of these reaches
here.
Copilot AI review requested due to automatic review settings July 16, 2026 11:34

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 98f92a5

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@coderabbitai coderabbitai Bot mentioned this pull request Aug 15, 2026
4 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants