Skip to content

feat(pacquet-cli): port the setup command - #12697

Merged
zkochan merged 5 commits into
mainfrom
feat/pacquet-setup-command
Jun 27, 2026
Merged

zkochan merged 5 commits into
mainfrom
feat/pacquet-setup-command

Conversation

@zkochan

@zkochan zkochan commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Ports pnpm's setup command to the pacquet (Rust) CLI, making pnpm
available for global use. It mirrors pnpm11/engine/pm/commands/src/setup/setup.ts
and the @pnpm/os.env.path-extender package family that command depends on.

What pacquet setup does, matching pnpm:

  • Installs the CLI into the global packages directory by spawning
    <exe> add -g --ignore-scripts file:<execDir> (writing a temporary
    @pnpm/exe package.json when none exists, then removing it).
  • Writes the pn / pnpx / pnx alias scripts into $PNPM_HOME/bin
    (POSIX sh scripts everywhere, plus .cmd / .ps1 on Windows).
  • Persists PNPM_HOME and $PNPM_HOME/bin into the user's environment:
    the current shell's rc file on POSIX (bash/zsh/ksh/dash/sh/fish/nushell),
    or the registry (reg / chcp / setx) on Windows.

Implementation notes:

  • The path-extender is inlined as a private module under the command. The
    shell rc-block create/append/skip/modify logic and the Windows reg query
    line parsing use plain string operations rather than adding a regex
    dependency.
  • Error codes mirror pnpm's PnpmError codes (ERR_PNPM_BAD_SHELL_SECTION,
    ERR_PNPM_BAD_ENV_FOUND, ERR_PNPM_UNKNOWN_SHELL, …), including the
    --force hints.
  • Unit tests port the upstream path-extender-posix spec cases and cover the
    Windows registry parser/renderer and the output rendering (26 tests).

No standalone end-to-end test for the full command: the flow always
self-installs via add -g file:<execDir>, which on a dev build points at the
build output directory — too heavy/side-effecting for a spawned-binary test.
This matches upstream, whose setup tests also skip the single-executable
branch. The Windows registry path is selected at runtime via cfg!(windows)
(so it compiles on all targets) but is only fully exercisable on Windows.

Squash Commit Body

Port pnpm's `setup` command to pacquet, making `pnpm` available for global
use. Mirrors pnpm11/engine/pm/commands/src/setup/setup.ts and the
`@pnpm/os.env.path-extender` package family it depends on.

The command installs the CLI into the global packages directory (spawning
`<exe> add -g --ignore-scripts file:<execDir>` with a temporary `@pnpm/exe`
package.json, as pnpm does), writes the `pn` / `pnpx` / `pnx` alias scripts
into `$PNPM_HOME/bin`, and persists `PNPM_HOME` plus `$PNPM_HOME/bin` into
the user's environment — the current shell's rc file on POSIX
(bash/zsh/ksh/dash/sh/fish/nushell) or the registry on Windows.

The path-extender is inlined as a private module under the command. The
shell rc-block editing and the Windows `reg query` parsing use plain string
operations rather than a regex dependency. Error codes mirror pnpm's
PnpmError codes, including the `--force` hints.

Unit tests port the upstream path-extender-posix spec cases and cover the
Windows registry parser/renderer and the output rendering.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting.
    (TypeScript setup already exists; this is the pacquet-side port. pnpm is
    the source of truth.)
  • Added or updated tests.

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

Summary by CodeRabbit

  • New Features

    • Added a new setup command to configure the CLI for global use.
    • Installs pnpm globally and generates pn, pnx, and pnpx launcher scripts (with Windows equivalents).
    • Updates your shell PATH persistently, using shell rc/config blocks on Unix and the Windows user environment registry on Windows.
    • Includes clear install status output and a --force/-f option to overwrite existing configuration.
  • Bug Fixes

    • Improves safety by validating PNPM_HOME, preventing duplicate PATH entries, and escaping proxy values to avoid unintended shell expansion.

Port pnpm's `setup` command to pacquet, making `pnpm` available for global
use. Mirrors pnpm11/engine/pm/commands/src/setup/setup.ts and the
`@pnpm/os.env.path-extender` package family it depends on.

The command installs the CLI into the global packages directory (spawning
`<exe> add -g --ignore-scripts file:<execDir>` with a temporary `@pnpm/exe`
package.json, as pnpm does), writes the `pn` / `pnpx` / `pnx` alias scripts
into `$PNPM_HOME/bin`, and persists `PNPM_HOME` plus `$PNPM_HOME/bin` into
the user's environment — the current shell's rc file on POSIX
(bash/zsh/ksh/dash/sh/fish/nushell) or the registry on Windows.

The path-extender is inlined as a private module under the command. The
shell rc-block create/append/skip/modify logic and the Windows `reg query`
line parsing use plain string operations rather than a regex dependency.
Error codes mirror pnpm's PnpmError codes (ERR_PNPM_BAD_SHELL_SECTION,
ERR_PNPM_BAD_ENV_FOUND, ...), including the `--force` hints.

Unit tests port the upstream path-extender-posix spec cases and cover the
Windows registry parser/renderer and the output rendering.
@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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5b238414-b315-42a5-b456-278930b47ca9

📥 Commits

Reviewing files that changed from the base of the PR and between 78bc072 and 8fe181e.

📒 Files selected for processing (4)
  • pacquet/crates/cli/src/cli_args/setup.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • pacquet/crates/cli/src/cli_args/setup.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender.rs

📝 Walkthrough

Walkthrough

Adds a new pacquet setup command, wires it into CLI dispatch, installs pnpm from the current executable, writes alias wrappers, and updates shell or Windows registry PATH configuration through platform-specific path-extender code. Unit tests cover output rendering and config edits.

Changes

pacquet setup flow

Layer / File(s) Summary
CLI wiring
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
Adds the setup module, CliCommand::Setup, and routing from the command dispatcher into dispatch_query::setup.
Path extender contract
pacquet/crates/cli/src/cli_args/setup/path_extender.rs
Defines shared path-extender types, validation, platform dispatch, and Windows report formatting.
Setup execution
pacquet/crates/cli/src/cli_args/setup.rs, pacquet/crates/cli/src/cli_args/setup/tests.rs
Implements SetupArgs, pnpm installation, alias script generation, setup output rendering, and the setup-facing tests.
POSIX path extender
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs, pacquet/crates/cli/src/cli_args/setup/path_extender/posix/tests.rs
Implements shell detection, shell config updates, POSIX renderers, and the associated POSIX tests.
Windows path extender
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs, pacquet/crates/cli/src/cli_args/setup/path_extender/windows/tests.rs
Implements registry-based PATH updates, code-page handling, registry parsing, and the Windows tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • pnpm/pnpm#12402: Both PRs update the global pnpm setup/CLI self-install flow to invoke pnpm add -g --ignore-scripts file:<execDir>, so the changes align at the same install command level.
  • pnpm/pnpm#12690: The retrieved refactor reshapes the CLI module structure and the dispatch/dispatch_query routing layer, and this PR extends that same routing by adding a new CliCommand::Setup arm and corresponding handler.

Suggested labels

product: pacquet

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/pacquet-setup-command

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

Port pnpm setup command to pacquet CLI (global install + PATH/PNPM_HOME)
✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

Description

• Add pacquet setup to install pnpm globally and create pn/pnpx/pnx wrappers.
• Persist PNPM_HOME and PATH updates via POSIX shell rc edits or Windows registry changes.
• Add unit coverage for rc-block editing, Windows reg query parsing, and output rendering.
Diagram

graph TD
  A["CLI: Setup command"] --> B["setup.rs handler"] --> C["Global self-install"] --> D["Alias scripts"] --> E["Path extender"]
  E --> F["POSIX rc file"]
  E --> G["Windows registry"]
  B --> H["Reporter logs"]

  subgraph Legend
    direction LR
    _cmd(["CLI cmd"]) ~~~ _mod["Rust module"] ~~~ _os[("OS persistence")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Extract `path_extender` into a reusable crate/module
  • ➕ Enables reuse by future commands needing persistent env edits
  • ➕ Keeps setup.rs smaller and improves separation of concerns
  • ➖ Premature abstraction if no other commands need it
  • ➖ May complicate visibility/error-type boundaries across crates
2. Use a regex-based parser for Windows `reg query` output
  • ➕ More flexible parsing if reg formatting differs across locales/versions
  • ➕ Potentially simpler to read/maintain for complex patterns
  • ➖ Adds a new dependency and compile-time surface area
  • ➖ Current fixed-column parsing matches pnpm behavior and is already tested
3. Avoid self-install by directly writing/relocating the binary into PNPM_HOME
  • ➕ Eliminates spawning add -g and temporary package.json handling
  • ➕ Reduces reliance on global package installation semantics
  • ➖ Would diverge from pnpm’s established setup behavior and layout
  • ➖ Higher risk of breaking expectations around global store metadata and upgrades

Recommendation: Keep the current approach: mirroring pnpm’s setup flow (including add -g file: and the rc/registry persistence rules) minimizes behavioral drift and makes upstream parity easier to validate. The inlined path-extender is reasonable for now given the tight coupling to setup, the desire to avoid extra dependencies, and the added unit coverage for the tricky string-parsing/editing logic.

Files changed (11) +1278 / -0

Enhancement (8) +921 / -0
cli_args.rsExport new 'setup' command module +1/-0

Export new 'setup' command module

• Adds 'pub mod setup;' to register the new command module in the CLI args tree.

pacquet/crates/cli/src/cli_args.rs

cli_command.rsAdd 'Setup' subcommand to CLI command enum +3/-0

Add 'Setup' subcommand to CLI command enum

• Imports 'SetupArgs' and adds a 'Setup(SetupArgs)' variant with user-facing help text.

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

dispatch.rsRoute 'setup' command to query dispatcher +1/-0

Route 'setup' command to query dispatcher

• Extends the top-level command router to dispatch 'CliCommand::Setup' via 'dispatch_query::setup'.

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

dispatch_query.rsAdd reporter-aware 'setup' dispatcher +21/-0

Add reporter-aware 'setup' dispatcher

• Introduces a new 'setup' dispatch function that selects the reporter type and runs 'SetupArgs::run' without requiring project config/lockfile.

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

setup.rsImplement 'pacquet setup' (global install, wrappers, env persistence) +212/-0

Implement 'pacquet setup' (global install, wrappers, env persistence)

• Implements the setup command: determines 'PNPM_HOME', self-installs globally via 'add -g --ignore-scripts file:<execDir>' (creating/removing a temporary 'package.json' when needed), writes alias scripts into '$PNPM_HOME/bin', invokes the inlined path-extender, and renders a pnpm-compatible summary output.

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

path_extender.rsAdd cross-platform path-extender facade and shared types +186/-0

Add cross-platform path-extender facade and shared types

• Adds shared option/report types and a pnpm-aligned error enum, dispatching at runtime to POSIX rc editing or Windows registry editing and normalizing Windows changes into the common report format.

pacquet/crates/cli/src/cli_args/setup/path_extender.rs

posix.rsImplement POSIX shell rc-file editing for PATH/PNPM_HOME +282/-0

Implement POSIX shell rc-file editing for PATH/PNPM_HOME

• Detects the current shell, renders shell-specific settings blocks (sh-family, fish, nushell), and creates/appends/replaces a '# <section>' block in the appropriate rc file, honoring '--force' overwrite semantics.

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs

windows.rsImplement Windows registry PATH/PNPM_HOME updates +215/-0

Implement Windows registry PATH/PNPM_HOME updates

• Implements reading 'HKEY_CURRENT_USER\Environment' via 'reg query', updating values via 'reg add', refreshing via 'setx', and handling code page changes ('chcp') to preserve UTF-8 output; includes a tested string-based parser for 'reg' output lines.

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs

Tests (3) +357 / -0
tests.rsPort pnpm path-extender POSIX spec tests +232/-0

Port pnpm path-extender POSIX spec tests

• Adds unit tests covering POSIX/fish/nushell renderer output and rc-block create/append/skip/replace behavior, including erroring when overwrite is disabled.

pacquet/crates/cli/src/cli_args/setup/path_extender/posix/tests.rs

tests.rsAdd unit tests for Windows registry parsing and report rendering +51/-0

Add unit tests for Windows registry parsing and report rendering

• Tests 'reg query' line parsing (case-insensitive name match), code-page number extraction, and the normalized before/after report rendering for Windows changes.

pacquet/crates/cli/src/cli_args/setup/path_extender/windows/tests.rs

tests.rsAdd unit tests for setup output and alias script creation +74/-0

Add unit tests for setup output and alias script creation

• Tests setup summary rendering for no-op/created-file/Windows flows and verifies alias scripts are written correctly (and executable on Unix).

pacquet/crates/cli/src/cli_args/setup/tests.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) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. PNPM_HOME validated too late ✓ Resolved 🐞 Bug ⛨ Security
Description
setup::handler() spawns the self-install and writes alias scripts before add_dir_to_env_path()
validates PNPM_HOME, so an unsafe/attacker-influenced PNPM_HOME can affect the environment of
the install subprocess and can leave partial side effects even if setup later fails validation. This
is especially risky because pacquet’s install pipeline can spawn external tools (e.g. node) by
name, making it important that PATH isn’t constructed from unvalidated input.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R42-69]

+fn handler<Reporter: self::Reporter + 'static>(force: bool, dir: &Path) -> miette::Result<String> {
+    let pnpm_home_dir = default_pnpm_home_dir::<Host>().ok_or_else(|| {
+        miette::miette!(
+            "Could not determine the pnpm home directory. Set the PNPM_HOME environment variable."
+        )
+    })?;
+    let bin_dir = pnpm_home_dir.join("bin");
+
+    let exec_path = std::env::current_exe()
+        .into_diagnostic()
+        .wrap_err("determine the path to the pnpm executable")?;
+    // pacquet is always a native executable (never a `.js` entrypoint), so
+    // pnpm's single-executable branch always applies: install the CLI
+    // globally and write the alias scripts.
+    install_cli_globally::<Reporter>(&exec_path, &pnpm_home_dir, dir)?;
+    create_alias_scripts(&bin_dir).into_diagnostic().wrap_err("create the pnpm alias scripts")?;
+
+    let report = path_extender::add_dir_to_env_path(
+        &pnpm_home_dir,
+        &AddDirToEnvPathOpts {
+            config_section_name: "pnpm",
+            proxy_var_name: Some("PNPM_HOME"),
+            proxy_var_sub_dir: Some("bin"),
+            overwrite: force,
+            position: AddingPosition::Start,
+        },
+    )?;
+    Ok(render_setup_output(&report))
Evidence
handler() uses pnpm_home_dir for self-install and filesystem writes before invoking the
path-extender, but default_pnpm_home_dir() sources pnpm_home_dir directly from the PNPM_HOME
env var. Separately, the install pipeline can spawn node by name (PATH resolution), so
constructing the self-install subprocess PATH from an unvalidated PNPM_HOME is unsafe and can
also lead to partial side effects even if the later validation fails.

pacquet/crates/cli/src/cli_args/setup.rs[42-69]
pacquet/crates/config/src/defaults.rs[124-152]
pacquet/crates/graph-hasher/src/engine_name.rs[41-70]
pacquet/crates/package-manager/src/install_frozen_lockfile.rs[861-884]

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 setup` performs side effects (global self-install + alias script writes) before it runs the path-extender validation logic that rejects unsafe `PNPM_HOME` values. This allows unsafe env input to influence the install subprocess environment and can leave partial state even if setup ultimately errors.
## Issue Context
- `default_pnpm_home_dir()` accepts `PNPM_HOME` verbatim.
- `handler()` uses `pnpm_home_dir` immediately to:
- build a `PATH` passed to the self-install subprocess,
- write `$PNPM_HOME/bin` alias scripts,
before calling `path_extender::add_dir_to_env_path()` (which performs the unsafe-character checks).
- The install pipeline can spawn external tools like `node` via `Command::new("node")`, which is resolved via `PATH`, so it’s important that the self-install subprocess does not inherit a `PATH` influenced by an unsafe `PNPM_HOME`.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[42-69]
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[19-35]
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[48-80]
### Concrete fix direction
- Extract a shared, pure validation helper in `path_extender` (e.g. `validate_pnpm_home_dir(dir, opts)`), reusing the exact unsafe-character rules already implemented in the POSIX/Windows implementations.
- Call this validation at the start of `handler()` (before `install_cli_globally()` / `create_alias_scripts()`).
- Keep the existing validation in the platform implementations as defense-in-depth (or refactor them to call the shared helper).

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


2. POSIX PATH colon injection ✓ Resolved 🐞 Bug ⛨ Security
Description
On POSIX, default_pnpm_home_dir() accepts PNPM_HOME from the environment verbatim and the rc
snippet later builds a colon-delimited PATH entry from $PNPM_HOME, so a value containing :
persistently injects extra PATH entries (e.g. PNPM_HOME=/tmp/pnpm:/tmp/evil adds /tmp/evil/bin).
This creates a durable PATH-poisoning vector activated whenever the user’s shell sources the
modified rc file.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[R86-116]

+fn render_posix_settings(dir: &str, opts: &AddDirToEnvPathOpts) -> String {
+    if let Some(proxy) = opts.proxy_var_name {
+        let path_ref = match opts.proxy_var_sub_dir {
+            Some(sub_dir) => format!("${proxy}/{sub_dir}"),
+            None => format!("${proxy}"),
+        };
+        format!(
+            "export {proxy}={value}\ncase \":$PATH:\" in\n  *\":{path_ref}:\"*) ;;\n  *) export PATH=\"{path_value}\" ;;\nesac",
+            value = sh_quote(dir),
+            path_value = create_path_value(opts.position, &path_ref),
+        )
+    } else {
+        let quoted = sh_quote(dir);
+        format!(
+            "case \":$PATH:\" in\n  *\":\"{quoted}\":\"*) ;;\n  *) export PATH={path_value} ;;\nesac",
+            path_value = create_path_value(opts.position, &quoted),
+        )
+    }
+}
+
+/// Wrap `value` in single quotes, escaping any embedded single quote as
+/// `'\''`, so the POSIX shell treats it as a literal with no expansion.
+fn sh_quote(value: &str) -> String {
+    format!("'{}'", value.replace('\'', r"'\''"))
+}
+
+fn create_path_value(position: AddingPosition, dir: &str) -> String {
+    match position {
+        AddingPosition::Start => format!("{dir}:$PATH"),
+        AddingPosition::End => format!("$PATH:{dir}"),
+    }
Evidence
The pnpm home directory can be fully controlled via the PNPM_HOME environment variable, and the
POSIX setup snippet uses $PNPM_HOME to build a colon-delimited PATH string; colons inside
PNPM_HOME therefore become PATH separators when the rc file is sourced. The repo’s review guide
explicitly requires treating env vars and paths as attacker-controlled and calls out PATH poisoning
risk.

pacquet/crates/config/src/defaults.rs[124-151]
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[86-116]
REVIEW_GUIDE.md[30-60]

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 POSIX, `pacquet setup` persists `PNPM_HOME` and then uses it to construct a `PATH` entry. If `PNPM_HOME` contains the POSIX path separator `:` (or newline characters), sourcing the generated rc block can add unintended extra PATH entries, creating a persistent PATH-poisoning vector.
### Issue Context
`default_pnpm_home_dir()` allows `PNPM_HOME` to come directly from the process environment, which REVIEW_GUIDE.md treats as attacker-controlled input.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender.rs[154-178]
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[86-116]
- pacquet/crates/config/src/defaults.rs[134-151]
### Recommended fix
- Add POSIX validation for `dir` (the pnpm home dir) before rendering/writing shell config:
- reject values containing `:` (PATH separator) and `\n`/`\r`.
- consider also rejecting NUL.
- Return a structured `PathExtenderError` (new variant or generalized from the Windows-specific one) explaining the unsafe character and how to fix (unset/repair `PNPM_HOME`).
- Keep behavior parity in `setup` by applying validation only where the value is persisted/used to build PATH.

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


3. Symlinkable rc temp file 🐞 Bug ⛨ Security
Description
The POSIX rc-file writer uses a predictable sibling temp filename (.pnpm-tmp) and File::create,
which follows symlinks, so an attacker who can write in the rc file’s directory can redirect the
temp write to an arbitrary victim-writable file. This enables local arbitrary file overwrite during
pacquet setup (especially if the rc path is under a shared/writable directory).
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[R278-296]

+fn write_atomic(path: &Path, content: &str) -> std::io::Result<()> {
+    use std::io::Write;
+    let file_name = path.file_name().ok_or_else(|| {
+        std::io::Error::new(std::io::ErrorKind::InvalidInput, "config path has no file name")
+    })?;
+    let mut temp_name = file_name.to_os_string();
+    temp_name.push(".pnpm-tmp");
+    let temp_path = path.with_file_name(temp_name);
+    let mut file = fs::File::create(&temp_path)?;
+    let write_result = file.write_all(content.as_bytes()).and_then(|()| file.sync_all());
+    if let Err(err) = write_result {
+        let _ = fs::remove_file(&temp_path);
+        return Err(err);
+    }
+    if let Err(err) = fs::rename(&temp_path, path) {
+        let _ = fs::remove_file(&temp_path);
+        return Err(err);
+    }
+    Ok(())
Evidence
write_atomic() currently chooses a deterministic temp name and uses File::create, which can
follow symlinks. Elsewhere in this repo, atomic writers explicitly use unique temp names and
create_new(true) to avoid symlink/truncation attacks; this demonstrates the expected hardening
standard for atomic writes in this codebase.

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[275-296]
pacquet/crates/fs/src/ensure_file.rs[355-368]
pacquet/crates/lockfile/src/save_lockfile.rs[146-155]

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

## Issue description
`write_atomic()` writes to a predictable temp path and opens it with `File::create`, which will follow a pre-existing symlink. This can be exploited to overwrite unintended files if the directory is attacker-writable.
### Issue Context
The repository already has hardened atomic writers that:
- use unique temp names, and
- open temp files with `create_new(true)` to avoid following symlinks/truncating attacker-preseeded paths.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[275-297]
- pacquet/crates/fs/src/ensure_file.rs[355-435]
- pacquet/crates/lockfile/src/save_lockfile.rs[146-205]
### Recommended fix
- Replace the current predictable `.<name>.pnpm-tmp` scheme with a unique temp name in the same directory (e.g. `.<name>.<pid>.<counter>.pnpm-tmp`).
- Open temp files with `OpenOptions::new().write(true).create_new(true)` and retry on `AlreadyExists` (pattern already used elsewhere in this repo).
- Keep the existing `sync_all` + `rename` semantics.
- Best-effort remove the temp file on any error path.

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


View more (3)
4. Windows tool path hijack 🐞 Bug ⛨ Security
Description
The Windows path-extender executes chcp, reg, and setx using bare program names, so Windows
executable search order (including current directory) can resolve to an attacker-provided
reg.exe/setx.exe when pacquet setup is run from an untrusted repo/dir. This enables arbitrary
code execution during setup.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[R186-188]

+    let output = Command::new("reg")
+        .args(["add", REG_KEY, "/v", env_var_name, "/t", reg_type, "/d", env_var_value, "/f"])
+        .output()?;
Evidence
The Windows path-extender spawns external commands (reg, setx, and chcp) via
Command::new(...) with bare names, which are resolved via Windows search semantics rather than a
fixed system path.

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[31-35]
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[186-188]
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[202-206]

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 Windows, the implementation spawns system tools (`reg`, `setx`, `chcp`) by unqualified name. Windows searches the application directory and current working directory before system locations in common cases, so a malicious `reg.exe`/`setx.exe` in the working directory can be executed when the user runs `pacquet setup`.
### Issue Context
This code runs in a command that users may invoke inside repositories (including untrusted ones). Executing an attacker-controlled binary here is a high-impact local RCE.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[25-45]
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[180-211]
### Implementation notes
- Resolve tool paths to known system locations (e.g. `${SystemRoot}\\System32\\reg.exe`, `${SystemRoot}\\System32\\setx.exe`).
- For `chcp`, consider invoking `%SystemRoot%\\System32\\cmd.exe /C chcp ...` (since `chcp` is typically a shell builtin) or use the `.com` in System32 if appropriate.
- Fail if `SystemRoot`/tool path cannot be resolved, rather than falling back to search-path execution.

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


5. Rc file command injection ✓ Resolved 🐞 Bug ⛨ Security
Description
The POSIX rc-block renderers interpolate pnpm_home_dir directly into double-quoted shell code
(bash/zsh/sh, fish, nushell), so attacker-controlled values from PNPM_HOME/XDG_DATA_HOME can
trigger command substitution (e.g. $(...)) when the rc file is sourced. This enables arbitrary
command execution on the user’s next shell startup after running pacquet setup.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[R81-96]

+fn render_posix_settings(dir: &str, opts: &AddDirToEnvPathOpts) -> String {
+    if let Some(proxy) = opts.proxy_var_name {
+        let path_ref = match opts.proxy_var_sub_dir {
+            Some(sub_dir) => format!("${proxy}/{sub_dir}"),
+            None => format!("${proxy}"),
+        };
+        format!(
+            "export {proxy}=\"{dir}\"\ncase \":$PATH:\" in\n  *\":{path_ref}:\"*) ;;\n  *) export PATH=\"{path_value}\" ;;\nesac",
+            path_value = create_path_value(opts.position, &path_ref),
+        )
+    } else {
+        format!(
+            "case \":$PATH:\" in\n  *\":{dir}:\"*) ;;\n  *) export PATH=\"{path_value}\" ;;\nesac",
+            path_value = create_path_value(opts.position, dir),
+        )
+    }
Evidence
pnpm_home_dir is derived from environment variables without sanitization, and the POSIX
path-extender writes it into double-quoted shell code, where command substitution and $ expansions
are still evaluated when sourced.

pacquet/crates/config/src/defaults.rs[134-151]
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[63-202]

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 setup` writes a shell rc block that contains `export PNPM_HOME="{dir}"` (and similar for fish/nu). Because `dir` can come from environment variables (`PNPM_HOME`, `XDG_DATA_HOME`) and is inserted into *executable* shell code without escaping, values containing `$()`, backticks, `$VAR`, quotes, or newlines can cause command execution when the rc file is sourced.
### Issue Context
- `default_pnpm_home_dir` prefers `PNPM_HOME` / `XDG_DATA_HOME` (env-controlled) when present.
- The rendered rc block is executed by the user’s shell on startup or via `source`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[81-201]
- pacquet/crates/cli/src/cli_args/setup.rs[42-70]
- pacquet/crates/config/src/defaults.rs[134-151]
### Suggested fix approach
- For sh-family shells: render `PNPM_HOME` using **single-quote escaping** (e.g. `export PNPM_HOME='...escaped...'`) so `$()`/backticks/`$VAR` are not expanded.
- For fish and nushell: render string literals in a form that does not perform interpolation/expansion (prefer single-quoted literals if supported, with correct escaping).
- Additionally, validate/reject `pnpm_home_dir` strings containing `\n`/`\r` (and potentially other characters that cannot be safely represented for a given shell) with a clear error code.

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


6. Windows PATH poisoning via PNPM_HOME ✓ Resolved 🐞 Bug ⛨ Security
Description
On Windows, setup persists PNPM_HOME then adds %PNPM_HOME%\bin to the user Path; if
PNPM_HOME contains a semicolon, expansion splits into multiple PATH entries and can persistently
prepend attacker-chosen directories. Because PNPM_HOME can be env-controlled, this is a durable
PATH-injection vector after running pacquet setup.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[R50-68]

+    let added_dir = dir.to_string_lossy().replace('/', r"\");
+    let registry_output = get_registry_output()?;
+    let mut changes = Vec::new();
+    if let Some(proxy) = opts.proxy_var_name {
+        changes.push(update_env_variable(
+            &registry_output,
+            proxy,
+            &added_dir,
+            false,
+            opts.overwrite,
+        )?);
+        let path_entry = match opts.proxy_var_sub_dir {
+            Some(sub_dir) => format!("%{proxy}%\\{sub_dir}"),
+            None => format!("%{proxy}%"),
+        };
+        changes.push(add_to_path(&registry_output, &path_entry, opts.position)?);
+    } else {
+        changes.push(add_to_path(&registry_output, &added_dir, opts.position)?);
+    }
Evidence
The pnpm home directory can come directly from PNPM_HOME, and the Windows path extender persists
that value then constructs Path entries using %PNPM_HOME%, which is sensitive to ; splitting.

pacquet/crates/config/src/defaults.rs[134-151]
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[46-68]

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

## Issue description
`add_dir_to_windows_env_path_inner` stores `PNPM_HOME` and then prepends `%PNPM_HOME%\\bin` to `Path` (REG_EXPAND_SZ). If the stored `PNPM_HOME` value contains `;`, `%PNPM_HOME%` expansion yields multiple path segments, effectively allowing persistent PATH injection.
### Issue Context
`PNPM_HOME` can originate from the process environment via `default_pnpm_home_dir`, so it must be treated as attacker-controlled per the repo security rules.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[46-69]
- pacquet/crates/cli/src/cli_args/setup/path_extender.rs[143-164]
- pacquet/crates/config/src/defaults.rs[134-151]
### Suggested fix approach
- Before writing `PNPM_HOME` / using `%PNPM_HOME%` indirection, validate that the resolved path string does not contain `;`, `\n`, `\r` (and consider also rejecting `%` to avoid surprising nested expansions).
- If validation fails, return a dedicated error (new `PathExtenderError` variant/code) explaining that `PNPM_HOME` contains invalid characters for Windows PATH persistence.
- Alternative safe fallback: if `PNPM_HOME` is “unsafe for proxy expansion”, skip the proxy variable and add the *literal* `...\\bin` directory to Path instead.

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



Remediation recommended

7. Registry parser slice panic 🐞 Bug ☼ Reliability
Description
get_env_value_from_registry() slices rest[..env_var_name.len()] / rest[env_var_name.len()..]
on a &str; if env_var_name.len() is not a UTF-8 char boundary in rest (e.g., registry contains
a non-ASCII env var name with multi-byte chars before that offset), this will panic and crash
pacquet setup on Windows.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[R164-176]

+fn get_env_value_from_registry(registry_output: &str, env_var_name: &str) -> Option<String> {
+    for line in registry_output.lines() {
+        let Some(rest) = line.strip_prefix("    ") else {
+            continue;
+        };
+        if rest.len() < env_var_name.len()
+            || !rest[..env_var_name.len()].eq_ignore_ascii_case(env_var_name)
+        {
+            continue;
+        }
+        let Some(after_name) = rest[env_var_name.len()..].strip_prefix("    ") else {
+            continue;
+        };
Evidence
The parser slices rest using env_var_name.len() as a byte offset; on &str this panics if the
offset is not a UTF-8 character boundary, which can occur with non-ASCII registry value names/output
lines.

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[164-176]

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

## Issue description
`get_env_value_from_registry()` indexes a Rust `&str` using byte offsets derived from `env_var_name.len()`. If that offset is not on a UTF-8 character boundary in the registry output line, Rust will panic at runtime, crashing `pacquet setup`.
### Issue Context
This function iterates every line of `reg query` output and performs `rest[..env_var_name.len()]` and `rest[env_var_name.len()..]` before it has guaranteed the boundary is valid.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[164-176]
### Suggested fix
Replace direct slicing with boundary-checked access:
- Use `rest.get(..env_var_name.len())` / `rest.get(env_var_name.len()..)` and `continue` when `None`.
- Or refactor to delimiter-based parsing (e.g., split once on the 4-space separator into `name` + remainder), avoiding manual byte offsets entirely.

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


8. Misleading registry env error 🐞 Bug ⚙ Maintainability
Description
PathExtenderError::BadEnvFound claims to show the current env var value but is constructed with
the desired value, so users can’t see what the registry actually contains when --force is
required. FailedSetEnv’s display string also has a stray trailing quote, making registry-write
failures harder to interpret.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender.rs[R117-142]

+    #[display("Currently '{env_name}' is set to '{wanted_value}'")]
+    #[diagnostic(
+        code(ERR_PNPM_BAD_ENV_FOUND),
+        help("If you want to override the existing env variable, use the --force option")
+    )]
+    BadEnvFound { env_name: String, wanted_value: String },
+
+    #[display("exec chcp failed: {message}")]
+    #[diagnostic(code(ERR_PNPM_CHCP))]
+    Chcp { message: String },
+
+    #[display("`{command}` failed: {stderr}")]
+    #[diagnostic(code(ERR_PNPM_SETUP_COMMAND_FAILED))]
+    CommandFailed { command: String, stderr: String },
+
+    #[display("win32 registry environment values could not be retrieved")]
+    #[diagnostic(code(ERR_PNPM_REG_READ))]
+    RegRead,
+
+    #[display(r#""Path" environment variable is not found in the registry"#)]
+    #[diagnostic(code(ERR_PNPM_NO_PATH))]
+    NoPath,
+
+    #[display(r#"Failed to set "{env_name}" to "{value}": {stderr}"#)]
+    #[diagnostic(code(ERR_PNPM_FAILED_SET_ENV))]
+    FailedSetEnv { env_name: String, value: String, stderr: String },
Evidence
BadEnvFound is defined to print wanted_value as if it were the current value, but on Windows it
is constructed specifically when the *current* registry value differs from the desired value, and
the variant does not carry current at all. FailedSetEnv’s display macro contains an extra
trailing quote character in the format string.

pacquet/crates/cli/src/cli_args/setup/path_extender.rs[117-142]
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[77-106]

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

## Issue description
Two user-facing diagnostics in the new `setup/path_extender` port are misleading:
1) `BadEnvFound`’s display says it’s showing the *current* value, but the variant only carries `wanted_value`, and the Windows implementation populates it with the desired value when the current registry value differs.
2) `FailedSetEnv`’s display string includes an extra trailing `"`, which degrades the error message when registry writes fail.
### Issue Context
This triggers specifically when a user already has e.g. `PNPM_HOME` set in the registry to a different value and runs `pacquet setup` without `--force`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender.rs[117-142]
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[77-106]
### Suggested fix approach
- Change `BadEnvFound` to include the actual `current_value` (and optionally also the `wanted_value`), and update its `#[display(...)]` to print the real current value (and ideally the wanted value too).
- Update `windows::update_env_variable()` to pass the `current` value into the error variant.
- Remove the stray trailing quote from `FailedSetEnv`’s `#[display(...)]` string.
- If there are unit tests around error strings (or if adding one is easy), add coverage for both formatted messages.

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


9. RC file UTF-8 assumption 🐞 Bug ☼ Reliability
Description
update_shell_config() reads existing shell rc files via fs::read_to_string(), which fails on
non-UTF-8 content and aborts pacquet setup without applying any PATH changes. This makes setup
unusable for users whose rc file contains non-UTF-8 bytes.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[R256-268]

+    if !config_file.exists() {
+        if let Some(parent) = config_file.parent() {
+            fs::create_dir_all(parent)?;
+        }
+        write_config(config_file, &format!("{new_content}\n"))?;
+        return Ok((ConfigFileChangeType::Created, String::new()));
+    }
+    let config_content = fs::read_to_string(config_file)?;
+    let Some((matched_range, old_settings)) =
+        find_section(&config_content, opts.config_section_name)
+    else {
+        write_config(config_file, &format!("{config_content}\n{new_content}\n"))?;
+        return Ok((ConfigFileChangeType::Appended, String::new()));
Evidence
The code path for existing files unconditionally calls fs::read_to_string(config_file)?, so any
non-UTF-8 rc content results in an I/O error and prevents section detection/append/replace from
running.

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[251-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
`update_shell_config()` uses `fs::read_to_string()`, which requires UTF-8 and returns an error on non-UTF-8 rc files. This causes `pacquet setup` to fail even though the markers and inserted block are ASCII.
### Issue Context
The section markers (`# pnpm` / `# pnpm end`) are ASCII and can be found/updated safely without decoding the entire file as UTF-8.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[256-283]
### Implementation notes
- Read with `fs::read()` into `Vec<u8>`.
- Search/replace markers at the byte level (ASCII) to preserve arbitrary existing bytes.
- Only the inserted/replaced section needs to be written as UTF-8/ASCII bytes.
- Keep the existing `pacquet_fs::ensure_file` atomic writer.

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


View more (7)
10. CRLF markers not matched 🐞 Bug ≡ Correctness
Description
find_section() matches markers using literal \n sequences (# \n and \n#  end), so existing
blocks written with CRLF (\r\n) aren’t detected. As a result, pacquet setup will append a new
block instead of updating/skipping, leading to duplicated sections across runs.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[R300-306]

+fn find_section(content: &str, section: &str) -> Option<(std::ops::Range<usize>, String)> {
+    let start_pat = format!("# {section}\n");
+    let end_pat = format!("\n# {section} end");
+    let start = content.find(&start_pat)?;
+    let inner_start = start + start_pat.len();
+    let end = content.rfind(&end_pat)?;
+    if end < inner_start {
Evidence
The section-finding logic constructs patterns containing only \n and uses find/rfind, so a
file containing \r\n at the marker boundaries will not match and will be treated as 'section
absent' (append path).

pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[295-311]
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[263-269]

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

## Issue description
`find_section()` searches for `# <section>\n` and `\n# <section> end` only. If the rc file uses CRLF line endings, the markers become `# <section>\r\n` and won’t match, causing repeated appends/duplicate blocks.
### Issue Context
Some users end up with CRLF in dotfiles (e.g., edited on Windows, synced via tools). The section detection should be tolerant to `\r\n`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[295-311]
### Implementation notes
- Either normalize input for searching (e.g., treat `\r\n` as `\n` in a search view while still using byte offsets carefully), or search for both variants:
- start: `# {section}\n` OR `# {section}\r\n`
- end: `\n# {section} end` OR `\r\n# {section} end`
- Add a unit test covering CRLF marker detection to prevent regressions.

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


11. Windows PATH dedupe case-sensitive 🐞 Bug ☼ Reliability
Description
On Windows, add_to_path() only treats a PATH entry as already present if it exactly equals the
added entry, so case/format variants can be duplicated and cause repeated setup runs to keep
growing the registry Path value. This is inconsistent with the module’s own case-insensitive
handling of registry value names and can lead to PATH bloat.
Code

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[R120-132]

+    let variable = "Path";
+    let path_data = get_env_value_from_registry(registry_output, variable);
+    let path_data = match path_data {
+        Some(data) if !data.trim().is_empty() => data,
+        _ => return Err(PathExtenderError::NoPath),
+    };
+    if path_data.split(';').any(|entry| entry == added_dir) {
+        return Ok(EnvVariableChange {
+            variable: variable.to_string(),
+            old_value: Some(path_data.clone()),
+            new_value: path_data,
+        });
+    }
Evidence
add_to_path() uses entry == added_dir for dedupe, which will miss equivalent entries that differ
only by casing/format. In the same file, the registry value-name matcher is case-insensitive
(eq_ignore_ascii_case), demonstrating that case-insensitivity matters in this Windows registry
parsing context.

pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[115-143]
pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[169-191]

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

## Issue description
`add_to_path()` checks for existing PATH membership using strict string equality. On Windows, PATH entries commonly vary by case (e.g. drive letter), and environment-variable expansions can differ in case (`%PNPM_HOME%` vs `%pnpm_home%`). This can lead to duplicate entries being appended/prepended on repeated runs.
## Issue Context
The same module already acknowledges case-insensitivity for registry value *names* (`get_env_value_from_registry` uses `eq_ignore_ascii_case`), but PATH entry comparison is still strict.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[115-143]
- pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs[166-193]
### Concrete fix direction
- Introduce a small normalizer for PATH entries used only for comparison (not for rewriting the stored value), e.g.:
- trim surrounding quotes/whitespace,
- compare case-insensitively (at least ASCII) for the whole entry, or at minimum normalize the drive letter + backslashes.
- Use the normalizer in the `split(';').any(...)` membership test so equivalent entries are deduped.

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


12. Non-atomic package.json write 🐞 Bug ☼ Reliability
Description
install_cli_globally() creates a temporary package.json using fs::write after an exists()
check; if the process crashes or the write is interrupted, a truncated/corrupt package.json can be
left next to the executable. Subsequent runs will see the file exists and skip regeneration, causing
persistent failures installing the CLI globally until the user manually fixes/removes the file.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R90-102]

+    // Write a package.json if one doesn't already exist. (Updated tarballs
+    // ship with package.json already.)
+    let created_pkg_json = !pkg_json_path.exists();
+    if created_pkg_json {
+        let pkg = serde_json::json!({
+            "name": "@pnpm/exe",
+            "version": PACQUET_VERSION,
+            "bin": { "pnpm": exec_name, "pn": exec_name },
+        });
+        fs::write(&pkg_json_path, pkg.to_string())
+            .into_diagnostic()
+            .wrap_err("write the temporary package.json next to the pnpm executable")?;
+    }
Evidence
The code explicitly decides whether to create the temp package.json based on
!pkg_json_path.exists(), and then writes it with fs::write, which is not crash-safe/atomic. This
combination can leave a partially written file that will be trusted on subsequent runs due to the
exists() guard.

pacquet/crates/cli/src/cli_args/setup.rs[88-102]

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 setup` may leave a corrupted `package.json` next to the executable because it uses `fs::write` after an `exists()` check. A crash, abrupt termination, or disk-full scenario can leave a partial file behind; future runs will skip rewriting (because the file exists) and then fail during global install.
## Issue Context
This affects the temporary `@pnpm/exe` `package.json` that is only created when one doesn’t already exist.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[90-102]
## Suggested fix
- Replace `fs::write(pkg_json_path, ...)` with an atomic write strategy in the same directory (temp file + `sync_all` + `rename`), similar to the rc-file `write_atomic` approach used elsewhere in this PR.
- Consider hardening the `exists()` shortcut by validating that an existing `package.json` is valid JSON and matches the expected shape (`name`, `version`, `bin`) before deciding to skip regeneration; if invalid, treat it as absent and overwrite (or error with a clear recovery hint).

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


13. Package.json cleanup skipped 🐞 Bug ☼ Reliability
Description
install_cli_globally() only executes the temporary package.json cleanup on the success path; if
spawning the install fails or it exits non-zero, the function returns early and leaves the temporary
file behind. This contradicts the comment about mirroring a try/finally cleanup and can leave stray
state next to the executable.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R124-142]

+    let status = Command::new(exec_path)
+        .args(["add", "-g", "--ignore-scripts", &format!("file:{}", exec_dir.display())])
+        .env("PNPM_HOME", pnpm_home_dir)
+        .env("PATH", path_value)
+        .status();
+
+    // Mirror pnpm's `try { spawn } finally { unlink }`: always attempt the
+    // cleanup, but let the install error take precedence over a cleanup error.
+    let cleanup = if created_pkg_json { fs::remove_file(&pkg_json_path) } else { Ok(()) };
+
+    let status = status.into_diagnostic().wrap_err("run the global pnpm install")?;
+    if !status.success() {
+        let code = status.code().map_or_else(|| "unknown".to_string(), |code| code.to_string());
+        return Err(miette::miette!("Failed to install pnpm globally (exit code {code})"));
+    }
+    cleanup
+        .into_diagnostic()
+        .wrap_err("remove the temporary package.json next to the pnpm executable")?;
+    Ok(())
Evidence
The code constructs a cleanup operation but returns before calling it when status is an Err or
when the process exits unsuccessfully, so the temporary file can remain on disk.

pacquet/crates/cli/src/cli_args/setup.rs[124-142]

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 temp `package.json` file is not removed if the install command fails to spawn or exits non-zero. Cleanup is only executed after a successful status check.
### Issue Context
The code comment says it mirrors `try { spawn } finally { unlink }`, but the current control flow returns before invoking `cleanup` on error paths.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[90-142]
### Recommended fix
- Ensure cleanup runs regardless of spawn/exit success:
- Option A: use a small RAII guard (`struct Cleanup { path, enabled }` with `Drop`) that removes the file best-effort.
- Option B: explicitly `match` on the `status` result and run cleanup in each branch, preserving the original install error over cleanup errors.
- Preserve the intended precedence: install/spawn error should win; cleanup failure should be surfaced only if install succeeded.

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


14. Spawn ignores --dir 🐞 Bug ☼ Reliability
Description
install_cli_globally() spawns pnpm add -g without setting current_dir(prefix_dir), so `pnpm -C
<dir> setup` runs the self-install from the original process CWD and can apply config/state from the
wrong directory.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R118-124]

+    let path_value =
+        format!("{}{separator}{}", bin_dir.display(), std::env::var("PATH").unwrap_or_default());
+    let status = Command::new(exec_path)
+        .args(["add", "-g", "--ignore-scripts", &format!("file:{}", exec_dir.display())])
+        .env("PNPM_HOME", pnpm_home_dir)
+        .env("PATH", path_value)
+        .status();
Evidence
The CLI defines a global -C/--dir flag, and setup receives ctx.dir, but the Command used for
the self-install never sets current_dir. Other commands that spawn processes explicitly set
current_dir to honor the provided directory.

pacquet/crates/cli/src/cli_args/cli_command.rs[61-63]
pacquet/crates/cli/src/cli_args/setup.rs[75-124]
pacquet/crates/cli/src/cli_args/exec.rs[172-179]
pacquet/crates/cli/src/cli_args/dlx.rs[358-361]

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 setup` passes `ctx.dir` down, but the spawned self-install (`pnpm add -g ...`) inherits the process CWD because the `Command` does not call `.current_dir(prefix_dir)`.
### Issue Context
This breaks the global `-C/--dir` contract and can cause the child process to resolve config/workspace state relative to the wrong directory.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[116-124]

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


15. Windows PATH key ambiguity 🐞 Bug ☼ Reliability
Description
The self-install spawn sets only PATH and builds it from std::env::var("PATH"), but on Windows
both Path and PATH can exist; without removing both, the child may observe an unspecified winner
and miss the injected pnpm bin directory.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R116-124]

+    let bin_dir = pnpm_home_dir.join("bin");
+    let separator = if cfg!(windows) { ";" } else { ":" };
+    let path_value =
+        format!("{}{separator}{}", bin_dir.display(), std::env::var("PATH").unwrap_or_default());
+    let status = Command::new(exec_path)
+        .args(["add", "-g", "--ignore-scripts", &format!("file:{}", exec_dir.display())])
+        .env("PNPM_HOME", pnpm_home_dir)
+        .env("PATH", path_value)
+        .status();
Evidence
setup sets .env("PATH", ...) without removing Path/PATH, while other spawn code paths
explicitly remove both to avoid Windows environment-block ambiguity.

pacquet/crates/cli/src/cli_args/setup.rs[116-124]
pacquet/crates/cli/src/cli_args/exec.rs[173-179]
pacquet/crates/cli/src/cli_args/dlx.rs[359-361]

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 Windows, having both `Path` and `PATH` keys can lead to ambiguous results in the child environment block. `setup` does not remove both keys before inserting its computed PATH.
### Issue Context
Other spawn sites in this repo proactively `env_remove("PATH")` and `env_remove("Path")` before setting `PATH`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[116-124]

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


16. Unquoted source hint 🐞 Bug ⛨ Security
Description
render_setup_output() prints source  without shell escaping, but the rc path can come from
environment variables (e.g. $ENV for sh/dash), so a malicious path can turn the suggested
command into shell code when copy-pasted. This is a copy/paste injection vector and can also break
for paths with spaces/metacharacters.
Code

pacquet/crates/cli/src/cli_args/setup.rs[R184-187]

+    match &report.config_file {
+        None => output.push("Setup complete. Open a new terminal to start using pnpm.".to_string()),
+        Some(config_file) if config_file.change_type != ConfigFileChangeType::Skipped => output
+            .push(format!("To start using pnpm, run:\nsource {}\n", config_file.path.display())),
Evidence
The setup output prints an unescaped source {} command using config_file.path.display(), and the
rc path can be taken from $ENV (arbitrary string) for sh/dash, so attacker-controlled env can
flow into a copy/pasteable shell command.

pacquet/crates/cli/src/cli_args/setup.rs[184-188]
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[119-127]

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 setup` prints a user instruction `source <path>` where `<path>` is inserted unquoted. Since the rc file path can be derived from environment variables (e.g. `ENV`, `ZDOTDIR`) it can contain spaces or shell metacharacters, turning the suggested command into a copy/paste injection.
### Issue Context
- The setup flow determines the rc file path based on shell detection; for `sh`/`dash` it uses `$ENV` directly.
- The rendered output is intended to be copy/pasted.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/setup.rs[172-190]
- pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs[119-127]
### Implementation notes
- Prefer printing a safe, non-executable hint (e.g. “Open a new terminal, or source your rc file: <path>”) **or** shell-escape/quote the path.
- If keeping the `source` command, ensure robust escaping (e.g. POSIX single-quote escaping `'/path/it'\''s'`) so `$()`/backticks/etc. cannot be interpreted by the shell.

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


Grey Divider

Qodo Logo

@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.01      6.8±0.37ms   634.9 KB/sec    1.00      6.8±0.55ms   638.1 KB/sec

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8083c6e

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

🧹 Nitpick comments (1)
pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs (1)

19-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Thread env/home discovery through the existing Host/Sys seam.

add_dir_to_posix_env_path reaches into process-global env state via std::env for shell detection, $SHELL, $ENV, and $ZDOTDIR. That makes these user-visible setup branches hard to test deterministically and violates the pacquet convention for library logic that reads process state.

As per path instructions, “Reading process state: avoid std::env::var/current_dir directly in library logic; thread values via parameters or a DI seam.”

Also applies to: 29-43, 106-113, 274-278

🤖 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 `@pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs` around lines 19
- 24, `add_dir_to_posix_env_path` and the shell-detection/update flow are
reading process-global state directly via std::env, which should instead be
threaded through the existing Host/Sys seam for deterministic testing. Refactor
`detect_current_shell`, `update_shell`, and the code paths around shell env/home
discovery so they accept the needed env/home values as parameters (or through
the DI seam) rather than calling std::env for $SHELL, $ENV, and $ZDOTDIR
internally. Keep the public behavior the same, but move all process-state access
out of the library logic and into the seam/wrapper layer.

Source: Path instructions

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

Inline comments:
In `@pacquet/crates/cli/src/cli_args/setup.rs`:
- Around line 126-128: The temporary package cleanup in setup.rs is swallowing
failures by ignoring the result of fs::remove_file, which can leave the
synthetic package.json behind and affect later behavior. Update the cleanup path
in the setup flow that uses created_pkg_json and pkg_json_path so the
remove_file error is handled and propagated instead of being discarded, keeping
the existing control flow but surfacing any cleanup failure to the caller.
- Around line 116-124: The PATH handling in setup logic is discarding non-UTF-8
values and can wipe out the caller’s ambient PATH when building the pnpm install
environment. Update the PATH construction in the setup flow around the
bin_dir/path_value logic to use an OsString-based approach with std::env::var_os
plus split_paths and join_paths, then pass that preserved value into
Command::env for the install command.

In `@pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs`:
- Around line 213-236: The rc-file update logic in the PathExtender POSIX flow
writes directly to the target file with fs::write, which is not crash-safe.
Update the code paths in the config-file creation, append, and replace flows to
write through a temporary file in the same directory, flush/sync it, and then
atomically rename it over the original. Keep the behavior centered around
find_section, replace_section, and the config_file write sites, but ensure every
overwrite of the shell rc file uses the atomic temp-file pattern.
- Around line 81-96: Escape all shell-interpolated path values before rendering
rc snippets: in render_posix_settings, and the related sh/fish/nu path
renderers, treat dir and proxy-derived entries as untrusted input and
quote/escape them with shell-appropriate escaping before inserting into PATH or
export statements. Update the helpers that build path_value/path_ref so they
cannot emit raw quotes, command substitutions, newlines, or metacharacters from
caller-provided paths. Ensure the fix is applied consistently across the
referenced renderer functions so the generated setup snippets remain safe for
shell rc files.

In `@pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs`:
- Around line 193-197: The refresh_env_vars function currently ignores whether
setx and reg delete actually succeed, so setup can report success even when the
environment refresh failed. Update refresh_env_vars to inspect the exit status
from both Command::new("setx") and Command::new("reg") in the windows path
extender flow, and return a PathExtenderError if either command fails. Keep the
failure handling local to refresh_env_vars so errors are propagated instead of
swallowed.
- Around line 138-140: `get_registry_output` and the code path in `add_to_path`
should not assume `run_capture` succeeded just because it returned stdout; check
the child process exit status before using the output. If `reg query` or `chcp
65001` exits non-zero, return the appropriate `PathExtenderError` (especially
`RegRead`) instead of letting empty/invalid stdout continue into path parsing.
Use the existing `get_registry_output` helper and the `add_to_path` flow to
propagate failures with the correct pnpm-compatible error code/message.

---

Nitpick comments:
In `@pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs`:
- Around line 19-24: `add_dir_to_posix_env_path` and the shell-detection/update
flow are reading process-global state directly via std::env, which should
instead be threaded through the existing Host/Sys seam for deterministic
testing. Refactor `detect_current_shell`, `update_shell`, and the code paths
around shell env/home discovery so they accept the needed env/home values as
parameters (or through the DI seam) rather than calling std::env for $SHELL,
$ENV, and $ZDOTDIR internally. Keep the public behavior the same, but move all
process-state access out of the library logic and into the seam/wrapper layer.
🪄 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: c7cd98aa-0ab0-411e-84af-b2db6c4ef0f7

📥 Commits

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

📒 Files selected for processing (11)
  • 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/setup.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/posix.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/posix/tests.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/windows.rs
  • pacquet/crates/cli/src/cli_args/setup/path_extender/windows/tests.rs
  • pacquet/crates/cli/src/cli_args/setup/tests.rs

@codecov-commenter

codecov-commenter commented Jun 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 38.58407% with 347 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.43%. Comparing base (f8e5a0d) to head (8fe181e).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...es/cli/src/cli_args/setup/path_extender/windows.rs 19.23% 126 Missing ⚠️
...ates/cli/src/cli_args/setup/path_extender/posix.rs 55.96% 96 Missing ⚠️
pacquet/crates/cli/src/cli_args/setup.rs 29.13% 90 Missing ⚠️
...uet/crates/cli/src/cli_args/setup/path_extender.rs 51.78% 27 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch_query.rs 0.00% 7 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12697      +/-   ##
==========================================
- Coverage   85.88%   85.43%   -0.46%     
==========================================
  Files         385      389       +4     
  Lines       59044    59609     +565     
==========================================
+ Hits        50709    50926     +217     
- Misses       8335     8683     +348     

☔ 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

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 8083c6ec85fc

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 5.190 ± 0.594 4.622 6.634 1.66 ± 0.22
pacquet@main 4.702 ± 0.203 4.435 5.009 1.50 ± 0.13
pnpr@HEAD 3.130 ± 0.201 2.821 3.534 1.00 ± 0.10
pnpr@main 3.129 ± 0.223 2.779 3.575 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 5.19012518934,
      "stddev": 0.5937455854187318,
      "median": 4.96649652284,
      "user": 3.2449333599999997,
      "system": 2.7083568,
      "min": 4.62240387984,
      "max": 6.63394201684,
      "times": [
        6.63394201684,
        5.635676058840001,
        5.0280991868400005,
        5.49211333384,
        4.92045569484,
        4.85150963484,
        4.62240387984,
        4.81554140684,
        4.88897332984,
        5.01253735084
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.702163533239999,
      "stddev": 0.20277565527926592,
      "median": 4.63451571384,
      "user": 3.28164666,
      "system": 2.6756789999999997,
      "min": 4.43549523884,
      "max": 5.00907933984,
      "times": [
        4.93382052784,
        4.60871877384,
        4.49956569184,
        4.85388021884,
        4.66031265384,
        4.43549523884,
        5.00907933984,
        4.57488770384,
        4.89538747684,
        4.55048770684
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.1300609367399996,
      "stddev": 0.20126824016132458,
      "median": 3.0974081278399996,
      "user": 2.2098837599999994,
      "system": 2.3015782,
      "min": 2.82102217584,
      "max": 3.5338507418400003,
      "times": [
        3.5338507418400003,
        3.12491391784,
        3.04422266684,
        2.95619981484,
        2.82102217584,
        2.99407373784,
        3.23468740584,
        3.06990233784,
        3.23712812584,
        3.28460844284
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.12901122614,
      "stddev": 0.22324120645017162,
      "median": 3.08940396684,
      "user": 2.2127291599999994,
      "system": 2.2886444,
      "min": 2.77917439184,
      "max": 3.57530912784,
      "times": [
        2.94205423784,
        3.23828762984,
        2.77917439184,
        3.24854284584,
        3.04407150784,
        3.13473642584,
        3.57530912784,
        3.03064426484,
        3.30370301384,
        2.99358881584
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 669.1 ± 43.9 633.6 757.9 1.00
pacquet@main 749.0 ± 114.7 637.7 944.5 1.12 ± 0.19
pnpr@HEAD 856.9 ± 117.3 677.2 1082.2 1.28 ± 0.19
pnpr@main 828.5 ± 122.5 683.1 1064.6 1.24 ± 0.20
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6690666358399999,
      "stddev": 0.043934632851556146,
      "median": 0.65251899434,
      "user": 0.31752737999999997,
      "system": 1.0454858000000002,
      "min": 0.63358316334,
      "max": 0.75789969234,
      "times": [
        0.65179682834,
        0.63664313334,
        0.65324116034,
        0.7373975203400001,
        0.65796854334,
        0.63880821534,
        0.75789969234,
        0.64160840934,
        0.68171969234,
        0.63358316334
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.74900065364,
      "stddev": 0.11469037518942783,
      "median": 0.72441743234,
      "user": 0.31514028,
      "system": 1.0510556000000002,
      "min": 0.63770964034,
      "max": 0.94453765834,
      "times": [
        0.85551635234,
        0.64302089234,
        0.64992306634,
        0.79339456734,
        0.63770964034,
        0.76423615934,
        0.63845454834,
        0.87861494634,
        0.94453765834,
        0.68459870534
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.8568754004400001,
      "stddev": 0.11728080354687968,
      "median": 0.81442888584,
      "user": 0.32848157999999994,
      "system": 1.0774044,
      "min": 0.67719500934,
      "max": 1.08221387234,
      "times": [
        1.08221387234,
        0.80671593534,
        0.78678372134,
        0.92701536234,
        0.82214183634,
        0.67719500934,
        0.78187447834,
        0.90613937934,
        0.98157642234,
        0.79709798734
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.8285150530400001,
      "stddev": 0.12253368117914218,
      "median": 0.82416734284,
      "user": 0.3237338799999999,
      "system": 1.0679750000000001,
      "min": 0.68305316034,
      "max": 1.06461483534,
      "times": [
        0.92512696234,
        0.9222396083400001,
        0.8385165263400001,
        0.68305316034,
        0.78083026634,
        0.6861450033400001,
        0.80981815934,
        0.87027950934,
        1.06461483534,
        0.70452649934
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.797 ± 0.187 4.583 5.068 1.56 ± 0.09
pacquet@main 4.786 ± 0.173 4.523 5.119 1.55 ± 0.08
pnpr@HEAD 3.082 ± 0.118 2.981 3.337 1.00
pnpr@main 3.326 ± 0.229 3.055 3.828 1.08 ± 0.09
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.79678020212,
      "stddev": 0.1874320520970358,
      "median": 4.79506327512,
      "user": 3.1405884799999995,
      "system": 2.6511214799999996,
      "min": 4.583124821119999,
      "max": 5.06770399112,
      "times": [
        4.631855177119999,
        4.78565685712,
        4.80446969312,
        5.06770399112,
        4.583124821119999,
        4.82832604312,
        5.0608830951199995,
        4.61948304312,
        4.60938430712,
        4.97691499312
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.786381796620001,
      "stddev": 0.17300791223938852,
      "median": 4.77795552862,
      "user": 3.13687828,
      "system": 2.66069698,
      "min": 4.52261222512,
      "max": 5.11915250512,
      "times": [
        4.79459912912,
        4.76405336612,
        5.11915250512,
        4.79185769112,
        4.71432027812,
        4.758723048119999,
        4.52261222512,
        4.93167599012,
        4.90044321212,
        4.56638052112
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.08153808912,
      "stddev": 0.11805269064067349,
      "median": 3.03600497362,
      "user": 2.26840878,
      "system": 2.5029410800000003,
      "min": 2.9811905441200004,
      "max": 3.3365270441200003,
      "times": [
        2.98462786912,
        2.9811905441200004,
        3.12794934812,
        3.04899363712,
        2.9922602721200002,
        3.3365270441200003,
        3.21395653812,
        2.99332947312,
        3.02301631012,
        3.1135298551200004
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.32584992312,
      "stddev": 0.22904079755755877,
      "median": 3.32561512062,
      "user": 2.3536282799999997,
      "system": 2.55015438,
      "min": 3.0548273811200004,
      "max": 3.8277035721200003,
      "times": [
        3.29426384412,
        3.4367376641200003,
        3.2424731431200002,
        3.08326999812,
        3.11029772912,
        3.8277035721200003,
        3.41472248512,
        3.43723701712,
        3.0548273811200004,
        3.3569663971200003
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.279 ± 0.025 1.255 1.337 1.00
pacquet@main 1.367 ± 0.147 1.251 1.688 1.07 ± 0.12
pnpr@HEAD 1.432 ± 0.158 1.302 1.772 1.12 ± 0.13
pnpr@main 1.403 ± 0.091 1.300 1.538 1.10 ± 0.07
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.27900869616,
      "stddev": 0.02522545123593971,
      "median": 1.27208849406,
      "user": 1.11943384,
      "system": 1.3645871599999997,
      "min": 1.25484708456,
      "max": 1.33749416356,
      "times": [
        1.26304974456,
        1.30869747956,
        1.26462224556,
        1.2748639365599999,
        1.33749416356,
        1.27520191356,
        1.25484708456,
        1.27892009856,
        1.26307724356,
        1.26931305156
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.36718169706,
      "stddev": 0.14700318326067346,
      "median": 1.30828100106,
      "user": 1.11739334,
      "system": 1.4170931599999999,
      "min": 1.25147411156,
      "max": 1.68756657256,
      "times": [
        1.33880173756,
        1.68756657256,
        1.58984171056,
        1.32605879456,
        1.29736310056,
        1.3139280415599999,
        1.30263396056,
        1.28500993056,
        1.27913901056,
        1.25147411156
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.43202303436,
      "stddev": 0.15833678493433775,
      "median": 1.3742771085599998,
      "user": 0.47429383999999997,
      "system": 1.2435524599999999,
      "min": 1.30153835456,
      "max": 1.7718965155600002,
      "times": [
        1.37876175956,
        1.7718965155600002,
        1.43023068056,
        1.36979245756,
        1.32231741956,
        1.32339758356,
        1.30153835456,
        1.34543267756,
        1.41114480156,
        1.66571809356
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.40269534296,
      "stddev": 0.09121397784384148,
      "median": 1.39392908106,
      "user": 0.47741044,
      "system": 1.23131986,
      "min": 1.30049626456,
      "max": 1.5381609135599998,
      "times": [
        1.49728158056,
        1.33540525056,
        1.36711385756,
        1.50720956656,
        1.44601805756,
        1.4207443045600001,
        1.30607457656,
        1.30844905756,
        1.5381609135599998,
        1.30049626456
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.937 ± 0.228 2.770 3.497 2.09 ± 0.21
pacquet@main 2.867 ± 0.063 2.795 2.964 2.04 ± 0.13
pnpr@HEAD 1.403 ± 0.084 1.323 1.599 1.00
pnpr@main 1.475 ± 0.124 1.338 1.671 1.05 ± 0.11
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.9373408480600003,
      "stddev": 0.22769579961313524,
      "median": 2.85772012226,
      "user": 1.4914045799999998,
      "system": 1.5893922,
      "min": 2.77001803876,
      "max": 3.49686142276,
      "times": [
        3.49686142276,
        2.81515889676,
        2.89216650476,
        2.88512143876,
        2.89164480176,
        2.82764879376,
        2.77001803876,
        3.17748733876,
        2.83031880576,
        2.78698243876
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.86697332426,
      "stddev": 0.06266350628982105,
      "median": 2.84753107576,
      "user": 1.50504028,
      "system": 1.6084963,
      "min": 2.79500126976,
      "max": 2.96351063476,
      "times": [
        2.79500126976,
        2.95626675476,
        2.80439326076,
        2.85160546876,
        2.96351063476,
        2.83565412076,
        2.8558009437600003,
        2.82456085476,
        2.8434566827600003,
        2.93948325176
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.40319302776,
      "stddev": 0.08439212418756853,
      "median": 1.3745216997599998,
      "user": 0.48068977999999996,
      "system": 1.2495176000000001,
      "min": 1.32342875176,
      "max": 1.59906123776,
      "times": [
        1.59906123776,
        1.35312172976,
        1.35977619476,
        1.49249247076,
        1.42691062276,
        1.35937309676,
        1.38969742176,
        1.32342875176,
        1.33880154676,
        1.3892672047599999
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4747641485599998,
      "stddev": 0.1240188936647019,
      "median": 1.43886272026,
      "user": 0.48036187999999996,
      "system": 1.2469807999999998,
      "min": 1.33752514976,
      "max": 1.67083937676,
      "times": [
        1.40494904776,
        1.3477661377599999,
        1.35317947176,
        1.67083937676,
        1.59269667376,
        1.62400937976,
        1.40427922176,
        1.47277639276,
        1.33752514976,
        1.53962063376
      ]
    }
  ]
}

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12697
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,796.78 ms
(+0.76%)Baseline: 4,760.61 ms
5,712.73 ms
(83.97%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
2,937.34 ms
(-3.58%)Baseline: 3,046.48 ms
3,655.78 ms
(80.35%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,279.01 ms
(-5.86%)Baseline: 1,358.63 ms
1,630.35 ms
(78.45%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
5,190.13 ms
(+7.25%)Baseline: 4,839.27 ms
5,807.13 ms
(89.38%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
669.07 ms
(+2.00%)Baseline: 655.96 ms
787.15 ms
(85.00%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12697
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,081.54 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,403.19 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,432.02 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,130.06 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
856.88 ms
🐰 View full continuous benchmarking report in Bencher

Harden `pacquet setup` beyond pnpm's `@pnpm/os.env.path-extender`, which
interpolates the pnpm home directory into the generated shell rc block and
the Windows registry without escaping.

POSIX: single-quote escape the directory before it is written into the
sh-family / fish / nushell rc block, so a value containing `$(...)`,
backticks, or `$VAR` cannot execute when the rc file is sourced.

Windows: reject a pnpm home directory containing `;`, `%`, or newlines —
characters that would split the persisted user `Path` into extra entries or
break the `%PNPM_HOME%` indirection — with a dedicated
`ERR_PNPM_INVALID_PNPM_HOME` error.

`pnpm_home_dir` is resolved only from the user's own environment, so this is
defense in depth rather than a cross-boundary fix; the equivalent change
should also land in pnpm's path-extender package.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1e60108

… loud

Address review findings on the setup port:

- Write the POSIX shell rc block atomically (temp file in the same directory,
  flushed, then renamed over the target) so a crash or disk-full mid-write
  leaves the existing rc file intact instead of truncated.
- Check command exit status in the Windows path-extender. `reg query`,
  `chcp`, `setx`, and the cleanup `reg delete` now surface a non-zero exit as
  an error instead of continuing with empty/invalid output, mirroring pnpm's
  `safe-execa` (which rejects on non-zero exit).
- Build the child `PATH` for the global install as an `OsString`, preserving
  a non-UTF-8 ambient `PATH` verbatim.
- Propagate failure to remove the temporary `@pnpm/exe` package.json instead
  of swallowing it, while keeping the install error's precedence.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1e60108

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

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

Copy link
Copy Markdown

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

… rc temp write

Address two further review findings on the setup port:

- Reject a POSIX pnpm home directory containing `:` (the PATH separator),
  a newline, or NUL before rendering the rc block. Single-quote escaping
  stops shell expansion but cannot stop a `:` in `$PNPM_HOME/bin` from
  splitting the colon-delimited PATH into extra entries. The Windows-specific
  error variant is generalized to `UnsafePnpmHome` and now covers both
  platforms.
- Write the rc file through `pacquet_fs::ensure_file`, the repo's hardened
  atomic writer, instead of a hand-rolled temp-file writer. It opens a unique
  sibling temp file with `O_CREAT|O_EXCL`, so setup no longer follows a
  pre-seeded symlink at a predictable temp path (a local file-overwrite
  vector) — and reuses existing code rather than duplicating it.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 78bc072

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 78bc072

`setup::handler` ran the global self-install and wrote the alias scripts
before the path-extender validated `PNPM_HOME`, so an unsafe value could
reach the install subprocess's `PATH` (which resolves external tools like
`node` by name) and leave partial state even when setup later errored.

Extract a shared `validate_pnpm_home_dir` (POSIX rejects `:` / newlines /
NUL; Windows rejects `;` / `%` / newlines) and call it at the very start of
the handler, before any side effect. The platform implementations keep their
own check as defense in depth.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8fe181e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8fe181e

@zkochan
zkochan merged commit e96c2ef into main Jun 27, 2026
21 checks passed
@zkochan
zkochan deleted the feat/pacquet-setup-command branch June 27, 2026 15:15
@coderabbitai coderabbitai Bot mentioned this pull request Jul 7, 2026
4 tasks done
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