Skip to content

fix(package-manager): keep peer-only aliases out of importers without auto-install-peers - #13372

Merged
zkochan merged 3 commits into
mainfrom
fix-13325
Jul 25, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-13325

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

With autoInstallPeers: false, pacquet added a project's own optional peer dependencies to that project's importer entry in pnpm-lock.yaml (and linked them into its node_modules) as soon as some other part of the workspace resolved a matching version. Reported for vite in #13325, where packages/vite gained jiti, tsx and yaml — the optional peers of postcss-load-config that packages/vite re-declares as its own optional peers.

The peer hoist itself is not the divergence: both stacks hoist an optional peer into the importer's resolved direct dependencies when a satisfying version is already in scope, which is what produces the (@pnpm.e2e/[email protected]) peer context on the dependent. The difference is what reaches the lockfile importer entry. The TypeScript CLI folds peerDependencies into an importer's dependencies only under autoInstallPeers (getAllDependenciesFromManifest(manifest, { autoInstallPeers }) in pnpm11/installing/deps-resolver/src/index.ts), so with the setting off a hoisted peer stays reachable only through the snapshots graph. pacquet's read_manifest_specifier consulted peerDependencies unconditionally; it now applies the same gate — which also lines it up with pacquet's own lockfile freshness check, whose peer fold is already gated on auto_install_peers.

Verified against the TypeScript CLI with a two-project fixture on the mocked registry: before the fix pacquet wrote '@pnpm.e2e/peer-c': { specifier: ^1.0.0, version: 1.0.0 } into pkg-a while pnpm v11.17.0 wrote nothing; after the fix the two lockfiles are byte-identical (modulo the settings: block), and so is pkg-a/node_modules. autoInstallPeers: true still materializes the peer in both stacks.

Closes #13325

Squash Commit Body

An importer's lockfile entry was built from every hoisted direct
dependency the manifest declared anywhere, `peerDependencies` included.
The peer hoist runs whenever a missing peer can be satisfied from a
version already resolved in the workspace, so with
`autoInstallPeers: false` a project's own optional peer became a direct
dependency of its importer as soon as a sibling project resolved a
matching version, and got linked into that project's `node_modules`.

The TypeScript CLI folds `peerDependencies` into an importer's
dependencies only under `autoInstallPeers`
(`getAllDependenciesFromManifest(manifest, { autoInstallPeers })` in
`installing/deps-resolver/src/index.ts`); peers hoisted with the setting
off never reach the importer entry and stay reachable only through the
snapshots graph. `read_manifest_specifier` now applies the same gate,
which also matches pacquet's lockfile freshness check — its peer fold is
already gated on the same setting, so the two now agree on which
importer entries a manifest is expected to have.

The fix is pacquet-only: the TypeScript CLI already behaves this way, and
gets a regression test for the same scenario.

Closes pnpm/pnpm#13325

Checklist

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

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


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

Summary by CodeRabbit

  • Bug Fixes
    • When automatic peer installation is disabled (autoInstallPeers: false), optional peer dependencies are no longer added to a project’s lockfile importer or installed into its node_modules.
    • Lockfiles produced with this setting work correctly with frozen installs.
    • Behavior remains unchanged when automatic peer installation is enabled.
  • Tests
    • Added regression coverage for optional-peer handling (issue #13325) across CLI and installer scenarios.

… auto-install-peers

An importer's lockfile entry was built from every hoisted direct
dependency the manifest declared anywhere, `peerDependencies` included.
The peer hoist runs whenever a missing peer can be satisfied from a
version already resolved in the workspace, so with
`autoInstallPeers: false` a project's own optional peer became a direct
dependency of its importer as soon as a sibling project resolved a
matching version, and got linked into that project's `node_modules`.

The TypeScript CLI folds `peerDependencies` into an importer's
dependencies only under `autoInstallPeers`
(`getAllDependenciesFromManifest(manifest, { autoInstallPeers })` in
`installing/deps-resolver/src/index.ts`); peers hoisted with the setting
off never reach the importer entry and stay reachable only through the
snapshots graph. `read_manifest_specifier` now applies the same gate,
which also matches pacquet's lockfile freshness check — its peer fold is
already gated on the same setting, so the two now agree on which
importer entries a manifest is expected to have.

The hoist itself is not the divergence: both stacks hoist the optional
peer and record the resulting peer context on the dependent, verified by
running the two CLIs over the same workspace on the mocked registry.

The fix is pacquet-only; the TypeScript CLI already behaves this way and
gets a regression test for the same scenario.

Closes #13325

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 17:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@zkochan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 15 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 387b52f4-7c8d-4361-9ab8-7987033cec01

📥 Commits

Reviewing files that changed from the base of the PR and between db5ccb9 and 0abcca7.

📒 Files selected for processing (1)
  • pnpm/crates/cli/tests/workspace_install.rs
📝 Walkthrough

Walkthrough

This change prevents optional peer dependencies from entering workspace importer lockfile entries or node_modules when autoInstallPeers: false. Importer construction now receives this setting, with Rust and Jest regression tests covering disabled and enabled behavior.

Changes

Optional peer importer handling

Layer / File(s) Summary
Gate peer entries during importer construction
pnpm/crates/package-manager/src/dependencies_graph_to_lockfile.rs
Importer construction propagates auto_install_peers and excludes peer dependency groups from importer specifiers when disabled.
Validate workspace and lockfile behavior
pnpm/crates/package-manager/src/dependencies_graph_to_lockfile/tests.rs, pnpm/crates/cli/tests/workspace_install.rs, pnpm11/installing/deps-installer/test/install/peerDependencies.ts, .changeset/optional-peers-stay-out-of-importers.md
Regression tests verify importer and linking behavior with optional peers, and the changeset records the patch release behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant WorkspaceInstall
  participant ImporterBuilder
  participant Lockfile
  participant NodeModules
  WorkspaceInstall->>ImporterBuilder: pass autoInstallPeers=false
  ImporterBuilder->>Lockfile: omit peer-only importer entry
  Lockfile->>NodeModules: do not link optional peer
Loading

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#13117 — Both changes account for autoInstallPeers during lockfile peer handling.
  • pnpm/pnpm#13120 — Both changes adjust optional peer handling during resolution and lockfile generation.

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

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-13325

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

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix lockfile importer entries for optional peers when autoInstallPeers is false

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Gate importer specifier/dependency recording of peerDependencies behind autoInstallPeers.
• Prevent optional peer-only aliases from being written to pnpm-lock.yaml importers or linked.
• Add regression coverage in Rust + TypeScript test suites for pnpm/pnpm#13325.
Diagram

graph TD
  Manifest["Project manifest"] --> Read["read_manifest_specifier (gated)"] --> Build["build_importer"] --> Lock[("pnpm-lock importer")] --> NM["pkg/node_modules links"]
  Settings["Workspace settings (autoInstallPeers)"] --> Read
  Graph["Resolved dep graph (hoist)"] --> Build
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Filter peer-only aliases earlier (before build_importer)
  • ➕ Keeps build_importer/read_manifest_specifier simpler by only receiving eligible aliases.
  • ➕ Could reduce the chance of future call sites forgetting to pass the flag.
  • ➖ Requires threading dependency-group context (or an additional data structure) through earlier stages.
  • ➖ Bigger refactor surface area for a narrowly-scoped regression fix.
2. Reuse/port pnpm’s getAllDependenciesFromManifest behavior directly
  • ➕ Maximizes behavioral parity with the TypeScript CLI by sharing/replicating the same manifest-folding logic.
  • ➕ Centralizes the autoInstallPeers gating in one canonical helper.
  • ➖ May be impractical across languages/crates; increases coupling and maintenance overhead.
  • ➖ More change than needed to fix the lockfile importer divergence.

Recommendation: The chosen fix (gate peerDependencies inclusion at read_manifest_specifier and thread auto_install_peers alongside exclude_links_from_lockfile) is the right scope: it corrects importer lockfile output and node_modules materialization while keeping the hoist behavior intact. Consider the earlier-filter alternative only if similar “alias eligibility” rules proliferate across importer-building paths.

Files changed (5) +225 / -15

Bug fix (1) +38 / -15
dependencies_graph_to_lockfile.rsGate peerDependencies fold into importer entries behind auto_install_peers +38/-15

Gate peerDependencies fold into importer entries behind auto_install_peers

• Threads an ImporterLockfileFlags struct into build_importer and updates read_manifest_specifier to only consult peerDependencies when auto_install_peers is enabled. This prevents hoisted peer-only aliases from being recorded in importer specifiers/dependencies when autoInstallPeers is false.

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

Tests (3) +182 / -0
workspace_install.rsAdd CLI regression test for optional peer not becoming importer dependency +55/-0

Add CLI regression test for optional peer not becoming importer dependency

• Introduces a workspace install regression test ensuring that with autoInstallPeers=false, a project’s optional peer does not get written into its importer section nor linked into its node_modules, even if a sibling resolves the matching version.

pnpm/crates/cli/tests/workspace_install.rs

tests.rsAdd unit regression test for peer-only alias recording rules +80/-0

Add unit regression test for peer-only alias recording rules

• Adds a focused test asserting that a hoisted peer-only alias is excluded from importer dependencies/specifiers when autoInstallPeers=false, and included with the correct specifier when autoInstallPeers=true.

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

peerDependencies.tsAdd pnpm v11 TS regression test matching #13325 scenario +47/-0

Add pnpm v11 TS regression test matching #13325 scenario

• Adds a TypeScript-side integration test verifying that a workspace project declaring an optional peer does not get that peer added to its own importer dependencies or linked when auto-install-peers is off, even when a sibling resolves the peer version.

pnpm11/installing/deps-installer/test/install/peerDependencies.ts

Documentation (1) +5 / -0
optional-peers-stay-out-of-importers.mdDocument optional-peer importer behavior under autoInstallPeers=false +5/-0

Document optional-peer importer behavior under autoInstallPeers=false

• Adds a changeset noting that optional peer dependencies are no longer added to pnpm-lock.yaml importer entries (or linked) when autoInstallPeers is disabled, aligning behavior with pnpm's TypeScript CLI for the reported regression.

.changeset/optional-peers-stay-out-of-importers.md

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "test(cli): read the workspace lockfile s..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Leftover dbg!(pkg_a) in test 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new regression test unconditionally includes a dbg!(pkg_a) debug print that is unrelated to
asserting the bug fix, creating persistent noisy stderr output (and minor overhead) in normal test
runs/CI logs and potentially leaking environment-specific snapshot details.
Code

pnpm/crates/cli/tests/workspace_install.rs[270]

+    dbg!(pkg_a);
Relevance

⭐⭐⭐ High

Team has accepted removing unconditional dbg! noise in tests; prefer assertion messages for context.

PR-#13329

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited change in pnpm/crates/cli/tests/workspace_install.rs shows an unconditional
dbg!(pkg_a) added immediately after reading the importer snapshot, so it will always emit the
snapshot contents to stderr on every successful test run. Because this debug output is not used for
any regression assertion, it constitutes unrelated non-functional noise that conflicts with the
bug-fix scope discipline and unnecessarily pollutes CI logs.

Rule 2255067: Bug fix changes must not include unrelated refactors or reformatting
pnpm/crates/cli/tests/workspace_install.rs[268-271]

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

## Issue description
A regression test contains a leftover `dbg!(pkg_a)` that prints unconditionally to stderr. This debug output does not contribute to the test’s assertions, adds persistent CI/log noise (with minor overhead), and may expose environment-specific snapshot details.

## Issue Context
This PR is a bug fix; per scope-discipline expectations, avoid unrelated non-functional changes and noisy output in the diff and in CI logs. `dbg!` writes to stderr even when the test passes, so the output will appear on every successful run.

If diagnostics are still needed, prefer failure-only context (e.g., include `pkg_a` in an assertion message) rather than always-on printing.

## Fix Focus Areas
- pnpm/crates/cli/tests/workspace_install.rs[268-271]

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


2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and omits the required pnpm package entry, so the
release tooling/policy cannot apply the mandated bump for pnpm. This violates the changeset
requirements for this repo.
Code

.changeset/optional-peers-stay-out-of-importers.md[R1-3]

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

⭐⭐⭐ High

Close precedent: same pacquet-only changeset was updated to include pnpm and accepted.

PR-#13337

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changesets to include an explicit pnpm package entry with a valid
bump type. The added changeset front-matter contains only "pacquet": patch and no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/optional-peers-stay-out-of-importers.md[1-3]

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

## Issue description
The changeset `.changeset/optional-peers-stay-out-of-importers.md` is missing a `pnpm` entry in its front-matter.

## Issue Context
Repo policy requires each changeset to explicitly include the `pnpm` package with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/optional-peers-stay-out-of-importers.md[1-3]

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



Informational

3. Dangling link can evade check 🐞 Bug ☼ Reliability ⭐ New
Description
The test asserts the optional peer is not linked using Path::exists(), which follows symlinks; a
dangling symlink/junction at that path would make exists() return false and the test would
incorrectly pass. This weakens the regression coverage for the node_modules side effect the test is
intended to prevent.
Code

pnpm/crates/cli/tests/workspace_install.rs[R278-280]

+    assert!(
+        !workspace.join("pkg-a/node_modules/@pnpm.e2e/peer-c").exists(),
+        "optional peer linked into pkg-a under `autoInstallPeers: false`",
Relevance

⭐ Low

Close precedent rejected replacing Path::exists() with lstat/symlink-metadata checks for dangling
symlink robustness.

PR-#13306

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new test uses .exists() for the node_modules assertion, while the shared test utilities
demonstrate the suite’s preferred approach for link detection via is_symlink_or_junction, which
inspects the link itself rather than following it.

pnpm/crates/cli/tests/workspace_install.rs[278-280]
pnpm/crates/cli/tests/_utils/mod.rs[490-493]

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

### Issue description
The test uses `Path::exists()` to prove an entry is absent from `node_modules`, but `exists()` can return false for a dangling symlink/junction. That allows a broken link to slip by undetected.

### Issue Context
The test suite already has link-aware helpers (e.g., `has_link` uses `is_symlink_or_junction`) that avoid this class of false-pass.

### Fix Focus Areas
- pnpm/crates/cli/tests/workspace_install.rs[278-280]
- pnpm/crates/cli/tests/_utils/mod.rs[490-493]

### Suggested fix
Replace the `.exists()` assertion with a no-follow metadata check, e.g.:

```rust
let peer_path = workspace.join("pkg-a/node_modules/@pnpm.e2e/peer-c");
assert!(
 matches!(fs::symlink_metadata(&peer_path), Err(e) if e.kind() == std::io::ErrorKind::NotFound),
 "optional peer linked into pkg-a under `autoInstallPeers: false`",
);
```

This fails if *any* filesystem entry exists there (directory, symlink, or dangling symlink).

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


4. Brittle lockfile substring check ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new Rust regression test verifies the deduplicated peer-context by searching for a raw `version:
...` substring inside a text-sliced importer section, which can false-pass/false-fail if lockfile
formatting or additional dependency entries change. This weakens the test’s ability to reliably
detect regressions around peer-context materialization.
Code

pnpm/crates/cli/tests/workspace_install.rs[R279-287]

+    // The optional peer is still deduplicated into the dependent's peer
+    // context — the same entry the TypeScript CLI writes for this
+    // workspace. Its counterpart lives in `peerDependencies.ts`, in
+    // `an optional peer declared by a workspace project is not added to
+    // its own importer, when auto-install-peers is off`.
+    assert!(
+        a_section.contains("version: 1.0.0(@pnpm.e2e/[email protected])"),
+        "pkg-a lost the deduplicated optional-peer context\n{lockfile}",
+    );
Relevance

⭐ Low

Very similar “parse lockfile structurally vs brittle string splitting” suggestion in same file was
previously rejected.

PR-#13117

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new test currently validates lockfile semantics by substring search on the serialized YAML, even
though the test utilities already provide a structured lockfile parser that would make the assertion
robust and properly scoped to the intended dependency entry.

pnpm/crates/cli/tests/workspace_install.rs[265-287]
pnpm/crates/cli/tests/_utils/mod.rs[355-360]

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

### Issue description
The test asserts the peer-context by doing `a_section.contains("version: 1.0.0(@pnpm.e2e/[email protected])")` on a substring of the YAML lockfile. This is sensitive to formatting/layout and doesn’t scope the check to the `@pnpm.e2e/abc-optional-peers` dependency entry.

### Issue Context
The test suite already has a typed lockfile reader (`read_lockfile`) that parses `pnpm-lock.yaml` into a `pacquet_lockfile::Lockfile`.

### Fix Focus Areas
- pnpm/crates/cli/tests/workspace_install.rs[279-287]
- pnpm/crates/cli/tests/_utils/mod.rs[355-360]

### Suggested change
1. Replace the substring `contains("version: ...")` assertion with parsing `pnpm-lock.yaml` via `_utils::read_lockfile(...)`.
2. Assert on the specific importer (`pkg-a`) and the specific dependency key (`@pnpm.e2e/abc-optional-peers`) version field, matching the peer-suffixed version string.
3. Keep the existing negative assertion (peer-c not present as direct dep) but ideally also make it structural (check the parsed importer dependencies map).

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


Grey Divider

Previous review results

Review updated until commit 0abcca7 ⚖️ Balanced

Results up to commit a484050 ⚖️ Balanced


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


Remediation recommended
1. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and omits the required pnpm package entry, so the
release tooling/policy cannot apply the mandated bump for pnpm. This violates the changeset
requirements for this repo.
Code

.changeset/optional-peers-stay-out-of-importers.md[R1-3]

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

⭐⭐⭐ High

Close precedent: same pacquet-only changeset was updated to include pnpm and accepted.

PR-#13337

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changesets to include an explicit pnpm package entry with a valid
bump type. The added changeset front-matter contains only "pacquet": patch and no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/optional-peers-stay-out-of-importers.md[1-3]

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

## Issue description
The changeset `.changeset/optional-peers-stay-out-of-importers.md` is missing a `pnpm` entry in its front-matter.

## Issue Context
Repo policy requires each changeset to explicitly include the `pnpm` package with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/optional-peers-stay-out-of-importers.md[1-3]

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


Results up to commit db5ccb9 ⚖️ Balanced


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


Informational
1. Brittle lockfile substring check ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new Rust regression test verifies the deduplicated peer-context by searching for a raw `version:
...` substring inside a text-sliced importer section, which can false-pass/false-fail if lockfile
formatting or additional dependency entries change. This weakens the test’s ability to reliably
detect regressions around peer-context materialization.
Code

pnpm/crates/cli/tests/workspace_install.rs[R279-287]

+    // The optional peer is still deduplicated into the dependent's peer
+    // context — the same entry the TypeScript CLI writes for this
+    // workspace. Its counterpart lives in `peerDependencies.ts`, in
+    // `an optional peer declared by a workspace project is not added to
+    // its own importer, when auto-install-peers is off`.
+    assert!(
+        a_section.contains("version: 1.0.0(@pnpm.e2e/[email protected])"),
+        "pkg-a lost the deduplicated optional-peer context\n{lockfile}",
+    );
Relevance

⭐ Low

Very similar “parse lockfile structurally vs brittle string splitting” suggestion in same file was
previously rejected.

PR-#13117

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new test currently validates lockfile semantics by substring search on the serialized YAML, even
though the test utilities already provide a structured lockfile parser that would make the assertion
robust and properly scoped to the intended dependency entry.

pnpm/crates/cli/tests/workspace_install.rs[265-287]
pnpm/crates/cli/tests/_utils/mod.rs[355-360]

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

### Issue description
The test asserts the peer-context by doing `a_section.contains("version: 1.0.0(@pnpm.e2e/[email protected])")` on a substring of the YAML lockfile. This is sensitive to formatting/layout and doesn’t scope the check to the `@pnpm.e2e/abc-optional-peers` dependency entry.

### Issue Context
The test suite already has a typed lockfile reader (`read_lockfile`) that parses `pnpm-lock.yaml` into a `pacquet_lockfile::Lockfile`.

### Fix Focus Areas
- pnpm/crates/cli/tests/workspace_install.rs[279-287]
- pnpm/crates/cli/tests/_utils/mod.rs[355-360]

### Suggested change
1. Replace the substring `contains("version: ...")` assertion with parsing `pnpm-lock.yaml` via `_utils::read_lockfile(...)`.
2. Assert on the specific importer (`pkg-a`) and the specific dependency key (`@pnpm.e2e/abc-optional-peers`) version field, matching the peer-suffixed version string.
3. Keep the existing negative assertion (peer-c not present as direct dep) but ideally also make it structural (check the parsed importer dependencies map).

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


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 Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     11.4±0.06ms    32.9 MB/sec    1.00     11.4±0.02ms    32.8 MB/sec
packument/parse                1.00     37.1±0.20µs  1790.1 MB/sec    1.05     38.8±0.37µs  1709.3 MB/sec
tarball/download_dependency    1.03      2.4±0.06ms  1794.6 KB/sec    1.00      2.4±0.07ms  1840.5 KB/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: 1

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

Inline comments:
In `@pnpm/crates/cli/tests/workspace_install.rs`:
- Around line 263-284: Extend the parity fixture across both implementations: in
pnpm/crates/cli/tests/workspace_install.rs lines 263-284, capture pacquet’s
lockfile and relevant pkg-a node_modules layout, then compare them byte-for-byte
and by importer entries/symlinks with the TypeScript pnpm baseline. In
pnpm11/installing/deps-installer/test/install/peerDependencies.ts lines
1579-1583, provide or consume the same fixture/baseline and assert the
equivalent lockfile bytes and importer-entry/link presence or absence; retain
the existing optional-peer expectations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4f62a3b6-36b0-447d-9f79-99fd8c547d6b

📥 Commits

Reviewing files that changed from the base of the PR and between 0754566 and a484050.

📒 Files selected for processing (5)
  • .changeset/optional-peers-stay-out-of-importers.md
  • pnpm/crates/cli/tests/workspace_install.rs
  • pnpm/crates/package-manager/src/dependencies_graph_to_lockfile.rs
  • pnpm/crates/package-manager/src/dependencies_graph_to_lockfile/tests.rs
  • pnpm11/installing/deps-installer/test/install/peerDependencies.ts

@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Re: Qodo's Changeset missing pnpm entry finding — declining this one; the changeset is correct as-is.

AGENTS.md is explicit that pnpm in a changeset always means the TypeScript CLI package, and that a Rust-only change must not name it:

Do not add "pnpm" to a Rust-only changeset: in changesets, pnpm always means the TypeScript CLI package. A changeset whose implementation is Rust-only and targets pacquet must omit "pnpm".

This PR's implementation is Rust-only. The one TypeScript file it touches is a test (pnpm11/installing/deps-installer/test/install/peerDependencies.ts), added to pin the behavior the TypeScript CLI already has — no published TypeScript package changes, so bumping pnpm would attach a release note to the TS CLI for a behavior it never had.

The cited precedent, #13337, is a parity change: it modified the implementation on both sides (pnpm11/deps/inspection/outdated/src/outdated.ts, pnpm11/installing/commands/src/update/getUpdateChoices.ts alongside the Rust crates), which is exactly the case where "pnpm" belongs in the changeset.


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

The regression tests for #13325 asserted only that the optional
peer is absent from the importer, which two stacks can satisfy while
still writing different lockfiles. Both now also assert the entry the
scenario does produce — `1.0.0(@pnpm.e2e/[email protected])` on the
dependent — so the pair pins one observable result rather than two
independent absences, and each test names its counterpart.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 17:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

Copy link
Copy Markdown

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

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

…eer test

The importer assertions matched substrings of a hand-sliced
`pnpm-lock.yaml` section, so a formatting change or an extra dependency
entry could flip them either way. Read the lockfile through the typed
`read_lockfile` / `importer` / `importer_version` helpers this test crate
already has, which also lets the absence check cover all three importer
dependency groups by key instead of by rendered text.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 17: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.

@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Qodo round 2:

Brittle lockfile substring check — accepted, fixed in 0abcca7. The importer assertions now go through the typed read_lockfile / importer / importer_version helpers that pnpm/crates/cli/tests/_utils already provides, instead of slicing the rendered YAML. The absence check is now by PkgName key across all three importer dependency groups, and the peer-context check is an assert_eq! on @pnpm.e2e/abc-optional-peers's resolved version rather than a substring search. Re-verified that the test still fails when the fix is reverted.

Changeset missing pnpm entry — still declining, same reasoning as my earlier comment: the implementation here is Rust-only, so per AGENTS.md the changeset must omit "pnpm", and the cited precedent (#13337) changed the implementation in both stacks.


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

@qodo-code-review

Copy link
Copy Markdown

Qodo round 2:

Brittle lockfile substring check — accepted, fixed in 0abcca7. The importer assertions now go through the typed read_lockfile / importer / importer_version helpers that pnpm/crates/cli/tests/_utils already provides, instead of slicing the rendered YAML. The absence check is now by PkgName key across all three importer dependency groups, and the peer-context check is an assert_eq! on @pnpm.e2e/abc-optional-peers's resolved version rather than a substring search. Re-verified that the test still fails when the fix is reverted.

Changeset missing pnpm entry — still declining, same reasoning as my earlier comment: the implementation here is Rust-only, so per AGENTS.md the changeset must omit "pnpm", and the cited precedent (#13337) changed the implementation in both stacks.


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

Thanks for the update. The changes address finding 2 with typed lockfile assertions and preserve both the importer absence check and peer-context regression coverage. Finding 1 remains open because the changeset intentionally targets only the Rust implementation and omits the pnpm entry, consistent with AGENTS.md and the cited precedent.

@zkochan
zkochan merged commit d17710c into main Jul 25, 2026
24 checks passed
@zkochan
zkochan deleted the fix-13325 branch July 25, 2026 17:27
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 0abcca7

@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 commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Qodo round 3 — both new findings accepted, fixed in e2a45ed.

Dangling link can evade check — correct: Path::exists follows the link, so a dangling peer-c entry in pkg-a/node_modules would have read as "not linked" and passed. The check is now fs::symlink_metadata(..).is_err(), which fails only when nothing is at that path at all (and still catches a Windows junction, whose symlink_metadata succeeds).

Leftover dbg!(pkg_a) — the importer snapshot now goes into the assertion message instead, so it prints when a check fails rather than on every run. Note for future reviews: pnpm/CODE_STYLE_GUIDE.md explicitly endorses the dbg!(&value); assert!(..) shape for complex structures ("Logging is almost always necessary when the assertion is not assert_eq!", with a worked dbg!(&hash_map) example), so an unconditional dbg! before an assert! is not a rule violation in this repo. Folding it into the message keeps the failure context while dropping the noise, which is the same resolution taken in #13329.

The changeset finding stays declined for the reason given above.


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

zkochan added a commit that referenced this pull request Jul 25, 2026
Resolving the Astro workspace with pacquet produced a `pnpm-lock.yaml`
that differed from pnpm 11's by 306 lines. Two independent bugs account
for 143 of them.

`dedupe_injected_deps` splits a resolved package id into its name and
its `file:` payload on the first `@`. A scoped id
(`@test/pkg@file:packages/…`) starts with `@`, so the split returned the
scope tail and the `file:` strip failed — the injected workspace dep was
never recognized and stayed a `file:` snapshot where pnpm records
`link:`. Split on the whole `@file:` separator instead.

`extract_children` walked every entry of `dependencies` and
`optionalDependencies`, including the ones the manifest declares as
bundled. npm ships those inside the package's own tarball, and pnpm's
`getNonDevWantedDependencies` filters them out before resolution; the
missing filter pulled extra packages into the lockfile (`napi-wasm`
under `@parcel/watcher-wasm`, the whole `@napi-rs`/`@emnapi` set under
`@tailwindcss/oxide-wasm32-wasi`). Both spellings are honored, and
`true` means every entry of `dependencies`, matching npm. The bundled
set is computed once and shared by both `collect_deps` calls, so an
alias declared in both groups is dropped from both — upstream filters
the merged `{...optionalDependencies, ...dependencies}` map and reaches
the same result. The alias validation still runs over bundled entries
so an unusable alias is rejected either way, as it is upstream.

A third divergence from the same reproduction — a project's own
`peerDependencies` reaching its lockfile importer entry without
`autoInstallPeers` — landed separately as #13372 while this was
in review, so it is no longer part of this change.

The remaining divergences — the `parentPkgAliases` arm of upstream's
peer-shadowed-dependency omission, and local `file:*.tgz` tarballs
resolving without a manifest — are described in the issue; both need
design work beyond this change.

Related to #13334.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.21%. Comparing base (0754566) to head (0abcca7).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13372   +/-   ##
=======================================
  Coverage   87.21%   87.21%           
=======================================
  Files         536      536           
  Lines       92049    92059   +10     
=======================================
+ Hits        80283    80293   +10     
  Misses      11766    11766           

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

zkochan added a commit that referenced this pull request Jul 25, 2026
Resolving the Astro workspace with pacquet produced a `pnpm-lock.yaml`
that differed from pnpm 11's by 306 lines. Two independent bugs account
for 143 of them.

`dedupe_injected_deps` splits a resolved package id into its name and
its `file:` payload on the first `@`. A scoped id
(`@test/pkg@file:packages/…`) starts with `@`, so the split returned the
scope tail and the `file:` strip failed — the injected workspace dep was
never recognized and stayed a `file:` snapshot where pnpm records
`link:`. Split on the whole `@file:` separator instead.

`extract_children` walked every entry of `dependencies` and
`optionalDependencies`, including the ones the manifest declares as
bundled. npm ships those inside the package's own tarball, and pnpm's
`getNonDevWantedDependencies` filters them out before resolution; the
missing filter pulled extra packages into the lockfile (`napi-wasm`
under `@parcel/watcher-wasm`, the whole `@napi-rs`/`@emnapi` set under
`@tailwindcss/oxide-wasm32-wasi`). Both spellings are honored, and
`true` means every entry of `dependencies`, matching npm. The bundled
set is computed once and shared by both `collect_deps` calls, so an
alias declared in both groups is dropped from both — upstream filters
the merged `{...optionalDependencies, ...dependencies}` map and reaches
the same result. The alias validation still runs over bundled entries
so an unusable alias is rejected either way, as it is upstream.

A third divergence from the same reproduction — a project's own
`peerDependencies` reaching its lockfile importer entry without
`autoInstallPeers` — landed separately as #13372 while this was
in review, so it is no longer part of this change.

The remaining divergences — the `parentPkgAliases` arm of upstream's
peer-shadowed-dependency omission, and local `file:*.tgz` tarballs
resolving without a manifest — are described in the issue; both need
design work beyond this change.

Related to #13334.
@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Correction on my previous comment: this PR merged (d17710c) about five minutes before I pushed e2a45edd1c, so the two test refinements described there are not on main — the push re-created the auto-deleted branch instead of failing, which hid that at the time.

They now live in #13378: the symlink_metadata check for a dangling peer-c link, and the dbg! folded into the assertion message. Everything else described in this PR — the read_manifest_specifier gate, the changeset, and all three regression tests — is on main as merged.


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

zkochan added a commit that referenced this pull request Jul 25, 2026
…13378)

`Path::exists` follows the link, so a dangling `peer-c` link in pkg-a's
`node_modules` would have read as "not linked" and passed the check;
`symlink_metadata` fails only when nothing is there at all.

The importer snapshot moves from an unconditional `dbg!` into the
assertion message, so it is printed when a check fails rather than on
every run.

Follow-up to #13372, which merged before this commit landed.
zkochan added a commit that referenced this pull request Jul 25, 2026
…13381)

The hoist rounds ran on every install, so a missing peer that some
version elsewhere in the workspace could satisfy was installed even with
`autoInstallPeers: false` and `dedupePeerDependents: false` — the
dependent then carried a peer context the TypeScript CLI never writes.

Upstream derives one flag from the two settings —
`hoistPeers = autoInstallPeers || dedupePeerDependents` in
`installing/deps-resolver/src/resolveDependencyTree.ts` — and
`resolveRootDependencies` returns before the hoist loop when it is
false: hoisting a peer nobody asked to install only pays off if
peer-suffixed variants are being collapsed. `ImporterHoistState` now
carries the same derived flag and both rounds no-op when it is unset,
which leaves the peer missing and the dependent's snapshot free of a
peer suffix. The final peer pass is untouched, so unmet peers are still
reported.

Verified against the TypeScript CLI on a two-project workspace: all four
`autoInstallPeers` x `dedupePeerDependents` combinations now produce
byte-identical lockfiles, where the both-off combination previously
diverged.

Follow-up to #13372.
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
… auto-install-peers (pnpm#13372)

An importer's lockfile entry was built from every hoisted direct
dependency the manifest declared anywhere, `peerDependencies` included.
The peer hoist runs whenever a missing peer can be satisfied from a
version already resolved in the workspace, so with
`autoInstallPeers: false` a project's own optional peer became a direct
dependency of its importer as soon as a sibling project resolved a
matching version, and got linked into that project's `node_modules`.

The TypeScript CLI folds `peerDependencies` into an importer's
dependencies only under `autoInstallPeers`
(`getAllDependenciesFromManifest(manifest, { autoInstallPeers })` in
`installing/deps-resolver/src/index.ts`); peers hoisted with the setting
off never reach the importer entry and stay reachable only through the
snapshots graph. `read_manifest_specifier` now applies the same gate,
which also matches pacquet's lockfile freshness check — its peer fold is
already gated on the same setting, so the two now agree on which
importer entries a manifest is expected to have.

The fix is pacquet-only: the TypeScript CLI already behaves this way, and
gets a regression test for the same scenario.

Closes pnpm#13325
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
Resolving the Astro workspace with pacquet produced a `pnpm-lock.yaml`
that differed from pnpm 11's by 306 lines. Two independent bugs account
for 143 of them.

`dedupe_injected_deps` splits a resolved package id into its name and
its `file:` payload on the first `@`. A scoped id
(`@test/pkg@file:packages/…`) starts with `@`, so the split returned the
scope tail and the `file:` strip failed — the injected workspace dep was
never recognized and stayed a `file:` snapshot where pnpm records
`link:`. Split on the whole `@file:` separator instead.

`extract_children` walked every entry of `dependencies` and
`optionalDependencies`, including the ones the manifest declares as
bundled. npm ships those inside the package's own tarball, and pnpm's
`getNonDevWantedDependencies` filters them out before resolution; the
missing filter pulled extra packages into the lockfile (`napi-wasm`
under `@parcel/watcher-wasm`, the whole `@napi-rs`/`@emnapi` set under
`@tailwindcss/oxide-wasm32-wasi`). Both spellings are honored, and
`true` means every entry of `dependencies`, matching npm. The bundled
set is computed once and shared by both `collect_deps` calls, so an
alias declared in both groups is dropped from both — upstream filters
the merged `{...optionalDependencies, ...dependencies}` map and reaches
the same result. The alias validation still runs over bundled entries
so an unusable alias is rejected either way, as it is upstream.

A third divergence from the same reproduction — a project's own
`peerDependencies` reaching its lockfile importer entry without
`autoInstallPeers` — landed separately as pnpm#13372 while this was
in review, so it is no longer part of this change.

The remaining divergences — the `parentPkgAliases` arm of upstream's
peer-shadowed-dependency omission, and local `file:*.tgz` tarballs
resolving without a manifest — are described in the issue; both need
design work beyond this change.

Related to pnpm#13334.
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…npm#13378)

`Path::exists` follows the link, so a dangling `peer-c` link in pkg-a's
`node_modules` would have read as "not linked" and passed the check;
`symlink_metadata` fails only when nothing is there at all.

The importer snapshot moves from an unconditional `dbg!` into the
assertion message, so it is printed when a check fails rather than on
every run.

Follow-up to pnpm#13372, which merged before this commit landed.
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…npm#13381)

The hoist rounds ran on every install, so a missing peer that some
version elsewhere in the workspace could satisfy was installed even with
`autoInstallPeers: false` and `dedupePeerDependents: false` — the
dependent then carried a peer context the TypeScript CLI never writes.

Upstream derives one flag from the two settings —
`hoistPeers = autoInstallPeers || dedupePeerDependents` in
`installing/deps-resolver/src/resolveDependencyTree.ts` — and
`resolveRootDependencies` returns before the hoist loop when it is
false: hoisting a peer nobody asked to install only pays off if
peer-suffixed variants are being collapsed. `ImporterHoistState` now
carries the same derived flag and both rounds no-op when it is unset,
which leaves the peer missing and the dependent's snapshot free of a
peer suffix. The final peer pass is untouched, so unmet peers are still
reported.

Verified against the TypeScript CLI on a two-project workspace: all four
`autoInstallPeers` x `dedupePeerDependents` combinations now produce
byte-identical lockfiles, where the both-off combination previously
diverged.

Follow-up to pnpm#13372.
@qodo-code-review qodo-code-review Bot mentioned this pull request Aug 15, 2026
4 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pnpm 12 adds optional peers to a workspace importer with autoInstallPeers disabled

3 participants