Skip to content

feat(pacquet): reconcile an existing node_modules on repeat installs (Stage 1) - #13151

Merged
zkochan merged 10 commits into
mainfrom
stage1-repeat-install-reconciliation
Jul 19, 2026
Merged

zkochan merged 10 commits into
mainfrom
stage1-repeat-install-reconciliation

Conversation

@zkochan

@zkochan zkochan commented Jul 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Stage 1 of #13146: pacquet now reconciles an existing node_modules on repeat installs — the port of the removal half of pnpm's modules-cleaner prune, plus the repair and validation semantics that were blocking 27 test ports.

Engine (new PruneStaleModules pass + fixes it surfaced):

  • Stale direct-dependency links (entry gone from the wanted lockfile) are removed with their bin shims, emitting pnpm:root removed; orphaned snapshots' hoisted aliases are unlinked via the persisted .modules.yaml map so the next hoist pass can claim the slots. The unique orphan-package count feeds one pnpm:stats removed per install (replacing the placeholder in CreateVirtualStore that predated a pruning pipeline). Orphan virtual-store directories stay the modules cache, swept only by the throttled prune_virtual_store pass — same as upstream's pruneVirtualStore gate.
  • pnpm add / pnpm remove now fail with ERR_PNPM_HOIST_PATTERN_DIFF / ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF / ERR_PNPM_VIRTUAL_STORE_DIR_MAX_LENGTH_DIFF against a drifted modules dir instead of silently recreating it; plain installs keep recreating (new installs_only flag = upstream installsOnly/forceNewModules).
  • The frozen no-op short-circuit now probes the tree it would skip (one metadata call per slot and per direct-dep link), so a hand-deleted package falls through to the full frozen path, which repairs it and emits pnpm:_broken_node_modules — pnpm's headless-repair semantics. Under GVS/hoisted linker the probe covers the importer links only.
  • Lockfile::is_empty now inspects all three group maps: upstream's isEmptyLockfile reads specifiers, which its in-memory model populates for every group; pacquet's v9-inline model leaves it empty, so a dev-only install misread as empty and deleted its current lockfile.
  • The fresh install path threads the current lockfile into the hoisted linker, activating its previous-graph orphan diff on add/update flows.

Test ports (all passing; each verified to fail against a deliberately broken implementation before landing):

  • hoist.rs: 16 known_failures stubs promoted to real ports (repeat-install map preservation, remove/rehoist/prune, alias hoisting, pattern-diff errors, workspace frozen replay and per-project update, combined public+private patterns).
  • hoisted_node_linker.rs: all 6 manifest-mutation stubs promoted.
  • New repeat_install.rs: headless repair, no-inner-lockfile repeat, outer/inner lockfile divergence, non-prod-then-all include growth, dirty-tree reuse with a wiped store.
  • TEST_PORTING.md checkboxes updated (24 entries ticked); the two peer-hoist stubs now carry their real blocker (a registry-mock fixture gap, not partial install).

Parity note: Rust-only — every behavior here already exists in the TypeScript CLI; the changeset targets pacquet only.

Remaining Stage-1 items (follow-ups, tracked in #13146): install --force stubs (#13142) and per-edge engineStrict (#13143); direct-dep bin precedence and extendNodePath stubs; the two --filter stubs (Stage 2 dependency); misc.ts npm-created-node_modules rewrite and the packageImportMethod=copy corrupted-state repair; the peer-hoist fixture pair.

Squash Commit Body

Port the removal half of pnpm's modules-cleaner prune as
PruneStaleModules, wired into the frozen and fresh install paths before
linking: stale direct-dep links and their bin shims are removed with
pnpm:root removed events, orphaned snapshots' hoisted aliases are
unlinked via the persisted .modules.yaml map, and the orphan-package
count feeds a single pnpm:stats removed emission per install. Orphan
virtual-store directories remain the modules cache (throttled
prune_virtual_store sweep), matching upstream's pruneVirtualStore gate.

Parity fixes surfaced by the port: add/remove now fail with the
validateModules *_DIFF errors instead of silently recreating a drifted
modules dir (new installs_only flag mirrors upstream installsOnly);
the frozen no-op short-circuit probes the tree it would skip so a
hand-deleted package is repaired with pnpm:_broken_node_modules;
Lockfile::is_empty inspects all three dependency groups so dev-only
installs stop deleting their current lockfile; the fresh path threads
the current lockfile into the hoisted linker, activating its orphan
diff on add/update flows.

Promote 22 known_failures stubs to real passing ports (16 in hoist.rs,
6 in hoisted_node_linker.rs), add the repeat_install.rs suite porting
the existing-node_modules scenarios, tick 24 TEST_PORTING.md entries,
and correct the peer-hoist stubs' blocker to the registry-mock fixture
gap. Every promoted port was verified to fail against a deliberately
broken implementation before landing.

Related to: pnpm/pnpm#13146 (Stage 1), pnpm/pacquet#299, pnpm/pacquet#433

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust pnpm/ port, or the description notes what still needs porting. — Rust-only: every behavior already exists in the TypeScript CLI (this is the pacquet side catching up).
  • Added a changeset (pnpm changeset) if this PR changes any published package.
  • Added or updated tests.
  • Updated the documentation if needed. — pnpm/plans/TEST_PORTING.md checkboxes.

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


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

    • Repeat installs now reconcile existing node_modules more reliably, removing stale direct links and hoisted aliases and repairing missing packages.
    • Frozen installs detect incomplete/changed on-disk trees and lockfile mismatches more accurately, preventing skipped work.
    • pnpm add / pnpm remove now surface clearer errors when hoist or virtual-store settings drift unexpectedly.
  • Improvements

    • Hoisted dependency updates, alias handling, and workspace installs are more consistent, including safer handling of orphaned packages and hoisted links.
    • Dev-only installs preserve the internal lockfile while keeping production deps excluded.
  • Documentation

    • Updated guidance for repeat installs and repeated node_modules reconciliation behavior.

Copilot AI review requested due to automatic review settings July 19, 2026 17:24

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 19, 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

Repeat installs now reconcile existing node_modules trees, detect persisted layout drift, preserve valid materialized packages, and explicitly configure install modes across command paths. Rust coverage expands for hoisting, frozen installs, lockfile divergence, and fresh hoisted-linker behavior.

Changes

Repeat-install reconciliation

Layer / File(s) Summary
Install contract and layout validation
pnpm/crates/package-manager/src/install.rs, pnpm/crates/lockfile/src/lib.rs, pnpm/crates/package-manager/src/{lib.rs,install_frozen_lockfile.rs,install_with_fresh_lockfile.rs}
Adds installs_only, layout-drift errors, normalized settings checks, stronger frozen-tree validation, and propagation of prior hoist state into materialization.
Stale-module reconciliation
pnpm/crates/package-manager/src/prune_stale_modules.rs, pnpm/crates/package-manager/src/{prune_direct_deps.rs,link_hoisted_modules.rs}, pnpm/crates/package-manager/src/*/tests.rs
Removes stale direct links, bin shims, orphan hoist aliases, and confined hoisted directories while emitting removal statistics.
Install-mode command wiring
pnpm/crates/cli/src/cli_args/*, pnpm/crates/package-manager/src/{add.rs,remove.rs,update.rs}, pnpm/crates/napi/src/install.rs, pnpr/crates/pnpr/src/resolver/resolve.rs
Explicitly selects install-only or mutation behavior across CLI, package-manager, N-API, and resolver install requests.
Integration coverage
pnpm/crates/cli/tests/{repeat_install.rs,hoist.rs,hoisted_node_linker.rs}, pnpm/crates/package-manager/src/install/tests.rs, pnpm/plans/TEST_PORTING.md
Adds and activates tests for repeat-install recovery, hoisting, lockfile divergence, store reuse, and fresh-path reconciliation; updates shared test helpers and porting records.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related issues

Possibly related PRs

Suggested labels: product: pacquet, product: pnpr

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch stage1-repeat-install-reconciliation

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

pacquet: reconcile existing node_modules on repeat installs (Stage 1)

✨ Enhancement 🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Adds PruneStaleModules to prune stale direct-dep links/bin shims and orphan hoist aliases.
• Enforces pnpm validateModules: add/remove fail on layout drift via installs_only.
• Probes frozen no-op tree; missing entries fall through to repair and emit broken-modules.
• Fixes dev-only installs deleting current lockfile by correcting Lockfile::is_empty.
• Promotes many known_failures to real E2E tests and adds repeat_install suite.
Diagram

graph TD
    A["Install pipeline"] --> B["Fresh/Frozen install paths"] --> C["PruneStaleModules"] --> D["unlink direct deps"]
    C --> E["unlink orphan hoists"] --> F[".modules.yaml map"]
    B --> G["frozen_tree_intact probe"] --> H["Full frozen repair"]
    B --> I["settings diff check"] --> J["ERR_PNPM_*_DIFF"]
    C --> K[("node_modules")]
    subgraph Legend
      direction LR
      _mod["Module"] ~~~ _file["File"] ~~~ _disk[("On disk")]
    end
Loading
High-Level Assessment

The approach intentionally mirrors upstream pnpm behavior (modules-cleaner prune removal + validateModules semantics) to maintain CLI compatibility (event names, stats semantics, error codes). Alternatives like always recreating node_modules or deferring all cleanup to virtual-store pruning would either regress incremental reuse or leave stale links/bins/hoist slots behind; Stage 1’s scoped, pre-link reconciliation is the right incremental step.

Files changed (28) +1665 / -271

Enhancement (19) +505 / -8
dedupe.rsMark dedupe as installs-only +1/-0

Mark dedupe as installs-only

• Sets 'installs_only: true' when building InstallOptions for 'dedupe', aligning it with plain-install semantics.

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

deploy.rsMark deploy as installs-only +1/-0

Mark deploy as installs-only

• Sets 'installs_only: true' for deploy-driven installs so drifted modules dirs may be recreated like 'install'.

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

fetch.rsMark fetch as installs-only +1/-0

Mark fetch as installs-only

• Sets 'installs_only: true' for fetch execution paths.

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

import.rsMark import as installs-only +1/-0

Mark import as installs-only

• Sets 'installs_only: true' for import execution paths.

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

install.rsMark install/pnpr-internal installs as installs-only +3/-0

Mark install/pnpr-internal installs as installs-only

• Threads 'installs_only: true' through the main 'install' args and pnpr-inner install call sites.

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

link.rsMark link as not installs-only +1/-0

Mark link as not installs-only

• Sets 'installs_only: false' for 'link', enabling validateModules drift errors instead of recreation.

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

prune.rsMark prune as installs-only +1/-0

Mark prune as installs-only

• Sets 'installs_only: true' for 'prune' command’s install invocation.

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

rebuild.rsMark rebuild as installs-only +1/-0

Mark rebuild as installs-only

• Sets 'installs_only: true' for rebuild’s install invocation.

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

unlink.rsMark unlink as not installs-only +1/-0

Mark unlink as not installs-only

• Sets 'installs_only: false' for 'unlink', matching non-plain mutation semantics.

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

install.rsMark NAPI install as installs-only +1/-0

Mark NAPI install as installs-only

• Threads 'installs_only: true' into the N-API install entry point’s InstallOptions.

pnpm/crates/napi/src/install.rs

add.rsMark add as not installs-only +2/-0

Mark add as not installs-only

• Sets 'installs_only: false' for add flows so layout drift surfaces 'ERR_PNPM_*_DIFF' errors rather than recreating node_modules.

pnpm/crates/package-manager/src/add.rs

install.rsCore install plumbing: installs_only, validateModules diffs, frozen probe, and orphan pruning context +163/-3

Core install plumbing: installs_only, validateModules diffs, frozen probe, and orphan pruning context

• Adds 'installs_only' to Install options, introduces 'ERR_PNPM_HOIST_PATTERN_DIFF'/'ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF'/'ERR_PNPM_VIRTUAL_STORE_DIR_MAX_LENGTH_DIFF' errors, gates non-plain mutations with settings-diff checks, adds 'frozen_tree_intact' probe to ensure fast-path correctness, and threads prior hoistedDependencies/current lockfile/prune-orphans flags into fresh and frozen install runs (with filtered-install safety).

pnpm/crates/package-manager/src/install.rs

install_frozen_lockfile.rsRun PruneStaleModules before linking on frozen installs and emit removed stats +43/-1

Run PruneStaleModules before linking on frozen installs and emit removed stats

• Adds prior-hoisted-dependencies and prune-orphans inputs, runs pre-link reconciliation for non-hoisted linker when a current lockfile exists, and emits 'pnpm:stats removed' with the computed orphan count.

pnpm/crates/package-manager/src/install_frozen_lockfile.rs

install_with_fresh_lockfile.rsRun PruneStaleModules before linking on fresh installs and thread current lockfile into hoisted linker +48/-4

Run PruneStaleModules before linking on fresh installs and thread current lockfile into hoisted linker

• Adds current-lockfile and prior-hoisted-dependencies inputs, runs pre-link reconciliation for non-hoisted linker, emits 'pnpm:stats removed', and passes the current lockfile to the hoisted linker to activate previous-graph orphan diffs.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs

lib.rsExport prune_stale_modules module +2/-0

Export prune_stale_modules module

• Registers and re-exports the new 'prune_stale_modules' pass from the package-manager crate.

pnpm/crates/package-manager/src/lib.rs

prune_stale_modules.rsImplement PruneStaleModules reconciliation pass +230/-0

Implement PruneStaleModules reconciliation pass

• New module implementing Stage 1 repeat-install reconciliation: removes stale direct-dep links (with pnpm:root removed events) and unlinks orphaned hoist aliases based on prior '.modules.yaml' hoistedDependencies, returning a unique orphan-package count for stats while leaving virtual-store directories to the modules-cache prune pass.

pnpm/crates/package-manager/src/prune_stale_modules.rs

remove.rsMark remove as not installs-only +2/-0

Mark remove as not installs-only

• Sets 'installs_only: false' for remove flows so drifted layout settings become typed 'ERR_PNPM_*_DIFF' errors.

pnpm/crates/package-manager/src/remove.rs

update.rsMark update as installs-only +2/-0

Mark update as installs-only

• Sets 'installs_only: true' for update flows, matching plain-install semantics.

pnpm/crates/package-manager/src/update.rs

resolve.rsMark pnpr resolver installs as installs-only +1/-0

Mark pnpr resolver installs as installs-only

• Threads 'installs_only: true' into pnpr resolver’s install invocation used for lockfile-only resolution.

pnpr/crates/pnpr/src/resolver/resolve.rs

Bug fix (1) +10 / -5
lib.rsFix empty-lockfile detection across dependency groups +10/-5

Fix empty-lockfile detection across dependency groups

• Updates 'Lockfile::is_empty' to consider devDependencies and optionalDependencies (in addition to specifiers/dependencies), preventing dev-only installs from being misdetected as empty and deleting the current lockfile.

pnpm/crates/lockfile/src/lib.rs

Refactor (2) +9 / -11
create_virtual_store.rsRemove placeholder stats removed emission +3/-8

Remove placeholder stats removed emission

• Deletes the hardcoded 'pnpm:stats removed: 0' placeholder since removed counts now come from PruneStaleModules results.

pnpm/crates/package-manager/src/create_virtual_store.rs

prune_direct_deps.rsExpose pruning helpers for reuse by PruneStaleModules +6/-3

Expose pruning helpers for reuse by PruneStaleModules

• Makes 'confined_modules_dir', 'selected_groups', and 'remove_direct_dep_link' pub(crate) so the new reconciliation pass can reuse existing safe deletion logic.

pnpm/crates/package-manager/src/prune_direct_deps.rs

Tests (4) +1103 / -214
hoist.rsConvert hoist known_failures into real E2E repeat-install/hoist tests +548/-158

Convert hoist known_failures into real E2E repeat-install/hoist tests

• Adds helpers to re-run the CLI in a workspace and read .modules.yaml hoistedDependencies, then ports many hoist scenarios to real tests: repeat-install map preservation, orphan hoist removal, rehoist on remove/prune, alias hoisting, workspace replay, and pattern drift error assertions.

pnpm/crates/cli/tests/hoist.rs

hoisted_node_linker.rsConvert hoisted-node-linker known_failures into real E2E tests +202/-45

Convert hoisted-node-linker known_failures into real E2E tests

• Ports update/add mutation behaviors to real tests under 'nodeLinker: hoisted', including overwriting packages, replacing squatting paths, preserving nested conflict copies, workspace member updates, alias/no-alias consistency, and self-peer lockfile semantics.

pnpm/crates/cli/tests/hoisted_node_linker.rs

repeat_install.rsAdd repeat-install E2E suite for repair/reuse/divergence cases +246/-0

Add repeat-install E2E suite for repair/reuse/divergence cases

• Introduces a new Unix-only test suite that installs twice with on-disk drift/damage, covering frozen repair emission ('pnpm:_broken_node_modules'), missing inner lockfile tolerance, outer/inner lockfile divergence updates, dev-only then full install include expansion, and dirty-node_modules reuse with a wiped store.

pnpm/crates/cli/tests/repeat_install.rs

tests.rsUpdate package-manager install tests for installs_only + frozen probe behavior +107/-11

Update package-manager install tests for installs_only + frozen probe behavior

• Adds 'installs_only: true' to many test InstallOptions and adjusts a frozen-short-circuit test to seed a marker file that proves the link pass was skipped only when the probe succeeds.

pnpm/crates/package-manager/src/install/tests.rs

Documentation (2) +38 / -33
reconcile-existing-node-modules-on-repeat-install.mdAdd changeset for repeat-install reconciliation +5/-0

Add changeset for repeat-install reconciliation

• Adds a minor changeset documenting repeat-install node_modules reconciliation, broken-modules repair detection, validateModules-style *_DIFF errors for add/remove, and the dev-only lockfile preservation fix.

.changeset/reconcile-existing-node-modules-on-repeat-install.md

TEST_PORTING.mdUpdate test-porting checklist after promoting stubs +33/-33

Update test-porting checklist after promoting stubs

• Marks multiple previously-stubbed TypeScript-suite ports as completed and updates notes to reference the new/real Rust test coverage.

pnpm/plans/TEST_PORTING.md

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.05     11.5±0.10ms    32.7 MB/sec    1.00     11.0±0.03ms    34.2 MB/sec
packument/parse                1.07     38.8±0.09µs  1708.8 MB/sec    1.00     36.3±0.09µs  1826.9 MB/sec
tarball/download_dependency    1.00      2.2±0.06ms  1948.9 KB/sec    1.01      2.3±0.05ms  1924.4 KB/sec

@greptile-apps

greptile-apps Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

This PR is safe to merge. The new pruning pass is conservative and self-healing — over-removal of a still-wanted entry is immediately corrected by the link pass that follows, and remove_direct_dep_link is idempotent on missing symlinks.

The Lockfile::is_empty fix correctly adds dev and optional dependency maps to the emptiness check, preventing dev-only installs from deleting their current lockfile. The PruneStaleModules logic is sound: the name+version comparison correctly identifies stale links, the confined_modules_dir guard prevents workspace escapes, and the idempotent removal function handles double-removal from PruneStaleModules and prune_direct_deps_excluded_by_groups gracefully. The frozen_tree_intact probe is correctly guarded by the same let Some(modules) = modules_manifest extraction that surrounds it. All installs_only sites (add, remove, update, install, napi) are set correctly per upstream validateModules semantics.

No files require special attention.

Reviews (5): Last reviewed commit: "fix(pacquet): fail the frozen tree probe..." | Re-trigger Greptile

Comment thread pnpm/crates/cli/tests/hoist.rs Resolved
@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Slot probe follows symlinks ✗ Dismissed 🐞 Bug ⛨ Security
Description
In frozen_tree_intact, the virtual-store slot probe uses dir.is_dir(), which follows
symlinks/junctions, so a preexisting symlinked package directory can satisfy the probe and let the
frozen no-op short-circuit reuse a tampered tree. This weakens the new “tree is intact” gate for
repeat frozen installs by not distinguishing real package dirs from indirections.
Code

pnpm/crates/package-manager/src/install.rs[R2588-2594]

+            let slot_node_modules = layout.slot_dir(key).join("node_modules");
+            match crate::safe_join_modules_dir::safe_join_modules_dir(
+                &slot_node_modules,
+                &key.name.to_string(),
+            ) {
+                Ok(dir) => dir.is_dir(),
+                Err(_) => false,
Evidence
The slot probe uses dir.is_dir() (follows symlinks) when checking virtual-store package dirs,
while other safety-sensitive code explicitly distinguishes real dirs from symlink/junction
indirections via symlink_metadata + read_symlink_dir. This mismatch means the probe can accept
an indirection that other parts of the installer would treat as unsafe to traverse/delete through.

pnpm/crates/package-manager/src/install.rs[2575-2595]
pnpm/crates/package-manager/src/prune_direct_deps.rs[181-189]

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

### Issue description
`frozen_tree_intact()` currently treats a symlink/junction at the expected slot `.../node_modules/<name>` path as “present” via `Path::is_dir()`, which follows links. That allows a preexisting tampered virtual-store layout to pass the probe and triggers the frozen no-op short-circuit.

### Issue Context
Pacquet already treats symlink/junction indirection as unsafe in removal paths (e.g. `is_real_dir()`), but the new frozen-tree completeness probe does not apply the same invariant to slot directories.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[2575-2599]
- pnpm/crates/package-manager/src/prune_direct_deps.rs[181-189]

### Suggested fix
- Replace `Ok(dir) => dir.is_dir()` with a symlink-aware check that requires a **real** directory at the slot path.
 - On Unix: `symlink_metadata(&dir)` and require `file_type().is_dir()` and `!file_type().is_symlink()`.
 - On Windows: also reject junctions/reparse points (e.g., attempt `pacquet_fs::read_symlink_dir(&dir)`; if it succeeds, treat as not intact).
- If the directory fails this check, return `false` so the install falls through to the full frozen path (repair/rematerialize).

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


2. allow_known_failure! bypasses tests ✗ Dismissed 📘 Rule violation ☼ Reliability
Description
The PR keeps tests passing by stubbing them out via allow_known_failure! instead of making them
pass (e.g., missing fixtures). This violates the requirement to not skip/dismiss failing tests
without fixing them.
Code

pnpm/crates/cli/tests/hoist.rs[R1299-1307]

    #[test]
    fn should_hoist_correctly_peer_dependencies() {
-        allow_known_failure!(partial_install_persists_hoisted_map());
+        allow_known_failure!(peer_variant_fixtures_missing());
    }

    #[test]
    fn should_uninstall_correctly_peer_dependencies() {
-        allow_known_failure!(partial_install_persists_hoisted_map());
-    }
-
-    /// Workspace install followed by frozen reinstall. Pacquet's
-    /// per-importer hoist walk lands the basic shape — covered by
-    /// [`super::workspace_hoist_walks_every_importer`] — but the
-    /// upstream test additionally re-installs and asserts
-    /// preservation, which needs partial install ([#433]).
-    ///
-    /// [#433]: https://github.com/pnpm/pacquet/issues/433
-    #[test]
-    fn workspace_hoist_all_to_virtual_store_node_modules() {
-        allow_known_failure!(partial_install_persists_hoisted_map());
-    }
-
-    /// Mutates the workspace package's `package.json` mid-test and
-    /// re-installs — needs `pnpm add`-equivalent manifest mutation.
-    #[test]
-    fn workspace_hoist_when_updating_one_project() {
-        allow_known_failure!(manifest_mutation_via_pnpm_add());
-    }
-
-    /// Removes `node_modules` and re-installs from the lockfile —
-    /// needs partial-install state for the rehoist comparison.
-    #[test]
-    fn should_recreate_node_modules_with_hoisting() {
-        allow_known_failure!(partial_install_persists_hoisted_map());
+        allow_known_failure!(peer_variant_fixtures_missing());
    }
Evidence
PR Compliance ID 2 requires investigating and fixing failures rather than skipping them. The tests
shown are explicitly routed through allow_known_failure!, which exits early instead of asserting
real behavior.

CLAUDE.md, AGENTS.md: Do not ignore or dismiss failing tests
pnpm/crates/cli/tests/hoist.rs[1296-1307]

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

## Issue description
Tests are being intentionally short-circuited with `allow_known_failure!`, which effectively skips failing coverage instead of fixing it.

## Issue Context
These test cases currently exit early due to missing fixtures, but the compliance checklist requires failing/affected tests to be fixed rather than bypassed.

## Fix Focus Areas
- pnpm/crates/cli/tests/hoist.rs[1299-1307]

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


3. Dangling link passes probe ✓ Resolved 🐞 Bug ☼ Reliability
Description
frozen_tree_intact uses std::fs::symlink_metadata to validate importer direct-dependency links,
which returns OK even for dangling symlinks/junctions, so the frozen no-op short-circuit can
incorrectly succeed while node_modules is broken. This is most impactful under hoisted linker or
global virtual store where the function explicitly skips probing virtual-store slot directories and
relies only on these link checks.
Code

pnpm/crates/package-manager/src/install.rs[R2619-2620]

+            match crate::safe_join_modules_dir::safe_join_modules_dir(&modules_dir, name) {
+                Ok(link) => std::fs::symlink_metadata(link).is_ok(),
Evidence
The new probe explicitly claims to detect missing entries and—when slot probing is disabled—“probe
only the importer links”, but the implementation uses symlink_metadata, which only validates that
the link itself exists, not that its target exists. Direct dependencies are represented as
symlinks/junctions in the isolated layout (the pruning code treats the presence of a direct dep
entry as read_symlink_dir(&link) succeeding), so a hand-deleted target can leave a dangling link
that still passes symlink_metadata and incorrectly allows the frozen early return.

pnpm/crates/package-manager/src/install.rs[2553-2626]
pnpm/crates/package-manager/src/prune_direct_deps.rs[219-230]

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 frozen no-op guard `frozen_tree_intact()` currently checks direct-dependency links with `std::fs::symlink_metadata(link).is_ok()`. `symlink_metadata` only verifies the directory entry exists (lstat) and will succeed for a dangling symlink/junction, so the install can short-circuit as up-to-date while the dependency target is missing.

This breaks the intended “headless repair” behavior described in the function docs, especially in modes where slot probing is skipped (hoisted linker / global virtual store).

### Issue Context
In `frozen_tree_intact()`, slot probing is disabled under hoisted linker and when `enable_global_virtual_store` is on; in those cases the code relies on the importer-link probe to detect broken trees.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[2553-2626]

### Suggested change
Replace the `symlink_metadata` existence check with a target-following check (and ideally ensure the target is a directory):
- Use `std::fs::metadata(&link)` (follows symlinks/junctions) and require it to succeed (and/or `is_dir()`), so dangling links fail the probe.
- Keep the existing behavior for malformed aliases (`Err(_) => true`) to avoid probing unsafe paths, but ensure a present link whose target is missing returns `false` so the install falls through to the full frozen repair path.

Optionally, if you specifically want to ensure the entry is a symlink/junction *and* the target exists, combine `read_symlink_dir(&link).is_ok()` with `std::fs::metadata(&link).is_ok_and(|m| m.is_dir())`.

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


View more (3)
4. Junction orphan delete 🐞 Bug ⛨ Security
Description
install_with_fresh_lockfile now passes current_lockfile into the hoisted linker, enabling
prev_graph orphan removal on fresh (non-frozen) runs; orphan removal uses
std::fs::remove_dir_all without rejecting junctions/reparse points. On Windows this can follow a
malicious junction inside node_modules and recursively delete outside the workspace.
Code

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[R2132-2136]

                crate::install_frozen_lockfile::HoistedLinkerInputs {
                    config,
                    lockfile: materialization_lockfile,
-                    // No previous-install `<virtual_store_dir>/lock.yaml`
-                    // is threaded into the fresh path yet, so the
-                    // walker runs without an orphan diff.
-                    current_lockfile: None,
+                    current_lockfile,
                    layout: &layout,
Evidence
The fresh-lockfile hoisted path now passes current_lockfile, which enables prev_graph and
therefore orphan removal. The orphan-removal implementation deletes via fs::remove_dir_all with no
junction/symlink guard, while other pruning code explicitly avoids deleting through junctioned
components on Windows.

pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[2131-2148]
pnpm/crates/package-manager/src/link_hoisted_modules.rs[149-175]
pnpm/crates/package-manager/src/prune_direct_deps.rs[181-189]

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

### Issue description
Fresh installs now thread `current_lockfile` into the hoisted linker, which enables the orphan-removal pass (`prev_graph` diff) on more code paths. That orphan-removal currently deletes with `std::fs::remove_dir_all` and does not guard against Windows junctions/reparse points; unlike other pruning code, it can therefore traverse outside the intended tree.

### Issue Context
- The directories being removed are graph-derived and ultimately influenced by lockfile state + on-disk `node_modules`.
- The repo already treats junction traversal as dangerous in other prune/delete code, so this should match that safety bar.

### Fix Focus Areas
- Add a safe deletion helper that (a) detects symlink/junction/reparse points and removes the link itself (or skips), and (b) avoids recursive traversal through redirected directories.
- Consider confining/removing only when the target is within the expected modules/virtual-store root.
- Add a Windows-focused regression test that creates a junction under the orphan path and verifies pacquet does not delete the junction target.

- pnpm/crates/package-manager/src/link_hoisted_modules.rs[149-175]
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[2131-2148]

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


5. Changeset missing @pnpm/napi and @pnpm/pnpr ✗ Dismissed 📘 Rule violation ⚙ Maintainability
Description
The added changeset bumps only pacquet, but this PR also changes code used by the @pnpm/napi and
@pnpm/pnpr packages. Without adding those package entries to the changeset, the release/versioning
record for the modified Rust artifacts will be incomplete.
Code

.changeset/reconcile-existing-node-modules-on-repeat-install.md[R1-3]

+---
+"pacquet": minor
+---
Evidence
PR Compliance ID 11 requires that changes affecting published/released packages are covered by a
changeset and that Rust changesets target the correct package names. The new changeset includes only
pacquet, while this PR also modifies pnpm/crates/napi (for @pnpm/napi) and pnpr/crates/pnpr
(for @pnpm/pnpr).

CLAUDE.md: Published-package changes must include a changeset; include pnpm explicitly when the TypeScript CLI is affected; follow Rust changeset targeting rules
.changeset/reconcile-existing-node-modules-on-repeat-install.md[1-3]
pnpm/crates/napi/src/install.rs[353-376]
pnpr/crates/pnpr/src/resolver/resolve.rs[183-214]
pnpm/npm/napi/package.json[1-6]
pnpr/npm/pnpr/package.json[1-6]

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 changeset only bumps `pacquet`, but this PR also changes code that ships via `@pnpm/napi` and `@pnpm/pnpr`, so the changeset should include those packages too.

## Issue Context
This PR modifies Rust code under `pnpm/crates/napi` and `pnpr/crates/pnpr`, which correspond to the `@pnpm/napi` and `@pnpm/pnpr` packages. The current changeset frontmatter only lists `pacquet`.

## Fix Focus Areas
- .changeset/reconcile-existing-node-modules-on-repeat-install.md[1-3]

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


6. Unsafe snapshot name join ✓ Resolved 🐞 Bug ⛨ Security
Description
frozen_tree_intact constructs a probe path with
layout.slot_dir(key)...join(key.name.to_string()) without validating that the lockfile-controlled
package name is a safe npm alias, so a crafted lockfile name containing .. or path separators can
escape the intended slot/node_modules/ subtree during the probe. Because the frozen fast path
calls verify_lockfile_eagerly (which returns early when verifiers is empty), this probe can run
(and potentially allow the no-op short-circuit) without the lockfile dependency-name structural gate
running at all.
Code

pnpm/crates/package-manager/src/install.rs[R2546-2553]

+        let layout = crate::VirtualStoreLayout::legacy(
+            config.virtual_store_dir.clone(),
+            config.virtual_store_dir_max_length as usize,
+        );
+        let all_slots_present = snapshots.keys().all(|key| {
+            skipped.contains(key)
+                || layout.slot_dir(key).join("node_modules").join(key.name.to_string()).is_dir()
+        });
Evidence
The probe uses key.name.to_string() as a path component without safety validation.
PkgName::parse does not enforce npm package-name restrictions, while the lockfile verification
layer explicitly exists to reject unsafe names; however, the fast-path verifier helper returns early
when there are no resolution verifiers, so this structural validation may not run on the no-op path.

pnpm/crates/package-manager/src/install.rs[2542-2556]
pnpm/crates/package-manager/src/install.rs[1493-1529]
pnpm/crates/package-manager/src/install.rs[56-76]
pnpm/crates/lockfile/src/pkg_name.rs[7-49]
pnpm/crates/lockfile-verification/src/verify_lockfile_resolutions.rs[65-76]

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

### Issue description
`frozen_tree_intact` builds filesystem paths from `PkgName` strings (`key.name.to_string()`) and probes them with `is_dir()`. `PkgName` parsing is permissive and does not enforce npm’s package-name safety rules, so lockfile-controlled names can contain traversal components or extra separators. This is a security footgun because it performs filesystem metadata access on attacker-controlled paths, and it also risks incorrectly qualifying the frozen no-op fast path.

Additionally, the fast-path verifier helper `verify_lockfile_eagerly` returns early when `verifiers.is_empty()`, which skips `verify_lockfile_dependency_names` (the structural “invalid dependency name” gate) even though that gate is intended to be offline and always-on.

### Issue Context
- The probe is new and runs on a warm path where attacker-controlled lockfile/current-lockfile/module state can exist.
- The repository’s security rules explicitly call out path traversal and untrusted lockfile input.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[56-76]
- pnpm/crates/package-manager/src/install.rs[1493-1529]
- pnpm/crates/package-manager/src/install.rs[2535-2557]

### Suggested fix
1. Make the probe path-safe:
  - When probing snapshot slots, validate `key.name` using the same rule used for `node_modules/<alias>` paths (e.g. `is_valid_old_npm_package_name` / `is_valid_dependency_alias`) and return `false` if invalid.
  - Prefer using `safe_join_modules_dir(slot_node_modules_dir, &name)` (or an equivalent helper) instead of raw `.join(name_string)`.
2. Ensure the always-on structural lockfile gate runs on the no-op path:
  - Either remove the `if verifiers.is_empty() { return Ok(()) }` early return in `verify_lockfile_eagerly`, or
  - Split out and always run `verify_lockfile_dependency_names(lockfile)` before the early return.

This keeps the probe from touching unintended paths and ensures malformed lockfiles can’t silently pass the frozen no-op path.

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



Remediation recommended

7. Duplicate version_of() manifest parsing 📘 Rule violation ⚙ Maintainability ⭐ New
Description
New tests duplicate package.json reading/parsing via bespoke version_of() helpers instead of
reusing the existing _utils::read_manifest() utility. This increases maintenance burden and risks
inconsistent JSON parsing/IO behavior across tests if the manifest helpers evolve.
Code

pnpm/crates/cli/tests/hoist.rs[R734-739]

+/// `version` field of the `package.json` under `dir`.
+fn version_of(dir: &Path) -> String {
+    let text = fs::read_to_string(dir.join("package.json")).expect("read package.json");
+    let manifest: serde_json::Value = serde_json::from_str(&text).expect("parse package.json");
+    manifest["version"].as_str().expect("version is a string").to_string()
+}
Evidence
The compliance rule requires reusing existing repo utilities instead of introducing parallel
implementations. hoist.rs and repeat_install.rs add new version_of helpers that replicate
reading/parsing package.json, while _utils/mod.rs already contains read_manifest() for this
purpose.

CLAUDE.md: Avoid duplication by reusing existing repo utilities and extracting shared code
pnpm/crates/cli/tests/hoist.rs[734-739]
pnpm/crates/cli/tests/repeat_install.rs[18-24]
pnpm/crates/cli/tests/_utils/mod.rs[301-307]

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

## Issue description
Two new test-local helpers (`version_of`) manually read and parse `package.json`, duplicating logic that already exists in the shared test utilities.

## Issue Context
`pnpm/crates/cli/tests/_utils/mod.rs` already provides `read_manifest(project: &Path) -> serde_json::Value`, which can be used to read `package.json` and then extract `manifest["version"]`.

## Fix Focus Areas
- pnpm/crates/cli/tests/hoist.rs[725-739]
- pnpm/crates/cli/tests/repeat_install.rs[18-24]
- pnpm/crates/cli/tests/_utils/mod.rs[301-307]

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


8. Orphan warning log spam 🐞 Bug ➹ Performance ⭐ New
Description
link_hoisted_modules::remove_orphans() emits tracing::warn! once per orphan directory that fails
the confinement check, which can generate large log volume and extra formatting/I/O cost on a repeat
install with malformed/tampered prior state. This is newly more reachable in the fresh install path
because the hoisted linker now receives current_lockfile and therefore computes
prev_graph/orphans from existing on-disk state.
Code

pnpm/crates/package-manager/src/link_hoisted_modules.rs[R172-181]

+        .filter(|dir| {
+            let confined = dir.starts_with(confine_root)
+                && dir.components().all(|part| !matches!(part, std::path::Component::ParentDir));
+            if !confined {
+                tracing::warn!(
+                    ?dir,
+                    ?confine_root,
+                    "refusing to remove an orphan directory outside the install root",
+                );
+            }
Evidence
The PR adds per-directory tracing::warn! inside the confinement filter, so the number of warnings
scales with the number of unconfined orphan dirs. The fresh install path now passes
current_lockfile into run_hoisted_linker, making orphan processing depend on existing on-disk
state. Hoisted graph construction derives importer-root paths from lockfile importer IDs
(workspace:<importer_id>) and joins them into paths, and validate_importer_id explicitly
documents that absolute/.. importer keys are hostile—making it plausible for malformed prior state
to produce many unconfined paths and therefore many warnings.

pnpm/crates/package-manager/src/link_hoisted_modules.rs[163-184]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[2131-2143]
pnpm/crates/real-hoist/src/lib.rs[300-317]
pnpm/crates/package-manager/src/hoisted_dep_graph.rs[556-574]
pnpm/crates/package-manager/src/symlink_direct_dependencies.rs[264-277]

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

### Issue description
`remove_orphans()` logs one warning per unconfined orphan directory. With a large number of such entries this can flood logs and add avoidable overhead.

### Issue Context
This warning is emitted inside the orphan-directory filter. The fresh install path now threads `current_lockfile` into the hoisted linker, enabling `prev_graph` orphan evaluation against pre-existing (potentially corrupted) `node_modules` state.

### Fix Focus Areas
- pnpm/crates/package-manager/src/link_hoisted_modules.rs[169-184]

### Suggested fix
- Aggregate and cap warnings:
 - Count unconfined orphans and emit **one** summary warning (e.g., `unconfined_orphans_count`), optionally including a small sample (first 1–5 dirs).
 - Or downgrade per-path logs to `debug` and keep a single `warn` summary.
- Keep the behavioral contract (skip deletion) unchanged; only adjust logging volume.

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


9. Unbounded manifest read on prune 🐞 Bug ⛨ Security
Description
The new PruneStaleModules pass removes stale direct-dependency links via
remove_direct_dep_link(), which reads <link>/package.json with fs::read (no size/type cap) to
compute bin shims to delete. On repeat installs against a preexisting/attacker-modified
node_modules, an oversized or non-regular package.json at the symlink target can cause excessive
memory usage or fail the install during reconciliation.
Code

pnpm/crates/package-manager/src/prune_stale_modules.rs[R104-114]

+            let wanted_specs = direct_deps_of(wanted_snapshot, included_groups);
+            let prefix = importer_dir.display().to_string();
+            for (alias, current_spec, group) in direct_deps_of(current_snapshot, &RECORDED_GROUPS) {
+                if wanted_specs
+                    .iter()
+                    .any(|(name, spec, _)| *name == alias && spec.version == current_spec.version)
+                {
+                    continue;
+                }
+                remove_direct_dep_link(&modules_dir, &alias.to_string())?;
+                Reporter::emit(&LogEvent::Root(RootLog {
Evidence
The new reconciliation pass calls remove_direct_dep_link() for each stale direct dependency, and
remove_direct_dep_link() invokes remove_dep_bins(), which reads the entire package.json into
memory via fs::read before parsing it. This creates a repeat-install path where an unexpectedly
large or problematic manifest file can cause excessive allocation or abort the install.

pnpm/crates/package-manager/src/prune_stale_modules.rs[89-125]
pnpm/crates/package-manager/src/prune_direct_deps.rs[205-246]

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

### Issue description
`PruneStaleModules` widens when we execute stale-link cleanup, and that cleanup reads `package.json` via `fs::read()` to remove bin shims. This is an unbounded read of a path reached through a symlink/junction, which can lead to local resource exhaustion (very large file) or install failure (I/O errors) during reconciliation.

### Issue Context
This runs on repeat installs when `<virtual_store_dir>/lock.yaml` exists. In repos/CI where `node_modules` can be pre-populated or modified between runs, this makes install robustness depend on reading an untrusted `package.json`.

### Fix Focus Areas
- pnpm/crates/package-manager/src/prune_stale_modules.rs[89-125]
- pnpm/crates/package-manager/src/prune_direct_deps.rs[205-246]

### Suggested fix
- In `remove_dep_bins()` (or a new helper used by stale-link pruning), add a cheap guard before `fs::read`:
 - `symlink_metadata(manifest_path)`; require `file_type().is_file()` and size <= a sane cap (e.g. 1–2 MiB).
 - If not a regular file / too large / metadata fails: skip bin removal (best-effort) rather than erroring.
- Consider making `ReadManifest` non-fatal for stale-link cleanup (still remove the direct-dep link; bins can be left behind and will be overwritten/cleaned on subsequent relink), to avoid turning a malformed on-disk tree into an install-stopper.

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


View more (8)
10. Duplicate .modules.yaml parsing helper 📘 Rule violation ⚙ Maintainability
Description
The new hoisted_dependencies() helper manually reads/parses node_modules/.modules.yaml instead
of reusing the existing read_modules_manifest-based test utilities. This introduces parallel
parsing logic and increases maintenance risk if the on-disk format or loader behavior changes.
Code

pnpm/crates/cli/tests/hoist.rs[R725-732]

+/// The `hoistedDependencies` map from `node_modules/.modules.yaml`.
+fn hoisted_dependencies(workspace: &Path) -> serde_json::Value {
+    let text = fs::read_to_string(workspace.join("node_modules/.modules.yaml"))
+        .expect("read .modules.yaml");
+    let manifest: serde_json::Value =
+        serde_json::from_str(&text).expect(".modules.yaml holds JSON content");
+    manifest["hoistedDependencies"].clone()
+}
Evidence
PR Compliance ID 3 requires reusing/extracting shared utilities instead of adding parallel
implementations. The PR adds a bespoke .modules.yaml reader in hoist.rs even though _utils
already provides a canonical modules() helper built on read_modules_manifest.

CLAUDE.md, AGENTS.md: Avoid duplicating logic: search for existing utilities and extract shared code when needed
pnpm/crates/cli/tests/hoist.rs[725-732]
pnpm/crates/cli/tests/_utils/mod.rs[226-231]

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 new helper reimplements `.modules.yaml` loading/parsing in the test, duplicating existing utilities.

## Issue Context
The test suite already has a shared helper that reads `.modules.yaml` via `pacquet_modules_yaml::read_modules_manifest`.

## Fix Focus Areas
- pnpm/crates/cli/tests/hoist.rs[725-732]
- pnpm/crates/cli/tests/_utils/mod.rs[226-231]

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


11. Historical comment in known_failures 📘 Rule violation ⚙ Maintainability
Description
A new known_failures module doc comment uses refactor-history framing ("formerly stubbed here")
instead of documenting the current contract/invariant and rationale, which violates the
comment-quality requirement. This introduces churn-prone history narration that the checklist
explicitly disallows.
Code

pnpm/crates/cli/tests/hoisted_node_linker.rs[R768-771]

+    //! early rather than masking a real bug. The `pnpm add` / update
+    //! manifest-mutation cases formerly stubbed here are real tests in
+    //! the parent module since the prune-stale-modules reconciliation
+    //! landed.
Evidence
PR Compliance ID 6 forbids comments that narrate refactor history (e.g., phrasing like
"previously/used to"). The newly added known_failures documentation comment explicitly states that
cases were "formerly stubbed here," which is precisely the kind of historical/refactor narration the
rule prohibits rather than a statement of the current contract or rationale.

CLAUDE.md, AGENTS.md: Comments must not restate code; document contracts and non-obvious rationale only
pnpm/crates/cli/tests/hoisted_node_linker.rs[768-771]
pnpm/crates/cli/tests/hoist.rs[1262-1264]

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 `known_failures` module documentation includes refactor-history narration ("formerly stubbed here"). Update the comment to focus on the current contract/invariant and rationale, and remove wording that describes where code/tests used to live.

## Issue Context
This is a new/modified doc comment within the hoisted node linker/hoist test suite.

## Fix Focus Areas
- pnpm/crates/cli/tests/hoisted_node_linker.rs[768-771]
- pnpm/crates/cli/tests/hoist.rs[1262-1264]

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


12. Quadratic stale-dep diff 🐞 Bug ➹ Performance
Description
PruneStaleModules::run builds a Vec of wanted direct deps, then for each current direct dep does
a linear iter().any(...) scan to find a match, making the diff O(n*m) per importer. This adds
avoidable CPU overhead to repeat installs, especially in workspaces/importers with large
direct-dependency sets.
Code

pnpm/crates/package-manager/src/prune_stale_modules.rs[R104-121]

+            let wanted_specs = direct_deps_of(wanted_snapshot, included_groups);
+            let prefix = importer_dir.display().to_string();
+            for (alias, current_spec, group) in direct_deps_of(current_snapshot, &RECORDED_GROUPS) {
+                if wanted_specs
+                    .iter()
+                    .any(|(name, spec, _)| *name == alias && spec.version == current_spec.version)
+                {
+                    continue;
+                }
+                remove_direct_dep_link(&modules_dir, &alias.to_string())?;
+                Reporter::emit(&LogEvent::Root(RootLog {
+                    level: LogLevel::Debug,
+                    message: RootMessage::Removed {
+                        prefix: prefix.clone(),
+                        removed: RemovedRoot {
+                            name: alias.to_string(),
+                            version: removed_version(current_spec),
+                            dependency_type: Some(dependency_type(group)),
Evidence
The new reconciliation loop constructs wanted_specs as a Vec and then performs a full scan of
that vector for each current dep to decide whether to prune, which is the classic O(n*m) pattern.

pnpm/crates/package-manager/src/prune_stale_modules.rs[104-125]
pnpm/crates/package-manager/src/prune_stale_modules.rs[187-210]

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

### Issue description
`PruneStaleModules` compares each current direct dep against a `Vec` of wanted direct deps using `iter().any(...)`, resulting in O(n*m) behavior.

### Issue Context
This reconciliation runs before linking on repeat installs, so it sits on a hot-ish path for large workspaces.

### Fix Focus Areas
- Build a `HashSet`/`HashMap` keyed by the exact match semantics used today (alias + `spec.version`) for `wanted_specs`.
- Use constant-time membership checks inside the current-deps loop.
- Avoid extra allocations where possible (e.g., avoid `alias.to_string()` unless removal is needed).

- pnpm/crates/package-manager/src/prune_stale_modules.rs[89-125]
- pnpm/crates/package-manager/src/prune_stale_modules.rs[187-210]

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


13. Redundant root canonicalize 🐞 Bug ➹ Performance
Description
PruneStaleModules calls confined_modules_dir per importer, and confined_modules_dir
canonicalizes workspace_root every time. On workspaces with many importers this adds redundant
filesystem syscalls to the repeat-install reconciliation pass.
Code

pnpm/crates/package-manager/src/prune_stale_modules.rs[R99-103]

+            let importer_dir = importer_root_dir(workspace_root, importer_id);
+            let modules_dir = importer_dir.join(modules_dir_name);
+            let Some(modules_dir) = confined_modules_dir(&modules_dir, workspace_root) else {
+                continue;
+            };
Evidence
PruneStaleModules invokes confined_modules_dir in its per-importer loop, and the helper
canonicalizes workspace_root for every call instead of reusing a single canonical root for the
whole run.

pnpm/crates/package-manager/src/prune_stale_modules.rs[89-103]
pnpm/crates/package-manager/src/prune_direct_deps.rs[161-170]

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

### Issue description
`confined_modules_dir()` canonicalizes both `modules_dir` and `workspace_root`. In `PruneStaleModules`, this is called once per importer, so the same `workspace_root` is canonicalized repeatedly.

### Issue Context
This reconciliation runs on repeat installs and can iterate many importers in large workspaces.

### Fix Focus Areas
- Canonicalize `workspace_root` once in `PruneStaleModules::run` and pass the canonical root into a new helper (e.g. `confined_modules_dir_with_root(modules_dir, &root_canon)`).
- Keep existing safety semantics (skip when canonicalization fails / escapes root).

- pnpm/crates/package-manager/src/prune_stale_modules.rs[89-103]
- pnpm/crates/package-manager/src/prune_direct_deps.rs[161-170]

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


14. Eager .modules.yaml parse 🐞 Bug ➹ Performance
Description
install.rs now calls read_modules_manifest() (full .modules.yaml parse) before the frozen
no-op short-circuit, so even warm up-to-date installs pay YAML parse/allocation cost. This defeats
the intent of the lightweight ModulesLayout fast-path and can add avoidable CPU+memory overhead to
a hot path.
Code

pnpm/crates/package-manager/src/install.rs[R1311-1327]

+        let previous_modules_metadata = if !resolve_only && !read_failed {
+            match pacquet_modules_yaml::read_modules_manifest::<Host>(&config.modules_dir) {
+                Ok(modules) => modules,
+                // A filtered install merges the unselected importers'
+                // entries out of this file, so it cannot proceed
+                // without it; an unfiltered install only loses the
+                // orphan hoist-link cleanup.
+                Err(error) if filtered_install => return Err(InstallError::ReadModules(error)),
+                Err(error) => {
+                    tracing::warn!(
+                        target: "pacquet::install",
+                        ?error,
+                        "failed to fully parse .modules.yaml; skipping orphan hoist-link cleanup",
+                    );
+                    None
+                }
+            }
Evidence
The install flow reads the lightweight layout first, but then parses the full manifest (including
hoist maps) before the later up-to-date early return, so the early-return path still incurs the full
parse. The modules-yaml crate explicitly documents ModulesLayout as avoiding large map
deserialization to prevent massive allocations, which this change undermines on warm installs.

pnpm/crates/package-manager/src/install.rs[1286-1336]
pnpm/crates/package-manager/src/install.rs[1493-1582]
pnpm/crates/modules-yaml/src/lib.rs[214-217]

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

### Issue description
`Install` eagerly parses the full `node_modules/.modules.yaml` (via `read_modules_manifest`) even when the install later exits via the frozen/up-to-date no-op short-circuit. This forces parsing/allocating potentially large `hoisted_dependencies`/`hoisted_locations` maps on every warm no-op install.

### Issue Context
The repo already has a `read_modules_layout()` API specifically to avoid deserializing large maps on the fast path. The current code reads the lightweight layout and *then* unconditionally attempts the full manifest parse for all non-`resolve_only` installs.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[1286-1336]
- pnpm/crates/package-manager/src/install.rs[1493-1582]

### Expected fix shape
- Defer `read_modules_manifest::<Host>(...)` until after it’s known the install will not short-circuit (or until reconciliation actually needs `hoisted_dependencies`).
- Keep the existing behavior for **filtered installs** (they still need the full manifest for merge correctness), but avoid full parsing on unfiltered no-op installs.
- Consider a cheap predicate (e.g., only load full manifest when `current_lockfile.is_some()` and either lockfiles differ / pruning will run / hoist cleanup is needed).

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


15. Skipped hoist orphan cleanup 🐞 Bug ⛨ Security
Description
On unfiltered installs, a full .modules.yaml parse failure is treated as non-fatal and sets
prior_hoisted_dependencies to None, which causes PruneStaleModules to skip orphan hoist-link
cleanup. This can leave stale hoisted aliases for lockfile-removed packages still reachable under
node_modules, potentially preserving removed/vulnerable code.
Code

pnpm/crates/package-manager/src/install.rs[R1314-1326]

+                // A filtered install merges the unselected importers'
+                // entries out of this file, so it cannot proceed
+                // without it; an unfiltered install only loses the
+                // orphan hoist-link cleanup.
+                Err(error) if filtered_install => return Err(InstallError::ReadModules(error)),
+                Err(error) => {
+                    tracing::warn!(
+                        target: "pacquet::install",
+                        ?error,
+                        "failed to fully parse .modules.yaml; skipping orphan hoist-link cleanup",
+                    );
+                    None
+                }
Evidence
The install code explicitly downgrades full .modules.yaml parse errors to a warning on unfiltered
installs and drops previous_modules_metadata, which makes prior_hoisted_dependencies None.
PruneStaleModules documents that hoist cleanup is skipped without this map and returns early in
that case, so orphan hoist links are not removed.

pnpm/crates/package-manager/src/install.rs[1311-1333]
pnpm/crates/package-manager/src/prune_stale_modules.rs[50-53]
pnpm/crates/package-manager/src/prune_stale_modules.rs[161-163]

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

### Issue description
If `node_modules/.modules.yaml` can be parsed as `ModulesLayout` but fails to fully deserialize as `Modules`, the install continues (unfiltered) and explicitly skips orphan hoist-link cleanup by setting `prior_hoisted_dependencies=None`. That allows stale hoisted aliases (from the previous install) to persist even after the wanted lockfile removes the owning snapshot.

### Issue Context
`PruneStaleModules` can only unlink orphan hoist aliases using `hoistedDependencies` from the prior `.modules.yaml`. When it’s absent, the code returns early without removing any hoist links.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[1311-1333]
- pnpm/crates/package-manager/src/prune_stale_modules.rs[50-53]
- pnpm/crates/package-manager/src/prune_stale_modules.rs[161-163]

### Expected fix shape
Choose a fail-safe behavior that preserves reconciliation guarantees:
- Option A (simplest/strict): Treat full-manifest parse failure as `node_modules` inconsistency for **unfiltered** installs too (trigger recreate/purge rather than proceeding with partial state).
- Option B: If full parse fails but layout is readable, run a conservative cleanup strategy that does not rely on `hoistedDependencies` (e.g., targeted hoist-dir scan limited to safe, confined locations) and then continue.
- Whichever option you choose, ensure the resulting tree cannot retain lockfile-removed hoisted aliases silently.

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


16. Duplicated prune+stats block 📘 Rule violation ⚙ Maintainability
Description
The pre-link PruneStaleModules reconciliation + pnpm:stats removed emission logic (and its
rationale comment) is duplicated across the frozen and fresh install paths, increasing maintenance
burden and risk of the two paths diverging over time.
Code

pnpm/crates/package-manager/src/install_frozen_lockfile.rs[R1095-1125]

+        // Reconcile before linking: stale direct-dep links and
+        // orphaned hoist links must vacate their slots so the relink +
+        // rehoist below can claim them. The hoisted linker is excluded
+        // — its previous-graph diff removes orphans and emits the
+        // `pnpm:stats` `removed` event itself (see
+        // [`crate::link_hoisted_modules()`]); on the isolated linker
+        // the event fires here, so every install carries exactly one,
+        // pairing the `added` emitted in `CreateVirtualStore`.
+        if !is_hoisted {
+            let removed_count = match current_lockfile {
+                Some(current) => crate::PruneStaleModules {
+                    config,
+                    workspace_root,
+                    wanted_lockfile: lockfile,
+                    current_lockfile: current,
+                    prior_hoisted_dependencies,
+                    included_groups: &dependency_groups,
+                    prune_orphans,
+                }
+                .run::<Reporter>()
+                .map_err(InstallFrozenLockfileError::PruneStaleModules)?,
+                None => 0,
+            };
+            Reporter::emit(&LogEvent::Stats(StatsLog {
+                level: LogLevel::Debug,
+                message: StatsMessage::Removed {
+                    prefix: requester.to_owned(),
+                    removed: removed_count,
+                },
+            }));
+        }
Evidence
PR Compliance ID 2 requires avoiding duplication by reusing/extracting shared logic, and PR
Compliance ID 3 requires documenting shared rationale once instead of duplicating it across peers.
The exact same reconciliation+stats block and accompanying rationale comment appear in both install
flows at the cited locations.

CLAUDE.md: Avoid duplication by reusing existing repo utilities and selecting dependencies at the appropriate package level
CLAUDE.md: Comments must document non-obvious rationale or contracts (not restate code or record history)
pnpm/crates/package-manager/src/install_frozen_lockfile.rs[1095-1125]
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[2084-2114]

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 `PruneStaleModules` reconciliation and `pnpm:stats removed` emission (plus the explanatory rationale comment) are duplicated in both frozen and fresh install paths.

## Issue Context
Duplicated logic/comments make it easy for behavior or documentation to drift between `InstallFrozenLockfile` and `InstallWithFreshLockfile`.

## Fix Focus Areas
- pnpm/crates/package-manager/src/install_frozen_lockfile.rs[1095-1125]
- pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs[2084-2114]

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


17. Frozen probe syscall cost 🐞 Bug ➹ Performance
Description
The new frozen no-op gate now performs filesystem metadata checks proportional to the number of
snapshot keys (slot probes) plus direct dependency links (symlink metadata probes), which can be
thousands of syscalls on common warm installs for 2k–3k package trees. This is an intentional
correctness feature, but it should be benchmarked/validated as acceptable for the frozen warm path
per the repo’s performance rules.
Code

pnpm/crates/package-manager/src/install.rs[R2535-2583]

+fn frozen_tree_intact(
+    wanted: &Lockfile,
+    modules: &pacquet_modules_yaml::ModulesLayout,
+    config: &Config,
+    workspace_root: &Path,
+    node_linker: NodeLinker,
+) -> bool {
+    let skipped = crate::SkippedSnapshots::from_strings(&modules.skipped);
+    let probe_slots =
+        !matches!(node_linker, NodeLinker::Hoisted) && !config.enable_global_virtual_store;
+    if probe_slots && let Some(snapshots) = wanted.snapshots.as_ref() {
+        let layout = crate::VirtualStoreLayout::legacy(
+            config.virtual_store_dir.clone(),
+            config.virtual_store_dir_max_length as usize,
+        );
+        let all_slots_present = snapshots.keys().all(|key| {
+            skipped.contains(key)
+                || layout.slot_dir(key).join("node_modules").join(key.name.to_string()).is_dir()
+        });
+        if !all_slots_present {
+            return false;
+        }
+    }
+    let groups = crate::prune_direct_deps::selected_groups(modules.included);
+    let modules_dir_name: &std::ffi::OsStr =
+        config.modules_dir.file_name().unwrap_or_else(|| std::ffi::OsStr::new("node_modules"));
+    wanted.importers.iter().all(|(importer_id, snapshot)| {
+        if crate::symlink_direct_dependencies::validate_importer_id(importer_id).is_err() {
+            return true;
+        }
+        let modules_dir =
+            crate::symlink_direct_dependencies::importer_root_dir(workspace_root, importer_id)
+                .join(modules_dir_name);
+        crate::symlink_direct_dependencies::direct_dep_names_for_importer(
+            snapshot,
+            groups.iter().copied(),
+            &skipped,
+            false,
+        )
+        .iter()
+        .all(|name| {
+            match crate::safe_join_modules_dir::safe_join_modules_dir(&modules_dir, name) {
+                Ok(link) => std::fs::symlink_metadata(link).is_ok(),
+                // A malformed alias never probes the disk; the full
+                // path rejects it with its own typed error.
+                Err(_) => true,
+            }
+        })
+    })
Evidence
The implementation explicitly iterates snapshot keys and direct dependency names, performing
filesystem metadata checks in each iteration. The repo performance guide calls out avoiding
thousands of filesystem ops on common install paths unless measured/justified.

pnpm/crates/package-manager/src/install.rs[2535-2583]
REVIEW_GUIDE.md[115-133]

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

### Issue description
`frozen_tree_intact` adds per-snapshot `is_dir()` probes and per-direct-dependency `symlink_metadata()` probes on the frozen no-op short-circuit. On large workspaces this changes the warm frozen path from “mostly constant work” to O(number of snapshots + number of direct links) filesystem syscalls.

This may be acceptable (and may match upstream behavior), but per REVIEW_GUIDE.md performance rules this kind of change should be measured, and obvious avoidable overhead (allocations in loops) should be minimized.

### Issue Context
The probe is on a hot path: repeat `--frozen-lockfile` installs where users expect the no-op path to be extremely fast.

### Fix Focus Areas
- pnpm/crates/package-manager/src/install.rs[2535-2583]
- REVIEW_GUIDE.md[115-133]

### Suggested fix
1. Add a benchmark (or at least a micro-benchmark/profiling note) for warm frozen no-op installs on representative lockfile sizes (e.g., 500 / 2k / 5k snapshots) to quantify the overhead.
2. Consider low-risk micro-opts that preserve semantics:
  - Avoid repeated `key.name.to_string()` allocations in the snapshot loop by constructing the final package-dir path from `PkgName` components (scope/bare) without allocating a full formatted string per key.
  - If feasible, avoid allocating intermediate `PathBuf`s per iteration (reuse buffers or factor common prefixes).

Keep semantics intact (must still detect hand-deleted packages), but ensure the added cost is understood and minimized.

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


Grey Divider

Qodo Logo

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 05da049

Warning

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

CategorySuggestion                                                                                                                                    Impact
Security
Reject malformed lockfile paths

Return false when validating invalid importer IDs or malformed aliases. This
ensures the program correctly falls through to the full execution path, where
these structural errors are properly rejected.

pnpm/crates/package-manager/src/install.rs [2605-2628]

         if crate::symlink_direct_dependencies::validate_importer_id(importer_id).is_err() {
-            return true;
+            return false;
         }
 ...
-                Err(_) => true,
+                Err(_) => false,

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 10

__

Why: Returning true for malformed aliases incorrectly keeps the execution in the fast path, completely bypassing the full materialization path where the typed rejection errors are actually generated.

High
Prevent symlink-based arbitrary deletion

Replace the lexical path containment check with filesystem-aware validation
(like canonicalization) to prevent symlink traversal attacks during directory
deletion.

pnpm/crates/package-manager/src/link_hoisted_modules.rs [169-187]

+let confine_root = std::fs::canonicalize(confine_root).ok();
 let orphan_dirs: Vec<&PathBuf> = prev
     .keys()
     .filter(|dir| !graph.contains_key(*dir))
     .filter(|dir| {
-        let confined = dir.starts_with(confine_root)
-            && dir.components().all(|part| !matches!(part, std::path::Component::ParentDir));
+        let confined = confine_root.as_ref().is_some_and(|root| {
+            dir.parent()
+                .and_then(|parent| std::fs::canonicalize(parent).ok())
+                .is_some_and(|parent| parent.starts_with(root))
+        });
         if !confined {
             tracing::warn!(
                 ?dir,
                 ?confine_root,
                 "refusing to remove an orphan directory outside the install root",
             );
         }
         confined
     })
     .collect();
 orphan_dirs.par_iter().for_each(|dir| {
     let _ = try_remove_dir(dir);
 });

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion addresses a valid security risk where a malicious symlink could bypass the lexical confinement check, potentially allowing arbitrary directory deletion outside the intended root.

Medium
Possible issue
Detect invalid dependency entries

Require dependencies to resolve to directories by checking metadata.is_dir().
This prevents regular files from mistakenly passing as valid installed packages
and improperly triggering the fast path.

pnpm/crates/package-manager/src/install.rs [2625]

-                Ok(link) => std::fs::metadata(link).is_ok(),
+                Ok(link) => std::fs::metadata(link).is_ok_and(|metadata| metadata.is_dir()),

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: Checking only for existence allows corrupted files or squatters to trigger the up-to-date fast path, whereas requiring a directory ensures the dependencies are structurally correct.

Medium
  • Update

Previous suggestions

Suggestions up to commit c98800f
CategorySuggestion                                                                                                                                    Impact
Security
Reject malformed lockfile paths

Return false instead of true for invalid importer IDs and malformed dependency
aliases.

pnpm/crates/package-manager/src/install.rs [2605-2626]

     if crate::symlink_direct_dependencies::validate_importer_id(importer_id).is_err() {
-        return true;
+        return false;
     }
 ...
-            Err(_) => true,
+            Err(_) => false,
Suggestion importance[1-10]: 8

__

Why: Returning false ensures invalid importer IDs and malformed paths do not incorrectly bypass the full validation path, preventing potential silent failures.

Medium
Canonically confine recursive deletion

Use std::fs::canonicalize to verify that the target directory to be removed
resides within the confine_root safely.

pnpm/crates/package-manager/src/link_hoisted_modules.rs [173-188]

+let canonical_root = std::fs::canonicalize(confine_root).ok();
 let orphan_dirs: Vec<&PathBuf> = prev
     .keys()
     .filter(|dir| !graph.contains_key(*dir))
     .filter(|dir| {
-        let confined = dir.starts_with(confine_root)
-            && dir.components().all(|part| !matches!(part, std::path::Component::ParentDir));
+        let confined = canonical_root.as_ref().is_some_and(|root| {
+            std::fs::canonicalize(dir)
+                .is_ok_and(|canonical_dir| canonical_dir.starts_with(root))
+        });
         if !confined {
             tracing::warn!(
                 ?dir,
                 ?confine_root,
                 "refusing to remove an orphan directory outside the install root",
             );
         }
         confined
     })
     .collect();
Suggestion importance[1-10]: 8

__

Why: Relying on lexical path checks for deletion leaves the code vulnerable to symlink-based directory traversal, which canonicalization effectively mitigates.

Medium
Possible issue
Validate direct dependency links

Check that direct-dependency entries are valid links to the expected target,
rather than just checking if the path exists.

pnpm/crates/package-manager/src/install.rs [2623]

-            Ok(link) => std::fs::symlink_metadata(link).is_ok(),
+            Ok(link) => direct_dependency_link_is_intact(
+                &link,
+                snapshot,
+                name,
+                config,
+            ),
Suggestion importance[1-10]: 5

__

Why: While validating the actual link target improves correctness, it deviates from the stated intent to mirror upstream's fast stat-based check and requires altering the test's sentinel logic.

Low
Suggestions up to commit 4a653fb
CategorySuggestion                                                                                                                                    Impact
Security
Reject malformed lockfile paths early

Return false instead of true for invalid importer IDs and malformed dependency
aliases to avoid bypassing structural validation.

pnpm/crates/package-manager/src/install.rs [2605-2622]

 if crate::symlink_direct_dependencies::validate_importer_id(importer_id).is_err() {
-    return true;
+    return false;
 }
 ...
-Err(_) => true,
+Err(_) => false,
Suggestion importance[1-10]: 9

__

Why: Returning true incorrectly signals that malformed entries are intact, triggering the short-circuit and inadvertently skipping the full path which is supposed to reject them.

High
Prevent symlink-based deletion escapes

Canonicalize paths before removing orphan directories to prevent symlink-based
escapes. This ensures deletions stay strictly within the installation root.

pnpm/crates/package-manager/src/link_hoisted_modules.rs [169-184]

+let Ok(confine_root) = std::fs::canonicalize(confine_root) else {
+    tracing::warn!(?confine_root, "refusing orphan removal without a canonical install root");
+    return 0;
+};
 let orphan_dirs: Vec<&PathBuf> = prev
     .keys()
     .filter(|dir| !graph.contains_key(*dir))
     .filter(|dir| {
-        let confined = dir.starts_with(confine_root)
-            && dir.components().all(|part| !matches!(part, std::path::Component::ParentDir));
+        let confined = std::fs::canonicalize(dir)
+            .is_ok_and(|canonical_dir| canonical_dir.starts_with(&confine_root));
         if !confined {
             tracing::warn!(
                 ?dir,
                 ?confine_root,
                 "refusing to remove an orphan directory outside the install root",
             );
         }
         confined
     })
     .collect();
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential security issue with path traversal via symlinks during orphan removal, though using canonicalize might inadvertently trigger warnings for missing directories.

Medium
Possible issue
Detect corrupted direct dependency links

Use link.is_dir() to verify direct dependencies instead of symlink_metadata, and
update the corresponding test accordingly.

pnpm/crates/package-manager/src/install.rs [2620]

-Ok(link) => std::fs::symlink_metadata(link).is_ok(),
+Ok(link) => link.is_dir(),
Suggestion importance[1-10]: 7

__

Why: symlink_metadata().is_ok() evaluates to true for plain files and dangling symlinks; using link.is_dir() correctly verifies that the dependency resolves to a directory.

Medium
Suggestions up to commit ce2fa5c
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate dependency link targets

Use std::fs::metadata to check that dependency links resolve to valid
directories rather than just checking for their existence.

pnpm/crates/package-manager/src/install.rs [2597]

-            Ok(link) => std::fs::symlink_metadata(link).is_ok(),
+            Ok(link) => std::fs::metadata(link).is_ok_and(|metadata| metadata.is_dir()),
Suggestion importance[1-10]: 9

__

Why: Checking only for existence allows broken symlinks or regular files to incorrectly satisfy the intactness check, bypassing the necessary repair step.

High
Preserve nested modules directory paths

Modify how the modules directory is computed for each importer to preserve
nested paths. Use strip_prefix on workspace_root instead of just taking the file
name of config.modules_dir.

pnpm/crates/package-manager/src/prune_stale_modules.rs [86-100]

-let modules_dir_name: &OsStr =
-    config.modules_dir.file_name().unwrap_or_else(|| OsStr::new("node_modules"));
+let modules_dir_relative = if config.modules_dir.is_absolute() {
+    let Ok(relative) = config.modules_dir.strip_prefix(workspace_root) else {
+        return Ok(0);
+    };
+    relative
+} else {
+    config.modules_dir.as_path()
+};
 
 for (importer_id, current_snapshot) in &current_lockfile.importers {
     ...
     let importer_dir = importer_root_dir(workspace_root, importer_id);
-    let modules_dir = importer_dir.join(modules_dir_name);
+    let modules_dir = importer_dir.join(modules_dir_relative);
Suggestion importance[1-10]: 3

__

Why: The suggestion identifies a valid edge case for nested modules-dir configurations, but the proposed solution can cause incorrect path duplication in subdirectories and silently aborts pruning by returning Ok(0) for external absolute paths.

Low
Security
Reject malformed lockfile paths

Return false for invalid importer IDs and aliases to ensure they fall back to
the full installation path.

pnpm/crates/package-manager/src/install.rs [2582-2600]

     if crate::symlink_direct_dependencies::validate_importer_id(importer_id).is_err() {
-        return true;
+        return false;
     }
 ...
-            Err(_) => true,
+            Err(_) => false,
Suggestion importance[1-10]: 8

__

Why: Returning true for invalid IDs and aliases improperly allows malformed dependencies to bypass validation, which could mask errors or cause unexpected behavior.

Medium
Suggestions up to commit 6f165a4
CategorySuggestion                                                                                                                                    Impact
General
make symlink creation cross-platform

Use conditional compilation to handle symlink creation across different
operating systems.

pnpm/crates/cli/tests/hoisted_node_linker.rs [523-525]

 fs::create_dir_all(workspace.join("node_modules")).expect("create node_modules");
+#[cfg(unix)]
 std::os::unix::fs::symlink(&workspace, workspace.join("node_modules/is-positive"))
     .expect("plant a wrong occupant symlink");
+#[cfg(windows)]
+std::os::windows::fs::symlink_dir(&workspace, workspace.join("node_modules/is-positive"))
+    .expect("plant a wrong occupant junction");
Suggestion importance[1-10]: 8

__

Why: Using std::os::unix::fs::symlink will break the compilation on Windows; making it cross-platform ensures the tests can compile and run successfully across different environments.

Medium
Possible issue
Remove unstable let_chains syntax to fix compilation

Replace the unstable let_chains syntax with a nested if block.

pnpm/crates/package-manager/src/install.rs [2544-2556]

-if probe_slots && let Some(snapshots) = wanted.snapshots.as_ref() {
-    let layout = crate::VirtualStoreLayout::legacy(
-        config.virtual_store_dir.clone(),
-        config.virtual_store_dir_max_length as usize,
-    );
-    let all_slots_present = snapshots.keys().all(|key| {
-        skipped.contains(key)
-            || layout.slot_dir(key).join("node_modules").join(key.name.to_string()).is_dir()
-    });
-    if !all_slots_present {
-        return false;
+if probe_slots {
+    if let Some(snapshots) = wanted.snapshots.as_ref() {
+        let layout = crate::VirtualStoreLayout::legacy(
+            config.virtual_store_dir.clone(),
+            config.virtual_store_dir_max_length as usize,
+        );
+        let all_slots_present = snapshots.keys().all(|key| {
+            skipped.contains(key)
+                || layout.slot_dir(key).join("node_modules").join(key.name.to_string()).is_dir()
+        });
+        if !all_slots_present {
+            return false;
+        }
     }
 }
Suggestion importance[1-10]: 7

__

Why: The let_chains syntax is unstable and will break the build on stable Rust; using nested if statements is the correct fix.

Medium
Replace unstable let_chains syntax with nested if

Replace the unstable let_chains syntax with a nested if block.

pnpm/crates/package-manager/src/install.rs [1358-1360]

-if !installs_only && let Some(modules) = modules_manifest {
-    check_modules_settings_diff(modules, config)?;
+if !installs_only {
+    if let Some(modules) = modules_manifest {
+        check_modules_settings_diff(modules, config)?;
+    }
 }
Suggestion importance[1-10]: 7

__

Why: The let_chains syntax is unstable and will break the build on stable Rust; using nested if statements resolves this.

Medium

@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 (1)
pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs (1)

622-624: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Redundant .modules.yaml-adjacent lockfile reload now that current_lockfile is threaded in.

current_lockfile is now a field loaded once by the caller (Install::run_inner, Lockfile::load_current_from_virtual_store_dir) and threaded into this struct. However, the (unchanged) preResolution hook block further down still does its own Lockfile::load_current_from_virtual_store_dir(&config.virtual_store_dir).ok().flatten() and binds it to a local also named current_lockfile, shadowing the new field for the rest of that block. This now duplicates the disk read+parse this same install already performed, and additionally swallows load errors (.ok()) that the outer field's load already surfaces as a typed InstallError.

Since the block runs after this field is destructured and before any lockfile-affecting mutation, it should be safe to drop the re-load and reuse the outer current_lockfile binding directly.

♻️ Proposed fix
         if let Some(ref hook) = pnpmfile_hook {
             let wanted_lockfile_json = wanted_lockfile.map_or_else(
                 || serde_json::json!({}),
                 |lf| serde_json::to_value(lf).unwrap_or_else(|_| serde_json::json!({})),
             );
-            let current_lockfile =
-                Lockfile::load_current_from_virtual_store_dir(&config.virtual_store_dir)
-                    .ok()
-                    .flatten();
             let exists_current_lockfile = current_lockfile.is_some();
             let current_lockfile_json = current_lockfile.map_or_else(
                 || serde_json::json!({}),
                 |lf| serde_json::to_value(lf).unwrap_or_else(|_| serde_json::json!({})),
             );
🤖 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/package-manager/src/install_with_fresh_lockfile.rs` around lines
622 - 624, Remove the inner Lockfile::load_current_from_virtual_store_dir call
and its shadowing current_lockfile binding in the preResolution hook block.
Reuse the current_lockfile field already threaded through Install::run_inner and
the surrounding struct destructuring, preserving the existing hook behavior and
error propagation.
🤖 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/package-manager/src/install.rs`:
- Around line 2593-2617: Update modules_layout_consistent_with() to compare
hoist_pattern and public_hoist_pattern through normalized_pattern(), treating
None and empty lists as equivalent. Keep the resulting mismatch behavior aligned
with check_modules_settings_diff() so add/remove surfaces the corresponding
HoistPatternDiff or PublicHoistPatternDiff instead of recreating node_modules.

---

Nitpick comments:
In `@pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs`:
- Around line 622-624: Remove the inner
Lockfile::load_current_from_virtual_store_dir call and its shadowing
current_lockfile binding in the preResolution hook block. Reuse the
current_lockfile field already threaded through Install::run_inner and the
surrounding struct destructuring, preserving the existing hook behavior and
error propagation.
🪄 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: b3dd7857-8afd-4724-b2b7-dc38194182c7

📥 Commits

Reviewing files that changed from the base of the PR and between 199c49b and 6f165a4.

📒 Files selected for processing (28)
  • .changeset/reconcile-existing-node-modules-on-repeat-install.md
  • pnpm/crates/cli/src/cli_args/dedupe.rs
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/cli/src/cli_args/fetch.rs
  • pnpm/crates/cli/src/cli_args/import.rs
  • pnpm/crates/cli/src/cli_args/install.rs
  • pnpm/crates/cli/src/cli_args/link.rs
  • pnpm/crates/cli/src/cli_args/prune.rs
  • pnpm/crates/cli/src/cli_args/rebuild.rs
  • pnpm/crates/cli/src/cli_args/unlink.rs
  • pnpm/crates/cli/tests/hoist.rs
  • pnpm/crates/cli/tests/hoisted_node_linker.rs
  • pnpm/crates/cli/tests/repeat_install.rs
  • pnpm/crates/lockfile/src/lib.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/package-manager/src/add.rs
  • pnpm/crates/package-manager/src/create_virtual_store.rs
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_frozen_lockfile.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/crates/package-manager/src/prune_direct_deps.rs
  • pnpm/crates/package-manager/src/prune_stale_modules.rs
  • pnpm/crates/package-manager/src/remove.rs
  • pnpm/crates/package-manager/src/update.rs
  • pnpm/plans/TEST_PORTING.md
  • pnpr/crates/pnpr/src/resolver/resolve.rs

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 7408f660b77a

Each scenario reports direct installs and pnpr installs. 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.494 ± 0.174 2.336 2.787 1.68 ± 0.21
pacquet@main 2.506 ± 0.170 2.343 2.750 1.69 ± 0.21
pnpr@HEAD 1.525 ± 0.143 1.369 1.781 1.03 ± 0.14
pnpr@main 1.486 ± 0.154 1.341 1.751 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.4935469137800004,
      "stddev": 0.1740131089816011,
      "median": 2.42193447558,
      "user": 1.47683164,
      "system": 1.27026656,
      "min": 2.33634530558,
      "max": 2.7867031255800003,
      "times": [
        2.34063313858,
        2.33634530558,
        2.7867031255800003,
        2.47106083258,
        2.3520541545800002,
        2.37280811858,
        2.54316789758,
        2.7137450275800004,
        2.67061070658,
        2.34834083058
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.50644262668,
      "stddev": 0.17045356563027725,
      "median": 2.4115449905800004,
      "user": 1.50486704,
      "system": 1.2400813599999998,
      "min": 2.34282535158,
      "max": 2.74955509258,
      "times": [
        2.71258324958,
        2.42464592358,
        2.35471246258,
        2.39227822358,
        2.3984440575800003,
        2.74955509258,
        2.74246299258,
        2.37140509658,
        2.34282535158,
        2.57551381658
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.5250639881799999,
      "stddev": 0.14326701662232952,
      "median": 1.47263064658,
      "user": 1.0594889399999998,
      "system": 1.1130507600000004,
      "min": 1.36877026558,
      "max": 1.78083676358,
      "times": [
        1.44297327658,
        1.6620141855800001,
        1.78083676358,
        1.50228801658,
        1.37036548058,
        1.6842259035800002,
        1.43503404358,
        1.42981237858,
        1.5743195675800001,
        1.36877026558
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4857289115800003,
      "stddev": 0.15367580911972173,
      "median": 1.4476626715800003,
      "user": 1.0401842399999999,
      "system": 1.10459146,
      "min": 1.3414854205800002,
      "max": 1.7507909275800002,
      "times": [
        1.58635314458,
        1.5334751515800003,
        1.35833788458,
        1.36185019158,
        1.6791772735800001,
        1.35458457458,
        1.3414854205800002,
        1.54477343358,
        1.3464611135800002,
        1.7507909275800002
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 245.2 ± 3.9 241.1 253.4 1.00
pacquet@main 247.0 ± 5.4 236.8 253.7 1.01 ± 0.03
pnpr@HEAD 264.0 ± 6.5 252.0 271.7 1.08 ± 0.03
pnpr@main 258.3 ± 6.0 248.7 265.4 1.05 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.24523851487999998,
      "stddev": 0.0038612800455147694,
      "median": 0.24421535798000002,
      "user": 0.19643908,
      "system": 0.50638506,
      "min": 0.24114779898000002,
      "max": 0.25341515598000003,
      "times": [
        0.24114779898000002,
        0.24265907598000003,
        0.24966530298,
        0.24259524698,
        0.24665797798000003,
        0.24536690698000002,
        0.24306380898000002,
        0.24202941098000003,
        0.24578446298,
        0.25341515598000003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.24699029468000006,
      "stddev": 0.005427673480379725,
      "median": 0.24725247898000002,
      "user": 0.19622637999999998,
      "system": 0.50922746,
      "min": 0.23680378698000001,
      "max": 0.25365837398,
      "times": [
        0.23680378698000001,
        0.25365837398,
        0.24652888598000003,
        0.24883229498,
        0.25299108798000003,
        0.24146370498000003,
        0.24504607198000003,
        0.24797607198000002,
        0.25269226498,
        0.24391040298000002
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.26399836788000003,
      "stddev": 0.006527590757263423,
      "median": 0.26478642848,
      "user": 0.20789697999999998,
      "system": 0.5350426599999999,
      "min": 0.25204550698,
      "max": 0.27167471498,
      "times": [
        0.25511024898,
        0.25204550698,
        0.26083376898000005,
        0.26476890998,
        0.26707874998000003,
        0.26944281198000003,
        0.27116869398000004,
        0.26480394698000004,
        0.26305632598,
        0.27167471498
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.25832593078,
      "stddev": 0.005960485691488778,
      "median": 0.25787116948,
      "user": 0.19532248,
      "system": 0.5143006599999999,
      "min": 0.24867569298000003,
      "max": 0.26540988798000004,
      "times": [
        0.26320464498,
        0.26404212198000004,
        0.25783367898000004,
        0.26540988798000004,
        0.24867569298000003,
        0.25150101398,
        0.25790865998,
        0.25581615998,
        0.25376755198,
        0.26509989498000003
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.684 ± 0.024 2.637 2.708 1.75 ± 0.13
pacquet@main 2.707 ± 0.015 2.676 2.730 1.77 ± 0.13
pnpr@HEAD 1.601 ± 0.131 1.402 1.806 1.04 ± 0.12
pnpr@main 1.533 ± 0.115 1.393 1.712 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.683691950400001,
      "stddev": 0.024011806819090018,
      "median": 2.6937416086,
      "user": 1.5685487999999999,
      "system": 1.2660024599999997,
      "min": 2.6367593271,
      "max": 2.7080425921,
      "times": [
        2.6551827821000002,
        2.6367593271,
        2.6734727971000005,
        2.6974435501,
        2.7024025691,
        2.6900396671,
        2.6692968721000003,
        2.7042528031,
        2.7080425921,
        2.7000265441
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.7066425364000004,
      "stddev": 0.015259073835909765,
      "median": 2.7062596276000006,
      "user": 1.6037095000000001,
      "system": 1.2196746600000001,
      "min": 2.6756499461,
      "max": 2.7301206401,
      "times": [
        2.7150327951000004,
        2.7301206401,
        2.7222196521,
        2.6967408251,
        2.7139122891000005,
        2.7041596071000003,
        2.7053577901000003,
        2.6960703541,
        2.7071614651000004,
        2.6756499461
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.6010091142,
      "stddev": 0.1306868684851154,
      "median": 1.5870852841,
      "user": 0.9550661,
      "system": 1.14594036,
      "min": 1.4016645901,
      "max": 1.8059939271,
      "times": [
        1.5261245181,
        1.4016645901,
        1.5355103411,
        1.5829527271000001,
        1.6027983130999999,
        1.5912178411,
        1.7416397151,
        1.7554053791000002,
        1.8059939271,
        1.4667837901
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.5325524009,
      "stddev": 0.11488406054267612,
      "median": 1.5314985741,
      "user": 0.9496684999999998,
      "system": 1.1455877599999997,
      "min": 1.3933711031,
      "max": 1.7121510731,
      "times": [
        1.6714339311,
        1.7121510731,
        1.4103107800999999,
        1.4482184951000001,
        1.4190512580999999,
        1.5683265241,
        1.3933711031,
        1.6061469601,
        1.4946706241,
        1.6018432601
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 545.8 ± 10.8 528.5 558.5 1.90 ± 0.05
pacquet@main 535.3 ± 13.8 512.5 550.1 1.86 ± 0.06
pnpr@HEAD 287.8 ± 5.5 278.0 294.3 1.00
pnpr@main 289.6 ± 9.5 277.0 306.9 1.01 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.5457994786000001,
      "stddev": 0.010804463519925525,
      "median": 0.5482586215,
      "user": 0.67270834,
      "system": 0.6528913199999999,
      "min": 0.5285337265000001,
      "max": 0.5585038365000001,
      "times": [
        0.5371930645,
        0.5488216715,
        0.5476955715,
        0.5401854965000001,
        0.5582642845000001,
        0.5509789635000001,
        0.5585038365000001,
        0.5558141135000001,
        0.5320040575000001,
        0.5285337265000001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.5353171479000001,
      "stddev": 0.013809018037092953,
      "median": 0.5397608970000001,
      "user": 0.65034524,
      "system": 0.66456532,
      "min": 0.5125356635000001,
      "max": 0.5501437495000001,
      "times": [
        0.5183043005000001,
        0.5125356635000001,
        0.5421784885,
        0.5331956095000001,
        0.5462764005,
        0.5373433055000001,
        0.5494061915000001,
        0.5198478975,
        0.5501437495000001,
        0.5439398725000001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.2878246743,
      "stddev": 0.005519617895755877,
      "median": 0.2872418745,
      "user": 0.17285563999999998,
      "system": 0.5156295199999998,
      "min": 0.27804399150000003,
      "max": 0.2943414475,
      "times": [
        0.2924699045,
        0.2930547855,
        0.2879848035,
        0.2841773865,
        0.2840290265,
        0.27804399150000003,
        0.28354846250000004,
        0.2943414475,
        0.2864989455,
        0.2940979895
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.2896324884,
      "stddev": 0.009519584491612401,
      "median": 0.28787187550000004,
      "user": 0.19651463999999996,
      "system": 0.49261811999999994,
      "min": 0.2770104265,
      "max": 0.3068649295,
      "times": [
        0.2891362605,
        0.3068649295,
        0.30159607250000003,
        0.2860789065,
        0.27972358350000004,
        0.2866613825,
        0.2969992495,
        0.2831717045,
        0.2770104265,
        0.2890823685
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.841 ± 0.011 1.822 1.859 6.36 ± 0.14
pacquet@main 1.827 ± 0.016 1.803 1.856 6.31 ± 0.14
pnpr@HEAD 0.297 ± 0.007 0.284 0.305 1.03 ± 0.03
pnpr@main 0.289 ± 0.006 0.280 0.300 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.84107593522,
      "stddev": 0.011404991539498147,
      "median": 1.8389739342200002,
      "user": 0.8811794199999999,
      "system": 0.71894762,
      "min": 1.8219575247200002,
      "max": 1.85894278072,
      "times": [
        1.85894278072,
        1.8219575247200002,
        1.85066649272,
        1.83528741272,
        1.83460386472,
        1.84253548072,
        1.83980301572,
        1.8381448527200002,
        1.83249273072,
        1.85632519672
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.82724213512,
      "stddev": 0.015947116377162795,
      "median": 1.82381766522,
      "user": 0.8651168200000001,
      "system": 0.71346932,
      "min": 1.80311458072,
      "max": 1.85577834572,
      "times": [
        1.83714246572,
        1.83062957172,
        1.85577834572,
        1.82211249472,
        1.82305064072,
        1.82458468972,
        1.8471501897200002,
        1.8163306867200002,
        1.80311458072,
        1.8125276857200001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.29670110892000007,
      "stddev": 0.007084018627412933,
      "median": 0.29893900272000007,
      "user": 0.16630591999999997,
      "system": 0.5384275199999999,
      "min": 0.28411691372000003,
      "max": 0.30523577972000004,
      "times": [
        0.30385924672000003,
        0.29898674172000006,
        0.28411691372000003,
        0.29889126372,
        0.29989107672000004,
        0.30523577972000004,
        0.29266128072,
        0.30245348072000006,
        0.29374703672,
        0.28716826872
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.28943733442,
      "stddev": 0.0060411236064779675,
      "median": 0.28853367422000004,
      "user": 0.17650401999999996,
      "system": 0.5275986199999999,
      "min": 0.28000374872000006,
      "max": 0.30037623972000005,
      "times": [
        0.28000374872000006,
        0.30037623972000005,
        0.28835605472000003,
        0.29384091372000004,
        0.28415221972000004,
        0.28574156272,
        0.28566647072,
        0.28871129372000004,
        0.29210512472000005,
        0.29541971572000003
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 315.6 ± 7.9 305.6 330.7 3.74 ± 0.13
pacquet@main 322.6 ± 12.0 308.5 342.2 3.82 ± 0.17
pnpr@HEAD 85.2 ± 2.5 81.2 90.3 1.01 ± 0.04
pnpr@main 84.3 ± 1.9 81.5 87.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.31563968666000003,
      "stddev": 0.007889613677522347,
      "median": 0.31325592426000004,
      "user": 0.30740292,
      "system": 0.055175260000000004,
      "min": 0.30558547726,
      "max": 0.33072053026000003,
      "times": [
        0.31711717826,
        0.32324322526000004,
        0.33072053026000003,
        0.32332424926000003,
        0.30558547726,
        0.31020410626,
        0.30923306826,
        0.31187163726,
        0.31464021126,
        0.31045718326000005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.32258871996000005,
      "stddev": 0.011972697033719124,
      "median": 0.31838572676,
      "user": 0.31235102,
      "system": 0.05690115999999999,
      "min": 0.30845814826,
      "max": 0.34218652626,
      "times": [
        0.30845814826,
        0.34218652626,
        0.33527338426000003,
        0.31121915826,
        0.31915571726,
        0.31176442426,
        0.32781847426000005,
        0.31597256126,
        0.33642306926000004,
        0.31761573626
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.08523327172875002,
      "stddev": 0.0025377083567357105,
      "median": 0.08579584076,
      "user": 0.020394913750000004,
      "system": 0.00768361125,
      "min": 0.08119901826,
      "max": 0.09033775126000002,
      "times": [
        0.08884418826000001,
        0.08588021426,
        0.08841297626000001,
        0.08681387426,
        0.08771270526000001,
        0.08424885226,
        0.08208436626000001,
        0.08224459726000001,
        0.08199875426000001,
        0.08567540926000002,
        0.08534136026000001,
        0.08119901826,
        0.08217632826000001,
        0.08384334826,
        0.08233273326000001,
        0.08209413326000001,
        0.08905907226000001,
        0.08640114626,
        0.08615130526,
        0.09033775126000002,
        0.08706392326000001,
        0.08588976326000002,
        0.08769215826000001,
        0.08661105226000002,
        0.08648005326000001,
        0.08434477326,
        0.08758287226000001,
        0.08636550926000001,
        0.08571146726000001,
        0.08177867926000001,
        0.08315581326,
        0.08193649626
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.0843403500478788,
      "stddev": 0.0019347205742625635,
      "median": 0.08495844926000001,
      "user": 0.020642668484848484,
      "system": 0.007121420000000001,
      "min": 0.08146223226,
      "max": 0.08789518026000001,
      "times": [
        0.08568826426000001,
        0.08336929626,
        0.08146223226,
        0.08276594926000001,
        0.08173518826000001,
        0.08180437826,
        0.08201191926000001,
        0.08531456926000001,
        0.08760920026,
        0.08691443326,
        0.08789518026000001,
        0.08779920026000002,
        0.08521173626,
        0.08246541326000001,
        0.08399564526000002,
        0.08495714626,
        0.08518079826000001,
        0.08605128726000001,
        0.08556641326000002,
        0.08263044326,
        0.08553533526000001,
        0.08495844926000001,
        0.08265273626000001,
        0.08200485526000001,
        0.08214987926,
        0.08220045326000001,
        0.08351539126,
        0.08593716226,
        0.08522281626000001,
        0.08592949726000002,
        0.08544882226000002,
        0.08227407226000001,
        0.08497338726
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.500 ± 0.130 4.414 4.781 1.28 ± 0.05
pacquet@main 4.596 ± 0.185 4.420 4.874 1.31 ± 0.06
pnpr@HEAD 3.571 ± 0.129 3.439 3.797 1.02 ± 0.05
pnpr@main 3.505 ± 0.101 3.439 3.778 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.50046742136,
      "stddev": 0.13046523023848708,
      "median": 4.4421863864599995,
      "user": 1.6379898599999998,
      "system": 1.36838748,
      "min": 4.4136440314600005,
      "max": 4.78138012146,
      "times": [
        4.69378669946,
        4.43774185946,
        4.4136440314600005,
        4.41750405246,
        4.44663091346,
        4.45450189846,
        4.52061116746,
        4.78138012146,
        4.41852378446,
        4.42034968546
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.59594144116,
      "stddev": 0.18542377540223798,
      "median": 4.51003902496,
      "user": 1.65883416,
      "system": 1.3072936800000001,
      "min": 4.41966443346,
      "max": 4.87366406246,
      "times": [
        4.81857098846,
        4.42057113146,
        4.67998203646,
        4.87366406246,
        4.43188032646,
        4.48601102646,
        4.82875670546,
        4.5340670234600005,
        4.41966443346,
        4.46624667746
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.5713305010599994,
      "stddev": 0.12937755295407236,
      "median": 3.53278866346,
      "user": 1.1701977599999998,
      "system": 1.21516628,
      "min": 3.4388244764600002,
      "max": 3.79713846746,
      "times": [
        3.51699432846,
        3.79713846746,
        3.48909696346,
        3.4819043344600002,
        3.54858299846,
        3.4388244764600002,
        3.77119675646,
        3.44807753746,
        3.55770749846,
        3.66378164946
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.50486435376,
      "stddev": 0.1006128733369873,
      "median": 3.47073501696,
      "user": 1.13916176,
      "system": 1.2184818800000001,
      "min": 3.4388947984600002,
      "max": 3.77760982846,
      "times": [
        3.45890045746,
        3.44933458646,
        3.77760982846,
        3.47323689546,
        3.46823313846,
        3.4435802244600002,
        3.4388947984600002,
        3.5226854104600003,
        3.52721563546,
        3.48895256246
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/13151
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,636.76 ms
(-1.78%)Baseline: 2,684.43 ms
3,221.32 ms
(81.85%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,821.96 ms
(-1.12%)Baseline: 1,842.61 ms
2,211.13 ms
(82.40%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
528.53 ms
(-3.00%)Baseline: 544.87 ms
653.84 ms
(80.83%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
305.59 ms
(-6.53%)Baseline: 326.92 ms
392.30 ms
(77.90%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,336.35 ms
(-1.90%)Baseline: 2,381.63 ms
2,857.95 ms
(81.75%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,413.64 ms
(-0.89%)Baseline: 4,453.23 ms
5,343.88 ms
(82.59%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
241.15 ms
(-2.70%)Baseline: 247.83 ms
297.39 ms
(81.09%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/13151
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,401.66 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
284.12 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
278.04 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
81.20 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,368.77 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,438.82 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
252.05 ms
🐰 View full continuous benchmarking report in Bencher

Copilot AI review requested due to automatic review settings July 19, 2026 18:03
@zkochan
zkochan force-pushed the stage1-repeat-install-reconciliation branch from 6f165a4 to ce2fa5c Compare July 19, 2026 18:03

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 19, 2026
@qodo-code-review

Copy link
Copy Markdown

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

@codecov-commenter

codecov-commenter commented Jul 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.35443% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.91%. Comparing base (ebacfa6) to head (05da049).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/package-manager/src/install.rs 88.00% 12 Missing ⚠️
.../crates/package-manager/src/prune_stale_modules.rs 93.10% 8 Missing ⚠️
...crates/package-manager/src/link_hoisted_modules.rs 95.83% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13151      +/-   ##
==========================================
+ Coverage   85.85%   85.91%   +0.05%     
==========================================
  Files         505      506       +1     
  Lines       84029    84353     +324     
==========================================
+ Hits        72147    72474     +327     
+ Misses      11882    11879       -3     

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

Copilot AI review requested due to automatic review settings July 19, 2026 18:33
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 7408f66

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

Labels

product: pacquet product: pnpr reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants