Skip to content

fix(cli): record packageManagerDependencies from every command - #13382

Merged
zkochan merged 1 commit into
mainfrom
fix-13348
Jul 25, 2026
Merged

zkochan merged 1 commit into
mainfrom
fix-13348

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13348.

pnpm records the pinned pnpm version under packageManagerDependencies from its
pre-command block, so every command writes it. pacquet only did so from the
install-family pipelines, so a project whose first pacquet command was pnpm list (or run, exec, why, …) got no lockfile at all.

The issue lists three ways out. This PR takes the first one — keep pacquet's
extra strictness and gate the pre-command sync
— because the alternative
(dropping FrozenLockfileOutdated for package-manager deps to match pnpm
exactly) gives up a real guard against a lockfile silently changing under
--frozen-lockfile in CI, and the third (record the divergence) leaves the
lockfile dependent on which command ran first.

The gate is the command itself rather than the effective frozen-lockfile
value: the install family (install, ci, add, update, remove, dedupe,
prune, deploy, unlink, install-test) already syncs from its own
pipeline, where the frozen-lockfile value is known, so the pre-command block
skips those and covers everything else. A frozen install therefore still fails
on an out-of-date packageManagerDependencies instead of having it repaired
first, and pacquet install's up-to-date fast path keeps its zero-network
startup.

Two more spots the pre-command block now mirrors pnpm:

  • The download policy with a pin the running pnpm already satisfies. pnpm gets
    there through switchCliVersion, which resolves and saves before it decides
    no switch is needed; pacquet returned early and wrote nothing. This is the
    issue's reproduction.
  • pmOnFail. pnpm resolves wantedPackageManager.onFail against the setting
    before shouldPersistLockfile reads it, so --pm-on-fail=ignore keeps the
    pin out of the lockfile and --pm-on-fail=warn puts a manifest-ignored pin
    back in. package_manager_to_sync now takes the effective policy, which fixes
    the install family too.

Rebased onto main after #13380 landed the same "pass the parsed
manifest" refactor of package_manager_to_sync, which shrank this diff to just
the on_fail parameter on that function.

pacquet-only: the TypeScript CLI already behaves this way, and nothing about its
behavior changes here.

Squash Commit Body

pnpm's pre-command block calls syncEnvLockfile for every command that isn't
in skipPackageManagerCheckForCommand, so a project pinning pnpm through
devEngines.packageManager (or a v12+ packageManager field) gets its
packageManagerDependencies recorded whatever the user ran. pacquet synced
only from the install-family pipelines, so `pnpm list` in a fresh clone left
no lockfile behind.

pre_command_plan now returns a PreCommandPlan — either the version switch it
already planned, or the env-lockfile sync it needs — and lib.rs runs whichever
came back on the pre-command runtime. The sync is planned in the same two
places pnpm reaches syncEnvLockfile: after checkPackageManager on the
warn/error/corepack path, and on the download path when the running pnpm
already satisfies the pin (where pnpm's switchCliVersion still resolves and
saves before returning).

The install family is excluded, because it passes its own frozen-lockfile
value to the sync and pacquet — unlike pnpm — fails a frozen install whose
packageManagerDependencies are out of date. Syncing those commands from the
pre-command block would repair the lockfile before the pipeline could refuse
to. Excluding them also keeps the up-to-date install fast path free of the
lockfile read.

The plan is skipped without touching the network whenever the env lockfile
already records a version satisfying the pin. That answer needs the lockfile,
but the download path has already read it looking for a version to switch to,
and `pnpm-lock.yaml` is read whole — so the parsed lockfile is threaded into
the sync decision rather than read a second time. A warm pinned project pays
one lockfile read per command, the same as before.

package_manager_to_sync now takes the effective pmOnFail rather than reading
the manifest's own onFail, matching how pnpm resolves
wantedPackageManager.onFail before shouldPersistLockfile sees it.

Closes pnpm/pnpm#13348

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

Summary by CodeRabbit

  • New Features
    • Pinned pnpm versions from devEngines.packageManager are now recorded in pnpm-lock.yaml for every pnpm command, including commands outside the install family.
    • The --version flow now records the pinned package manager when it matches the current pinned pnpm.
  • Bug Fixes
    • Lockfile synchronization now consistently follows pmOnFail (warn vs ignore), and avoids updating pnpm-lock.yaml when it’s already up to date.
  • Tests
    • Added coverage for recording behavior across pinned versions and pmOnFail settings.

Copilot AI review requested due to automatic review settings July 25, 2026 23:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@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: 2 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: 246903b4-4dad-4ad5-a3f8-263bc34ec8f5

📥 Commits

Reviewing files that changed from the base of the PR and between 54652ff and 25bc1f3.

📒 Files selected for processing (10)
  • .changeset/sync-package-manager-deps-on-every-command.md
  • pnpm/crates/cli/src/cli_args/package_manager.rs
  • pnpm/crates/cli/src/cli_args/pipelines.rs
  • pnpm/crates/cli/src/cli_args/pre_command.rs
  • pnpm/crates/cli/src/cli_args/pre_command/tests.rs
  • pnpm/crates/cli/src/cli_args/tests.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/tests/package_manager_check.rs
  • pnpm/crates/cli/tests/version.rs
  • pnpm/crates/config/src/lib.rs
📝 Walkthrough

Walkthrough

Changes

Package manager dependency synchronization

Layer / File(s) Summary
Pin policy resolution
pnpm/crates/cli/src/cli_args/package_manager.rs, pnpm/crates/cli/src/cli_args/pipelines.rs, pnpm/crates/config/src/lib.rs
The effective pmOnFail policy is passed into package manager synchronization and exposes string representations for its variants.
Pre-command synchronization planning
pnpm/crates/cli/src/cli_args/pre_command.rs, pnpm/crates/cli/src/lib.rs
Pre-command execution now plans pnpm switching or env-lockfile synchronization, while avoiding duplicate synchronization for install-family pipelines.
Synchronization validation and release metadata
pnpm/crates/cli/src/cli_args/pre_command/tests.rs, pnpm/crates/cli/src/cli_args/tests.rs, pnpm/crates/cli/tests/package_manager_check.rs, pnpm/crates/cli/tests/version.rs, .changeset/sync-package-manager-deps-on-every-command.md
Tests cover lockfile synchronization for non-install and version commands, pin policy decisions, and existing lockfile states; the changeset documents the behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant PreCommand
  participant EnvLockfile
  participant InstallPipeline
  CLI->>PreCommand: Build pre-command plan
  PreCommand->>InstallPipeline: Check whether pipeline syncs lockfile
  PreCommand->>EnvLockfile: Check packageManagerDependencies
  EnvLockfile-->>PreCommand: Return sync-needed status
  PreCommand-->>CLI: Execute switch or lockfile sync
Loading

Assessment against linked issues

Objective Addressed Explanation
Record pinned packageManagerDependencies for non-install commands [#13348] ✅
Respect pmOnFail when deciding whether the pin is recorded [#13348] ✅

Possibly related issues

  • pnpm/tasks#27 — Concerns recording packageManagerDependencies in the environment lockfile.

Possibly related PRs

  • pnpm/pnpm#13287 — Modifies the same pre-command package manager and pin-handling flow.

Suggested labels: product: pacquet

Suggested reviewers: copilot

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

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 pre-command env-lockfile sync for pinned pnpm on all commands

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Record pinned pnpm under packageManagerDependencies for non-install commands via pre-command
 sync.
• Respect effective pmOnFail when deciding whether the pin persists to the lockfile.
• Add coverage for sync gating, up-to-date fast paths, and pmOnFail override behavior.
Diagram

graph TD
  A["CLI entrypoint"] --> B["pre_command_plan"] --> C{"Install-family?"}
  C -->|"Yes"| D["Install pipeline"] --> H[("pnpm-lock.yaml")]
  C -->|"No"| E{"PreCommandPlan"}
  E -->|"Switch"| F["Switch pnpm version"]
  E -->|"Sync env lockfile"| G["Sync packageManagerDeps"] --> H

  subgraph Legend
    direction LR
    _proc["Process"] ~~~ _dec{"Decision"} ~~~ _db[("Lockfile")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Always sync in pre-command (match pnpm exactly)
  • ➕ Simpler mental model: every command syncs via the same pre-command hook
  • ➕ Less branching/gating logic by command family
  • ➖ Would repair packageManagerDependencies before install pipeline can enforce --frozen-lockfile strictness
  • ➖ Could regress the install fast path by forcing lockfile reads/writes on install-family commands
2. Relax pacquet strictness: don’t fail frozen installs on packageManagerDependencies drift
  • ➕ More consistent with pnpm’s behavior under --frozen-lockfile
  • ➕ Avoids needing command-family gating
  • ➖ Loses a valuable CI guardrail against silent lockfile changes
  • ➖ Contradicts pacquet’s stated goal of extra strictness
3. Persist a divergence marker in lockfile (record ‘not synced yet’)
  • ➕ Avoids command-order dependency while preserving strict install behavior
  • ➖ Introduces a new lockfile state/format contract
  • ➖ Adds complexity to lockfile semantics and downstream tooling

Recommendation: The chosen approach (gate pre-command sync for install-family commands, sync for everything else) is the best tradeoff: it fixes the missing-lockfile/undocumented pin issue for non-install commands while preserving pacquet’s stricter frozen-lockfile enforcement and the zero-network install fast path. The additional alignment on the “already satisfied download pin” path and honoring effective pmOnFail also reduces behavioral surprises versus pnpm without weakening safeguards.

Files changed (9) +363 / -34

Bug fix (4) +162 / -29
package_manager.rsMake package-manager sync honor effective pmOnFail +26/-10

Make package-manager sync honor effective pmOnFail

• Extends 'package_manager_to_sync' to accept an optional effective 'PmOnFail' and factors out 'package_manager_to_sync_from_manifest' for callers with a preloaded manifest. Ensures the decision to persist (and the derived wanted version) reflects 'pmOnFail' overrides.

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

pipelines.rsThread pmOnFail into package-manager-to-sync derivation +1/-1

Thread pmOnFail into package-manager-to-sync derivation

• Passes 'cfg.pm_on_fail' into 'package_manager_to_sync' so install-family pipelines compute lockfile sync intent using the effective policy. Aligns pipeline behavior with pre-command planning.

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

pre_command.rsPlan and execute env-lockfile sync for non-install commands +133/-16

Plan and execute env-lockfile sync for non-install commands

• Refactors pre-command logic to return a 'PreCommandPlan' (switch pnpm or sync env lockfile) and adds 'execute_plan' to run the selected async work. Introduces 'env_lockfile_sync' that mirrors pnpm’s 'syncEnvLockfile' while gating install-family commands to preserve frozen-lockfile strictness and install fast paths; also fixes the download-policy early-return case where the running pnpm already satisfies the pin.

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

lib.rsRun pre-command sync/switch via unified execute_plan +2/-2

Run pre-command sync/switch via unified execute_plan

• Updates the CLI entrypoint to execute either a version switch or env-lockfile sync based on 'PreCommandPlan'. Preserves the prior delegated-pnpm early-exit behavior while enabling non-switch pre-command work.

pnpm/crates/cli/src/lib.rs

Refactor (1) +12 / -0
lib.rsAdd string conversion helper for PmOnFail +12/-0

Add string conversion helper for PmOnFail

• Introduces 'PmOnFail::as_str()' to reliably map enum values to their canonical string forms. Used to apply effective 'pmOnFail' overrides back onto manifest-derived package manager policy.

pnpm/crates/config/src/lib.rs

Tests (3) +184 / -5
tests.rsAdd unit tests for pre-command env-lockfile sync planning +166/-4

Add unit tests for pre-command env-lockfile sync planning

• Adds targeted tests covering: satisfied-pin download behavior producing a sync plan, warn-only pins still syncing, install-family gating, skipping sync when lockfile already resolves the pin, and 'pmOnFail' override effects. Updates helper input to use a non-install command by default to exercise the new path.

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

tests.rsUpdate CLI args tests for new package_manager_to_sync signature +1/-1

Update CLI args tests for new package_manager_to_sync signature

• Adjusts existing tests to pass the new 'on_fail' argument (using 'None' where no override is intended). Keeps prior behavior assertions intact.

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

package_manager_check.rsAdd integration coverage for non-install command writing lockfile pin +17/-0

Add integration coverage for non-install command writing lockfile pin

• Adds an integration test asserting that a command outside the install family records the pinned pnpm in 'pnpm-lock.yaml' under 'packageManagerDependencies'. Prevents regressions where first command like 'run'/'list' leaves no lockfile pin written.

pnpm/crates/cli/tests/package_manager_check.rs

Documentation (1) +5 / -0
sync-package-manager-deps-on-every-command.mdDocument env-lockfile pin sync for all commands +5/-0

Document env-lockfile pin sync for all commands

• Adds a changeset noting that pinned pnpm is now recorded under 'packageManagerDependencies' for any command, not just install-family commands. Documents the interaction with 'pmOnFail' overrides.

.changeset/sync-package-manager-deps-on-every-command.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; the previously raised lockfile-disable concern is invalid because both pnpm implementations intentionally persist package-manager dependencies without a use-lockfile gate.

Reviews (4): Last reviewed commit: "fix(cli): record packageManagerDependenc..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Action required

1. Frozen/lockfile ignored in sync ✗ Dismissed 🐞 Bug ⛨ Security
Description
execute_plan always calls sync_package_manager_dependencies(..., false), so SyncEnvLockfile can
update pnpm-lock.yaml even when frozenLockfile is configured or when lockfile=false is set.
This breaks the documented “don’t write lockfile” / frozen behavior and can introduce unexpected
network+write side effects on non-install commands (e.g. run, list, --version).
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R100-108]

+        PreCommandPlan::SyncEnvLockfile(sync) => {
+            let EnvLockfileSync { config, root_dir, package_manager } = sync;
+            config_deps::sync_package_manager_dependencies(
+                &config,
+                &root_dir,
+                &package_manager.specifier,
+                &package_manager.version,
+                false,
+            )
Relevance

⭐⭐⭐ High

Pre-command should respect frozen/lockfile settings; unexpected lockfile writes/network side effects
are treated as bugs.

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The SyncEnvLockfile plan currently hardcodes frozen_lockfile=false even though config supports
lockfile=false and frozen_lockfile, and the env-installer implementation explicitly blocks
updates only when opts.frozen_lockfile is true; therefore the new pre-command sync bypasses those
controls.

pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]
pnpm/crates/cli/src/cli_args/pre_command.rs[169-175]
pnpm/crates/config/src/lib.rs[837-858]
pnpm/crates/cli/src/config_deps.rs[54-70]
pnpm/crates/env-installer/src/resolve_package_manager_integrities.rs[20-42]

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

## Issue description
The new `PreCommandPlan::SyncEnvLockfile` execution path calls `config_deps::sync_package_manager_dependencies(..., false)` unconditionally. This bypasses:
- `Config::frozen_lockfile` (so a frozen config does not prevent mutation)
- `Config::lockfile=false` (which is documented to prevent reading/generating `pnpm-lock.yaml`)

As a result, non-install commands can still write/update `pnpm-lock.yaml` and perform package-manager dependency resolution.

## Issue Context
`sync_package_manager_dependencies` takes an explicit `frozen_lockfile: bool` parameter and the env-installer implementation will refuse to update `packageManagerDependencies` only when that flag is true. The pre-command path currently never passes true.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[92-113]
- pnpm/crates/config/src/lib.rs[837-858]
- pnpm/crates/cli/src/config_deps.rs[54-70]

### Suggested implementation direction
In the `PreCommandPlan::SyncEnvLockfile` branch:
1. Short-circuit when `config.lockfile == false` (do not attempt to read/write `pnpm-lock.yaml`).
2. Derive a boolean frozen value from config (e.g. `let frozen = config.frozen_lockfile.unwrap_or(false);`).
3. Pass `frozen` into `sync_package_manager_dependencies` instead of `false`.

Optionally, to avoid planning work that will be skipped, also prevent scheduling `PreCommandPlan::SyncEnvLockfile` earlier when `config.lockfile == false`.

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



Remediation recommended

2. dbg!(&output) in version test 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new --version test contains an unconditional dbg!(&output) call that prints captured process
output to stderr on every run, creating noisy and unrelated debug logging in a bug-fix PR and
potentially surfacing unexpected stderr content. This can clutter CI logs and violates the
expectation that bug-fix PRs avoid unrelated changes like adding debug output.
Code

pnpm/crates/cli/tests/version.rs[82]

+    dbg!(&output);
Relevance

⭐⭐⭐ High

Unconditional dbg! adds noisy stderr; repo tends to keep diagnostics inside assertion messages,
not always-on logs.

PR-#13127
PR-#13372

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited lines in the new --version integration test show a dbg!(&output) invocation that
executes regardless of whether assertions pass or fail, meaning it will emit the command Output to
stderr on every successful test run. Per PR Compliance ID 2255067, bug-fix PRs should avoid
unrelated refactors/reformatting, and this added debug/logging output is unrelated to test
correctness and therefore falls into the category of avoidable noise.

Rule 2255067: Bug fix changes must not include unrelated refactors or reformatting
pnpm/crates/cli/tests/version.rs[77-84]
pnpm/crates/cli/tests/version.rs[77-85]

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 `version_flag_records_a_pinned_package_manager_it_does_not_need_to_switch_to()` includes an unconditional `dbg!(&output)` call that writes to stderr on every run, adding CI log noise and introducing an unrelated debug/logging change in a bug-fix PR.

## Issue Context
This PR is a bug fix, and the `dbg!` output is not required for correctness; because `dbg!` executes unconditionally, it can clutter CI output and may unintentionally surface captured command output. If diagnostics are useful, they should be emitted only when an assertion fails (e.g., include stdout/stderr in an assertion failure message) rather than on every successful run.

## Fix Focus Areas
- pnpm/crates/cli/tests/version.rs[77-85]

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


3. --version mutates lockfile 🐞 Bug ➹ Performance
Description
The --version/DisplayVersion path now allows env_lockfile_sync to schedule a SyncEnvLockfile
plan, so pacquet --version can read and potentially update pnpm-lock.yaml (including registry
resolution) before printing the version. This adds I/O (and potentially network + working-tree
writes) to a commonly expected fast, side-effect-free command when a project pins pnpm and the env
lockfile entry is missing/out-of-date.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R82-85]

+            // No install pipeline runs behind `--version`, so nothing else
+            // would record the pin.
+            syncs_env_lockfile_in_pipeline: false,
            emit: DefaultReporter::emit,
Relevance

⭐⭐⭐ High

Team previously accepted avoiding --version triggering repo/config discovery; similar concern
about side effects and I/O.

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
pre_command_plan_for_version_flag explicitly disables the pipeline-sync gate, and run_cli
executes the resulting pre-command plan before printing. The SyncEnvLockfile execution path calls
sync_package_manager_dependencies, which resolves and writes package-manager deps into the env
lockfile, and the env-installer path reads/writes pnpm-lock.yaml and may require registry
resolution when entries are missing/out-of-date.

pnpm/crates/cli/src/cli_args/pre_command.rs[73-90]
pnpm/crates/cli/src/lib.rs[79-90]
pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]
pnpm/crates/cli/src/config_deps.rs[54-70]
pnpm/crates/env-installer/src/resolve_package_manager_integrities.rs[20-42]
pnpm/crates/cli/src/cli_args/pre_command.rs[241-283]

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

### Issue description
`pre_command_plan_for_version_flag` currently sets `syncs_env_lockfile_in_pipeline: false`, which allows `env_lockfile_sync` to return a `SyncEnvLockfile` plan. Because `run_cli` executes that plan before printing the version, `pacquet --version` can perform lockfile I/O and even registry resolution/writes in pinned projects.

### Issue Context
This is a performance/command-semantics concern: users and tooling often rely on `--version` being fast and side-effect free. The new behavior is conditional (only pinned projects with missing/stale `packageManagerDependencies`), but it can still cause surprising working-tree modifications or failures due to lockfile/network issues.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[73-90]
- pnpm/crates/cli/src/lib.rs[79-90]
- pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]

### Suggested fix approach
- Make `--version` opt out of env-lockfile syncing (e.g., set `syncs_env_lockfile_in_pipeline: true` for the version-flag path, or add a dedicated boolean like `allow_env_lockfile_sync` and set it to `false` for `--version`).
- If you still want some parity behavior, consider a cheaper/read-only alternative for `--version` (e.g., only check/validate, or only sync when the lockfile already exists and can be updated without network), but avoid network and writes by default for `--version`.

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


4. Unsanitized path in error 🐞 Bug ⛨ Security
Description
env_lockfile_sync formats root_dir.display() into an error context string without sanitization, so
control characters in the working-directory path can reach terminal/CI output on the lockfile-read
error path. This is the same class of terminal escape injection risk previously addressed elsewhere
in pre_command output handling.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R253-255]

+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
Relevance

⭐⭐⭐ High

They recently accepted sanitizing untrusted strings in pre_command warnings/errors to prevent
terminal escape injection.

PR-#13287

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new error context directly embeds an unescaped filesystem path; the same file shows an
established pattern of sanitizing untrusted strings at the output boundary, and a recent accepted
bug notes escape-sequence injection risks in pre_command output.

pnpm/crates/cli/src/cli_args/pre_command.rs[252-255]
pnpm/crates/cli/src/cli_args/pre_command.rs[413-418]
PR-#13287

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 error context added around `EnvLockfile::read(root_dir)` interpolates `root_dir.display()` directly into a diagnostic string. Filesystem paths can contain terminal control characters, which can lead to terminal/CI log injection if the error is rendered to a terminal.

### Issue Context
This module already sanitizes warnings via `sanitize_inline()` before emitting them, but the new `wrap_err_with` context string is not sanitized.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[252-255]
- pnpm/crates/cli/src/cli_args/pre_command.rs[413-418]

### Implementation notes
- Apply `sanitize_inline()` to the formatted path string before including it in the error context, e.g.:
 - `let dir = sanitize_inline(&root_dir.display().to_string());`
 - then use `{dir}` in the message.
- Add a regression test that constructs a temp directory whose name includes ANSI/control characters, triggers an `EnvLockfile::read` failure, and asserts the emitted message is sanitized (no raw escape sequences).

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


View more (1)
5. Full lockfile parse startup 🐞 Bug ➹ Performance
Description
For projects with a persisting pnpm pin on non-install-family commands, env_lockfile_sync always
reads the entire pnpm-lock.yaml into memory and YAML-parses the env document just to decide whether
packageManagerDependencies are already resolved. This adds extra I/O + allocations + YAML parse cost
to hot-start commands (run/exec/list) even when the lockfile is already up to date.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R252-264]

+    let env_lockfile =
+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
+    if env_lockfile.is_some_and(|env_lockfile| {
+        is_package_manager_resolved(
+            &env_lockfile,
+            &package_manager.specifier,
+            &package_manager.version,
+        )
+    }) {
+        return Ok(None);
+    }
Relevance

⭐⭐ Medium

Team sometimes accepts hot-path perf fixes, but has also rejected similar “avoid extra parse/IO”
optimizations.

PR-#13359
PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new env_lockfile_sync logic reads/parses the env lockfile on the pre-command path before it can
determine that no sync is needed; the underlying reader loads the whole lockfile into memory via
read_to_string.

pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
pnpm/crates/lockfile/src/env_lockfile.rs[110-123]
pnpm/crates/lockfile/src/env_lockfile.rs[151-166]

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

### Issue description
`env_lockfile_sync()` performs a full lockfile read (string allocation) and YAML parse on common non-install commands to check `is_package_manager_resolved`, even when it will quickly return `Ok(None)` because the entry is already correct. On large lockfiles this can noticeably increase CLI startup latency.

### Issue Context
- `EnvLockfile::read()` reads the entire `pnpm-lock.yaml` into a `String`, then extracts/parses the env document.
- The up-to-date check happens *after* the read/parse.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
- pnpm/crates/lockfile/src/env_lockfile.rs[103-123]

### Implementation notes
Consider a cheaper “is up to date” probe that avoids full YAML parse / avoids reading the main lockfile document:
- Add a dedicated reader that streams only the first YAML document (stop at the document separator) instead of `read_to_string` of the full file.
- Or implement a lightweight string scan for the relevant `packageManagerDependencies` keys/specifier/version in the env doc boundary, only falling back to YAML parse if needed.
- Add a micro-benchmark or a test using a large synthetic lockfile to guard against startup regressions on `pnpm run`/`pnpm list`.

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



Informational

6. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and does not declare a bump for pnpm, which violates
the requirement that changesets explicitly include the pnpm package with a valid bump type.
Code

.changeset/sync-package-manager-deps-on-every-command.md[R1-3]

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

⭐ Low

Multiple closely analogous “add pnpm entry to pacquet-only changeset” suggestions were rejected in
recent PRs.

PR-#13377
PR-#13347
PR-#13346

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each new/modified changeset to include an explicit pnpm package
bump entry. The added changeset’s front-matter includes only pacquet and omits pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/sync-package-manager-deps-on-every-command.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 front-matter is missing a `pnpm` entry. Compliance requires changesets to explicitly declare the `pnpm` package and its bump type (`patch`/`minor`/`major`).

## Issue Context
This PR adds a new changeset at `.changeset/sync-package-manager-deps-on-every-command.md` that currently only includes `"pacquet": patch`.

## Fix Focus Areas
- .changeset/sync-package-manager-deps-on-every-command.md[1-3]

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


7. Symlink lockfile read DoS 🐞 Bug ⛨ Security
Description
env_lockfile_sync now calls EnvLockfile::read(root_dir) during pre-command for pinned projects, and
EnvLockfile::read follows symlinks and reads the entire target into a String. A malicious repo can
commit pnpm-lock.yaml as a symlink to /dev/zero (or another non-regular/huge file), causing commands
like pnpm run/list/exec to hang or OOM before the command runs.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R252-255]

+    let env_lockfile =
+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
Relevance

⭐ Low

Closely analogous hardening (reject non-regular symlink targets before reading) was rejected
previously.

PR-#13075

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The pre-command path now always attempts to read the env lockfile for pinned projects, and the
lockfile reader follows symlinks and reads unboundedly into memory, enabling a repo-controlled
symlink target to cause startup-time hangs/OOM.

pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
pnpm/crates/lockfile/src/env_lockfile.rs[110-167]

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

### Issue description
`env_lockfile_sync()` now reads `pnpm-lock.yaml` on non-install commands, and `EnvLockfile::read()` currently follows symlinks and performs an unbounded `read_to_string`. In an untrusted checkout, a repo-controlled symlinked lockfile can target special files (e.g. `/dev/zero`) or very large files, causing a startup-time hang or memory exhaustion.

### Issue Context
- The PR introduces `EnvLockfile::read(root_dir)` on pre-command paths that used to not touch the lockfile.
- `EnvLockfile::read()` ultimately uses `File::open()` (follows symlinks) and `read_to_string()` without file-type checks or size limits.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
- pnpm/crates/lockfile/src/env_lockfile.rs[110-167]

### Implementation notes
- Add a hardened read path for the env lockfile used by pre-command:
 - Reject non-regular files after open (`file.metadata()?.file_type().is_file()`), so device files/pipes can’t hang.
 - Add a maximum read size (e.g. 10–50MB) using `Read::take` and error if exceeded.
 - Keep compatibility with legitimate symlink-to-regular-file use cases (sandbox staging) by checking the *target* metadata, not only the link.
- Add a regression test that creates a symlinked `pnpm-lock.yaml` to a non-regular file (or simulates via a temp FIFO/device if feasible) and asserts the CLI fails fast with a clear error instead of hanging.

ⓘ 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 25bc1f3

Results up to commit 6641d19 ⚖️ Balanced


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


Remediation recommended
1. Unsanitized path in error 🐞 Bug ⛨ Security
Description
env_lockfile_sync formats root_dir.display() into an error context string without sanitization, so
control characters in the working-directory path can reach terminal/CI output on the lockfile-read
error path. This is the same class of terminal escape injection risk previously addressed elsewhere
in pre_command output handling.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R253-255]

+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
Relevance

⭐⭐⭐ High

They recently accepted sanitizing untrusted strings in pre_command warnings/errors to prevent
terminal escape injection.

PR-#13287

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new error context directly embeds an unescaped filesystem path; the same file shows an
established pattern of sanitizing untrusted strings at the output boundary, and a recent accepted
bug notes escape-sequence injection risks in pre_command output.

pnpm/crates/cli/src/cli_args/pre_command.rs[252-255]
pnpm/crates/cli/src/cli_args/pre_command.rs[413-418]
PR-#13287

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 error context added around `EnvLockfile::read(root_dir)` interpolates `root_dir.display()` directly into a diagnostic string. Filesystem paths can contain terminal control characters, which can lead to terminal/CI log injection if the error is rendered to a terminal.

### Issue Context
This module already sanitizes warnings via `sanitize_inline()` before emitting them, but the new `wrap_err_with` context string is not sanitized.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[252-255]
- pnpm/crates/cli/src/cli_args/pre_command.rs[413-418]

### Implementation notes
- Apply `sanitize_inline()` to the formatted path string before including it in the error context, e.g.:
 - `let dir = sanitize_inline(&root_dir.display().to_string());`
 - then use `{dir}` in the message.
- Add a regression test that constructs a temp directory whose name includes ANSI/control characters, triggers an `EnvLockfile::read` failure, and asserts the emitted message is sanitized (no raw escape sequences).

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


2. Full lockfile parse startup 🐞 Bug ➹ Performance
Description
For projects with a persisting pnpm pin on non-install-family commands, env_lockfile_sync always
reads the entire pnpm-lock.yaml into memory and YAML-parses the env document just to decide whether
packageManagerDependencies are already resolved. This adds extra I/O + allocations + YAML parse cost
to hot-start commands (run/exec/list) even when the lockfile is already up to date.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R252-264]

+    let env_lockfile =
+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
+    if env_lockfile.is_some_and(|env_lockfile| {
+        is_package_manager_resolved(
+            &env_lockfile,
+            &package_manager.specifier,
+            &package_manager.version,
+        )
+    }) {
+        return Ok(None);
+    }
Relevance

⭐⭐ Medium

Team sometimes accepts hot-path perf fixes, but has also rejected similar “avoid extra parse/IO”
optimizations.

PR-#13359
PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new env_lockfile_sync logic reads/parses the env lockfile on the pre-command path before it can
determine that no sync is needed; the underlying reader loads the whole lockfile into memory via
read_to_string.

pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
pnpm/crates/lockfile/src/env_lockfile.rs[110-123]
pnpm/crates/lockfile/src/env_lockfile.rs[151-166]

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

### Issue description
`env_lockfile_sync()` performs a full lockfile read (string allocation) and YAML parse on common non-install commands to check `is_package_manager_resolved`, even when it will quickly return `Ok(None)` because the entry is already correct. On large lockfiles this can noticeably increase CLI startup latency.

### Issue Context
- `EnvLockfile::read()` reads the entire `pnpm-lock.yaml` into a `String`, then extracts/parses the env document.
- The up-to-date check happens *after* the read/parse.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
- pnpm/crates/lockfile/src/env_lockfile.rs[103-123]

### Implementation notes
Consider a cheaper “is up to date” probe that avoids full YAML parse / avoids reading the main lockfile document:
- Add a dedicated reader that streams only the first YAML document (stop at the document separator) instead of `read_to_string` of the full file.
- Or implement a lightweight string scan for the relevant `packageManagerDependencies` keys/specifier/version in the env doc boundary, only falling back to YAML parse if needed.
- Add a micro-benchmark or a test using a large synthetic lockfile to guard against startup regressions on `pnpm run`/`pnpm list`.

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



Informational
3. Symlink lockfile read DoS 🐞 Bug ⛨ Security
Description
env_lockfile_sync now calls EnvLockfile::read(root_dir) during pre-command for pinned projects, and
EnvLockfile::read follows symlinks and reads the entire target into a String. A malicious repo can
commit pnpm-lock.yaml as a symlink to /dev/zero (or another non-regular/huge file), causing commands
like pnpm run/list/exec to hang or OOM before the command runs.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R252-255]

+    let env_lockfile =
+        EnvLockfile::read(root_dir).map_err(miette::Report::new).wrap_err_with(|| {
+            format!("read the package-manager env lockfile in {}", root_dir.display())
+        })?;
Relevance

⭐ Low

Closely analogous hardening (reject non-regular symlink targets before reading) was rejected
previously.

PR-#13075

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The pre-command path now always attempts to read the env lockfile for pinned projects, and the
lockfile reader follows symlinks and reads unboundedly into memory, enabling a repo-controlled
symlink target to cause startup-time hangs/OOM.

pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
pnpm/crates/lockfile/src/env_lockfile.rs[110-167]

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

### Issue description
`env_lockfile_sync()` now reads `pnpm-lock.yaml` on non-install commands, and `EnvLockfile::read()` currently follows symlinks and performs an unbounded `read_to_string`. In an untrusted checkout, a repo-controlled symlinked lockfile can target special files (e.g. `/dev/zero`) or very large files, causing a startup-time hang or memory exhaustion.

### Issue Context
- The PR introduces `EnvLockfile::read(root_dir)` on pre-command paths that used to not touch the lockfile.
- `EnvLockfile::read()` ultimately uses `File::open()` (follows symlinks) and `read_to_string()` without file-type checks or size limits.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[238-265]
- pnpm/crates/lockfile/src/env_lockfile.rs[110-167]

### Implementation notes
- Add a hardened read path for the env lockfile used by pre-command:
 - Reject non-regular files after open (`file.metadata()?.file_type().is_file()`), so device files/pipes can’t hang.
 - Add a maximum read size (e.g. 10–50MB) using `Read::take` and error if exceeded.
 - Keep compatibility with legitimate symlink-to-regular-file use cases (sandbox staging) by checking the *target* metadata, not only the link.
- Add a regression test that creates a symlinked `pnpm-lock.yaml` to a non-regular file (or simulates via a temp FIFO/device if feasible) and asserts the CLI fails fast with a clear error instead of hanging.

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


Results up to commit c02f9f8 ⚖️ Balanced


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


Remediation recommended
1. --version mutates lockfile 🐞 Bug ➹ Performance
Description
The --version/DisplayVersion path now allows env_lockfile_sync to schedule a SyncEnvLockfile
plan, so pacquet --version can read and potentially update pnpm-lock.yaml (including registry
resolution) before printing the version. This adds I/O (and potentially network + working-tree
writes) to a commonly expected fast, side-effect-free command when a project pins pnpm and the env
lockfile entry is missing/out-of-date.
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R82-85]

+            // No install pipeline runs behind `--version`, so nothing else
+            // would record the pin.
+            syncs_env_lockfile_in_pipeline: false,
            emit: DefaultReporter::emit,
Relevance

⭐⭐⭐ High

Team previously accepted avoiding --version triggering repo/config discovery; similar concern
about side effects and I/O.

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
pre_command_plan_for_version_flag explicitly disables the pipeline-sync gate, and run_cli
executes the resulting pre-command plan before printing. The SyncEnvLockfile execution path calls
sync_package_manager_dependencies, which resolves and writes package-manager deps into the env
lockfile, and the env-installer path reads/writes pnpm-lock.yaml and may require registry
resolution when entries are missing/out-of-date.

pnpm/crates/cli/src/cli_args/pre_command.rs[73-90]
pnpm/crates/cli/src/lib.rs[79-90]
pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]
pnpm/crates/cli/src/config_deps.rs[54-70]
pnpm/crates/env-installer/src/resolve_package_manager_integrities.rs[20-42]
pnpm/crates/cli/src/cli_args/pre_command.rs[241-283]

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

### Issue description
`pre_command_plan_for_version_flag` currently sets `syncs_env_lockfile_in_pipeline: false`, which allows `env_lockfile_sync` to return a `SyncEnvLockfile` plan. Because `run_cli` executes that plan before printing the version, `pacquet --version` can perform lockfile I/O and even registry resolution/writes in pinned projects.

### Issue Context
This is a performance/command-semantics concern: users and tooling often rely on `--version` being fast and side-effect free. The new behavior is conditional (only pinned projects with missing/stale `packageManagerDependencies`), but it can still cause surprising working-tree modifications or failures due to lockfile/network issues.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[73-90]
- pnpm/crates/cli/src/lib.rs[79-90]
- pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]

### Suggested fix approach
- Make `--version` opt out of env-lockfile syncing (e.g., set `syncs_env_lockfile_in_pipeline: true` for the version-flag path, or add a dedicated boolean like `allow_env_lockfile_sync` and set it to `false` for `--version`).
- If you still want some parity behavior, consider a cheaper/read-only alternative for `--version` (e.g., only check/validate, or only sync when the lockfile already exists and can be updated without network), but avoid network and writes by default for `--version`.

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



Informational
2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and does not declare a bump for pnpm, which violates
the requirement that changesets explicitly include the pnpm package with a valid bump type.
Code

.changeset/sync-package-manager-deps-on-every-command.md[R1-3]

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

⭐ Low

Multiple closely analogous “add pnpm entry to pacquet-only changeset” suggestions were rejected in
recent PRs.

PR-#13377
PR-#13347
PR-#13346

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each new/modified changeset to include an explicit pnpm package
bump entry. The added changeset’s front-matter includes only pacquet and omits pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/sync-package-manager-deps-on-every-command.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 front-matter is missing a `pnpm` entry. Compliance requires changesets to explicitly declare the `pnpm` package and its bump type (`patch`/`minor`/`major`).

## Issue Context
This PR adds a new changeset at `.changeset/sync-package-manager-deps-on-every-command.md` that currently only includes `"pacquet": patch`.

## Fix Focus Areas
- .changeset/sync-package-manager-deps-on-every-command.md[1-3]

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


Results up to commit 54652ff ⚖️ Balanced


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


Action required
1. Frozen/lockfile ignored in sync ✗ Dismissed 🐞 Bug ⛨ Security
Description
execute_plan always calls sync_package_manager_dependencies(..., false), so SyncEnvLockfile can
update pnpm-lock.yaml even when frozenLockfile is configured or when lockfile=false is set.
This breaks the documented “don’t write lockfile” / frozen behavior and can introduce unexpected
network+write side effects on non-install commands (e.g. run, list, --version).
Code

pnpm/crates/cli/src/cli_args/pre_command.rs[R100-108]

+        PreCommandPlan::SyncEnvLockfile(sync) => {
+            let EnvLockfileSync { config, root_dir, package_manager } = sync;
+            config_deps::sync_package_manager_dependencies(
+                &config,
+                &root_dir,
+                &package_manager.specifier,
+                &package_manager.version,
+                false,
+            )
Relevance

⭐⭐⭐ High

Pre-command should respect frozen/lockfile settings; unexpected lockfile writes/network side effects
are treated as bugs.

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The SyncEnvLockfile plan currently hardcodes frozen_lockfile=false even though config supports
lockfile=false and frozen_lockfile, and the env-installer implementation explicitly blocks
updates only when opts.frozen_lockfile is true; therefore the new pre-command sync bypasses those
controls.

pnpm/crates/cli/src/cli_args/pre_command.rs[92-112]
pnpm/crates/cli/src/cli_args/pre_command.rs[169-175]
pnpm/crates/config/src/lib.rs[837-858]
pnpm/crates/cli/src/config_deps.rs[54-70]
pnpm/crates/env-installer/src/resolve_package_manager_integrities.rs[20-42]

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

## Issue description
The new `PreCommandPlan::SyncEnvLockfile` execution path calls `config_deps::sync_package_manager_dependencies(..., false)` unconditionally. This bypasses:
- `Config::frozen_lockfile` (so a frozen config does not prevent mutation)
- `Config::lockfile=false` (which is documented to prevent reading/generating `pnpm-lock.yaml`)

As a result, non-install commands can still write/update `pnpm-lock.yaml` and perform package-manager dependency resolution.

## Issue Context
`sync_package_manager_dependencies` takes an explicit `frozen_lockfile: bool` parameter and the env-installer implementation will refuse to update `packageManagerDependencies` only when that flag is true. The pre-command path currently never passes true.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/pre_command.rs[92-113]
- pnpm/crates/config/src/lib.rs[837-858]
- pnpm/crates/cli/src/config_deps.rs[54-70]

### Suggested implementation direction
In the `PreCommandPlan::SyncEnvLockfile` branch:
1. Short-circuit when `config.lockfile == false` (do not attempt to read/write `pnpm-lock.yaml`).
2. Derive a boolean frozen value from config (e.g. `let frozen = config.frozen_lockfile.unwrap_or(false);`).
3. Pass `frozen` into `sync_package_manager_dependencies` instead of `false`.

Optionally, to avoid planning work that will be skipped, also prevent scheduling `PreCommandPlan::SyncEnvLockfile` earlier when `config.lockfile == false`.

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

Copilot AI review requested due to automatic review settings July 25, 2026 23:27

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

Thanks — one of the three led to a real fix, in c02f9f8. Taking them in turn.

2. Full lockfile parse on startup — fixed, and it was worse than described.

The read itself has to stay: it is what lets the common case cost nothing else. Without knowing what the lockfile records, every command in a pinned project would have to build a resolver and go to the registry to find out. One lockfile read is the cheap answer, not the expensive one.

But the review made me look at the path again, and the download policy — the default for devEngines.packageManager — already reads pnpm-lock.yaml in switch_target, looking for a version to switch to. My env_lockfile_sync then read and parsed the whole file a second time to answer a question the first read could already answer. Every pnpm run in a pinned project paid for two full parses.

The parsed lockfile is now threaded into the sync decision:

match &target.source {
    SwitchSource::LockedEnv { env, .. } => ReadEnvLockfile::Already(env),
    SwitchSource::Resolve { .. } => ReadEnvLockfile::NotYet,
}

Already / NotYet rather than Option<&EnvLockfile>, because None would conflate "no lockfile on disk" with "nobody has read it yet" — and those two mean opposite things to the sync decision.

pre_command_plan_records_a_pin_whose_specifier_the_lockfile_no_longer_matches covers the reuse: the shared lockfile still has to be inspected, not trusted. A lockfile holding a satisfying version resolved from a wider specifier is exactly the case where the switch lookup says "nothing to do" but the sync must still run. I verified the test fails if the Already arm short-circuits.

1. Unsanitized path in error — not sanitizing, but the duplication is gone.

The sanitize boundary in this module is drawn around manifest-derived strings — the package manager name and the wanted version range, which come from a repository the user has only cloned. global_warn says so in its doc comment. A directory path is not in that class, and the CLI interpolates path.display() into error contexts in dozens of places (canonicalizing the --dir argument: {}, initialize the state for {}, and so on). Sanitizing this one would be arbitrary, and sanitizing all of them is a repo-wide change that should be argued on its own merits, not smuggled into a parity fix.

Worth noting the flagged string is not new: switch_target has carried the identical message since the pre-command block landed, which is where I copied it from. That duplication was a fair thing to catch, so both now go through one read_env_lockfile helper — which also means that if the repo ever does adopt path sanitization, there is a single place to put it.

3. Symlink lockfile read DoS — declined, deliberately.

Reading a lockfile through a symlink is a decision the project made on purpose, not an oversight: #13073 restored it because Bazel and Nix stage pnpm-lock.yaml as a symlink, and rejecting it broke those sandboxes. Writing a changed lockfile through a symlink is still refused, which is where the actual risk is.

The exposure is also not new here. switch_target reads the env lockfile on the same pre-command path today, and so does every install. Your own note that the analogous hardening was rejected in #13075 is the same signal.


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

@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     10.9±0.02ms    34.3 MB/sec    1.04     11.4±0.02ms    32.8 MB/sec
packument/parse                1.00     36.9±0.15µs  1798.6 MB/sec    1.00     36.8±0.06µs  1803.9 MB/sec
tarball/download_dependency    1.00      2.3±0.07ms  1870.8 KB/sec    1.00      2.3±0.07ms  1872.5 KB/sec

@qodo-code-review

Copy link
Copy Markdown

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

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

🧹 Nitpick comments (1)
pnpm/crates/cli/src/cli_args/package_manager.rs (1)

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

Use PmOnFail::as_str() for package_manager_to_sync.

package_manager.rs:39-40 converts on_fail with the same match values already in pacquet_config::PmOnFail::as_str() and pre_command.rs's helper. Reuse the inherent method and remove on_fail_str from pre_command.rs so this mapping has one source of truth.

🤖 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/cli/src/cli_args/package_manager.rs` around lines 33 - 41, Update
package_manager_to_sync to use PmOnFail::as_str() when assigning pm.on_fail, and
remove the redundant on_fail_str helper from pre_command.rs. Preserve the
existing option handling and string values while making PmOnFail::as_str the
single mapping source.
🤖 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.

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/package_manager.rs`:
- Around line 33-41: Update package_manager_to_sync to use PmOnFail::as_str()
when assigning pm.on_fail, and remove the redundant on_fail_str helper from
pre_command.rs. Preserve the existing option handling and string values while
making PmOnFail::as_str the single mapping source.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c99ee563-eb4a-4d04-8d87-1b587cd6d327

📥 Commits

Reviewing files that changed from the base of the PR and between 7a77822 and c02f9f8.

📒 Files selected for processing (9)
  • .changeset/sync-package-manager-deps-on-every-command.md
  • pnpm/crates/cli/src/cli_args/package_manager.rs
  • pnpm/crates/cli/src/cli_args/pipelines.rs
  • pnpm/crates/cli/src/cli_args/pre_command.rs
  • pnpm/crates/cli/src/cli_args/pre_command/tests.rs
  • pnpm/crates/cli/src/cli_args/tests.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/tests/package_manager_check.rs
  • pnpm/crates/config/src/lib.rs

Copilot AI review requested due to automatic review settings July 25, 2026 23:38

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

Two new findings in the updated review, plus CodeRabbit's nitpick — all addressed in 54652ff.

--version mutates lockfile — kept, and now tested.

pnpm --version already runs the whole pre-command package-manager block, in both stacks, and that is deliberate. In pnpm/src/main.ts the block is gated on shouldSkipPmHandling(cmd, cliParams), which returns false when cmd == null — the --version case — so switchCliVersion / syncEnvLockfile run before the version is printed. pacquet mirrors it through pre_command_plan_for_version_flag, which exists for exactly that reason.

The side effect is not new, and the version flag is not a read-only command today. tests/version.rs's version_flag_switches_to_project_package_manager_version has pnpm --version resolve [email protected] from the registry, download it, and re-exec — and for a pin that persists to the lockfile, install_pnpm_to_store calls sync_package_manager_dependencies on the way, writing packageManagerDependencies into the project's pnpm-lock.yaml. So on main, pnpm --version in a devEngines-pinned project whose version doesn't match already goes to the network and writes the lockfile.

What this PR adds to that path is the smaller half: recording the pin when no download is needed. Taking the suggested fix would make --version the one command that silently skips the pin — the command-order dependence #13348 is about, in a subtler form.

Since it is a real behavioral decision, it now has a test rather than only a comment: version_flag_records_a_pinned_package_manager_it_does_not_need_to_switch_to. I verified it fails under the suggested change (syncs_env_lockfile_in_pipeline: true for the version path).

If pnpm --version should be side-effect-free, that is a change to the shared contract and belongs in both stacks at once — worth its own issue, not a one-sided edit here.

Changeset missing pnpm entry — intentional, per the repo's own rule.

pnpm/AGENTS.md is explicit: "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 changes only Rust crates, so "pacquet": patch alone is correct. The general "always include pnpm" rule is the TypeScript-CLI one; the Rust products section overrides it.

CodeRabbit's nitpick — accepted.

Right, and it was my own leftover: adding PmOnFail::as_str() made pre_command.rs's local on_fail_str redundant. The helper is gone and switch_target uses the inherent method, so the mapping has one home.


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

@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/version.rs`:
- Around line 85-90: Update the lockfile assertion in the version test to parse
pnpm-lock.yaml as YAML and inspect the packageManagerDependencies mapping
directly. Assert that this mapping contains the expected pinned package-manager
entry, rather than independently checking broad string containment; retain the
existing failure context showing the written lockfile.
🪄 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: 3d14db5f-3793-42c4-96d0-3b5667f8561a

📥 Commits

Reviewing files that changed from the base of the PR and between c02f9f8 and 54652ff.

📒 Files selected for processing (10)
  • .changeset/sync-package-manager-deps-on-every-command.md
  • pnpm/crates/cli/src/cli_args/package_manager.rs
  • pnpm/crates/cli/src/cli_args/pipelines.rs
  • pnpm/crates/cli/src/cli_args/pre_command.rs
  • pnpm/crates/cli/src/cli_args/pre_command/tests.rs
  • pnpm/crates/cli/src/cli_args/tests.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/tests/package_manager_check.rs
  • pnpm/crates/cli/tests/version.rs
  • pnpm/crates/config/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (8)
  • .changeset/sync-package-manager-deps-on-every-command.md
  • pnpm/crates/config/src/lib.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/src/cli_args/package_manager.rs
  • pnpm/crates/cli/tests/package_manager_check.rs
  • pnpm/crates/cli/src/cli_args/pipelines.rs
  • pnpm/crates/cli/src/cli_args/pre_command/tests.rs
  • pnpm/crates/cli/src/cli_args/pre_command.rs

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 54652ff

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

pnpm's pre-command block calls syncEnvLockfile for every command that isn't
in skipPackageManagerCheckForCommand, so a project pinning pnpm through
devEngines.packageManager (or a v12+ packageManager field) gets its
packageManagerDependencies recorded whatever the user ran. pacquet synced
only from the install-family pipelines, so `pnpm list` in a fresh clone left
no lockfile behind.

pre_command_plan now returns a PreCommandPlan — either the version switch it
already planned, or the env-lockfile sync it needs — and lib.rs runs whichever
came back on the pre-command runtime. The sync is planned in the same two
places pnpm reaches syncEnvLockfile: after checkPackageManager on the
warn/error/corepack path, and on the download path when the running pnpm
already satisfies the pin (where pnpm's switchCliVersion still resolves and
saves before returning).

The install family is excluded, because it passes its own frozen-lockfile
value to the sync and pacquet — unlike pnpm — fails a frozen install whose
packageManagerDependencies are out of date. Syncing those commands from the
pre-command block would repair the lockfile before the pipeline could refuse
to. Excluding them also keeps the up-to-date install fast path free of the
lockfile read.

The plan is skipped without touching the network whenever the env lockfile
already records a version satisfying the pin. That answer needs the lockfile,
but the download path has already read it looking for a version to switch to,
and `pnpm-lock.yaml` is read whole — so the parsed lockfile is threaded into
the sync decision rather than read a second time. A warm pinned project pays
one lockfile read per command, the same as before.

package_manager_to_sync now takes the effective pmOnFail rather than reading
the manifest's own onFail, matching how pnpm resolves
wantedPackageManager.onFail before shouldPersistLockfile sees it.

Closes #13348

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

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 25bc1f3

@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 1590aeb into main Jul 25, 2026
35 of 36 checks passed
@zkochan
zkochan deleted the fix-13348 branch July 25, 2026 23:56
@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Heads-up on the one red check: Code Coverage is failing repo-wide right now, not because of this PR.

Same signature everywhere — the job dies about 5–6 minutes in with the Run step never reporting a conclusion (null), which is the runner going away rather than a test or a threshold failing:

run branch result
30179519420 main failure
30179537922 main failure
30179767654 this PR failure
23:32–23:39 fix-13335, fix-13345 failure

The main runs contain none of this change, and coverage was green on main until 23:12. Everything else here is green, including the full Rust CI matrix (ubuntu, macOS, windows), Clippy, Dylint, Doc, Format, Spell Check and Cargo Deny.


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

kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…13382)

pnpm's pre-command block calls syncEnvLockfile for every command that isn't
in skipPackageManagerCheckForCommand, so a project pinning pnpm through
devEngines.packageManager (or a v12+ packageManager field) gets its
packageManagerDependencies recorded whatever the user ran. pacquet synced
only from the install-family pipelines, so `pnpm list` in a fresh clone left
no lockfile behind.

pre_command_plan now returns a PreCommandPlan — either the version switch it
already planned, or the env-lockfile sync it needs — and lib.rs runs whichever
came back on the pre-command runtime. The sync is planned in the same two
places pnpm reaches syncEnvLockfile: after checkPackageManager on the
warn/error/corepack path, and on the download path when the running pnpm
already satisfies the pin (where pnpm's switchCliVersion still resolves and
saves before returning).

The install family is excluded, because it passes its own frozen-lockfile
value to the sync and pacquet — unlike pnpm — fails a frozen install whose
packageManagerDependencies are out of date. Syncing those commands from the
pre-command block would repair the lockfile before the pipeline could refuse
to. Excluding them also keeps the up-to-date install fast path free of the
lockfile read.

The plan is skipped without touching the network whenever the env lockfile
already records a version satisfying the pin. That answer needs the lockfile,
but the download path has already read it looking for a version to switch to,
and `pnpm-lock.yaml` is read whole — so the parsed lockfile is threaded into
the sync decision rather than read a second time. A warm pinned project pays
one lockfile read per command, the same as before.

package_manager_to_sync now takes the effective pmOnFail rather than reading
the manifest's own onFail, matching how pnpm resolves
wantedPackageManager.onFail before shouldPersistLockfile sees it.

Closes pnpm#13348
zkochan added a commit that referenced this pull request Sep 26, 2026
The install loaded only the global and project pnpmfiles, so a config
dependency plugin's pnpmfile contributed its updateConfig hook and
nothing else. Its readPackage, afterAllResolved and custom resolvers
never ran, and pnpmfileChecksum left it out. pnpm 11 puts plugin
pnpmfiles in the same requireHooks set as the project's.

PnpmfileSelection now carries the config dependencies, and
find_pnpmfiles returns the global pnpmfile, then the installed plugin
pnpmfiles, then the project's own, which is pnpm 11's order. Every
consumer of the selection now sees the same set: install, update,
deploy, the lockfile freshness checks, the optimistic repeat-install
state, and the updateConfig/beforePacking pass. The updateConfig pass
used to run plugins ahead of the global pnpmfile and now runs them
after it, as pnpm 11 does.

The up-to-date fast path already bails out whenever config dependencies
exist, so it is unaffected. The workspace state's pnpmfile list now
includes plugin pnpmfiles, as pnpm 11's does. A state written before
this change therefore triggers one re-validation.

Closes pnpm/pnpm#12366. Its env-lockfile items were already fixed by
#13382, #13346 and #13436. This was the last
lockfile divergence found while verifying them.

---------

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

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pacquet: packageManagerDependencies are synced only by install commands, not by every command as in pnpm

2 participants