Skip to content

feat(pacquet-cli): implement pnpm peers command - #12706

Merged
zkochan merged 11 commits into
pnpm:mainfrom
kairosci:paquet-peers
Jul 4, 2026
Merged

zkochan merged 11 commits into
pnpm:mainfrom
kairosci:paquet-peers

Conversation

@kairosci

@kairosci kairosci commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements the pnpm peers command in the Rust pacquet port, matching the TypeScript CLI behavior: it reads the current (or wanted, with --lockfile-only) lockfile, walks each importer's dependency graph, and reports unmet and missing peer dependencies. Supports --json, --lockfile-only, -r/--recursive, honors pnpm.peerDependencyRules (ignoreMissing, allowAny, allowedVersions including parent-scoped selectors), and exits non-zero when issues are found.

Also fixes a bug in the TypeScript @pnpm/deps.inspection.peers-checker: a missing peer excluded via pnpm.peerDependencyRules.ignoreMissing could still surface as a stale conflict in the JSON output. The pacquet implementation recomputes conflicts after filtering; the TypeScript side now does the equivalent.

Related to: #11633

Squash Commit Body

Add the peers command to pacquet-cli, which checks for unmet or missing
peer dependency issues by walking the lockfile, mirroring the TypeScript
CLI: one shared visited set across importers so each package is
evaluated once, missing-peer ranges merged via interval intersection to
detect conflicts, peerDependencyRules filtering (ignoreMissing,
allowAny, allowedVersions with parent-scoped selectors), deterministic
BTreeMap-ordered output, and a PeersOutcome mapped to exit code 1 in
the dispatch layer. Importer link: targets resolve relative to the
importer directory and are rejected when they escape the lockfile
directory.

Also fix the TypeScript peers-checker to drop conflicts of missing
peers removed by peerDependencyRules.ignoreMissing, so the JSON output
no longer reports a conflict while the text output reports no issues.

Related to: pnpm/pnpm#11633

Checklist

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

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

@kairosci
kairosci requested a review from zkochan as a code owner June 28, 2026 17:47
@coderabbitai

coderabbitai Bot commented Jun 28, 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 a new peers CLI subcommand for peer dependency analysis and moves URI/package-name encoding helpers into pacquet_network for reuse by multiple callers.

Changes

peers subcommand

Layer / File(s) Summary
peers CLI wiring and dispatch
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
Registers pub mod peers, adds PeersArgs import and CliCommand::Peers variant, adds a dispatch arm in route, and implements the peers dispatcher function that calls args.run(cfg, dir, recursive).
PeersArgs, run, and lockfile scanning
pacquet/crates/cli/src/cli_args/peers.rs
Defines PeersArgs (--json, --lockfile-only), peer-issue data structures (BadPeerIssue, MissingPeerIssue, PeerIssues), implements run for lockfile selection/output, and the importer-iteration entrypoint with workspace/importer resolution helpers.
Snapshot traversal, peer validation, and missing-peer merging
pacquet/crates/cli/src/cli_args/peers.rs
Implements walk_snapshot with cycle avoidance and parent-context tracking, satisfies using node_semver with prerelease handling, get_pkg_version, merge_missing_peers, extract_candidate_version, and have_common_version.
Filtering, rule interpretation, and rendering
pacquet/crates/cli/src/cli_args/peers.rs
Implements filter_peer_issues applying PeerDependencyRules (ignore patterns, allow_any, allowed_versions with parent-scoped selectors), parse_allowed_versions, simple_glob_match, and colored output via render_peer_issues.
peers unit tests
pacquet/crates/cli/src/cli_args/peers/tests.rs
Tests satisfies, extract_candidate_version, have_common_version, merge_missing_peers, parse_allowed_versions, filter_peer_issues, and format_range.

shared URL encoding helpers

Layer / File(s) Summary
URL encoding module and exports
pacquet/crates/network/src/lib.rs, pacquet/crates/network/src/url_encoding.rs
Adds url_encoding to pacquet_network, defines encode_package_name and encode_uri_component, and re-exports both from the crate root.
Callers use shared encoders
pacquet/crates/auth-commands/src/logout.rs, pacquet/crates/cli/src/cli_args/audit/signatures.rs, pacquet/crates/cli/src/cli_args/audit/signatures/tests.rs, pacquet/crates/cli/src/cli_args/dist_tag.rs, pacquet/crates/cli/src/cli_args/self_update/verify_engine.rs, pacquet/crates/resolving-git-resolver/src/hosted_git.rs
Switches logout, audit signatures, dist-tag, self-update verify, and hosted git code to import shared encoding helpers instead of local implementations, with the matching test import change in audit signatures.

Sequence Diagram(s)

sequenceDiagram
  participant CliCommand
  participant dispatch
  participant dispatch_query
  participant PeersArgs
  CliCommand->>dispatch: route(CliCommand::Peers)
  dispatch->>dispatch_query: peers(ctx, args)
  dispatch_query->>PeersArgs: run(cfg, dir, recursive)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

product: pacquet

Suggested reviewers

  • zkochan
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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): add peers and repo commands with lockfile checks and URL opening
✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

Description

• Add pnpm peers to detect missing/unmet peer dependencies from the lockfile.
• Add pnpm repo to open package repository URLs from manifest or registry.
• Add unit and integration tests to pin behavior and error contracts.
Diagram

graph TD
  A["pacquet CLI"] --> B["Clap CliCommand"] --> C["dispatch::route"] --> D["dispatch_query"]
  D --> E["peers cmd"] --> F[("lockfile + config")]
  D --> G["repo cmd"] --> H{{"npm registry"}}
  G --> I{{"OS browser opener"}}
  subgraph Legend
    direction LR
    _cli["CLI/Module"] ~~~ _data[("Data") ] ~~~ _ext{{"External"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Return an exit code instead of calling std::process::exit
  • ➕ Improves testability (no process termination in unit tests)
  • ➕ Fits a uniform error/exit-code handling strategy across commands
  • ➕ Avoids surprising termination if peers is used as a library entrypoint
  • ➖ Requires plumbed exit-code handling through the dispatch layer
  • ➖ May diverge from pnpm behavior unless carefully mirrored
2. Use a dedicated glob / pattern-matching crate for peer rules
  • ➕ More complete and predictable glob semantics
  • ➕ Less custom logic to maintain (edge cases, escaping, etc.)
  • ➖ Adds a dependency and possible behavior differences vs pnpm
  • ➖ May be overkill for the current simple patterns
3. Use a cross-platform URL opener crate (e.g., `open`)
  • ➕ Reduces OS-specific branching and platform maintenance burden
  • ➕ Potentially better handling for edge platforms/desktops
  • ➖ New dependency plus transitive dependencies
  • ➖ Less direct control over redaction/fallback behavior

Recommendation: The PR’s overall approach is sound for a pnpm-compatible port: peers is lockfile-driven (deterministic, fast, offline-friendly) and repo implements robust URL normalization with explicit error codes. The main consideration is whether the CLI framework should standardize on returning exit codes rather than calling std::process::exit; if there’s already (or planned) centralized exit-code handling, migrating peers to return a failure status would improve composability without changing user-visible behavior.

Files changed (9) +1702 / -0

Enhancement (6) +1055 / -0
cli_args.rsExport 'peers' and 'repo' CLI modules +2/-0

Export 'peers' and 'repo' CLI modules

• Registers the new 'peers' and 'repo' argument modules so they can be referenced by the CLI command enum and dispatch layer.

pacquet/crates/cli/src/cli_args.rs

cli_command.rsAdd 'peers' and 'repo' subcommands to 'CliCommand' +7/-0

Add 'peers' and 'repo' subcommands to 'CliCommand'

• Introduces new Clap subcommands for 'peers' (peer dependency issues) and 'repo' (open repository URL), wiring them into the CLI command enum with help text.

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

dispatch.rsRoute 'peers' and 'repo' to query dispatch +2/-0

Route 'peers' and 'repo' to query dispatch

• Extends the main router to dispatch the new 'peers' and 'repo' commands to 'dispatch_query', aligning them with other read-only/query operations.

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

dispatch_query.rsAdd dispatch entrypoints for 'peers' and 'repo' +18/-0

Add dispatch entrypoints for 'peers' and 'repo'

• Adds 'dispatch_query::peers' (sync run) and 'dispatch_query::repo' (async run), passing config/dir/recursive context as needed.

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

peers.rsImplement 'pnpm peers' lockfile-based peer issue detection +648/-0

Implement 'pnpm peers' lockfile-based peer issue detection

• Implements peer dependency issue detection by walking lockfile snapshots, computing missing/unmet/conflicting peers, and filtering results via configured peer dependency rules. Supports human-readable colored output or JSON output, and exits non-zero when issues are found.

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

repo.rsImplement 'pnpm repo' repository URL resolution and opening +378/-0

Implement 'pnpm repo' repository URL resolution and opening

• Adds 'repo' command implementation that reads repository info from the current project’s manifest or fetches package metadata from the registry, then normalizes repository URLs into browsable web URLs and opens them via platform-specific open mechanisms. Includes structured 'ERR_PNPM_NO_REPO_URL' errors for missing repository fields.

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

Tests (3) +647 / -0
tests.rsAdd unit tests for peers range handling and filtering +430/-0

Add unit tests for peers range handling and filtering

• Adds focused unit tests for semver satisfaction (including prerelease tolerance), candidate-version extraction, missing-peer merging/conflicts, and rule-based filtering/formatting helpers.

pacquet/crates/cli/src/cli_args/peers/tests.rs

tests.rsAdd unit tests for repository URL parsing/normalization +153/-0

Add unit tests for repository URL parsing/normalization

• Covers local manifest extraction and multiple URL/shorthand normalization cases (git+https, ssh, fragments/branches, monorepo directories), plus missing/invalid repository behavior.

pacquet/crates/cli/src/cli_args/repo/tests.rs

repo.rsAdd integration tests for 'repo' help and error contract +64/-0

Add integration tests for 'repo' help and error contract

• Adds CLI-level tests verifying 'repo' failure modes when package.json/repository is missing and ensuring stderr includes 'ERR_PNPM_NO_REPO_URL' guidance; also validates 'repo --help' succeeds and mentions repository behavior.

pacquet/crates/cli/tests/repo.rs

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Missing importer silently ignored 🐞 Bug ≡ Correctness
Description
check_peer_dependencies_from_lockfile() silently skips an importer when the computed importer_id
is not present in lockfile.importers, which can yield an empty issues map and a false "No peer
dependency issues found" result. This is likely when --dir points to a subdirectory that is not a
lockfile importer root or when importer-id derivation differs from lockfile-writer semantics.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R130-141]

+    let mut importer_ids: Vec<String> = if recursive {
+        lockfile.importers.keys().cloned().collect()
+    } else {
+        vec![resolve_importer_id(lockfile_dir, dir)]
+    };
+    importer_ids.sort();
+
+    let mut result: IssuesByProjects = HashMap::new();
+
+    for importer_id in &importer_ids {
+        let Some(_importer) = lockfile.importers.get(importer_id.as_str()) else { continue };
+
Evidence
The peers command currently skips missing importer keys without reporting, unlike other commands
(e.g., list) which fall back to the root importer or print a message. The repo also contains a
canonical importer-id helper used by lockfile writers; peers currently reimplements this logic and
then ignores the missing-key case.

pacquet/crates/cli/src/cli_args/peers.rs[119-183]
pacquet/crates/cli/src/cli_args/list.rs[104-142]
pacquet/crates/workspace/src/importer_id.rs[10-31]

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

## Issue description
`check_peer_dependencies_from_lockfile()` computes an importer id (non-recursive mode) and then silently `continue`s when that id is not in `lockfile.importers`. This can produce an empty `IssuesByProjects`, leading the command to print success/no-issues even though the lockfile exists and may contain peer issues.
## Issue Context
Other CLI commands in this repo avoid this silent-false-negative pattern by either falling back to the root importer or emitting a user-visible message / error when the importer is missing.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[130-141]
- pacquet/crates/cli/src/cli_args/peers.rs[173-183]
### Concrete fix approach
- Derive importer ids using the shared helper `pacquet_workspace::importer_id_from_root_dir(lockfile_dir, dir)` (or otherwise match its semantics).
- In non-recursive mode, if the derived importer id is not present in `lockfile.importers`, return a diagnostic error (preferred) or fall back to `Lockfile::ROOT_IMPORTER_KEY` explicitly and still report that the requested importer was missing.
- Ensure the resulting behavior cannot produce a silent empty `issues` map for a present lockfile.

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


2. Link path traversal read 🐞 Bug ⛨ Security
Description
resolve_link_version() and check_linked_package_peers() build filesystem paths by joining
attacker-controlled link: targets (and importer_id) onto lockfile_dir without validation,
allowing absolute paths and .. segments to escape the workspace. This can trigger unintended local
file reads and potential hangs (e.g. reading special files) when PackageManifest::from_path()
calls fs::read_to_string().
Code

pacquet/crates/cli/src/cli_args/peers.rs[R185-203]

+fn resolve_link_version(lockfile_dir: &std::path::Path, link_target: &str) -> Option<String> {
+    let manifest_path = lockfile_dir.join(link_target).join("package.json");
+    PackageManifest::from_path(manifest_path).ok().and_then(|manifest| {
+        manifest.value().get("version").and_then(|v| v.as_str()).map(String::from)
+    })
+}
+
+fn check_linked_package_peers(
+    importer_id: &str,
+    importer: &pacquet_lockfile::ProjectSnapshot,
+    link_target: &str,
+    alias: &str,
+    linked_version: &str,
+    lockfile_dir: &std::path::Path,
+    issues: &mut PeerIssues,
+) {
+    let linked_pkg_dir = lockfile_dir.join(importer_id).join(link_target);
+    let manifest_path = linked_pkg_dir.join("package.json");
+    let Ok(manifest) = PackageManifest::from_path(manifest_path) else { return };
Evidence
The peers command constructs manifest paths directly from lockfile link: payloads; the lockfile
layer explicitly preserves absolute/relative link payloads verbatim, and PackageManifest reads the
resulting path with fs::read_to_string, so an attacker-controlled lockfile can steer reads outside
the workspace.

pacquet/crates/cli/src/cli_args/peers.rs[185-203]
pacquet/crates/lockfile/src/resolved_dependency.rs[40-77]
pacquet/crates/lockfile/src/resolved_dependency/tests.rs[21-34]
pacquet/crates/package-manifest/src/lib.rs[122-146]

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 peers command reads `package.json` for `link:` dependencies by constructing paths like `lockfile_dir.join(link_target)` and `lockfile_dir.join(importer_id).join(link_target)`. Because `link_target` (and potentially `importer_id`) originate from the lockfile, a crafted lockfile can supply absolute paths or `..` components, escaping the workspace root and causing arbitrary local reads / potential hangs when reading special files.
### Issue Context
- `ImporterDepVersion::Link` is documented and tested to preserve the link payload verbatim (including absolute paths).
- `PackageManifest::from_path()` reads the target path via `fs::read_to_string()`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[185-203]
### Suggested fix approach
- Introduce a small helper to resolve a `link_target` to a safe `PathBuf`:
- Treat relative `link_target` as relative to the importer's root dir (`lockfile_dir.join(importer_id)`), not just `lockfile_dir`.
- Reject paths that are absolute (`Path::is_absolute()`), contain `Component::ParentDir`, or otherwise escape the intended root.
- Optionally canonicalize and enforce `starts_with(root)` (being careful about symlinks / existence), and fall back to skipping manifest reads when validation fails.
- If validation fails, do not attempt to read; return `None` and proceed with a safe placeholder version (or skip linked peer evaluation) rather than touching the filesystem outside the workspace.

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


3. Scoped allowedVersions misparsed 🐞 Bug ≡ Correctness
Description
parse_allowed_versions() splits global allowedVersions selectors on the first @, so scoped
package selectors like @scope/pkg become an empty target name and never match. This breaks
peerDependencyRules.allowedVersions for scoped peers and can cause false peer-issue reports /
peers exiting non-zero even when the workspace config intends to allow those versions.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R486-493]

+            let target_name = if let Some((name, _version)) = selector.split_once('@') {
+                name.to_string()
+            } else {
+                selector.clone()
+            };
+            let ranges: Vec<String> = spec.split("||").map(|seg| seg.trim().to_string()).collect();
+            match_all.entry(target_name).or_default().extend(ranges);
+        }
Evidence
The Rust implementation strips everything after the first @ for non-parent>child selectors,
which turns scoped package selectors into an empty string key, so they can never match actual peer
names. Repository docs explicitly allow these selectors, and the repo’s TypeScript implementation
uses a real selector parser (parseOverrides) and matches by targetPkg.name, which handles scoped
names correctly.

pacquet/crates/cli/src/cli_args/peers.rs[468-493]
pacquet/crates/config/src/workspace_yaml.rs[458-476]
pnpm11/deps/inspection/peers-checker/src/checkPeerDependencies.ts[194-216]
pacquet/crates/config-parse-overrides/src/lib.rs[147-186]

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

## Issue description
`parse_allowed_versions()` currently does `selector.split_once('@')` to strip a potential `@version` suffix. This breaks scoped package names because `"@scope/pkg".split_once('@')` yields `("", "scope/pkg")`, so the target name becomes empty and the allowlist entry never applies.
### Issue Context
- `peerDependencyRules.allowedVersions` is documented to accept peer selectors like `name`, `parent>name`, and `parent@range>name` (and by implication must support scoped names like `@scope/pkg`).
- The TypeScript implementation parses these selectors via `parseOverrides()` and uses `targetPkg.name`, which correctly preserves scoped names.
### Fix
Replace the ad-hoc `split_once('@')` logic with proper selector parsing. The simplest approach for the non-`parent>child` branch is to reuse existing parsing utilities already in this repo:
- Use `pacquet_resolving_parse_wanted_dependency::parse_wanted_dependency(selector)` and take `wanted.alias` as the package name (this correctly handles `react@^18`, `@scope/pkg`, and `@scope/pkg@^1`).
- If parsing fails (no alias), surface a structured error (mirroring pnpm’s `INVALID_ALLOWED_VERSION_SELECTOR`) or at least skip with a diagnostic.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[468-497]

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


View more (11)
4. Visited set hides parents 🐞 Bug ≡ Correctness
Description
walk_snapshot() returns early for any package key already in visited, so peer issues are only
recorded for the first dependency path that reaches a package. In graphs where the same package is
reachable via multiple parents, this can underreport peer issues and produce incorrect
parents/"required by" chains.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R191-202]

+    if !visited.insert(key.clone()) {
+        return;
+    }
+
+    let Some(snapshot) = snapshots.get(key) else { return };
+
+    let pkg_name = key.name.to_string();
+    let pkg_version = get_pkg_version(key, packages);
+
+    let mut current_parents = parents.to_vec();
+    current_parents.push(ParentPkg { name: pkg_name, version: pkg_version });
+
Evidence
The function returns immediately on revisiting a node, but issues embed the full parents chain for
attribution, so alternative paths are discarded by construction.

pacquet/crates/cli/src/cli_args/peers.rs[183-203]
pacquet/crates/cli/src/cli_args/peers.rs[225-257]

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

## Issue description
`walk_snapshot()` uses a node-level `visited` set and returns immediately on revisits. Because the function records a full `parents` chain into each issue, skipping revisits drops alternative parent chains and can underreport/misattribute peer issues when a package is reachable from multiple paths.
### Issue Context
The current logic:
- early-returns on `!visited.insert(key.clone())`
- builds `current_parents` and stores it into `BadPeerIssue` / `MissingPeerIssue`
So only the first path that reaches a given `PkgNameVerPeer` contributes issues.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[183-274]
### Suggested fix approach
- Separate “should we recurse into children?” from “should we evaluate/report peer issues for this path?”
- Always evaluate the current node’s peer deps (so each distinct parent path can contribute required-by data).
- Only recurse into children the first time a node is seen (to avoid cycles/exponential traversal).
- To avoid duplicate issue entries after allowing multiple parent paths, deduplicate/merge issue records by a stable key (e.g., declaring package + peer name + wantedRange + foundVersion) while accumulating multiple `parents` chains (or a set of declaring parents) in the output model.

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


5. Link peers misreported 🐞 Bug ≡ Correctness
Description
walk_snapshot() treats peer deps resolved as link: entries as automatically unmet by recording
found_version = "link:" and never resolving the linked package’s real version, so peer checks can
false-fail in workspaces. Because SnapshotDepRef::resolve() returns None for Link, the
traversal also cannot descend into linked workspace deps, so peers can be missed under link:
edges.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R214-246]

+            let Ok(peer_pkg_name) = peer_name.parse::<PkgName>() else { continue };
+            let resolved_ref =
+                snapshot.dependencies.as_ref().and_then(|deps| deps.get(&peer_pkg_name)).or_else(
+                    || {
+                        snapshot
+                            .optional_dependencies
+                            .as_ref()
+                            .and_then(|deps| deps.get(&peer_pkg_name))
+                    },
+                );
+
+            match resolved_ref {
+                Some(dep_ref) => {
+                    if let Some(ver_peer) = dep_ref.ver_peer() {
+                        let version_str = ver_peer.version().to_string();
+                        if !satisfies(&version_str, peer_range) {
+                            issues.bad.entry(peer_name.clone()).or_default().push(BadPeerIssue {
+                                parents: current_parents.clone(),
+                                optional: is_optional,
+                                wanted_range: peer_range.clone(),
+                                found_version: version_str,
+                                resolved_from: Vec::new(),
+                            });
+                        }
+                    } else if let Some(link_target) = dep_ref.as_link_target() {
+                        issues.bad.entry(peer_name.clone()).or_default().push(BadPeerIssue {
+                            parents: current_parents.clone(),
+                            optional: is_optional,
+                            wanted_range: peer_range.clone(),
+                            found_version: format!("link:{link_target}"),
+                            resolved_from: Vec::new(),
+                        });
+                    }
Evidence
The peers implementation explicitly treats link: refs as unmet and never derives a semver version;
separately, the lockfile model defines link: as non-resolving for snapshot traversal, so the
current recursion cannot include linked workspaces.

pacquet/crates/cli/src/cli_args/peers.rs[214-246]
pacquet/crates/cli/src/cli_args/peers.rs[269-272]
pacquet/crates/lockfile/src/snapshot_dep_ref.rs[58-71]

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

## Issue description
`walk_snapshot()` currently flags any peer dependency that resolves to a `link:` snapshot ref as a bad peer (unmet), because it cannot derive a semver version and does not attempt to resolve the linked package’s version. Additionally, traversal skips `link:` dependencies because `SnapshotDepRef::resolve()` returns `None` for `Link`, preventing discovery of peer requirements beneath linked workspace deps.
### Issue Context
In pnpm lockfiles, `link:<path>` is used for workspace sibling dependencies. For correct peer checking, the command needs to (a) determine the linked package’s real version and compare it to the peer range, and (b) include linked deps in the traversal so peers under those subtrees are included.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[214-274]
### Suggested approach
- When `dep_ref.as_link_target()` is `Some(target)`, resolve `target` relative to `lockfile_dir` and load the linked workspace package’s `package.json` (or map it to the corresponding lockfile importer/snapshot if available).
- Use the linked package’s actual version for `satisfies()` and for `found_version` in diagnostics.
- Extend traversal to follow `link:` edges by mapping them to the linked project/importer (or by separately invoking the same walk for that workspace package), so peer requirements inside linked workspaces are included.

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


6. Conflicts not filtered 🐞 Bug ≡ Correctness
Description
filter_peer_issues() rewrites missing, bad, and intersections but never recomputes/filters
conflicts, so --json output can contain stale conflict entries for peers that were removed by
peerDependencyRules filtering. This makes the emitted JSON internally inconsistent with the filtered
issue sets.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R457-460]

+        project_issues.missing = filtered_missing;
+        project_issues.bad = filtered_bad;
+        project_issues.intersections = filtered_intersections;
+    }
Evidence
PeerIssues includes conflicts, but the filtering function only assigns missing, bad, and
intersections back to the struct, leaving conflicts as whatever was computed pre-filter.

pacquet/crates/cli/src/cli_args/peers.rs[40-46]
pacquet/crates/cli/src/cli_args/peers.rs[394-463]

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

## Issue description
After applying `peerDependencyRules`, the code updates `project_issues.missing`, `bad`, and `intersections`, but leaves `project_issues.conflicts` unchanged. This can produce JSON output where `conflicts` refers to peers that no longer exist in `missing`.
### Issue Context
`conflicts` and `intersections` are derived from missing peers via `merge_missing_peers()` earlier. Once missing peers are filtered, these derived fields must be recomputed from the filtered set to remain consistent.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[394-463]
### Suggested fix
After building `filtered_missing` (and before assigning back to `project_issues`), call `merge_missing_peers(&filtered_missing)` and set:
- `project_issues.conflicts = merged.conflicts`
- `project_issues.intersections = merged.intersections`
This ensures JSON output is self-consistent with the filtered missing set.

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


7. Repo drops directory on branch 🐞 Bug ≡ Correctness
Description
repository_to_web_url() constructs a monorepo browse URL including directory, but if the
repository URL also includes a #fragment (branch/tag), it overwrites the URL with /tree/ and
silently drops the directory. This opens the wrong location for monorepo packages that specify both
repository.directory and a branch fragment.
Code

pacquet/crates/cli/src/cli_args/repo.rs[R151-159]

+    let mut final_url = if let Some(dir) = directory {
+        format!("{base_url}/tree/HEAD/{}", dir.trim_start_matches('/'))
+    } else {
+        base_url.clone()
+    };
+
+    if let Some(fragment) = try_extract_fragment(raw_url) {
+        final_url = format!("{base_url}/tree/{fragment}");
+    }
Evidence
The function builds a directory URL, but then unconditionally replaces it if
try_extract_fragment(raw_url) returns a value, discarding directory.

pacquet/crates/cli/src/cli_args/repo.rs[125-161]

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

## Issue description
In `repository_to_web_url()`, `directory` is applied first, but then `#fragment` handling overwrites `final_url` and removes the directory portion. This yields incorrect browse URLs for monorepo packages.
### Issue Context
`pick_repo_url()` supports repository objects with both `url` and `directory` (common for monorepos).
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/repo.rs[125-161]
### Suggested fix
When a fragment exists:
- if `directory.is_some()`, emit `{base_url}/tree/{fragment}/{directory}` (with leading `/` trimmed)
- else keep `{base_url}/tree/{fragment}`
This preserves both branch selection and monorepo subdirectory browsing.

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


8. Workspace-wide peers scan 🐞 Bug ➹ Performance
Description
check_peer_dependencies_from_lockfile() treats any workspace (i.e., lockfile_dir != dir) as
implicit recursion and scans all lockfile importers even when --recursive is not set, so running
pacquet peers inside one workspace package can report other projects’ issues and get very slow on
large monorepos.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R122-126]

+    let importer_ids: Vec<String> = if recursive || config_has_workspace(lockfile_dir, dir) {
+        lockfile.importers.keys().cloned().collect()
+    } else {
+        vec![resolve_importer_id(lockfile_dir, dir)]
+    };
Evidence
Config.workspace_dir is explicitly “the nearest ancestor pnpm-workspace.yaml” dir, so for typical
workspace subprojects lockfile_dir != dir is true; the new peers logic then scans all importers.
By contrast, list resolves a single importer_id from dir vs lockfile_dir and does not
implicitly expand to all importers just because it’s in a workspace.

pacquet/crates/cli/src/cli_args/peers.rs[111-170]
pacquet/crates/config/src/lib.rs[1077-1084]
pacquet/crates/cli/src/cli_args/list.rs[104-135]

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 peers` currently expands to *all* lockfile importers whenever it detects a workspace (`lockfile_dir != dir`), even if the user did not request recursion. This changes command semantics (unexpected cross-project results) and can significantly increase runtime on large workspaces.
### Issue Context
- `lockfile_dir` is set to the nearest ancestor `pnpm-workspace.yaml` directory via `Config.workspace_dir`, which commonly differs from `dir` when invoked from a workspace subproject.
- Other commands (e.g. `list`) resolve a single importer id from `dir` vs `lockfile_dir` unless recursion is explicitly requested.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[111-170]
### Suggested fix
- Change importer selection to **only** use all importers when `recursive == true`.
- e.g. `if recursive { lockfile.importers.keys().cloned().collect() } else { vec![resolve_importer_id(lockfile_dir, dir)] }`
- Remove (or repurpose with a correct definition) `config_has_workspace()` so workspace presence alone does not imply recursion.
- (Optional) If you want deterministic output, sort `importer_ids` after collecting.

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


9. Peer rule negation ignored 🐞 Bug ≡ Correctness
Description
filter_peer_issues() applies peerDependencyRules.ignoreMissing / allowAny using
simple_glob_match(), which does not implement pnpm’s documented createMatcher negation semantics
(leading !), so workspace-configured peer rule patterns can be applied incorrectly.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R417-521]

+        for (peer_name, peer_issues) in &project_issues.missing {
+            if ignore_missing_pats.iter().any(|pat| simple_glob_match(pat, peer_name))
+                || peer_issues.iter().all(|i| i.optional)
+            {
+                continue;
+            }
+            filtered_missing.insert(peer_name.clone(), peer_issues.clone());
+            if let Some(range) = project_issues.intersections.get(peer_name) {
+                filtered_intersections.insert(peer_name.clone(), range.clone());
+            }
+        }
+
+        for (peer_name, peer_issues) in &project_issues.bad {
+            if allow_any_pats.iter().any(|pat| simple_glob_match(pat, peer_name)) {
+                continue;
+            }
+            let remaining: Vec<BadPeerIssue> = peer_issues
+                .iter()
+                .filter(|issue| {
+                    if let Some(ranges) = allow_all_matcher.get(peer_name)
+                        && ranges.iter().any(|range| satisfies(&issue.found_version, range))
+                    {
+                        return false;
+                    }
+                    if let Some(declaring_parent) = issue.parents.last()
+                        && let Some(parent_map) = allow_by_parent.get(&declaring_parent.name)
+                        && let Some(ranges) = parent_map.get(peer_name)
+                        && ranges.iter().any(|range| satisfies(&issue.found_version, range))
+                    {
+                        return false;
+                    }
+                    true
+                })
+                .cloned()
+                .collect();
+            if !remaining.is_empty() {
+                filtered_bad.insert(peer_name.clone(), remaining);
+            }
+        }
+
+        project_issues.missing = filtered_missing;
+        project_issues.bad = filtered_bad;
+        project_issues.intersections = filtered_intersections;
+    }
+
+    issues
+}
+
+type AllowAllMatcher = HashMap<String, Vec<String>>;
+type AllowByParentMatcher = HashMap<String, HashMap<String, Vec<String>>>;
+
+fn parse_allowed_versions(
+    allowed: &HashMap<String, String>,
+) -> (AllowAllMatcher, AllowByParentMatcher) {
+    let mut match_all: HashMap<String, Vec<String>> = HashMap::new();
+    let mut by_parent: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
+
+    for (selector, spec) in allowed {
+        if let Some((parent, target)) = selector.split_once('>') {
+            let parent_name = parent.trim().to_string();
+            let target_name = target.trim().to_string();
+            let ranges: Vec<String> = spec.split("||").map(|seg| seg.trim().to_string()).collect();
+            by_parent
+                .entry(parent_name)
+                .or_default()
+                .entry(target_name)
+                .or_default()
+                .extend(ranges);
+        } else {
+            let target_name = if let Some((name, _version)) = selector.split_once('@') {
+                name.to_string()
+            } else {
+                selector.clone()
+            };
+            let ranges: Vec<String> = spec.split("||").map(|seg| seg.trim().to_string()).collect();
+            match_all.entry(target_name).or_default().extend(ranges);
+        }
+    }
+
+    (match_all, by_parent)
+}
+
+fn simple_glob_match(pattern: &str, value: &str) -> bool {
+    if !pattern.contains('*') {
+        return pattern == value;
+    }
+    let segments: Vec<&str> = pattern.split('*').collect();
+    let mut rest = value;
+    for (i, segment) in segments.iter().enumerate() {
+        if segment.is_empty() {
+            continue;
+        }
+        if i == 0 {
+            let Some(stripped) = rest.strip_prefix(segment) else { return false };
+            rest = stripped;
+        } else if i == segments.len() - 1 {
+            return rest.ends_with(segment);
+        } else if let Some(pos) = rest.find(segment) {
+            rest = &rest[pos + segment.len()..];
+        } else {
+            return false;
+        }
+    }
+    true
+}
Evidence
The configuration docs explicitly call these pattern lists createMatcher glob/negation patterns,
and the repository already has a matcher implementation that supports leading ! ignore rules;
peers.rs bypasses it and uses a simplified matcher without negation support.

pacquet/crates/config/src/workspace_yaml.rs[458-466]
pacquet/crates/cli/src/cli_args/peers.rs[394-521]
pacquet/crates/config/src/matcher.rs[1-64]

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 `peerDependencyRules.ignoreMissing` and `peerDependencyRules.allowAny` pattern lists are documented as pnpm `createMatcher` glob/negation patterns, but `peers.rs` uses a local `simple_glob_match()` that does not support negation (`!`). This can cause false positives/negatives when users rely on negated patterns.
### Issue Context
The repo already contains a matcher implementation (`pacquet_config::matcher`) that mirrors pnpm’s `createMatcher` behavior, including the leading `!` ignore rule semantics.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[394-521]
- pacquet/crates/config/src/matcher.rs[1-60]
### Suggested fix
- Replace `simple_glob_match()` usage with `pacquet_config::matcher::create_matcher(...)` (or `create_matcher_with_index`) for both ignoreMissing and allowAny.
- Compile matchers once at the start of `filter_peer_issues()` and call `matcher.matches(peer_name)`.
- Remove `simple_glob_match()` to avoid maintaining duplicate matcher logic.

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


10. Parent@range selector ignored 🐞 Bug ≡ Correctness
Description
allowedVersions selectors of the documented form parent@range>peer are silently ignored because
parse_allowed_versions() stores the full parent@range string as the key, but filtering looks up
overrides only by declaring_parent.name (without the @range).
Code

pacquet/crates/cli/src/cli_args/peers.rs[R441-485]

+                    if let Some(declaring_parent) = issue.parents.last()
+                        && let Some(parent_map) = allow_by_parent.get(&declaring_parent.name)
+                        && let Some(ranges) = parent_map.get(peer_name)
+                        && ranges.iter().any(|range| satisfies(&issue.found_version, range))
+                    {
+                        return false;
+                    }
+                    true
+                })
+                .cloned()
+                .collect();
+            if !remaining.is_empty() {
+                filtered_bad.insert(peer_name.clone(), remaining);
+            }
+        }
+
+        project_issues.missing = filtered_missing;
+        project_issues.bad = filtered_bad;
+        project_issues.intersections = filtered_intersections;
+    }
+
+    issues
+}
+
+type AllowAllMatcher = HashMap<String, Vec<String>>;
+type AllowByParentMatcher = HashMap<String, HashMap<String, Vec<String>>>;
+
+fn parse_allowed_versions(
+    allowed: &HashMap<String, String>,
+) -> (AllowAllMatcher, AllowByParentMatcher) {
+    let mut match_all: HashMap<String, Vec<String>> = HashMap::new();
+    let mut by_parent: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
+
+    for (selector, spec) in allowed {
+        if let Some((parent, target)) = selector.split_once('>') {
+            let parent_name = parent.trim().to_string();
+            let target_name = target.trim().to_string();
+            let ranges: Vec<String> = spec.split("||").map(|seg| seg.trim().to_string()).collect();
+            by_parent
+                .entry(parent_name)
+                .or_default()
+                .entry(target_name)
+                .or_default()
+                .extend(ranges);
+        } else {
Evidence
The config type’s documentation explicitly includes parent@range>name selectors, but the
implementation neither parses the @range portion nor compares it to the declaring parent’s
version; it keys the map by the full parent@range string while later lookups use only the parent
name.

pacquet/crates/config/src/workspace_yaml.rs[462-466]
pacquet/crates/cli/src/cli_args/peers.rs[410-447]
pacquet/crates/cli/src/cli_args/peers.rs[468-497]

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

## Issue description
`peerDependencyRules.allowedVersions` supports selectors like `parent>name` and `parent@range>name`, but the current implementation never parses/applies the `@range` portion. As a result, version-scoped parent selectors never match and the configured exception is ignored.
### Issue Context
- `workspace_yaml.rs` documents `parent@range>name` as a supported selector form.
- `peers.rs` stores the whole `parent` string (including `@range`) as the map key, but later performs lookups using only `declaring_parent.name`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[394-497]
- pacquet/crates/config/src/workspace_yaml.rs[462-466]
### Suggested fix
- Extend `parse_allowed_versions()` to parse `parent@range>peer` into `(parent_name, parent_range_opt, peer_name)`.
- In `filter_peer_issues()`, when evaluating parent-scoped rules:
- Match by `declaring_parent.name == parent_name`.
- If `parent_range_opt` is present, also require `satisfies(declaring_parent.version, parent_range_opt)` before applying the override.
- Add unit tests for `allowedVersions` with `parent@range>peer` to prevent regressions.

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


11. PATH-hijack URL opener 🐞 Bug ⛨ Security
Description
repo::open_url spawns xdg-open/open by bare executable name, so if PATH includes a
repo-controlled directory (commonly node_modules/.bin), a malicious binary can be executed instead
of the system opener. This enables arbitrary code execution when a user runs pacquet repo in an
attacker-influenced environment.
Code

pacquet/crates/cli/src/cli_args/repo.rs[R324-333]

+fn open_url(url: &str) -> miette::Result<()> {
+    let result = {
+        #[cfg(target_os = "linux")]
+        {
+            std::process::Command::new("xdg-open").arg(url).spawn()
+        }
+        #[cfg(target_os = "macos")]
+        {
+            std::process::Command::new("open").arg(url).spawn()
+        }
Evidence
The new repo command directly spawns xdg-open/open by name, which is resolved from PATH.
Elsewhere in this repo, spawning tools by absolute path / rejecting project-local PATH entries is
explicitly used to prevent repo-controlled node_modules/.bin binaries from being executed.

pacquet/crates/cli/src/cli_args/repo.rs[324-333]
pacquet/crates/cli/src/cli_args/pack_app.rs[901-926]

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 repo` launches the browser opener via `Command::new("xdg-open")` (Linux) / `Command::new("open")` (macOS), which resolves the executable via `PATH`. If `PATH` is influenced by the repo (e.g. `node_modules/.bin` ahead of system dirs), an attacker can place a malicious `xdg-open`/`open` and get code execution.
### Issue Context
This repo already treats PATH hijacking via `node_modules/.bin` as a real threat (see pack-app’s signer spawning).
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/repo.rs[324-333]
### What to change
- On macOS: spawn `/usr/bin/open` (absolute path).
- On Linux: resolve `xdg-open` to a trusted absolute path (e.g., via `which::which_all`) and **reject** any resolved path that is within the project/workspace directory (mirroring `pack_app`’s `first_signer_outside_project` pattern). If no trusted opener exists, fall back to printing the URL.
- Preferably, factor this into a shared helper (so `docs` and `repo` share a single hardened implementation), but ensure this PR at least fixes the newly introduced `repo` path.

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


12. Repo ignores version spec 🐞 Bug ≡ Correctness
Description
get_repo_url_from_registry() parses a pkg@version (or range/tag) input but then always reads the
repository field from package.latest(), so pacquet repo [email protected] can open the wrong repo
metadata compared to pnpm.
Code

pacquet/crates/cli/src/cli_args/repo.rs[R60-107]

+async fn get_repo_url_from_registry(config: &Config, raw_spec: &str) -> miette::Result<String> {
+    let parsed = parse_wanted_dependency(raw_spec);
+    let name = parsed.alias.as_deref().unwrap_or(raw_spec);
+    let bare = parsed.bare_specifier.as_deref().unwrap_or(name);
+    let (resolved_name, _range) = PackageManifest::resolve_registry_dependency(name, bare);
+
+    let http_client = ThrottledClient::for_installs(
+        &config.proxy,
+        &config.tls,
+        &config.tls_by_uri,
+        &NetworkSettings {
+            network_concurrency: config.network_concurrency,
+            fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
+            user_agent: config.user_agent.clone(),
+        },
+    )
+    .into_diagnostic()
+    .wrap_err("create the network client for repo")?;
+
+    let registries: std::collections::HashMap<String, String> =
+        config.resolved_registries().into_iter().collect();
+    let registry = pick_registry_for_package(&registries, resolved_name, Some(bare));
+
+    let outcome = fetch_full_metadata(
+        resolved_name,
+        &FetchFullMetadataOptions {
+            registry: &registry,
+            http_client: &http_client,
+            auth_headers: &config.auth_headers,
+            full_metadata: true,
+            etag: None,
+            modified: None,
+            retry_opts: RetryOpts::default(),
+        },
+    )
+    .await
+    .into_diagnostic()
+    .wrap_err_with(|| format!("fetch package info for {raw_spec}"))?;
+
+    let package = match outcome {
+        FetchFullMetadataOutcome::Modified(pkg) => *pkg,
+        FetchFullMetadataOutcome::NotModified => {
+            miette::bail!("registry returned 304 Not Modified unexpectedly")
+        }
+    };
+
+    let repository = package.latest().and_then(|version| version.other.get("repository").cloned());
+    pick_repo_url(repository.as_ref())
Evidence
The Rust implementation explicitly ignores the parsed selector (_range) and always uses
package.latest(), while the upstream pnpm path selects the version that matches the user’s spec;
the repo already has a pinned_version() helper that demonstrates the intended selection mechanism.

pacquet/crates/cli/src/cli_args/repo.rs[60-109]
pnpm11/deps/inspection/commands/src/fetchPackageInfo.ts[47-87]
pacquet/crates/registry/src/package.rs[139-163]

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 repo` accepts package specs that may include a version/range/tag, but the implementation always uses `package.latest()` when extracting the `repository` field. This breaks pnpm parity and can open the wrong repository URL.
### Issue Context
The upstream pnpm implementation resolves the package spec to a specific version (via `fetchPackageInfo` + `pickPackageFromMeta`), whereas the Rust port discards the parsed spec (`_range`) and uses `latest`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/repo.rs[60-109]
- pacquet/crates/registry/src/package.rs[139-163]
- pnpm11/deps/inspection/commands/src/fetchPackageInfo.ts[47-87]
### Implementation notes
- Use the parsed wanted dependency (`bare_specifier`) to pick the correct manifest/version from the fetched metadata (tag/version/range).
- In Rust, consider using existing helpers like `Package::pinned_version()` for ranges/versions and dist-tags for tags; fall back to `latest()` only when the user did not specify a selector.

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


13. Repo keeps query/hash 🐞 Bug ⛨ Security
Description
In repository_to_web_url()’s URL-parse fallback (used for non-hosted/self-hosted repositories),
the code rebuilds the URL from parsed.to_string() without clearing query/fragment, which can yield
malformed browse URLs and diverges from pnpm’s normalization (which clears both).
Code

pacquet/crates/cli/src/cli_args/repo.rs[R134-161]

+    let cleaned = raw_url.strip_prefix("git+").unwrap_or(raw_url);
+
+    let parsed = url::Url::parse(cleaned).ok()?;
+    if parsed.scheme() != "http" && parsed.scheme() != "https" {
+        return None;
+    }
+
+    let mut url = parsed.to_string();
+    if url.ends_with('/') {
+        url.pop();
+    }
+    if url.ends_with(".git") {
+        url.truncate(url.len() - 4);
+    }
+
+    let base_url = url;
+
+    let mut final_url = if let Some(dir) = directory {
+        format!("{base_url}/tree/HEAD/{}", dir.trim_start_matches('/'))
+    } else {
+        base_url.clone()
+    };
+
+    if let Some(fragment) = try_extract_fragment(raw_url) {
+        final_url = format!("{base_url}/tree/{fragment}");
+    }
+
+    Some(final_url)
Evidence
The Rust fallback path turns a parsed URL directly into a string and then appends path segments;
pnpm explicitly clears query and hash before doing similar normalization, so the Rust behavior can
retain attacker-controlled components and break resulting URLs.

pacquet/crates/cli/src/cli_args/repo.rs[125-162]
pnpm11/deps/inspection/commands/src/repo/index.ts[90-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
For self-hosted (non-hosted-git) repository URLs, `repository_to_web_url()` uses `url::Url::parse()` and then converts back to string without removing `.query()` / `.fragment()`. This differs from upstream pnpm, can produce invalid URLs after appending `/tree/...`, and can carry attacker-controlled query parameters into the opened browser URL.
### Issue Context
Upstream pnpm clears `search` and `hash` before trimming `.git` and appending `/tree/HEAD/<directory>`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/repo.rs[125-162]
- pnpm11/deps/inspection/commands/src/repo/index.ts[90-104]
### Implementation notes
- Keep the parsed `Url` as a `Url` object and mutate it (clear query/fragment; normalize path) instead of converting to string early.
- Mirror pnpm behavior: clear query + fragment, strip trailing slashes and `.git`, then append `/tree/HEAD/<directory>` (if present).

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


14. Peers intersections computed incorrectly 🐞 Bug ≡ Correctness
Description
merge_missing_peers() uses a candidate-version heuristic (have_common_version) and then stores
issues[0].wanted_range as the intersection string; this can misclassify complex overlapping ranges
as conflicts and emits incorrect intersections data compared to pnpm’s semver-range-intersect
logic.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R313-366]

+fn merge_missing_peers(missing: &HashMap<String, Vec<MissingPeerIssue>>) -> MergeResult {
+    let mut conflicts = Vec::new();
+    let mut intersections = HashMap::new();
+
+    for (peer_name, issues) in missing {
+        if issues.iter().all(|i| i.optional) {
+            continue;
+        }
+        if issues.len() == 1 {
+            intersections.insert(peer_name.clone(), issues[0].wanted_range.clone());
+            continue;
+        }
+        let ranges: Vec<&str> = issues.iter().map(|i| i.wanted_range.as_str()).collect();
+        let unique: HashSet<&&str> = ranges.iter().collect();
+        if unique.len() == 1 {
+            intersections.insert(peer_name.clone(), issues[0].wanted_range.clone());
+            continue;
+        }
+        let range_owned: Vec<String> = issues.iter().map(|i| i.wanted_range.clone()).collect();
+        if have_common_version(&range_owned) {
+            intersections.insert(peer_name.clone(), issues[0].wanted_range.clone());
+        } else {
+            conflicts.push(peer_name.clone());
+        }
+    }
+
+    MergeResult { conflicts, intersections }
+}
+
+struct MergeResult {
+    conflicts: Vec<String>,
+    intersections: HashMap<String, String>,
+}
+
+fn have_common_version(ranges: &[String]) -> bool {
+    if ranges.len() <= 1 {
+        return true;
+    }
+
+    let candidate_versions: Vec<String> =
+        ranges.iter().filter_map(|r| extract_candidate_version(r)).collect();
+
+    if candidate_versions.is_empty() {
+        return false;
+    }
+
+    for ver_str in &candidate_versions {
+        if ranges.iter().all(|r| satisfies(ver_str, r)) {
+            return true;
+        }
+    }
+
+    false
+}
Evidence
The Rust implementation uses a heuristic overlap check and then writes the first wanted range into
intersections, while pnpm computes an actual intersection string (or declares a conflict) using
safeIntersect(intersect(...)).

pacquet/crates/cli/src/cli_args/peers.rs[313-366]
pnpm11/installing/deps-resolver/src/mergePeers.ts[9-25]

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 Rust `peers` port does not compute true semver intersections for missing peer ranges. It uses a heuristic that can return false negatives (marking conflicts when an intersection exists) and it records the first range as the intersection even when ranges differ, making JSON output inaccurate.
### Issue Context
Upstream pnpm computes intersections using `intersect(...ranges)` (via `semver-range-intersect`) and only marks conflicts when that returns `null`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/peers.rs[313-366]
- pnpm11/installing/deps-resolver/src/mergePeers.ts[9-25]
### Implementation notes
- Replace `have_common_version()`/`extract_candidate_version()`-based overlap detection with a real range-intersection implementation (or port the upstream `safeIntersect` semantics).
- Ensure `intersections[peerName]` contains the actual intersection string (not an arbitrary input range), matching pnpm’s output contract.

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



Remediation recommended

15. Excessive parents cloning 🐞 Bug ➹ Performance ⭐ New
Description
walk_snapshot() clones the full Vec<ParentPkg> (with owned Strings) for every recorded issue
and every dependency edge pushed onto the stack, causing avoidable allocation/copy amplification on
large graphs. This can make pacquet peers significantly slower and more memory-hungry on large
lockfiles/monorepos.
Code

pacquet/crates/cli/src/cli_args/peers.rs[R394-480]

+        let mut current_parents = parents.clone();
+        current_parents.push(ParentPkg { name: pkg_name, version: pkg_version });
+
+        let base_key = key.without_peer();
+        if let Some(meta) = packages.get(&base_key)
+            && let Some(peers) = &meta.peer_dependencies
+        {
+            let snapshot = snapshots.get(&key);
+            for (peer_name, peer_range) in peers {
+                let is_optional = meta
+                    .peer_dependencies_meta
+                    .as_ref()
+                    .and_then(|meta_map| meta_map.get(peer_name))
+                    .is_some_and(|peer_meta| peer_meta.optional);
+
+                let Ok(peer_pkg_name) = peer_name.parse::<PkgName>() else { continue };
+                let resolved_ref = snapshot.and_then(|snapshot_entry| {
+                    snapshot_entry
+                        .dependencies
+                        .as_ref()
+                        .and_then(|deps| deps.get(&peer_pkg_name))
+                        .or_else(|| {
+                            snapshot_entry
+                                .optional_dependencies
+                                .as_ref()
+                                .and_then(|deps| deps.get(&peer_pkg_name))
+                        })
+                });
+
+                match resolved_ref {
+                    Some(dep_ref) => {
+                        if let Some(ver_peer) = dep_ref.ver_peer() {
+                            let version_str = ver_peer.version().to_string();
+                            if !satisfies(&version_str, peer_range) {
+                                issues.bad.entry(peer_name.clone()).or_default().push(
+                                    BadPeerIssue {
+                                        parents: current_parents.clone(),
+                                        optional: is_optional,
+                                        wanted_range: peer_range.clone(),
+                                        found_version: version_str,
+                                        resolved_from: Vec::new(),
+                                    },
+                                );
+                            }
+                        } else if let Some(link_target) = dep_ref.as_link_target() {
+                            let found_version =
+                                resolve_link_version(lockfile_dir, lockfile_dir, link_target)
+                                    .unwrap_or_else(|| format!("link:{link_target}"));
+                            if !satisfies(&found_version, peer_range) {
+                                issues.bad.entry(peer_name.clone()).or_default().push(
+                                    BadPeerIssue {
+                                        parents: current_parents.clone(),
+                                        optional: is_optional,
+                                        wanted_range: peer_range.clone(),
+                                   ...

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

🧹 Nitpick comments (2)
pacquet/crates/cli/src/cli_args/peers/tests.rs (1)

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

Replace the glob import with explicit test imports.

use super::*; violates the pacquet Rust import rule and also makes it harder to see which helpers this module is actually exercising. As per coding guidelines, "Do not use star imports inside module bodies; prefer explicit imports such as use super::{Foo, bar}." As per path instructions, pacquet/CODE_STYLE_GUIDE.md says "Imports: avoid star/glob imports inside module bodies (no use super::*;)."

🤖 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/peers/tests.rs` at line 3, Replace the glob
import in the peers tests module with explicit imports from super; update the
test module’s import statement to name only the helper types/functions it
actually uses instead of `use super::*;`, following the import style used by the
`peers/tests.rs` test code and keeping the test dependencies clear.

Sources: Coding guidelines, Path instructions

pacquet/crates/cli/src/cli_args/repo/tests.rs (1)

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

Replace the glob import with explicit imports.

use super::*; breaks the pacquet Rust import rule and makes the test surface harder to track as this module grows. As per coding guidelines, "Do not use star imports inside module bodies; prefer explicit imports such as use super::{Foo, bar}." As per path instructions, "Imports: avoid star/glob imports inside module bodies (no use super::*;)."

🤖 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/repo/tests.rs` at line 1, Replace the glob
import in the test module with explicit imports from super, listing only the
items actually used by the tests. Update the import at the top of repo tests.rs
to follow the module-body import rule and keep the test dependencies easy to
audit as the module grows.

Sources: Coding guidelines, Path instructions

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

Inline comments:
In `@pacquet/crates/cli/src/cli_args/peers.rs`:
- Around line 123-127: The importer selection in peers handling is too broad for
non-recursive runs because it expands to all workspace importers when
config.workspace_dir differs from the current directory. Update the logic around
the importer_ids assignment to use resolve_importer_id(lockfile_dir, dir) for
normal runs and only collect lockfile.importers.keys() when recursive is true,
so pacquet peers matches pnpm’s scoped behavior and avoids unrelated workspace
packages affecting the result.
- Around line 348-367: The have_common_version helper is using guessed candidate
versions instead of checking range overlap, which can misclassify open ranges as
conflicting. Update have_common_version in peers.rs to compute compatibility by
intersecting the version constraints directly rather than iterating over
extract_candidate_version results and probing with satisfies. Keep the existing
function name and call sites, but change the logic so any overlapping ranges are
recognized correctly.
- Around line 413-461: The filtering in peers handling updates
project_issues.missing and project_issues.intersections but leaves
project_issues.conflicts stale, so recompute conflicts after the pruning step in
the same loop. Update the logic around the issues.values_mut() processing in
peers.rs to rebuild conflicts from the filtered missing map before returning,
ensuring the JSON and text outputs stay consistent when ignoreMissing removes
all missing peers.
- Around line 81-84: The no-lockfile branch in peers handling currently prints
plain text via the peers command path, which breaks the machine-readable
contract for --json. Update the logic in the peers-related argument handling so
it checks the JSON output mode before emitting the “No lockfile found” message,
and in that case return a valid JSON shape instead of plain text. Keep the
behavior aligned with pnpm’s output contract by using the existing peers command
flow and its JSON output handling rather than unconditional println output.
- Around line 487-493: Scoped peer selectors are being parsed incorrectly
because `split_once('@')` in the `peers.rs` selector handling treats the leading
scope marker as the version separator, so `target_name` can become empty and
`allowedVersions` won’t match. Update the selector parsing logic around
`target_name` to ignore a leading scoped `@scope/` prefix and only split on the
version delimiter after the package name, so `match_all.entry(target_name)`
receives the correct scoped package key.

In `@pacquet/crates/cli/src/cli_args/peers/tests.rs`:
- Around line 214-232: Add a regression test for filter_peer_issues that
exercises parent-scoped allowedVersions, since the existing
parse_allowed_versions tests only cover parsing and not enforcement. Use
BadPeerIssue with parents set to match a rule like `@foo/bar`>react, then assert
filter_peer_issues keeps or filters the peer issue accordingly when the scoped
rule is present. Reuse the existing parse_allowed_versions and
filter_peer_issues symbols so the test verifies the behavior contract
end-to-end.

In `@pacquet/crates/cli/src/cli_args/repo.rs`:
- Around line 342-351: Add a safety comment for the unsafe ShellExecuteW call in
repo.rs explaining why the null pointers and the NUL-terminated url_wide buffer
satisfy the Windows API contract. Update the unsafe block around ShellExecuteW
to document the invariants being upheld, using the ShellExecuteW invocation and
url_wide construction as the key symbols to locate the change.
- Around line 60-108: get_repo_url_from_registry currently ignores the requested
version/range and always reads repository info from package.latest(), which can
point to the wrong release. Use the parsed spec from parse_wanted_dependency and
the resolved package data to select the matching packument entry for the
requested version before calling pick_repo_url. Update the repository lookup
logic in get_repo_url_from_registry so repo [email protected] resolves metadata from the
requested release instead of dist-tags.latest.
- Around line 211-212: The repository URL handling in repositoryToWebUrl is
missing common git forms, so valid git:// and scp-style git@host:owner/repo.git
inputs can fall through to Url::parse and trigger ERR_PNPM_NO_REPO_URL. Update
the early hosted-URL detection around try_hosted_url so it recognizes git:// as
well as scp-style git@ URLs, and route those cases through the hosted URL
conversion path before any generic parsing fallback.

In `@pacquet/crates/cli/src/cli_args/repo/tests.rs`:
- Around line 80-82: The monorepo URL expectations in the repository URL tests
are out of sync with the current repository_to_web_url behavior, which formats
directory links with HEAD instead of master. Update the assertions in the
relevant test cases in tests.rs to match the existing contract from
repository_to_web_url, or if master is the intended public shape, adjust
repository_to_web_url first and then keep the tests aligned. Use
repository_to_web_url and the monorepo URL test names as the anchor points when
updating both sides.

In `@pacquet/crates/cli/tests/repo.rs`:
- Around line 25-32: The repo CLI test is only matching a few substrings, so it
does not fully protect the public stderr contract for RepoError::NoRepoUrlLocal.
Tighten the assertion in the repo test to verify the complete expected guidance
sentence together with ERR_PNPM_NO_REPO_URL, using the stable diagnostic text
defined by the repo command implementation so wording regressions are caught.
Keep the check centered on the existing stderr assertion in the repo test and
update it to compare against the full message rather than partial fragments.

---

Nitpick comments:
In `@pacquet/crates/cli/src/cli_args/peers/tests.rs`:
- Line 3: Replace the glob import in the peers tests module with explicit
imports from super; update the test module’s import statement to name only the
helper types/functions it actually uses instead of `use super::*;`, following
the import style used by the `peers/tests.rs` test code and keeping the test
dependencies clear.

In `@pacquet/crates/cli/src/cli_args/repo/tests.rs`:
- Line 1: Replace the glob import in the test module with explicit imports from
super, listing only the items actually used by the tests. Update the import at
the top of repo tests.rs to follow the module-body import rule and keep the test
dependencies easy to audit as the module grows.
🪄 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: 4953f9c5-fb51-487b-a1ca-f22678b29ff0

📥 Commits

Reviewing files that changed from the base of the PR and between c00400d and c32753a.

📒 Files selected for processing (9)
  • 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/peers.rs
  • pacquet/crates/cli/src/cli_args/peers/tests.rs
  • pacquet/crates/cli/src/cli_args/repo.rs
  • pacquet/crates/cli/src/cli_args/repo/tests.rs
  • pacquet/crates/cli/tests/repo.rs

Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
Comment thread pacquet/crates/cli/tests/repo.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 3b2fe5e43cad

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.103 ± 0.115 3.971 4.370 1.91 ± 0.12
pacquet@main 3.994 ± 0.094 3.879 4.180 1.86 ± 0.11
pnpr@HEAD 2.154 ± 0.111 2.002 2.297 1.00 ± 0.08
pnpr@main 2.149 ± 0.122 2.039 2.370 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.1026432560799995,
      "stddev": 0.1149770292116461,
      "median": 4.10631621678,
      "user": 3.9372966199999992,
      "system": 3.52772282,
      "min": 3.97104798428,
      "max": 4.37024450528,
      "times": [
        4.11751452228,
        3.97104798428,
        4.37024450528,
        4.13487992628,
        4.15035768928,
        4.09511791128,
        3.99008246228,
        4.06305523928,
        4.13666304528,
        3.99746927528
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.9944649765799993,
      "stddev": 0.09354125285277778,
      "median": 3.98057488178,
      "user": 3.8571911199999995,
      "system": 3.4629822199999993,
      "min": 3.8794575502799997,
      "max": 4.18020569728,
      "times": [
        4.10684155628,
        3.94292558728,
        4.18020569728,
        4.0048372922799995,
        3.96755431628,
        4.03862601428,
        3.92984026628,
        3.9935954472799997,
        3.8794575502799997,
        3.90076603828
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.15426637218,
      "stddev": 0.1111824238624308,
      "median": 2.1512984042800003,
      "user": 2.66735922,
      "system": 3.029309819999999,
      "min": 2.00228606728,
      "max": 2.29737109728,
      "times": [
        2.27862033128,
        2.0198374702799997,
        2.17690797328,
        2.00228606728,
        2.2269773422799997,
        2.26889790528,
        2.09742272628,
        2.12568883528,
        2.29737109728,
        2.04865397328
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.14867900068,
      "stddev": 0.12219267166575039,
      "median": 2.0987434497799997,
      "user": 2.6204900199999996,
      "system": 3.0210373199999987,
      "min": 2.03868916728,
      "max": 2.36972192128,
      "times": [
        2.36972192128,
        2.09926638428,
        2.13606108728,
        2.07823630428,
        2.03868916728,
        2.23868235128,
        2.33425158528,
        2.04305081028,
        2.0506098802799997,
        2.09822051528
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 641.8 ± 7.4 632.7 658.2 1.00
pacquet@main 643.4 ± 12.1 626.3 663.7 1.00 ± 0.02
pnpr@HEAD 690.5 ± 13.0 669.9 714.2 1.08 ± 0.02
pnpr@main 694.3 ± 13.7 671.3 717.7 1.08 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6418296312999999,
      "stddev": 0.0074453254742661065,
      "median": 0.6402845794,
      "user": 0.3987176,
      "system": 1.3094685,
      "min": 0.6326658929,
      "max": 0.6581653069,
      "times": [
        0.6465889569000001,
        0.6326658929,
        0.6358595519,
        0.6395293569,
        0.6344775079,
        0.6408564659,
        0.6581653069,
        0.6397126929,
        0.6462222429,
        0.6442183379
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6433761194,
      "stddev": 0.01206172991836948,
      "median": 0.6446973679000001,
      "user": 0.3736731,
      "system": 1.3237291,
      "min": 0.6262782029,
      "max": 0.6637101829000001,
      "times": [
        0.6537949729,
        0.6431698579,
        0.6462248779,
        0.6324522839,
        0.6539598419,
        0.6302408779,
        0.6356808449,
        0.6637101829000001,
        0.6482492509000001,
        0.6262782029
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6905066708999998,
      "stddev": 0.012980619499586022,
      "median": 0.6887734154,
      "user": 0.3978862,
      "system": 1.3500695999999999,
      "min": 0.6699083249000001,
      "max": 0.7142080889,
      "times": [
        0.6699083249000001,
        0.6810812149000001,
        0.6927240019,
        0.6857857649,
        0.6937681529,
        0.7081441689,
        0.6912811609,
        0.7142080889,
        0.6819001609,
        0.6862656699
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.6943397882,
      "stddev": 0.013737114966279853,
      "median": 0.6961842844,
      "user": 0.38929959999999997,
      "system": 1.3468037,
      "min": 0.6712848379,
      "max": 0.7177091869000001,
      "times": [
        0.7074730909,
        0.7024334369,
        0.6873981689,
        0.6997372519,
        0.6943856749,
        0.6849063079000001,
        0.6979828939,
        0.7177091869000001,
        0.6712848379,
        0.6800870319
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.247 ± 0.046 4.179 4.321 1.95 ± 0.14
pacquet@main 4.245 ± 0.048 4.148 4.305 1.95 ± 0.14
pnpr@HEAD 2.201 ± 0.109 2.029 2.346 1.01 ± 0.09
pnpr@main 2.175 ± 0.150 1.999 2.464 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.24688452044,
      "stddev": 0.04612292920093075,
      "median": 4.23965137084,
      "user": 3.7916856399999994,
      "system": 3.3864395000000003,
      "min": 4.178913361839999,
      "max": 4.321270783839999,
      "times": [
        4.25409640884,
        4.21106058084,
        4.178913361839999,
        4.22293095184,
        4.20294083384,
        4.26833124884,
        4.22520633284,
        4.321270783839999,
        4.300505225839999,
        4.2835894758399995
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.245366665939999,
      "stddev": 0.048284453433652945,
      "median": 4.246969583339999,
      "user": 3.760251939999999,
      "system": 3.3715996000000006,
      "min": 4.14842546584,
      "max": 4.3052041678399995,
      "times": [
        4.14842546584,
        4.20041577584,
        4.253455091839999,
        4.23513856784,
        4.29552725384,
        4.2404840748399995,
        4.220762114839999,
        4.295168674839999,
        4.3052041678399995,
        4.25908547184
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.2005868141400002,
      "stddev": 0.10893745036371125,
      "median": 2.1688670093400004,
      "user": 2.5348892399999996,
      "system": 2.9114792,
      "min": 2.02882994084,
      "max": 2.3459643478400003,
      "times": [
        2.3315410998400004,
        2.12445582484,
        2.18704026384,
        2.32947481384,
        2.1506937548400002,
        2.25485730884,
        2.3459643478400003,
        2.12334578484,
        2.1296650018400003,
        2.02882994084
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.1746917320400003,
      "stddev": 0.15045631291427558,
      "median": 2.1186306108400004,
      "user": 2.49069054,
      "system": 2.9111895,
      "min": 1.99920441284,
      "max": 2.46448384284,
      "times": [
        2.46448384284,
        2.33685663284,
        2.1200915948400003,
        2.09469761784,
        2.03376703184,
        2.0866606778400003,
        2.16983076184,
        2.11716962684,
        1.99920441284,
        2.32415512084
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.344 ± 0.017 1.323 1.375 2.02 ± 0.14
pacquet@main 1.418 ± 0.081 1.381 1.647 2.13 ± 0.19
pnpr@HEAD 0.673 ± 0.030 0.655 0.757 1.01 ± 0.08
pnpr@main 0.665 ± 0.046 0.637 0.793 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3436516506599998,
      "stddev": 0.01688786564828589,
      "median": 1.3412441822599999,
      "user": 1.35416344,
      "system": 1.6796418999999996,
      "min": 1.32280103026,
      "max": 1.37471399426,
      "times": [
        1.36656953226,
        1.3414478452599998,
        1.3319684862599999,
        1.32280103026,
        1.33350022526,
        1.3507868512599999,
        1.32572799426,
        1.34796002826,
        1.34104051926,
        1.37471399426
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.4176664801599999,
      "stddev": 0.0811547993927226,
      "median": 1.39281362976,
      "user": 1.3235602400000002,
      "system": 1.7729449,
      "min": 1.38105236526,
      "max": 1.6469071742599999,
      "times": [
        1.4038620762599998,
        1.3957332242599998,
        1.6469071742599999,
        1.38989403526,
        1.39717135726,
        1.38224564626,
        1.38311302526,
        1.3856020412599999,
        1.38105236526,
        1.4110838562599999
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.67318557846,
      "stddev": 0.029774927305360112,
      "median": 0.6645808632600001,
      "user": 0.34621324000000003,
      "system": 1.2775877999999998,
      "min": 0.6545232012600001,
      "max": 0.7565059712600001,
      "times": [
        0.66281398426,
        0.7565059712600001,
        0.6650184972600001,
        0.6545232012600001,
        0.6688464672600001,
        0.65914030926,
        0.67469504826,
        0.6608629142600001,
        0.66414322926,
        0.6653061622600001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.6653781855600001,
      "stddev": 0.046230511358964305,
      "median": 0.6519468202600001,
      "user": 0.32816383999999993,
      "system": 1.2735447999999998,
      "min": 0.63702099026,
      "max": 0.79334967426,
      "times": [
        0.6578520022600001,
        0.6753953782600001,
        0.65519689526,
        0.65304174226,
        0.63702099026,
        0.65085189826,
        0.6444967692600001,
        0.6463458872600001,
        0.64023061826,
        0.79334967426
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.031 ± 0.054 2.981 3.152 4.55 ± 0.15
pacquet@main 2.991 ± 0.029 2.954 3.049 4.49 ± 0.13
pnpr@HEAD 0.678 ± 0.010 0.666 0.700 1.02 ± 0.03
pnpr@main 0.666 ± 0.019 0.640 0.709 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.0307918950600006,
      "stddev": 0.054140963448469026,
      "median": 3.02030452956,
      "user": 1.8255780600000002,
      "system": 1.9535120600000002,
      "min": 2.98116995206,
      "max": 3.15214051906,
      "times": [
        3.01777504006,
        2.98387218106,
        3.0956177730600003,
        2.9885874120600002,
        3.0228340190600003,
        3.00296413606,
        3.0311607300600003,
        3.03179718806,
        3.15214051906,
        2.98116995206
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.9913459187599996,
      "stddev": 0.02940922733857478,
      "median": 2.9901477080600003,
      "user": 1.76898776,
      "system": 1.95680276,
      "min": 2.9535756930600003,
      "max": 3.04884521606,
      "times": [
        2.9984864910600004,
        2.9535756930600003,
        2.98239461006,
        2.9979008060600005,
        2.9682287410600003,
        2.9731077310600003,
        2.9641679570600004,
        3.02564302206,
        3.04884521606,
        3.00110892006
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6784901436599999,
      "stddev": 0.00974835386847517,
      "median": 0.67698023656,
      "user": 0.35197736,
      "system": 1.30925856,
      "min": 0.6660734740600001,
      "max": 0.6999893850600001,
      "times": [
        0.68238596706,
        0.6999893850600001,
        0.67392752906,
        0.68003294406,
        0.6722761860600001,
        0.6660734740600001,
        0.68499529506,
        0.67254989606,
        0.67021146706,
        0.68245929306
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.66630397836,
      "stddev": 0.018785378060794458,
      "median": 0.66783562906,
      "user": 0.33671006000000003,
      "system": 1.26682856,
      "min": 0.63996318206,
      "max": 0.70943153006,
      "times": [
        0.65570082306,
        0.65152835406,
        0.63996318206,
        0.66825290806,
        0.66741835006,
        0.67677921006,
        0.67128257306,
        0.70943153006,
        0.65417784706,
        0.6685050060600001
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 6.848 ± 0.083 6.731 6.980 1.38 ± 0.03
pacquet@main 6.830 ± 0.073 6.732 6.951 1.38 ± 0.03
pnpr@HEAD 4.958 ± 0.107 4.810 5.124 1.00
pnpr@main 5.042 ± 0.126 4.890 5.314 1.02 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 6.84823525136,
      "stddev": 0.08304111846384664,
      "median": 6.8395724951600005,
      "user": 4.077625920000001,
      "system": 3.75876502,
      "min": 6.73104227666,
      "max": 6.980230205660001,
      "times": [
        6.73104227666,
        6.769246933660001,
        6.96421275566,
        6.77591826266,
        6.980230205660001,
        6.83512221466,
        6.84402277566,
        6.84585672666,
        6.81844363166,
        6.9182567306600005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 6.82974412926,
      "stddev": 0.07301540368957164,
      "median": 6.83981736866,
      "user": 4.009920320000001,
      "system": 3.76785652,
      "min": 6.73155264966,
      "max": 6.9507327956600005,
      "times": [
        6.84431590566,
        6.83531883166,
        6.7547527056600005,
        6.88618853866,
        6.7324057256600005,
        6.811858490660001,
        6.9507327956600005,
        6.73155264966,
        6.894247759660001,
        6.85606788966
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 4.958437763260001,
      "stddev": 0.10681104414778171,
      "median": 4.93626846916,
      "user": 2.7858786199999996,
      "system": 3.23801792,
      "min": 4.81003980066,
      "max": 5.124106788660001,
      "times": [
        4.90868847866,
        4.824267738660001,
        5.10369643666,
        4.81003980066,
        4.9095016216600005,
        5.124106788660001,
        4.96207330066,
        5.0025579676600005,
        4.91046363766,
        5.02898186166
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 5.041732223160001,
      "stddev": 0.1262900080333376,
      "median": 5.00519871866,
      "user": 2.76320882,
      "system": 3.2344974199999994,
      "min": 4.89011197966,
      "max": 5.31352587666,
      "times": [
        4.927660358660001,
        4.89011197966,
        4.963461955660001,
        5.158203165660001,
        4.982383916660001,
        5.04185515166,
        5.00988921166,
        5.31352587666,
        5.12972238966,
        5.00050822566
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12706
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,246.88 ms
(-2.47%)Baseline: 4,354.58 ms
5,225.50 ms
(81.27%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,030.79 ms
(-0.48%)Baseline: 3,045.46 ms
3,654.55 ms
(82.93%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,343.65 ms
(-0.70%)Baseline: 1,353.08 ms
1,623.70 ms
(82.75%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,102.64 ms
(-2.40%)Baseline: 4,203.49 ms
5,044.18 ms
(81.33%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
6,848.24 ms
(-1.80%)Baseline: 6,973.61 ms
8,368.33 ms
(81.84%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
641.83 ms
(+3.28%)Baseline: 621.47 ms
745.76 ms
(86.06%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12706
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
2,200.59 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
678.49 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
673.19 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,154.27 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
4,958.44 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
690.51 ms
🐰 View full continuous benchmarking report in Bencher

Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pacquet/crates/cli/src/cli_args/peers.rs (2)

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

Don’t use the first range as the merged intersection.

When multiple missing-peer ranges overlap, this stores issues[0].wanted_range, which can be broader than the actual common constraint. For example, >=1.0.0 <3.0.0 plus <2.0.0 should not render/report >=1.0.0 <3.0.0 as the safe intersection. Compute the real intersection or keep/render all contributing ranges. As per path instructions, peer/range behavior and output shape must mirror pnpm.

🤖 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/peers.rs` around lines 331 - 334, The overlap
handling in the peer range merge logic is using the first entry’s wanted range
as the combined result, which can overstate the actual safe intersection. Update
the intersection path in the code around have_common_version and
intersections.insert so it computes the real merged constraint from all issues,
or preserves all contributing ranges for later rendering, instead of reusing
issues[0].wanted_range. Make sure the resulting peer/range output shape stays
aligned with pnpm’s behavior.

Source: Path instructions


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

Resolve linked peer versions before marking them bad.

This path reports every link: peer as unsatisfied, even when a workspace-linked package’s manifest version satisfies peer_range. Resolve the link target/importer version before creating BadPeerIssue, or mirror pnpm’s upstream peer-issue source for linked peers. As per path instructions, pacquet behavior and output must match pnpm exactly.

🤖 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/peers.rs` around lines 238 - 245, The
linked-peer branch in peers.rs is treating every dep_ref.as_link_target() case
as unsatisfied, even when the workspace-linked package’s manifest version
actually satisfies peer_range. Update the peer resolution flow to inspect the
link target/importer package version before pushing a BadPeerIssue, and only
record it as bad when that resolved version truly fails the range. Align the
logic in this branch with pnpm’s upstream peer-issue handling for linked peers,
using the existing BadPeerIssue construction path as the location to adjust.

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.

Outside diff comments:
In `@pacquet/crates/cli/src/cli_args/peers.rs`:
- Around line 331-334: The overlap handling in the peer range merge logic is
using the first entry’s wanted range as the combined result, which can overstate
the actual safe intersection. Update the intersection path in the code around
have_common_version and intersections.insert so it computes the real merged
constraint from all issues, or preserves all contributing ranges for later
rendering, instead of reusing issues[0].wanted_range. Make sure the resulting
peer/range output shape stays aligned with pnpm’s behavior.
- Around line 238-245: The linked-peer branch in peers.rs is treating every
dep_ref.as_link_target() case as unsatisfied, even when the workspace-linked
package’s manifest version actually satisfies peer_range. Update the peer
resolution flow to inspect the link target/importer package version before
pushing a BadPeerIssue, and only record it as bad when that resolved version
truly fails the range. Align the logic in this branch with pnpm’s upstream
peer-issue handling for linked peers, using the existing BadPeerIssue
construction path as the location to adjust.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4960198b-93fb-482c-b536-7b3b304a4e1d

📥 Commits

Reviewing files that changed from the base of the PR and between c32753a and f80614a.

📒 Files selected for processing (1)
  • pacquet/crates/cli/src/cli_args/peers.rs

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

Copy link
Copy Markdown

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

@codecov-commenter

codecov-commenter commented Jun 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 35.46441% with 535 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.98%. Comparing base (ce5d5a5) to head (3b2fe5e).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/peers.rs 35.98% 523 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch_query.rs 0.00% 11 Missing ⚠️
pacquet/crates/cli/src/cli_args/dispatch.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12706      +/-   ##
==========================================
- Coverage   85.62%   84.98%   -0.64%     
==========================================
  Files         413      414       +1     
  Lines       64343    65172     +829     
==========================================
+ Hits        55093    55387     +294     
- Misses       9250     9785     +535     

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 085d14e

Comment thread pacquet/crates/cli/src/cli_args/repo.rs Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 085d14e

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 88a1f83

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 88a1f83

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 61854d2

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 51aca94

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 51aca94

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 849eb56

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 849eb56

kairosci and others added 10 commits July 4, 2026 11:25
…n peers.rs

Rename peers.rs violated two perfectionist lints:
- import_granularity: split use statements merged into one
- derive_ordering: Default must precede Clone in derive list
…aw_string in peers

- rename single-letter closure params |r| -> |range|, |s| -> |seg|
- use raw string literals for expected output in tests
Make the peers command deterministic and behaviorally identical to the
TypeScript CLI:

- Use BTreeMap for project, bad, missing, and intersection maps so JSON
  key order and rendered section order no longer vary between runs.
- Share one visited set across importers and skip already-visited
  packages before evaluating their peers, matching pnpm's lockfile
  walker, which walks each package exactly once.
- Resolve importer link: targets relative to the importer directory
  instead of the lockfile root; previously any link target from a
  non-root workspace package escaped the traversal guard and fell back
  to version 0.0.0.
- Treat a missing lockfile as empty issues so the text mode prints
  "No peer dependency issues found" like pnpm, and emit per-importer
  empty entries when the lockfile has no packages section.
- Use bright color variants matching chalk's yellowBright/cyanBright,
  dedupe packages per wanted range, and end the report with a newline.
- Return PeersOutcome from PeersArgs::run and map it to the exit code
  in the dispatch layer, following the OutdatedOutcome/AuditOutcome
  pattern (clippy::exit never fires inside impl methods, so an expect
  attribute there is unfulfilled).
- Replace the star import in the unit tests with explicit imports and
  fix a dylint raw-string warning.
Copilot AI review requested due to automatic review settings July 4, 2026 10:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

Copy link
Copy Markdown

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

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

qodo-free-for-open-source-projects Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

…Missing

filterPeerDependencyIssues pruned the missing and intersections maps but
passed conflicts through unchanged, so a missing peer excluded via
pnpm.peerDependencyRules.ignoreMissing could still surface as a conflict
in the JSON output while the text output reported no issues. Keep only
the conflicts whose peer survived the missing filter.

This matches the pacquet peers command, which already recomputes
conflicts from the filtered missing map.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3b2fe5e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3b2fe5e

@zkochan
zkochan merged commit ebb4096 into pnpm:main Jul 4, 2026
34 checks passed
@kairosci
kairosci deleted the paquet-peers branch July 4, 2026 11:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants