Skip to content

fix(pacquet): make the global virtual store safe to share, and reachable from the Node API - #13648

Merged
zkochan merged 3 commits into
mainfrom
gvs-embedder-and-concurrency
Aug 5, 2026
Merged

zkochan merged 3 commits into
mainfrom
gvs-embedder-and-concurrency

Conversation

@zkochan

@zkochan zkochan commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Makes global virtual-store imports safe when multiple processes materialize the same content-addressed slot, and exposes the related embedding options through @pnpm/napi.

  • Adds ImportIndexedDirOpts::safe_to_skip for immutable global virtual-store slots. A competing importer keeps an occupied target only after verifying that the import is complete; incomplete targets still use the repair path.
  • Keeps mutable directory sources on the repair path because an occupied slot may contain stale files.
  • Treats the needs-build marker as transient so a late importer does not replace a slot that another process has already built.
  • Adds enableGlobalVirtualStore, globalVirtualStoreDir, packageExtensions, and patchedDependencies to the N-API install options.
  • Resolves relative patch paths from the requested install directory and recomputes derived global virtual-store paths after applying the N-API configuration overlay.
  • Reports enableGlobalVirtualStore, globalVirtualStoreDir, virtualStoreDir, and effectiveVirtualStoreDir from readConfig.

The TypeScript implementation already enables safeToSkip for global virtual-store imports. The N-API surface is specific to pacquet, so no TypeScript implementation change is required.

Validation performed on this branch:

  • Reproduced the original race with 10 concurrent installs sharing one store: 6 failures before the fix and 0 after it.
  • cargo nextest run --workspace --exclude pnpr --exclude pnpr-fixtures: 7010 passed, 0 failed.
  • The pre-push TypeScript and Rust checks passed, including formatting, linting, clippy, rustdoc, dylint, spelling, and metadata validation.
  • Validated the global virtual store through the N-API in three Bit workspaces with 609, 332, and 105 components and the approximately 2800-test Bit end-to-end suite.

Squash Commit Body

The global virtual store is shared across projects, so concurrent installs may materialize the same content-addressed slot. The existing swap removed an occupied target before moving its staged copy into place. This could race with another writer, fail with a directory-not-empty error, or briefly remove a directory another process was reading.

Add a safe-to-skip import mode for immutable global virtual-store slots. It first attempts a non-destructive rename. If another importer already completed the target, discard only the staging directory. Incomplete targets still use the repair path. Mutable directory sources do not use this mode because a complete slot may still contain stale files, and the transient needs-build marker is excluded from completeness checks so completed build output is preserved.

Expose enableGlobalVirtualStore, globalVirtualStoreDir, packageExtensions, and patchedDependencies through @pnpm/napi. Resolve relative patch paths from the requested install directory, recompute global virtual-store derivation after applying the overlay, and return both configured and effective virtual-store paths from readConfig.

Checklist

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

Written by an agent (Codex, GPT-5).

Copilot AI lite review requested due to automatic review settings August 4, 2026 19:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix global virtual store concurrency; keep directory deps local; expose GVS via N-API

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Make global virtual-store imports concurrency-safe by skipping destructive swaps for complete
 slots.
• Keep directory-resolved (injected/file:) snapshots in the project-local virtual store under GVS.
• Expose GVS + embedder-critical config (effective store dir, extensions, patches) via Node API.
Diagram

graph TD
  A([Embedder / CLI]) --> B["napi::InstallOptions / cli args"] --> C["ConfigOverlay + build_config"] --> D["VirtualStoreLayout"] --> E{"�Directory resolution?"}
  E -->|yes| F["Local virtual store"] --> G["slot_dir(key)"] --> H["import_indexed_dir"]
  E -->|no| I["Global virtual store"] --> G --> H
  H --> J{"�GVS content-addressed slot?"} --> K["stage_and_swap (safe_to_skip)"]

  subgraph Legend
    direction LR
    _actor([Caller]) ~~~ _mod["Rust module"] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Per-slot lock file (advisory locking)
  • ➕ Eliminates most races by serializing writers to the same slot
  • ➕ Avoids heuristic checks like 'all expected files exist'
  • ➖ Harder cross-platform semantics (Windows vs Unix) and potential for stale locks
  • ➖ Adds blocking and potential deadlock/timeout behavior under crashes
2. Always rename-first + strict marker validation
  • ➕ Keeps non-destructive behavior for shared targets
  • ➕ Can be made robust by requiring a completion marker (or manifest) before treating the slot as valid
  • ➖ Requires ensuring marker semantics exist for all slot types (not always available)
  • ➖ If markers are missing/optional, falls back to similar heuristics anyway
3. Content hash verification on conflict (byte-level)
  • ➕ Strong correctness: ensures existing slot content exactly matches expected content
  • ➕ Works even if file list overlaps but contents differ
  • ➖ Potentially expensive I/O (rehashing) on hot paths
  • ➖ More complex implementation than name/marker presence checks

Recommendation: The PR’s optimistic, non-destructive rename-first strategy with a completeness check is a strong tradeoff for a content-addressed shared store: it avoids global locks, aligns with pnpm’s existing safeToSkip semantics, and still repairs partial slots by falling through to the destructive swap. If future issues show false-positives from the 'all expected names exist' heuristic, the next incremental hardening would be to require/validate a completion marker for GVS slots (or introduce optional locking only on conflict).

Files changed (17) +467 / -38

Enhancement (4) +158 / -1
config.rsExpose GVS + embedder config in ConfigOverlay and re-derive roots +58/-1

Expose GVS + embedder config in ConfigOverlay and re-derive roots

• Extends the N-API config overlay with enableGlobalVirtualStore, globalVirtualStoreDir, packageExtensions, and patchedDependencies. Re-derives the global virtual store root after overlay application, and anchors patched dependency paths to the install dir for embedders.

pnpm/crates/napi/src/config.rs

install.rsAdd N-API install inputs for GVS, packageExtensions, patchedDependencies +47/-0

Add N-API install inputs for GVS, packageExtensions, patchedDependencies

• Extends InstallOptions with GVS toggles/root, packageExtensions input shape, and patchedDependencies. Maps these into ConfigOverlay, converting extension maps into the core PackageExtension structure.

pnpm/crates/napi/src/install.rs

read_config.rsReturn GVS state and effective virtual store dir via N-API +14/-0

Return GVS state and effective virtual store dir via N-API

• Extends ResolvedConfig with enableGlobalVirtualStore, globalVirtualStoreDir, and effectiveVirtualStoreDir so embedders can locate the correct virtual store directory under GVS.

pnpm/crates/napi/src/read_config.rs

index.d.tsExtend Node typings for GVS config, packageExtensions, patchedDependencies +39/-0

Extend Node typings for GVS config, packageExtensions, patchedDependencies

• Adds TypeScript types for PackageExtension and new InstallOptions fields, and extends ResolvedConfig with enableGlobalVirtualStore/globalVirtualStoreDir/effectiveVirtualStoreDir for embedders.

pnpm/npm/napi/index.d.ts

Bug fix (4) +149 / -3
create_virtual_dir_by_snapshot.rsEnable safe_to_skip for GVS slot materialization +7/-2

Enable safe_to_skip for GVS slot materialization

• Plumbs a safe_to_skip flag into ImportIndexedDirOpts when global virtual store mode is active, preventing destructive swaps for shared content-addressed slots during concurrent imports.

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

import_indexed_dir.rsAdd safe_to_skip option and non-destructive rename-first import path +69/-0

Add safe_to_skip option and non-destructive rename-first import path

• Introduces ImportIndexedDirOpts::safe_to_skip and threads it through to stage_and_swap. Implements a rename-first path that treats occupied-but-complete targets as a successful concurrent win, while still repairing incomplete targets via the existing destructive swap path.

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

validate_lockfile_paths.rsValidate slot containment against per-key store root under GVS +4/-1

Validate slot containment against per-key store root under GVS

• Changes containment checks to use layout.store_root_for(key) so directory-resolved snapshots (kept local) aren’t incorrectly flagged as escaping the shared global root.

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

virtual_store_layout.rsRoute directory-resolved snapshots to project-local store under GVS +69/-0

Route directory-resolved snapshots to project-local store under GVS

• Adds local_store_dir and directory_keys to VirtualStoreLayout and routes slot_dir/store_root_for decisions per key. Directory resolutions stay in the project-local virtual store; registry snapshots still use the global store.

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

Refactor (4) +12 / -4
deploy.rsAdopt ImportIndexedDirOpts default initialization in deploy +1/-1

Adopt ImportIndexedDirOpts default initialization in deploy

• Switches to struct update syntax for ImportIndexedDirOpts to keep new option fields (e.g., safe_to_skip) consistently initialized.

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

build_modules.rsUse ImportIndexedDirOpts defaults where possible +5/-1

Use ImportIndexedDirOpts defaults where possible

• Switches ImportIndexedDirOpts construction to include default fields, ensuring new options are consistently initialized across call sites.

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

link_hoisted_modules.rsUse ImportIndexedDirOpts defaults in hoisted-module import +5/-1

Use ImportIndexedDirOpts defaults in hoisted-module import

• Updates ImportIndexedDirOpts initialization to keep new fields (like safe_to_skip) consistently set via defaults.

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

patch.rsUse ImportIndexedDirOpts defaults in patch materialization +1/-1

Use ImportIndexedDirOpts defaults in patch materialization

• Switches to default-based ImportIndexedDirOpts initialization to remain compatible with added option fields.

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

Tests (3) +132 / -30
tests.rsUpdate N-API install options test fixtures for new fields +4/-0

Update N-API install options test fixtures for new fields

• Initializes newly added InstallOptions fields to None in test helpers to keep compilation and baseline behavior consistent.

pnpm/crates/napi/src/install/tests.rs

tests.rsAdd tests for safe_to_skip behavior on shared slots +73/-2

Add tests for safe_to_skip behavior on shared slots

• Extends constants to include the new safe_to_skip field and adds tests verifying that a complete pre-existing target is accepted while an incomplete target is repaired.

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

tests.rsTest that directory deps stay local while registry deps stay global +55/-28

Test that directory deps stay local while registry deps stay global

• Reworks the directory dependency test to assert directory-resolved slots are project-local under GVS and that registry-resolved slots still share the global store across projects.

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

Documentation (2) +16 / -0
gvs-concurrent-slot-import.mdDocument GVS concurrent slot import fix +7/-0

Document GVS concurrent slot import fix

• Adds a changeset describing the new non-destructive import behavior for shared content-addressed slots and the failure mode it prevents (Directory not empty during swap).

.changeset/gvs-concurrent-slot-import.md

gvs-directory-resolutions-stay-local.mdDocument directory-resolution routing under GVS +9/-0

Document directory-resolution routing under GVS

• Adds a changeset explaining why directory-resolved/injected dependencies remain project-local even when the global virtual store is enabled.

.changeset/gvs-directory-resolutions-stay-local.md

@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge based on the currently established behavior.

No blocking failure remains established; the prior shared-slot content-integrity concern cannot be classified conclusively without evidence that unintended content modification is reachable under supported store ownership and permissions.

Reviews (10): Last reviewed commit: "docs(pacquet): align comments with style..." | Re-trigger Greptile

Comment thread pnpm/crates/napi/src/read_config.rs Resolved
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds NAPI options and resolved fields for global virtual stores, package extensions, and patched dependencies. It routes directory resolutions to project-local stores and adds non-destructive reuse for completed shared slots during concurrent imports.

Changes

Global virtual-store configuration and public API

Layer / File(s) Summary
NAPI configuration and public options
pnpm/crates/napi/src/config.rs, pnpm/crates/napi/src/install.rs, pnpm/crates/napi/src/read_config.rs, pnpm/npm/napi/index.d.ts, .changeset/napi-global-virtual-store.md
NAPI install options accept global virtual-store settings, package extensions, and patched dependencies. Configuration overlays resolve patch paths and derive effective virtual-store paths. Resolved configuration and TypeScript declarations expose the resulting values.

Virtual-store routing and import behavior

Layer / File(s) Summary
Local resolution storage routing
pnpm/crates/deps-restorer/src/virtual_store_layout.rs, pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs, pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs, pnpm/crates/cli/tests/global_virtual_store.rs, .changeset/gvs-directory-resolutions-stay-local.md
Directory resolutions and injected local packages use project-local virtual-store slots. Registry packages continue to use shared global slots.
Concurrent shared-slot imports
pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs, pnpm/crates/deps-restorer/src/import_indexed_dir.rs, pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs, pnpm/crates/cli/src/cli_args/deploy.rs, pnpm/crates/deps-restorer/src/build_modules.rs, pnpm/crates/deps-restorer/src/link_hoisted_modules.rs, pnpm/crates/package-manager/src/patch.rs, .changeset/gvs-concurrent-slot-import.md
Global virtual-store imports enable safe_to_skip. Complete occupied targets are retained. Incomplete targets are replaced and repaired. Other import callers use defaulted options while preserving existing force and module-directory settings.

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

Sequence Diagram(s)

sequenceDiagram
  participant InstallOptions
  participant build_overlay
  participant build_config
  participant ResolvedConfig
  InstallOptions->>build_overlay: provide virtual-store and dependency settings
  build_overlay->>build_config: apply configuration overlay
  build_config->>ResolvedConfig: expose effective virtual-store paths
Loading
sequenceDiagram
  participant create_virtual_dir_by_snapshot
  participant import_indexed_dir
  participant stage_and_swap
  participant SharedSlot
  create_virtual_dir_by_snapshot->>import_indexed_dir: enable safe_to_skip
  import_indexed_dir->>stage_and_swap: pass safe_to_skip
  stage_and_swap->>SharedSlot: attempt staged rename
  SharedSlot-->>stage_and_swap: report target state
  stage_and_swap->>SharedSlot: preserve complete target or replace incomplete target
Loading

Possibly related PRs

  • pnpm/pnpm#13060: Both changes modify ImportIndexedDirOpts and shared import behavior.
  • pnpm/pnpm#13170: Both changes modify global virtual-store recovery and slot imports.
  • pnpm/pnpm#13513: Both changes extend ResolvedConfig and NAPI virtual-store reporting.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch gvs-embedder-and-concurrency

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (8) 📘 Rule violations (4) 📜 Skill insights (0)

Grey Divider


Action required

1. Build marker breaks skip ✓ Resolved 🐞 Bug ☼ Reliability
Description
is_complete_import() treats a slot as complete only if **every** cas_paths entry exists, but GVS
build/patch success intentionally removes .pnpm-needs-build, so a finished (built) slot can be
misclassified as incomplete and fall through to the destructive swap, wiping build outputs under
concurrency.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R316-319]

+fn is_complete_import(dir_path: &Path, cas_paths: &HashMap<String, PathBuf>) -> bool {
+    marker_present(dir_path, cas_paths)
+        && cas_paths.keys().all(|entry| dir_path.join(entry).exists())
+}
Relevance

●●● Strong

Team has recently accepted multiple fixes around .pnpm-needs-build marker semantics and GVS
correctness.

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new is_complete_import() requires all cas_paths entries to exist, and
CreateVirtualDirBySnapshot can inject .pnpm-needs-build into cas_paths during
interrupted-build handling. Separately, the build phase removes .pnpm-needs-build after successful
build/patch in GVS, so a slot can be valid while failing the new completeness test, triggering the
destructive fallback.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[316-319]
pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs[149-176]
pnpm/crates/deps-restorer/src/build_modules.rs[1315-1329]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[451-462]

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 `safe_to_skip` completion predicate requires *all* `cas_paths` keys to exist in the destination. For packages that temporarily import `.pnpm-needs-build`, a competing process may observe a fully-built slot where the marker has been removed (as intended) and incorrectly treat it as incomplete, falling through to the destructive `remove_dir_all` swap.

### Issue Context
- The completeness check is used to decide whether an occupied shared slot can be accepted as-is.
- `.pnpm-needs-build` is a transient marker that can be removed after successful build/patch.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[316-319]

### What to change
- Adjust the completeness census to exclude transient markers like `crate::NEEDS_BUILD_MARKER` (similar to `marker_file`’s exclusion), e.g.:
 - `cas_paths.keys().filter(|k| k.as_str() != crate::NEEDS_BUILD_MARKER).all(...)`
- (Optional hardening) If you want to be conservative, explicitly accept both “marker present” and “marker absent” outcomes for `.pnpm-needs-build` while still requiring the real completion marker (`marker_present(...)`).
- Add a regression test that simulates an occupied slot where the only missing expected entry is `.pnpm-needs-build` (because another process already finished build/patch) and asserts the `safe_to_skip` branch does **not** fall through to destructive swap.

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


2. safe_to_skip gated by nm_moved ✗ Dismissed 🐞 Bug ☼ Reliability
Description
stage_and_swap() only takes the non-destructive safe_to_skip rename path when nm_moved is
false; when keep_modules_dir causes node_modules/ to be moved aside (nm_moved=true), the code
falls through to the destructive remove_dir_all(dir_path) swap even in GVS mode, reintroducing the
concurrent-writer race the PR aims to eliminate for shared slots.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R447-450]

+    if safe_to_skip && !nm_moved {
+        match fs::rename(&stage, dir_path) {
+            Ok(()) => return Ok(()),
+            Err(error) if is_occupied_target(&error) && is_complete_import(dir_path, cas_paths) => {
Relevance

●●● Strong

Reliability bug aligned with PR’s stated goal (avoid destructive swap races in shared GVS slots).

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
GVS imports set safe_to_skip and, for interrupted builds, also set keep_modules_dir=true;
stage_and_swap moves dir_path/node_modules into staging (making nm_moved=true) and then gates
the new non-destructive branch on !nm_moved, so it can still fall through to
remove_dir_all(dir_path) in GVS mode.

pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs[149-175]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[389-429]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[447-467]

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 concurrency-safe path (`safe_to_skip`) is disabled when `nm_moved` is true. In GVS mode, interrupted-build imports set `keep_modules_dir=true`, and if `dir_path/node_modules` exists it will be moved (`nm_moved=true`), which bypasses `safe_to_skip` and can still hit `remove_dir_all(dir_path)`.

This leaves a real execution path where GVS slots can still be destructively removed mid-import under concurrency (the failure mode this PR is explicitly trying to remove).

### Issue Context
- `CreateVirtualDirBySnapshot` enables `safe_to_skip` for all GVS imports, including interrupted-build recovery where `keep_modules_dir=true`.
- `stage_and_swap` currently requires `safe_to_skip && !nm_moved` to take the non-destructive path.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs[166-175]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[412-429]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[447-467]

### Implementation directions
Choose one:
1) Extend the `safe_to_skip` branch to handle `nm_moved=true` safely:
  - Attempt `rename(stage, dir_path)` first (or after staging) without permanently altering the live `dir_path`.
  - If the target is occupied and complete, restore any moved `node_modules` back to `dir_path/node_modules` and then delete the staging dir; return `Ok(())`.
  - Ensure restoration is best-effort but does not silently lose the preserved `node_modules`.

2) Reorder logic so the safe-to-skip occupancy check happens before moving `node_modules` out of the live directory, to avoid perturbing a directory you might ultimately decide to keep.

Add/adjust a regression test that simulates an interrupted build (`keep_modules_dir=true`) concurrent with another completed importer and asserts the path does not do a destructive `remove_dir_all` on the live slot.

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



Remediation recommended

3. PermissionDenied misread occupied 🐞 Bug ☼ Reliability ⭐ New
Description
is_occupied_target() treats PermissionDenied as “destination occupied” on all platforms, but on
Unix this commonly represents a real permission/FS failure. In the new safe_to_skip path this can
convert a failed rename(stage, dir_path) into a silent success when the destination merely appears
complete, masking real I/O faults.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R286-292]

+fn is_occupied_target(error: &io::Error) -> bool {
+    matches!(
+        error.kind(),
+        io::ErrorKind::DirectoryNotEmpty
+            | io::ErrorKind::AlreadyExists
+            | io::ErrorKind::PermissionDenied,
+    )
Relevance

●● Moderate

Team has precedent rejecting propagation of some filesystem/permission cleanup errors; could view
this as acceptable tradeoff.

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new helper is_occupied_target() explicitly includes PermissionDenied, and the new
safe_to_skip branch uses it to treat a rename failure as success when the destination looks
complete. On non-Windows platforms, PermissionDenied can indicate real access errors rather than
an occupied destination, so the success path can incorrectly suppress the error.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[280-293]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[442-472]

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

### Issue description
`is_occupied_target()` currently treats `io::ErrorKind::PermissionDenied` as an “occupied target” signal on every OS. That mapping is intended for Windows rename semantics, but on Unix it can indicate genuine permission/filesystem problems. In the `safe_to_skip` branch, this can cause `stage_and_swap()` to return `Ok(())` after a real rename failure, hiding the underlying issue.

### Issue Context
The new `safe_to_skip` logic uses `is_occupied_target(err)` to decide whether an `fs::rename(stage, dir_path)` failure means “someone else won the race” and should be treated as success.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[280-293]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[462-472]

### Suggested fix
- Make `PermissionDenied` count as “occupied” only on Windows (or when the OS error code matches the specific Windows rename-to-existing-dir case).
 - Example approach:
   - `DirectoryNotEmpty | AlreadyExists` => occupied on all platforms.
   - `PermissionDenied` => occupied only under `cfg(windows)`.
- (Optional) Add a Unix-only regression test that forces `fs::rename(stage, dir_path)` to fail with `PermissionDenied` (e.g., by making the parent dir non-writable) and assert the importer returns an error rather than succeeding via `safe_to_skip` when the target happens to look complete.

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


4. @pnpm/napi changeset despite private 📘 Rule violation § Compliance
Description
A new changeset declares a @pnpm/napi minor bump, but pnpm/npm/napi/package.json marks the
package as private: true, so it is not a published TypeScript package. This violates the
requirement to only create changesets for published package changes and to avoid listing unaffected
packages.
Code

.changeset/napi-global-virtual-store.md[R1-2]

+---
+"@pnpm/napi": minor
Relevance

●●● Strong

Team has accepted removing unaffected packages from changesets to match what’s actually released.

PR-#13090

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713441 requires changesets only when published TypeScript packages are affected and
warns against changesets listing unaffected packages. The new changeset targets @pnpm/napi, but
the package is marked private: true, indicating it is not published.

Rule 713441: Require changeset for TypeScript package changes
.changeset/napi-global-virtual-store.md[1-3]
pnpm/npm/napi/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 PR adds a changeset for `@pnpm/napi`, but that package is currently marked `private: true`, so it is not a published TypeScript package. Per compliance, changesets should correspond to published package releases, and should not list packages that cannot be released.

## Issue Context
- New changeset: `.changeset/napi-global-virtual-store.md` declares `"@pnpm/napi": minor`.
- Package metadata: `pnpm/npm/napi/package.json` has `"private": true`.

## Fix Focus Areas
- .changeset/napi-global-virtual-store.md[1-3]
- pnpm/npm/napi/package.json[1-6]

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


5. Before safe_to_skip comment 📘 Rule violation ⚙ Maintainability
Description
A new doc comment uses historical phrasing (Before safe_to_skip), which is disallowed because
comments must describe current behavior rather than prior implementations. This increases the risk
of comments becoming stale or misleading over time.
Code

pnpm/crates/package-manager/src/import_indexed_dir/tests.rs[R687-689]

+/// A shared content-addressed slot that another process is still populating must not be torn
+/// down. Before `safe_to_skip`, the swap `remove_dir_all`'d the live directory and surfaced the
+/// concurrent writer's leftovers as `RemoveExisting` ("Directory not empty").
Relevance

●●● Strong

Team has accepted removing historical/refactor phrasing from doc comments in favor of current
behavior.

PR-#13624

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The added test comment explicitly references past behavior using Before safe_to_skip, which the
checklist forbids for inline comments/docstrings.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/package-manager/src/import_indexed_dir/tests.rs[687-689]

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

## Issue description
A newly added comment uses historical phrasing (`Before ...`), which violates the rule that comments must describe current behavior rather than past implementations.

## Issue Context
The comment is attached to a new test for `safe_to_skip` behavior and can be rewritten to describe the current invariant and the rationale without referencing the previous implementation.

## Fix Focus Areas
- pnpm/crates/package-manager/src/import_indexed_dir/tests.rs[687-689]

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


View more (7)
6. Redundant staging on skip 🐞 Bug ➹ Performance
Description
stage_and_swap() still fully populates the staging directory before discovering (via the new
safe_to_skip branch) that the destination slot is already complete and will be kept, so the losing
concurrent importer can do all the I/O work and then discard it. Under GVS contention this creates
avoidable hardlink/copy work per losing process and can measurably increase install time on large
packages.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R462-468]

+    if safe_to_skip && !nm_moved {
+        match fs::rename(&stage, dir_path) {
+            Ok(()) => return Ok(()),
+            Err(error) if is_occupied_target(&error) && is_complete_import(dir_path, cas_paths) => {
+                let _ = fs::remove_dir_all(&stage);
+                return Ok(());
+            }
Relevance

●● Moderate

Perf win but needs reordering staging logic; no close precedent on skipping staging under
contention.

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new safe_to_skip short-circuit happens only after step (1) has already populated stage, so
the optimization avoids destructive swapping but not the expensive staging work.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[387-393]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[462-471]
pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs[166-176]

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

### Issue description
With `safe_to_skip` enabled, `stage_and_swap()` can return success while keeping an already-complete destination slot, but only *after* it has already populated a full staging tree. This causes redundant staging work under contention.

### Issue Context
The new `safe_to_skip` behavior is meant for shared, content-addressed GVS slots where concurrent importers are expected.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[442-474]

### Suggested fix
1. Add an early fast-path near the start of `stage_and_swap()`:
  - If `safe_to_skip` is true (and the slot shape implies it’s safe), check `is_complete_import(dir_path, cas_paths)` **before** calling `populate_dir(..., &stage, ...)`.
  - If complete, return `Ok(())` immediately (optionally best-effort cleanup of any preexisting stage path if your stage naming can collide).
2. Keep the existing post-staging `rename`/occupied-target logic as a race-safe fallback (the destination may transition from incomplete→complete during the call).

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


7. File tarballs routed local ⊘ Outdated 🐞 Bug ➹ Performance
Description
VirtualStoreLayout now decides which snapshots stay in the project-local store under GVS via
directory_keys, but it populates that set using is_local_directory(), which returns true for any
file: snapshot when packages metadata lacks a version even if the lockfile resolution is not
Directory (e.g. a local tarball). This can silently prevent global-store sharing/dedup for file:
tarball dependencies and make routing depend on metadata completeness.
Code

pnpm/crates/deps-restorer/src/virtual_store_layout.rs[R300-306]

+        let directory_keys = snapshots
+            .keys()
+            .filter(|key| {
+                let metadata_key = key.without_peer();
+                is_local_directory(
+                    packages.and_then(|packages| packages.get(&metadata_key)),
+                    &key.suffix,
Relevance

●● Moderate

Subtle GVS routing semantics; repo has mixed precedent on tightening file: tarball handling vs
conservative fallbacks.

PR-#13170
PR-#13349

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
directory_keys is built from snapshots.keys() using is_local_directory(...), and routing uses
directory_keys to decide whether a snapshot’s slot lives under the project-local store. However,
is_local_directory(...) can return true for non-Directory resolutions when metadata.version is
missing and the snapshot key is file: (VersionPart::File), so those non-directory file:
snapshots can be routed locally too.

pnpm/crates/deps-restorer/src/virtual_store_layout.rs[293-310]
pnpm/crates/deps-restorer/src/virtual_store_layout.rs[542-566]
pnpm/crates/deps-restorer/src/virtual_store_layout.rs[379-386]

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

## Issue description
`directory_keys` is computed using `is_local_directory(...)`, but that predicate can classify non-directory `file:` resolutions (e.g. tarball resolutions with missing/partial metadata) as “directory-like”. Those keys are then routed to the project-local virtual store under GVS, reducing sharing and making layout depend on whether `packages.version` was present.

## Issue Context
- The new behavior intends to keep **directory resolutions** local under GVS.
- Current code uses `is_local_directory(...)` (which has fallback behavior for missing metadata) to decide routing.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/virtual_store_layout.rs[293-310]
- pnpm/crates/deps-restorer/src/virtual_store_layout.rs[542-566]

### Suggested fix approach
- Introduce a routing-specific predicate (e.g. `is_directory_resolution_for_routing(metadata, suffix)`) that:
 - Returns `true` when `metadata.resolution` is `LockfileResolution::Directory(_)`.
 - Only falls back to `VersionPart::File(_)` when metadata is actually missing (if you still want the conservative behavior for pruned lockfiles).
- Use that predicate for `directory_keys` and `store_root_for`/`slot_dir` routing decisions.
- Add a regression test covering a `file:` **tarball** resolution with missing/None `packages.version` and assert it does **not** get routed to `local_store_dir` under GVS (unless you explicitly want that behavior).

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


8. Overlay cache key noncanonical 🐞 Bug ➹ Performance
Description
ConfigOverlay now includes IndexMap fields (package_extensions / patched_dependencies) but
the intern key hashes format!("{overlay:?}"), so semantically identical overlays with different
insertion orders can miss the cache and leak additional &'static Config entries in long-lived
embedders.
Code

pnpm/crates/napi/src/config.rs[77]

+    pub package_extensions: Option<IndexMap<String, PackageExtension>>,
Relevance

●● Moderate

Cache-key canonicalization changes are subtle; similar interned-config-cache refactor concerns were
previously rejected.

PR-#13513

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new ConfigOverlay fields are IndexMaps, while cache_key() hashes the overlay’s Debug
output and explicitly relies on ordered map iteration for stability; IndexMap ordering is
insertion-order, not key-order, so equivalent overlays can produce different Debug strings and
different cache keys.

pnpm/crates/napi/src/config.rs[62-81]
pnpm/crates/napi/src/config.rs[163-173]

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

### Issue description
`cache_key()` hashes `format!("{overlay:?}")`, which is only stable if every map-like field has canonical iteration order. The newly added overlay fields `package_extensions` / `patched_dependencies` are `IndexMap`s, whose iteration order depends on insertion order, so logically equivalent overlays can hash differently and cause avoidable config-cache misses and retained leaked configs.

### Issue Context
This is specifically a problem for the new Node API capabilities (`packageExtensions`, `patchedDependencies`) introduced by this PR: callers are likely to build these maps dynamically and not guarantee insertion order stability across calls.

### Fix Focus Areas
- pnpm/crates/napi/src/config.rs[62-81]
- pnpm/crates/napi/src/config.rs[163-173]

### Implementation directions
- Make the cache key independent of `IndexMap` insertion order by hashing a canonical representation (e.g., clone into `BTreeMap`/sorted vec of `(k,v)` before hashing) for `package_extensions` and `patched_dependencies` (and any other `IndexMap` fields included in the overlay).
- Alternatively, stop using `Debug` as the key material and implement a deterministic key builder (hash each field; for maps hash entries in sorted-key order).

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


9. Relative patch path misresolved 🐞 Bug ≡ Correctness
Description
NAPI build_config() rewrites patchedDependencies entries to dir.join(path) strings, but later
Config::patched_dependency_hashes() resolves any non-absolute patch path by joining it against
workspace_dir again. If InstallOptions.dir is relative, this double-prefixes the patch path
(e.g. proj/proj/patches/x.patch) and patch hashing/applying can fail or target the wrong file.
Code

pnpm/crates/napi/src/config.rs[R315-318]

+        config.patched_dependencies = Some(
+            patched_dependencies
+                .iter()
+                .map(|(key, path)| (key.clone(), dir.join(path).display().to_string()))
Relevance

●● Moderate

Looks like a real path-resolution bug, but no clear precedent; depends on whether dir can be
relative.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
NAPI rewrites patch paths by stringifying dir.join(path), and later the config’s patch-hash logic
treats any non-absolute string as relative and joins it again against workspace_dir. If dir is
relative, the stored patch path remains relative and gets prefixed twice.

pnpm/crates/napi/src/config.rs[303-324]
pnpm/crates/config/src/lib.rs[2180-2196]

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

## Issue description
NAPI rewrites patch paths by prefixing them with `dir.join(...)` and also sets `config.workspace_dir = dir` when absent. Downstream patch resolution joins relative paths against `workspace_dir` again, so a relative `dir` causes incorrect doubled paths.

## Issue Context
This affects NAPI callers that pass `InstallOptions.dir` as a relative path (which is currently accepted) and provide relative `patchedDependencies` paths.

## Fix Focus Areas
- pnpm/crates/napi/src/config.rs[309-324]
- pnpm/crates/config/src/lib.rs[2180-2196]

## Implementation notes
- Ensure `dir` is made absolute (or canonicalized) once before rewriting patch paths, so `dir.join(rel)` becomes absolute and will not be re-anchored later.
- Alternatively, stop pre-joining here: keep the raw `patchedDependencies` strings and set `workspace_dir` appropriately, letting the existing resolver do the single join.
- Add a regression test for NAPI with relative `dir` + relative patch path.

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


10. Relative GVS dir unanchored 🐞 Bug ⛨ Security
Description
NAPI accepts globalVirtualStoreDir as a raw string and stores it as a PathBuf without resolving
relative paths against the install/workspace directory. This diverges from workspace-yaml behavior
(which resolves against base_dir) and can cause materialization to occur relative to the Node
process CWD, potentially writing into unintended locations.
Code

pnpm/crates/napi/src/install.rs[R575-577]

+        enable_global_virtual_store: options.enable_global_virtual_store,
+        global_virtual_store_dir: options.global_virtual_store_dir.as_ref().map(PathBuf::from),
+        package_extensions: options.package_extensions.as_ref().map(|extensions| {
Relevance

●● Moderate

Potentially important path-anchoring/security behavior, but could be intentional API contract; no
matching precedent found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
NAPI constructs global_virtual_store_dir directly from the provided string and later copies it
into config.global_virtual_store_dir as-is. In contrast, workspace-yaml resolves that setting
relative to the yaml/base directory, showing the intended anchoring behavior.

pnpm/crates/napi/src/install.rs[557-577]
pnpm/crates/napi/src/config.rs[448-463]
pnpm/crates/config/src/workspace_yaml.rs[1101-1106]

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

## Issue description
`globalVirtualStoreDir` coming from the NAPI overlay is not anchored when relative, so later filesystem operations interpret it relative to process CWD rather than the install/workspace root. This is inconsistent with `pnpm-workspace.yaml` semantics and can lead to writes in unexpected directories.

## Issue Context
Workspace YAML applies `resolve(base_dir, value)` for `globalVirtualStoreDir`, while NAPI currently uses `PathBuf::from(value)`.

## Fix Focus Areas
- pnpm/crates/napi/src/install.rs[557-577]
- pnpm/crates/napi/src/config.rs[448-463]
- pnpm/crates/config/src/workspace_yaml.rs[1101-1106]

## Implementation notes
- If `globalVirtualStoreDir` is relative, resolve it against the install dir (or the effective workspace dir) before storing it in the overlay/config.
- Alternatively, reject relative values at the NAPI boundary with a clear error message.
- Add a regression test covering a relative `globalVirtualStoreDir` with a non-CWD `dir`.

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


11. O(n) exists checks 🐞 Bug ➹ Performance
Description
When safe_to_skip is enabled and the target directory is already occupied, stage_and_swap()
calls all_files_match() which does an exists() check for every CAS entry. Under GVS contention
this can add thousands of metadata syscalls per conflicting package, increasing install latency on
large packages/slow filesystems.
Code

pnpm/crates/package-manager/src/import_indexed_dir.rs[R302-304]

+fn all_files_match(dir_path: &Path, cas_paths: &HashMap<String, PathBuf>) -> bool {
+    cas_paths.keys().all(|entry| dir_path.join(entry).exists())
+}
Relevance

●● Moderate

Perf tweak plausible, but team has rejected similar FS-overhead optimizations without strong need.

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
all_files_match() performs one exists() per CAS entry, and stage_and_swap() calls it on
occupied-target rename failures under safe_to_skip. The same file documents that the marker is
placed last, which enables a constant-time completion check for packages that include package.json
(the common marker).

pnpm/crates/package-manager/src/import_indexed_dir.rs[297-304]
pnpm/crates/package-manager/src/import_indexed_dir.rs[428-434]
pnpm/crates/package-manager/src/import_indexed_dir.rs[234-237]

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

### Issue description
`safe_to_skip`’s occupied-target branch verifies completeness by calling `all_files_match()`, which stats every expected file. This is expensive under the exact workload `safe_to_skip` targets (concurrent imports).

### Issue Context
The importer already has a completion-marker concept: it links every other file first and places the marker last, so marker presence is a strong completion signal for the common case where `package.json` exists.

### Fix Focus Areas
- pnpm/crates/package-manager/src/import_indexed_dir.rs[297-304]
- pnpm/crates/package-manager/src/import_indexed_dir.rs[428-434]

### Suggested fix
In the `safe_to_skip` occupied-target check, prefer an O(1) completion test when possible:
- If `cas_paths` contains `package.json` (very common), treat `dir_path/package.json` existence as “complete” (since `marker_file()` selects it, and it’s placed last).
- Otherwise (legacy/no-package-json cases where other implementations may choose a different marker), fall back to the current `all_files_match()` scan to preserve interoperability.

This keeps correctness while removing the per-file stat loop from the common contention case.

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


12. Directory deps bypass GVS 📘 Rule violation ⌂ Architecture
Description
The PR changes global-virtual-store behavior so LockfileResolution::Directory snapshots are routed
to the project-local virtual store instead of the global store, which diverges from pnpm v11’s
documented/tested behavior. This creates a cross-stack compatibility gap where pnpm and pacquet
place the same dependency type in different on-disk locations under GVS.
Code

pnpm/crates/package-manager/src/virtual_store_layout.rs[R363-366]

+        if let Some(local_store_dir) = &self.local_store_dir
+            && self.directory_keys.contains(key)
+        {
+            return local_store_dir
Relevance

●● Moderate

User-visible layout parity concerns are taken seriously, but directory deps rationale may outweigh
strict v11 matching.

PR-#13464

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The Rust implementation now routes directory snapshots to local_store_dir under GVS, which is a
user-visible on-disk layout/behavior change. Pnpm v11’s tests assert that a file:dep directory
dependency under GVS resolves to a path inside globalVirtualStoreDir, demonstrating a cross-stack
mismatch.

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
Rule 713429: Pacquet must not introduce new user-visible behavior beyond pnpm
pnpm/crates/package-manager/src/virtual_store_layout.rs[360-368]
pnpm11/installing/deps-installer/test/install/globalVirtualStore.ts[542-571]

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

## Issue description
Pacquet now routes directory-resolved dependencies to the project-local virtual store even when `enable_global_virtual_store` is enabled. Pnpm v11’s tests assert that `file:` directory dependencies live in the global virtual store under GVS, so this PR introduces an observable divergence between the stacks.

## Issue Context
- Rust change: `VirtualStoreLayout::slot_dir()` returns a project-local slot for keys classified as directory resolutions.
- TypeScript (pnpm v11) behavior: tests assert `node_modules/dep` resolves into `globalVirtualStoreDir` when GVS is enabled.
- Compliance requires cross-stack user-visible behavior changes to be kept in sync, or explicitly called out with a port/alignment plan.

## Fix Focus Areas
- pnpm/crates/package-manager/src/virtual_store_layout.rs[360-368]
- pnpm/crates/package-manager/src/validate_lockfile_paths.rs[37-44]
- pnpm11/installing/deps-installer/test/install/globalVirtualStore.ts[542-571]

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



Informational

13. Extra directory-key pass ⊘ Outdated 🐞 Bug ➹ Performance
Description
VirtualStoreLayout::new() now makes an additional full pass over snapshots.keys() to compute
directory_keys after it already iterated snapshots to compute gvs_suffixes. This adds avoidable
O(n) traversal (and repeated metadata predicate work) to every GVS-enabled layout construction on
large lockfiles.
Code

pnpm/crates/deps-restorer/src/virtual_store_layout.rs[R300-304]

+        let directory_keys = snapshots
+            .keys()
+            .filter(|key| {
+                let metadata_key = key.without_peer();
+                is_local_directory(
Relevance

●● Moderate

Team has mixed history on extra-pass optimizations; similar “avoid redundant traversal” was rejected
elsewhere.

PR-#13141
PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The file shows one full iteration building gvs_suffixes followed by a second full scan of
snapshots.keys() to compute directory_keys.

pnpm/crates/deps-restorer/src/virtual_store_layout.rs[257-292]
pnpm/crates/deps-restorer/src/virtual_store_layout.rs[293-310]

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

### Issue description
`VirtualStoreLayout::new()` performs two passes over the snapshot set: one to build `gvs_suffixes`, then another to classify directory-resolved snapshots into `directory_keys`. The second traversal is avoidable overhead in large workspaces.

### Issue Context
The `directory_keys` set is needed for per-key routing (`slot_dir`, `store_root_for`, `is_shared_slot`), but the *separate full traversal* can be folded into the existing iteration.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/virtual_store_layout.rs[293-310]

### Suggested fix
During the existing `for (snapshot_key, ...) in in_lockfile_order(snapshots)` loop that builds `gvs_suffixes`, also compute whether that `snapshot_key` is directory-resolved (using the same `metadata_key = snapshot_key.without_peer()` + `is_local_directory(...)` predicate) and insert into `directory_keys` then. This removes the second `snapshots.keys()` pass while preserving the set’s semantics.

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


14. Stage cleanup errors ignored 🐞 Bug ☼ Reliability
Description
In the new safe_to_skip occupied-target success path, errors from remove_dir_all(stage) are
ignored, so failed cleanup can silently leak large staging directories (disk bloat / degraded future
installs), especially on platforms with transient file locks.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R454-456]

+            Err(error) if is_occupied_target(&error) && is_complete_import(dir_path, cas_paths) => {
+                let _ = fs::remove_dir_all(&stage);
+                return Ok(());
Relevance

● Weak

Repo precedent prefers best-effort cleanup; propagating marker-removal failures was explicitly
rejected.

PR-#13170

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new occupied-target success branch explicitly discards the remove_dir_all(stage) result, so
cleanup failure can’t be observed by callers and the staged directory can remain on disk
indefinitely.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[451-456]

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

### Issue description
When `safe_to_skip` decides to accept the already-present destination, the staged directory is deleted with `let _ = fs::remove_dir_all(&stage);` and any error is dropped. If deletion fails (e.g., transient locks), the install still returns success and the staged tree is left behind.

### Issue Context
This branch is expected to run under contention (multiple processes importing the same GVS slot), so even rare cleanup failures can accumulate.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[454-456]

### What to change
- Don’t drop the error silently. Options:
 - Log a `tracing::warn!` with `stage` and the error on failure, or
 - Retry deletion a few times (particularly for Windows), or
 - Propagate a typed error if leaking staged trees is unacceptable.
- If you choose “warn only”, consider including guidance in the log message for how to clean up stale stage dirs safely.

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


15. GVS slot trust bypass 🐞 Bug ⛨ Security
Description
With safe_to_skip enabled, stage_and_swap() treats an occupied destination as valid if each
expected path merely exists(), which follows symlinks and does not validate file type or content.
If an attacker (or untrusted process) can write to the shared global virtual store root, they can
pre-create a slot with the right filenames but poisoned/symlinked contents and have installs accept
it unchanged.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R430-433]

+        match fs::rename(&stage, dir_path) {
+            Ok(()) => return Ok(()),
+            Err(error) if is_occupied_target(&error) && all_files_match(dir_path, cas_paths) => {
+                let _ = fs::remove_dir_all(&stage);
Relevance

● Weak

Closely matching prior security hardening around symlink-following existence checks in slot
validation was rejected.

PR-#13151

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The safe_to_skip branch returns Ok(()) without swapping the staged tree into place when the
destination looks “complete”. Completeness is determined by all_files_match() using
Path::exists(), which follows symlinks and only checks pathname presence, so a poisoned/symlinked
destination can satisfy the predicate and be reused.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[280-303]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[414-440]

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

## Issue description
When `ImportIndexedDirOpts.safe_to_skip` is set, `stage_and_swap()` may return success without replacing the destination directory, based solely on `all_files_match()` using `Path::exists()`. This can accept a pre-existing directory whose entries are symlinks or poisoned files, which is unsafe for a shared/writable global virtual store.

## Issue Context
`all_files_match()` currently checks only path existence and does not reject symlinks/reparse points or validate a completion marker; in the `safe_to_skip` branch this causes the existing slot to “win” permanently.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[280-303]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[414-440]

## Implementation notes
- Tighten the “occupied-but-complete” acceptance criteria to be symlink-resistant:
 - Use `symlink_metadata` (not `exists`) for each expected entry.
 - Reject if any expected entry is a symlink/reparse-point (platform-specific) or otherwise not the expected type.
 - Also require the completion marker to be present (or an equivalent strong invariant) before skipping.
- If the destination fails validation, fall through to the repairing destructive swap (current behavior).

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


View more (1)
16. Changeset missing pnpm bump 📘 Rule violation § Compliance
Description
The newly added changesets only declare a pacquet bump and omit the required pnpm package entry.
This can cause the release tooling to miss or misclassify the pnpm version bump for these
user-visible changes.
Code

.changeset/gvs-concurrent-slot-import.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

● Weak

Same “add pnpm bump to pacquet-only changeset” suggestion repeatedly rejected in recent PRs.

PR-#13545
PR-#13587
PR-#13459

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changesets to include an explicit pnpm entry with a correct bump
type. Both added changeset files include only "pacquet": patch in the front-matter and have no
pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/gvs-concurrent-slot-import.md[1-3]
.changeset/gvs-directory-resolutions-stay-local.md[1-3]

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 two new changeset files are missing a `pnpm` entry in their front-matter; they currently only specify `pacquet`.

## Issue Context
Compliance requires every new/modified changeset to explicitly include the `pnpm` package with an appropriate bump type (`patch`/`minor`/`major`). These changesets introduce user-visible behavior changes (store layout / Node API reachability) and should be represented in pnpm's release metadata.

## Fix Focus Areas
- .changeset/gvs-concurrent-slot-import.md[1-3]
- .changeset/gvs-directory-resolutions-stay-local.md[1-3]

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


Grey Divider

Context used
✅ Compliance rules (platform): 24 rules

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings August 4, 2026 20:12
@zkochan
zkochan force-pushed the gvs-embedder-and-concurrency branch from a042485 to af385fc Compare August 4, 2026 20:12

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 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: 8

Caution

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

⚠️ Outside diff range comments (1)
pnpm/crates/package-manager/src/import_indexed_dir.rs (1)

394-438: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Run the non-destructive check before preserving node_modules.

When keep_modules_dir is true, Lines 395-408 move the live node_modules into staging. That sets nm_moved, so Lines 428-438 bypass the safe branch. pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs passes both flags for interrupted global-store imports. A completed shared slot with dependencies is still dismantled and replaced, so concurrent readers can lose its node_modules.

Try the occupied-target check before moving target_modules. Preserve node_modules only after the target is known incomplete. Add coverage for safe_to_skip: true, keep_modules_dir: true, and a completed target with nested dependencies.

🤖 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/import_indexed_dir.rs` around lines 394 -
438, Reorder the import flow so the safe-to-skip occupied-target check runs
before the `nm_moved`/`node_modules` preservation block. For `safe_to_skip` with
a completed target confirmed by `all_files_match`, discard staging and return
without moving or removing `target_modules`; only preserve `node_modules` when
the target is incomplete and the destructive swap is required. Add coverage for
`safe_to_skip: true`, `keep_modules_dir: true`, and a completed target
containing nested dependencies.
🧹 Nitpick comments (3)
pnpm/crates/package-manager/src/virtual_store_layout/tests.rs (1)

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

Remove assertion-narrating comments.

The comments on Line 572 and Line 582 only restate the adjacent assertions. Keep the test-level doc comment because it records the cross-project routing invariant.

Proposed cleanup
-    // Each project keeps its own copy of the injected directory, under its own store.
     assert_ne!(dir_in_a, dir_in_b);
@@
-    // The registry dependency is unaffected: same shared slot for both projects.
     assert_eq!(registry_in_a, registry_in_b);

As per coding guidelines, comments must explain non-obvious invariants instead of narrating code. As per path instructions, document only non-obvious reasons or invariants.

Also applies to: 582-582

🤖 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/virtual_store_layout/tests.rs` at line 572,
Remove the assertion-narrating comments adjacent to the assertions at the
referenced locations in the test. Preserve the test-level documentation comment
describing the cross-project routing invariant, and leave the assertions and
test behavior unchanged.

Sources: Coding guidelines, Path instructions

.changeset/gvs-directory-resolutions-stay-local.md (1)

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

Keep the changeset user-facing.

Line 7 describes hash scoping and module-resolution internals. Remove that rationale from the release note. Keep a concise statement that directory resolutions remain local and registry resolutions remain shared.

As per coding guidelines, changesets must describe user-visible behavior. Based on learnings, keep implementation rationale outside Changeset entries.

🤖 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 @.changeset/gvs-directory-resolutions-stay-local.md at line 7, Update the
changeset entry to remove the internal rationale about hash scoping, global
virtual stores, and module-resolution paths. Keep only a concise user-facing
statement that directory resolutions remain local while registry resolutions
remain shared.

Sources: Coding guidelines, Path instructions, Learnings

pnpm/crates/package-manager/src/virtual_store_layout.rs (1)

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

Correct the package_store_dir documentation contract.

Directory slots can now live under local_store_dir, but the existing package_store_dir field and accessor documentation say that this path contains every snapshot slot. Describe it as the default slot root, which is global only in GVS mode. Direct per-slot callers to store_root_for.

As per coding guidelines, comments must explain non-obvious invariants. As per path instructions, document hidden path and compatibility invariants.

🤖 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/virtual_store_layout.rs` around lines 71 -
94, Update the documentation for the package_store_dir field and its accessor to
describe it as the default snapshot-slot root, global only when GVS is enabled,
rather than claiming it contains every slot. Explain that directory-resolved
slots may use local_store_dir, and direct per-slot callers to store_root_for.
Preserve comments documenting the hidden path and compatibility invariants.

Sources: Coding guidelines, Path instructions

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

Inline comments:
In @.changeset/gvs-concurrent-slot-import.md:
- Around line 5-7: Rewrite the changeset description to state only the
user-visible fix: concurrent global virtual-store imports no longer fail or
temporarily remove shared package slots. Remove implementation details about
directory removal, staging, content-addressed paths, and pnpm internals.

In @.changeset/gvs-directory-resolutions-stay-local.md:
- Around line 1-2: Add a separate changeset entry for the published package
"pnpm/napi" with a minor version bump, while retaining the existing "pacquet"
patch entry for the Rust-only routing fix. Ensure the changeset names both
affected packages with their required bump levels.

In `@pnpm/crates/napi/src/install/tests.rs`:
- Around line 534-537: Extend the tests around build_overlay() and
build_config() with focused cases for enableGlobalVirtualStore,
globalVirtualStoreDir, packageExtensions, and patchedDependencies. Verify
shared-store path derivation/pinning, package-extension conversion, relative
patch paths anchored to the install dir, and workspace_dir set when no workspace
manifest exists; replace or supplement the current all-None fixture values with
targeted assertions for each behavior.

In `@pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs`:
- Around line 166-175: Derive safe_to_skip in the import-options setup around
ImportIndexedDirOpts from whether the per-snapshot resolution uses the global
store, rather than directly from layout.enable_global_virtual_store(). Ensure
local_store_dir imports cannot skip replacement when source bytes change, while
preserving skip behavior for the per-snapshot global-store route. Add a
regression test covering global mode, a directory dependency with unchanged
filenames, and changed source bytes.

In `@pnpm/crates/package-manager/src/import_indexed_dir.rs`:
- Around line 431-433: Update the occupied-target branch in importIndexedDir to
handle errors from fs::remove_dir_all(&stage) instead of discarding them.
Propagate a contextual ImportIndexedDirError when staging cleanup fails, while
preserving Ok(()) only when cleanup succeeds.

In `@pnpm/crates/package-manager/src/validate_lockfile_paths.rs`:
- Around line 40-43: Add tests in validate_lockfile_paths/tests.rs covering
validate_virtual_store_slot_containment with LockfileResolution::Directory
snapshots under GVS: verify an injected local directory slot within the
project-local store passes, and a crafted directory slot escaping its selected
route fails. Reuse the existing lockfile path fixtures and assertions for
regular containment and GVS escape cases.

In `@pnpm/npm/napi/index.d.ts`:
- Around line 142-146: Correct the mixed virtual-store contract across
pnpm/npm/napi/index.d.ts lines 142-146, pnpm/npm/napi/index.d.ts lines 421-427,
and pnpm/crates/napi/src/read_config.rs lines 62-70: document that shared-store
placement applies only to global-eligible snapshots, while directory-resolved
snapshots remain project-local; scope the virtual-store path field accordingly
or expose both roots, and keep the Rust read_config contract aligned with the
TypeScript declaration.
- Around line 107-112: Extend the NAPI PackageExtension type to expose
peerDependenciesMeta, then update the object conversion and build_overlay in
install.rs to map it into pacquet_config::PackageExtension instead of always
setting peer_dependencies_meta to None. Add an install test covering propagation
of peer dependency metadata through the Node API configuration.

---

Outside diff comments:
In `@pnpm/crates/package-manager/src/import_indexed_dir.rs`:
- Around line 394-438: Reorder the import flow so the safe-to-skip
occupied-target check runs before the `nm_moved`/`node_modules` preservation
block. For `safe_to_skip` with a completed target confirmed by
`all_files_match`, discard staging and return without moving or removing
`target_modules`; only preserve `node_modules` when the target is incomplete and
the destructive swap is required. Add coverage for `safe_to_skip: true`,
`keep_modules_dir: true`, and a completed target containing nested dependencies.

---

Nitpick comments:
In @.changeset/gvs-directory-resolutions-stay-local.md:
- Line 7: Update the changeset entry to remove the internal rationale about hash
scoping, global virtual stores, and module-resolution paths. Keep only a concise
user-facing statement that directory resolutions remain local while registry
resolutions remain shared.

In `@pnpm/crates/package-manager/src/virtual_store_layout.rs`:
- Around line 71-94: Update the documentation for the package_store_dir field
and its accessor to describe it as the default snapshot-slot root, global only
when GVS is enabled, rather than claiming it contains every slot. Explain that
directory-resolved slots may use local_store_dir, and direct per-slot callers to
store_root_for. Preserve comments documenting the hidden path and compatibility
invariants.

In `@pnpm/crates/package-manager/src/virtual_store_layout/tests.rs`:
- Line 572: Remove the assertion-narrating comments adjacent to the assertions
at the referenced locations in the test. Preserve the test-level documentation
comment describing the cross-project routing invariant, and leave the assertions
and test behavior unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 743851ea-4152-4cdb-83f5-2ce852296ee8

📥 Commits

Reviewing files that changed from the base of the PR and between 0238477 and a042485.

📒 Files selected for processing (17)
  • .changeset/gvs-concurrent-slot-import.md
  • .changeset/gvs-directory-resolutions-stay-local.md
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/napi/src/config.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/napi/src/install/tests.rs
  • pnpm/crates/napi/src/read_config.rs
  • pnpm/crates/package-manager/src/build_modules.rs
  • pnpm/crates/package-manager/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/package-manager/src/import_indexed_dir.rs
  • pnpm/crates/package-manager/src/import_indexed_dir/tests.rs
  • pnpm/crates/package-manager/src/link_hoisted_modules.rs
  • pnpm/crates/package-manager/src/patch.rs
  • pnpm/crates/package-manager/src/validate_lockfile_paths.rs
  • pnpm/crates/package-manager/src/virtual_store_layout.rs
  • pnpm/crates/package-manager/src/virtual_store_layout/tests.rs
  • pnpm/npm/napi/index.d.ts

Comment thread pnpm/crates/napi/src/install/tests.rs Resolved
Comment thread pnpm/npm/napi/index.d.ts Resolved
Comment thread pnpm/npm/napi/index.d.ts Resolved
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.00     13.6±0.75ms    27.6 MB/sec    1.34     18.2±2.66ms    20.6 MB/sec
packument/parse                                  1.00     39.6±1.91µs  1675.9 MB/sec    1.22     48.1±7.77µs  1378.5 MB/sec
tarball/download_dependency                      1.23      3.0±0.35ms  1433.1 KB/sec    1.00      2.5±0.21ms  1760.6 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.00   232.1±23.29ms 68.9 KElem/sec    1.00   232.0±23.96ms 69.0 KElem/sec
workspace_resolution/hoist_heavy                 1.00   286.5±22.83ms        ? ?/sec    1.55   443.3±55.85ms        ? ?/sec

@qodo-code-review

Copy link
Copy Markdown

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings August 4, 2026 20:22
@zkochan
zkochan force-pushed the gvs-embedder-and-concurrency branch from af385fc to 67e7792 Compare August 4, 2026 20:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 67e7792

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
pnpm/crates/deps-restorer/src/build_modules.rs (1)

264-266: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document the newly public utility contracts.

Each function now has pub visibility but no Rustdoc contract.

  • pnpm/crates/deps-restorer/src/build_modules.rs#L264-L266: document the peer-suffix normalization guarantee.
  • pnpm/crates/deps-restorer/src/build_modules.rs#L1607-L1613: document leading-slash handling, last-@ splitting, and the empty-version result.
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs#L259-L267: document the mapping from PackageImportMethod to WireImportMethod.

As per coding guidelines, use Rustdoc comments for public API contracts.

🤖 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/deps-restorer/src/build_modules.rs` around lines 264 - 266,
Document the public utility contracts with Rustdoc comments at all three sites:
in pnpm/crates/deps-restorer/src/build_modules.rs:264-266, describe
normalize_build_dep_path’s peer-suffix normalization guarantee; in
pnpm/crates/deps-restorer/src/build_modules.rs:1607-1613, document leading-slash
handling, splitting at the last @, and the empty-version result; and in
pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs:259-267,
document the mapping from PackageImportMethod to WireImportMethod.

Sources: Coding guidelines, Path instructions

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

Inline comments:
In `@pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs`:
- Around line 166-174: Restrict safe_to_skip in the
create_virtual_dir_by_snapshot import flow to shared global-virtual-store
content-addressed slots: derive it per PackageKey only when a precomputed GVS
suffix exists and the key is not a directory dependency, rather than using
VirtualStoreLayout::enable_global_virtual_store() alone. Preserve project-local
handling for directory packages and add a regression covering changed directory
contents with an unchanged file list.

In `@pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs`:
- Around line 687-689: Update the test comment near the shared content-addressed
slot case to describe only the invariant that a slot being populated by another
process must not be torn down. Remove the references to safe_to_skip, the prior
remove_dir_all behavior, concurrent-writer leftovers, and the obsolete
“RemoveExisting” error.

In `@pnpm/crates/deps-restorer/src/virtual_store_layout.rs`:
- Around line 296-306: Update the directory_keys filter to reuse
is_local_directory(), so metadata-less file snapshots and entries marked
LockfileResolution::Directory are classified as project-local regardless of
whether packages is None or lacks the peer-stripped entry. Add a regression
covering snapshots: Some(...) with packages: None and verify the snapshot
remains in the local layout.

---

Outside diff comments:
In `@pnpm/crates/deps-restorer/src/build_modules.rs`:
- Around line 264-266: Document the public utility contracts with Rustdoc
comments at all three sites: in
pnpm/crates/deps-restorer/src/build_modules.rs:264-266, describe
normalize_build_dep_path’s peer-suffix normalization guarantee; in
pnpm/crates/deps-restorer/src/build_modules.rs:1607-1613, document leading-slash
handling, splitting at the last @, and the empty-version result; and in
pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs:259-267,
document the mapping from PackageImportMethod to WireImportMethod.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 76c0694c-1174-4d3d-95a0-56fbecc69e53

📥 Commits

Reviewing files that changed from the base of the PR and between a042485 and af385fc.

📒 Files selected for processing (17)
  • .changeset/gvs-concurrent-slot-import.md
  • .changeset/gvs-directory-resolutions-stay-local.md
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/crates/napi/src/config.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/napi/src/install/tests.rs
  • pnpm/crates/napi/src/read_config.rs
  • pnpm/crates/package-manager/src/patch.rs
  • pnpm/npm/napi/index.d.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/napi/src/install/tests.rs
  • pnpm/crates/package-manager/src/patch.rs
  • .changeset/gvs-directory-resolutions-stay-local.md
  • pnpm/npm/napi/index.d.ts
  • pnpm/crates/napi/src/config.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/napi/src/read_config.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/deps-restorer/src/import_indexed_dir/tests.rs`:
- Around line 691-724: Update
safe_to_skip_keeps_a_target_a_concurrent_importer_already_completed and its test
setup to run two import_indexed_dir calls concurrently against the same target,
synchronizing both at the swap point. Assert both imports succeed, the completed
target contents remain intact, and no staging directories remain; retain
coverage for the occupied completed-target interleaving rather than only
pre-populating the target before a single import.

In `@pnpm/crates/napi/src/read_config.rs`:
- Around line 65-71: Update the rustdoc for the public field virtual_store_dir
to state that <modules_dir>/.pnpm is its default value, while the actual path is
configurable through config.virtual_store_dir. Preserve the existing explanation
that local resolutions remain in this project-local store even when the global
virtual store is enabled.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d21d927a-7987-49f5-a975-399691d45b87

📥 Commits

Reviewing files that changed from the base of the PR and between af385fc and 67e7792.

📒 Files selected for processing (17)
  • .changeset/gvs-concurrent-slot-import.md
  • .changeset/gvs-directory-resolutions-stay-local.md
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/crates/napi/src/config.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/napi/src/install/tests.rs
  • pnpm/crates/napi/src/read_config.rs
  • pnpm/crates/package-manager/src/patch.rs
  • pnpm/npm/napi/index.d.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • pnpm/crates/package-manager/src/patch.rs
  • pnpm/crates/cli/src/cli_args/deploy.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • .changeset/gvs-directory-resolutions-stay-local.md
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/npm/napi/index.d.ts
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/napi/src/install.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/napi/src/install/tests.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/napi/src/config.rs

Comment thread pnpm/crates/napi/src/read_config.rs Resolved
Copilot AI review requested due to automatic review settings August 4, 2026 20:39
@zkochan
zkochan force-pushed the gvs-embedder-and-concurrency branch from 67e7792 to 3963d42 Compare August 4, 2026 20:39

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.

Copilot AI review requested due to automatic review settings August 4, 2026 20:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings August 4, 2026 23:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6583d13

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@zkochan
zkochan merged commit a550eca into main Aug 5, 2026
29 checks passed
@zkochan
zkochan deleted the gvs-embedder-and-concurrency branch August 5, 2026 00:01
zkochan added a commit to zkochan/bit that referenced this pull request Aug 5, 2026
Documents `enableGlobalVirtualStore`, `globalVirtualStoreDir` and
`patchedDependencies`, and adds the script that installs a locally built
pnpm engine over the published `@pnpm/napi` - needed until a release
carries the options this branch passes (pnpm/pnpm#13648).
zkochan added a commit to zkochan/bit that referenced this pull request Aug 5, 2026
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit to zkochan/bit that referenced this pull request Aug 5, 2026
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit to zkochan/bit that referenced this pull request Aug 5, 2026
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit to zkochan/bit that referenced this pull request Aug 7, 2026
Documents `enableGlobalVirtualStore`, `globalVirtualStoreDir` and
`patchedDependencies`, and adds the script that installs a locally built
pnpm engine over the published `@pnpm/napi` - needed until a release
carries the options this branch passes (pnpm/pnpm#13648).
zkochan added a commit to zkochan/bit that referenced this pull request Aug 7, 2026
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit to zkochan/bit that referenced this pull request Aug 7, 2026
Documents `enableGlobalVirtualStore`, `globalVirtualStoreDir` and
`patchedDependencies`, and adds the script that installs a locally built
pnpm engine over the published `@pnpm/napi` - needed until a release
carries the options this branch passes (pnpm/pnpm#13648).
zkochan added a commit to zkochan/bit that referenced this pull request Aug 7, 2026
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zkochan added a commit to teambit/bit that referenced this pull request Aug 8, 2026
Opt-in support for pnpm's global virtual store: dependency directories
are created once in a store shared by every workspace on the machine,
instead of being re-created inside each `node_modules/.pnpm`. Capsules
deliberately keep the project-local layout — see below.

Every engine dependency is in a published `@pnpm/napi`: the settings
surface (pnpm/pnpm#13648) and the `link:` slot fix (pnpm/pnpm#13658) in
12.0.0-rc.0, and the slot-materialization dedup (pnpm/pnpm#13669) in
12.0.0-rc.1, which this branch pins. The local-engine bootstrap script
is gone.

## Effect

After a fresh install the project-local virtual store holds nothing but
`lock.yaml` and the hoisted `node_modules` — every dependency directory,
including injected workspace components, lives in the shared store:

| workspace | `node_modules/.pnpm` entries, no GVS | with GVS |
|---|---|---|
| a Bit Cloud workspace | 20832 | 0 |
| the bit repo itself | 6441 | 0 |
| bitdev-envs | 4017 | 0 |

Bit uses pnpm's own `<storeDir>/links`, so slots are reused across bit
versions and shared with every other pnpm project on the machine,
upgrades stay incremental, and `pnpm store prune` accounts for them.

Migration note: switching an existing workspace over does not remove
what the previous project-local store already contains — pnpm does not
prune it once the effective virtual store points elsewhere — so the old
directories linger until `node_modules/.pnpm` is deleted. New workspaces
never see them.

## Turning it on

Off by default. Per workspace under
`teambit.dependencies/dependency-resolver`, machine-wide with `bit
config set enable_global_virtual_store true`, or per run with
`BIT_ENABLE_GLOBAL_VIRTUAL_STORE=true`. It has no effect when
`nodeLinker` is `hoisted`, which uses no virtual store at all.

## What it took to behave identically

A shared store breaks one assumption that runs through Bit: that a
package can walk *up* out of `node_modules/.pnpm` into the workspace.
Consequences:

- **Core aspects (CJS).** Bit deliberately does not declare `@teambit/*`
core aspects as dependencies of the envs and aspects that use them —
they have to be the single copy from the running installation, and
declaring them would install duplicates. Project-locally they resolved
by walking up into the workspace root; nothing in a shared store can.
This branch uses pnpm's documented mechanism for hoisted dependencies in
this layout: the privately hoisted directory stays project-local at
`node_modules/.pnpm/node_modules` even under the global virtual store,
the core aspects are linked there, and `bootstrap` puts that directory
on `NODE_PATH` before any aspect loads. Nothing is written inside the
store itself, which is what allows the shared `<storeDir>/links` to be
used at all.
- **Core aspects (ESM).** Node ignores `NODE_PATH` for ESM, and bit
supports ESM components, so the same hoisted-directory fallback is
provided to the ESM resolver via a `module.register()` loader (adapted
from pnpm's `@pnpm/plugin-esm-node-path`, MIT), installed at bootstrap
and propagated to child processes through `NODE_OPTIONS`.
- **Phantom `tsconfig` `extends` in published envs.** TypeScript
resolves `extends` with its own resolver — neither `NODE_PATH` nor the
ESM loader applies — and several published envs extend a package they
never declare (`@teambit/react/typescript/tsconfig.json` from the node
mocha envs, `base-react-env`, `rspack.envs.react-env` and `react-env`
1.x; `rspack.envs.react-env/config/tsconfig.json` from `cloud-react`).
Project-locally the walk up out of `.pnpm` passed the privately hoisted
directory and caught these by accident. Fixed with pnpm's documented
remedy: built-in `packageExtensions` declaring the missing dependency
for the known envs, merged under the workspace's own `packageExtensions`
so users can cover third-party envs the same way. Extensions only add
what a manifest lacks, an unmatched entry is not an error (react-env's
is scoped to `@1` — 2.x inlined the config), and none of these envs
import their extends-target at runtime, so the added copy cannot shadow
the host-provided singletons. (#10572 explored a
`patchedDependencies`-based variant for react-env 1.x and is closed —
the extensions cover it.)
- **The bit repo itself.** A workspace that *authors* the core aspects
bridges them into the hoisted store only until they compile, then
removes the bridge. Right project-locally, fatal from a shared store.
The bridge now persists, repointed at the compiled workspace copy.
- **Injected dirs.** `getInjectedDirs` reports an injected copy absolute
when it cannot be made relative to the lockfile dir — under a shared
store, always. `compiler.task.ts` joined it onto the capsule root
regardless, hard-linking build artifacts into a path that does not
exist. (`node-modules-linker` and `workspace-compiler` already guarded
this; only that one site did not.)
- **`bit deps diagnose`.** Its duplicate-copy counts came from scanning
`node_modules/.pnpm`. The shared store holds every workspace's packages,
so it cannot answer that question for one workspace; the counts now come
from the current lockfile pnpm writes next to the hoisted directory,
whose dep paths map one-to-one onto the project-local directory names.
- **Capsules stay project-local.** A capsule is a self-contained build
sandbox and TypeScript's declaration emit depends on that: it names an
inferred type through the package that declares it, which it can only do
while that package sits inside the capsule. Moving env/aspect packages
out made `bit build` of any custom env fail with `TS2742`. Workspace
installs — the ones users wait on repeatedly — still get the shared
store.

## Also here: `patchedDependencies`

The branch adds pnpm's `patchedDependencies` as a dependency-resolver
setting (it began as the vehicle for the react-env `tsconfig` fix above,
and is useful on its own):

```json
{
  "teambit.dependencies/dependency-resolver": {
    "patchedDependencies": { "[email protected]": "patches/is-positive.patch" }
  }
}
```

Paths are relative to the workspace root. pnpm resolves a relative patch
path from the directory it is installing in, so capsule installs — which
run in the capsules directory — get the paths resolved against the
workspace root first; workspace installs keep the configured spelling,
which pnpm records in `pnpm-lock.yaml` and which must stay
machine-independent there.

## Self-hosting: a workspace whose node_modules provides the running bit

Both layouts are safe in steady state: repeat installs preserve the
top-level package directories the running process resolves from
(verified by sampling them through live installs), and the
end-of-install compile refreshes the per-variant copies. A layout
*switch* is different — it relocates every injected component package,
rebuilding the top-level directories from source, so their compiled
`dist` disappears mid-install and a bit running from them dies before
reaching the compile that would restore it, leaving `node_modules`
unusable. The installer now detects the combination (current layout read
off `.modules.yaml`, self-hosting by realpath of the running module) and
refuses up front with instructions to run the one-time transition from
an external bit installation.

With that and the engine fix, the bit repo itself runs under the global
virtual store: full install + compile of all 332 components, repeat
self-hosted installs in ~50s, `npm run lint` green. The repo's own tsc
needed the type-layer counterpart of the runtime bridges —
`tsconfig.json` `paths` routing react typings and `@teambit/*` through
the workspace's `node_modules`, since a published package's `.d.ts`
cannot reach undeclared `@types`/core aspects from a store slot either.

## Phantom dependencies, generally

A shared store makes an under-declared package fail loudly: it lives
outside the project, so nothing the project hoisted is on its resolution
path any more. That is a real constraint, not a bug to work around, and
it applies to pnpm generally rather than to Bit. Every failure this
branch hit was a genuine phantom dependency — an env's undeclared
`tsconfig` base, a fixture env with detection switched off
(`@bit-no-check` removed so the dependency gets declared),
`@teambit/webpack.webpack-bundler` requiring `events/` without declaring
it (covered by `packageExtensions`, documented in the aspect docs), and
the repo's own undeclared `@types/graceful-fs` (now declared).

## One CI change

`bit_pr` now runs on a temp lane (dropped `--keep-lane`). A reused PR
lane serves components unchanged since an earlier export with artifacts
from older commits, so capsules mix generations of `@teambit` packages
and cross-copy `instanceof` checks start failing — deterministic red
that looks exactly like branch breakage and defeats bisection (on this
branch: run 1 green on a fresh lane, every later push red, across 11
runs and 2 lanes). Filed as #10583; the temp-lane flow is
self-consistent per run.

## Testing

- New e2e: `global-virtual-store.e2e.ts` (nothing materialized in the
workspace, dependencies linked from the shared store, component loads
and compiles, patched dependencies under the store) and
`patched-dependencies.e2e.ts` (a workspace-relative patch applies both
in the workspace and in the capsule — verified to fail before the
capsule-path fix).
- The bit repo (332 components): full global-virtual-store install,
repeat self-hosted installs, transition guard verified in both
directions (clean refusal, workspace intact), lint green. Runs on the
released rc.1 engine.
- A Bit Cloud workspace, 105 components: wiped-`node_modules` install +
compile, slot reuse verified (a repeat install creates 0 of 30766
slots), core-aspect resolution through `NODE_PATH` verified positively
and negatively, `bit start` working.
- bitdev-envs (609 components, 20 apps): `bit app list` byte-identical
to the non-GVS baseline, apps running — against an earlier revision of
the core-aspect mechanism.
- The full e2e suite under `BIT_ENABLE_GLOBAL_VIRTUAL_STORE=true` was
run locally against an earlier revision: no GVS-specific failures (the
`validate command` failures reproduce with the store off). CI runs the
suite in its default store-off configuration, where this branch has been
green including the 40-shard e2e.

The first commit (`fix(doctor)`) is unrelated to the rest and can be
split out — it surfaced because the e2e temp dir contains a dot, which
is why `doctor-infra.e2e.ts` fails locally but passes on CI.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants