Skip to content

refactor(deps-restorer): extract headless install - #13637

Merged
zkochan merged 4 commits into
mainfrom
refactor-headless-install
Aug 4, 2026
Merged

zkochan merged 4 commits into
mainfrom
refactor-headless-install

Conversation

@zkochan

@zkochan zkochan commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Extract the Rust headless installation pipeline from pacquet-package-manager into one new internal pacquet-deps-restorer crate, matching the responsibility boundary used by the TypeScript implementation.

The supporting materialization, linking, build, and lockfile helpers move with the installer so the new crate does not depend back on pacquet-package-manager. The package-manager crate consumes and re-exports the restorer API, preserving existing call sites without duplicating implementations or changing install behavior.

Squash Commit Body

Move the frozen-lockfile installer and its shared dependency preparation primitives into a dedicated internal crate.

Keep the fresh-lockfile path sharing the same linker and build primitives through the new crate, and re-export the restorer API from the package-manager crate to avoid call-site churn. Move the associated unit tests and update test-plan references without changing observable install behavior.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added or updated tests.
  • Updated the documentation if needed.

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


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

Summary by CodeRabbit

  • New Features

    • Added comprehensive dependency restoration for frozen installations, including hoisting, symlink creation, package linking, virtual-store setup, and package-map generation.
    • Added deterministic dependency build ordering and support for cached side effects, patches, optional packages, and workspace layouts.
    • Added support for multiple file import methods, including copy, hardlink, reflink, and clone-based approaches.
  • Bug Fixes

    • Improved path validation and protection against unsafe dependency aliases and traversal.
  • Tests

    • Expanded coverage for installation, linking, hoisting, caching, platform compatibility, and error handling.

Copilot AI lite review requested due to automatic review settings August 4, 2026 10:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e01e8806-9a50-424b-a2b0-93f3cdc57284

📥 Commits

Reviewing files that changed from the base of the PR and between 6d0ff26 and 19bd9c3.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (70)
  • Cargo.toml
  • pnpm/crates/cli/tests/multiple_importers.rs
  • pnpm/crates/deps-restorer/Cargo.toml
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/deps-restorer/src/build_modules/tests.rs
  • pnpm/crates/deps-restorer/src/build_sequence.rs
  • pnpm/crates/deps-restorer/src/build_sequence/tests.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs
  • pnpm/crates/deps-restorer/src/current_lockfile.rs
  • pnpm/crates/deps-restorer/src/current_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/deps_graph.rs
  • pnpm/crates/deps-restorer/src/deps_graph/tests.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer/tests.rs
  • pnpm/crates/deps-restorer/src/hoist.rs
  • pnpm/crates/deps-restorer/src/hoist/tests.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph/tests.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits/tests.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/install_frozen_lockfile.rs
  • pnpm/crates/deps-restorer/src/install_frozen_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs
  • pnpm/crates/deps-restorer/src/installability.rs
  • pnpm/crates/deps-restorer/src/installability/tests.rs
  • pnpm/crates/deps-restorer/src/lib.rs
  • pnpm/crates/deps-restorer/src/link_bins.rs
  • pnpm/crates/deps-restorer/src/link_bins/tests.rs
  • pnpm/crates/deps-restorer/src/link_file.rs
  • pnpm/crates/deps-restorer/src/link_file/tests.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members/tests.rs
  • pnpm/crates/deps-restorer/src/package_map.rs
  • pnpm/crates/deps-restorer/src/package_map/tests.rs
  • pnpm/crates/deps-restorer/src/pnp.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs
  • pnpm/crates/deps-restorer/src/prune_stale_modules.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine/tests.rs
  • pnpm/crates/deps-restorer/src/retry_config.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir/tests.rs
  • pnpm/crates/deps-restorer/src/store_init.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs
  • pnpm/crates/deps-restorer/src/symlink_package.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths/tests.rs
  • pnpm/crates/deps-restorer/src/version_policy.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/crates/package-manager/Cargo.toml
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md

📝 Walkthrough

Walkthrough

The PR adds the pacquet-deps-restorer crate, moves dependency restoration APIs into it, exposes installation, graph, linking, and safety helpers, and updates package-manager integration and test references.

Changes

Dependency restorer extraction

Layer / File(s) Summary
Crate and package-manager integration
Cargo.toml, pnpm/crates/deps-restorer/..., pnpm/crates/package-manager/...
Adds the new crate, re-exports restoration APIs, removes obsolete package-manager modules, and updates package-manager callers.
Graph construction and build sequencing
pnpm/crates/deps-restorer/src/{build_modules,build_sequence,deps_graph,graph_sequencer,hoisted_dep_graph,hoisting_limits}.rs
Adds deterministic graph traversal, build sequencing, cycle handling, hoisting limits, and hoisted dependency graph construction with tests.
Installation and installability
pnpm/crates/deps-restorer/src/{install_frozen_lockfile,install_package_by_snapshot,install_package_from_registry,installability,virtual_store_layout}.rs
Exposes installation and installability APIs and adds tests for fetchers, runtime manifests, caches, and virtual-store layouts.
Filesystem materialization and linking
pnpm/crates/deps-restorer/src/{link_file,link_hoisted_modules,link_root_component_members,symlink_direct_dependencies,link_bins}.rs
Adds file importing, hoisted linking, root-component linking, direct-dependency linking, and binary linking with typed errors and tests.
Reconciliation and safety
pnpm/crates/deps-restorer/src/{current_lockfile,import_indexed_dir,package_map,prune_direct_deps,safe_join_modules_dir,validate_lockfile_paths}.rs
Exposes reconciliation helpers and adds tests for import repair, package maps, pruning, alias validation, containment, and filesystem safety.
Supporting APIs and documentation
pnpm/crates/deps-restorer/src/{pnp,retry_config,remove_quarantine,store_init,version_policy}.rs, pnpm/plans/TEST_PORTING.md
Exposes supporting utilities, adds quarantine-removal tests, and updates relocated test references.

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

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#12899 — Related package-manager extraction and dependency-restoration changes.
  • pnpm/pnpm#13151 — Related installation, linking, pruning, and reconciliation migration.
  • pnpm/pnpm#13624 — Related fresh-lockfile installation and linking refactoring.

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 refactor-headless-install

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.

@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (5): Last reviewed commit: "refactor(deps-restorer): align crate nam..." | Re-trigger Greptile

Copilot AI review requested due to automatic review settings August 4, 2026 10:31

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

refactor(deps-preparer): extract headless install into internal crate

✨ Enhancement ⚙️ Configuration changes 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Extract Rust headless/frozen install pipeline into new internal pacquet-deps-preparer crate.
• Move shared materialization/link/build/lockfile helpers to avoid back-dependencies on
 package-manager.
• Re-export preparer API from pacquet-package-manager to preserve existing call sites and
 behavior.
Diagram

graph TD
  A["Rust CLI / callers"] --> B["pacquet-package-manager"] --> C["pacquet-deps-preparer"] --> D[("Lockfile + current lockfile")] --> E[("Store / virtual store")]
  C --> F{{"Registry / network"}}

  subgraph Legend
    direction LR
    _crate["Crate"] ~~~ _db[("On-disk state")] ~~~ _ext{{"External"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Keep preparer modules in package-manager (no new crate)
  • ➕ No new crate wiring or workspace dependency edge
  • ➕ Avoids widening visibility solely for cross-crate access
  • ➖ Doesn’t enforce the intended responsibility boundary; package-manager remains a dependency sink
  • ➖ Harder to align with the TypeScript layering and to reuse from other Rust entry points
2. Define a minimal facade trait instead of broad re-export
  • ➕ Smaller stable surface; fewer helper functions/types exposed
  • ➕ Cleaner seam for mocking/swapping implementations
  • ➖ More abstraction/migration work now; higher chance of drift if the facade misses semantics
  • ➖ Still requires carefully mapping many types used across install/link/build phases
3. Publish deps-preparer as a public crate
  • ➕ Clearer long-term reuse story beyond the workspace
  • ➖ Premature API stability burden while the port is still evolving
  • ➖ Would constrain future refactors of installer internals

Recommendation: The internal-crate extraction + package-manager re-export is the best tradeoff: it enforces the responsibility boundary while keeping existing call sites stable and minimizing behavior risk (moving code rather than rewriting it). The main thing to watch is API surface creep—prefer re-exporting only what callers need and keep helper visibility narrow where possible.

Files changed (31) +397 / -249 · 1 not counted

Refactor (22) +252 / -237
build_modules.rsPublicize shared build helper functions +4/-2

Publicize shared build helper functions

• Exports helper utilities ('normalize_build_dep_path', 'parse_name_version_from_key') and annotates them with '#[must_use]' for cross-crate consumption.

pnpm/crates/deps-preparer/src/build_modules.rs

create_virtual_dir_by_snapshot.rsExpose concurrency probe hooks and wire-method mapping +4/-3

Expose concurrency probe hooks and wire-method mapping

• Makes test probe fields/modules public under '#[cfg(test)]' and exports 'optimistic_wire_method' for reuse after crate extraction.

pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs

create_virtual_store.rsAdjust docs and expose test probe field +3/-3

Adjust docs and expose test probe field

• Updates documentation to remove now-invalid 'crate::' references post-extraction and makes the test probe field public under '#[cfg(test)]'.

pnpm/crates/deps-preparer/src/create_virtual_store.rs

current_lockfile.rsExport lockfile filtering/skip-closure helpers +3/-2

Export lockfile filtering/skip-closure helpers

• Promotes 'merge_filtered_current_lockfile' and 'extend_skipped_with_dependency_closure' to public API (with '#[must_use]') to support the extracted pipeline without back-dependencies.

pnpm/crates/deps-preparer/src/current_lockfile.rs

deps_graph.rsExport snapshot child construction and lockfile ordering helpers +4/-2

Export snapshot child construction and lockfile ordering helpers

• Exposes 'build_children' and 'in_lockfile_order' (both '#[must_use]') to reuse graph-building logic across installer paths.

pnpm/crates/deps-preparer/src/deps_graph.rs

hoist.rsExport hoist graph builder entrypoint +1/-1

Export hoist graph builder entrypoint

• Makes 'build_hoist_graph_with_max_length' public to keep hoisting logic reusable across crates.

pnpm/crates/deps-preparer/src/hoist.rs

import_indexed_dir.rsExport CAFS completion-marker check +2/-1

Export CAFS completion-marker check

• Promotes 'marker_present' to public API with '#[must_use]' for shared import logic.

pnpm/crates/deps-preparer/src/import_indexed_dir.rs

install_frozen_lockfile.rsPublicize shared build/hoist primitives for extracted installer +66/-62

Publicize shared build/hoist primitives for extracted installer

• Exports key functions/types used by both frozen and fresh install flows (e.g., 'BuildPhaseInputs', 'run_build_phase', hoisted linker inputs/errors/output, patch resolution helpers) and updates documentation for the new crate context.

pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs

install_package_by_snapshot.rsExport fetch-validation and platform selector helpers +10/-8

Export fetch-validation and platform selector helpers

• Exports 'unverified_fetch_is_allowed', 'host_platform_selector', and 'runtime_platform_selector' (with '#[must_use]') and updates docs to reflect the new ownership boundary.

pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs

install_package_from_registry.rsExport tarball extraction and dist metadata helpers +5/-3

Export tarball extraction and dist metadata helpers

• Promotes 'extract_tarball', 'manifest_unpacked_size', and 'manifest_file_count' to public API (with '#[must_use]' where relevant) for shared installer use.

pnpm/crates/deps-preparer/src/install_package_from_registry.rs

installability.rsExport installability helpers and skip-set utilities +13/-11

Export installability helpers and skip-set utilities

• Makes installability checks and skip-set manipulation methods public (adding '#[must_use]' where appropriate) so external callers/tests can drive consistent behavior.

pnpm/crates/deps-preparer/src/installability.rs

lib.rsDefine deps-preparer public surface and shared constants/helpers +115/-0

Define deps-preparer public surface and shared constants/helpers

• Adds the crate root, re-exporting preparer modules and centralizing shared helpers/constants like 'NEEDS_BUILD_MARKER', store-index key derivation, patch detection, script thread sizing, and package-map gating.

pnpm/crates/deps-preparer/src/lib.rs

package_map.rsMake package-map writers and types public +9/-12

Make package-map writers and types public

• Exports '.package-map.json' constants/types and write/conversion functions so package-manager can re-export them without duplicating implementations.

pnpm/crates/deps-preparer/src/package_map.rs

pnp.rsExport PnP file writer +1/-1

Export PnP file writer

• Promotes 'write_pnp_file' to public API to match the extracted preparer boundary.

pnpm/crates/deps-preparer/src/pnp.rs

prune_direct_deps.rsExport pruning helpers and refine docs +6/-8

Export pruning helpers and refine docs

• Updates documentation for the new crate context and makes pruning helpers ('confined_modules_dir', 'selected_groups', 'remove_direct_dep_link') public (with '#[must_use]' on selectors).

pnpm/crates/deps-preparer/src/prune_direct_deps.rs

prune_stale_modules.rsUpdate docs referencing package-manager prune pass +1/-1

Update docs referencing package-manager prune pass

• Adjusts documentation to refer to the package-manager virtual-store pruning pass after extraction; no behavioral change implied.

pnpm/crates/deps-preparer/src/prune_stale_modules.rs

remove_quarantine.rsExport macOS quarantine removal helper +2/-2

Export macOS quarantine removal helper

• Promotes 'remove_quarantine_from_native_binaries' to public API for both macOS and non-macOS implementations.

pnpm/crates/deps-preparer/src/remove_quarantine.rs

retry_config.rsExport retry options builder +1/-1

Export retry options builder

• Makes 'retry_opts_from_config' public to keep retry behavior consistent across installer call sites.

pnpm/crates/deps-preparer/src/retry_config.rs

store_init.rsExport store initialization helper +1/-1

Export store initialization helper

• Promotes 'init_store_dir_best_effort' to public API so frozen and fresh install flows share the same store init and degradation policy.

pnpm/crates/deps-preparer/src/store_init.rs

install.rsRemove should_write_package_map helper from package-manager +0/-4

Remove should_write_package_map helper from package-manager

• Deletes the local helper because it now lives in deps-preparer (and is re-exported via package-manager).

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

install_with_fresh_lockfile.rsAlign CreateVirtualStore invocation with extracted API +0/-2

Align CreateVirtualStore invocation with extracted API

• Removes the test-only 'link_concurrency_probe' field from the 'CreateVirtualStore' call site to match the extracted crate’s interface.

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

lib.rsRe-export deps-preparer API and drop duplicated internal modules +1/-107

Re-export deps-preparer API and drop duplicated internal modules

• Removes many internal installer/helper modules from package-manager and replaces them with 'pub use pacquet_deps_preparer::*', preserving external call sites while centralizing implementation ownership in deps-preparer.

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

Tests (4) +7 / -7
multiple_importers.rsUpdate known-failure reference to deps-preparer path +1/-1

Update known-failure reference to deps-preparer path

• Adjusts test-plan commentary to point to 'crates/deps-preparer/src/current_lockfile.rs' after extraction.

pnpm/crates/cli/tests/multiple_importers.rs

tests.rsMove build_modules unit tests under deps-preparer not counted

Move build_modules unit tests under deps-preparer

• Relocates build/lifecycle/side-effects unit coverage into the new crate so tests stay colocated with the implementation.

pnpm/crates/deps-preparer/src/build_modules/tests.rs

tests.rsMake LinkConcurrencyProbe public +1/-1

Make LinkConcurrencyProbe public

• Exports 'LinkConcurrencyProbe' so external tests/callers can assert linking concurrency behavior.

pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs

tests.rsUpdate package-map gating test to use re-exported helper +5/-5

Update package-map gating test to use re-exported helper

• Adjusts tests to call 'crate::should_write_package_map' after the helper moved into deps-preparer and is re-exported.

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

Documentation (1) +5 / -5
TEST_PORTING.mdUpdate test-plan references to deps-preparer paths +5/-5

Update test-plan references to deps-preparer paths

• Repoints lifecycle/side-effects porting references from package-manager test locations to the new deps-preparer crate paths.

pnpm/plans/TEST_PORTING.md

Other (4) +133 / -0
Cargo.lockRecord new pacquet-deps-preparer package in lockfile +59/-0

Record new pacquet-deps-preparer package in lockfile

• Adds 'pacquet-deps-preparer' to the workspace lockfile and includes it as a dependency where required.

Cargo.lock

Cargo.tomlAdd pacquet-deps-preparer as a workspace path dependency +1/-0

Add pacquet-deps-preparer as a workspace path dependency

• Registers the new internal crate at 'pnpm/crates/deps-preparer' in the workspace dependency list.

Cargo.toml

Cargo.tomlIntroduce pacquet-deps-preparer crate manifest +72/-0

Introduce pacquet-deps-preparer crate manifest

• Creates the new internal crate with the dependencies and dev-dependencies required to host the headless install pipeline and its unit tests.

pnpm/crates/deps-preparer/Cargo.toml

Cargo.tomlAdd dependency on pacquet-deps-preparer +1/-0

Add dependency on pacquet-deps-preparer

• Wires the new internal crate into package-manager so it can consume and re-export preparer APIs.

pnpm/crates/package-manager/Cargo.toml

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

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. API surface unintentionally widened 🐞 Bug ⚙ Maintainability
Description
pacquet-deps-restorer publicly exposes and glob re-exports many implementation modules/helpers,
and pacquet-package-manager now glob re-exports the entire crate. This expands the effective
public surface beyond the intended “restorer API”, increasing the chance other workspace code
couples to internal helpers and making security hardening/auditing more difficult.
Code

pnpm/crates/package-manager/src/lib.rs[47]

+pub use pacquet_deps_restorer::*;
Relevance

●● Moderate

Team has accepted narrowing pub→pub(crate), but glob re-export/API-boundary change is broader and
may be deferred.

PR-#13141

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The diff shows both the new crate-wide glob re-export in package-manager and that deps-restorer is
structured to publicly expose and re-export most modules and helpers (including low-level helpers
that don’t need to be public for the extraction), which directly constitutes an expanded API surface
contrary to the repo’s “contained contract / avoid extra surface” guidance.

pnpm/crates/package-manager/src/lib.rs[34-58]
pnpm/crates/deps-restorer/src/lib.rs[1-65]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[264-272]
pnpm/crates/deps-restorer/src/build_modules.rs[259-267]
REVIEW_GUIDE.md[20-27]

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-package-manager` re-exports everything from `pacquet-deps-restorer` via a glob import, and `pacquet-deps-restorer` itself exposes most implementation modules publicly and then glob re-exports them. This makes internal helpers part of the de facto API, increasing coupling and making it harder to reason about which functions are safe/approved entry points.

## Issue Context
This PR’s goal is a refactor/extraction with preserved call sites, not a deliberate expansion of the supported API surface.

## Fix Focus Areas
- pnpm/crates/package-manager/src/lib.rs[47-47]
- pnpm/crates/deps-restorer/src/lib.rs[1-65]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[264-272]
- pnpm/crates/deps-restorer/src/build_modules.rs[259-267]

## Suggested fix
1. In `pacquet-deps-restorer`, introduce a small curated public facade (e.g. `pub mod api { ... }`) that `pub use`s only the intended cross-crate entry points/types.
2. Make implementation modules private (`mod foo;`) where possible, and change helpers that are only used internally back to `pub(crate)` (e.g. `marker_present`, `normalize_build_dep_path`, etc.).
3. In `pacquet-package-manager`, re-export only the facade or an explicit allow-list of items rather than `pub use pacquet_deps_restorer::*;`.
4. If preserving existing paths is required, re-export explicit items/modules matching the prior public surface rather than exporting everything by default.

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


Grey Divider

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

Previous review results

Review updated until commit 19bd9c3 ⚖️ Balanced

Results up to commit 607aea8 ⚖️ Balanced


No changes from previous review

Results up to commit 23584da ⚖️ Balanced


No changes from previous review

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.

@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.17     16.9±1.95ms    22.2 MB/sec    1.00     14.4±0.82ms    26.0 MB/sec
packument/parse                                  1.00     45.2±2.69µs  1466.7 MB/sec    1.00     45.3±2.15µs  1464.6 MB/sec
tarball/download_dependency                      1.31      3.7±0.64ms  1164.4 KB/sec    1.00      2.8±0.23ms  1523.7 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.11   253.9±23.74ms 63.0 KElem/sec    1.00   229.4±20.87ms 69.8 KElem/sec
workspace_resolution/hoist_heavy                 1.10   367.8±43.56ms        ? ?/sec    1.00   334.5±18.10ms        ? ?/sec

@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

🧹 Nitpick comments (20)
pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs (1)

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

Use pacquet_fs::symlink_dir for the pre-existing Windows link.

pacquet-fs falls back to a junction when true directory symlinks fail due to SeCreateSymbolicLinkPrivilege, while this test uses raw std::os::windows::fs::symlink_dir, which can fail on Windows CI. pacquet-fs is already declared for this crate, and production deps-preparer code uses the same helper for directory links.

🤖 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-preparer/src/link_root_component_members/tests.rs` around
lines 375 - 381, Update the Windows branch of the preexisting link setup in the
test to call pacquet_fs::symlink_dir instead of
std::os::windows::fs::symlink_dir, preserving the existing source and
destination paths and Unix behavior.

Source: Coding guidelines

pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs (1)

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

Add #[must_use] here for consistency.

This diff adds #[must_use] to unverified_fetch_is_allowed (line 785) and host_platform_selector (line 799). runtime_platform_selector is the same shape: a pure function whose only effect is the returned PlatformSelector. Discarding its result is always a bug.

♻️ Proposed change
+#[must_use]
 pub fn runtime_platform_selector(
     supported: Option<&pacquet_package_is_installable::SupportedArchitectures>,
 ) -> PlatformSelector {
🤖 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-preparer/src/install_package_by_snapshot.rs` at line 811,
Add the #[must_use] attribute to the runtime_platform_selector function,
matching the existing annotations on unverified_fetch_is_allowed and
host_platform_selector so callers cannot silently discard its PlatformSelector
result.
pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs (1)

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

Replace the exhaustive Config literal with Config::new() plus overrides.

create_config spells out roughly 145 fields, and about 40 of them are Default::default(). Every new field on pacquet_config::Config breaks this file. Sibling test modules in this crate already use the cheaper pattern: create_virtual_store/tests.rs calls Config::new() and then assigns only the fields under test. Adopting that here removes the whole literal, removes the need for the file-level clippy::default_trait_access expectation at lines 1-4, and keeps the fixture stable across Config changes.

Set only what these tests depend on: store_dir, modules_dir, virtual_store_dir, cache_dir, registry, and symlink/hoist if Config::new() does not already default them to the values asserted here.

♻️ Sketch of the replacement
fn create_config(
    store_dir: &Path,
    modules_dir: &Path,
    virtual_store_dir: &Path,
    cache_dir: &Path,
) -> Config {
    let mut config = Config::new();
    config.store_dir = StoreDir::new(store_dir);
    config.modules_dir = modules_dir.to_path_buf();
    config.virtual_store_dir = virtual_store_dir.to_path_buf();
    config.global_virtual_store_dir = virtual_store_dir.to_path_buf();
    config.cache_dir = cache_dir.to_path_buf();
    config.symlink = false;
    config
}

Verify each remaining assertion still holds against Config::new()'s defaults before dropping a field.

🤖 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-preparer/src/install_package_from_registry/tests.rs` around
lines 27 - 178, Replace the exhaustive Config literal in create_config with
Config::new() and override only the fixture-dependent fields: store_dir,
modules_dir, virtual_store_dir, global_virtual_store_dir, cache_dir, registry,
and symlink/hoist when needed to preserve assertions. Remove the file-level
clippy::default_trait_access allowance if it is no longer used, and verify the
tests retain their expected defaults.

Source: Path instructions

pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs (1)

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

Reuse one helper for the three mem-cache installs.

These three InstallPackageBySnapshot literals differ only in tarball_mem_cache. This file already defines run_snapshot_install_with_picker (lines 754-799) for exactly this purpose on the fetcher tests. Extract a sibling helper that takes tarball_mem_cache: Option<&Arc<MemCache>> and returns the Result, so a future field added to InstallPackageBySnapshot needs one edit instead of three.

Also applies to: 598-621, 673-696

🤖 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-preparer/src/install_package_by_snapshot/tests.rs` around
lines 520 - 546, The three mem-cache install tests duplicate the full
InstallPackageBySnapshot construction. Extract a sibling helper near
run_snapshot_install_with_picker that accepts tarball_mem_cache:
Option<&Arc<MemCache>> and returns the install Result, centralizing the shared
fields; update the install sites around the referenced blocks to call it with
each cache variant.
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs (1)

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

Keep the concurrency probe surface inside pacquet-deps-preparer. The probe, LinkConcurrencyGuard, and the link_concurrency_probe fields are only used for intra-crate tests, including the tests submodule, so pub(crate) is clearer here.

  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19: make LinkConcurrencyProbe pub(crate).
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297: make #[cfg(test)] mod tests use pub(crate) mod tests.
  • pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185: make the public field pub(crate) link_concurrency_probe inside the existing #[cfg(test)] block.
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78: make the public field for this type match pub(crate) too.
🤖 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-preparer/src/create_virtual_dir_by_snapshot/tests.rs` at
line 19, Restrict the concurrency probe test surface to crate visibility: make
LinkConcurrencyProbe in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19
pub(crate), change tests to pub(crate) mod tests in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297, and make
the link_concurrency_probe fields pub(crate) in
pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185,
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78, and
pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs:135.
pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs (1)

1722-1725: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider a typed error instead of expect now that run_hoisted_linker is public.

run_hoisted_linker is now pub, so package-manager and any future caller can pass cas_paths_by_pkg_id: None. Line 1725 turns that into a panic. The in-repo caller guards the value, so this is not currently reachable. A HoistedLinkerError variant would keep the newly public boundary on the typed-diagnostic path.

As per coding guidelines, pnpm/CODE_STYLE_GUIDE.md asks the new public deps-preparer API to "use typed error enums with proper propagation, avoid unnecessary unwrap".

♻️ Proposed refactor
 pub enum HoistedLinkerError {
     #[diagnostic(transparent)]
     HoistedDepGraph(#[error(source)] HoistedDepGraphError),
+    #[display("hoisted linking requires the CAS path index produced by CreateVirtualStore")]
+    #[diagnostic(code(ERR_PNPM_PACKAGE_MANAGER_MISSING_CAS_PATHS))]
+    MissingCasPaths,
-    let cas_index = cas_paths_by_pkg_id.expect("hoisted CreateVirtualStore populates cas_paths");
+    let cas_index = cas_paths_by_pkg_id.ok_or(HoistedLinkerError::MissingCasPaths)?;
🤖 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-preparer/src/install_frozen_lockfile.rs` around lines 1722 -
1725, Replace the expect in the public run_hoisted_linker flow with a dedicated
HoistedLinkerError variant for missing cas_paths_by_pkg_id, and propagate it
through the existing Result-based error path. Preserve the current linker
behavior for Some values and the no-op handling for installs without snapshots.

Source: Path instructions

pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs (1)

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

Rename self_loop_not_safe_flag; the name contradicts the assertion.

The test asserts result.safe is true for a length-1 self-loop, but the name reads as "not safe". A reader who scans test names concludes the opposite of the pinned behavior, and a later change could "fix" the assertion to match the name. Name it after the behavior it pins.

♻️ Proposed rename
-fn self_loop_not_safe_flag() {
+fn self_loop_does_not_clear_safe_flag() {
🤖 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-preparer/src/graph_sequencer/tests.rs` around lines 95 -
104, Rename the test function self_loop_not_safe_flag to a name that clearly
states that a length-1 self-loop is considered safe, while preserving its
existing assertions and behavior.
pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs (1)

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

Correct the doc comment; the test does not cover staging-name uniqueness.

The comment states that two staging paths produced back-to-back in the same process must differ, so concurrent rayon workers do not collide on the rename target. The test imports into two different targets (pkg-a and pkg-b), whose staging paths already differ by target path. It never exercises two staging names derived for the same target. Describe what the test verifies: two concurrent force imports into separate targets both complete and clear stale files.

♻️ Proposed comment fix
-/// Two staging paths produced back-to-back in the same process must
-/// differ — otherwise concurrent rayon workers would collide on the
-/// rename target. Uses the function indirectly via two force re-installs
-/// in parallel.
+/// Two force re-imports running in parallel against separate targets
+/// must both complete and clear their stale files. Staging-name
+/// uniqueness for a single target is not covered here.
🤖 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-preparer/src/import_indexed_dir/tests.rs` around lines 484 -
487, Correct the doc comment above the test to describe its actual coverage:
concurrent force imports into separate targets (pkg-a and pkg-b) both complete
successfully and clear stale files. Remove the unsupported claim about
back-to-back staging-path uniqueness and rayon rename-target collisions.
pnpm/crates/deps-preparer/src/deps_graph/tests.rs (1)

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

Assert the full full_pkg_id, not just its prefix.

The test name states the integrity is used verbatim, but the assertion only checks the prefix @scope/[email protected]:sha512-. It passes even if the integrity body is truncated or rewritten after that prefix. full_pkg_id feeds side-effects cache keys and global-virtual-store slot digests, so a change in integrity rendering moves store paths. Compare the whole string so the test enforces the contract its name claims.

♻️ Proposed tightening
     let graph = build_deps_graph(&snapshots, &packages);
     let node = graph.get(&pkg).expect("graph node");
-    let expected_prefix = "`@scope/foo`@1.0.0:sha512-";
-    assert!(
-        node.full_pkg_id.starts_with(expected_prefix),
-        "expected full_pkg_id to start with `{expected_prefix}`, got `{}`",
-        node.full_pkg_id,
-    );
+    let expected = format!("`@scope/foo`@1.0.0:{}", integrity());
+    assert_eq!(node.full_pkg_id, expected);
 }
🤖 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-preparer/src/deps_graph/tests.rs` around lines 47 - 61,
Update the test registry_resolution_full_pkg_id_uses_integrity_verbatim to
assert node.full_pkg_id equals the complete expected package ID, including the
exact integrity value produced by registry_metadata(), rather than checking only
a prefix. Preserve the existing package and graph setup while ensuring truncated
or rewritten integrity content causes the test to fail.
pnpm/crates/deps-preparer/src/build_modules.rs (1)

264-265: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Narrow normalize_build_dep_path to pub(crate).

normalize_build_dep_path is only callable from outside deps_preparer because of pub mod build_modules; plus pub use build_modules::*;, but the only current callers are inside deps-preparer. No Rust package-manager code uses it, so export it to the crate's public API only if a caller is intentionally required.

🤖 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-preparer/src/build_modules.rs` around lines 264 - 265,
Change normalize_build_dep_path from public to pub(crate) so it is available
only within the deps-preparer crate. Keep the existing implementation and
callers unchanged, and do not expose it through the crate’s public re-exports.
pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs (1)

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

Simplify the node update in fill_children.

Line 486 indexes graph[&dir], so the key is proven present. The if let Some(node) = graph.get_mut(&dir) guard on line 495 can never take the None branch. A direct &mut binding states the invariant and drops the dead branch.

♻️ Proposed simplification
         let snapshot = lockfile.snapshots.as_ref().and_then(|m| m.get(&pkg_key));
         let children = compute_children(snapshot, pkg_locations);
-        if let Some(node) = graph.get_mut(&dir) {
-            node.children = children;
-        }
+        graph.get_mut(&dir).expect("dir came from graph.keys()").children = children;
🤖 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-preparer/src/hoisted_dep_graph.rs` around lines 479 - 500,
In fill_children, replace the conditional graph.get_mut(&dir) update with a
direct mutable binding, since each dir comes from graph.keys() and is guaranteed
to exist. Assign the computed children directly through that binding while
preserving the existing child computation.
pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs (2)

1-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Merge the two import blocks into one.

Lines 1-11 and lines 96-102 both import from super, pacquet_lockfile, and std::collections. The style guide asks for merged explicit imports. Move the second block into the first so each module is imported once.

As per coding guidelines: "Prefer ... merged explicit imports".

Also applies to: 96-102

🤖 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-preparer/src/hoisted_dep_graph/tests.rs` around lines 1 -
11, Merge the duplicate imports in the test module into the existing top-level
import block. Combine all symbols from the later super, pacquet_lockfile, and
std::collections imports with their corresponding first-block imports, leaving
each module imported exactly once and preserving explicit import style.

Source: Path instructions


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

Extract the empty-Lockfile literal into a fixture helper.

Three tests repeat the same 13-field Lockfile literal, differing only in packages and snapshots. A helper such as empty_lockfile(packages, snapshots) removes the duplication and keeps future field additions to one site.

Also applies to: 595-607, 633-645

🤖 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-preparer/src/hoisted_dep_graph/tests.rs` around lines 176 -
188, Extract the repeated empty Lockfile construction into an empty_lockfile
helper accepting packages and snapshots, and initialize all shared fields there.
Update the three affected tests to call the helper with their respective
packages and snapshots values while preserving the existing test behavior.
pnpm/crates/deps-preparer/src/virtual_store_layout.rs (1)

371-381: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import BTreeMap instead of writing the full path inline.

Line 40 already imports std::collections::{HashMap, HashSet}. The collect_injected_deps signature and body spell out std::collections::BTreeMap five times. Add BTreeMap to that import and shorten the occurrences.

As per coding guidelines: "Prefer ... merged explicit imports".

♻️ Proposed change
 use std::{
-    collections::{HashMap, HashSet},
+    collections::{BTreeMap, HashMap, HashSet},
     path::{Path, PathBuf},
 };
     skipped: &crate::SkippedSnapshots,
-    hoisted_locations: Option<&std::collections::BTreeMap<String, Vec<String>>>,
-) -> std::collections::BTreeMap<String, Vec<String>> {
-    let mut injected: std::collections::BTreeMap<String, Vec<String>> =
-        std::collections::BTreeMap::new();
+    hoisted_locations: Option<&BTreeMap<String, Vec<String>>>,
+) -> BTreeMap<String, Vec<String>> {
+    let mut injected: BTreeMap<String, Vec<String>> = BTreeMap::new();
🤖 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-preparer/src/virtual_store_layout.rs` around lines 371 -
381, Add BTreeMap to the existing std::collections import in
collect_injected_deps and replace every fully qualified
std::collections::BTreeMap reference in its signature and body with BTreeMap,
without changing behavior.

Source: Path instructions

pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs (1)

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

Add a test for the no-root-importer case.

get_hoisting_limits only emits the .@ entry when a root importer is present (root_present at pnpm/crates/deps-preparer/src/hoisting_limits.rs line 54). That branch is documented as upstream parity behavior, and no test covers it. A test with only packages/foo in importers under Dependencies mode should assert that .@ is absent and that the per-importer key is still emitted.

🤖 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-preparer/src/hoisting_limits/tests.rs` around lines 42 - 65,
Add a test alongside dependencies_mode_borders_each_importer using only the
“packages/foo” importer and HoistingLimits::Dependencies. Assert
get_hoisting_limits omits the ".@" entry while still emitting the
"packages%2Ffoo@workspace:packages/foo" key with its expected dependency set.
pnpm/crates/deps-preparer/src/hoisting_limits.rs (1)

22-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider an exhaustive match on mode instead of two matches! guards.

get_hoisting_limits tests mode twice with matches!. If pacquet_config::HoistingLimits gains a variant, that variant silently takes the Workspaces behavior. An exhaustive match on mode makes the compiler flag the new variant.

🤖 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-preparer/src/hoisting_limits.rs` around lines 22 - 52,
Update get_hoisting_limits to use an exhaustive match on mode instead of the two
matches!(mode, ...) guards. Preserve the existing early return for
HoistingLimits::None and dependency-specific importer-border behavior, while
ensuring any future HoistingLimits variant causes a compile-time exhaustiveness
error rather than defaulting to workspace behavior.
pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs (1)

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

Reuse package_metadata for the inline PackageMetadata literals.

Line 27 defines package_metadata(resolution, version) and line 800 defines registry_metadata(lead). Six more sites still spell out all twelve fields of PackageMetadata, and every one sets the same nine fields to None. A new field on PackageMetadata then requires six edits. Route these sites through package_metadata with a registry resolution.

As per coding guidelines: "Keep the change focused, avoid duplicated helpers".

♻️ Example for the first site
     let mut packages = HashMap::new();
     packages.insert(
         key.clone(),
-        PackageMetadata {
-            resolution: LockfileResolution::Registry(RegistryResolution {
-                integrity: "sha512-AAAA...AAAA"
-                    .parse()
-                    .expect("parse integrity"),
-            }),
-            version: None,
-            engines: None,
-            cpu: None,
-            os: None,
-            libc: None,
-            deprecated: None,
-            has_bin: None,
-            prepare: None,
-            bundled_dependencies: None,
-            peer_dependencies: None,
-            peer_dependencies_meta: None,
-        },
+        package_metadata(registry_resolution("A"), None),
     );

Add a small registry_resolution(lead: &str) -> LockfileResolution helper next to registry_metadata, which can then be expressed as package_metadata(registry_resolution(lead), None).

Also applies to: 122-142, 168-188, 225-245, 346-366, 419-440

🤖 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-preparer/src/virtual_store_layout/tests.rs` around lines 68
- 88, Replace the six inline twelve-field PackageMetadata literals in the
affected tests with package_metadata calls, passing a registry
LockfileResolution and the existing version value (or None). Add one shared
registry_resolution(lead: &str) -> LockfileResolution helper beside
registry_metadata, and reuse it at each site without introducing additional
duplicated helpers.

Source: Path instructions

pnpm/crates/deps-preparer/src/package_map/tests.rs (1)

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

Log the rendered package map before the comparison.

This assertion compares a large structured value. Bind the actual JSON and emit it with eprintln! before assert_eq!. This keeps regression output readable.

Proposed change
-    assert_eq!(
-        serde_json::to_value(&package_map).expect("serialize package map"),
+    let actual = serde_json::to_value(&package_map).expect("serialize package map");
+    eprintln!("PACKAGE MAP:\n{actual}\n");
+    assert_eq!(
+        actual,

As per path instructions, log complex values before non-equality assertions. Based on learnings, emit the rendered value with eprintln! using {} formatting before the assertion.

🤖 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-preparer/src/package_map/tests.rs` around lines 80 - 131, In
the package map test, bind the rendered JSON value from
serde_json::to_value(&package_map) to a local variable, print it with eprintln!
using {} formatting immediately before assert_eq!, and compare that variable
against the expected JSON.

Sources: Path instructions, Learnings

pnpm/crates/deps-preparer/src/package_map.rs (1)

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

Document the exported deps-preparer API contracts.

These items now cross crate boundaries but lack rustdoc contracts. Document path bases, side effects, errors, and required caller invariants. For remove_direct_dep_link, state that callers must first confine the modules directory.

  • pnpm/crates/deps-preparer/src/package_map.rs#L13-L21: Document the filename and serialized package-map records.
  • pnpm/crates/deps-preparer/src/package_map.rs#L36-L36: Document path bases and layout requirements.
  • pnpm/crates/deps-preparer/src/package_map.rs#L47-L54: Document hoisted-map inputs and package-map write behavior.
  • pnpm/crates/deps-preparer/src/package_map.rs#L69-L69: Document the hoisted output target and errors.
  • pnpm/crates/deps-preparer/src/package_map.rs#L86-L86: Document lockfile-map semantics, including standard versus loose mode.
  • pnpm/crates/deps-preparer/src/package_map.rs#L229-L229: Document graph-map semantics and graph-directory requirements.
  • pnpm/crates/deps-preparer/src/pnp.rs#L17-L17: Document the .pnp.cjs output and write behavior.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L167-L167: Document canonical containment and None behavior.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L191-L192: Document selected-group ordering and output semantics.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L206-L206: Document symlink-only removal and the caller containment precondition.

As per coding guidelines, use rustdoc comments for public API contracts. As per path instructions, new public deps-preparer APIs must document observable contracts with rustdoc intra-links.

🤖 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-preparer/src/package_map.rs` around lines 13 - 21,
pnpm/crates/deps-preparer/src/package_map.rs lines 13-21: add rustdoc for
PACKAGE_MAP_FILENAME, PackageMap, and PackageMapPackage describing the filename
and serialized records; lines 36, 47-54, 69, 86, and 229: document each public
API’s path bases, layout and graph-directory requirements, hoisted and
lockfile-map inputs, standard versus loose mode, output targets, write side
effects, and errors using intra-links. In pnpm/crates/deps-preparer/src/pnp.rs
lines 17, document the .pnp.cjs output and write behavior. In
pnpm/crates/deps-preparer/src/prune_direct_deps.rs lines 167, 191-192, and 206,
document canonical containment and None behavior, selected-group ordering and
output semantics, and symlink-only removal; explicitly require callers to
confine the modules directory before invoking remove_direct_dep_link.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-preparer/src/remove_quarantine.rs (1)

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

Document the new public API contracts with rustdoc.

  • pnpm/crates/deps-preparer/src/remove_quarantine.rs#L44-L57: document the macOS quarantine-removal behavior and the non-macOS no-op behavior.
  • pnpm/crates/deps-preparer/src/retry_config.rs#L8-L8: document the Config to RetryOpts conversion contract and timeout units.
  • pnpm/crates/deps-preparer/src/store_init.rs#L15-L15: document that initialization is best effort and that failures only produce warnings.

As per coding guidelines, “Use rustdoc comments for public API contracts.” As per path instructions, “For the new public deps-preparer API, document observable contracts with rustdoc intra-links.”

🤖 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-preparer/src/remove_quarantine.rs` around lines 44 - 57, Add
rustdoc contracts at pnpm/crates/deps-preparer/src/remove_quarantine.rs:44-57
for remove_quarantine_from_native_binaries, covering macOS quarantine removal
and the non-macOS no-op; document the Config-to-RetryOpts conversion and timeout
units at pnpm/crates/deps-preparer/src/retry_config.rs:8-8; document best-effort
initialization and warning-only failures at
pnpm/crates/deps-preparer/src/store_init.rs:15-15, using rustdoc intra-links for
referenced public API symbols.

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-preparer/src/create_symlink_layout.rs`:
- Around line 20-25: Correct the rustdoc for virtual_node_modules_dir to state
only that the directory need not already exist; remove the inaccurate claim that
symlink_package pre-creates the parent before each link and the resulting
redundant-stat explanation. Keep the documentation focused on the public
contract, leaving implementation rationale to regular comments.

In `@pnpm/crates/deps-preparer/src/current_lockfile/tests.rs`:
- Line 1: Update the module-level documentation in the tests module to reference
all covered functions: filter_lockfile_for_current, materialization_closure,
merge_filtered_wanted_lockfile, merge_filtered_current_lockfile, and
extend_skipped_with_dependency_closure.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs`:
- Around line 61-63: Fix the documentation sentence near the background
prefetcher description by removing the dangling “the pnpr client's” possessive
and clearly attributing TarballPrefetcher to a single owner, consistent with the
parallel create_virtual_store documentation; preserve the parallel listing with
PrefetchingResolver.

---

Nitpick comments:
In `@pnpm/crates/deps-preparer/src/build_modules.rs`:
- Around line 264-265: Change normalize_build_dep_path from public to pub(crate)
so it is available only within the deps-preparer crate. Keep the existing
implementation and callers unchanged, and do not expose it through the crate’s
public re-exports.

In `@pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs`:
- Line 19: Restrict the concurrency probe test surface to crate visibility: make
LinkConcurrencyProbe in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19
pub(crate), change tests to pub(crate) mod tests in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297, and make
the link_concurrency_probe fields pub(crate) in
pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185,
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78, and
pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs:135.

In `@pnpm/crates/deps-preparer/src/deps_graph/tests.rs`:
- Around line 47-61: Update the test
registry_resolution_full_pkg_id_uses_integrity_verbatim to assert
node.full_pkg_id equals the complete expected package ID, including the exact
integrity value produced by registry_metadata(), rather than checking only a
prefix. Preserve the existing package and graph setup while ensuring truncated
or rewritten integrity content causes the test to fail.

In `@pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs`:
- Around line 95-104: Rename the test function self_loop_not_safe_flag to a name
that clearly states that a length-1 self-loop is considered safe, while
preserving its existing assertions and behavior.

In `@pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs`:
- Around line 479-500: In fill_children, replace the conditional
graph.get_mut(&dir) update with a direct mutable binding, since each dir comes
from graph.keys() and is guaranteed to exist. Assign the computed children
directly through that binding while preserving the existing child computation.

In `@pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs`:
- Around line 1-11: Merge the duplicate imports in the test module into the
existing top-level import block. Combine all symbols from the later super,
pacquet_lockfile, and std::collections imports with their corresponding
first-block imports, leaving each module imported exactly once and preserving
explicit import style.
- Around line 176-188: Extract the repeated empty Lockfile construction into an
empty_lockfile helper accepting packages and snapshots, and initialize all
shared fields there. Update the three affected tests to call the helper with
their respective packages and snapshots values while preserving the existing
test behavior.

In `@pnpm/crates/deps-preparer/src/hoisting_limits.rs`:
- Around line 22-52: Update get_hoisting_limits to use an exhaustive match on
mode instead of the two matches!(mode, ...) guards. Preserve the existing early
return for HoistingLimits::None and dependency-specific importer-border
behavior, while ensuring any future HoistingLimits variant causes a compile-time
exhaustiveness error rather than defaulting to workspace behavior.

In `@pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs`:
- Around line 42-65: Add a test alongside
dependencies_mode_borders_each_importer using only the “packages/foo” importer
and HoistingLimits::Dependencies. Assert get_hoisting_limits omits the ".@"
entry while still emitting the "packages%2Ffoo@workspace:packages/foo" key with
its expected dependency set.

In `@pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs`:
- Around line 484-487: Correct the doc comment above the test to describe its
actual coverage: concurrent force imports into separate targets (pkg-a and
pkg-b) both complete successfully and clear stale files. Remove the unsupported
claim about back-to-back staging-path uniqueness and rayon rename-target
collisions.

In `@pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs`:
- Around line 1722-1725: Replace the expect in the public run_hoisted_linker
flow with a dedicated HoistedLinkerError variant for missing
cas_paths_by_pkg_id, and propagate it through the existing Result-based error
path. Preserve the current linker behavior for Some values and the no-op
handling for installs without snapshots.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs`:
- Line 811: Add the #[must_use] attribute to the runtime_platform_selector
function, matching the existing annotations on unverified_fetch_is_allowed and
host_platform_selector so callers cannot silently discard its PlatformSelector
result.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs`:
- Around line 520-546: The three mem-cache install tests duplicate the full
InstallPackageBySnapshot construction. Extract a sibling helper near
run_snapshot_install_with_picker that accepts tarball_mem_cache:
Option<&Arc<MemCache>> and returns the install Result, centralizing the shared
fields; update the install sites around the referenced blocks to call it with
each cache variant.

In `@pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs`:
- Around line 27-178: Replace the exhaustive Config literal in create_config
with Config::new() and override only the fixture-dependent fields: store_dir,
modules_dir, virtual_store_dir, global_virtual_store_dir, cache_dir, registry,
and symlink/hoist when needed to preserve assertions. Remove the file-level
clippy::default_trait_access allowance if it is no longer used, and verify the
tests retain their expected defaults.

In `@pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs`:
- Around line 375-381: Update the Windows branch of the preexisting link setup
in the test to call pacquet_fs::symlink_dir instead of
std::os::windows::fs::symlink_dir, preserving the existing source and
destination paths and Unix behavior.

In `@pnpm/crates/deps-preparer/src/package_map.rs`:
- Around line 13-21: pnpm/crates/deps-preparer/src/package_map.rs lines 13-21:
add rustdoc for PACKAGE_MAP_FILENAME, PackageMap, and PackageMapPackage
describing the filename and serialized records; lines 36, 47-54, 69, 86, and
229: document each public API’s path bases, layout and graph-directory
requirements, hoisted and lockfile-map inputs, standard versus loose mode,
output targets, write side effects, and errors using intra-links. In
pnpm/crates/deps-preparer/src/pnp.rs lines 17, document the .pnp.cjs output and
write behavior. In pnpm/crates/deps-preparer/src/prune_direct_deps.rs lines 167,
191-192, and 206, document canonical containment and None behavior,
selected-group ordering and output semantics, and symlink-only removal;
explicitly require callers to confine the modules directory before invoking
remove_direct_dep_link.

In `@pnpm/crates/deps-preparer/src/package_map/tests.rs`:
- Around line 80-131: In the package map test, bind the rendered JSON value from
serde_json::to_value(&package_map) to a local variable, print it with eprintln!
using {} formatting immediately before assert_eq!, and compare that variable
against the expected JSON.

In `@pnpm/crates/deps-preparer/src/remove_quarantine.rs`:
- Around line 44-57: Add rustdoc contracts at
pnpm/crates/deps-preparer/src/remove_quarantine.rs:44-57 for
remove_quarantine_from_native_binaries, covering macOS quarantine removal and
the non-macOS no-op; document the Config-to-RetryOpts conversion and timeout
units at pnpm/crates/deps-preparer/src/retry_config.rs:8-8; document best-effort
initialization and warning-only failures at
pnpm/crates/deps-preparer/src/store_init.rs:15-15, using rustdoc intra-links for
referenced public API symbols.

In `@pnpm/crates/deps-preparer/src/virtual_store_layout.rs`:
- Around line 371-381: Add BTreeMap to the existing std::collections import in
collect_injected_deps and replace every fully qualified
std::collections::BTreeMap reference in its signature and body with BTreeMap,
without changing behavior.

In `@pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs`:
- Around line 68-88: Replace the six inline twelve-field PackageMetadata
literals in the affected tests with package_metadata calls, passing a registry
LockfileResolution and the existing version value (or None). Add one shared
registry_resolution(lead: &str) -> LockfileResolution helper beside
registry_metadata, and reuse it at each site without introducing additional
duplicated helpers.
🪄 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: a6836c74-059c-46f5-ab5a-57ba5c944845

📥 Commits

Reviewing files that changed from the base of the PR and between e3638c1 and 209b08e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (70)
  • Cargo.toml
  • pnpm/crates/cli/tests/multiple_importers.rs
  • pnpm/crates/deps-preparer/Cargo.toml
  • pnpm/crates/deps-preparer/src/build_modules.rs
  • pnpm/crates/deps-preparer/src/build_modules/tests.rs
  • pnpm/crates/deps-preparer/src/build_sequence.rs
  • pnpm/crates/deps-preparer/src/build_sequence/tests.rs
  • pnpm/crates/deps-preparer/src/create_symlink_layout.rs
  • pnpm/crates/deps-preparer/src/create_symlink_layout/tests.rs
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/deps-preparer/src/create_virtual_store.rs
  • pnpm/crates/deps-preparer/src/create_virtual_store/tests.rs
  • pnpm/crates/deps-preparer/src/current_lockfile.rs
  • pnpm/crates/deps-preparer/src/current_lockfile/tests.rs
  • pnpm/crates/deps-preparer/src/deps_graph.rs
  • pnpm/crates/deps-preparer/src/deps_graph/tests.rs
  • pnpm/crates/deps-preparer/src/graph_sequencer.rs
  • pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs
  • pnpm/crates/deps-preparer/src/hoist.rs
  • pnpm/crates/deps-preparer/src/hoist/tests.rs
  • pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs
  • pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs
  • pnpm/crates/deps-preparer/src/hoisting_limits.rs
  • pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs
  • pnpm/crates/deps-preparer/src/import_indexed_dir.rs
  • pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs
  • pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs
  • pnpm/crates/deps-preparer/src/install_frozen_lockfile/tests.rs
  • pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs
  • pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs
  • pnpm/crates/deps-preparer/src/install_package_from_registry.rs
  • pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs
  • pnpm/crates/deps-preparer/src/installability.rs
  • pnpm/crates/deps-preparer/src/installability/tests.rs
  • pnpm/crates/deps-preparer/src/lib.rs
  • pnpm/crates/deps-preparer/src/link_bins.rs
  • pnpm/crates/deps-preparer/src/link_bins/tests.rs
  • pnpm/crates/deps-preparer/src/link_file.rs
  • pnpm/crates/deps-preparer/src/link_file/tests.rs
  • pnpm/crates/deps-preparer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-preparer/src/link_hoisted_modules/tests.rs
  • pnpm/crates/deps-preparer/src/link_root_component_members.rs
  • pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs
  • pnpm/crates/deps-preparer/src/package_map.rs
  • pnpm/crates/deps-preparer/src/package_map/tests.rs
  • pnpm/crates/deps-preparer/src/pnp.rs
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs
  • pnpm/crates/deps-preparer/src/prune_direct_deps/tests.rs
  • pnpm/crates/deps-preparer/src/prune_stale_modules.rs
  • pnpm/crates/deps-preparer/src/remove_quarantine.rs
  • pnpm/crates/deps-preparer/src/remove_quarantine/tests.rs
  • pnpm/crates/deps-preparer/src/retry_config.rs
  • pnpm/crates/deps-preparer/src/safe_join_modules_dir.rs
  • pnpm/crates/deps-preparer/src/safe_join_modules_dir/tests.rs
  • pnpm/crates/deps-preparer/src/store_init.rs
  • pnpm/crates/deps-preparer/src/symlink_direct_dependencies.rs
  • pnpm/crates/deps-preparer/src/symlink_direct_dependencies/tests.rs
  • pnpm/crates/deps-preparer/src/symlink_package.rs
  • pnpm/crates/deps-preparer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-preparer/src/validate_lockfile_paths/tests.rs
  • pnpm/crates/deps-preparer/src/version_policy.rs
  • pnpm/crates/deps-preparer/src/virtual_store_layout.rs
  • pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs
  • pnpm/crates/package-manager/Cargo.toml
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md
💤 Files with no reviewable changes (2)
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/install.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.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🧹 Nitpick comments (20)
pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs (1)

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

Use pacquet_fs::symlink_dir for the pre-existing Windows link.

pacquet-fs falls back to a junction when true directory symlinks fail due to SeCreateSymbolicLinkPrivilege, while this test uses raw std::os::windows::fs::symlink_dir, which can fail on Windows CI. pacquet-fs is already declared for this crate, and production deps-preparer code uses the same helper for directory links.

🤖 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-preparer/src/link_root_component_members/tests.rs` around
lines 375 - 381, Update the Windows branch of the preexisting link setup in the
test to call pacquet_fs::symlink_dir instead of
std::os::windows::fs::symlink_dir, preserving the existing source and
destination paths and Unix behavior.

Source: Coding guidelines

pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs (1)

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

Add #[must_use] here for consistency.

This diff adds #[must_use] to unverified_fetch_is_allowed (line 785) and host_platform_selector (line 799). runtime_platform_selector is the same shape: a pure function whose only effect is the returned PlatformSelector. Discarding its result is always a bug.

♻️ Proposed change
+#[must_use]
 pub fn runtime_platform_selector(
     supported: Option<&pacquet_package_is_installable::SupportedArchitectures>,
 ) -> PlatformSelector {
🤖 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-preparer/src/install_package_by_snapshot.rs` at line 811,
Add the #[must_use] attribute to the runtime_platform_selector function,
matching the existing annotations on unverified_fetch_is_allowed and
host_platform_selector so callers cannot silently discard its PlatformSelector
result.
pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs (1)

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

Replace the exhaustive Config literal with Config::new() plus overrides.

create_config spells out roughly 145 fields, and about 40 of them are Default::default(). Every new field on pacquet_config::Config breaks this file. Sibling test modules in this crate already use the cheaper pattern: create_virtual_store/tests.rs calls Config::new() and then assigns only the fields under test. Adopting that here removes the whole literal, removes the need for the file-level clippy::default_trait_access expectation at lines 1-4, and keeps the fixture stable across Config changes.

Set only what these tests depend on: store_dir, modules_dir, virtual_store_dir, cache_dir, registry, and symlink/hoist if Config::new() does not already default them to the values asserted here.

♻️ Sketch of the replacement
fn create_config(
    store_dir: &Path,
    modules_dir: &Path,
    virtual_store_dir: &Path,
    cache_dir: &Path,
) -> Config {
    let mut config = Config::new();
    config.store_dir = StoreDir::new(store_dir);
    config.modules_dir = modules_dir.to_path_buf();
    config.virtual_store_dir = virtual_store_dir.to_path_buf();
    config.global_virtual_store_dir = virtual_store_dir.to_path_buf();
    config.cache_dir = cache_dir.to_path_buf();
    config.symlink = false;
    config
}

Verify each remaining assertion still holds against Config::new()'s defaults before dropping a field.

🤖 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-preparer/src/install_package_from_registry/tests.rs` around
lines 27 - 178, Replace the exhaustive Config literal in create_config with
Config::new() and override only the fixture-dependent fields: store_dir,
modules_dir, virtual_store_dir, global_virtual_store_dir, cache_dir, registry,
and symlink/hoist when needed to preserve assertions. Remove the file-level
clippy::default_trait_access allowance if it is no longer used, and verify the
tests retain their expected defaults.

Source: Path instructions

pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs (1)

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

Reuse one helper for the three mem-cache installs.

These three InstallPackageBySnapshot literals differ only in tarball_mem_cache. This file already defines run_snapshot_install_with_picker (lines 754-799) for exactly this purpose on the fetcher tests. Extract a sibling helper that takes tarball_mem_cache: Option<&Arc<MemCache>> and returns the Result, so a future field added to InstallPackageBySnapshot needs one edit instead of three.

Also applies to: 598-621, 673-696

🤖 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-preparer/src/install_package_by_snapshot/tests.rs` around
lines 520 - 546, The three mem-cache install tests duplicate the full
InstallPackageBySnapshot construction. Extract a sibling helper near
run_snapshot_install_with_picker that accepts tarball_mem_cache:
Option<&Arc<MemCache>> and returns the install Result, centralizing the shared
fields; update the install sites around the referenced blocks to call it with
each cache variant.
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs (1)

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

Keep the concurrency probe surface inside pacquet-deps-preparer. The probe, LinkConcurrencyGuard, and the link_concurrency_probe fields are only used for intra-crate tests, including the tests submodule, so pub(crate) is clearer here.

  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19: make LinkConcurrencyProbe pub(crate).
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297: make #[cfg(test)] mod tests use pub(crate) mod tests.
  • pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185: make the public field pub(crate) link_concurrency_probe inside the existing #[cfg(test)] block.
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78: make the public field for this type match pub(crate) too.
🤖 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-preparer/src/create_virtual_dir_by_snapshot/tests.rs` at
line 19, Restrict the concurrency probe test surface to crate visibility: make
LinkConcurrencyProbe in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19
pub(crate), change tests to pub(crate) mod tests in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297, and make
the link_concurrency_probe fields pub(crate) in
pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185,
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78, and
pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs:135.
pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs (1)

1722-1725: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider a typed error instead of expect now that run_hoisted_linker is public.

run_hoisted_linker is now pub, so package-manager and any future caller can pass cas_paths_by_pkg_id: None. Line 1725 turns that into a panic. The in-repo caller guards the value, so this is not currently reachable. A HoistedLinkerError variant would keep the newly public boundary on the typed-diagnostic path.

As per coding guidelines, pnpm/CODE_STYLE_GUIDE.md asks the new public deps-preparer API to "use typed error enums with proper propagation, avoid unnecessary unwrap".

♻️ Proposed refactor
 pub enum HoistedLinkerError {
     #[diagnostic(transparent)]
     HoistedDepGraph(#[error(source)] HoistedDepGraphError),
+    #[display("hoisted linking requires the CAS path index produced by CreateVirtualStore")]
+    #[diagnostic(code(ERR_PNPM_PACKAGE_MANAGER_MISSING_CAS_PATHS))]
+    MissingCasPaths,
-    let cas_index = cas_paths_by_pkg_id.expect("hoisted CreateVirtualStore populates cas_paths");
+    let cas_index = cas_paths_by_pkg_id.ok_or(HoistedLinkerError::MissingCasPaths)?;
🤖 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-preparer/src/install_frozen_lockfile.rs` around lines 1722 -
1725, Replace the expect in the public run_hoisted_linker flow with a dedicated
HoistedLinkerError variant for missing cas_paths_by_pkg_id, and propagate it
through the existing Result-based error path. Preserve the current linker
behavior for Some values and the no-op handling for installs without snapshots.

Source: Path instructions

pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs (1)

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

Rename self_loop_not_safe_flag; the name contradicts the assertion.

The test asserts result.safe is true for a length-1 self-loop, but the name reads as "not safe". A reader who scans test names concludes the opposite of the pinned behavior, and a later change could "fix" the assertion to match the name. Name it after the behavior it pins.

♻️ Proposed rename
-fn self_loop_not_safe_flag() {
+fn self_loop_does_not_clear_safe_flag() {
🤖 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-preparer/src/graph_sequencer/tests.rs` around lines 95 -
104, Rename the test function self_loop_not_safe_flag to a name that clearly
states that a length-1 self-loop is considered safe, while preserving its
existing assertions and behavior.
pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs (1)

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

Correct the doc comment; the test does not cover staging-name uniqueness.

The comment states that two staging paths produced back-to-back in the same process must differ, so concurrent rayon workers do not collide on the rename target. The test imports into two different targets (pkg-a and pkg-b), whose staging paths already differ by target path. It never exercises two staging names derived for the same target. Describe what the test verifies: two concurrent force imports into separate targets both complete and clear stale files.

♻️ Proposed comment fix
-/// Two staging paths produced back-to-back in the same process must
-/// differ — otherwise concurrent rayon workers would collide on the
-/// rename target. Uses the function indirectly via two force re-installs
-/// in parallel.
+/// Two force re-imports running in parallel against separate targets
+/// must both complete and clear their stale files. Staging-name
+/// uniqueness for a single target is not covered here.
🤖 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-preparer/src/import_indexed_dir/tests.rs` around lines 484 -
487, Correct the doc comment above the test to describe its actual coverage:
concurrent force imports into separate targets (pkg-a and pkg-b) both complete
successfully and clear stale files. Remove the unsupported claim about
back-to-back staging-path uniqueness and rayon rename-target collisions.
pnpm/crates/deps-preparer/src/deps_graph/tests.rs (1)

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

Assert the full full_pkg_id, not just its prefix.

The test name states the integrity is used verbatim, but the assertion only checks the prefix @scope/[email protected]:sha512-. It passes even if the integrity body is truncated or rewritten after that prefix. full_pkg_id feeds side-effects cache keys and global-virtual-store slot digests, so a change in integrity rendering moves store paths. Compare the whole string so the test enforces the contract its name claims.

♻️ Proposed tightening
     let graph = build_deps_graph(&snapshots, &packages);
     let node = graph.get(&pkg).expect("graph node");
-    let expected_prefix = "`@scope/foo`@1.0.0:sha512-";
-    assert!(
-        node.full_pkg_id.starts_with(expected_prefix),
-        "expected full_pkg_id to start with `{expected_prefix}`, got `{}`",
-        node.full_pkg_id,
-    );
+    let expected = format!("`@scope/foo`@1.0.0:{}", integrity());
+    assert_eq!(node.full_pkg_id, expected);
 }
🤖 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-preparer/src/deps_graph/tests.rs` around lines 47 - 61,
Update the test registry_resolution_full_pkg_id_uses_integrity_verbatim to
assert node.full_pkg_id equals the complete expected package ID, including the
exact integrity value produced by registry_metadata(), rather than checking only
a prefix. Preserve the existing package and graph setup while ensuring truncated
or rewritten integrity content causes the test to fail.
pnpm/crates/deps-preparer/src/build_modules.rs (1)

264-265: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Narrow normalize_build_dep_path to pub(crate).

normalize_build_dep_path is only callable from outside deps_preparer because of pub mod build_modules; plus pub use build_modules::*;, but the only current callers are inside deps-preparer. No Rust package-manager code uses it, so export it to the crate's public API only if a caller is intentionally required.

🤖 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-preparer/src/build_modules.rs` around lines 264 - 265,
Change normalize_build_dep_path from public to pub(crate) so it is available
only within the deps-preparer crate. Keep the existing implementation and
callers unchanged, and do not expose it through the crate’s public re-exports.
pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs (1)

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

Simplify the node update in fill_children.

Line 486 indexes graph[&dir], so the key is proven present. The if let Some(node) = graph.get_mut(&dir) guard on line 495 can never take the None branch. A direct &mut binding states the invariant and drops the dead branch.

♻️ Proposed simplification
         let snapshot = lockfile.snapshots.as_ref().and_then(|m| m.get(&pkg_key));
         let children = compute_children(snapshot, pkg_locations);
-        if let Some(node) = graph.get_mut(&dir) {
-            node.children = children;
-        }
+        graph.get_mut(&dir).expect("dir came from graph.keys()").children = children;
🤖 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-preparer/src/hoisted_dep_graph.rs` around lines 479 - 500,
In fill_children, replace the conditional graph.get_mut(&dir) update with a
direct mutable binding, since each dir comes from graph.keys() and is guaranteed
to exist. Assign the computed children directly through that binding while
preserving the existing child computation.
pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs (2)

1-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Merge the two import blocks into one.

Lines 1-11 and lines 96-102 both import from super, pacquet_lockfile, and std::collections. The style guide asks for merged explicit imports. Move the second block into the first so each module is imported once.

As per coding guidelines: "Prefer ... merged explicit imports".

Also applies to: 96-102

🤖 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-preparer/src/hoisted_dep_graph/tests.rs` around lines 1 -
11, Merge the duplicate imports in the test module into the existing top-level
import block. Combine all symbols from the later super, pacquet_lockfile, and
std::collections imports with their corresponding first-block imports, leaving
each module imported exactly once and preserving explicit import style.

Source: Path instructions


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

Extract the empty-Lockfile literal into a fixture helper.

Three tests repeat the same 13-field Lockfile literal, differing only in packages and snapshots. A helper such as empty_lockfile(packages, snapshots) removes the duplication and keeps future field additions to one site.

Also applies to: 595-607, 633-645

🤖 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-preparer/src/hoisted_dep_graph/tests.rs` around lines 176 -
188, Extract the repeated empty Lockfile construction into an empty_lockfile
helper accepting packages and snapshots, and initialize all shared fields there.
Update the three affected tests to call the helper with their respective
packages and snapshots values while preserving the existing test behavior.
pnpm/crates/deps-preparer/src/virtual_store_layout.rs (1)

371-381: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import BTreeMap instead of writing the full path inline.

Line 40 already imports std::collections::{HashMap, HashSet}. The collect_injected_deps signature and body spell out std::collections::BTreeMap five times. Add BTreeMap to that import and shorten the occurrences.

As per coding guidelines: "Prefer ... merged explicit imports".

♻️ Proposed change
 use std::{
-    collections::{HashMap, HashSet},
+    collections::{BTreeMap, HashMap, HashSet},
     path::{Path, PathBuf},
 };
     skipped: &crate::SkippedSnapshots,
-    hoisted_locations: Option<&std::collections::BTreeMap<String, Vec<String>>>,
-) -> std::collections::BTreeMap<String, Vec<String>> {
-    let mut injected: std::collections::BTreeMap<String, Vec<String>> =
-        std::collections::BTreeMap::new();
+    hoisted_locations: Option<&BTreeMap<String, Vec<String>>>,
+) -> BTreeMap<String, Vec<String>> {
+    let mut injected: BTreeMap<String, Vec<String>> = BTreeMap::new();
🤖 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-preparer/src/virtual_store_layout.rs` around lines 371 -
381, Add BTreeMap to the existing std::collections import in
collect_injected_deps and replace every fully qualified
std::collections::BTreeMap reference in its signature and body with BTreeMap,
without changing behavior.

Source: Path instructions

pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs (1)

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

Add a test for the no-root-importer case.

get_hoisting_limits only emits the .@ entry when a root importer is present (root_present at pnpm/crates/deps-preparer/src/hoisting_limits.rs line 54). That branch is documented as upstream parity behavior, and no test covers it. A test with only packages/foo in importers under Dependencies mode should assert that .@ is absent and that the per-importer key is still emitted.

🤖 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-preparer/src/hoisting_limits/tests.rs` around lines 42 - 65,
Add a test alongside dependencies_mode_borders_each_importer using only the
“packages/foo” importer and HoistingLimits::Dependencies. Assert
get_hoisting_limits omits the ".@" entry while still emitting the
"packages%2Ffoo@workspace:packages/foo" key with its expected dependency set.
pnpm/crates/deps-preparer/src/hoisting_limits.rs (1)

22-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider an exhaustive match on mode instead of two matches! guards.

get_hoisting_limits tests mode twice with matches!. If pacquet_config::HoistingLimits gains a variant, that variant silently takes the Workspaces behavior. An exhaustive match on mode makes the compiler flag the new variant.

🤖 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-preparer/src/hoisting_limits.rs` around lines 22 - 52,
Update get_hoisting_limits to use an exhaustive match on mode instead of the two
matches!(mode, ...) guards. Preserve the existing early return for
HoistingLimits::None and dependency-specific importer-border behavior, while
ensuring any future HoistingLimits variant causes a compile-time exhaustiveness
error rather than defaulting to workspace behavior.
pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs (1)

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

Reuse package_metadata for the inline PackageMetadata literals.

Line 27 defines package_metadata(resolution, version) and line 800 defines registry_metadata(lead). Six more sites still spell out all twelve fields of PackageMetadata, and every one sets the same nine fields to None. A new field on PackageMetadata then requires six edits. Route these sites through package_metadata with a registry resolution.

As per coding guidelines: "Keep the change focused, avoid duplicated helpers".

♻️ Example for the first site
     let mut packages = HashMap::new();
     packages.insert(
         key.clone(),
-        PackageMetadata {
-            resolution: LockfileResolution::Registry(RegistryResolution {
-                integrity: "sha512-AAAA...AAAA"
-                    .parse()
-                    .expect("parse integrity"),
-            }),
-            version: None,
-            engines: None,
-            cpu: None,
-            os: None,
-            libc: None,
-            deprecated: None,
-            has_bin: None,
-            prepare: None,
-            bundled_dependencies: None,
-            peer_dependencies: None,
-            peer_dependencies_meta: None,
-        },
+        package_metadata(registry_resolution("A"), None),
     );

Add a small registry_resolution(lead: &str) -> LockfileResolution helper next to registry_metadata, which can then be expressed as package_metadata(registry_resolution(lead), None).

Also applies to: 122-142, 168-188, 225-245, 346-366, 419-440

🤖 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-preparer/src/virtual_store_layout/tests.rs` around lines 68
- 88, Replace the six inline twelve-field PackageMetadata literals in the
affected tests with package_metadata calls, passing a registry
LockfileResolution and the existing version value (or None). Add one shared
registry_resolution(lead: &str) -> LockfileResolution helper beside
registry_metadata, and reuse it at each site without introducing additional
duplicated helpers.

Source: Path instructions

pnpm/crates/deps-preparer/src/package_map/tests.rs (1)

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

Log the rendered package map before the comparison.

This assertion compares a large structured value. Bind the actual JSON and emit it with eprintln! before assert_eq!. This keeps regression output readable.

Proposed change
-    assert_eq!(
-        serde_json::to_value(&package_map).expect("serialize package map"),
+    let actual = serde_json::to_value(&package_map).expect("serialize package map");
+    eprintln!("PACKAGE MAP:\n{actual}\n");
+    assert_eq!(
+        actual,

As per path instructions, log complex values before non-equality assertions. Based on learnings, emit the rendered value with eprintln! using {} formatting before the assertion.

🤖 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-preparer/src/package_map/tests.rs` around lines 80 - 131, In
the package map test, bind the rendered JSON value from
serde_json::to_value(&package_map) to a local variable, print it with eprintln!
using {} formatting immediately before assert_eq!, and compare that variable
against the expected JSON.

Sources: Path instructions, Learnings

pnpm/crates/deps-preparer/src/package_map.rs (1)

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

Document the exported deps-preparer API contracts.

These items now cross crate boundaries but lack rustdoc contracts. Document path bases, side effects, errors, and required caller invariants. For remove_direct_dep_link, state that callers must first confine the modules directory.

  • pnpm/crates/deps-preparer/src/package_map.rs#L13-L21: Document the filename and serialized package-map records.
  • pnpm/crates/deps-preparer/src/package_map.rs#L36-L36: Document path bases and layout requirements.
  • pnpm/crates/deps-preparer/src/package_map.rs#L47-L54: Document hoisted-map inputs and package-map write behavior.
  • pnpm/crates/deps-preparer/src/package_map.rs#L69-L69: Document the hoisted output target and errors.
  • pnpm/crates/deps-preparer/src/package_map.rs#L86-L86: Document lockfile-map semantics, including standard versus loose mode.
  • pnpm/crates/deps-preparer/src/package_map.rs#L229-L229: Document graph-map semantics and graph-directory requirements.
  • pnpm/crates/deps-preparer/src/pnp.rs#L17-L17: Document the .pnp.cjs output and write behavior.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L167-L167: Document canonical containment and None behavior.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L191-L192: Document selected-group ordering and output semantics.
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs#L206-L206: Document symlink-only removal and the caller containment precondition.

As per coding guidelines, use rustdoc comments for public API contracts. As per path instructions, new public deps-preparer APIs must document observable contracts with rustdoc intra-links.

🤖 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-preparer/src/package_map.rs` around lines 13 - 21,
pnpm/crates/deps-preparer/src/package_map.rs lines 13-21: add rustdoc for
PACKAGE_MAP_FILENAME, PackageMap, and PackageMapPackage describing the filename
and serialized records; lines 36, 47-54, 69, 86, and 229: document each public
API’s path bases, layout and graph-directory requirements, hoisted and
lockfile-map inputs, standard versus loose mode, output targets, write side
effects, and errors using intra-links. In pnpm/crates/deps-preparer/src/pnp.rs
lines 17, document the .pnp.cjs output and write behavior. In
pnpm/crates/deps-preparer/src/prune_direct_deps.rs lines 167, 191-192, and 206,
document canonical containment and None behavior, selected-group ordering and
output semantics, and symlink-only removal; explicitly require callers to
confine the modules directory before invoking remove_direct_dep_link.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-preparer/src/remove_quarantine.rs (1)

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

Document the new public API contracts with rustdoc.

  • pnpm/crates/deps-preparer/src/remove_quarantine.rs#L44-L57: document the macOS quarantine-removal behavior and the non-macOS no-op behavior.
  • pnpm/crates/deps-preparer/src/retry_config.rs#L8-L8: document the Config to RetryOpts conversion contract and timeout units.
  • pnpm/crates/deps-preparer/src/store_init.rs#L15-L15: document that initialization is best effort and that failures only produce warnings.

As per coding guidelines, “Use rustdoc comments for public API contracts.” As per path instructions, “For the new public deps-preparer API, document observable contracts with rustdoc intra-links.”

🤖 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-preparer/src/remove_quarantine.rs` around lines 44 - 57, Add
rustdoc contracts at pnpm/crates/deps-preparer/src/remove_quarantine.rs:44-57
for remove_quarantine_from_native_binaries, covering macOS quarantine removal
and the non-macOS no-op; document the Config-to-RetryOpts conversion and timeout
units at pnpm/crates/deps-preparer/src/retry_config.rs:8-8; document best-effort
initialization and warning-only failures at
pnpm/crates/deps-preparer/src/store_init.rs:15-15, using rustdoc intra-links for
referenced public API symbols.

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-preparer/src/create_symlink_layout.rs`:
- Around line 20-25: Correct the rustdoc for virtual_node_modules_dir to state
only that the directory need not already exist; remove the inaccurate claim that
symlink_package pre-creates the parent before each link and the resulting
redundant-stat explanation. Keep the documentation focused on the public
contract, leaving implementation rationale to regular comments.

In `@pnpm/crates/deps-preparer/src/current_lockfile/tests.rs`:
- Line 1: Update the module-level documentation in the tests module to reference
all covered functions: filter_lockfile_for_current, materialization_closure,
merge_filtered_wanted_lockfile, merge_filtered_current_lockfile, and
extend_skipped_with_dependency_closure.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs`:
- Around line 61-63: Fix the documentation sentence near the background
prefetcher description by removing the dangling “the pnpr client's” possessive
and clearly attributing TarballPrefetcher to a single owner, consistent with the
parallel create_virtual_store documentation; preserve the parallel listing with
PrefetchingResolver.

---

Nitpick comments:
In `@pnpm/crates/deps-preparer/src/build_modules.rs`:
- Around line 264-265: Change normalize_build_dep_path from public to pub(crate)
so it is available only within the deps-preparer crate. Keep the existing
implementation and callers unchanged, and do not expose it through the crate’s
public re-exports.

In `@pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs`:
- Line 19: Restrict the concurrency probe test surface to crate visibility: make
LinkConcurrencyProbe in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs:19
pub(crate), change tests to pub(crate) mod tests in
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:297, and make
the link_concurrency_probe fields pub(crate) in
pnpm/crates/deps-preparer/src/create_virtual_store.rs:183-185,
pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs:77-78, and
pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs:135.

In `@pnpm/crates/deps-preparer/src/deps_graph/tests.rs`:
- Around line 47-61: Update the test
registry_resolution_full_pkg_id_uses_integrity_verbatim to assert
node.full_pkg_id equals the complete expected package ID, including the exact
integrity value produced by registry_metadata(), rather than checking only a
prefix. Preserve the existing package and graph setup while ensuring truncated
or rewritten integrity content causes the test to fail.

In `@pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs`:
- Around line 95-104: Rename the test function self_loop_not_safe_flag to a name
that clearly states that a length-1 self-loop is considered safe, while
preserving its existing assertions and behavior.

In `@pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs`:
- Around line 479-500: In fill_children, replace the conditional
graph.get_mut(&dir) update with a direct mutable binding, since each dir comes
from graph.keys() and is guaranteed to exist. Assign the computed children
directly through that binding while preserving the existing child computation.

In `@pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs`:
- Around line 1-11: Merge the duplicate imports in the test module into the
existing top-level import block. Combine all symbols from the later super,
pacquet_lockfile, and std::collections imports with their corresponding
first-block imports, leaving each module imported exactly once and preserving
explicit import style.
- Around line 176-188: Extract the repeated empty Lockfile construction into an
empty_lockfile helper accepting packages and snapshots, and initialize all
shared fields there. Update the three affected tests to call the helper with
their respective packages and snapshots values while preserving the existing
test behavior.

In `@pnpm/crates/deps-preparer/src/hoisting_limits.rs`:
- Around line 22-52: Update get_hoisting_limits to use an exhaustive match on
mode instead of the two matches!(mode, ...) guards. Preserve the existing early
return for HoistingLimits::None and dependency-specific importer-border
behavior, while ensuring any future HoistingLimits variant causes a compile-time
exhaustiveness error rather than defaulting to workspace behavior.

In `@pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs`:
- Around line 42-65: Add a test alongside
dependencies_mode_borders_each_importer using only the “packages/foo” importer
and HoistingLimits::Dependencies. Assert get_hoisting_limits omits the ".@"
entry while still emitting the "packages%2Ffoo@workspace:packages/foo" key with
its expected dependency set.

In `@pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs`:
- Around line 484-487: Correct the doc comment above the test to describe its
actual coverage: concurrent force imports into separate targets (pkg-a and
pkg-b) both complete successfully and clear stale files. Remove the unsupported
claim about back-to-back staging-path uniqueness and rayon rename-target
collisions.

In `@pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs`:
- Around line 1722-1725: Replace the expect in the public run_hoisted_linker
flow with a dedicated HoistedLinkerError variant for missing
cas_paths_by_pkg_id, and propagate it through the existing Result-based error
path. Preserve the current linker behavior for Some values and the no-op
handling for installs without snapshots.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs`:
- Line 811: Add the #[must_use] attribute to the runtime_platform_selector
function, matching the existing annotations on unverified_fetch_is_allowed and
host_platform_selector so callers cannot silently discard its PlatformSelector
result.

In `@pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs`:
- Around line 520-546: The three mem-cache install tests duplicate the full
InstallPackageBySnapshot construction. Extract a sibling helper near
run_snapshot_install_with_picker that accepts tarball_mem_cache:
Option<&Arc<MemCache>> and returns the install Result, centralizing the shared
fields; update the install sites around the referenced blocks to call it with
each cache variant.

In `@pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs`:
- Around line 27-178: Replace the exhaustive Config literal in create_config
with Config::new() and override only the fixture-dependent fields: store_dir,
modules_dir, virtual_store_dir, global_virtual_store_dir, cache_dir, registry,
and symlink/hoist when needed to preserve assertions. Remove the file-level
clippy::default_trait_access allowance if it is no longer used, and verify the
tests retain their expected defaults.

In `@pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs`:
- Around line 375-381: Update the Windows branch of the preexisting link setup
in the test to call pacquet_fs::symlink_dir instead of
std::os::windows::fs::symlink_dir, preserving the existing source and
destination paths and Unix behavior.

In `@pnpm/crates/deps-preparer/src/package_map.rs`:
- Around line 13-21: pnpm/crates/deps-preparer/src/package_map.rs lines 13-21:
add rustdoc for PACKAGE_MAP_FILENAME, PackageMap, and PackageMapPackage
describing the filename and serialized records; lines 36, 47-54, 69, 86, and
229: document each public API’s path bases, layout and graph-directory
requirements, hoisted and lockfile-map inputs, standard versus loose mode,
output targets, write side effects, and errors using intra-links. In
pnpm/crates/deps-preparer/src/pnp.rs lines 17, document the .pnp.cjs output and
write behavior. In pnpm/crates/deps-preparer/src/prune_direct_deps.rs lines 167,
191-192, and 206, document canonical containment and None behavior,
selected-group ordering and output semantics, and symlink-only removal;
explicitly require callers to confine the modules directory before invoking
remove_direct_dep_link.

In `@pnpm/crates/deps-preparer/src/package_map/tests.rs`:
- Around line 80-131: In the package map test, bind the rendered JSON value from
serde_json::to_value(&package_map) to a local variable, print it with eprintln!
using {} formatting immediately before assert_eq!, and compare that variable
against the expected JSON.

In `@pnpm/crates/deps-preparer/src/remove_quarantine.rs`:
- Around line 44-57: Add rustdoc contracts at
pnpm/crates/deps-preparer/src/remove_quarantine.rs:44-57 for
remove_quarantine_from_native_binaries, covering macOS quarantine removal and
the non-macOS no-op; document the Config-to-RetryOpts conversion and timeout
units at pnpm/crates/deps-preparer/src/retry_config.rs:8-8; document best-effort
initialization and warning-only failures at
pnpm/crates/deps-preparer/src/store_init.rs:15-15, using rustdoc intra-links for
referenced public API symbols.

In `@pnpm/crates/deps-preparer/src/virtual_store_layout.rs`:
- Around line 371-381: Add BTreeMap to the existing std::collections import in
collect_injected_deps and replace every fully qualified
std::collections::BTreeMap reference in its signature and body with BTreeMap,
without changing behavior.

In `@pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs`:
- Around line 68-88: Replace the six inline twelve-field PackageMetadata
literals in the affected tests with package_metadata calls, passing a registry
LockfileResolution and the existing version value (or None). Add one shared
registry_resolution(lead: &str) -> LockfileResolution helper beside
registry_metadata, and reuse it at each site without introducing additional
duplicated helpers.
🪄 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: a6836c74-059c-46f5-ab5a-57ba5c944845

📥 Commits

Reviewing files that changed from the base of the PR and between e3638c1 and 209b08e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (70)
  • Cargo.toml
  • pnpm/crates/cli/tests/multiple_importers.rs
  • pnpm/crates/deps-preparer/Cargo.toml
  • pnpm/crates/deps-preparer/src/build_modules.rs
  • pnpm/crates/deps-preparer/src/build_modules/tests.rs
  • pnpm/crates/deps-preparer/src/build_sequence.rs
  • pnpm/crates/deps-preparer/src/build_sequence/tests.rs
  • pnpm/crates/deps-preparer/src/create_symlink_layout.rs
  • pnpm/crates/deps-preparer/src/create_symlink_layout/tests.rs
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-preparer/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/deps-preparer/src/create_virtual_store.rs
  • pnpm/crates/deps-preparer/src/create_virtual_store/tests.rs
  • pnpm/crates/deps-preparer/src/current_lockfile.rs
  • pnpm/crates/deps-preparer/src/current_lockfile/tests.rs
  • pnpm/crates/deps-preparer/src/deps_graph.rs
  • pnpm/crates/deps-preparer/src/deps_graph/tests.rs
  • pnpm/crates/deps-preparer/src/graph_sequencer.rs
  • pnpm/crates/deps-preparer/src/graph_sequencer/tests.rs
  • pnpm/crates/deps-preparer/src/hoist.rs
  • pnpm/crates/deps-preparer/src/hoist/tests.rs
  • pnpm/crates/deps-preparer/src/hoisted_dep_graph.rs
  • pnpm/crates/deps-preparer/src/hoisted_dep_graph/tests.rs
  • pnpm/crates/deps-preparer/src/hoisting_limits.rs
  • pnpm/crates/deps-preparer/src/hoisting_limits/tests.rs
  • pnpm/crates/deps-preparer/src/import_indexed_dir.rs
  • pnpm/crates/deps-preparer/src/import_indexed_dir/tests.rs
  • pnpm/crates/deps-preparer/src/install_frozen_lockfile.rs
  • pnpm/crates/deps-preparer/src/install_frozen_lockfile/tests.rs
  • pnpm/crates/deps-preparer/src/install_package_by_snapshot.rs
  • pnpm/crates/deps-preparer/src/install_package_by_snapshot/tests.rs
  • pnpm/crates/deps-preparer/src/install_package_from_registry.rs
  • pnpm/crates/deps-preparer/src/install_package_from_registry/tests.rs
  • pnpm/crates/deps-preparer/src/installability.rs
  • pnpm/crates/deps-preparer/src/installability/tests.rs
  • pnpm/crates/deps-preparer/src/lib.rs
  • pnpm/crates/deps-preparer/src/link_bins.rs
  • pnpm/crates/deps-preparer/src/link_bins/tests.rs
  • pnpm/crates/deps-preparer/src/link_file.rs
  • pnpm/crates/deps-preparer/src/link_file/tests.rs
  • pnpm/crates/deps-preparer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-preparer/src/link_hoisted_modules/tests.rs
  • pnpm/crates/deps-preparer/src/link_root_component_members.rs
  • pnpm/crates/deps-preparer/src/link_root_component_members/tests.rs
  • pnpm/crates/deps-preparer/src/package_map.rs
  • pnpm/crates/deps-preparer/src/package_map/tests.rs
  • pnpm/crates/deps-preparer/src/pnp.rs
  • pnpm/crates/deps-preparer/src/prune_direct_deps.rs
  • pnpm/crates/deps-preparer/src/prune_direct_deps/tests.rs
  • pnpm/crates/deps-preparer/src/prune_stale_modules.rs
  • pnpm/crates/deps-preparer/src/remove_quarantine.rs
  • pnpm/crates/deps-preparer/src/remove_quarantine/tests.rs
  • pnpm/crates/deps-preparer/src/retry_config.rs
  • pnpm/crates/deps-preparer/src/safe_join_modules_dir.rs
  • pnpm/crates/deps-preparer/src/safe_join_modules_dir/tests.rs
  • pnpm/crates/deps-preparer/src/store_init.rs
  • pnpm/crates/deps-preparer/src/symlink_direct_dependencies.rs
  • pnpm/crates/deps-preparer/src/symlink_direct_dependencies/tests.rs
  • pnpm/crates/deps-preparer/src/symlink_package.rs
  • pnpm/crates/deps-preparer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-preparer/src/validate_lockfile_paths/tests.rs
  • pnpm/crates/deps-preparer/src/version_policy.rs
  • pnpm/crates/deps-preparer/src/virtual_store_layout.rs
  • pnpm/crates/deps-preparer/src/virtual_store_layout/tests.rs
  • pnpm/crates/package-manager/Cargo.toml
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md
💤 Files with no reviewable changes (2)
  • pnpm/crates/package-manager/src/install_with_fresh_lockfile.rs
  • pnpm/crates/package-manager/src/install.rs
🛑 Comments failed to post (2)
pnpm/crates/deps-preparer/src/create_symlink_layout.rs (1)

20-25: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the parent-directory claim in the rustdoc.

The doc states that symlink_package calls fs::create_dir_all on the symlink path's parent "before each link", and concludes that callers which already created the directory pay redundant stat syscalls. symlink_package documents the opposite mechanism at pnpm/crates/deps-preparer/src/symlink_package.rs lines 58-64: force_symlink_dir does not pre-create the parent. It creates the parent only after a NotFound failure, and avoiding the extra stat per symlink is the stated reason for that design.

The observable contract is correct — virtual_node_modules_dir does not have to exist. Only the mechanism and the cost note are wrong. Keeping them accurate prevents a later change from reintroducing the pre-link stat this design avoids.

📝 Proposed doc fix
 /// `virtual_node_modules_dir` does not have to exist —
-/// `symlink_package` calls `fs::create_dir_all` on the symlink path's
-/// parent before each link. Callers that already know the directory
-/// exists (e.g. `CreateVirtualStore::run`, which `mkdir`s it just
-/// before calling this function) just pay redundant stat syscalls,
-/// which is cheap and matches pnpm's own redundant-mkdir shape.
+/// `symlink_package` recovers from a missing parent by calling
+/// `create_dir_all` once and reissuing the symlink syscall. Callers
+/// that already know the directory exists (e.g.
+/// `CreateVirtualStore::run`, which `mkdir`s it just before calling
+/// this function) pay nothing extra, because there is no pre-link
+/// stat on the common path.

As per coding guidelines: "Use rustdoc comments for public API contracts and regular comments for implementation rationale. Do not duplicate test behavior in documentation; comments should explain only non-obvious reasons or invariants."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/// `virtual_node_modules_dir` does not have to exist —
/// `symlink_package` recovers from a missing parent by calling
/// `create_dir_all` once and reissuing the symlink syscall. Callers
/// that already know the directory exists (e.g.
/// `CreateVirtualStore::run`, which `mkdir`s it just before calling
/// this function) pay nothing extra, because there is no pre-link
/// stat on the common path.
🤖 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-preparer/src/create_symlink_layout.rs` around lines 20 - 25,
Correct the rustdoc for virtual_node_modules_dir to state only that the
directory need not already exist; remove the inaccurate claim that
symlink_package pre-creates the parent before each link and the resulting
redundant-stat explanation. Keep the documentation focused on the public
contract, leaving implementation rationale to regular comments.

Source: Coding guidelines

pnpm/crates/deps-preparer/src/current_lockfile/tests.rs (1)

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

Update the module doc to match the file scope.

The module doc names only super::filter_lockfile_for_current. The file now also tests materialization_closure, merge_filtered_wanted_lockfile, merge_filtered_current_lockfile, and extend_skipped_with_dependency_closure. A reader who searches for the merge tests will not find them from this header.

📝 Proposed doc fix
-//! Unit tests for [`super::filter_lockfile_for_current`].
+//! Unit tests for the current-lockfile module: [`super::filter_lockfile_for_current`],
+//! [`super::materialization_closure`], [`super::merge_filtered_wanted_lockfile`],
+//! [`super::merge_filtered_current_lockfile`], and
+//! [`super::extend_skipped_with_dependency_closure`].
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

//! Unit tests for the current-lockfile module: [`super::filter_lockfile_for_current`],
//! [`super::materialization_closure`], [`super::merge_filtered_wanted_lockfile`],
//! [`super::merge_filtered_current_lockfile`], and
//! [`super::extend_skipped_with_dependency_closure`].
🤖 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-preparer/src/current_lockfile/tests.rs` at line 1, Update
the module-level documentation in the tests module to reference all covered
functions: filter_lockfile_for_current, materialization_closure,
merge_filtered_wanted_lockfile, merge_filtered_current_lockfile, and
extend_skipped_with_dependency_closure.

Copilot AI review requested due to automatic review settings August 4, 2026 10: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.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 23584da

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.04%. Comparing base (d4a9248) to head (19bd9c3).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13637      +/-   ##
==========================================
- Coverage   88.05%   88.04%   -0.02%     
==========================================
  Files         573      574       +1     
  Lines       98390    98386       -4     
==========================================
- Hits        86642    86628      -14     
- Misses      11748    11758      +10     

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

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

Copilot AI review requested due to automatic review settings August 4, 2026 11:10

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.

@zkochan zkochan changed the title refactor(deps-preparer): extract headless install refactor(deps-restorer): extract headless install Aug 4, 2026
Copilot AI review requested due to automatic review settings August 4, 2026 11:14
@zkochan
zkochan force-pushed the refactor-headless-install branch from 6d0ff26 to 19bd9c3 Compare August 4, 2026 11:14

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.

@zkochan
zkochan merged commit e719786 into main Aug 4, 2026
28 of 29 checks passed
@zkochan
zkochan deleted the refactor-headless-install branch August 4, 2026 11:18
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 19bd9c3

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

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/hoist.rs (1)

65-70: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Justify the wider API surface and document build_hoist_graph_with_max_length.

compute_hoist_plan calls this internally, and pacquet/package-manager depends on pacquet-deps-restorer without importing the helper itself. Keep the helper private to crate::hoist or mark it as a deliberate extraction API. If it remains pub, add rustdoc that states the degraded behavior for missing metadata and how virtual_store_dir_max_length affects sort_key ordering.

🤖 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/hoist.rs` around lines 65 - 70, The public
build_hoist_graph_with_max_length API needs justification and documentation.
Prefer making build_hoist_graph_with_max_length private to crate::hoist if
external callers do not require it; otherwise add rustdoc describing degraded
behavior when metadata is missing and how virtual_store_dir_max_length
influences sort_key ordering.

Source: Coding guidelines

🧹 Nitpick comments (7)
pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs (2)

396-397: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert a symlink, not mere existence, for the second-visit link.

Path::exists follows the link and also returns true for a real directory. The assertion therefore does not prove the second visit created the per-parent symlink. Use the same helper the sibling tests use.

💚 Suggested assertion
     let symlink_path = second_parent_dir.path().join("second-alias");
-    assert!(symlink_path.exists() || symlink_path.is_symlink(), "per-parent symlink missing");
+    assert!(
+        pacquet_testing_utils::fs::is_symlink_or_junction(&symlink_path)
+            .expect("inspect per-parent link"),
+        "per-parent symlink missing at {symlink_path:?}",
+    );
🤖 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/install_package_from_registry/tests.rs` around
lines 396 - 397, Update the assertion for second-alias in the relevant
install-package test to use the existing symlink-specific helper used by sibling
tests, ensuring it verifies the path is actually a symlink rather than merely an
existing directory.

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

Build the test Config from Config::new() instead of a full struct literal.

create_config names about 145 fields. Sibling test modules in the same crate build their config from Config::new() and override only the fields they care about — see pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs lines 114-121 and pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs lines 55-59. The literal here duplicates the whole config surface, so every new Config field breaks this file alone. The #![expect(clippy::default_trait_access)] at the top of the file exists only to support the literal.

Rewrite create_config in the same shape as the sibling modules and drop the file-level expect.

As per coding guidelines from AGENTS.md "Code Reuse and Avoiding Duplication": before adding code, verify no helper is duplicated elsewhere.

♻️ Suggested shape
 fn create_config(
     store_dir: &Path,
     modules_dir: &Path,
     virtual_store_dir: &Path,
     cache_dir: &Path,
 ) -> Config {
-    Config {
-        versioning: Default::default(),
-        // ... ~145 fields ...
-        config_dir: None,
-    }
+    let mut config = Config::new();
+    config.store_dir = StoreDir::new(store_dir);
+    config.modules_dir = modules_dir.to_path_buf();
+    config.virtual_store_dir = virtual_store_dir.to_path_buf();
+    config.global_virtual_store_dir = virtual_store_dir.to_path_buf();
+    config.cache_dir = cache_dir.to_path_buf();
+    config
 }

Add only the extra overrides the tests actually depend on, such as registry, verify_store_integrity, and child_concurrency.

🤖 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/install_package_from_registry/tests.rs` around
lines 27 - 178, Replace the full struct literal in create_config with
Config::new(), overriding only the test-required fields such as store_dir,
modules_dir, virtual_store_dir, cache_dir, registry, verify_store_integrity, and
child_concurrency. Match the initialization pattern used by the sibling test
modules, and remove the file-level clippy::default_trait_access expectation
since it is no longer needed.

Source: Path instructions

pnpm/crates/deps-restorer/src/link_file.rs (1)

30-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Correct the stated location of the downgrade statics.

Both comments say the process-global state lives inside link_file. AUTO_STATE and CLONE_OR_COPY_STATE are declared inside try_import at lines 210 and 237. Point the comments at try_import so a reader can find the state.

📝 Suggested wording
-// These are the state *values*, not the cache itself: each mode keeps
-// its own process-global `AtomicU8` (`AUTO_STATE` inside `link_file`,
-// `CLONE_OR_COPY_STATE` likewise), so an `Auto` downgrade doesn't
-// affect `CloneOrCopy` and vice versa.
+// These are the state *values*, not the cache itself: each mode keeps
+// its own process-global `AtomicU8` (`AUTO_STATE` and
+// `CLONE_OR_COPY_STATE`, both declared inside `try_import`), so an
+// `Auto` downgrade doesn't affect `CloneOrCopy` and vice versa.
-/// pass their own `AtomicU8` and exercise the downgrade logic in
-/// isolation — the production path uses a `static` declared inside
-/// [`link_file`]. Only capability / cross-device style failures
+/// pass their own `AtomicU8` and exercise the downgrade logic in
+/// isolation — the production path uses the `AUTO_STATE` `static`
+/// declared inside `try_import`. Only capability / cross-device style failures

Also applies to: 305-312

🤖 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/link_file.rs` around lines 30 - 34, Update the
comments describing AUTO_STATE and CLONE_OR_COPY_STATE to state that each
process-global AtomicU8 is declared inside try_import, replacing the incorrect
reference to link_file. Apply this correction to both comment blocks while
preserving their explanation that the states are independent.
pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs (1)

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

Collapse the duplicated rustdoc blocks.

Each of these two items carries the contract twice. On validate_importer_id, lines 275-282 describe rejecting keys that resolve outside the workspace root, and lines 283-288 restate the same rule with the same rejected shapes. On importer_root_dir, lines 377-383 explain the "." root key and POSIX resolution, and lines 384-385 restate the return value. Keep one statement of each contract.

As per coding guidelines: "Use rustdoc comments for public API contracts... Do not duplicate test behavior in documentation; comments should explain only non-obvious reasons or invariants." pnpm/CODE_STYLE_GUIDE.md adds: "Do not repeat what the code already says."

📝 Suggested consolidation
 /// Reject importer keys that would resolve outside the workspace root.
 ///
 /// Pnpm's lockfile spec writes importer keys as POSIX paths relative
 /// to the workspace root (`.` for the root, `packages/web` for a
 /// subproject). Anything else — an absolute POSIX path, a Windows
-/// drive prefix, a `..` segment — is either malformed or hostile, so
-/// surface it as a typed error rather than silently letting
-/// `Path::join` produce an off-workspace path.
-/// Reject a lockfile importer key that cannot be safely joined onto the
-/// lockfile dir: absolute paths, Windows drive prefixes, backslash
-/// separators, and `..` traversal segments. `.` (the root importer) and any
-/// ordinary POSIX-relative sub-path are accepted. Callers that turn an
-/// importer key into an on-disk path — via [`importer_root_dir`] — must run
-/// this first when the key comes from an untrusted lockfile.
+/// drive prefix, a backslash separator, a `..` segment — is either
+/// malformed or hostile, so surface it as a typed error rather than
+/// silently letting `Path::join` produce an off-workspace path.
+///
+/// Callers that turn an importer key into an on-disk path — via
+/// [`importer_root_dir`] — must run this first when the key comes from
+/// an untrusted lockfile.
 pub fn validate_importer_id(importer_id: &str) -> Result<(), SymlinkDirectDependenciesError> {
 /// Resolve `importer_id` (a lockfile key) against the workspace root.
 ///
 /// Pnpm's lockfile spec uses `"."` for the root importer and
 /// forward-slash POSIX paths for sub-importers. Mirroring that here
 /// keeps lockfiles written by pacquet and pnpm interchangeable. The
 /// returned path is platform-native (`Path::join` handles the
 /// conversion on Windows).
-/// The on-disk root of the project a lockfile importer ID names, relative
-/// to `workspace_root` (which is normally the lockfile directory).
 #[must_use]

Also applies to: 377-386

🤖 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/symlink_direct_dependencies.rs` around lines
275 - 288, Collapse the duplicated rustdoc comments for validate_importer_id and
importer_root_dir into one concise contract per public function. Retain only the
non-obvious importer-key safety invariant and the "." root/POSIX-relative path
behavior; remove repeated descriptions of rejected shapes and return values
without changing implementation behavior.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs (1)

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

Remove the tolerant skip in cold_batch_links_slots_in_parallel.

The test returns early when rayon reports fewer than two threads. The concurrency assertion then never runs, and the environment problem stays invisible. Let the test fail instead, or force a two-thread rayon pool for this test so the assertion always runs.

As per coding guidelines: "Tests must not silently return early when required tools such as git, node, or npm are unavailable; let the test fail." pnpm/AGENTS.md states the same: "If a test cannot run without a tool, let it panic rather than silently skipping. The environment must be fixed, not the test."

🤖 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/create_virtual_store/tests.rs` around lines 99
- 105, Remove the early-return guard based on rayon::current_num_threads() from
cold_batch_links_slots_in_parallel so the concurrency assertion always executes.
Let the test fail naturally when insufficient rayon threads are available,
without silently skipping the assertion.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs (1)

40-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider sharing the recording reporter as a crate helper.

This file repeats the same static EVENTS plus RecordingReporter pattern five times. If the crate-level tests module is the intended boundary, put the helper once there and call it from these tests instead of duplicating it in each case.

🤖 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/symlink_direct_dependencies/tests.rs` around
lines 40 - 48, Move the duplicated EVENTS static and RecordingReporter
implementation from the individual tests into the crate-level tests module as a
shared helper. Update each affected test in the symlink direct-dependencies test
module to reuse that helper while preserving the existing event-clearing and
recording behavior.

Source: Learnings

pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs (1)

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

Add coverage for the removed stats payload and the orphan-confinement refusal.

Two behaviors of link_hoisted_modules stay untested in this file:

  • link_hoisted_modules emits pnpm:stats Removed { prefix, removed } on every run (link_hoisted_modules.rs lines 137-140). Every test here uses SilentReporter, so the count and prefix are never asserted. The coding guidelines require recording-fake coverage for reporter events. Sibling test files already define a recording reporter you can reuse.
  • remove_orphans refuses an orphan directory that is not lexically inside confine_root (link_hoisted_modules.rs lines 172-183). No test drives that branch. Add a case with a prev_graph entry outside confine_root and assert the directory survives.

As per coding guidelines: "Reporter pnpm:<channel> events emitted by Rust code must match the TypeScript implementation in call site, payload, ordering, channel mapping, and recording-fake test coverage."

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

In `@pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs` around lines 140
- 180, Extend the tests around link_hoisted_modules to use the existing
recording reporter and assert each run emits the pnpm:stats Removed event with
the expected prefix and removal count. Add coverage for remove_orphans using a
prev_graph entry whose directory is outside confine_root, and assert that
directory remains intact after linking. Preserve the existing orphan removal
assertions for paths within the confinement root.

Source: Coding guidelines

🤖 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_symlink_layout/tests.rs`:
- Around line 24-34: Update the symlink assertions in the test, including the
additional assertion block around the referenced lines, to use
pacquet_fs::read_symlink_dir instead of std::fs::read_link so junctions work on
Windows. Preserve the existing expected relative-target comparisons and
assertion behavior.

In `@pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs`:
- Line 393: Make both permission-error tests deterministic by adding a narrow
Host/Sys filesystem capability seam and injecting errors instead of relying on
mode bits: in pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:393-393,
preserve node_modules then inject PermissionDenied from remove_dir_all; in
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:458-458, inject
PermissionDenied from symlink_metadata for target/node_modules. Update the
relevant test setup and Host/Sys implementations while keeping the production
filesystem behavior unchanged.

In `@pnpm/crates/deps-restorer/src/link_bins.rs`:
- Around line 684-687: Update the documentation near the fallback path in
`link_bins.rs` to remove or correct the unresolved
`crate::InstallWithFreshLockfile` link, using plain prose consistent with the
surrounding comment unless a valid import or re-export is intentionally added.
Ensure the resulting documentation resolves successfully in `cargo doc`.

In `@pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs`:
- Around line 292-293: Rename the test function
prune_direct_deps_respects_trusted_importer_allow_set to reflect that it
exercises prunable_importer_ids, not trusted_importer_ids. Add the short
rationale comment used by the sibling tests explaining this set is unrelated to
trusted importer validation.

---

Outside diff comments:
In `@pnpm/crates/deps-restorer/src/hoist.rs`:
- Around line 65-70: The public build_hoist_graph_with_max_length API needs
justification and documentation. Prefer making build_hoist_graph_with_max_length
private to crate::hoist if external callers do not require it; otherwise add
rustdoc describing degraded behavior when metadata is missing and how
virtual_store_dir_max_length influences sort_key ordering.

---

Nitpick comments:
In `@pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs`:
- Around line 99-105: Remove the early-return guard based on
rayon::current_num_threads() from cold_batch_links_slots_in_parallel so the
concurrency assertion always executes. Let the test fail naturally when
insufficient rayon threads are available, without silently skipping the
assertion.

In `@pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs`:
- Around line 396-397: Update the assertion for second-alias in the relevant
install-package test to use the existing symlink-specific helper used by sibling
tests, ensuring it verifies the path is actually a symlink rather than merely an
existing directory.
- Around line 27-178: Replace the full struct literal in create_config with
Config::new(), overriding only the test-required fields such as store_dir,
modules_dir, virtual_store_dir, cache_dir, registry, verify_store_integrity, and
child_concurrency. Match the initialization pattern used by the sibling test
modules, and remove the file-level clippy::default_trait_access expectation
since it is no longer needed.

In `@pnpm/crates/deps-restorer/src/link_file.rs`:
- Around line 30-34: Update the comments describing AUTO_STATE and
CLONE_OR_COPY_STATE to state that each process-global AtomicU8 is declared
inside try_import, replacing the incorrect reference to link_file. Apply this
correction to both comment blocks while preserving their explanation that the
states are independent.

In `@pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs`:
- Around line 140-180: Extend the tests around link_hoisted_modules to use the
existing recording reporter and assert each run emits the pnpm:stats Removed
event with the expected prefix and removal count. Add coverage for
remove_orphans using a prev_graph entry whose directory is outside confine_root,
and assert that directory remains intact after linking. Preserve the existing
orphan removal assertions for paths within the confinement root.

In `@pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs`:
- Around line 275-288: Collapse the duplicated rustdoc comments for
validate_importer_id and importer_root_dir into one concise contract per public
function. Retain only the non-obvious importer-key safety invariant and the "."
root/POSIX-relative path behavior; remove repeated descriptions of rejected
shapes and return values without changing implementation behavior.

In `@pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs`:
- Around line 40-48: Move the duplicated EVENTS static and RecordingReporter
implementation from the individual tests into the crate-level tests module as a
shared helper. Update each affected test in the symlink direct-dependencies test
module to reuse that helper while preserving the existing event-clearing and
recording behavior.
🪄 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: 12a0ff75-36d2-420f-af2e-2afd6eaf6f10

📥 Commits

Reviewing files that changed from the base of the PR and between 23584da and 6d0ff26.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (67)
  • Cargo.toml
  • pnpm/crates/cli/tests/multiple_importers.rs
  • pnpm/crates/deps-restorer/Cargo.toml
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/deps-restorer/src/build_modules/tests.rs
  • pnpm/crates/deps-restorer/src/build_sequence.rs
  • pnpm/crates/deps-restorer/src/build_sequence/tests.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs
  • pnpm/crates/deps-restorer/src/current_lockfile.rs
  • pnpm/crates/deps-restorer/src/current_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/deps_graph.rs
  • pnpm/crates/deps-restorer/src/deps_graph/tests.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer/tests.rs
  • pnpm/crates/deps-restorer/src/hoist.rs
  • pnpm/crates/deps-restorer/src/hoist/tests.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph/tests.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits/tests.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/install_frozen_lockfile.rs
  • pnpm/crates/deps-restorer/src/install_frozen_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs
  • pnpm/crates/deps-restorer/src/installability.rs
  • pnpm/crates/deps-restorer/src/installability/tests.rs
  • pnpm/crates/deps-restorer/src/lib.rs
  • pnpm/crates/deps-restorer/src/link_bins.rs
  • pnpm/crates/deps-restorer/src/link_bins/tests.rs
  • pnpm/crates/deps-restorer/src/link_file.rs
  • pnpm/crates/deps-restorer/src/link_file/tests.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members/tests.rs
  • pnpm/crates/deps-restorer/src/package_map.rs
  • pnpm/crates/deps-restorer/src/package_map/tests.rs
  • pnpm/crates/deps-restorer/src/pnp.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs
  • pnpm/crates/deps-restorer/src/prune_stale_modules.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine/tests.rs
  • pnpm/crates/deps-restorer/src/retry_config.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir/tests.rs
  • pnpm/crates/deps-restorer/src/store_init.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs
  • pnpm/crates/deps-restorer/src/symlink_package.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths/tests.rs
  • pnpm/crates/deps-restorer/src/version_policy.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/crates/package-manager/Cargo.toml
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/plans/TEST_PORTING.md
  • pnpm/crates/cli/tests/multiple_importers.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.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

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/hoist.rs (1)

65-70: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Justify the wider API surface and document build_hoist_graph_with_max_length.

compute_hoist_plan calls this internally, and pacquet/package-manager depends on pacquet-deps-restorer without importing the helper itself. Keep the helper private to crate::hoist or mark it as a deliberate extraction API. If it remains pub, add rustdoc that states the degraded behavior for missing metadata and how virtual_store_dir_max_length affects sort_key ordering.

🤖 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/hoist.rs` around lines 65 - 70, The public
build_hoist_graph_with_max_length API needs justification and documentation.
Prefer making build_hoist_graph_with_max_length private to crate::hoist if
external callers do not require it; otherwise add rustdoc describing degraded
behavior when metadata is missing and how virtual_store_dir_max_length
influences sort_key ordering.

Source: Coding guidelines

🧹 Nitpick comments (7)
pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs (2)

396-397: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert a symlink, not mere existence, for the second-visit link.

Path::exists follows the link and also returns true for a real directory. The assertion therefore does not prove the second visit created the per-parent symlink. Use the same helper the sibling tests use.

💚 Suggested assertion
     let symlink_path = second_parent_dir.path().join("second-alias");
-    assert!(symlink_path.exists() || symlink_path.is_symlink(), "per-parent symlink missing");
+    assert!(
+        pacquet_testing_utils::fs::is_symlink_or_junction(&symlink_path)
+            .expect("inspect per-parent link"),
+        "per-parent symlink missing at {symlink_path:?}",
+    );
🤖 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/install_package_from_registry/tests.rs` around
lines 396 - 397, Update the assertion for second-alias in the relevant
install-package test to use the existing symlink-specific helper used by sibling
tests, ensuring it verifies the path is actually a symlink rather than merely an
existing directory.

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

Build the test Config from Config::new() instead of a full struct literal.

create_config names about 145 fields. Sibling test modules in the same crate build their config from Config::new() and override only the fields they care about — see pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs lines 114-121 and pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs lines 55-59. The literal here duplicates the whole config surface, so every new Config field breaks this file alone. The #![expect(clippy::default_trait_access)] at the top of the file exists only to support the literal.

Rewrite create_config in the same shape as the sibling modules and drop the file-level expect.

As per coding guidelines from AGENTS.md "Code Reuse and Avoiding Duplication": before adding code, verify no helper is duplicated elsewhere.

♻️ Suggested shape
 fn create_config(
     store_dir: &Path,
     modules_dir: &Path,
     virtual_store_dir: &Path,
     cache_dir: &Path,
 ) -> Config {
-    Config {
-        versioning: Default::default(),
-        // ... ~145 fields ...
-        config_dir: None,
-    }
+    let mut config = Config::new();
+    config.store_dir = StoreDir::new(store_dir);
+    config.modules_dir = modules_dir.to_path_buf();
+    config.virtual_store_dir = virtual_store_dir.to_path_buf();
+    config.global_virtual_store_dir = virtual_store_dir.to_path_buf();
+    config.cache_dir = cache_dir.to_path_buf();
+    config
 }

Add only the extra overrides the tests actually depend on, such as registry, verify_store_integrity, and child_concurrency.

🤖 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/install_package_from_registry/tests.rs` around
lines 27 - 178, Replace the full struct literal in create_config with
Config::new(), overriding only the test-required fields such as store_dir,
modules_dir, virtual_store_dir, cache_dir, registry, verify_store_integrity, and
child_concurrency. Match the initialization pattern used by the sibling test
modules, and remove the file-level clippy::default_trait_access expectation
since it is no longer needed.

Source: Path instructions

pnpm/crates/deps-restorer/src/link_file.rs (1)

30-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Correct the stated location of the downgrade statics.

Both comments say the process-global state lives inside link_file. AUTO_STATE and CLONE_OR_COPY_STATE are declared inside try_import at lines 210 and 237. Point the comments at try_import so a reader can find the state.

📝 Suggested wording
-// These are the state *values*, not the cache itself: each mode keeps
-// its own process-global `AtomicU8` (`AUTO_STATE` inside `link_file`,
-// `CLONE_OR_COPY_STATE` likewise), so an `Auto` downgrade doesn't
-// affect `CloneOrCopy` and vice versa.
+// These are the state *values*, not the cache itself: each mode keeps
+// its own process-global `AtomicU8` (`AUTO_STATE` and
+// `CLONE_OR_COPY_STATE`, both declared inside `try_import`), so an
+// `Auto` downgrade doesn't affect `CloneOrCopy` and vice versa.
-/// pass their own `AtomicU8` and exercise the downgrade logic in
-/// isolation — the production path uses a `static` declared inside
-/// [`link_file`]. Only capability / cross-device style failures
+/// pass their own `AtomicU8` and exercise the downgrade logic in
+/// isolation — the production path uses the `AUTO_STATE` `static`
+/// declared inside `try_import`. Only capability / cross-device style failures

Also applies to: 305-312

🤖 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/link_file.rs` around lines 30 - 34, Update the
comments describing AUTO_STATE and CLONE_OR_COPY_STATE to state that each
process-global AtomicU8 is declared inside try_import, replacing the incorrect
reference to link_file. Apply this correction to both comment blocks while
preserving their explanation that the states are independent.
pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs (1)

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

Collapse the duplicated rustdoc blocks.

Each of these two items carries the contract twice. On validate_importer_id, lines 275-282 describe rejecting keys that resolve outside the workspace root, and lines 283-288 restate the same rule with the same rejected shapes. On importer_root_dir, lines 377-383 explain the "." root key and POSIX resolution, and lines 384-385 restate the return value. Keep one statement of each contract.

As per coding guidelines: "Use rustdoc comments for public API contracts... Do not duplicate test behavior in documentation; comments should explain only non-obvious reasons or invariants." pnpm/CODE_STYLE_GUIDE.md adds: "Do not repeat what the code already says."

📝 Suggested consolidation
 /// Reject importer keys that would resolve outside the workspace root.
 ///
 /// Pnpm's lockfile spec writes importer keys as POSIX paths relative
 /// to the workspace root (`.` for the root, `packages/web` for a
 /// subproject). Anything else — an absolute POSIX path, a Windows
-/// drive prefix, a `..` segment — is either malformed or hostile, so
-/// surface it as a typed error rather than silently letting
-/// `Path::join` produce an off-workspace path.
-/// Reject a lockfile importer key that cannot be safely joined onto the
-/// lockfile dir: absolute paths, Windows drive prefixes, backslash
-/// separators, and `..` traversal segments. `.` (the root importer) and any
-/// ordinary POSIX-relative sub-path are accepted. Callers that turn an
-/// importer key into an on-disk path — via [`importer_root_dir`] — must run
-/// this first when the key comes from an untrusted lockfile.
+/// drive prefix, a backslash separator, a `..` segment — is either
+/// malformed or hostile, so surface it as a typed error rather than
+/// silently letting `Path::join` produce an off-workspace path.
+///
+/// Callers that turn an importer key into an on-disk path — via
+/// [`importer_root_dir`] — must run this first when the key comes from
+/// an untrusted lockfile.
 pub fn validate_importer_id(importer_id: &str) -> Result<(), SymlinkDirectDependenciesError> {
 /// Resolve `importer_id` (a lockfile key) against the workspace root.
 ///
 /// Pnpm's lockfile spec uses `"."` for the root importer and
 /// forward-slash POSIX paths for sub-importers. Mirroring that here
 /// keeps lockfiles written by pacquet and pnpm interchangeable. The
 /// returned path is platform-native (`Path::join` handles the
 /// conversion on Windows).
-/// The on-disk root of the project a lockfile importer ID names, relative
-/// to `workspace_root` (which is normally the lockfile directory).
 #[must_use]

Also applies to: 377-386

🤖 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/symlink_direct_dependencies.rs` around lines
275 - 288, Collapse the duplicated rustdoc comments for validate_importer_id and
importer_root_dir into one concise contract per public function. Retain only the
non-obvious importer-key safety invariant and the "." root/POSIX-relative path
behavior; remove repeated descriptions of rejected shapes and return values
without changing implementation behavior.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs (1)

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

Remove the tolerant skip in cold_batch_links_slots_in_parallel.

The test returns early when rayon reports fewer than two threads. The concurrency assertion then never runs, and the environment problem stays invisible. Let the test fail instead, or force a two-thread rayon pool for this test so the assertion always runs.

As per coding guidelines: "Tests must not silently return early when required tools such as git, node, or npm are unavailable; let the test fail." pnpm/AGENTS.md states the same: "If a test cannot run without a tool, let it panic rather than silently skipping. The environment must be fixed, not the test."

🤖 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/create_virtual_store/tests.rs` around lines 99
- 105, Remove the early-return guard based on rayon::current_num_threads() from
cold_batch_links_slots_in_parallel so the concurrency assertion always executes.
Let the test fail naturally when insufficient rayon threads are available,
without silently skipping the assertion.

Sources: Coding guidelines, Path instructions

pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs (1)

40-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider sharing the recording reporter as a crate helper.

This file repeats the same static EVENTS plus RecordingReporter pattern five times. If the crate-level tests module is the intended boundary, put the helper once there and call it from these tests instead of duplicating it in each case.

🤖 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/symlink_direct_dependencies/tests.rs` around
lines 40 - 48, Move the duplicated EVENTS static and RecordingReporter
implementation from the individual tests into the crate-level tests module as a
shared helper. Update each affected test in the symlink direct-dependencies test
module to reuse that helper while preserving the existing event-clearing and
recording behavior.

Source: Learnings

pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs (1)

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

Add coverage for the removed stats payload and the orphan-confinement refusal.

Two behaviors of link_hoisted_modules stay untested in this file:

  • link_hoisted_modules emits pnpm:stats Removed { prefix, removed } on every run (link_hoisted_modules.rs lines 137-140). Every test here uses SilentReporter, so the count and prefix are never asserted. The coding guidelines require recording-fake coverage for reporter events. Sibling test files already define a recording reporter you can reuse.
  • remove_orphans refuses an orphan directory that is not lexically inside confine_root (link_hoisted_modules.rs lines 172-183). No test drives that branch. Add a case with a prev_graph entry outside confine_root and assert the directory survives.

As per coding guidelines: "Reporter pnpm:<channel> events emitted by Rust code must match the TypeScript implementation in call site, payload, ordering, channel mapping, and recording-fake test coverage."

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

In `@pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs` around lines 140
- 180, Extend the tests around link_hoisted_modules to use the existing
recording reporter and assert each run emits the pnpm:stats Removed event with
the expected prefix and removal count. Add coverage for remove_orphans using a
prev_graph entry whose directory is outside confine_root, and assert that
directory remains intact after linking. Preserve the existing orphan removal
assertions for paths within the confinement root.

Source: Coding guidelines

🤖 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_symlink_layout/tests.rs`:
- Around line 24-34: Update the symlink assertions in the test, including the
additional assertion block around the referenced lines, to use
pacquet_fs::read_symlink_dir instead of std::fs::read_link so junctions work on
Windows. Preserve the existing expected relative-target comparisons and
assertion behavior.

In `@pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs`:
- Line 393: Make both permission-error tests deterministic by adding a narrow
Host/Sys filesystem capability seam and injecting errors instead of relying on
mode bits: in pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:393-393,
preserve node_modules then inject PermissionDenied from remove_dir_all; in
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:458-458, inject
PermissionDenied from symlink_metadata for target/node_modules. Update the
relevant test setup and Host/Sys implementations while keeping the production
filesystem behavior unchanged.

In `@pnpm/crates/deps-restorer/src/link_bins.rs`:
- Around line 684-687: Update the documentation near the fallback path in
`link_bins.rs` to remove or correct the unresolved
`crate::InstallWithFreshLockfile` link, using plain prose consistent with the
surrounding comment unless a valid import or re-export is intentionally added.
Ensure the resulting documentation resolves successfully in `cargo doc`.

In `@pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs`:
- Around line 292-293: Rename the test function
prune_direct_deps_respects_trusted_importer_allow_set to reflect that it
exercises prunable_importer_ids, not trusted_importer_ids. Add the short
rationale comment used by the sibling tests explaining this set is unrelated to
trusted importer validation.

---

Outside diff comments:
In `@pnpm/crates/deps-restorer/src/hoist.rs`:
- Around line 65-70: The public build_hoist_graph_with_max_length API needs
justification and documentation. Prefer making build_hoist_graph_with_max_length
private to crate::hoist if external callers do not require it; otherwise add
rustdoc describing degraded behavior when metadata is missing and how
virtual_store_dir_max_length influences sort_key ordering.

---

Nitpick comments:
In `@pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs`:
- Around line 99-105: Remove the early-return guard based on
rayon::current_num_threads() from cold_batch_links_slots_in_parallel so the
concurrency assertion always executes. Let the test fail naturally when
insufficient rayon threads are available, without silently skipping the
assertion.

In `@pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs`:
- Around line 396-397: Update the assertion for second-alias in the relevant
install-package test to use the existing symlink-specific helper used by sibling
tests, ensuring it verifies the path is actually a symlink rather than merely an
existing directory.
- Around line 27-178: Replace the full struct literal in create_config with
Config::new(), overriding only the test-required fields such as store_dir,
modules_dir, virtual_store_dir, cache_dir, registry, verify_store_integrity, and
child_concurrency. Match the initialization pattern used by the sibling test
modules, and remove the file-level clippy::default_trait_access expectation
since it is no longer needed.

In `@pnpm/crates/deps-restorer/src/link_file.rs`:
- Around line 30-34: Update the comments describing AUTO_STATE and
CLONE_OR_COPY_STATE to state that each process-global AtomicU8 is declared
inside try_import, replacing the incorrect reference to link_file. Apply this
correction to both comment blocks while preserving their explanation that the
states are independent.

In `@pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs`:
- Around line 140-180: Extend the tests around link_hoisted_modules to use the
existing recording reporter and assert each run emits the pnpm:stats Removed
event with the expected prefix and removal count. Add coverage for
remove_orphans using a prev_graph entry whose directory is outside confine_root,
and assert that directory remains intact after linking. Preserve the existing
orphan removal assertions for paths within the confinement root.

In `@pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs`:
- Around line 275-288: Collapse the duplicated rustdoc comments for
validate_importer_id and importer_root_dir into one concise contract per public
function. Retain only the non-obvious importer-key safety invariant and the "."
root/POSIX-relative path behavior; remove repeated descriptions of rejected
shapes and return values without changing implementation behavior.

In `@pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs`:
- Around line 40-48: Move the duplicated EVENTS static and RecordingReporter
implementation from the individual tests into the crate-level tests module as a
shared helper. Update each affected test in the symlink direct-dependencies test
module to reuse that helper while preserving the existing event-clearing and
recording behavior.
🪄 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: 12a0ff75-36d2-420f-af2e-2afd6eaf6f10

📥 Commits

Reviewing files that changed from the base of the PR and between 23584da and 6d0ff26.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (67)
  • Cargo.toml
  • pnpm/crates/cli/tests/multiple_importers.rs
  • pnpm/crates/deps-restorer/Cargo.toml
  • pnpm/crates/deps-restorer/src/build_modules.rs
  • pnpm/crates/deps-restorer/src/build_modules/tests.rs
  • pnpm/crates/deps-restorer/src/build_sequence.rs
  • pnpm/crates/deps-restorer/src/build_sequence/tests.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout.rs
  • pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/create_virtual_dir_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store.rs
  • pnpm/crates/deps-restorer/src/create_virtual_store/tests.rs
  • pnpm/crates/deps-restorer/src/current_lockfile.rs
  • pnpm/crates/deps-restorer/src/current_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/deps_graph.rs
  • pnpm/crates/deps-restorer/src/deps_graph/tests.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer.rs
  • pnpm/crates/deps-restorer/src/graph_sequencer/tests.rs
  • pnpm/crates/deps-restorer/src/hoist.rs
  • pnpm/crates/deps-restorer/src/hoist/tests.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph.rs
  • pnpm/crates/deps-restorer/src/hoisted_dep_graph/tests.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits.rs
  • pnpm/crates/deps-restorer/src/hoisting_limits/tests.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/install_frozen_lockfile.rs
  • pnpm/crates/deps-restorer/src/install_frozen_lockfile/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot.rs
  • pnpm/crates/deps-restorer/src/install_package_by_snapshot/tests.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry.rs
  • pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs
  • pnpm/crates/deps-restorer/src/installability.rs
  • pnpm/crates/deps-restorer/src/installability/tests.rs
  • pnpm/crates/deps-restorer/src/lib.rs
  • pnpm/crates/deps-restorer/src/link_bins.rs
  • pnpm/crates/deps-restorer/src/link_bins/tests.rs
  • pnpm/crates/deps-restorer/src/link_file.rs
  • pnpm/crates/deps-restorer/src/link_file/tests.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules.rs
  • pnpm/crates/deps-restorer/src/link_hoisted_modules/tests.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members.rs
  • pnpm/crates/deps-restorer/src/link_root_component_members/tests.rs
  • pnpm/crates/deps-restorer/src/package_map.rs
  • pnpm/crates/deps-restorer/src/package_map/tests.rs
  • pnpm/crates/deps-restorer/src/pnp.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps.rs
  • pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs
  • pnpm/crates/deps-restorer/src/prune_stale_modules.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine.rs
  • pnpm/crates/deps-restorer/src/remove_quarantine/tests.rs
  • pnpm/crates/deps-restorer/src/retry_config.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir.rs
  • pnpm/crates/deps-restorer/src/safe_join_modules_dir/tests.rs
  • pnpm/crates/deps-restorer/src/store_init.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies.rs
  • pnpm/crates/deps-restorer/src/symlink_direct_dependencies/tests.rs
  • pnpm/crates/deps-restorer/src/symlink_package.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths.rs
  • pnpm/crates/deps-restorer/src/validate_lockfile_paths/tests.rs
  • pnpm/crates/deps-restorer/src/version_policy.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout.rs
  • pnpm/crates/deps-restorer/src/virtual_store_layout/tests.rs
  • pnpm/crates/package-manager/Cargo.toml
  • pnpm/crates/package-manager/src/lib.rs
  • pnpm/plans/TEST_PORTING.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm/plans/TEST_PORTING.md
  • pnpm/crates/cli/tests/multiple_importers.rs
🛑 Comments failed to post (3)
pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs (1)

24-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the internal symlink implementations.
rg -n -C 8 \
  'fn (force_symlink_dir|symlink_dir)\b|junction|read_link' \
  pnpm/crates \
  --type rust

# Locate Windows CI coverage for this crate.
rg -n -C 4 \
  'windows|deps-restorer|cargo nextest|cargo test' \
  .github pnpm \
  -g '*.yml' -g '*.yaml' -g '*.toml'

Repository: pnpm/pnpm

Length of output: 139


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files 'pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs' 'pnpm/crates/*fs*' | sed -n '1,120p'

echo "== create_symlink_layout tests relevant =="
if [ -f pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs ]; then
  wc -l pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs
  sed -n '1,80p;210,250p' pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs
fi

echo "== force_symlink_dir/read_link search focused =="
rg -n -C 6 'force_symlink_dir|symlink_dir|read_link|junction' pnpm/crates --type rust | sed -n '1,260p'

echo "== CI package/test mentions =="
rg -n -C 3 'deps-restorer|create_symlink_layout|package-manager|cargo nextest|cargo test' .github pnpm -g '*.yml' -g '*.yaml' -g '*.toml' | sed -n '1,260p'

Repository: pnpm/pnpm

Length of output: 139


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== git status =="
git status --short | sed -n '1,80p' || true

echo "== files =="
git ls-files 'pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs' 'pnpm/crates/*fs*' 'pnpm/crates/registry-mock' | sed -n '1,200p' || true

echo "== locate symlink funcs =="
rg -n -C 6 'force_symlink_dir|symlink_dir|junction|read_link' pnpm/crates --type rust 2>/dev/null | sed -n '1,240p' || true

echo "== locate target test =="
rg -n -C 6 'read_link|target_path|pathdiff|create_symlink_layout' pnpm/crates/deps-restorer/src/create_symlink_layout/tests.rs pnpm/crates/deps-restorer/src --type rust 2>/dev/null | sed -n '1,260p' || true

Repository: pnpm/pnpm

Length of output: 47859


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== fs lib exports =="
sed -n '1,140p' pnpm/crates/fs/src/lib.rs

echo "== symlink_dir implementation =="
sed -n '1,260p' pnpm/crates/fs/src/symlink_dir.rs

echo "== tests around raw read assertions =="
sed -n '220,270p' pnpm/crates/fs/src/symlink_dir/tests.rs || true
rg -n -C 6 'read_link|junction|force_symlink_dir|symlink_dir' pnpm/crates/fs/src/symlink_dir/tests.rs pnpm/crates/fs/src --type rust | sed -n '1,220p'

Repository: pnpm/pnpm

Length of output: 32576


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== windows module =="
sed -n '1,260p' pnpm/crates/fs/src/symlink_dir.rs.windows 2>/dev/null || rg -n -C 8 'mod windows|create_junction|windows::create' pnpm/crates/fs/src/symlink_dir.rs pnpm/crates/fs/src --type rust | sed -n '1,260p'
rg -n -C 6 'create_junction|junction::create|symlink_dir' pnpm/crates/fs/src/symlink_dir.rs pnpm/crates/fs/src --type rust | sed -n '1,260p'

echo "== create_symlink_layout caller =="
rg -n -C 8 'force_symlink_dir|symlink_dir|read_link_dir|read_symlink_dir|create_directory_symlink|create_directory_hardlink' pnpm/crates/deps-restorer/src/create_symlink_layout.rs pnpm/crates/deps-restorer/src --type rust | sed -n '1,260p'

Repository: pnpm/pnpm

Length of output: 50365


Use the Windows-aware symlink reader for read_link assertions.

create_symlink_layout can produce junctions on Windows, and std::fs::read_link fails with InvalidInput for junctions. These raw assertions should use pacquet_fs::read_symlink_dir or resolve paths on Windows so the tests pass on the junction fallback path.

Also applies to: 227-237

🤖 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/create_symlink_layout/tests.rs` around lines 24
- 34, Update the symlink assertions in the test, including the additional
assertion block around the referenced lines, to use pacquet_fs::read_symlink_dir
instead of std::fs::read_link so junctions work on Windows. Preserve the
existing expected relative-target comparisons and assertion behavior.
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs (1)

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

Make the permission-error tests deterministic.

Mode bits do not force PermissionDenied for a privileged test process. Both tests can reach the success path and fail at expect_err. Add a narrow Host/Sys filesystem seam and inject the required errors.

  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs#L393-L393: inject PermissionDenied from remove_dir_all after preserving node_modules.
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs#L458-L458: inject PermissionDenied from symlink_metadata for target/node_modules.

As per coding guidelines, use dependency injection through Host/Sys capability traits for filesystem error branches that real fixtures cannot portably reach.

📍 Affects 1 file
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs#L393-L393 (this comment)
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs#L458-L458
🤖 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/import_indexed_dir/tests.rs` at line 393, Make
both permission-error tests deterministic by adding a narrow Host/Sys filesystem
capability seam and injecting errors instead of relying on mode bits: in
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:393-393, preserve
node_modules then inject PermissionDenied from remove_dir_all; in
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs:458-458, inject
PermissionDenied from symlink_metadata for target/node_modules. Update the
relevant test setup and Host/Sys implementations while keeping the production
filesystem behavior unchanged.

Source: Coding guidelines

pnpm/crates/deps-restorer/src/prune_direct_deps/tests.rs (1)

292-293: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Rename the test: it does not exercise trusted_importer_ids.

The test name says trusted_importer_allow_set, but the argument it passes is prunable_importer_ids. prune_direct_deps.rs lines 77-80 state that this set is unrelated to crate::SymlinkDirectDependencies::trusted_importer_ids, which names importers allowed to skip ID validation. The current name asserts the opposite contract. Rename it to match the parameter, and add the short rationale comment the sibling tests carry.

✏️ Proposed rename
+/// `prunable_importer_ids` narrows removal to the importers a filtered
+/// install re-materialized; every other importer's links stay.
 #[test]
-fn prune_direct_deps_respects_trusted_importer_allow_set() {
+fn prune_direct_deps_only_touches_prunable_importer_ids() {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/// `prunable_importer_ids` narrows removal to the importers a filtered
/// install re-materialized; every other importer's links stay.
#[test]
fn prune_direct_deps_only_touches_prunable_importer_ids() {
🤖 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/prune_direct_deps/tests.rs` around lines 292 -
293, Rename the test function
prune_direct_deps_respects_trusted_importer_allow_set to reflect that it
exercises prunable_importer_ids, not trusted_importer_ids. Add the short
rationale comment used by the sibling tests explaining this set is unrelated to
trusted importer validation.

KSXGitHub pushed a commit that referenced this pull request Aug 4, 2026
Main renamed pnpm/crates/package-manager/src/install_package_from_registry/tests.rs
into the new deps-restorer crate (#13637). The branch's added
config_warnings field initializer in create_config follows the file to its new
home at pnpm/crates/deps-restorer/src/install_package_from_registry/tests.rs.
KSXGitHub pushed a commit that referenced this pull request Aug 4, 2026
Picks up the install-module decomposition (#13640 and
#13624), the headless-install extraction (#13637), the
PnP-loader fix for virtual-store-only installs (#13636), and a
dependency bump (#13631).

`build_workspace_state` moved out of `install.rs` into the new
`install/workspace_state.rs`, and its two call sites moved into
`install/apply_materialization.rs` and `install/prepare_modules_state.rs`.
This branch's `Sys: Clock` seam and the `::<Host>` turbofish are
re-applied at those new homes.

# Conflicts:
#	pnpm/crates/package-manager/src/install.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants