Skip to content

feat(pacquet-cli): port the with command - #12696

Merged
zkochan merged 6 commits into
mainfrom
with
Jun 27, 2026
Merged

zkochan merged 6 commits into
mainfrom
with

Conversation

@zkochan

@zkochan zkochan commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports pnpm's with command to the Rust pacquet/ port (the TypeScript CLI already ships it, so this is the pacquet side catching up — no TypeScript change).

  • pnpm with <version> <args...> — resolves the spec (version / range / dist-tag) through the trusted package-manager bootstrap registry, installs that pnpm engine into the global virtual store (<store>/links/..., matching pnpm's installPnpmToStore: shared across invocations and, unlike self-update, not registered in the global packages directory so pnpm ls -g doesn't see it), then spawns it with the remaining args and the child's packageManager / devEngines.packageManager check disabled.
  • pnpm with current <args...> — rewritten before clap parses argv into a direct in-process dispatch of <args>, forcing pmOnFail to ignore via the pnpm_config_pm_on_fail env var.

Implementation notes:

  • GVS install fidelity. The engine is installed with the global virtual store enabled and pnpm / `@pnpm/exe` marked buildable, so ENGINE_NAME is folded into the GVS hash exactly as pnpm's findPnpmGvsPath does. To avoid any hash-mismatch risk, the install is located via its post-install symlink (ground truth), while the pipeline's own VirtualStoreLayout drives the cache-hit short-circuit — so install and locate are guaranteed consistent, and a cache hit skips both the re-install and the network signature check, like pnpm.
  • Reuse. The self-update engine installer was made global-virtual-store aware and its engine-identity verifier + native-binary linker promoted to pub(crate), so with reuses the proven, signature-verifying install path instead of duplicating it.
  • pmOnFail setting is wired into Config and the env overlay so the override is honored once the runtime packageManager check is ported (the check itself is not ported yet).

Squash Commit Body

Port pnpm's `with` command to pacquet.

`pnpm with <version> <args...>` resolves the spec through the trusted
package-manager bootstrap registry, installs that pnpm engine into the
global virtual store (matching pnpm's installPnpmToStore — shared across
invocations and, unlike self-update, not registered in the global
packages directory), and spawns it with the remaining args and the
child's packageManager check disabled.

`pnpm with current <args...>` is rewritten before clap parses argv into a
direct in-process dispatch of `<args>`, forcing pmOnFail to ignore via
the pnpm_config_pm_on_fail env var.

Wire the pmOnFail setting into Config and the env overlay so the override
is honored once the packageManager check is ported. Reuse the self-update
engine installer (now global-virtual-store aware) and the engine-identity
verifier rather than duplicating them.

The end-to-end `with <version>` download path has no automated test
because the mock registry does not serve the pnpm / `@pnpm/exe` engine
packages, the same limitation self-update has.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting. (The
    TypeScript CLI already has with; this is the pacquet port.)
  • Added or updated tests. (with_current argv-rewrite unit tests +
    with integration tests for the usage errors and the with current
    rewrite. The end-to-end with <version> download path is not covered
    because the mock registry doesn't serve the pnpm / `@pnpm/exe`
    engine packages — the same limitation self-update has.)

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

Summary by CodeRabbit

  • New Features
    • Added a with command to run pnpm for a specified version (or current) in a single invocation.
    • Added with current shorthand for inline commands.
    • Added pmOnFail / PM_ON_FAIL support across configuration, workspace YAML, and environment overrides.
  • Bug Fixes
    • Improved with/with current validation and diagnostics for missing spec/command and safer argument handling.
    • Prevents running under corepack and forwards pnpm spawn failures correctly.
    • Adds a PATH delimiter safety check for the shared pnpm install.
  • Tests
    • Added/expanded unit and CLI test coverage for with and with current.

@coderabbitai

coderabbitai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds pnpm with and pnpm with current handling, threads pm_on_fail through config parsing, and updates pnpm installation so the command can resolve and spawn a pinned engine from the shared store.

Changes

CLI with command and config plumbing

Layer / File(s) Summary
pm_on_fail config
pacquet/crates/config/src/lib.rs, pacquet/crates/config/src/env_overlay.rs, pacquet/crates/config/src/workspace_yaml.rs, pacquet/crates/package-manager/src/install_package_from_registry/tests.rs
Adds PmOnFail to config types, workspace YAML, env overrides, and the package-manager test fixture.
with current rewrite
pacquet/crates/cli/src/lib.rs, pacquet/crates/cli/src/with_current.rs, pacquet/crates/cli/src/with_current/tests.rs
Rewrites pnpm with current argv before clap parsing and validates the token-planning rules.
with command contract
pacquet/crates/cli/src/cli_args.rs, pacquet/crates/cli/src/cli_args/cli_command.rs, pacquet/crates/cli/src/cli_args/dispatch.rs, pacquet/crates/cli/src/cli_args/with.rs, pacquet/crates/cli/src/cli_args/with/tests.rs
Registers CliCommand::With, adds its CLI argument and error types, wires the route entry, and covers prepend_to_path.
GVS installer support
pacquet/crates/cli/src/cli_args/self_update/*, pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs
Makes self-update helpers crate-visible and adds the shared-virtual-store pnpm installer.
with execution
pacquet/crates/cli/src/cli_args/dispatch_query.rs, pacquet/crates/cli/src/cli_args/with.rs, pacquet/crates/cli/tests/with.rs
Loads config, resolves and runs pinned pnpm, spawns it with a computed PATH, and checks the top-level with failures.

Sequence Diagram(s)

sequenceDiagram
  participant Main as main
  participant Rewrite as with_current::rewrite
  participant Parse as CliArgs::parse_from
  participant Route as dispatch_query::with
  participant Run as WithArgs::run
  participant Install as install_pnpm_to_store::install_pnpm_to_store
  participant Pnpm as pnpm

  Main->>Rewrite: rewrite argv before clap parsing
  Rewrite-->>Main: rewritten argv or error
  Main->>Parse: parse argv
  Parse->>Route: route CliCommand::With(args)
  Route->>Run: args.run::<Reporter>(config)
  Run->>Install: install pnpm@spec into store
  Install-->>Run: bin path
  Run->>Pnpm: spawn installed pnpm with args
  Pnpm-->>Run: exit status
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • pnpm/pnpm#12693: Shares the pnpm with path and the helper access used to resolve and install a pinned pnpm engine.

Suggested labels

product: pacquet

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

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-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

feat(pacquet-cli): port the pnpm with command to Rust
✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

Description

• Adds pnpm with   subcommand that resolves the spec, installs the engine into the global virtual
 store (/links/...), and spawns it with packageManager checks disabled.
• Adds pnpm with current  as a pre-parse argv rewrite that strips the with current tokens and
 forces pmOnFail=ignore via env var before clap sees the arguments.
• Promotes self-update's run_install, link_exe_platform_binary, and
 verify_pnpm_engine_identity to pub(crate) so with can reuse the proven, signature-verifying
 install path.
• Extends run_install with an enable_global_virtual_store flag so the engine lands in
 /links/... (GVS) for with vs. the self-contained install dir for self-update.
• Adds PmOnFail enum and Config::pm_on_fail field, wired into WorkspaceSettings,
 env_overlay, and pnpm-workspace.yaml deserialization.
• Adds unit tests for the with current argv rewrite and integration tests for usage errors and the
 with current dispatch.
Diagram

graph TD
    A["main() / lib.rs"] --> B["with_current::rewrite"]
    B -->|"strips 'with current', sets env var"| C["clap / CliArgs::parse_from"]
    C --> D["CliCommand::With"]
    D --> E["dispatch_query::with"]
    E --> F["WithArgs::run"]
    F --> G["install_pnpm_to_store"]
    G --> H["self_update::run_install\n(GVS enabled)"]
    G --> I["verify_pnpm_engine_identity"]
    G --> J[("Global Virtual Store\n store/links/...")]
    F --> K["spawn_pnpm\n(PATH + pmOnFail=ignore)"]
    L["Config / PmOnFail"] --> E
    subgraph Legend
        direction LR
        _db[("Store / FS")] ~~~ _svc["Module / Function"]
    end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use `tempfile::TempDir` for the throwaway install directory
  • ➕ Guaranteed unique names via OS-provided temp-file APIs
  • ➕ Automatic cleanup on drop even if the process panics before remove_dir_all
  • ➖ Adds a dependency (tempfile crate)
  • ➖ Minor: the current PID+nanos approach is sufficient in practice

Recommendation: The PR's approach is well-suited to the problem. The key design decision — reusing self_update's install pipeline rather than duplicating it — is the right call and avoids divergence in the security-critical signature-verification path. One alternative worth noting is using a dedicated temp-dir crate (e.g. tempfile) instead of the hand-rolled PID+timestamp suffix for concurrent-invocation isolation, which would be more robust against clock skew and PID reuse. The current approach is acceptable for now but could be improved.

Files changed (17) +687 / -14

Enhancement (8) +67 / -3
cli_command.rsRegister 'With(WithArgs)' variant in the 'CliCommand' enum +5/-0

Register 'With(WithArgs)' variant in the 'CliCommand' enum

• Adds the 'With(WithArgs)' variant with a doc-comment describing the command's behavior, making it visible to clap's subcommand parser.

pacquet/crates/cli/src/cli_args/cli_command.rs

dispatch.rsRoute 'CliCommand::With' to 'dispatch_query::with' +1/-0

Route 'CliCommand::With' to 'dispatch_query::with'

• Adds a match arm for 'CliCommand::With(args)' that delegates to the new 'dispatch_query::with' handler.

pacquet/crates/cli/src/cli_args/dispatch.rs

dispatch_query.rsAdd 'with' dispatch function wiring reporter selection +15/-0

Add 'with' dispatch function wiring reporter selection

• Implements 'pub(super) fn with' that loads config and dispatches 'WithArgs::run' with the appropriate reporter type (Default/AppendOnly, Ndjson, or Silent).

pacquet/crates/cli/src/cli_args/dispatch_query.rs

cli_args.rsExpose 'with' module from 'cli_args' +1/-0

Expose 'with' module from 'cli_args'

• Adds 'pub mod with;' to the 'cli_args' module so 'WithArgs' is accessible from the rest of the crate.

pacquet/crates/cli/src/cli_args.rs

lib.rsWire 'with_current::rewrite' into the main argv processing pipeline +6/-0

Wire 'with_current::rewrite' into the main argv processing pipeline

• Adds 'mod with_current' and calls 'with_current::rewrite(argv)?' between 'ConfigOverrides::extract' and 'CliArgs::parse_from', so 'with current' is rewritten before clap sees the arguments.

pacquet/crates/cli/src/lib.rs

lib.rsAdd 'PmOnFail' enum and 'Config::pm_on_fail' field +29/-0

Add 'PmOnFail' enum and 'Config::pm_on_fail' field

• Defines the 'PmOnFail' enum ('Download | Error | Warn | Ignore') mirroring pnpm's 'pmOnFail' setting, and adds an optional 'pm_on_fail' field to 'Config' so the package-manager check can read the configured behavior.

pacquet/crates/config/src/lib.rs

env_overlay.rsWire 'pm_on_fail' into the env-var overlay +2/-1

Wire 'pm_on_fail' into the env-var overlay

• Adds 'enum_field!(pm_on_fail, "PM_ON_FAIL", PmOnFail)' so 'pnpm_config_pm_on_fail' env var is read and applied to 'Config::pm_on_fail' during the env overlay pass.

pacquet/crates/config/src/env_overlay.rs

workspace_yaml.rsAdd 'pmOnFail' to 'WorkspaceSettings' and apply it to 'Config' +8/-2

Add 'pmOnFail' to 'WorkspaceSettings' and apply it to 'Config'

• Adds 'pm_on_fail: Option<PmOnFail>' to 'WorkspaceSettings' for deserialization from 'pnpm-workspace.yaml', and applies it to 'Config::pm_on_fail' in 'WorkspaceSettings::apply_to'.

pacquet/crates/config/src/workspace_yaml.rs

Refactor (3) +45 / -11
install_pnpm.rsMake engine installer GVS-aware and promote internals to 'pub(crate)' +40/-8

Make engine installer GVS-aware and promote internals to 'pub(crate)'

• Adds 'enable_global_virtual_store: bool' parameter to 'run_install'; when true, sets 'cfg.global_virtual_store_dir' to '<store>/links/' and populates 'allow_builds' with 'PNPM_ALLOW_BUILDS' so 'ENGINE_NAME' enters the GVS hash. Promotes 'run_install', 'link_exe_platform_binary', 'PNPM_PACKAGE_NAME', and the new 'PNPM_ALLOW_BUILDS' constant to 'pub(crate)' for reuse by 'with'.

pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs

verify_engine.rsPromote 'verify_pnpm_engine_identity' to 'pub(crate)' +1/-1

Promote 'verify_pnpm_engine_identity' to 'pub(crate)'

• Changes the visibility of 'verify_pnpm_engine_identity' from 'pub(super)' to 'pub(crate)' so the 'with' command can reuse the registry-signature verification path.

pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs

self_update.rsRe-export 'install_pnpm' and 'verify_engine' submodules as 'pub(crate)' +4/-2

Re-export 'install_pnpm' and 'verify_engine' submodules as 'pub(crate)'

• Changes 'mod install_pnpm' and 'mod verify_engine' from private to 'pub(crate)' so the 'with' command can import from them directly.

pacquet/crates/cli/src/cli_args/self_update.rs

Tests (3) +143 / -0
tests.rsUnit tests for the 'with current' argv rewrite logic +74/-0

Unit tests for the 'with current' argv rewrite logic

• Covers stripping 'with current', forwarding command arguments, preserving global flags before 'with', leaving non-'current' specs untouched, erroring on missing command, skipping 'with' consumed by a value-taking option, and the 'long_option_consumes_value' predicate.

pacquet/crates/cli/src/with_current/tests.rs

with.rsIntegration tests for 'pnpm with' usage errors and 'with current' dispatch +68/-0

Integration tests for 'pnpm with' usage errors and 'with current' dispatch

• Tests that 'pnpm with' (no spec) fails with the expected error message, 'pnpm with current' (no command) fails with the expected error, and 'pnpm with current <unknown-cmd>' strips the 'with current' tokens and passes the inner command to clap.

pacquet/crates/cli/tests/with.rs

tests.rsInitialize 'pm_on_fail: None' in test config fixture +1/-0

Initialize 'pm_on_fail: None' in test config fixture

• Adds the new 'pm_on_fail: None' field to the 'create_config' helper so the test config struct remains complete after the 'Config' struct gained the new field.

pacquet/crates/package-manager/src/install_package_from_registry/tests.rs

Other (3) +432 / -0
with.rsNew 'with' subcommand handler: resolve spec, install to GVS, spawn pnpm +147/-0

New 'with' subcommand handler: resolve spec, install to GVS, spawn pnpm

• Implements 'WithArgs::run', which resolves the version spec via the bootstrap registry, delegates to 'install_pnpm_to_store', then spawns the downloaded pnpm with 'bin_dir' prepended to PATH and 'pnpm_config_pm_on_fail=ignore' set. Defines 'WithError' variants mirroring pnpm's 'ERR_PNPM_*' codes. Includes helpers for PATH manipulation and corepack detection.

pacquet/crates/cli/src/cli_args/with.rs

install_pnpm_to_store.rsNew GVS-based pnpm engine installer for 'pnpm with' +180/-0

New GVS-based pnpm engine installer for 'pnpm with'

• Ports pnpm's 'installPnpmToStore': syncs the env lockfile, computes the GVS slot for a cache-hit short-circuit, verifies the engine's registry signature on a genuine download, runs the install into a throwaway temp dir with GVS enabled, resolves the real slot via symlink canonicalization, and links bins. Concurrent invocations are isolated via a PID+timestamp temp-dir suffix.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs

with_current.rsPre-parse argv rewrite for 'pnpm with current <cmd>' +105/-0

Pre-parse argv rewrite for 'pnpm with current <cmd>'

• Implements 'rewrite(argv)' which scans for a 'with current' token pair (skipping pairs consumed by value-taking long options), drains them from argv, and sets 'pnpm_config_pm_on_fail=ignore' via env var before clap parses. The pure 'plan()' function is split out for testability without environment mutation.

pacquet/crates/cli/src/with_current.rs

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Trust policy bypass 🐞 Bug ⛨ Security
Description
WithArgs::run ignores ResolvedPnpm.policy_violation from resolve_pnpm_version, so `pnpm with
<spec>` can proceed even when the resolver indicates the chosen version violated configured
minimumReleaseAge/trustPolicy gates. This fails open compared to self-update, undermining strict
maturity/trust policy enforcement for the new command.
Code

pacquet/crates/cli/src/cli_args/with.rs[R78-81]

+        let resolved = config_deps::resolve_pnpm_version(config, spec)
+            .await?
+            .ok_or_else(|| WithError::CannotResolvePnpm { spec: spec.clone() })?;
+
Evidence
with resolves a pnpm version and proceeds directly to install/spawn without checking
policy_violation, while ResolvedPnpm explicitly includes that flag to represent a maturity/trust
gate violation and self-update fails closed under strict resolution when it is set.

pacquet/crates/cli/src/cli_args/with.rs[71-93]
pacquet/crates/cli/src/config_deps.rs[73-84]
pacquet/crates/cli/src/cli_args/self_update.rs[139-147]

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

## Issue description
`pnpm with <spec>` resolves a pnpm version via `config_deps::resolve_pnpm_version`, but does not check the returned `ResolvedPnpm.policy_violation` flag before proceeding. In this codebase, `policy_violation` explicitly signals that the resolver picked a version despite maturity/trust gates; `self-update` treats this as merge-blocking under strict resolution.
## Issue Context
- `ResolvedPnpm.policy_violation` is documented as a maturity/trust gate violation indicator.
- `self-update` computes `strict_resolution` and fails closed when `policy_violation` is true.
- `with` should honor the same strict-mode semantics (or explicitly document/encode a different behavior).
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with.rs[71-93]
- pacquet/crates/cli/src/cli_args/self_update.rs[139-147]
- pacquet/crates/cli/src/config_deps.rs[73-84]
## Suggested fix
1. After resolving `resolved`, compute `strict_resolution` using the same logic as `self-update`:
- strict when `(config.resolved_minimum_release_age().is_some() && config.resolved_minimum_release_age_strict()) || config.trust_policy == TrustPolicy::NoDowngrade`.
2. If `strict_resolution && resolved.policy_violation`, return an error (add a `WithError::ReleasePolicyViolation { version: String }` diagnostic, or reuse an existing shared error type/pattern).
3. Add a unit/integration test that configures strict resolution and asserts `pnpm with <spec>` fails when `resolve_pnpm_version` reports `policy_violation=true` (you can mock/stub resolver behavior where existing test infrastructure allows).

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


2. PATH delimiter injection ✓ Resolved 🐞 Bug ⛨ Security
Description
spawn_pnpm prepends bin_dir to PATH without rejecting path-delimiter characters, so a
repo-controlled storeDir containing ':' (or ';' on Windows) can split into multiple PATH entries
in the child process. This can make the child pnpm (and any tools it spawns) resolve
attacker-controlled executables first when running pnpm with ... inside a malicious workspace.
Code

pacquet/crates/cli/src/cli_args/with.rs[R134-142]

+/// Prepend `dir` to the current process `PATH`.
+fn prepend_to_path(dir: &Path) -> OsString {
+    let sep = if cfg!(windows) { ";" } else { ":" };
+    let mut out = OsString::from(dir);
+    if let Some(current) = std::env::var_os("PATH").filter(|value| !value.is_empty()) {
+        out.push(sep);
+        out.push(current);
+    }
+    out
Evidence
with builds PATH by raw concatenation with ':'/';' and does not validate bin_dir, while
store_dir is workspace-configurable (repo-controlled) and exec already documents/implements a
delimiter guard to avoid PATH splitting/injection.

pacquet/crates/cli/src/cli_args/with.rs[134-142]
pacquet/crates/config/src/workspace_yaml.rs[794-796]
pacquet/crates/cli/src/cli_args/exec.rs[214-231]
pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[87-90]

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

## Issue description
`pacquet with` constructs the child PATH by string-concatenating `bin_dir` + `:`/`;` + existing PATH. If `bin_dir` contains the platform PATH delimiter character, the resulting PATH is interpreted as multiple entries, enabling PATH injection.
## Issue Context
- `store_dir` is configurable from `pnpm-workspace.yaml` and is resolved relative to the workspace directory, so a malicious repo can set it to a delimiter-containing path.
- `pacquet exec` already treats this as an error (it rejects delimiter-containing PATH entries) to avoid silent splitting.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with.rs[99-142]
- pacquet/crates/config/src/workspace_yaml.rs[781-796]
- pacquet/crates/cli/src/cli_args/exec.rs[214-251]
## Suggested fix
- Add a delimiter guard before constructing the PATH (mirroring `exec::prepend_dirs_to_path`):
- Determine delimiter (`:` on Unix, `;` on Windows).
- If `bin_dir.to_string_lossy().contains(delimiter)`, return a structured error (new `WithError` variant or reuse an existing pnpm-style error code if appropriate).
- Prefer reusing/shared helper code for PATH construction to keep parity across commands.
- Add a unit/integration test that sets `storeDir` to a path containing the delimiter and asserts `pnpm with ...` fails with the explicit error (rather than silently producing a malformed PATH).

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


3. Overbroad argv rewrite ✓ Resolved 🐞 Bug ≡ Correctness
Description
with_current::rewrite can strip a with current token pair even when it appears inside another
subcommand’s arguments (e.g. pnpm exec ...), because it scans the entire argv and drains the first
matching pair it finds. This can change which command clap parses/executes and can also incorrectly
force pnpm_config_pm_on_fail=ignore for that invocation.
Code

pacquet/crates/cli/src/with_current.rs[R54-83]

+fn plan(mut argv: Vec<OsString>) -> miette::Result<(Vec<OsString>, bool)> {
+    let Some(index) = find_with_current_index(&argv) else {
+        return Ok((argv, false));
+    };
+    // `with current` with nothing after it is a usage error.
+    if argv.len() <= index + 2 {
+        return Err(MissingWithCurrentCommand.into());
+    }
+    argv.drain(index..index + 2);
+    Ok((argv, true))
+}
+
+/// The index of the `with` token of the first `with current` command pair
+/// in `argv`, skipping a pair whose `with` is the argument of a preceding
+/// value-taking long option. Mirrors pnpm's `findWithCurrentIndex`.
+fn find_with_current_index(argv: &[OsString]) -> Option<usize> {
+    // Start at 1 to skip the program name; stop before the last element so
+    // `index + 1` is always in bounds.
+    for index in 1..argv.len().saturating_sub(1) {
+        if argv[index] != "with" || argv[index + 1] != "current" {
+            continue;
+        }
+        if let Some(prev) = argv.get(index - 1)
+            && long_option_consumes_value(prev)
+        {
+            continue;
+        }
+        return Some(index);
+    }
+    None
Evidence
The rewrite runs before clap parsing and drains the first with current pair found anywhere in
argv, with no awareness of the subcommand boundary; because commands like exec accept arbitrary
trailing args, with current can legitimately appear there and would be incorrectly removed.

pacquet/crates/cli/src/lib.rs[24-33]
pacquet/crates/cli/src/with_current.rs[54-83]
pacquet/crates/cli/src/cli_args/exec.rs[27-33]

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

## Issue description
`with_current::find_with_current_index` scans the whole argv vector for the first `with current` sequence and `plan()` drains it. Because `rewrite()` runs before clap parsing, this can rewrite tokens that are *arguments* to another subcommand (e.g. `pnpm exec with current ...`), changing behavior and incorrectly setting `pnpm_config_pm_on_fail=ignore`.
### Issue Context
The rewrite should only apply when `with` is the **actual top-level subcommand** (`pnpm [global-opts] with current <cmd> ...`), not when `with current` appears later as data passed to other commands.
### Fix Focus Areas
- pacquet/crates/cli/src/with_current.rs[54-83]
### Suggested fix
1. Compute the subcommand position as: the first non-flag token after skipping known global options (and respecting `--` as end-of-options).
- From `CliArgs`, the global options to account for include:
- `-C`/`--dir` (takes value)
- `--npmrc-auth-file`/`--userconfig` (takes value)
- `-r`/`--recursive` (boolean)
- `--reporter` (takes value)
- `-F`/`--filter` (takes value; can repeat)
- `--filter-prod` (takes value; can repeat)
2. Only rewrite if the token at the computed command position is exactly `with` and the next token is `current`.
3. Do **not** scan beyond the command position; this prevents rewriting inside subcommand trailing args.
4. Add unit tests that prove no rewrite occurs for e.g. `pnpm exec with current install` and `pnpm run with current`.

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


View more (3)
4. PATH fallback wrong pnpm ✓ Resolved 🐞 Bug ☼ Reliability
Description
On a cache hit, install_pnpm_to_store returns slot/bin without validating that the pnpm shim
exists, but spawn_pnpm resolves pnpm by searching the full PATH; if the shim is missing/broken,
a different pnpm (e.g. from the project/user PATH) may be executed instead of the requested
engine.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R66-74]

+    if let Some(slot) = compute_pnpm_slot(config, &env, version) {
+        let pkg_dir = slot.join("node_modules").join(PNPM_PACKAGE_NAME);
+        let bin_dir = slot.join("bin");
+        if pkg_dir.join("package.json").exists() {
+            if !bin_dir.exists() {
+                link_bins(&pkg_dir, &bin_dir)?;
+            }
+            return Ok(bin_dir);
+        }
Evidence
The cache-hit early return only checks package.json and whether bin_dir exists, not whether
bin_dir contains pnpm. The spawned program is then resolved by searching the extended PATH, so
if bin_dir lacks pnpm, another PATH entry can be selected.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[60-74]
pacquet/crates/cli/src/cli_args/with.rs[99-110]

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

## Issue description
`install_pnpm_to_store` treats an existing slot as a cache hit and returns `bin_dir` if `package.json` exists, but it does not ensure that `bin_dir` actually contains a valid `pnpm` executable/shim. `spawn_pnpm` then uses `which::which_in("pnpm", Some(&path), ...)`, which can fall through to another `pnpm` elsewhere on PATH.
### Issue Context
This breaks the guarantee that `pnpm with <spec> ...` runs the resolved engine, and can also become a PATH-hijack footgun if an unexpected `pnpm` earlier in PATH is executed.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[60-75]
- pacquet/crates/cli/src/cli_args/with.rs[99-129]
### Suggested change
1) On cache hit, verify that the expected executable exists in `bin_dir` (platform-aware: `pnpm` vs `pnpm.cmd`/`pnpm.exe`). If missing, re-run `link_bins(...)` (and ideally make it overwrite/repair existing shims).
2) In `spawn_pnpm`, resolve `pnpm` **only** within `bin_dir` (not the full PATH). Options:
- Directly build the expected path (`bin_dir.join("pnpm")` / `pnpm.cmd`) and execute it.
- Or call `which_in` with a PATH string that contains only `bin_dir`, so failure is an error instead of falling back to another PATH entry.

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


5. Cache hit skips verification 🐞 Bug ⛨ Security
Description
install_pnpm_to_store treats an existing GVS slot as a cache hit and returns it before running
verify_pnpm_engine_identity, so the engine can be executed without any identity check. Because
storeDir is configurable from pnpm-workspace.yaml, a malicious repo can point the store at
attacker-controlled content and get arbitrary code run when a developer executes `pnpm with <spec>
...`.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R60-75]

+    // Cache hit: when the engine already sits in its GVS slot, skip both
+    // the signature check and the install — exactly as pnpm short-circuits
+    // on `fs.existsSync(pnpmPkgDir/package.json)`. The slot is computed
+    // with the same hashing the install pipeline uses, so a stale or wrong
+    // computation merely misses the cache (the idempotent install below
+    // then re-derives the slot from the install's own symlink).
+    if let Some(slot) = compute_pnpm_slot(config, &env, version) {
+        let pkg_dir = slot.join("node_modules").join(PNPM_PACKAGE_NAME);
+        let bin_dir = slot.join("bin");
+        if pkg_dir.join("package.json").exists() {
+            if !bin_dir.exists() {
+                link_bins(&pkg_dir, &bin_dir)?;
+            }
+            return Ok(bin_dir);
+        }
+    }
Evidence
The cache-hit branch returns bin_dir purely based on package.json existence and explicitly skips
verify_pnpm_engine_identity (which only runs on the miss path). storeDir is applied from
pnpm-workspace.yaml, making the store location (and thus the cache-hit contents) potentially
repo-controlled.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-83]
pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[84-113]
pacquet/crates/config/src/workspace_yaml.rs[785-796]

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

## Issue description
`install_pnpm_to_store()` short-circuits on `pkg_dir/package.json.exists()` and skips `verify_pnpm_engine_identity()` and reinstall. Since `storeDir` can be set by repo-controlled `pnpm-workspace.yaml`, an attacker can pre-populate the expected `<store>/links/...` slot (and `bin/`) so `pnpm with` executes attacker-provided `pnpm` without any verification.
### Issue Context
- The signature/identity verification only happens on a “genuine download”. The cache-hit path uses a filesystem existence check as the only guard.
- For `pnpm with`, this is a security-sensitive boundary: the command is explicitly intended to run a *trusted* pnpm engine resolved via the bootstrap registry.
### Fix Focus Areas
Pick one of these defenses (stronger earlier in the list):
1) **Do not use repo-controlled store settings for `with` engines**: force a trusted per-user store root for the engine install/cache (ignore `pnpm-workspace.yaml`/project `.npmrc` for `storeDir`/`globalVirtualStoreDir` when installing the engine).
2) **Remove the cache-hit early return** for `with` (always run an idempotent install path that validates content integrity in the store).
3) **Harden the cache-hit check**: when `pkg_dir/package.json` exists, validate the slot contents match the env lockfile (at minimum `name/version`, and ideally integrity/store verification for `pnpm`, `@pnpm/exe`, and the platform binary) before returning `bin_dir`.
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-113]
- pacquet/crates/config/src/workspace_yaml.rs[785-796]

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


6. Unsafe temp directory 🐞 Bug ⛨ Security
Description
install_pnpm_to_store creates a predictable temp directory under the configurable store tmp path
via create_dir_all and later remove_dir_all without any symlink/TOCTOU hardening. If the store
tmp dir is shared/attacker-writable (or pacquet is run with elevated privileges against an
attacker-writable store), a pre-created symlink can redirect writes and/or cleanup outside the store
tree.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R87-104]

+    let tmp_install_dir =
+        config.store_dir.tmp().join(format!("pnpm-with-{version}-{}", unique_suffix()));
+    fs::create_dir_all(&tmp_install_dir)
+        .into_diagnostic()
+        .wrap_err("create the temporary pnpm install directory")?;
+    let slot = Box::pin(run_install::<Reporter>(
+        config,
+        &tmp_install_dir,
+        version,
+        config.supported_architectures.clone(),
+        true,
+    ))
+    .await
+    .and_then(|()| resolve_slot(&tmp_install_dir));
+    // The temp directory held only symlinks into the GVS, so removing it
+    // does not touch the installed engine.
+    let _ = fs::remove_dir_all(&tmp_install_dir);
+    let slot = slot?;
Evidence
The new code creates and deletes a temp directory under the configurable store tmp path without
symlink checks, while other code in the repo explicitly rejects symlink temp dirs before
remove_dir_all.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[84-113]
pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[173-180]
pacquet/crates/store-dir/src/store_dir.rs[22-28]
pacquet/crates/store-dir/src/store_dir.rs[161-164]
pacquet/crates/cli/src/cli_args/patch_commit.rs[404-420]

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

## Issue description
`install_pnpm_to_store` builds a temp install path from a predictable string (version + pid + timestamp), creates it with `fs::create_dir_all`, runs installation work that writes beneath it, then best-effort deletes it with `fs::remove_dir_all`.
Because `store_dir` (and therefore `<store>/tmp`) is configurable, this becomes a classic symlink/TOCTOU hazard when the tmp parent is not strictly private to the current user/process (e.g., shared store, misconfigured permissions, or privileged execution). A pre-created symlink at the expected temp path can redirect installer writes and/or cleanup outside the intended store subtree.
### Issue Context
The repo already has precedent for guarding temp-dir cleanup against symlinks before `remove_dir_all`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[84-113]
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[173-180]
- pacquet/crates/cli/src/cli_args/patch_commit.rs[404-420]
### Concrete fix direction
- Replace the hand-rolled `tmp_install_dir` naming + `create_dir_all` with a secure tempdir creation API (e.g., `tempfile::Builder::new().prefix("pnpm-with-").tempdir_in(config.store_dir.tmp())`) so the directory is created uniquely and atomically.
- Before deleting, ensure the temp path is not a symlink (and ideally that it is under `<store>/tmp`) similar to `remove_dir_if_exists` in `patch_commit.rs`.
- Don’t silently ignore cleanup errors: either surface them (if safe) or emit a debug log so failures don’t mask unexpected filesystem state.

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



Remediation recommended

7. Cache hit skips exe link 🐞 Bug ☼ Reliability ⭐ New
Description
install_pnpm_to_store returns a cache-hit slot after only checking for package.json, but it
never re-runs link_exe_platform_binary on that path. If a prior run crashed after the engine was
materialized in the GVS but before the native executable was linked, pnpm with can repeatedly
return a non-functional engine until the store is manually repaired.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R60-75]

+    // Cache hit: when the engine already sits in its GVS slot, skip both
+    // the signature check and the install — exactly as pnpm short-circuits
+    // on `fs.existsSync(pnpmPkgDir/package.json)`. The slot is computed
+    // with the same hashing the install pipeline uses, so a stale or wrong
+    // computation merely misses the cache (the idempotent install below
+    // then re-derives the slot from the install's own symlink).
+    if let Some(slot) = compute_pnpm_slot(config, &env, version) {
+        let pkg_dir = slot.join("node_modules").join(PNPM_PACKAGE_NAME);
+        let bin_dir = slot.join("bin");
+        if pkg_dir.join("package.json").exists() {
+            if !bin_dir.exists() {
+                link_bins(&pkg_dir, &bin_dir)?;
+            }
+            return Ok(bin_dir);
+        }
+    }
Evidence
The cache-hit branch returns slot/bin after checking only package.json and possibly linking
bin/, but it never invokes the native-binary linker that is required when scripts are disabled;
the linker is explicitly described as the critical path to avoid a non-functional pnpm install.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[60-75]
pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[226-235]
pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[265-294]

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

### Issue description
On the cache-hit path in `install_pnpm_to_store`, we short-circuit to `Ok(bin_dir)` once `<slot>/node_modules/pnpm/package.json` exists and (optionally) `bin/` is linked. However, the install pipeline relies on `link_exe_platform_binary` (scripts are disabled) to make the wrapper functional; if a prior invocation crashed after downloading/materializing but before this step, future runs will treat it as a hit and keep returning a broken engine.

### Issue Context
`link_exe_platform_binary` is documented as the critical step to avoid a “successful install with a non-functional pnpm” when scripts are disabled.

### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[60-75]
- pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs[226-294]

### Suggested fix
1. In the cache-hit branch, add a lightweight “repair” check for the wrapper executable inside `<slot>/node_modules/pnpm` (e.g., `pnpm` on unix, `pnpm.exe` on Windows).
2. If missing (or unconditionally, if acceptable), call `link_exe_platform_binary(&slot, PNPM_PACKAGE_NAME)` before returning.
3. Keep the existing `bin_dir` existence check/linking, but ensure the engine wrapper is functional before returning the cache-hit path.

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


8. Nondeterministic snapshot key pick 🐞 Bug ⛨ Security ⭐ New
Description
compute_pnpm_slot iterates env.snapshots (a HashMap) and picks the first key whose
without_peer() equals pnpm@<version>. Because without_peer() can collapse multiple distinct
keys (e.g., patch-hash + peer variants) to the same base, the selected slot can become
iteration-order dependent when such variants exist, leading to an unintended engine slot being
treated as the cache hit.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R122-125]

+fn compute_pnpm_slot(config: &Config, env: &EnvLockfile, version: &str) -> Option<PathBuf> {
+    let wanted: PackageKey = format!("{PNPM_PACKAGE_NAME}@{version}").parse().ok()?;
+    let key = env.snapshots.keys().find(|key| key.without_peer() == wanted)?.clone();
+
Evidence
The code selects the snapshot key by iterating an unordered HashMap and comparing
without_peer(), which (by design) strips peer and patch-hash suffixes—so multiple distinct
snapshot keys can legitimately collapse to the same base and make the chosen key dependent on
HashMap iteration order.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[122-125]
pacquet/crates/lockfile/src/env_lockfile.rs[67-80]
pacquet/crates/lockfile/src/pkg_name_ver_peer.rs[40-47]
pacquet/crates/lockfile/src/pkg_name_ver_peer/tests.rs[119-132]

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

### Issue description
`compute_pnpm_slot` chooses the snapshot key by scanning `env.snapshots.keys()` and selecting the first entry where `key.without_peer() == wanted`. Since `EnvLockfile.snapshots` is a `HashMap`, iteration order is unstable; and since `without_peer()` strips peer suffixes and patch hashes, multiple snapshot keys can match the same `wanted` base.

### Issue Context
This function drives the cache-hit short-circuit for `pnpm with`. If the env lockfile ever contains multiple variants that collapse to the same base key, this lookup becomes nondeterministic and may resolve an unintended GVS slot.

### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[122-143]
- pacquet/crates/lockfile/src/env_lockfile.rs[67-80]
- pacquet/crates/lockfile/src/pkg_name_ver_peer.rs[40-47]
- pacquet/crates/lockfile/src/pkg_name_ver_peer/tests.rs[119-132]

### Suggested fix
- Prefer an exact key match first: `if env.snapshots.contains_key(&wanted) { key = wanted; }`.
- Otherwise, collect all matching keys where `without_peer() == wanted`:
 - If there is exactly one match, use it.
 - If there are 0 or >1 matches, return `None` (treat as cache miss) to avoid nondeterministic slot selection.
This preserves the “safe miss” behavior while making hits deterministic.

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


9. Misleading NoGlobalDir help 🐞 Bug ⚙ Maintainability
Description
WithError::NoGlobalDir is raised when config.global_pkg_dir is None, but its diagnostic help
suggests setting global-bin-dir, which does not populate global_pkg_dir and therefore won’t
resolve this failure. This can mislead users into applying a config change that cannot fix `pnpm
with` startup in environments where pnpm home/global dir cannot be derived.
Code

pacquet/crates/cli/src/cli_args/with.rs[R41-48]

+    #[display("Unable to find the global packages directory")]
+    #[diagnostic(
+        code(ERR_PNPM_NO_GLOBAL_BIN_DIR),
+        help(
+            r#"Run "pnpm setup" to create it automatically, or set the global-bin-dir setting, or the PNPM_HOME env variable."#
+        )
+    )]
+    NoGlobalDir,
Evidence
The error is thrown specifically because config.global_pkg_dir is missing, but Config::current
computes global_pkg_dir from global_dir or pnpm home independently of global_bin_dir, so
advising global-bin-dir can’t address the root cause.

pacquet/crates/cli/src/cli_args/with.rs[41-48]
pacquet/crates/cli/src/cli_args/with.rs[82-83]
pacquet/crates/config/src/lib.rs[2263-2279]

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

## Issue description
`WithError::NoGlobalDir` fires when `Config.global_pkg_dir` is absent, but the diagnostic help text recommends setting `global-bin-dir`, which is not used to derive `global_pkg_dir`. Users following the help will still hit the same error.
### Issue Context
- `pnpm with` needs `config.global_pkg_dir` (`env_root`) and errors if it is `None`.
- `Config::current` derives `global_pkg_dir` from `global_dir` (env: `pnpm_config_global_dir` / `PNPM_CONFIG_GLOBAL_DIR`) or from the pnpm home dir; `global_bin_dir` is derived separately and does not affect `global_pkg_dir`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with.rs[41-48]
- pacquet/crates/config/src/lib.rs[2263-2279]
### What to change
- Update `WithError::NoGlobalDir` help text to recommend settings that actually influence `global_pkg_dir`, e.g.:
- `global-dir` / `PNPM_CONFIG_GLOBAL_DIR`, and/or
- `PNPM_HOME` (if that’s the intended control surface), and/or
- `pnpm setup`.
- Remove (or de-emphasize) `global-bin-dir` from this specific error’s help since it does not resolve `global_pkg_dir` being `None`.

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


View more (7)
10. Silent temp-dir leak 🐞 Bug ☼ Reliability
Description
install_pnpm_to_store discards errors from deleting its temporary install directory, so failed
cleanups (permission errors, Windows file locks, etc.) can silently accumulate /tmp/pnpm-with-*
directories and waste disk over time. Because the error is ignored, users get no signal that the
store is growing due to leaked temp dirs.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R101-107]

+    // The temp directory held only symlinks into the GVS, so removing it
+    // does not touch the installed engine. Refuse to recurse through a
+    // symlink at the temp path as defense-in-depth — even though the store
+    // is within pnpm's trust domain — mirroring the guard `patch-commit`
+    // applies before its own `remove_dir_all`.
+    let _ = remove_dir_if_not_symlink(&tmp_install_dir);
+    let slot = slot?;
Evidence
The code creates a per-invocation temp install directory under store_dir.tmp(), then explicitly
ignores any error returned by the removal helper. The helper can return real errors (e.g. invalid
input when the path is a symlink, or any remove_dir_all failure), but those are dropped, so leaked
directories are possible without observability.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[84-116]
pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[176-196]

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

## Issue description
`install_pnpm_to_store` performs best-effort cleanup of the temporary install directory, but it currently discards any error returned by `remove_dir_if_not_symlink`. When cleanup fails, the temp directory can be left behind indefinitely, causing store/tmp bloat and making failures hard to diagnose.
## Issue Context
This temp directory is created on genuine downloads (cache misses) and can be created repeatedly across invocations. Cleanup failures are plausible on Windows (file locks) and on any platform with transient permission/IO errors.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[84-116]
## Implementation notes
- Don’t ignore the `Result` from `remove_dir_if_not_symlink`.
- Either:
- emit a warning via the active reporter/logger when cleanup fails (preferred for non-fatal cleanup), or
- attach cleanup failure as additional context when the install itself fails.
- If you want to keep it non-fatal on the success path, explicitly document that behavior and log at least once per invocation so disk leaks are diagnosable.

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


11. Non-atomic env lockfile writes 🐞 Bug ☼ Reliability
Description
The new pnpm with flow updates the shared package-manager env lockfile under global_pkg_dir, but
the env lockfile writer overwrites pnpm-lock.yaml in-place, so concurrent pnpm with invocations
or a crash mid-write can leave a truncated/invalid lockfile and break later runs.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R50-58]

+    // Resolve `pnpm` + `@pnpm/exe` + their closure into the env lockfile
+    // (a no-op when this spec+version is already recorded there).
+    config_deps::sync_package_manager_dependencies(config, env_root, spec, version, false).await?;
+    let env = EnvLockfile::read(env_root)
+        .map_err(miette::Report::new)
+        .wrap_err("read the package-manager env lockfile")?
+        .ok_or_else(|| {
+            miette::miette!("the package-manager env lockfile is missing after resolution")
+        })?;
Evidence
install_pnpm_to_store always runs the env-installer sync against env_root (the global env root)
before reading the resulting lockfile. The underlying env lockfile writer uses a single fs::write
to overwrite the combined YAML documents, which is non-atomic and vulnerable to
truncation/corruption under concurrent writes or crashes.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-58]
pacquet/crates/lockfile/src/env_lockfile.rs[133-149]

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

## Issue description
`pnpm with` depends on a shared env lockfile stored under the global env root (`global_pkg_dir`). Today the env lockfile write path overwrites `pnpm-lock.yaml` directly (non-atomic), so concurrent writers or an interrupted write can corrupt the file and cause subsequent invocations to fail.
### Issue Context
This PR introduces a new command (`with`) that is likely to be invoked frequently and potentially concurrently (e.g., CI steps, shells, or tools). That increases the practical exposure of the env lockfile persistence behavior.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-58]
- pacquet/crates/lockfile/src/env_lockfile.rs[138-149]
### Suggested fix approach
- Change `EnvLockfile::write` to use an atomic temp-file + `rename` strategy (write into the same directory, fsync as appropriate, then rename).
- Consider adding a simple lock (file lock / OS-level lock) around the read-modify-write in the env-installer path so two concurrent `with` processes don’t clobber each other’s updates.

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


12. Duplicate env lockfile parsing 🐞 Bug ➹ Performance
Description
install_pnpm_to_store causes redundant disk I/O and YAML parsing by calling
sync_package_manager_dependencies (which reads/parses the env lockfile to check if it’s already
resolved) and then immediately calling EnvLockfile::read again.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R50-58]

+    // Resolve `pnpm` + `@pnpm/exe` + their closure into the env lockfile
+    // (a no-op when this spec+version is already recorded there).
+    config_deps::sync_package_manager_dependencies(config, env_root, spec, version, false).await?;
+    let env = EnvLockfile::read(env_root)
+        .map_err(miette::Report::new)
+        .wrap_err("read the package-manager env lockfile")?
+        .ok_or_else(|| {
+            miette::miette!("the package-manager env lockfile is missing after resolution")
+        })?;
Evidence
The env-installer sync path reads/parses the env lockfile to decide whether it’s already resolved.
The with installer then reads/parses the same lockfile again to compute cache hit / verify /
install decisions, creating redundant work on every run.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-58]
pacquet/crates/cli/src/config_deps.rs[58-71]
pacquet/crates/env-installer/src/resolve_package_manager_integrities.rs[24-29]

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

## Issue description
On the `pnpm with` path, the env lockfile is read twice per invocation:
1) inside `sync_package_manager_dependencies` via `resolve_package_manager_integrities` (reads/parses to check cache hit)
2) immediately after, via `EnvLockfile::read` in `install_pnpm_to_store`
This doubles YAML I/O/parsing on a path intended to be fast on warm caches.
### Issue Context
This is introduced by the new `with` command’s implementation and affects every invocation, including cache hits.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[50-58]
- pacquet/crates/cli/src/config_deps.rs[58-71]
- pacquet/crates/env-installer/src/resolve_package_manager_integrities.rs[24-29]
### Suggested fix approach
- Refactor `sync_package_manager_dependencies` to return the `EnvLockfile` it read/produced (or a struct containing it), so `install_pnpm_to_store` can reuse it.
- Alternatively, read the env lockfile once in `install_pnpm_to_store`, check `is_package_manager_resolved(...)`, and only call `sync_package_manager_dependencies` on a miss (then re-read only in the miss case).

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


13. Short flag mis-rewrite ✓ Resolved 🐞 Bug ≡ Correctness
Description
with_current::find_with_current_index only avoids rewriting when with is the value of a
preceding value-taking *long* option, but it ignores short options like -C/--dir and
-F/--filter that also consume the next token. This can incorrectly strip with current and
force pnpm_config_pm_on_fail=ignore, changing command meaning (e.g. pnpm -C with current install
becomes effectively pnpm -C install).
Code

pacquet/crates/cli/src/with_current.rs[R66-102]

+/// The index of the `with` token of the first `with current` command pair
+/// in `argv`, skipping a pair whose `with` is the argument of a preceding
+/// value-taking long option. Mirrors pnpm's `findWithCurrentIndex`.
+fn find_with_current_index(argv: &[OsString]) -> Option<usize> {
+    // Start at 1 to skip the program name; stop before the last element so
+    // `index + 1` is always in bounds.
+    for index in 1..argv.len().saturating_sub(1) {
+        if argv[index] != "with" || argv[index + 1] != "current" {
+            continue;
+        }
+        if let Some(prev) = argv.get(index - 1)
+            && long_option_consumes_value(prev)
+        {
+            continue;
+        }
+        return Some(index);
+    }
+    None
+}
+
+/// Whether `token` is a long option that consumes the next argv token as
+/// its value. Booleans and `--no-` negations don't; an inline `--opt=val`
+/// carries its own value. Unknown long options are assumed to consume a
+/// value, matching pnpm.
+fn long_option_consumes_value(token: &OsString) -> bool {
+    let Some(token) = token.to_str() else {
+        return false;
+    };
+    if !token.starts_with("--") || token.contains('=') {
+        return false;
+    }
+    let name = &token[2..];
+    if name.starts_with("no-") {
+        return false;
+    }
+    !BOOLEAN_LONG_OPTIONS.contains(&name)
+}
Evidence
The rewrite logic only calls long_option_consumes_value (which explicitly ignores non---...
tokens), so a preceding short option won’t block rewriting. Pacquet’s clap definitions include
global short options -C (dir) and -F (filter) that consume the following argv token, so with
can legitimately appear as an option value and must not trigger rewriting.

pacquet/crates/cli/src/with_current.rs[66-102]
pacquet/crates/cli/src/cli_args/cli_command.rs[57-104]

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

## Issue description
`with_current::find_with_current_index` only checks whether the token *before* `with` is a long option that consumes a value. However, pacquet has global short options (notably `-C` and `-F`) that consume the next token too; in those cases `with` may be an option value and must not be treated as the `with` subcommand.
### Issue Context
This can cause accidental argv rewrites and unintended `pnpm_config_pm_on_fail=ignore` injection.
### Fix Focus Areas
- pacquet/crates/cli/src/with_current.rs[66-102]
- pacquet/crates/cli/src/with_current/tests.rs[13-74]
### Suggested fix
- Extend the “option consumes value” guard to also recognize short options that take a value (at minimum `-C` and `-F`, matching `CliArgs`).
- Add unit tests covering cases like:
- `pnpm -C with current install` (must **not** rewrite)
- `pnpm -F with current install` (must **not** rewrite)
- Prefer a single helper like `option_consumes_value(token: &OsString)` that checks both long and known short value-takers to reduce drift as global flags evolve.

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


14. Cache probe hashes all snapshots 🐞 Bug ➹ Performance
Description
compute_pnpm_slot constructs a VirtualStoreLayout with Some(&env.snapshots), which precomputes
GVS suffixes by iterating every snapshot and hashing each; this makes the cache-hit probe more
expensive than necessary for a command intended to be fast on warm caches.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R122-143]

+fn compute_pnpm_slot(config: &Config, env: &EnvLockfile, version: &str) -> Option<PathBuf> {
+    let wanted: PackageKey = format!("{PNPM_PACKAGE_NAME}@{version}").parse().ok()?;
+    let key = env.snapshots.keys().find(|key| key.without_peer() == wanted)?.clone();
+
+    let mut cfg = config.clone();
+    cfg.enable_global_virtual_store = true;
+    cfg.global_virtual_store_dir = config.store_dir.links();
+    cfg.allow_builds.clear();
+    for name in PNPM_ALLOW_BUILDS {
+        cfg.allow_builds.insert(name.to_string(), true);
+    }
+    let policy = AllowBuildPolicy::from_config(&cfg).ok()?;
+    let engine = detect_node_major().map(|major| engine_name(major, None, None));
+    let layout = VirtualStoreLayout::new(
+        &cfg,
+        engine.as_deref(),
+        Some(&env.snapshots),
+        Some(&env.packages),
+        Some(&policy),
+    );
+    Some(layout.slot_dir(&key))
+}
Evidence
compute_pnpm_slot passes the full env.snapshots map into VirtualStoreLayout::new. When
snapshots are present and GVS is enabled, VirtualStoreLayout::new iterates `for (snapshot_key,
snapshot) in snapshots and computes calc_graph_node_hash(...)` for each entry to populate
gvs_suffixes, which is unnecessary work when only one slot dir is needed.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[118-143]
pacquet/crates/package-manager/src/virtual_store_layout.rs[158-246]

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

## Issue description
`compute_pnpm_slot` calls `VirtualStoreLayout::new(..., Some(&env.snapshots), ...)` and then asks for `layout.slot_dir(&key)`. When snapshots are provided, `VirtualStoreLayout::new` builds the dep graph and computes hash/suffix entries for **all** snapshots, even though `pnpm with` only needs the slot for one key (`pnpm@version`).
### Issue Context
This runs on the cache-hit probe path of `pnpm with`, so the extra hashing work becomes recurring overhead on repeated invocations.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[118-143]
- pacquet/crates/package-manager/src/virtual_store_layout.rs[158-246]
### Suggested change
Implement a targeted slot computation API that hashes only the requested snapshot:
- Build the dep graph once from the provided snapshots/packages.
- Call the existing hash routine for the single desired `PackageKey` (with memoization), rather than iterating and hashing every snapshot to populate a full `gvs_suffixes` map.
Concretely, consider adding a helper in `pacquet_package_manager` (or `pacquet_graph_hasher`) like `compute_gvs_slot_dir_for_key(config, engine, snapshots, packages, policy, key)` that returns the slot path for one key without precomputing suffixes for all entries.

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


15. Cache probe spawns node 🐞 Bug ➹ Performance
Description
compute_pnpm_slot calls detect_node_major(), which spawns node --version, adding a process
spawn to every cache-hit probe even when the engine is already installed. This increases latency for
repeated pnpm with  invocations on warm caches.
Code

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[R119-132]

+fn compute_pnpm_slot(config: &Config, env: &EnvLockfile, version: &str) -> Option<PathBuf> {
+    let wanted: PackageKey = format!("{PNPM_PACKAGE_NAME}@{version}").parse().ok()?;
+    let key = env.snapshots.keys().find(|key| key.without_peer() == wanted)?.clone();
+
+    let mut cfg = config.clone();
+    cfg.enable_global_virtual_store = true;
+    cfg.global_virtual_store_dir = config.store_dir.links();
+    cfg.allow_builds.clear();
+    for name in PNPM_ALLOW_BUILDS {
+        cfg.allow_builds.insert(name.to_string(), true);
+    }
+    let policy = AllowBuildPolicy::from_config(&cfg).ok()?;
+    let engine = detect_node_major().map(|major| engine_name(major, None, None));
+    let layout = VirtualStoreLayout::new(
Evidence
compute_pnpm_slot invokes detect_node_major(), and detect_node_major() is implemented by
spawning node --version, so the cache-hit probe incurs a process spawn each time it runs.

pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[119-139]
pacquet/crates/graph-hasher/src/engine_name.rs[43-70]

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 `with` cache-hit probe (`compute_pnpm_slot`) spawns `node --version` via `detect_node_major()` to compute `ENGINE_NAME`, even when the pnpm engine is already present in the store. This adds avoidable overhead to the warm-cache path.
### Issue Context
`detect_node_major()` is implemented by spawning `node --version` and parsing stdout; unlike `host_libc()`, it is not cached.
### Fix Focus Areas
- Add a cached variant of `detect_node_major()` (e.g., `LazyLock<Option<u32>>`) so the spawn happens at most once per process.
- Optionally, thread a precomputed node-major/engine-name into `compute_pnpm_slot` so this function stays pure and avoids spawning.
- pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[119-139]
- pacquet/crates/graph-hasher/src/engine_name.rs[43-70]

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


16. Startup unsafe set_var 🐞 Bug ⛨ Security
Description
with_current::rewrite uses unsafe { std::env::set_var(...) } to force
pnpm_config_pm_on_fail=ignore. This is only sound if no other threads can read the environment at
that moment, so the safety of this code depends on a fragile startup-ordering invariant.
Code

pacquet/crates/cli/src/with_current.rs[R37-46]

+pub fn rewrite(argv: Vec<OsString>) -> miette::Result<Vec<OsString>> {
+    let (argv, force_pm_on_fail_ignore) = plan(argv)?;
+    if force_pm_on_fail_ignore {
+        // SAFETY: `rewrite` runs in `main` before the tokio runtime and
+        // rayon pool start, so the process is single-threaded and no other
+        // thread can be reading the environment concurrently.
+        unsafe {
+            std::env::set_var("pnpm_config_pm_on_fail", "ignore");
+        }
+    }
Evidence
The code performs an unsafe environment mutation, and it is called from main as part of startup;
the safety relies on ordering remaining thread-free until that point.

pacquet/crates/cli/src/with_current.rs[37-46]
pacquet/crates/cli/src/lib.rs[16-46]

Agent prompt
The issue below was found during a code review. Fol...

@github-actions

github-actions Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.00      6.7±0.27ms   643.3 KB/sec    1.01      6.8±0.48ms   634.6 KB/sec

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@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 `@pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs`:
- Around line 60-74: The cache-hit path in
install_pnpm_to_store::install_pnpm_to_store is returning too early when
package.json exists, even though fresh installs still perform the executable/bin
setup. Update the cache-hit branch so it validates or recreates the runnable
wrapper the same way the normal install flow does, using the existing
link_exe_platform_binary and link_bins steps after the package directory check.
Ensure a partially completed prior install cannot leave compute_pnpm_slot
returning a bin directory that has package files but no runnable wrapper.
🪄 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: f595374b-7c22-4bd5-8d99-9c902974b5e2

📥 Commits

Reviewing files that changed from the base of the PR and between f8e5a0d and c7baf10.

📒 Files selected for processing (17)
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/cli_command.rs
  • pacquet/crates/cli/src/cli_args/dispatch.rs
  • pacquet/crates/cli/src/cli_args/dispatch_query.rs
  • pacquet/crates/cli/src/cli_args/self_update.rs
  • pacquet/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs
  • pacquet/crates/cli/src/cli_args/with.rs
  • pacquet/crates/cli/src/cli_args/with/install_pnpm_to_store.rs
  • pacquet/crates/cli/src/lib.rs
  • pacquet/crates/cli/src/with_current.rs
  • pacquet/crates/cli/src/with_current/tests.rs
  • pacquet/crates/cli/tests/with.rs
  • pacquet/crates/config/src/env_overlay.rs
  • pacquet/crates/config/src/lib.rs
  • pacquet/crates/config/src/workspace_yaml.rs
  • pacquet/crates/package-manager/src/install_package_from_registry/tests.rs

@codecov-commenter

codecov-commenter commented Jun 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 31.90661% with 175 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.26%. Comparing base (66c531e) to head (0359401).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...tes/cli/src/cli_args/with/install_pnpm_to_store.rs 0.00% 112 Missing ⚠️
pacquet/crates/cli/src/cli_args/with.rs 30.00% 42 Missing ⚠️
...rates/cli/src/cli_args/self_update/install_pnpm.rs 23.52% 13 Missing ⚠️
pacquet/crates/cli/src/with_current.rs 92.59% 4 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch_query.rs 71.42% 2 Missing ⚠️
...ates/cli/src/cli_args/self_update/verify_engine.rs 0.00% 1 Missing ⚠️
pacquet/crates/config/src/workspace_yaml.rs 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12696      +/-   ##
==========================================
- Coverage   85.47%   85.26%   -0.22%     
==========================================
  Files         393      396       +3     
  Lines       59808    60060     +252     
==========================================
+ Hits        51120    51208      +88     
- Misses       8688     8852     +164     

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

@github-actions

github-actions Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 452eb3fd6d6e

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.940 ± 0.209 4.666 5.356 1.67 ± 0.11
pacquet@main 4.812 ± 0.154 4.687 5.159 1.63 ± 0.10
pnpr@HEAD 2.961 ± 0.154 2.793 3.320 1.00
pnpr@main 3.012 ± 0.120 2.870 3.264 1.02 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.940197974299999,
      "stddev": 0.2089688943622284,
      "median": 4.8904063873,
      "user": 4.0330213,
      "system": 3.54516084,
      "min": 4.6659136138,
      "max": 5.3556278528,
      "times": [
        5.1002910578,
        5.3556278528,
        4.8758003728,
        5.1675707838,
        4.913422456799999,
        4.8498600248,
        4.8340479387999995,
        4.7344332397999995,
        4.9050124018,
        4.6659136138
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.811601972499999,
      "stddev": 0.1535351445285978,
      "median": 4.750202412799999,
      "user": 3.9999656000000003,
      "system": 3.5207178399999988,
      "min": 4.6867592958,
      "max": 5.159288731799999,
      "times": [
        5.159288731799999,
        4.7026206317999995,
        5.022335540799999,
        4.6867592958,
        4.7757251558,
        4.748082473799999,
        4.752322351799999,
        4.7477649118,
        4.735277894799999,
        4.785842736799999
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.9605167997999997,
      "stddev": 0.1544656639616241,
      "median": 2.9144356013,
      "user": 2.7538668999999993,
      "system": 3.0510536399999997,
      "min": 2.7929461568000002,
      "max": 3.3202393818,
      "times": [
        2.8574679008,
        2.7929461568000002,
        2.8874573248,
        2.8302593978000004,
        2.9303007008,
        3.3202393818,
        2.9804232398,
        3.0837570928,
        3.0237463008,
        2.8985705018
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.0117384674000007,
      "stddev": 0.12015120464529101,
      "median": 2.9892560763000002,
      "user": 2.7097960999999997,
      "system": 3.0585041399999993,
      "min": 2.8703012618000003,
      "max": 3.2638128558,
      "times": [
        3.1596982248,
        2.9841289508,
        2.9197053878,
        3.0390366898,
        3.2638128558,
        2.8703012618000003,
        2.9790647848000003,
        3.0101440538,
        2.9943832018000003,
        2.8971092628000004
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 650.5 ± 13.6 632.0 674.9 1.00
pacquet@main 660.0 ± 38.6 630.6 766.0 1.01 ± 0.06
pnpr@HEAD 699.9 ± 11.7 685.4 716.4 1.08 ± 0.03
pnpr@main 699.7 ± 21.7 677.8 750.8 1.08 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6505262658400001,
      "stddev": 0.013583563307290472,
      "median": 0.65348965264,
      "user": 0.3939404999999999,
      "system": 1.33518578,
      "min": 0.63201450064,
      "max": 0.67489736664,
      "times": [
        0.65734068064,
        0.63901863264,
        0.63770790864,
        0.65298544664,
        0.67489736664,
        0.66448003064,
        0.63822130464,
        0.63201450064,
        0.65460292864,
        0.65399385864
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6599547347400001,
      "stddev": 0.03863656148801284,
      "median": 0.65466073114,
      "user": 0.38494779999999995,
      "system": 1.32645118,
      "min": 0.63062207064,
      "max": 0.76604441264,
      "times": [
        0.65422355264,
        0.65509973764,
        0.66273794364,
        0.65536857164,
        0.64187203364,
        0.63565542664,
        0.64282568864,
        0.76604441264,
        0.65509790964,
        0.63062207064
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.69989412084,
      "stddev": 0.011732062470449113,
      "median": 0.69855522564,
      "user": 0.4009644,
      "system": 1.3658663799999997,
      "min": 0.68541955564,
      "max": 0.71642182064,
      "times": [
        0.70268481364,
        0.70201895664,
        0.68556728264,
        0.69229917764,
        0.68541955564,
        0.71379111964,
        0.71394768164,
        0.69509149464,
        0.71642182064,
        0.69169930564
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.69974146124,
      "stddev": 0.02168164693433397,
      "median": 0.69286829764,
      "user": 0.3903176,
      "system": 1.3689033799999997,
      "min": 0.67778155564,
      "max": 0.75084331664,
      "times": [
        0.69240744264,
        0.68432593164,
        0.69332915264,
        0.69067030164,
        0.68889274364,
        0.69515606464,
        0.67778155564,
        0.72389763064,
        0.75084331664,
        0.70011047264
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.801 ± 0.047 4.705 4.864 1.52 ± 0.05
pacquet@main 4.733 ± 0.081 4.608 4.888 1.49 ± 0.05
pnpr@HEAD 3.167 ± 0.091 3.071 3.328 1.00
pnpr@main 3.185 ± 0.101 3.051 3.375 1.01 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.801176505160001,
      "stddev": 0.04725432539884123,
      "median": 4.79841706176,
      "user": 3.9461361999999993,
      "system": 3.4345996,
      "min": 4.70495262726,
      "max": 4.86354150026,
      "times": [
        4.8570143232600005,
        4.80811290226,
        4.768036797260001,
        4.80357623226,
        4.86354150026,
        4.793257891260001,
        4.84588165426,
        4.70495262726,
        4.78197537326,
        4.78541575026
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.732834627760001,
      "stddev": 0.08122971868161481,
      "median": 4.72699762576,
      "user": 3.8402000999999997,
      "system": 3.4028261,
      "min": 4.60776784026,
      "max": 4.88778257726,
      "times": [
        4.8143306822600005,
        4.7392893892600005,
        4.7695816112600005,
        4.88778257726,
        4.75676611326,
        4.70903804126,
        4.68581218826,
        4.60776784026,
        4.71470586226,
        4.64327197226
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.16730410166,
      "stddev": 0.09071014588023216,
      "median": 3.14610997876,
      "user": 2.8218775000000003,
      "system": 3.1866627000000003,
      "min": 3.07093945126,
      "max": 3.3277862392600004,
      "times": [
        3.10707142626,
        3.1546521852600002,
        3.3277862392600004,
        3.09425761626,
        3.1926016122600003,
        3.13756777226,
        3.3238597392600004,
        3.1584709652600003,
        3.07093945126,
        3.10583400926
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.18532927286,
      "stddev": 0.10071463262440829,
      "median": 3.16048453126,
      "user": 2.7807239999999998,
      "system": 3.2314445,
      "min": 3.05057352326,
      "max": 3.3752992812600002,
      "times": [
        3.1959195632600004,
        3.15145778726,
        3.16951127526,
        3.0807873692600003,
        3.2249382802600004,
        3.3752992812600002,
        3.05057352326,
        3.13523807526,
        3.32320060926,
        3.1463669642600003
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.393 ± 0.018 1.365 1.418 1.00
pacquet@main 1.398 ± 0.030 1.358 1.473 1.00 ± 0.03
pnpr@HEAD 1.484 ± 0.035 1.446 1.541 1.07 ± 0.03
pnpr@main 1.455 ± 0.024 1.426 1.493 1.04 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3930452995,
      "stddev": 0.018328139895722132,
      "median": 1.3886300608999997,
      "user": 1.4111784200000002,
      "system": 1.7063156,
      "min": 1.3651157539,
      "max": 1.4184499919,
      "times": [
        1.4184499919,
        1.4045827289,
        1.3831972658999998,
        1.3651157539,
        1.3809855769,
        1.3749411289,
        1.4183862298999999,
        1.3873157199,
        1.3899444018999998,
        1.4075341969
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3981862296999998,
      "stddev": 0.030246784526081795,
      "median": 1.3961752494,
      "user": 1.36316292,
      "system": 1.7192579,
      "min": 1.3578149068999998,
      "max": 1.4726746009,
      "times": [
        1.4126322769,
        1.4726746009,
        1.4008148869,
        1.3772229989,
        1.3913229859,
        1.3957550538999999,
        1.3965954449,
        1.3796328998999998,
        1.3578149068999998,
        1.3973962419
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4840953049999999,
      "stddev": 0.034789180080448706,
      "median": 1.4784571619,
      "user": 0.62321902,
      "system": 1.6045833999999999,
      "min": 1.4459380659,
      "max": 1.5406281519,
      "times": [
        1.4459380659,
        1.4963859029,
        1.5406281519,
        1.5317690608999999,
        1.4822290829,
        1.4479151958999998,
        1.4490447809,
        1.4746852409,
        1.4619038319,
        1.5104537359
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4551431318999999,
      "stddev": 0.024412108026384154,
      "median": 1.4446511824,
      "user": 0.60363802,
      "system": 1.557839,
      "min": 1.4257987039,
      "max": 1.4930645868999999,
      "times": [
        1.4427167549,
        1.4810594769,
        1.4930645868999999,
        1.4257987039,
        1.4461449619,
        1.4871724679,
        1.4627366848999999,
        1.4431574028999998,
        1.4419211069,
        1.4276591718999998
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.101 ± 0.018 3.075 3.136 2.16 ± 0.03
pacquet@main 3.045 ± 0.054 3.004 3.191 2.12 ± 0.05
pnpr@HEAD 1.433 ± 0.018 1.409 1.458 1.00
pnpr@main 1.443 ± 0.104 1.373 1.733 1.01 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.101308037,
      "stddev": 0.018328371918542866,
      "median": 3.1019604542999994,
      "user": 1.89712904,
      "system": 1.9882256200000004,
      "min": 3.0754341328,
      "max": 3.1364713928,
      "times": [
        3.1049246237999997,
        3.0989962847999997,
        3.0976378228,
        3.0804961438,
        3.1364713928,
        3.1171381348,
        3.1070257307999998,
        3.0754341328,
        3.1105124598,
        3.0844436438
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.0447614559000002,
      "stddev": 0.05354098209970025,
      "median": 3.0334787453,
      "user": 1.7904441400000004,
      "system": 1.99932182,
      "min": 3.0036404738,
      "max": 3.1912456417999997,
      "times": [
        3.0144397927999997,
        3.0117086767999997,
        3.0410920137999997,
        3.0036404738,
        3.0314896268,
        3.0354678637999997,
        3.0450661107999997,
        3.0259090318,
        3.1912456417999997,
        3.0475553268
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4330023079,
      "stddev": 0.018104949612331767,
      "median": 1.4303169088,
      "user": 0.6171531399999999,
      "system": 1.59200692,
      "min": 1.4087287258,
      "max": 1.4579037498,
      "times": [
        1.4579037498,
        1.4355599548000002,
        1.4222210988000001,
        1.4178763278000002,
        1.4150658228000002,
        1.4526517668,
        1.4374737728,
        1.4574679968000002,
        1.4087287258,
        1.4250738628000001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4431584527,
      "stddev": 0.10434334186466952,
      "median": 1.4138270563000002,
      "user": 0.5708500400000001,
      "system": 1.5847851199999998,
      "min": 1.3727355218000001,
      "max": 1.7333723438000002,
      "times": [
        1.4199808738000002,
        1.4595321568000001,
        1.7333723438000002,
        1.4053915288,
        1.4147020328000002,
        1.4129520798000001,
        1.3969961048000001,
        1.4189559778,
        1.3969659068,
        1.3727355218000001
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12696
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,801.18 ms
(+0.91%)Baseline: 4,757.77 ms
5,709.33 ms
(84.09%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,101.31 ms
(+1.75%)Baseline: 3,047.87 ms
3,657.44 ms
(84.79%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,393.05 ms
(+2.84%)Baseline: 1,354.63 ms
1,625.56 ms
(85.70%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,940.20 ms
(+1.91%)Baseline: 4,847.67 ms
5,817.21 ms
(84.92%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
650.53 ms
(-0.01%)Baseline: 650.59 ms
780.71 ms
(83.33%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12696
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,167.30 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,433.00 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,484.10 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,960.52 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
699.89 ms
🐰 View full continuous benchmarking report in Bencher

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jun 27, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2cd4181

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 2cd4181

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 20111b9

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 20111b9

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 452eb3f

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 452eb3f

zkochan added 6 commits June 27, 2026 18:05
Port pnpm's `with` command to pacquet.

`pnpm with <version> <args...>` resolves the spec through the trusted
package-manager bootstrap registry, installs that pnpm engine into the
global virtual store (matching pnpm's installPnpmToStore — shared across
invocations and, unlike self-update, not registered in the global
packages directory), and spawns it with the remaining args and the
child's packageManager check disabled.

`pnpm with current <args...>` is rewritten before clap parses argv into a
direct in-process dispatch of `<args>`, forcing pmOnFail to ignore via
the pnpm_config_pm_on_fail env var.

Wire the pmOnFail setting into Config and the env overlay so the override
is honored once the packageManager check is ported. Reuse the self-update
engine installer (now global-virtual-store aware) and the engine-identity
verifier rather than duplicating them.

The end-to-end `with <version>` download path has no automated test
because the mock registry does not serve the pnpm / `@pnpm/exe` engine
packages, the same limitation self-update has.
Satisfy the dylint perfectionist::macro-trailing-comma lint enforced by
the pre-push hook.
Before recursively removing the throwaway install directory used by
`pnpm with`, refuse to recurse through a symlink at the temp path,
mirroring the guard patch-commit already applies. The store is within
pnpm's trust domain, so this is defense-in-depth rather than a fix for an
in-scope threat. Adds a single lstat on the install (cache-miss) path
only.
spawn_pnpm resolved `pnpm` against the full prepended PATH, so a missing
or broken shim in the engine's bin directory could fall through to a
different `pnpm` on PATH and run the wrong engine. Resolve strictly within
the engine's bin directory instead, matching pnpm's `with`, which spawns
the explicit `path.join(binDir, 'pnpm')`. which_in is still used so the
platform-correct shim name (e.g. pnpm.cmd on Windows) is picked.
The with-current argv rewrite scanned the whole argv and stripped the
first `with current` pair anywhere, so `pnpm exec with current ...` (where
the tokens are data for another command) would be wrongly rewritten and
incorrectly force pmOnFail=ignore. Anchor the match to the top-level
subcommand position by skipping global options (and the values they
consume), mirroring pnpm, which only enters the rewrite when the parsed
command is `with` with first param `current`.
spawn_pnpm prepended the engine's store-resident bin directory to PATH
without rejecting a path-delimiter character in it, so a bin dir
containing ':' (or ';' on Windows) would silently split into multiple
PATH entries. Guard it with an explicit ERR_PNPM_BAD_PATH_DIR error,
mirroring the guard exec's prepend_dirs_to_path already applies. The store
is within pnpm's trust domain, so this is defense-in-depth aligned with
the existing exec precedent.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@zkochan
zkochan merged commit c00400d into main Jun 27, 2026
29 checks passed
@zkochan
zkochan deleted the with branch June 27, 2026 16:17
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants