Skip to content

feat(pacquet): make list and why feature complete with the TypeScript CLI - #13178

Merged
zkochan merged 9 commits into
mainfrom
rust-why
Jul 20, 2026
Merged

zkochan merged 9 commits into
mainfrom
rust-why

Conversation

@zkochan

@zkochan zkochan commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Makes pacquet's pnpm list (ls/ll/la) and pnpm why feature complete and behaviorally identical to the TypeScript CLI. The TypeScript side is untouched — it is the source of truth here; this PR closes the Rust side of the gap and ports the corresponding test suites.

New shared tree-builder. A new cli_args/deps_tree module ports @pnpm/deps.inspection.tree-builder: a lockfile-backed dependency graph (importer + package nodes, workspace-link resolution, --only-projects edge filtering), a materializer with per-(node, depth) subtree deduplication ([deduped] markers and dedupedDependenciesCount, bounding output to O(N)), a circular-reference post-pass, dev/prod dep-type detection (port of @pnpm/lockfile.detect-dep-types), and per-node metadata resolution: absolute filesystem paths (global-virtual-store aware, resolving through parent node_modules symlinks), reconstructed registry tarball URLs for resolved, peer/skipped flags, link: version rewriting, and peer-variant hashes.

pnpm list. Rewritten on the tree-builder with byte-identical renderers: the legend, cyan group headers, the N packages[ in M projects] summary, peer/ skipped annotations, red peer#hash (N variations) suffixes, bold search matches with subtree pruning, --long manifest details (description/repository/homepage/path; JSON adds license/author), sorted JSON keyed by alias with from/version/resolved/path, and flat deduplicated parseable output. New surface matching TS: --only-projects, --find-by (finders exported by .pnpmfile.cjs, evaluated through the pnpmfile Node worker via a new finder protocol), version-range search queries (pnpm ls "foo@^2"), --depth for globally installed packages (with the ERR_PNPM_GLOBAL_LS_DEPTH_NOT_SUPPORTED guard and install-group narrowing), and shared-lockfile recursive rendering in a single pass (one legend, cross-project dedup, combined summary). The pacquet-only "No lockfile found" messages are gone — a lockfile-less project renders the root header like TS does.

pnpm why. Rebuilt on the same graph: --json/--parseable/--long output, -P/-D/--no-optional include filters, --find-by, workspace project names/versions read from importer manifests, (dependencies)-style dependency-field annotations on importer leaves, [circular]/[deduped] markers, peer-variant hashes, semver-ordered results, the Found N versions[, M instances] of <pkg> summary, archy-style tree rendering, and current-lockfile preference. Error message/code now match TS (ERR_PNPM_MISSING_PACKAGE_NAME: `pnpm why` requires the package name or --find-by=<finder-name>). Search roots are now package nodes only, matching TS.

Tests. Ported one-to-one and enumerated in pnpm/plans/TEST_PORTING.md (new "pnpm list / pnpm why (deps/inspection)" section): the 24 getTree materialization tests, the packages-searcher and getPkgInfo tests, all 21 renderDependentsTree renderer tests, the renderer-level list tests, and the CLI-level listing/why/list.ts suites — exact tree output including legend and summary, --lockfile-only, the JSON private field, file: deps, recursive rendering, finders end to end (including finder manifest reads from the content-addressable store), and global-virtual-store paths. 62 unit + 38 integration tests pass; regression checks were done per the "test the tests" convention (breaking dedup, the missing-package fallback, version-range matching, and the summary each made the corresponding tests fail).

Not ported, with reasons recorded in the plan: the upstream test.skip-ped skipped-optional-deps listing test, the nameFormatter group of buildDependentsTree.test.ts (no pnpm command passes a nameFormatter; the displayName rendering it feeds is covered), and manyDeps.ts (its OOM guard is the dedup cache, pinned directly).

Squash Commit Body

Rebuild pacquet's list/why on a shared deps_tree module that ports the
TypeScript deps.inspection tree-builder: a lockfile-backed dependency
graph, materialization with subtree deduplication and circular-reference
marking, dev/prod dep-type detection, absolute package paths (global
virtual store aware), reconstructed tarball URLs, peer/skipped flags,
and peer-variant hashes. The renderers now match the TypeScript output
byte for byte: legend, cyan group headers, package-count summary, long
manifest details, JSON field order, and parseable dedup.

New command surface, matching the TypeScript CLI: list gains
--only-projects, --find-by (finders exported by .pnpmfile.cjs, evaluated
through the pnpmfile Node worker via a new finder protocol), search by
version range, --depth for globally installed packages (with the
GLOBAL_LS_DEPTH_NOT_SUPPORTED guard), and shared-lockfile single-pass
recursive rendering. why gains --json/--parseable/--long, the
prod/dev/no-optional include filters, --find-by, workspace project
names read from importer manifests, dependency-field annotations,
circular/deduped markers, peer-variant hashes, semver-ordered results,
and the Found-N-versions summary. why now prefers the current lockfile
over the wanted one, and error codes/messages match the TypeScript CLI
(MISSING_PACKAGE_NAME, FINDER_NOT_FOUND).

Ported the upstream test suites: the 24 getTree materialization tests,
the packages-searcher and getPkgInfo tests, all 21 renderDependentsTree
renderer tests, the renderer-level list tests, and the CLI-level
listing/why/list.ts suites (exact tree output, lockfile-only, private
JSON field, file: deps, recursive rendering, finders end to end, finder
manifest reads from the store, and global-virtual-store paths). The
ported coverage is enumerated in pnpm/plans/TEST_PORTING.md.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
    (Rust-only by design: the TypeScript CLI already has all of this
    behavior and is unchanged.)
  • 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. (No docs changes: the flags and
    output formats are already documented for the TypeScript CLI.)

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


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Summary by CodeRabbit

  • New Features
    • pnpm list and pnpm why are now more feature-complete and behaviorally aligned, including --only-projects and --find-by finder support with version-range searching.
    • Expanded output across tree/JSON/parseable and --long, with richer peer, deduped, and circular annotations plus “Found …” summaries.
  • Bug Fixes
    • Improved consistency for global installs and recursive workspace rendering, and clearer pnpm why validation messaging.
  • Tests
    • Added extensive integration and unit test coverage for search, rendering, depth/caching, and finder results.
  • Documentation
    • Updated porting notes for pnpm list / pnpm why.

zkochan added 2 commits July 20, 2026 17:34
… CLI

Rebuild pacquet's list/why on a shared deps_tree module that ports the
TypeScript deps.inspection tree-builder: a lockfile-backed dependency
graph, materialization with subtree deduplication and circular-reference
marking, dev/prod dep-type detection, absolute package paths (global
virtual store aware), reconstructed tarball URLs, peer/skipped flags,
and peer-variant hashes. The renderers now match the TypeScript output
byte for byte: legend, cyan group headers, package-count summary, long
manifest details, JSON field order, and parseable dedup.

New command surface, matching the TypeScript CLI: list gains
--only-projects, --find-by (finders exported by .pnpmfile.cjs, evaluated
through the pnpmfile Node worker via a new finder protocol), search by
version range, --depth for globally installed packages (with the
GLOBAL_LS_DEPTH_NOT_SUPPORTED guard), and shared-lockfile single-pass
recursive rendering. why gains --json/--parseable/--long, the
prod/dev/no-optional include filters, --find-by, workspace project
names read from importer manifests, dependency-field annotations,
circular/deduped markers, peer-variant hashes, semver-ordered results,
and the Found-N-versions summary. why now prefers the current lockfile
over the wanted one, and error codes/messages match the TypeScript CLI
(MISSING_PACKAGE_NAME, FINDER_NOT_FOUND).

Ported the upstream test suites: the 24 getTree materialization tests,
the packages-searcher and getPkgInfo tests, all 21 renderDependentsTree
renderer tests, the renderer-level list tests, and the CLI-level
listing/why/list.ts suites (exact tree output, lockfile-only, private
JSON field, file: deps, recursive rendering, finders end to end, finder
manifest reads from the store, and global-virtual-store paths). The
ported coverage is enumerated in pnpm/plans/TEST_PORTING.md.
Copilot AI review requested due to automatic review settings July 20, 2026 15:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Jul 20, 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

The Rust CLI now shares dependency-tree infrastructure between pnpm list and pnpm why, including graph construction, search, finder hooks, rendering, depth handling, peer/deduplication markers, and expanded parity tests.

Changes

Dependency inspection infrastructure

Layer / File(s) Summary
Shared graph and tree materialization
pnpm/crates/cli/src/cli_args/deps_tree/*
Adds lockfile-backed graph construction, package metadata resolution, dependency classification, depth-limited materialization, caching, circular detection, peer filtering, and query matching.
Finder hook integration
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs, pnpm/crates/hooks/src/*
Adds pnpmfile finder discovery and execution through Node worker IPC, including manifest contexts and verdict handling.
Reverse dependent rendering
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs, pnpm/crates/cli/src/cli_args/why/render.rs
Adds reverse traversal and tree, JSON, and parseable output with depth limits, metadata, markers, and version summaries.

Command integration

Layer / File(s) Summary
List pipeline and formats
pnpm/crates/cli/src/cli_args/list*, pnpm/crates/global/*
Refactors list onto the shared pipeline, adds --only-projects and --find-by, supports global installations, and renders tree, JSON, and parseable output.
Why pipeline and validation
pnpm/crates/cli/src/cli_args/why*, pnpm/crates/cli/src/cli_args/dispatch_query.rs
Expands why options and routes execution through shared graph, search, finder, and dependent-rendering logic.
Parity tests and tracking
pnpm/crates/cli/tests/*, .changeset/list-why-parity.md, pnpm/plans/TEST_PORTING.md
Adds list/why integration coverage and documents ported and unported upstream test areas.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • pnpm/pnpm#13030 — Both changes modify the WhyArgs::run execution path and workspace/lockfile handling.

Suggested labels: product: pacquet

Suggested reviewers: copilot

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

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

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Make pnpm list and pnpm why match TypeScript CLI via shared deps-tree builder

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add shared lockfile-backed deps-tree builder used by list and why.
• Rebuild pnpm list/pnpm why rendering and CLI flags for TS parity.
• Port upstream test suites for tree builder, renderers, and CLI behavior.
Diagram

graph TD
  A["pnpm CLI"] --> B["list.rs"] --> D["deps_tree module"]
  A --> C["why.rs"] --> D
  D --> E[("pnpm-lock.yaml")]
  D --> F["modules.yaml"]
  D --> G["pnpmfile Node worker"]
  subgraph Legend
    direction LR
    _cli["CLI cmd"] ~~~ _mod["Rust module"] ~~~ _db[("Lock/manifest")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Incremental patch existing list/why implementations
  • ➕ Smaller diffs per change
  • ➕ Lower short-term review load
  • ➖ Harder to guarantee byte-identical TS parity across many features
  • ➖ Duplicate logic between list and why likely persists
  • ➖ Higher long-term maintenance cost due to drift risk
2. Generate golden outputs from TS in CI (snapshot testing)
  • ➕ Stronger parity guarantee across platforms
  • ➕ Less need to port upstream tests verbatim
  • ➖ Adds dependency on TS runtime/tooling in Rust CI
  • ➖ More complex fixture management and cross-platform normalization
  • ➖ Does not replace need for Rust-side unit tests for edge cases
3. Expose tree-builder as a library crate with stable API
  • ➕ Clear separation between graph/materialization and command-specific renderers
  • ➕ Easier reuse for future inspection commands
  • ➖ Extra public API surface and semver commitments
  • ➖ May slow iteration until the API stabilizes

Recommendation: The PR’s approach (shared deps_tree module + direct ports of upstream renderers/tests) is the best path to enforce behavioral and output parity with the TypeScript CLI while minimizing future drift. Incremental patching would likely reintroduce divergence, and TS-driven snapshot CI adds significant tooling complexity; consider library-crate extraction later once the API proves stable.

Files changed (30) +6194 / -2080

Enhancement (19) +3683 / -1465
deps_tree.rsIntroduce shared deps-tree types and peer-variant hashing +96/-0

Introduce shared deps-tree types and peer-variant hashing

• Defines 'TreeNodeId' for importer/package nodes, 'DependencyNode' as the forward tree shape, and a 'peers_suffix_hash' helper matching TS ordering/serialization expectations.

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

build.rsAdd tree-build orchestration (lockfiles/modules/env) for list/why +477/-0

Add tree-build orchestration (lockfiles/modules/env) for list/why

• Loads current/wanted lockfiles and modules manifest, builds a shared dependency graph, and materializes per-project dependency hierarchies with shared dedupe cache across projects. Encapsulates environment needed for pkg metadata resolution (registries, skipped deps, store dir, virtual store settings).

pnpm/crates/cli/src/cli_args/deps_tree/build.rs

dep_types.rsPort lockfile dep-type detection (dev/prod/both) +82/-0

Port lockfile dep-type detection (dev/prod/both)

• Implements dev-only/prod-only/both classification for depPaths by walking dependency subgraphs from importer dependency groups, mirroring '@pnpm/lockfile.detect-dep-types'.

pnpm/crates/cli/src/cli_args/deps_tree/dep_types.rs

dependents.rsImplement reverse dependency (dependents) tree for 'pnpm why' +415/-0

Implement reverse dependency (dependents) tree for 'pnpm why'

• Builds a reverse tree per matched depPath (including peer variants), with cycle detection, branch deduplication, importer leaf dep-field annotations, and semver/name ordering. Also resolves package node filesystem locations by walking through parent 'node_modules' (global virtual store aware).

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs

finders.rsAdd '--find-by' finder resolution and pre-evaluation pipeline +217/-0

Add '--find-by' finder resolution and pre-evaluation pipeline

• Resolves requested finder names from pnpmfiles, enumerates candidate '(alias, node)' pairs, reads manifests (prefer CAFS store via store index), and evaluates JS finder callbacks via hooks to produce 'SearchMatch' verdicts for the tree walk.

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs

get_tree.rsMaterialize dependency trees with dedupe, search pruning, and cycles +319/-0

Materialize dependency trees with dedupe, search pruning, and cycles

• Turns the dependency graph into 'DependencyNode' trees with '(node, depth)' cache-based subtree elision ('[deduped]' + counts), search-based pruning/messages, and a post-pass to mark circular references without polluting cached subtrees.

pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs

graph.rsBuild lockfile-backed dependency graph shared by list/why +225/-0

Build lockfile-backed dependency graph shared by list/why

• Implements BFS graph construction from importer/package nodes, capturing edges (including link handling and non-traversable leaves) and peerDependency alias sets used for peer annotations.

pnpm/crates/cli/src/cli_args/deps_tree/graph.rs

pkg_info.rsResolve per-edge node metadata (paths, resolved URLs, flags) +244/-0

Resolve per-edge node metadata (paths, resolved URLs, flags)

• Computes display name/version, absolute package paths (including global virtual store symlink resolution), tarball URL reconstruction, optional/dev/peer/skipped flags, and link-version rewriting. Provides 'ManifestSource' for '--long' and finder evaluation.

pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs

render.rsAdd shared archy renderer and formatting helpers +230/-0

Add shared archy renderer and formatting helpers

• Implements TS-matching archy tree rendering with dimmed connectors, color helpers, peer-variant aggregation/suffixing, dedupe/circular labels, and '--long' manifest detail extraction.

pnpm/crates/cli/src/cli_args/deps_tree/render.rs

search.rsAdd version-range aware searcher + finder result integration +130/-0

Add version-range aware searcher + finder result integration

• Parses '<name>[@<range>]' queries (scope-aware), matches by alias/name and semver range, and consults precomputed '--find-by' verdicts keyed by '(alias, node)' before returning 'SearchMatch' results.

pnpm/crates/cli/src/cli_args/deps_tree/search.rs

list.rsRewrite 'pnpm list' on deps_tree with TS-parity flags and global depth logic +294/-985

Rewrite 'pnpm list' on deps_tree with TS-parity flags and global depth logic

• Replaces bespoke list logic with async deps-tree pipeline, adds TS-parity flags ('--only-projects', '--find-by'), version-range search, and shared-lockfile recursive rendering. Updates global listing to support '--depth' with an error guard when multiple isolated global installs would require merging trees.

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

render.rsAdd TS-matching list renderers (tree/JSON/parseable) +440/-0

Add TS-matching list renderers (tree/JSON/parseable)

• Implements byte-identical renderers including legend, cyan group headers, peer/skipped annotations, peer-variant hash suffixes, '[deduped]' markers, long manifest details, JSON ordering/shape, and parseable output semantics.

pnpm/crates/cli/src/cli_args/list/render.rs

why.rsRewrite 'pnpm why' on deps_tree with TS-parity flags and outputs +137/-479

Rewrite 'pnpm why' on deps_tree with TS-parity flags and outputs

• Rebuilds 'why' using the shared dependency graph and reverse dependents tree, adds '--json'/'--parseable'/'--long', include filters ('--prod'/'--dev'/'--no-optional'), '--find-by', and TS-matching missing-args error message/code.

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

render.rsAdd TS-matching why renderers (tree/JSON/parseable) + summary +287/-0

Add TS-matching why renderers (tree/JSON/parseable) + summary

• Implements archy-style dependents tree rendering with circular/deduped markers, dep-field annotations on importer leaves, optional long manifest details, JSON/parseable formats, and the 'Found N versions[, M instances]' summary ordering.

pnpm/crates/cli/src/cli_args/why/render.rs

lib.rsRe-export new global install-dir discovery helper +1/-1

Re-export new global install-dir discovery helper

• Exports 'find_global_install_dirs' for use by CLI global list depth behavior.

pnpm/crates/global/src/lib.rs

list.rsAdd helper to locate matching global install directories +18/-0

Add helper to locate matching global install directories

• Introduces 'find_global_install_dirs' to identify which isolated global install dirs match top-level dependency params, enabling 'ls -g --depth' narrowing and guarding against unsupported merged trees.

pnpm/crates/global/src/list.rs

lib.rsExtend pnpmfile hooks trait with finder APIs +17/-0

Extend pnpmfile hooks trait with finder APIs

• Adds default hook methods 'get_finder_names' and 'run_finder' to support '.pnpmfile.cjs' 'finders' object integration for '--find-by'.

pnpm/crates/hooks/src/lib.rs

node_runtime.rsImplement finder APIs for Node-based pnpmfile hooks +8/-0

Implement finder APIs for Node-based pnpmfile hooks

• Wires new finder hook methods to the Node worker ('get_finder_names', 'call_finder').

pnpm/crates/hooks/src/node_runtime.rs

worker.rsAdd Node worker protocol endpoints for finders +46/-0

Add Node worker protocol endpoints for finders

• Adds Rust methods and JS-side request handling for listing exported finder names and invoking a named finder with a context including 'readManifest()'.

pnpm/crates/hooks/src/worker.rs

Refactor (2) +9 / -4
cli_args.rsRegister new shared deps-tree module in CLI args +1/-0

Register new shared deps-tree module in CLI args

• Exposes 'cli_args::deps_tree' so 'list' and 'why' can share the new tree-building pipeline.

pnpm/crates/cli/src/cli_args.rs

dispatch_query.rsMake list/ll dispatch async to support finder evaluation +8/-4

Make list/ll dispatch async to support finder evaluation

• Changes list command dispatch to return an async future and await 'ListArgs::run', enabling async pnpmfile finder evaluation and shared-lockfile single-pass rendering.

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

Tests (7) +2451 / -611
tests.rsPort upstream getTree test suite +735/-0

Port upstream getTree test suite

• Adds extensive unit tests covering depth limiting, cache behavior, cross-root dedupe, circular detection, linked deps, search-with-dedup semantics, and peer exclusion parity with upstream.

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

tests.rsPort upstream getPkgInfo missing-snapshot test +80/-0

Port upstream getPkgInfo missing-snapshot test

• Adds a regression test ensuring missing package snapshots don’t crash and that alias/ref fallbacks are used, matching observable TS behavior.

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

tests.rsAdd searcher unit tests +85/-0

Add searcher unit tests

• Covers query parsing/matching semantics and finder-result precedence/lookup behavior.

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

tests.rsPort list renderer-level tests and update fixtures +342/-539

Port list renderer-level tests and update fixtures

• Replaces older unit tests with ports that assert TS renderer behavior (empty suppression, sorting, alias label formatting, parseable dedup/search behavior) and adds coverage for depth parsing ('Infinity', '-1').

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

tests.rsPort why renderer-level tests (tree/json/parseable/summary) +383/-69

Port why renderer-level tests (tree/json/parseable/summary)

• Adds one-to-one ports of upstream renderer tests asserting output formatting, depth truncation, marker rendering, and summary construction.

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

list.rsPort CLI-level TS list tests (end-to-end) +562/-0

Port CLI-level TS list tests (end-to-end)

• Adds end-to-end tests for list output parity including legend/summary, filter flags, lockfile-only behavior, long output, recursive shared-lockfile rendering, finder loading from '.pnpmfile.cjs', and global virtual store path correctness.

pnpm/crates/cli/tests/list.rs

why.rsPort CLI-level TS why tests and update expectations +264/-3

Port CLI-level TS why tests and update expectations

• Updates missing-arg error expectations to TS wording and adds end-to-end tests for reverse tree behavior (transitive paths, npm: alias matching, parseable/json/long outputs, finder messages, store-backed manifest reads, and workspace naming).

pnpm/crates/cli/tests/why.rs

Documentation (2) +51 / -0
list-why-parity.mdAdd changeset noting list/why TS parity and new flags +5/-0

Add changeset noting list/why TS parity and new flags

• Adds a minor changeset entry documenting that Rust 'pnpm list' and 'pnpm why' are now feature-complete vs the TypeScript CLI, including '--find-by', version-range search, dedupe/circular markers, and new output formats.

.changeset/list-why-parity.md

TEST_PORTING.mdDocument list/why parity test-port mapping to upstream sources +46/-0

Document list/why parity test-port mapping to upstream sources

• Adds a detailed checklist linking upstream TS tests (CLI, renderer, and tree-builder layers) to their Rust ports, including explicitly skipped/unneeded upstream cases.

pnpm/plans/TEST_PORTING.md

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.01     12.3±0.73ms    30.4 MB/sec    1.00     12.2±0.19ms    30.6 MB/sec
packument/parse                1.00     40.9±1.41µs  1622.8 MB/sec    1.00     41.1±0.85µs  1615.3 MB/sec
tarball/download_dependency    1.00      2.5±0.11ms  1759.8 KB/sec    1.02      2.5±0.10ms  1733.8 KB/sec

Copilot AI review requested due to automatic review settings July 20, 2026 15:57

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-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to c080c34

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Possible issue
Restore JSON output precedence

Restore the previous precedence of --json over --parseable.

pnpm/crates/cli/src/cli_args/list.rs [243-249]

-if self.parseable {
+if self.json {
+    ReportAs::Json
+} else if self.parseable {
     ReportAs::Parseable
-} else if self.json {
-    ReportAs::Json
 } else {
     ReportAs::Tree
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This fixes a regression introduced during refactoring where the precedence of output flags was accidentally inverted, potentially breaking callers expecting JSON output.

Medium
Preserve matched package aliases

Save the matching incoming alias as display_name and pass it to DependentsTree.

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs [147-180]

+let mut display_name = None;
 let mut matched = opts.search.matches(&name, &name, &version, Some(node_id));
 if !matched.is_match()
     && let Some(incoming) = reverse_map.get(node_id)
 {
     for edge in incoming {
         if edge.alias != name {
             matched = opts.search.matches(&edge.alias, &name, &version, Some(node_id));
             if matched.is_match() {
+                display_name = Some(edge.alias.clone());
                 break;
             }
         }
     }
 }
 if !matched.is_match() {
     continue;
 }
 
 ...
 
 trees.push(DependentsTree {
     name,
-    display_name: None,
+    display_name,
     version,
     path: Some(resolved.path.to_string_lossy().into_owned()),
     peers_suffix_hash: peers_suffix_hash(dep_path),
     dependents,
     search_message: matched.message().map(str::to_string),
 });

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: It fixes a functional issue where pnpm why <alias> doesn't show the correct alias by properly capturing and using display_name from matching aliases.

Medium
Exclude optionals from dev-only results

Condition the inclusion of optional dependencies on whether production
dependencies are also being included.

pnpm/crates/cli/src/cli_args/why.rs [150-153]

 IncludedDependencies {
     dependencies: has_both || self.production,
     dev_dependencies: has_both || self.dev,
-    optional_dependencies: !self.no_optional,
+    optional_dependencies: !self.no_optional && (has_both || self.production),
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: This change correctly aligns the inclusion of optional dependencies with the --prod and --dev flags to prevent unexpected packages from being included when only --dev is provided.

Medium
General
Support unlimited depth syntax

Use a custom parser for the --depth flag to support the Infinity value in
addition to numerical depths.

pnpm/crates/cli/src/cli_args/why.rs [37-39]

 /// Max display depth of the reverse dependency tree.
-#[clap(long)]
-pub depth: Option<usize>,
+#[clap(long, value_parser = parse_depth)]
+pub depth: Option<DependentsDepth>,

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: Supporting Infinity as a depth value prevents parsing errors and ensures command-line parity with the original pnpm CLI.

Medium
  • Update

Previous suggestions

Suggestions up to commit 99864e0
CategorySuggestion                                                                                                                                    Impact
Possible issue
Honor peer exclusion option

Pass the exclude_peers option to BuildDependentsOptions.

pnpm/crates/cli/src/cli_args/why.rs [162-167]

 let trees = build_dependents_tree(&BuildDependentsOptions {
     env: &env,
     graph: &graph,
     search: &searcher,
     importer_info: &importer_info,
+    exclude_peer_dependencies: self.exclude_peers,
 });
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies that the newly added --exclude-peers CLI argument is completely ignored in the run method, which is a significant functional bug.

High
Preserve valid recursive JSON output

Fix invalid JSON output by parsing and flattening arrays before outputting them
together.

pnpm/crates/cli/src/cli_args/list.rs [238-243]

         if !output.is_empty() {
             outputs.push(output);
         }
     }
+    if self.report_as() == ReportAs::Json {
+        let mut projects = Vec::new();
+        for output in outputs {
+            let mut output_projects: Vec<serde_json::Value> =
+                serde_json::from_str(&output).into_diagnostic()?;
+            projects.append(&mut output_projects);
+        }
+        return serde_json::to_string_pretty(&projects).into_diagnostic();
+    }
     let joiner = if self.depth == RecursionLimit::ProjectsOnly { "\n" } else { "\n\n" };
     Ok(outputs.join(joiner))
Suggestion importance[1-10]: 8

__

Why: This addresses a critical bug that causes the CLI to produce invalid JSON output when running in recursive mode with per-project lockfiles.

Medium
Preserve matched package aliases

Update the tree building logic to store the matched alias as display_name when a
package is found via an npm: alias.

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs [146-180]

+        let mut display_name = None;
         let mut matched = opts.search.matches(&name, &name, &version, Some(node_id));
         if !matched.is_match()
             && let Some(incoming) = reverse_map.get(node_id)
         {
             for edge in incoming {
                 if edge.alias != name {
                     matched = opts.search.matches(&edge.alias, &name, &version, Some(node_id));
                     if matched.is_match() {
+                        display_name = Some(edge.alias.clone());
                         break;
                     }
                 }
             }
         }
 ...
         trees.push(DependentsTree {
             name,
-            display_name: None,
+            display_name,
             version,
             path: Some(resolved.path.to_string_lossy().into_owned()),
             peers_suffix_hash: peers_suffix_hash(dep_path),
             dependents,
             search_message: matched.message().map(str::to_string),
         });
Suggestion importance[1-10]: 8

__

Why: The suggestion resolves a functional discrepancy with the upstream tool by accurately capturing and passing display_name for aliased search matches.

Medium
General
Validate scope directories before recursion

Validate that an @scope entry is actually a directory before attempting to
recurse into it.

pnpm/crates/cli/src/cli_args/deps_tree/build.rs [390-403]

         let file_name = entry.file_name();
         let Some(name) = file_name.to_str() else {
             continue;
         };
         if name.starts_with('.') {
             continue;
         }
-        if entry.file_type().is_ok_and(|file_type| file_type.is_file()) {
+        let file_type = entry.file_type()?;
+        if file_type.is_file() {
             continue;
         }
         if scope.is_none() && name.starts_with('@') {
-            collect_module_names(modules_dir, Some(name), names)?;
+            if file_type.is_dir() {
+                collect_module_names(modules_dir, Some(name), names)?;
+            }
             continue;
         }
Suggestion importance[1-10]: 7

__

Why: The suggestion improves code robustness and prevents potential filesystem traversal errors from crashing the command when encountering unusual files named as scopes.

Medium
Restore JSON flag precedence

Prioritize the --json flag over --parseable to maintain CLI backward
compatibility.

pnpm/crates/cli/src/cli_args/list.rs [245-251]

-    if self.parseable {
+    if self.json {
+        ReportAs::Json
+    } else if self.parseable {
         ReportAs::Parseable
-    } else if self.json {
-        ReportAs::Json
     } else {
         ReportAs::Tree
     }
Suggestion importance[1-10]: 6

__

Why: This restores backward compatibility for command-line argument priorities, preventing potential breakage in automated scripts expecting JSON output.

Low
Suggestions up to commit 6a90541
CategorySuggestion                                                                                                                                    Impact
Possible issue
Emit valid recursive JSON

Fix recursive JSON output by parsing and flattening individual project arrays
into a single JSON array before printing.

pnpm/crates/cli/src/cli_args/list.rs [240-241]

+if self.report_as() == ReportAs::Json {
+    let mut projects = Vec::new();
+    for output in outputs {
+        let mut output_projects: Vec<serde_json::Value> =
+            serde_json::from_str(&output).into_diagnostic()?;
+        projects.append(&mut output_projects);
+    }
+    return serde_json::to_string_pretty(&projects).into_diagnostic();
+}
+
 let joiner = if self.depth == RecursionLimit::ProjectsOnly { "\n" } else { "\n\n" };
 Ok(outputs.join(joiner))
Suggestion importance[1-10]: 9

__

Why: This addresses a critical bug where the JSON output for recursive operations would produce invalid JSON by concatenating stringified JSON arrays instead of flattening them into a single array.

High
Exclude optional dependencies in dev-only mode

Modify the logic to exclude optional dependencies when only dev dependencies are
requested (--dev).

pnpm/crates/cli/src/cli_args/why.rs [141-145]

 IncludedDependencies {
     dependencies: has_both || self.production,
     dev_dependencies: has_both || self.dev,
-    optional_dependencies: !self.no_optional,
+    optional_dependencies: (has_both || self.production) && !self.no_optional,
 }
Suggestion importance[1-10]: 7

__

Why: This suggestion accurately identifies a logical flaw where optional dependencies are still included in --dev mode, aligning the tool's behavior with typical package manager expectations.

Medium
General
Count dependencies hidden by deduplication

Include deduplicated dependencies in the summary calculation.

pnpm/crates/cli/src/cli_args/list/render.rs [244-247]

 fn list_summary(projects: &[ProjectHierarchy]) -> String {
     fn count(nodes: &[DependencyNode]) -> u64 {
-        nodes.iter().map(|node| 1 + count(&node.dependencies)).sum()
+        nodes
+            .iter()
+            .map(|node| {
+                1 + node
+                    .deduped_dependencies_count
+                    .unwrap_or_else(|| count(&node.dependencies))
+            })
+            .sum()
     }
Suggestion importance[1-10]: 8

__

Why: This fixes a bug where deduplicated dependencies were excluded from the total count, ensuring the summary output matches upstream pnpm behavior.

Medium
Restore output-format precedence

Reorder the condition in report_as to prioritize --json over --parseable for
consistency with the previous implementation.

pnpm/crates/cli/src/cli_args/list.rs [244-250]

-if self.parseable {
+if self.json {
+    ReportAs::Json
+} else if self.parseable {
     ReportAs::Parseable
-} else if self.json {
-    ReportAs::Json
 } else {
     ReportAs::Tree
 }
Suggestion importance[1-10]: 6

__

Why: Restores backward compatibility and parity with the TypeScript CLI regarding flag precedence, ensuring existing scripts depending on --json continue to function as expected.

Low
Suggestions up to commit d4c7a4a
CategorySuggestion                                                                                                                                    Impact
Possible issue
Emit one valid JSON array

Fix the concatenation of JSON outputs for workspaces to ensure a single, valid
JSON array is produced.

pnpm/crates/cli/src/cli_args/list.rs [236-241]

         if !output.is_empty() {
             outputs.push(output);
         }
     }
+    if self.report_as() == ReportAs::Json {
+        let mut projects = Vec::new();
+        for output in outputs {
+            projects.extend(
+                serde_json::from_str::<Vec<serde_json::Value>>(&output).into_diagnostic()?,
+            );
+        }
+        return serde_json::to_string_pretty(&projects).into_diagnostic();
+    }
     let joiner = if self.depth == RecursionLimit::ProjectsOnly { "\n" } else { "\n\n" };
     Ok(outputs.join(joiner))
Suggestion importance[1-10]: 9

__

Why: Catches a critical bug where naively concatenating JSON strings produces invalid JSON output for multi-project workspaces.

High
Honor peer dependency exclusion

Pass the --exclude-peers flag to BuildDependentsOptions in
build_dependents_tree. Ensure the tree builder correctly skips peer dependencies
when requested.

pnpm/crates/cli/src/cli_args/why.rs [162-167]

 let trees = build_dependents_tree(&BuildDependentsOptions {
     env: &env,
     graph: &graph,
     search: &searcher,
     importer_info: &importer_info,
+    exclude_peer_dependencies: self.exclude_peers,
 });
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies that the newly added --exclude-peers CLI flag is completely ignored in the implementation, representing a clear functional bug.

High
Preserve matched dependency aliases

Set the display_name field to the matched alias when a package matches the
search query via its alias.

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs [145-180]

+let mut display_name = None;
 let mut matched = opts.search.matches(&name, &name, &version, Some(node_id));
 if !matched.is_match()
     && let Some(incoming) = reverse_map.get(node_id)
 {
     for edge in incoming {
         if edge.alias != name {
             matched = opts.search.matches(&edge.alias, &name, &version, Some(node_id));
             if matched.is_match() {
+                display_name = Some(edge.alias.clone());
                 break;
             }
         }
     }
 }
 ...
 trees.push(DependentsTree {
     name,
-    display_name: None,
+    display_name,
     version,
     path: Some(resolved.path.to_string_lossy().into_owned()),
     peers_suffix_hash: peers_suffix_hash(dep_path),
     dependents,
     search_message: matched.message().map(str::to_string),
 });
Suggestion importance[1-10]: 8

__

Why: This suggestion resolves a functional parity issue with upstream pnpm where the why command output should display the matched dependency alias instead of the canonical name.

Medium
Preserve JSON output precedence

Restore the original flag precedence where --json takes priority over
--parseable.

pnpm/crates/cli/src/cli_args/list.rs [243-251]

     fn report_as(&self) -> ReportAs {
-        if self.parseable {
+        if self.json {
+            ReportAs::Json
+        } else if self.parseable {
             ReportAs::Parseable
-        } else if self.json {
-            ReportAs::Json
         } else {
             ReportAs::Tree
         }
     }
Suggestion importance[1-10]: 7

__

Why: Identifies a regression in flag precedence that could silently break scripts relying on JSON output when multiple flags are passed.

Medium
Suggestions up to commit 40e551a
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve valid recursive JSON output

Merge recursive JSON outputs into a single JSON array to prevent invalid JSON
formatting.

pnpm/crates/cli/src/cli_args/list.rs [239-240]

+if self.report_as() == ReportAs::Json {
+    let mut projects = Vec::new();
+    for output in outputs {
+        let mut rendered_projects: Vec<serde_json::Value> =
+            serde_json::from_str(&output).into_diagnostic()?;
+        projects.append(&mut rendered_projects);
+    }
+    return serde_json::to_string_pretty(&projects).into_diagnostic();
+}
+
 let joiner = if self.depth == RecursionLimit::ProjectsOnly { "\n" } else { "\n\n" };
 Ok(outputs.join(joiner))
Suggestion importance[1-10]: 8

__

Why: This points out a critical bug where multiple JSON objects are joined with newlines, resulting in invalid JSON output when run recursively.

Medium
Preserve matched dependency aliases

Capture the matched edge.alias and assign it to the display_name property of the
DependentsTree.

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs [146-174]

+        let mut display_name = None;
         let mut matched = opts.search.matches(&name, &name, &version, Some(node_id));
         if !matched.is_match()
             && let Some(incoming) = reverse_map.get(node_id)
         {
             for edge in incoming {
                 if edge.alias != name {
                     matched = opts.search.matches(&edge.alias, &name, &version, Some(node_id));
                     if matched.is_match() {
+                        display_name = Some(edge.alias.clone());
                         break;
                     }
                 }
             }
         }
 ...
-            display_name: None,
+            display_name,
Suggestion importance[1-10]: 8

__

Why: Assigning the matched alias to display_name ensures that pnpm why correctly displays npm: aliases instead of the canonical package name.

Medium
Render aliases throughout reverse trees

Assign display_name using edge.alias for DependentNodes reached via an npm:
alias. Apply this consistently across appropriate branches.

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs [343-347]

-                let mut node = DependentNode::leaf(name, version);
+                let mut node = DependentNode::leaf(name.clone(), version);
+                if edge.alias != name {
+                    node.display_name = Some(edge.alias.clone());
+                }
                 node.peers_suffix_hash = hash;
                 node.dependents =
                     if child_dependents.is_empty() { None } else { Some(child_dependents) };
                 dependents.push(node);
Suggestion importance[1-10]: 8

__

Why: Populating display_name for dependent nodes ensures that reverse-tree paths accurately display npm: aliases as declared by their parents.

Medium
Exclude optional dependencies in dev-only mode

Update the IncludedDependencies initialization to exclude optionalDependencies
when only --dev is passed.

pnpm/crates/cli/src/cli_args/why.rs [141-145]

 IncludedDependencies {
     dependencies: has_both || self.production,
     dev_dependencies: has_both || self.dev,
-    optional_dependencies: !self.no_optional,
+    optional_dependencies: !self.no_optional && (!self.dev || self.production),
 }
Suggestion importance[1-10]: 7

__

Why: This addresses a logical bug where --dev could incorrectly include optionalDependencies, resulting in unexpected reverse dependency paths.

Medium
General
Count elided dependency subtrees

Update the count function to include node.deduped_dependencies_count if
available. This accounts for elided dependencies in the summary total.

pnpm/crates/cli/src/cli_args/list/render.rs [245-247]

     fn count(nodes: &[DependencyNode]) -> u64 {
-        nodes.iter().map(|node| 1 + count(&node.dependencies)).sum()
+        nodes
+            .iter()
+            .map(|node| {
+                1 + node
+                    .deduped_dependencies_count
+                    .unwrap_or_else(|| count(&node.dependencies))
+            })
+            .sum()
     }
Suggestion importance[1-10]: 8

__

Why: Including deduped_dependencies_count avoids underreporting the total package count when subtrees are elided due to deduplication.

Medium
Restore output format precedence

Revert the evaluation order so that --json takes precedence over --parseable for
proper compatibility.

pnpm/crates/cli/src/cli_args/list.rs [244-250]

-if self.parseable {
+if self.json {
+    ReportAs::Json
+} else if self.parseable {
     ReportAs::Parseable
-} else if self.json {
-    ReportAs::Json
 } else {
     ReportAs::Tree
 }
Suggestion importance[1-10]: 7

__

Why: This successfully catches an unintentional behavior change introduced by the PR, ensuring backward compatibility with the original flag precedence.

Medium
Suggestions up to commit fe88f53
CategorySuggestion                                                                                                                                    Impact
Possible issue
Honor peer dependency exclusion

Pass the missing self.exclude_peers flag to BuildDependentsOptions so the option
actually works.

pnpm/crates/cli/src/cli_args/why.rs [172-177]

 BuildDependentsOptions {
     env: &env,
     graph: &graph,
     search: &searcher,
     importer_info: &importer_info,
+    exclude_peer_dependencies: self.exclude_peers,
 }
Suggestion importance[1-10]: 9

__

Why: The exclude_peers field was added to WhyArgs but is never utilized in the run execution logic, meaning the CLI flag would be completely non-functional without this fix.

High
Produce valid recursive JSON output

Ensure valid JSON output when printing recursive results.

pnpm/crates/cli/src/cli_args/list.rs [222-238]

 let mut outputs = Vec::new();
 for project_dir in project_dirs {
     let output = self
         .render_projects(
             config,
             std::slice::from_ref(&project_dir),
             &self.packages,
             &project_dir,
             always_print_root_package,
         )
         .await?;
     if !output.is_empty() {
         outputs.push(output);
     }
 }
+if self.report_as() == ReportAs::Json {
+    let mut projects = Vec::new();
+    for output in outputs {
+        let mut value: Vec<serde_json::Value> =
+            serde_json::from_str(&output).into_diagnostic()?;
+        projects.append(&mut value);
+    }
+    return serde_json::to_string_pretty(&projects).into_diagnostic();
+}
 let joiner = if self.depth == RecursionLimit::ProjectsOnly { "\n" } else { "\n\n" };
 Ok(outputs.join(joiner))
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a logic error where joining individual JSON outputs directly results in invalid JSON, which breaks automated parsing for recursive JSON listings.

Medium
Exclude optional dependencies in dev-only mode

Update the dependency inclusion logic to exclude optional dependencies when only
--dev is selected.

pnpm/crates/cli/src/cli_args/why.rs [143-147]

 IncludedDependencies {
     dependencies: has_both || self.production,
     dev_dependencies: has_both || self.dev,
-    optional_dependencies: !self.no_optional,
+    optional_dependencies: !self.no_optional && (has_both || self.production),
 }
Suggestion importance[1-10]: 5

__

Why: While adjusting the optional dependencies logic for the --dev flag might better align with user expectations, it's a minor edge case whose behavior depends on strict pnpm parity requirements.

Low
General
Count packages in deduped subtrees

Include the deduped_dependencies_count when calculating the total dependency
count to ensure deduped subtrees are accurately represented.

pnpm/crates/cli/src/cli_args/list/render.rs [245-247]

 fn count(nodes: &[DependencyNode]) -> u64 {
-    nodes.iter().map(|node| 1 + count(&node.dependencies)).sum()
+    nodes
+        .iter()
+        .map(|node| {
+            1 + if node.deduped {
+                node.deduped_dependencies_count.unwrap_or(0)
+            } else {
+                count(&node.dependencies)
+            }
+        })
+        .sum()
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that list_summary undercounts the total dependencies by ignoring the children of deduplicated subtrees, and uses deduped_dependencies_count to fix it.

Medium
Handle unmatched global filters correctly

Handle empty match results properly instead of throwing a multiple-tree merge
error.

pnpm/crates/cli/src/cli_args/list.rs [163-173]

-if matching_install_dirs.len() > 1
-    || (matching_install_dirs.is_empty() && !all_install_dirs.is_empty())
-{
+if matching_install_dirs.is_empty() {
+    return list_global_packages(
+        &global_pkg_dir,
+        &self.packages,
+        global_report_as(self.report_as()),
+        self.long,
+    )
+    .into_diagnostic();
+}
+if matching_install_dirs.len() > 1 {
     return Err(miette::miette!(
         code = "ERR_PNPM_GLOBAL_LS_DEPTH_NOT_SUPPORTED",
         "Cannot list a merged dependency tree across multiple global packages. \
          Each global package is installed in an isolated directory with its own lockfile, \
          so transitive dependencies cannot be coherently merged. \
          Filter to a single global package by its top-level name, or omit --depth."
     ));
 }
Suggestion importance[1-10]: 7

__

Why: This fixes an incorrect error response for empty matches, improving the accuracy and user experience of global package searches with a depth parameter.

Medium
Preserve output format precedence

Restore output-format precedence by prioritizing the --json flag over
--parseable.

pnpm/crates/cli/src/cli_args/list.rs [241-247]

-if self.parseable {
+if self.json {
+    ReportAs::Json
+} else if self.parseable {
     ReportAs::Parseable
-} else if self.json {
-    ReportAs::Json
 } else {
     ReportAs::Tree
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion catches a subtle regression in CLI flag evaluation order, ensuring backward compatibility for users employing multiple formatting flags.

Medium

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. importer_id path join unvalidated ✓ Resolved 📘 Rule violation ⛨ Security
Description
pnpm why builds a filesystem path from lockfile-controlled importer_id via
lockfile_dir.join(importer_id) without validating the importer key, which can resolve outside the
workspace root or to an absolute path. This bypasses existing repo utilities meant to prevent unsafe
importer paths and can lead to unintended file reads/DoS when reading package.json.
Code

pnpm/crates/cli/src/cli_args/why.rs[125]

+            let manifest = read_project_manifest(&lockfile_dir.join(importer_id.as_str()));
Evidence
The checklist requires reusing existing utilities instead of reimplementing/duplicating logic. The
new code uses lockfile_dir.join(importer_id) directly when reading a manifest, while the repo
already has validate_importer_id() and importer_root_dir() specifically to prevent unsafe
importer paths derived from lockfiles.

CLAUDE.md: Avoid code duplication by reusing existing repo utilities and extracting shared logic
pnpm/crates/cli/src/cli_args/why.rs[123-136]
pnpm/crates/package-manager/src/symlink_direct_dependencies.rs[272-395]

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

## Issue description
`why.rs` reads project manifests using `lockfile_dir.join(importer_id)` where `importer_id` comes from the lockfile. This can produce off-workspace or absolute paths and is missing the repo’s existing importer-id safety validation.

## Issue Context
The repo already provides `validate_importer_id()` + `importer_root_dir()` for turning untrusted lockfile importer keys into safe on-disk paths.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/why.rs[123-136]
- pnpm/crates/package-manager/src/symlink_direct_dependencies.rs[272-395]

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


2. walk_reverse() deep recursion risk ✓ Resolved 📘 Rule violation ⛨ Security
Description
deps_tree/dependents.rs relies on unbounded recursion in both walk_reverse() and the nested
resolve_package_nodes::walk() traversal, which can overflow the stack on sufficiently deep (but
acyclic) dependency chains and crash pnpm why on attacker-controlled lockfiles/graphs. This
creates a denial-of-service risk because cycle guards (visited/expanded) prevent infinite loops
but do not cap recursion depth.
Code

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[R204-352]

+    fn walk(
+        env: &PkgInfoEnv<'_>,
+        graph: &DependencyGraph,
+        resolved: &mut HashMap<TreeNodeId, ManifestSource>,
+        node_id: &TreeNodeId,
+        parent_dir: Option<&Path>,
+    ) {
+        let Some(node) = graph.nodes.get(node_id) else {
+            return;
+        };
+        for edge in &node.edges {
+            let Some(target) = &edge.target else {
+                continue;
+            };
+            if resolved.contains_key(target) || !matches!(target, TreeNodeId::Package(_)) {
+                continue;
+            }
+            let edge_ctx = EdgeContext {
+                peers: None,
+                linked_path_base_dir: env.modules_dir.clone(),
+                rewrite_link_version_dir: None,
+                parent_dir: parent_dir.map(Path::to_path_buf),
+            };
+            let (_, manifest_source) = get_pkg_info(env, edge, &edge_ctx);
+            let target_path = manifest_source.path.clone();
+            resolved.insert(target.clone(), manifest_source);
+            walk(env, graph, resolved, target, Some(&target_path));
+        }
+    }
+
+    for node_id in graph.nodes.keys() {
+        if matches!(node_id, TreeNodeId::Importer(_)) {
+            walk(env, graph, &mut resolved, node_id, None);
+        }
+    }
+    resolved
+}
+
+fn invert_graph(graph: &DependencyGraph) -> HashMap<TreeNodeId, Vec<ReverseEdge>> {
+    let mut reverse: HashMap<TreeNodeId, Vec<ReverseEdge>> = HashMap::new();
+    for (parent_id, node) in &graph.nodes {
+        for edge in &node.edges {
+            let Some(target) = &edge.target else {
+                continue;
+            };
+            reverse
+                .entry(target.clone())
+                .or_default()
+                .push(ReverseEdge { parent: parent_id.clone(), alias: edge.alias.clone() });
+        }
+    }
+    reverse
+}
+
+fn walk_reverse(ctx: &mut WalkCtx<'_>, node_id: &TreeNodeId) -> Vec<DependentNode> {
+    let Some(reverse_edges) = ctx.reverse_map.get(node_id) else {
+        return Vec::new();
+    };
+
+    // Sort by parent name (serialized id as tiebreaker) so
+    // deduplication is deterministic: the first parent always gets
+    // fully expanded.
+    let mut sorted_edges: Vec<&ReverseEdge> = reverse_edges.iter().collect();
+    sorted_edges.sort_by(|a, b| {
+        resolve_parent_name(ctx, &a.parent)
+            .cmp(&resolve_parent_name(ctx, &b.parent))
+            .then_with(|| a.parent.serialize().cmp(&b.parent.serialize()))
+    });
+
+    let mut dependents: Vec<DependentNode> = Vec::new();
+
+    for edge in sorted_edges {
+        if ctx.visited.contains(&edge.parent) {
+            match &edge.parent {
+                TreeNodeId::Importer(importer_id) => {
+                    if let Some(info) = ctx.importer_info.get(importer_id) {
+                        let mut node = DependentNode::leaf(info.name.clone(), info.version.clone());
+                        node.circular = true;
+                        dependents.push(node);
+                    }
+                }
+                TreeNodeId::Package(dep_path) => {
+                    if ctx
+                        .lockfile
+                        .snapshots
+                        .as_ref()
+                        .is_some_and(|snapshots| snapshots.contains_key(dep_path))
+                    {
+                        let (name, version) = name_ver_from_dep_path(ctx.lockfile, dep_path);
+                        let mut node = DependentNode::leaf(name, version);
+                        node.circular = true;
+                        dependents.push(node);
+                    }
+                }
+            }
+            continue;
+        }
+
+        match &edge.parent {
+            TreeNodeId::Importer(importer_id) => {
+                let (name, version) = match ctx.importer_info.get(importer_id) {
+                    Some(info) => (info.name.clone(), info.version.clone()),
+                    None => (importer_id.clone(), String::new()),
+                };
+                let mut node = DependentNode::leaf(name, version);
+                node.dep_field = ctx
+                    .lockfile
+                    .importers
+                    .get(importer_id.as_str())
+                    .and_then(|importer| dep_field_for_alias(&edge.alias, importer));
+                dependents.push(node);
+            }
+            TreeNodeId::Package(dep_path) => {
+                if !ctx
+                    .lockfile
+                    .snapshots
+                    .as_ref()
+                    .is_some_and(|snapshots| snapshots.contains_key(dep_path))
+                {
+                    continue;
+                }
+                let (name, version) = name_ver_from_dep_path(ctx.lockfile, dep_path);
+                let hash = peers_suffix_hash(dep_path);
+
+                if ctx.expanded.contains(&edge.parent) {
+                    // Already expanded elsewhere in the tree — show as
+                    // a leaf to keep the output bounded.
+                    let mut node = DependentNode::leaf(name, version);
+                    node.peers_suffix_hash = hash;
+                    node.deduped = true;
+                    dependents.push(node);
+                    continue;
+                }
+
+                ctx.visited.insert(edge.parent.clone());
+                ctx.expanded.insert(edge.parent.clone());
+                let child_dependents = walk_reverse(ctx, &edge.parent);
+                ctx.visited.remove(&edge.parent);
+
+                let mut node = DependentNode::leaf(name, version);
+                node.peers_suffix_hash = hash;
+                node.dependents =
+                    if child_dependents.is_empty() { None } else { Some(child_dependents) };
+                dependents.push(node);
+            }
+        }
+    }
+
+    dependents
Evidence
PR Compliance ID 9 calls for avoiding unsafe/inefficient loop patterns, and the cited code in
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs implements two self-recursive traversals (a
top-down walk in resolve_package_nodes() and a reverse-tree build in walk_reverse()) whose
recursion depth can grow with the longest dependency chain, making stack exhaustion possible even
without cycles. The pnpm/crates/cli/src/cli_args/why.rs citations show pnpm why invokes this
code path to build its output, so a deeply nested dependency graph from an attacker-controlled
lockfile can trigger the crash.

CLAUDE.md: Async and Loop Practices: Prefer Async FS and async/await; Parallelize Independent Work; Hoist Loop Invariants
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[198-240]
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[258-352]
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[194-231]
pnpm/crates/cli/src/cli_args/why.rs[114-168]

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

## Issue description
`pnpm why` can crash via stack overflow because the dependents-tree implementation performs unbounded recursive traversals in both the reverse tree construction (`walk_reverse`) and package-node resolution (a nested recursive `walk` inside `resolve_package_nodes`). Even for valid, acyclic graphs, recursion depth scales with the longest simple path length, so attacker-controlled lockfiles/graphs can trigger a denial-of-service.

## Issue Context
- The current implementation uses DFS-style recursion in two places: a top-down traversal for resolving package nodes and a reverse traversal for building the dependents output.
- While `visited`/`expanded` cycle/duplication guards prevent infinite recursion and repeated expansion, they do not limit call-stack depth on long acyclic chains.
- Lockfiles and dependency graphs are treated as attacker-controlled inputs per the repo security review guidance, and PR Compliance ID 9 emphasizes avoiding unsafe/inefficient loop patterns; unbounded recursion is a common DoS vector.
- `why.rs` calls into this dependents-tree code path to produce `pnpm why` output, so the crash is reachable from the CLI.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[198-240]
- pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[258-352]
- pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[204-231]
- pnpm/crates/cli/src/cli_args/why.rs[114-168]

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


3. parse_search_query missing code ✗ Dismissed 📘 Rule violation ☼ Reliability
Description
The new invalid search-query error is constructed without a stable ERR_PNPM_* code, making it
harder to reliably handle in scripts and inconsistent with pnpm-style user-reachable errors. This
also increases the risk of message-based breakage if wording changes.
Code

pnpm/crates/cli/src/cli_args/deps_tree/search.rs[R105-112]

+fn parse_search_query(query: &str) -> miette::Result<ParsedQuery> {
+    let (name, spec) = split_query(query);
+    let match_name = create_matcher(std::slice::from_ref(&name.to_string()));
+    let match_version = match spec {
+        None => None,
+        Some(spec) => Some(spec.parse::<Range>().map_err(|_| {
+            miette::miette!("Invalid query - {query}. List can search only by version or range")
+        })?),
Evidence
PR Compliance ID 5 requires user-reachable errors to carry stable error codes. The new invalid query
path constructs a plain miette::miette!(...) message without code = "ERR_PNPM_...".

CLAUDE.md: User-Reachable Errors Must Use PnpmError and Errors Must Not Be Swallowed
pnpm/crates/cli/src/cli_args/deps_tree/search.rs[105-112]

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_search_query()` returns a user-reachable error without a stable pnpm-style error code.

## Issue Context
This error is triggered by CLI user input (`pnpm ls "name@<spec>"`). The compliance checklist requires stable, user-friendly errors with stable codes.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/search.rs[105-112]

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


View more (2)
4. resolve_package_path joins raw alias ✓ Resolved 📘 Rule violation ⛨ Security
Description
resolve_package_path() builds a filesystem path from the lockfile-derived alias and
canonicalizes it without validating that alias cannot escape node_modules (e.g., via ..
segments or absolute paths). This can enable unintended path traversal/file reads via
--long/--find-by manifest access and also bypasses the repo’s existing
ERR_PNPM_INVALID_DEPENDENCY_NAME guard used elsewhere.
Code

pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[R217-244]

+    let constructed = env
+        .virtual_store_dir
+        .join(dep_path.to_virtual_store_name(env.virtual_store_dir_max_length))
+        .join("node_modules")
+        .join(name);
+
+    if !env.is_global_virtual_store() {
+        return constructed;
+    }
+
+    let node_modules_dir = match &ctx.parent_dir {
+        Some(parent_dir) => {
+            let mut dir = parent_dir.parent().map(Path::to_path_buf).unwrap_or_default();
+            // Scoped parents live one level deeper (`node_modules/@scope/pkg`).
+            if dir.file_name().is_some_and(|component| component.to_string_lossy().starts_with('@'))
+                && let Some(grandparent) = dir.parent()
+            {
+                dir = grandparent.to_path_buf();
+            }
+            dir
+        }
+        None => env.modules_dir.clone(),
+    };
+    dunce::canonicalize(node_modules_dir.join(alias)).unwrap_or(constructed)
+}
+
+#[cfg(test)]
+mod tests;
Evidence
The new code canonicalizes node_modules_dir.join(alias) when the virtual store is global, with no
validation that alias is a safe package-name-shaped path. The repo already defines and uses an
explicit invalid-alias error (ERR_PNPM_INVALID_DEPENDENCY_NAME) describing this exact escape risk,
indicating the expected contract is to reject such aliases rather than interpret them as paths.

AGENTS.md: Use correct error types and handling patterns (PnpmError for user errors; no swallowing; catch specific cases)
AGENTS.md: Avoid code duplication: reuse existing utilities and extract shared logic
pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[217-248]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[285-296]

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

## Issue description
`resolve_package_path()` joins `node_modules_dir.join(alias)` and canonicalizes it. Because `alias` ultimately comes from lockfile dependency keys, a malformed/attacker-controlled lockfile can provide values containing traversal segments or absolute paths, causing the computed path to escape the intended `node_modules` root.

## Issue Context
The repo already treats invalid dependency aliases as a user-facing error with code `ERR_PNPM_INVALID_DEPENDENCY_NAME` in the resolver layer. The new list/why tree-builder should apply an equivalent validation when turning aliases into filesystem paths (especially before `canonicalize()`), rather than trusting the string.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[217-248]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[285-296]

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


5. Finder link path misbased ✓ Resolved 🐞 Bug ⛨ Security
Description
finder_candidates() resolves link: edges with target == None relative to env.lockfile_dir
instead of the parent importer directory, so --find-by can read the wrong package.json (and
produce wrong matches/messages) for nested workspace projects. With .. segments in link_target,
this also makes it easier to resolve outside the intended workspace root than the main tree walk
does.
Code

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[R103-116]

+                None => {
+                    let link_target = edge.link_target.clone().unwrap_or_default();
+                    push(
+                        edge.alias.clone(),
+                        None,
+                        ManifestSource {
+                            path: pacquet_fs::lexical_normalize(
+                                &env.lockfile_dir.join(link_target),
+                            ),
+                            integrity: None,
+                            name: edge.alias.clone(),
+                            version: edge.ref_display.clone(),
+                        },
+                    );
Evidence
finder_candidates() currently bases unresolvable link paths on env.lockfile_dir, while the tree
walk bases link resolution on the parent node id (importer vs package) and then joins the link
target against that parent-specific base; this mismatch means finder evaluation can read a different
path than the tree would.

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[66-116]
pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[126-152]
pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[131-136]

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

## Issue description
`finder_candidates()` computes `ManifestSource.path` for `edge.target == None` using `env.lockfile_dir.join(link_target)`, which disagrees with the main tree materialization (`get_tree`/`get_pkg_info`) that resolves `link_target` relative to the *parent importer directory* for importer parents.

## Issue Context
This causes `--find-by` finder evaluation to inspect a different manifest than the dependency edge actually refers to, especially for nested importers (e.g. `packages/a` with `link:../b`).

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[66-116]
- pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[126-152]
- pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[131-136]

## Implementation notes
- Change the graph iteration in `finder_candidates()` to retain the parent node id (iterate `for (parent_id, node) in &graph.nodes`), and for `edge.target == None` choose the same `linked_path_base_dir` logic as `get_tree`:
 - `TreeNodeId::Importer(importer_id)` => `env.lockfile_dir.join(importer_id)`
 - `TreeNodeId::Package(_)` => `env.lockfile_dir.clone()`
- Then compute `lexical_normalize(base_dir.join(link_target))`.
- (Optional hardening) If you intend to prevent escaping the workspace root for these unresolvable edges, add an explicit boundary check before reading/using the path.

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



Remediation recommended

6. Finder prototype dispatch 🐞 Bug ⛨ Security ⭐ New
Description
The pnpmfile worker resolves a finder via finders[req.name] without ensuring req.name is an own
property, so inherited functions (e.g. constructor, toString) can be invoked even though
get_finder_names() only enumerates own keys. This creates a mismatch between discoverable finder
names and callable functions, and can yield unexpected matches or worker-side errors for crafted
--find-by values.
Code

pnpm/crates/hooks/src/worker.rs[R388-403]

+    if (req.target === 'finder') {{
+      const finders = mod && mod.finders;
+      const finder = (finders != null && typeof finders === 'object') ? finders[req.name] : null;
+      if (typeof finder !== 'function') {{
+        send({{ ok: false }});
+        return;
+      }}
+      const ctx = req.ctx || {{}};
+      const res = await finder({{
+        alias: ctx.alias,
+        name: ctx.name,
+        version: ctx.version,
+        readManifest: () => ctx.manifest,
+      }});
+      send({{ ok: res === undefined ? false : res }});
+      return;
Evidence
Object.keys(finders) returns only own enumerable properties, but finders[req.name] can resolve
inherited properties; the current code then calls the resolved function.

pnpm/crates/hooks/src/worker.rs[381-402]

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 Node worker’s `finder` dispatch uses `finders[req.name]`, which can resolve prototype-chain properties. This allows `--find-by` to call inherited functions that are not actually exported as finders (and not returned by `Object.keys(finders)`), creating inconsistent behavior.

### Issue Context
Finder names are discovered via `Object.keys(finders)` but invoked via bracket lookup without an own-property check.

### Fix Focus Areas
- pnpm/crates/hooks/src/worker.rs[381-403]

### Proposed fix
In the worker JS snippet, gate `finder` lookup with an own-property check:
- Ensure `finders` is a non-null object.
- Require `Object.prototype.hasOwnProperty.call(finders, req.name)` before reading `finders[req.name]`.
- Keep the `typeof finder === 'function'` check.
This makes callable finders exactly match the discoverable set.

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


7. Unused extraneous scan 🐞 Bug ➹ Performance
Description
hierarchy_for_project() always scans node_modules and may read/parse many package.json files
to populate unsaved_dependencies when not searching, even though the default tree renderer is
configured with show_extraneous: false and won’t display them. This adds avoidable filesystem and
JSON-parsing overhead to common pnpm list tree output on large projects.
Code

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[R249-256]

+    // Unsaved (extraneous) dependencies: packages present in the
+    // project's modules dir but absent from its lockfile entry. They
+    // are irrelevant while searching — they are not in the lockfile
+    // graph and cannot contain paths to the search target.
+    if opts.search.is_none() {
+        hierarchy.unsaved_dependencies =
+            read_unsaved_dependencies(importer, project_dir, &project_modules_dir)?;
+    }
Evidence
The build step populates unsaved_dependencies on the non-search path by scanning node_modules
and potentially reading/parsing package.json for entries, but the default tree renderer is
explicitly configured to not display extraneous/unsaved dependencies; the render code only uses
unsaved_dependencies when show_extraneous is enabled.

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[249-256]
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[331-455]
pnpm/crates/cli/src/cli_args/list.rs[342-351]
pnpm/crates/cli/src/cli_args/list/render.rs[83-121]

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

## Issue description
`deps_tree::build::hierarchy_for_project()` computes `unsaved_dependencies` (node_modules enumeration + `package.json` reads/parses) whenever `opts.search.is_none()`, but the default tree output path configures the renderer with `show_extraneous: false`, so this data is unused for the common `pnpm list` tree view.

## Issue Context
- Tree rendering only includes `unsaved_dependencies` when `RenderTreeOptions.show_extraneous` is true.
- Parseable and JSON outputs *do* currently include `unsavedDependencies`, so they may legitimately need this data.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[249-256]
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[328-455]
- pnpm/crates/cli/src/cli_args/list.rs[342-358]

### Suggested approach
1. Add a flag to `BuildTreeOptions` (e.g., `collect_unsaved_dependencies: bool`).
2. Set it from `ListArgs::render_projects()` based on the selected output:
  - `ReportAs::Tree`: `collect_unsaved_dependencies = false` (unless/ until you add an explicit “show extraneous” mode)
  - `ReportAs::Json | ReportAs::Parseable`: `collect_unsaved_dependencies = true`
3. In `hierarchy_for_project()`, guard the `read_unsaved_dependencies(...)` call with `opts.collect_unsaved_dependencies && opts.search.is_none()` so default tree output skips the scan.

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


8. ListArgs::run() prints output 📘 Rule violation ⚙ Maintainability
Description
ListArgs::run() prints to stdout (print_output(&output)) instead of returning data for the
CLI/dispatch layer to print, reducing unit-testability and breaking the intended layering. The same
printing helper is also used by WhyArgs::run(), spreading the pattern across commands.
Code

pnpm/crates/cli/src/cli_args/list.rs[R117-128]

+    pub async fn run(self, config: &Config, dir: &Path, recursive: bool) -> miette::Result<()> {
+        let output = if self.global {
+            self.run_global(config).await?
+        } else if recursive {
+            self.run_recursive(config, dir).await?
+        } else {
+            let lockfile_dir = local_lockfile_dir(config, dir);
+            self.render_projects(config, &[dir.to_path_buf()], &self.packages, &lockfile_dir, true)
+                .await?
+        };
+        print_output(&output);
+        Ok(())
Evidence
The checklist explicitly requires command handlers to be unit-testable by returning data rather than
printing. The modified list handler prints via print_output, and why does the same, keeping
presentation inside handlers instead of the dispatch layer.

CLAUDE.md: Configuration and layering: flow configurable values through @pnpm/config and keep command handlers unit-testable by returning data instead of printing
pnpm/crates/cli/src/cli_args/list.rs[117-128]
pnpm/crates/cli/src/cli_args/list.rs[388-399]
pnpm/crates/cli/src/cli_args/why.rs[169-178]

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 `list` (and `why`) command handlers print directly instead of returning output for the CLI layer to print.

## Issue Context
The compliance rule for configuration/layering requires command handlers to return data and keep printing/presentation in the CLI dispatch layer.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/list.rs[117-128]
- pnpm/crates/cli/src/cli_args/list.rs[388-399]
- pnpm/crates/cli/src/cli_args/why.rs[169-178]
- pnpm/crates/cli/src/cli_args/dispatch_query.rs[121-126]

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


View more (14)
9. Recursive dep-type traversal ✓ Resolved 🐞 Bug ☼ Reliability
Description
detect_in_subgraph() recursively walks dependency chains from the lockfile and can stack-overflow
on unusually deep (but valid) graphs, crashing pnpm list/why. This traversal runs on every
deps-tree build because LoadedState::env() unconditionally calls detect_dep_types().
Code

pnpm/crates/cli/src/cli_args/deps_tree/dep_types.rs[R55-80]

+fn detect_in_subgraph(ctx: &mut Ctx<'_>, dep_paths: &[PkgNameVerPeer], dev: bool) {
+    for dep_path in dep_paths {
+        if !ctx.walked.insert((dep_path.clone(), dev)) {
+            continue;
+        }
+        let Some(snapshot) =
+            ctx.lockfile.snapshots.as_ref().and_then(|snapshots| snapshots.get(dep_path))
+        else {
+            continue;
+        };
+        if dev {
+            ctx.not_prod_only.insert(dep_path.clone());
+            ctx.dep_types.insert(dep_path.clone(), DepType::DevOnly);
+        } else if ctx.dep_types.get(dep_path) == Some(&DepType::DevOnly) {
+            ctx.dep_types.insert(dep_path.clone(), DepType::DevAndProd);
+        } else if !ctx.dep_types.contains_key(dep_path) && !ctx.not_prod_only.contains(dep_path) {
+            ctx.dep_types.insert(dep_path.clone(), DepType::ProdOnly);
+        }
+        for group in [&snapshot.dependencies, &snapshot.optional_dependencies] {
+            let child_paths: Vec<PkgNameVerPeer> = group
+                .iter()
+                .flatten()
+                .filter_map(|(alias, dep_ref)| dep_ref.resolve(alias))
+                .collect();
+            detect_in_subgraph(ctx, &child_paths, dev);
+        }
Evidence
The dep-type detector is implemented via self-recursion with no depth bound, and it is invoked
unconditionally when creating PkgInfoEnv, making a deep dependency chain sufficient to crash
commands that build the tree.

pnpm/crates/cli/src/cli_args/deps_tree/dep_types.rs[55-80]
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[83-130]

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

### Issue description
`detect_in_subgraph()` uses recursion over lockfile snapshot edges. Deep acyclic chains can exhaust the thread stack and crash the process.

### Issue Context
This dep-type classification is executed as part of deps-tree environment construction, so it affects `pnpm list` and `pnpm why` whenever a lockfile-backed tree is built.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/dep_types.rs[55-80]
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[83-130]

### Suggested fix
Replace recursion with an explicit work stack/queue (iterative DFS/BFS). Keep the existing `walked` de-dup key `(dep_path, dev)` to avoid repeated processing, but drive the traversal with `while let Some(item) = stack.pop()` and push child depPaths onto the stack instead of calling `detect_in_subgraph()` recursively.

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


10. walk_reverse sort allocates Strings 📘 Rule violation ➹ Performance
Description
walk_reverse() sorts reverse edges with a comparator that repeatedly calls resolve_parent_name()
and TreeNodeId::serialize(), allocating fresh Strings during each comparison and amplifying work
to O(k log k) allocations for high-fanout nodes. Precomputing sort keys once per edge (e.g., via
sort_by_cached_key or a decorate-sort-undecorate approach) avoids repeated allocations and reduces
CPU/memory churn.
Code

pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[R263-271]

+    // Sort by parent name (serialized id as tiebreaker) so
+    // deduplication is deterministic: the first parent always gets
+    // fully expanded.
+    let mut sorted_edges: Vec<&ReverseEdge> = reverse_edges.iter().collect();
+    sorted_edges.sort_by(|a, b| {
+        resolve_parent_name(ctx, &a.parent)
+            .cmp(&resolve_parent_name(ctx, &b.parent))
+            .then_with(|| a.parent.serialize().cmp(&b.parent.serialize()))
+    });
Evidence
PR Compliance ID 9 emphasizes hoisting loop invariants and avoiding repeated work; here, the
sort_by comparator recomputes values on every comparison. The cited code path calls
resolve_parent_name() (which returns an owned String) and TreeNodeId::serialize() (also
producing an owned String) inside the comparator, so sorting (which performs O(k log k)
comparisons) multiplies allocations instead of computing the parent-name/serialized-id keys once per
element and reusing them during ordering.

CLAUDE.md: Async and Loop Practices: Prefer Async FS and async/await; Parallelize Independent Work; Hoist Loop Invariants
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[263-272]
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[263-271]
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[355-373]

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_reverse()` sorts `reverse_edges` using a `sort_by` comparator that allocates new `String`s during comparisons by calling `resolve_parent_name()` and `TreeNodeId::serialize()`. Because sorting performs O(k log k) comparisons for k edges, this can multiply allocations and CPU/memory churn, especially for packages with many dependents.

## Issue Context
This code runs on potentially large graphs and is exercised when a searched package has many dependents (large `reverse_edges`), so reducing per-comparison allocations improves `pnpm why` responsiveness. PR Compliance ID 9 also calls for hoisting loop invariants and avoiding unnecessary repeated work, which applies to caching sort keys rather than recomputing them in the comparator.

A suitable fix is to precompute the sort keys once per edge (e.g., `sort_by_cached_key` or decorate-sort-undecorate): build a vector of tuples like `(parent_name: String, serialized_id: String, edge_ref/edge_idx)`, sort by the tuple, then iterate in sorted order.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[263-272]
- pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[355-373]

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


11. Global dir scan quadratic 📘 Rule violation ➹ Performance
Description
find_global_install_dirs() de-duplicates install directories by calling
Vec::contains()/install_dirs.contains() inside a loop, causing O(n²) runtime as the number of
candidate global packages/install dirs grows. Tracking seen directories with a HashSet (or
BTreeSet) avoids this unnecessary quadratic behavior on the global listing path.
Code

pnpm/crates/global/src/list.rs[R41-47]

+    let packages = scan_global_packages(global_dir)?;
+    let mut install_dirs: Vec<PathBuf> = Vec::new();
+    for pkg in packages {
+        let matched = pkg.dependencies.iter().any(|(alias, _)| matches_params(params, alias));
+        if matched && !install_dirs.contains(&pkg.install_dir) {
+            install_dirs.push(pkg.install_dir);
+        }
Evidence
PR Compliance ID 9 calls out avoiding unnecessary repeated work in loops, and the cited
implementation performs linear membership checks via install_dirs.contains(...) on an ever-growing
Vec during insertion. Because contains is O(k) per check and it is executed for each candidate
directory, the overall time becomes O(k²) for k unique directories, which is avoidable by using a
set for constant- (or log-) time membership tests.

CLAUDE.md: Async and Loop Practices: Prefer Async FS and async/await; Parallelize Independent Work; Hoist Loop Invariants
pnpm/crates/global/src/list.rs[41-47]
pnpm/crates/global/src/list.rs[37-49]

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

## Issue description
`find_global_install_dirs()` currently de-duplicates install directories by running linear membership tests (`Vec::contains()` / `install_dirs.contains()`) inside a loop, resulting in quadratic O(n²) behavior as the number of unique install dirs (or candidate install groups) grows.

## Issue Context
This function is used by `pnpm ls -g --depth <n>` to narrow install groups and should remain efficient as global installs grow; even if typical global installs are small, the repeated work in the loop is avoidable and conflicts with the intent of PR Compliance ID 9.

## Fix Focus Areas
- pnpm/crates/global/src/list.rs[37-48]

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


12. Lockfile-only loads current lockfile 📘 Rule violation ➹ Performance
Description
LoadedState::load() reads the modules manifest and attempts to load the current lockfile even when
check_wanted_lockfile_only is true, adding avoidable filesystem I/O on --lockfile-only paths.
This extra work can slow commands and increases the surface for unexpected I/O errors in a mode
intended to avoid node_modules checks.
Code

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[R42-62]

+    pub(crate) fn load(
+        lockfile_dir: &Path,
+        modules_dir_opt: Option<&Path>,
+        check_wanted_lockfile_only: bool,
+    ) -> miette::Result<LoadedState> {
+        let modules_dir_raw = match modules_dir_opt {
+            Some(dir) if dir.is_absolute() => dir.to_path_buf(),
+            Some(dir) => lockfile_dir.join(dir),
+            None => lockfile_dir.join("node_modules"),
+        };
+        let modules_dir = realpath_missing(&modules_dir_raw);
+        let modules = read_modules_manifest::<Host>(&modules_dir)
+            .into_diagnostic()
+            .wrap_err("read the modules manifest")?;
+        let current_lockfile =
+            Lockfile::load_current_from_virtual_store_dir(&modules_dir.join(".pnpm"))
+                .into_diagnostic()
+                .wrap_err("load the current lockfile")?;
+        let wanted_lockfile = Lockfile::load_wanted_from_dir(lockfile_dir)
+            .into_diagnostic()
+            .wrap_err("load the wanted lockfile")?;
Evidence
PR Compliance ID 9 requires hoisting/avoiding unnecessary work; the new loader performs I/O that is
not needed when --lockfile-only selects the wanted lockfile path, increasing overhead for a
performance-sensitive CLI command.

CLAUDE.md: Async and Loop Practices: Prefer Async FS and async/await; Parallelize Independent Work; Hoist Loop Invariants
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[42-69]

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

## Issue description
`LoadedState::load()` always reads `.modules.yaml` and the current lockfile, even when `--lockfile-only` is requested via `check_wanted_lockfile_only`.

## Issue Context
In `--lockfile-only` mode, the tree should be buildable from the wanted lockfile without paying extra `node_modules`-adjacent I/O.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[42-69]

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


13. Symlink followed in scan 🐞 Bug ⛨ Security
Description
collect_module_names() recurses into top-level node_modules/@scope entries without verifying
they are real directories (and not symlinks). If node_modules/@scope is a symlink, pnpm list can
end up enumerating directories outside node_modules, potentially causing unexpected filesystem
traversal and large/unbounded work on local runs.
Code

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[R372-408]

+fn collect_module_names(
+    modules_dir: &Path,
+    scope: Option<&str>,
+    names: &mut Vec<String>,
+) -> io::Result<()> {
+    let parent_dir = match scope {
+        Some(scope) => modules_dir.join(scope),
+        None => modules_dir.to_path_buf(),
+    };
+    let entries = match std::fs::read_dir(&parent_dir) {
+        Ok(entries) => entries,
+        // A missing directory is "no packages"; every other error is
+        // surfaced, matching `readModulesDir`, which only swallows ENOENT.
+        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
+        Err(error) => return Err(error),
+    };
+    for entry in entries {
+        let entry = entry?;
+        let file_name = entry.file_name();
+        let Some(name) = file_name.to_str() else {
+            continue;
+        };
+        if name.starts_with('.') {
+            continue;
+        }
+        if entry.file_type().is_ok_and(|file_type| file_type.is_file()) {
+            continue;
+        }
+        if scope.is_none() && name.starts_with('@') {
+            collect_module_names(modules_dir, Some(name), names)?;
+            continue;
+        }
+        match scope {
+            Some(scope) => names.push(format!("{scope}/{name}")),
+            None => names.push(name.to_string()),
+        }
+    }
Evidence
The scan only filters out regular files and then recurses on any @* entry at the top level,
without confirming it is a directory and not a symlink. This makes the recursion path dependent on
whatever read_dir resolves for that path, which can be outside node_modules if the @scope
entry is a symlink.

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[372-409]

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

### Issue description
`collect_module_names()` treats any non-file entry as eligible for recursion when the name starts with `@`, which can cause `std::fs::read_dir()` to traverse through a symlinked `node_modules/@scope` directory and enumerate outside the intended `node_modules` subtree.

### Issue Context
This code runs when scanning `node_modules` to identify “unsaved/extraneous” dependencies. A scoped directory (`@scope`) should be treated as a real directory container; symlinks (and non-directories) should not be recursed into.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[372-409]

Suggested implementation direction:
- When iterating entries, fetch `file_type` once and:
 - `continue` unless `file_type.is_dir()`.
 - `continue` if `file_type.is_symlink()` (or use `symlink_metadata`/`file_type` to explicitly reject symlinks).
- Apply the same guard before:
 - Recursing into `@scope` entries.
 - Treating an entry as a package directory name.

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


14. realpath_missing duplicated again 📘 Rule violation ⚙ Maintainability
Description
The PR introduces another realpath_missing helper in a second location, diverging from an existing
realpath_missing already present elsewhere in the repo. This duplication increases confusion and
future bug risk due to differing semantics under the same name.
Code

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[R303-326]

+/// Resolve symlinks in the deepest existing ancestor of `path`,
+/// re-appending the missing tail (counterpart of the `realpath-missing`
+/// package).
+pub(crate) fn realpath_missing(path: &Path) -> PathBuf {
+    let mut current = path.to_path_buf();
+    let mut tail: Vec<std::ffi::OsString> = Vec::new();
+    loop {
+        match dunce::canonicalize(&current) {
+            Ok(mut real) => {
+                for component in tail.iter().rev() {
+                    real.push(component);
+                }
+                return real;
+            }
+            Err(_) => match (current.parent(), current.file_name()) {
+                (Some(parent), Some(name)) => {
+                    tail.push(name.to_os_string());
+                    current = parent.to_path_buf();
+                }
+                _ => return lexical_normalize(path),
+            },
+        }
+    }
+}
Evidence
PR Compliance ID 2 requires avoiding duplicated utilities. The PR adds a new realpath_missing() in
deps-tree while another realpath_missing() already exists in pnpm/crates/pack, creating
duplicated/competing implementations.

CLAUDE.md: Avoid Duplication by Reusing Existing Repo Utilities and Established Libraries
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[303-326]
pnpm/crates/pack/src/lib.rs[856-861]

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

## Issue description
A new `realpath_missing()` implementation was added even though the repo already defines a function with the same name elsewhere.

## Issue Context
Having multiple helpers with the same name but different semantics makes it hard to know which behavior is intended and increases maintenance cost.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[303-326]
- pnpm/crates/pack/src/lib.rs[856-861]

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


15. Unbounded recursion in get_tree ✓ Resolved 🐞 Bug ☼ Reliability
Description
materialize_children() and fix_circular_refs() are implemented recursively, and
MaxDepth::Unlimited does not decrement depth. On sufficiently deep (even acyclic) dependency
chains, this can exhaust the process stack and crash pnpm list/why, making the commands
susceptible to denial-of-service on pathological lockfiles/graphs.
Code

pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[R201-210]

+                        ancestors.insert(target.clone());
+                        let child_result = materialize_children(
+                            opts,
+                            cache,
+                            ancestors,
+                            target,
+                            child_tree_max_depth,
+                            Some(Path::new(&package_info.path)),
+                        );
+                        ancestors.remove(target);
Evidence
MaxDepth::Unlimited explicitly does not decrement, and the implementation recurses into children
and later recurses again to mark circular references. This combination means recursion depth is
effectively controlled by the deepest dependency chain in the graph when unlimited depth is
requested.

pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[18-45]
pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[105-235]
pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[289-316]

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 dependency tree materialization uses recursion in both the main walk (`materialize_children`) and the circular-marking pass (`fix_circular_refs`). With `MaxDepth::Unlimited`, recursion depth is bounded only by graph depth, which can be large enough to cause stack overflow.

### Issue Context
Although typical dependency graphs are not extremely deep, this is still a robustness/DoS vector when processing unusually deep graphs (including intentionally-crafted lockfiles).

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[18-45]
- pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[105-235]
- pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[289-316]

Suggested implementation direction:
- Convert `fix_circular_refs` to an explicit stack-based DFS (Vec stack of iterators or indices).
- Consider similarly converting `materialize_children` to an explicit stack, or introduce a hard recursion ceiling even when `MaxDepth::Unlimited` (e.g., detect depth > N and return a structured error).

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


16. read_project_manifest duplicates reader 📘 Rule violation ⚙ Maintainability
Description
A new manifest reader (read_project_manifest) reimplements manifest reading/parsing instead of
reusing the existing workspace manifest utilities, increasing maintenance burden and behavior drift
(e.g., package.yaml handling and structured error types). This violates the repo’s
reuse/duplication guidance.
Code

pnpm/crates/cli/src/cli_args/deps_tree/build.rs[R464-478]

+/// Read `name` / `version` / `private` from a project manifest,
+/// treating an unreadable manifest as empty (mirroring the TypeScript
+/// `safeReadProjectManifestOnly`).
+pub(crate) fn read_project_manifest(project_dir: &Path) -> ProjectManifestSummary {
+    let Ok(bytes) = std::fs::read(project_dir.join("package.json")) else {
+        return ProjectManifestSummary::default();
+    };
+    let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
+        return ProjectManifestSummary::default();
+    };
+    ProjectManifestSummary {
+        name: manifest.get("name").and_then(serde_json::Value::as_str).map(str::to_string),
+        version: manifest.get("version").and_then(serde_json::Value::as_str).map(str::to_string),
+        private: manifest.get("private").and_then(serde_json::Value::as_bool).unwrap_or(false),
+    }
Evidence
PR Compliance ID 2 requires reusing existing repo utilities instead of duplicating non-trivial
logic. The PR adds a new manifest-reading implementation while an established one already exists in
pacquet_workspace.

CLAUDE.md: Avoid Duplication by Reusing Existing Repo Utilities and Established Libraries
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[464-478]
pnpm/crates/workspace/src/project_manifest.rs[60-92]

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

## Issue description
`read_project_manifest()` duplicates existing project manifest reading logic that already exists in `pacquet_workspace`.

## Issue Context
The repo already provides `pacquet_workspace::try_read_project_manifest()` / `safe_read_project_manifest_only()` with established parsing behavior and error codes.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[464-478]
- pnpm/crates/workspace/src/project_manifest.rs[60-92]

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


17. Finder evaluation blows up 🐞 Bug ➹ Performance
Description
evaluate_finders() runs each --find-by finder for every candidate package and deep-clones the
full ctx (including the manifest JSON) for every call, resulting in O(candidates×finders) worker
IPC + JSON cloning. This can make pnpm list/why --find-by ... disproportionately slow on large
lockfiles or when multiple finders are provided.
Code

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[R145-166]

+        let ctx = serde_json::json!({
+            "alias": alias,
+            "name": source.name,
+            "version": source.version,
+            "manifest": manifest,
+        });
+        let mut messages: Vec<String> = Vec::new();
+        let mut found = false;
+        for finder in finders {
+            let verdict = finder
+                .hooks
+                .run_finder(&finder.name, ctx.clone())
+                .await
+                .map_err(|err| miette::miette!("running finder {}: {err}", finder.name))?;
+            match verdict {
+                serde_json::Value::String(message) => {
+                    found = true;
+                    messages.push(message);
+                }
+                other => {
+                    if truthy(&other) {
+                        found = true;
Evidence
evaluate_finders() builds a ctx containing manifest and then calls `run_finder(...,
ctx.clone()) inside a for finder in finders` loop for each candidate, creating
O(candidates×finders) deep clones and worker requests; both list and why invoke this when
--find-by is set.

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[131-180]
pnpm/crates/cli/src/cli_args/list.rs[286-304]
pnpm/crates/cli/src/cli_args/why.rs[154-160]

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

### Issue description
`evaluate_finders()` performs a nested loop over `(candidate × finder)` and calls `run_finder(..., ctx.clone())`, where `ctx` contains the full manifest JSON. This creates avoidable deep JSON clones and amplifies Node-worker IPC overhead.

### Issue Context
This is on the `--find-by` path for both `pnpm list` and `pnpm why`, and will scale poorly on large dependency graphs.

### Fix Focus Areas
- Implement batching / reduce IPC calls: add a worker endpoint that accepts many candidates for one finder and returns an array/map of verdicts.
- Avoid deep-cloning `ctx`: adjust the Rust→worker request building to serialize borrowed data (e.g., a `struct FinderRequest<'a> { .., ctx: &'a Value }` serialized directly) or change `run_finder` to take `&Value`/`Arc<Value>`.
- Consider bounded concurrency (`buffer_unordered`) if batching isn’t feasible.

- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[131-180]
- pnpm/crates/cli/src/cli_args/list.rs[286-324]
- pnpm/crates/cli/src/cli_args/why.rs[154-160]

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


18. Long reads manifests repeatedly 🐞 Bug ➹ Performance
Description
read_long_pkg_info() does a fresh std::fs::read + JSON parse of <pkg_dir>/package.json per
call, and the list/why renderers call it for every rendered node in --long mode. For large trees
this can trigger a very large number of synchronous reads/parses and significantly slow --long
output.
Code

pnpm/crates/cli/src/cli_args/deps_tree/render.rs[R169-176]

+/// Read the `--long` manifest details from `<pkg_dir>/package.json`.
+/// Unreadable manifests degrade to a placeholder description, matching
+/// the TypeScript CLI.
+pub(crate) fn read_long_pkg_info(pkg_dir: &Path) -> LongPkgInfo {
+    let manifest: Option<serde_json::Value> = std::fs::read(pkg_dir.join("package.json"))
+        .ok()
+        .and_then(|bytes| serde_json::from_slice(&bytes).ok());
+    let Some(manifest) = manifest else {
Evidence
read_long_pkg_info() always performs a full file read and JSON parse; the list and why tree
renderers call it inside their per-node render loops when --long is enabled, which scales linearly
with the number of rendered nodes.

pnpm/crates/cli/src/cli_args/deps_tree/render.rs[169-198]
pnpm/crates/cli/src/cli_args/list/render.rs[147-184]
pnpm/crates/cli/src/cli_args/why/render.rs[47-61]

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

### Issue description
`read_long_pkg_info()` reads and parses `package.json` every time it’s invoked, and renderers call it per node. This repeats identical I/O/parse work and can dominate `pnpm list/why --long` runtime on large graphs.

### Issue Context
The long renderer only needs a handful of fields; many nodes can point at the same package path across repeated occurrences/deduped nodes.

### Fix Focus Areas
- Add a simple cache (e.g., `HashMap<PathBuf, LongPkgInfo>`) in the render pass and memoize by `node.path`.
- Alternatively, plumb a manifest/provider into renderers (e.g., from CAFS/store index) and reuse the already-available manifest data where possible.

- pnpm/crates/cli/src/cli_args/deps_tree/render.rs[169-198]
- pnpm/crates/cli/src/cli_args/list/render.rs[147-184]
- pnpm/crates/cli/src/cli_args/why/render.rs[47-61]

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


19. Canonicalize per edge 🐞 Bug ➹ Performance
Description
When the virtual store is global (outside the project’s node_modules), resolve_package_path()
calls dunce::canonicalize() to resolve through node_modules symlinks, and tree materialization
calls get_pkg_info() for every edge. In that configuration, large trees can incur many filesystem
canonicalizations and slow list/why output.
Code

pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[R227-241]

+    let node_modules_dir = match &ctx.parent_dir {
+        Some(parent_dir) => {
+            let mut dir = parent_dir.parent().map(Path::to_path_buf).unwrap_or_default();
+            // Scoped parents live one level deeper (`node_modules/@scope/pkg`).
+            if dir.file_name().is_some_and(|component| component.to_string_lossy().starts_with('@'))
+                && let Some(grandparent) = dir.parent()
+            {
+                dir = grandparent.to_path_buf();
+            }
+            dir
+        }
+        None => env.modules_dir.clone(),
+    };
+    dunce::canonicalize(node_modules_dir.join(alias)).unwrap_or(constructed)
+}
Evidence
The code explicitly gates the global-virtual-store branch via is_global_virtual_store(), and in
that branch uses dunce::canonicalize(...). The tree materializer calls get_pkg_info() within the
per-edge loop, so global-store setups can execute canonicalize repeatedly across large graphs.

pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[44-51]
pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[206-241]
pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[126-154]

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 global-virtual-store mode, resolving each package path via `dunce::canonicalize(node_modules_dir.join(alias))` can become a high-volume filesystem operation because it’s invoked during per-edge materialization.

### Issue Context
This only applies when `PkgInfoEnv::is_global_virtual_store()` is true, but in that mode canonicalization happens inside `resolve_package_path()`, which is reached from `get_pkg_info()` during edge-walk materialization.

### Fix Focus Areas
- Add memoization for canonicalized results keyed by `(node_modules_dir, alias)` or `(parent_dir, alias)`.
- Consider using a cheaper symlink resolution path (`read_link` + lexical normalize) when the node_modules entry is a symlink, avoiding full canonicalization.

- pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[44-51]
- pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs[206-241]
- pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[126-154]

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


20. Finder failures lack stable code 📘 Rule violation ☼ Reliability
Description
Failures while loading/running --find-by finders are wrapped into generic miette::miette!(...)
messages without a stable pnpm-style error code, making them harder to handle and inconsistent with
existing pnpmfile failure codes. This violates the requirement that user-reachable errors carry
stable codes and actionable structure.
Code

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[R39-58]

+    let pnpmfiles = crate::config_deps::load_before_packing_hooks(config, lockfile_dir);
+    let mut finders_by_name: HashMap<String, Arc<dyn PnpmfileHooks>> = HashMap::new();
+    for hooks in pnpmfiles {
+        let names = hooks
+            .get_finder_names()
+            .await
+            .map_err(|err| miette::miette!("loading finders from a pnpmfile: {err}"))?;
+        for name in names {
+            finders_by_name.insert(name, Arc::clone(&hooks));
+        }
+    }
+    find_by
+        .iter()
+        .map(|name| match finders_by_name.get(name) {
+            Some(hooks) => Ok(FinderHandle { name: name.clone(), hooks: Arc::clone(hooks) }),
+            None => Err(miette::miette!(
+                code = "ERR_PNPM_FINDER_NOT_FOUND",
+                "No finder with name {name} is found"
+            )),
+        })
Evidence
The new finder resolution path wraps HookError with miette::miette!("loading finders...{err}")
(and similarly for running a finder) without attaching a stable code, even though these errors are
user-reachable via pnpm list/why --find-by. The checklist requires stable codes for user errors.

AGENTS.md: Use correct error types and handling patterns (PnpmError for user errors; no swallowing; catch specific cases)
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[39-67]
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[153-166]

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

## Issue description
`resolve_finders()` converts pnpmfile worker errors into plain `miette::miette!(...)` strings without a stable error code.

## Issue Context
The repo already has a stable code for pnpmfile execution failures (e.g. `ERR_PNPM_PNPMFILE_FAIL`). List/why finder loading and evaluation are user-invoked and should surface the same style of stable, code-addressable error.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[39-67]
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[153-166]

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


21. List builds graph twice ✓ Resolved 🐞 Bug ➹ Performance
Description
pnpm list --find-by builds a DependencyGraph to enumerate finder candidates, then calls
build_dependencies_tree() which rebuilds the graph again for rendering, duplicating traversal and
allocations. On large lockfiles this is avoidable hot-path overhead.
Code

pnpm/crates/cli/src/cli_args/list.rs[R283-329]

+            let searcher = if searching {
+                let mut searcher = Searcher::from_queries(params)?;
+                if !self.find_by.is_empty() {
+                    let finders = resolve_finders(config, lockfile_dir, &self.find_by).await?;
+                    let graph_root_ids: Vec<_> = project_dirs
+                        .iter()
+                        .map(|dir| {
+                            crate::cli_args::deps_tree::TreeNodeId::Importer(
+                                crate::cli_args::deps_tree::build::importer_id_for(
+                                    lockfile_dir,
+                                    dir,
+                                ),
+                            )
+                        })
+                        .collect();
+                    let graph = build_dependency_graph(
+                        &graph_root_ids,
+                        &BuildGraphOptions {
+                            lockfile: env.current_lockfile,
+                            include,
+                            only_projects: self.only_projects,
+                        },
+                    );
+                    let candidates = finder_candidates(env, &graph);
+                    let results = evaluate_finders(env, &finders, candidates).await?;
+                    searcher.set_finder_results(results);
                }
-                _ => Vec::new(),
+                Some(searcher)
+            } else {
+                None
            };

-            (dep_name, dep_version, peer, children)
-        }
-        None => (alias.clone(), version_str, false, Vec::new()),
-    };
-
-    let pkg_path = if let Some(key) = &snapshot_key {
-        let vsn = key.to_virtual_store_name(ctx.virtual_store_dir_max_length);
-        format!(".pnpm/{vsn}/node_modules/{resolved_name}")
-    } else if let Some(link_target) = spec.version.as_link_target() {
-        format!("link:{link_target}")
-    } else {
-        String::new()
-    };
-
-    Some(DepNode {
-        alias,
-        name: resolved_name,
-        version: resolved_version,
-        path: pkg_path,
-        is_peer,
-        is_dev: false,
-        is_optional: false,
-        dependencies: child_deps,
-    })
-}
-
-fn resolve_snapshot_children(
-    key: &PkgNameVerPeer,
-    ctx: &BuildContext,
-    current_depth: i32,
-) -> Vec<DepNode> {
-    let Some(snapshots) = ctx.snapshots else { return Vec::new() };
-    let Some(entry) = snapshots.get(key) else { return Vec::new() };
-
-    let peer_set = get_peer_set(key, ctx.packages);
-
-    let mut children = Vec::new();
-
-    let mut push_child = |dep_alias: &PkgName, dep_ref: &pacquet_lockfile::SnapshotDepRef| {
-        let child_key = dep_ref.resolve(dep_alias);
-        let alias_str = dep_alias.to_string();
-
-        let is_peer = ctx.exclude_peers && peer_set.contains(&alias_str);
-        if is_peer {
-            return;
-        }
-
-        let (child_name, child_version) = match &child_key {
-            Some(ck) => (ck.name.to_string(), ck.suffix.version().to_string()),
-            None => (alias_str.clone(), dep_ref.to_string()),
-        };
-
-        let grandchildren = match ctx.depth {
-            RecursionLimit::Unlimited => child_key
-                .as_ref()
-                .map_or(Vec::new(), |ck| resolve_snapshot_children(ck, ctx, current_depth + 1)),
-            RecursionLimit::Levels(n) if (current_depth as u32) < n => child_key
-                .as_ref()
-                .map_or(Vec::new(), |ck| resolve_snapshot_children(ck, ctx, current_depth + 1)),
-            _ => Vec::new(),
-        };
-
-        let pkg_path = if let Some(ck) = &child_key {
-            let vsn = ck.to_virtual_store_name(ctx.virtual_store_dir_max_length);
-            format!(".pnpm/{vsn}/node_modules/{child_name}")
-        } else if let Some(link_target) = dep_ref.as_link_target() {
-            format!("link:{link_target}")
-        } else {
-            String::new()
-        };
-
-        children.push(DepNode {
-            alias: alias_str,
-            name: child_name,
-            version: child_version,
-            path: pkg_path,
-            is_peer,
-            is_dev: false,
-            is_optional: false,
-            dependencies: grandchildren,
-        });
-    };
-
-    if let Some(deps) = &entry.dependencies {
-        for (dep_alias, dep_ref) in deps {
-            push_child(dep_alias, dep_ref);
-        }
-    }
-
-    if ctx.include_optional
-        && let Some(opt_deps) = &entry.optional_dependencies
-    {
-        for (dep_alias, dep_ref) in opt_deps {
-            push_child(dep_alias, dep_ref);
-        }
-    }
-
-    sort_deps(&mut children);
-    children
-}
-
-pub(crate) fn get_peer_set(
-    key: &PkgNameVerPeer,
-    packages: Option<&HashMap<PkgNameVerPeer, pacquet_lockfile::PackageMetadata>>,
-) -> HashSet<String> {
-    let Some(packages) = packages else { return HashSet::new() };
-    let base_key = key.without_peer();
-    packages
-        .get(&base_key)
-        .and_then(|meta| meta.peer_dependencies.as_ref())
-        .map(|peers| peers.keys().cloned().collect())
-        .unwrap_or_default()
-}
-
-pub(crate) fn sort_deps(deps: &mut [DepNode]) {
-    deps.sort_by(|a, b| a.name.cmp(&b.name));
-    for dep in deps.iter_mut() {
-        sort_deps(&mut dep.dependencies);
-    }
-}
-
-pub(crate) fn matches_params(params: &[String], alias: &str) -> bool {
-    if params.is_empty() {
-        return true;
-    }
-    params.iter().any(|pattern| glob_match(pattern, alias))
-}
-
-pub(crate) fn dep_or_subtree_matches(dep: &DepNode, params: &[String]) -> bool {
-    if params.is_empty() {
-        return true;
-    }
-    if matches_params(params, &dep.alias) || matches_params(params, &dep.name) {
-        return true;
-    }
-    dep.dependencies.iter().any(|child| dep_or_subtree_matches(child, params))
-}
-
-pub(crate) fn 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
-}
-
-pub(crate) fn read_root_manifest(
-    manifest_path: &Path,
-) -> miette::Result<(Option<String>, Option<String>, Option<bool>)> {
-    let content = std::fs::read_to_string(manifest_path)
-        .into_diagnostic()
-        .wrap_err_with(|| format!("failed to read {}", manifest_path.display()))?;
-    let parsed: Value = serde_json::from_str(&content)
-        .into_diagnostic()
-        .wrap_err_with(|| format!("failed to parse {}", manifest_path.display()))?;
-    let name = parsed.get("name").and_then(Value::as_str).map(str::to_string);
-    let version = parsed.get("version").and_then(Value::as_str).map(str::to_string);
-    let private = parsed.get("private").and_then(Value::as_bool);
-    Ok((name, version, private))
-}
-
-/// Scan `project_dir`'s `node_modules` for packages that are installed on
-/// disk but not recorded in `importer` (npm's "extraneous" dependencies),
-/// building a leaf [`DepNode`] for each. Mirrors the unsaved-dependency
-/// handling of the TypeScript CLI's `buildDependenciesTree`.
-fn read_unsaved_dependencies(
-    importer: &ProjectSnapshot,
-    project_dir: &Path,
-    config: &Config,
-) -> miette::Result<Vec<DepNode>> {
-    // Same per-importer modules-dir suffix the linker uses: the final
-    // component of `modules_dir` (default `node_modules`) under the
-    // project root.
-    let modules_dir_name =
-        config.modules_dir.file_name().unwrap_or_else(|| OsStr::new("node_modules"));
-    let modules_dir = project_dir.join(modules_dir_name);
-
-    let saved = saved_direct_dep_names(importer);
-    let mut unsaved: Vec<DepNode> = read_modules_dir_names(&modules_dir)
-        .into_diagnostic()
-        .wrap_err_with(|| format!("failed to read {}", modules_dir.display()))?
-        .into_iter()
-        .filter(|name| !saved.contains(name))
-        .map(|name| build_unsaved_node(&name, &modules_dir, project_dir))
-        .collect();
-    sort_deps(&mut unsaved);
-    Ok(unsaved)
-}
-
-/// The alias keys of an importer's `dependencies`, `devDependencies`, and
-/// `optionalDependencies` — the directory names a saved dependency owns
-/// under `node_modules`. Always spans all three groups regardless of
-/// `--prod`/`--dev`/`--optional`, matching the TypeScript CLI's
-/// `getAllDirectDependencies`.
-fn saved_direct_dep_names(importer: &ProjectSnapshot) -> HashSet<String> {
-    let mut names = HashSet::new();
-    let groups =
-        [&importer.dependencies, &importer.dev_dependencies, &importer.optional_dependencies];
-    for group in groups.into_iter().flatten() {
-        for name in group.keys() {
-            names.insert(name.to_string());
+            hierarchies = build_dependencies_tree(
+                &state,
+                env,
+                project_dirs,
+                &BuildTreeOptions {
+                    lockfile_dir,
+                    depth: self.depth.max_depth(),
+                    include,
+                    exclude_peer_dependencies: self.exclude_peers,
+                    only_projects: self.only_projects,
+                    search: searcher.as_ref(),
+                    show_deduped_search_matches: searcher.is_some(),
+                    modules_dir_opt: Some(config.modules_dir.as_path()),
+                },
+            )?;
Evidence
list.rs explicitly builds a graph for finder evaluation, and build_dependencies_tree()
separately constructs its own graph from the same project roots/options, so the work is duplicated
whenever --find-by is used.

pnpm/crates/cli/src/cli_args/list.rs[283-329]
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[155-181]

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

## Issue description
When `--find-by` is present, `list.rs` builds a dependency graph for `finder_candidates()`, but `build_dependencies_tree()` unconditionally builds another graph internally.

## Issue Context
Graph construction is a BFS over reachable nodes/edges. Rebuilding it adds CPU time and extra allocations on large workspaces.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/list.rs[283-329]
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[155-181]

## Implementation notes
- Refactor to build the graph once and reuse it for both:
 - Option A: expose an additional API like `build_dependencies_tree_with_graph(graph, ...)` that accepts a prebuilt `DependencyGraph` and uses it instead of calling `build_dependency_graph`.
 - Option B: move finder candidate enumeration into the tree-builder pipeline (build graph once, derive candidates, evaluate finders, then materialize).
- Keep the shared `MaterializationCache` behavior intact.

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


22. read_manifest() uses blocking fs 📘 Rule violation ➹ Performance
Description
The new async finder-evaluation path calls read_manifest(), which performs synchronous
std::fs::read of package.json (including from CAFS paths), blocking the async runtime and
degrading pnpm list/why --find-by performance on large graphs. Because these reads are unbounded
and may target paths derived from lockfile/link targets or node_modules (which can be symlinks or
special files), they can also lead to hangs or memory exhaustion on malicious or unusual filesystem
entries.
Code

pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[R189-207]

+fn read_manifest(
+    env: &PkgInfoEnv<'_>,
+    store_index: Option<&StoreIndex>,
+    source: &ManifestSource,
+) -> serde_json::Value {
+    if let Some(manifest) = read_manifest_from_cafs(env, store_index, source) {
+        return manifest;
+    }
+    std::fs::read(source.path.join("package.json"))
+        .ok()
+        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
+        .unwrap_or(serde_json::Value::Null)
+}
+
+fn read_manifest_from_cafs(
+    env: &PkgInfoEnv<'_>,
+    store_index: Option<&StoreIndex>,
+    source: &ManifestSource,
+) -> Option<serde_json::Value> {
Evidence
PR Compliance ID 10 requires preferring async filesystem APIs and safe parallelization in async
codepaths, yet the added read_manifest() uses blocking std::fs::read(...) and is invoked from
the new async evaluate_finders() loop, introducing avoidable blocking I/O during async command
execution. Additionally, the code reads package.json fully into memory with no bounds, and the
read path is derived from graph edges (including link_target resolution) rather than a fixed
trusted location, which makes the command susceptible to indefinite blocking (e.g., FIFO/device) or
OOM if the target is unexpectedly large.

CLAUDE.md: Async and Loops: Prefer Async FS and async/await; Parallelize Independent Work Safely
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[127-173]
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[189-217]
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[189-201]
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[66-116]

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 async `evaluate_finders()` flow invokes `read_manifest()`, but `read_manifest()` uses blocking `std::fs::read(...)` to load `package.json` (and reads from CAFS paths similarly), which can block Tokio runtime threads and degrade performance in `pnpm list/why --find-by` on large dependency graphs. In addition, these reads are unbounded and lack file-type/size checks, so if `package.json` resolves to a very large file, FIFO/device, or a symlink to such a target (via `node_modules` or `link:`/`link_target`-derived paths), the command can hang or exhaust memory.

## Issue Context
Compliance guidance (PR Compliance ID 10) calls for preferring async filesystem APIs and avoiding unnecessary serialization/blocking of I/O work in async codepaths. `ManifestSource.path` can originate from lockfile graph edges (including `link_target`-based paths), and `read_manifest()` is invoked per finder candidate when `--find-by` is used, so the impact scales with graph size and the trustworthiness of filesystem entries.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[66-116]
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[127-173]
- pnpm/crates/cli/src/cli_args/deps_tree/finders.rs[189-217]

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



Informational

23. Why reads extra manifests 🐞 Bug ➹ Performance ⭐ New
Description
WhyArgs::run() reads/parses package.json for every importer in lockfile.importers to build
importer_info even though the dependency graph is built from selected root_ids and may only
include a subset of importers. This adds synchronous filesystem reads and JSON parsing for importer
projects that cannot be reached from the selected roots, slowing pnpm why on large workspaces with
filtered selection.
Code

pnpm/crates/cli/src/cli_args/why.rs[R127-146]

+        let mut importer_info: HashMap<String, ImporterInfo> = HashMap::new();
+        for importer_id in lockfile.importers.keys() {
+            // A key that cannot be safely joined (a malformed or
+            // hostile lockfile) is never dereferenced; the raw key
+            // still names the importer in the output.
+            let manifest = safe_importer_dir(&lockfile_dir, importer_id)
+                .map(|importer_dir| read_project_manifest(&importer_dir))
+                .unwrap_or_default();
+            let name = manifest.name.unwrap_or_else(|| {
+                if importer_id == "." {
+                    "the root project".to_string()
+                } else {
+                    importer_id.clone()
                }
-            }
+            });
+            importer_info.insert(
+                importer_id.clone(),
+                ImporterInfo { name, version: manifest.version.unwrap_or_default() },
+            );
        }
-    }
-
-    for (parent_key, edges) in &forward_edges {
-        for (alias, target) in edges {
-            if let Some(target_key) = target {
-                reverse_map
-                    .entry(ReverseKey::Package(target_key.clone()))
-                    .or_default()
-                    .push((ParentNode::Package(parent_key.clone()), alias.clone()));
-            }
-        }
-    }
-
-    for edges in reverse_map.values_mut() {
-        edges.sort_by_cached_key(|entry| entry.0.to_string());
-    }
-
-    let ctx = WalkCtx { reverse_map: &reverse_map, importer_info, packages };
-
-    let mut matched_roots: Vec<(String, String, ReverseKey)> = Vec::new();
-
-    for key in &node_keys {
-        let name = key.name.to_string();
-        let version = display_version(key, packages);
-
-        let matched = matcher.matches(&name)
-            || reverse_map
-                .get(&ReverseKey::Package(key.clone()))
-                .is_some_and(|edges| edges.iter().any(|(_parent, alias)| matcher.matches(alias)));
-
-        if matched {
-            matched_roots.push((name, version, ReverseKey::Package(key.clone())));
-        }
-    }
-
-    for importer_id in importer_info.keys() {
-        let info = importer_info.get(importer_id.as_str());
-        let name = info.map_or_else(|| importer_id.clone(), |i| i.name.clone());
-
-        let matched = matcher.matches(&name)
-            || reverse_map
-                .get(&ReverseKey::Importer(importer_id.clone()))
-                .is_some_and(|edges| edges.iter().any(|(_parent, alias)| matcher.matches(alias)));
-
-        if matched {
-            let version = info.map_or_else(String::new, |i| i.version.clone());
-            matched_roots.push((name, version, ReverseKey::Importer(importer_id.clone())));
-        }
-    }
-
-    let mut memo: HashMap<(ReverseKey, usize), Vec<DependentNode>> = HashMap::new();
-    let mut results: Vec<WhyResult> = Vec::new();
-
-    for (name, version, root_key) in &matched_roots {
-        let mut visited = HashSet::new();
-        match root_key {
-            ReverseKey::Package(key) => {
-                visited.insert(ParentNode::Package(key.clone()));
-            }
-            ReverseKey::Importer(id) => {
-                visited.insert(ParentNode::Importer(id.clone()));
-            }
-        }
-        let mut expanded = HashSet::new();
-        let dependents =
-            walk_reverse(root_key, &ctx, &mut visited, &mut expanded, &mut memo, 0, max_depth);
-
-        results.push(WhyResult { name: name.clone(), version: version.clone(), dependents });
-    }
-
-    results
-        .sort_by(|left, right| left.name.cmp(&right.name).then(left.version.cmp(&right.version)));
-
-    results
-}
-
-fn walk_reverse(
-    node_key: &ReverseKey,
-    ctx: &WalkCtx<'_>,
-    visited: &mut HashSet<ParentNode>,
-    expanded: &mut HashSet<ParentNode>,
-    memo: &mut HashMap<(ReverseKey, usize), Vec<DependentNode>>,
-    depth: usize,
-    max_depth: Option<usize>,
-) -> Vec<DependentNode> {
-    if depth >= MAX_REVERSE_WALK_DEPTH || max_depth.is_some_and(|max| depth >= max) {
-        return vec![];
-    }
-
-    let Some(edges) = ctx.reverse_map.get(node_key) else {
-        return vec![];
-    };
-
-    let memo_key = (node_key.clone(), depth);
-    if let Some(cached) = memo.get(&memo_key) {
-        return cached.clone();
-    }
-
-    let mut dependents = Vec::new();
-
-    for (parent_node, _alias) in edges {
-        match parent_node {
-            ParentNode::Importer(importer_id) => {
-                let info = ctx.importer_info.get(importer_id.as_str());
-                dependents.push(DependentNode {
-                    name: info.map_or_else(|| importer_id.clone(), |i| i.name.clone()),
-                    version: info.map_or_else(String::new, |i| i.version.clone()),
-                    dep_field: None,
-                    dependents: vec![],
-                });
-            }
-            ParentNode::Package(parent_key) => {
-                if visited.contains(parent_node) {
-                    dependents.push(DependentNode {
-                        name: parent_key.name.to_string(),
-                        version: display_version(parent_key, ctx.packages),
-                        dep_field: None,
-                        dependents: vec![],
-                    });
-                    continue;
-                }
Evidence
why.rs iterates all lockfile.importers.keys() and calls read_project_manifest, which does a
full std::fs::read + JSON parse. The graph build starts from root_ids, so importers outside that
reachable set can’t be encountered by the reverse walk that consults importer_info.

pnpm/crates/cli/src/cli_args/why.rs[118-169]
pnpm/crates/cli/src/cli_args/deps_tree/build.rs[472-487]
pnpm/crates/cli/src/cli_args/deps_tree/graph.rs[49-106]
pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs[309-320]

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

### Issue description
`pnpm why` eagerly reads `package.json` for all lockfile importers to populate `importer_info`, even though only importer nodes reachable in the built dependency graph can appear in the dependents output.

### Issue Context
- The graph is constructed from `root_ids` (selected projects) via BFS.
- `importer_info` is only consulted when rendering/sorting importer nodes encountered in the reverse walk.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/why.rs[127-176]
- pnpm/crates/cli/src/cli_args/deps_tree/build.rs[475-487]
- pnpm/crates/cli/src/cli_args/deps_tree/graph.rs[49-106]

### Proposed fix
Build the dependency graph first, then build `importer_info` only for importer ids present in `graph.nodes.keys()` (filter `TreeNodeId::Importer`). This preserves current output for reachable importers while avoiding manifest reads for importers outside the selected graph.

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


24. Finder lookup allocates 🐞 Bug ➹ Performance ⭐ New
Description
When --find-by is enabled and positional queries don’t match, Searcher::matches() allocates a
fresh (String, Option<TreeNodeId>) key (alias.to_string(), node.cloned()) for every
finder-result lookup. Because matches() is called in the per-edge tree-walk loop, this adds
avoidable allocation/cloning overhead proportional to edges visited.
Code

pnpm/crates/cli/src/cli_args/deps_tree/search.rs[R95-100]

+        if self.has_finders {
+            let key = (alias.to_string(), node.cloned());
+            if let Some(verdict) = self.finder_results.get(&key) {
+                return verdict.clone();
+            }
+        }
Evidence
Searcher stores finder results keyed by owned (String, Option<TreeNodeId>), and get_tree calls
search.matches(...) inside the per-edge loop, so the temporary key allocation happens repeatedly
during traversal.

pnpm/crates/cli/src/cli_args/deps_tree/search.rs[43-47]
pnpm/crates/cli/src/cli_args/deps_tree/search.rs[73-101]
pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs[146-166]

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

### Issue description
`Searcher::matches()` constructs an owned tuple key on each lookup into `finder_results`, causing repeated allocations/clones in a hot per-edge traversal path.

### Issue Context
`finder_results` is keyed by `(String, Option<TreeNodeId>)`, but callers naturally have `&str` and `Option<&TreeNodeId>`.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/deps_tree/search.rs[43-47]
- pnpm/crates/cli/src/cli_args/deps_tree/search.rs[73-101]

### Proposed fix
Refactor `finder_results` into a structure that supports borrowed lookup without allocating, e.g.:
- `finder_results_unresolved: HashMap<String, SearchMatch>` for `node == None`
- `finder_results_by_node: HashMap<TreeNodeId, HashMap<String, SearchMatch>>` for `Some(node)`
Then `matches()` can do `by_node.get(node).and_then(|m| m.get(alias))` / `unresolved.get(alias)` with no `String` allocation and no `TreeNodeId` cloning.

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


25. Changeset text too long 📘 Rule violation ⚙ Maintainability
Description
The changeset entry is unusually long and reads more like an implementation changelog than a
concise, release-note-ready summary. This increases maintenance overhead and may not meet the repo’s
requirement for concise, user-focused changeset prose.
Code

.changeset/list-why-parity.md[R1-5]

+---
+"pacquet": minor
+---
+
+`pnpm list` and `pnpm why` are now feature complete and behaviorally identical to the TypeScript CLI. `pnpm list` gained `--only-projects`, `--find-by` (finders declared in `.pnpmfile.cjs`), search by version range (`pnpm ls "foo@^2"`), subtree deduplication with `[deduped]` markers, peer/skipped annotations, the package-count summary, `--long` manifest details, resolved tarball URLs and absolute paths in `--json`/`--parseable` output, and `--depth` support for globally installed packages. `pnpm why` gained `--json`, `--parseable`, `--long`, `--prod`/`--dev`/`--no-optional`, `--find-by`, workspace project names in the reverse tree, dependency-field annotations, `[circular]`/`[deduped]` markers, peer-variant hashes, and the `Found N versions` summary.
Evidence
The compliance checklist requires changeset prose to be concise and user-focused. The added
changeset contains an extensive enumeration of flags and behaviors that is likely too verbose for
release notes.

AGENTS.md: Require changesets for published-package changes and follow pnpm/Rust product targeting rules
.changeset/list-why-parity.md[1-5]

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

## Issue description
The `.changeset/` note is overly detailed; it should be concise and user-facing.

## Issue Context
Changesets are intended to be release-note ready summaries, not exhaustive feature inventories.

## Fix Focus Areas
- .changeset/list-why-parity.md[1-5]

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


View more (1)
26. get_finder_names comment restates code ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The added doc comments for get_finder_names/call_finder primarily restate what the function
names and signatures already convey, adding little non-obvious value. This increases maintenance
noise without documenting additional contract/rationale.
Code

pnpm/crates/hooks/src/worker.rs[R251-264]

+    /// The names of the finders exported by the pnpmfile's `finders`
+    /// object.
+    pub async fn get_finder_names(&self) -> Result<Vec<String>, HookError> {
+        let value = self
+            .request("finders", serde_json::json!({ "target": "finders" }), Arc::new(|_| {}))
+            .await?;
+        serde_json::from_value(value).map_err(|err| self.exec_err(err.to_string()))
+    }
+
+    /// Call the finder named `name` with a context of `alias`, `name`,
+    /// `version`, and `manifest` (exposed to the finder as a
+    /// `readManifest()` callback). Returns the finder's verdict:
+    /// `false`/`true` or a message string.
+    pub async fn call_finder(&self, name: &str, ctx: Value) -> Result<Value, HookError> {
Evidence
PR Compliance ID 4 requires comments to add non-obvious value and not restate code. The newly added
doc comments directly paraphrase the method names (get_finder_names, call_finder) and their
arguments/returns without documenting additional constraints or rationale beyond what the code
already shows.

CLAUDE.md: Comments Must Add Non-Obvious Value and Must Not Restate Code or Record Refactor History
pnpm/crates/hooks/src/worker.rs[251-264]

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

## Issue description
New doc comments restate the function names/signatures without adding non-obvious rationale, invariants, or edge cases.

## Issue Context
Compliance expects comments to capture non-obvious value (contracts, invariants, rationale) rather than repeating what code already expresses.

## Fix Focus Areas
- pnpm/crates/hooks/src/worker.rs[251-264]

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


Grey Divider

Qodo Logo

@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 (1)
pnpm/crates/cli/src/cli_args/why.rs (1)

67-162: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Wire --exclude-peers into why
WhyArgs::run never reads exclude_peers, so pnpm why --exclude-peers is accepted but ignored. list already threads this flag into graph construction; why should do the same or drop the option.

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

In `@pnpm/crates/cli/src/cli_args/why.rs` around lines 67 - 162, Update
WhyArgs::run and its BuildGraphOptions construction to propagate
self.exclude_peers into dependency graph building, matching the existing list
command behavior. Ensure --exclude-peers changes graph traversal/output while
preserving the current behavior when the flag is false.

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 `@pnpm/crates/cli/src/cli_args/why.rs`:
- Around line 67-162: Update WhyArgs::run and its BuildGraphOptions construction
to propagate self.exclude_peers into dependency graph building, matching the
existing list command behavior. Ensure --exclude-peers changes graph
traversal/output while preserving the current behavior when the flag is false.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b1f7b3ad-1162-4a5c-8131-745d7f962164

📥 Commits

Reviewing files that changed from the base of the PR and between b4ec43c and acdf11c.

📒 Files selected for processing (30)
  • .changeset/list-why-parity.md
  • pnpm/crates/cli/src/cli_args.rs
  • pnpm/crates/cli/src/cli_args/deps_tree.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/build.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/dep_types.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/dependents.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/finders.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/get_tree.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/get_tree/tests.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/graph.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/pkg_info.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/pkg_info/tests.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/render.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/search.rs
  • pnpm/crates/cli/src/cli_args/deps_tree/search/tests.rs
  • pnpm/crates/cli/src/cli_args/dispatch_query.rs
  • pnpm/crates/cli/src/cli_args/list.rs
  • pnpm/crates/cli/src/cli_args/list/render.rs
  • pnpm/crates/cli/src/cli_args/list/tests.rs
  • pnpm/crates/cli/src/cli_args/why.rs
  • pnpm/crates/cli/src/cli_args/why/render.rs
  • pnpm/crates/cli/src/cli_args/why/tests.rs
  • pnpm/crates/cli/tests/list.rs
  • pnpm/crates/cli/tests/why.rs
  • pnpm/crates/global/src/lib.rs
  • pnpm/crates/global/src/list.rs
  • pnpm/crates/hooks/src/lib.rs
  • pnpm/crates/hooks/src/node_runtime.rs
  • pnpm/crates/hooks/src/worker.rs
  • pnpm/plans/TEST_PORTING.md

@greptile-apps

greptile-apps Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge. The TypeScript CLI is untouched; the Rust-side changes are an additive port with extensive test coverage and no regressions to existing functionality.

The tree-building pipeline faithfully mirrors the TypeScript tree-builder, the deduplication cache bounds output to O(N), the path-traversal guard in normalize_importer_path correctly stops .. from escaping the workspace, and the worker finder protocol is consistent with the existing hook protocol. No incorrect filtering, wrong data, or dropped state was found in the changed paths.

No files require special attention. deps_tree/build.rs and deps_tree/get_tree.rs are the most complex new additions; both have matching unit tests in their tests submodules.

Reviews (6): Last reviewed commit: "fix(pacquet-cli): validate lockfile impo..." | Re-trigger Greptile

Comment thread pnpm/crates/global/src/list.rs Resolved
@codecov-commenter

codecov-commenter commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.37740% with 296 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.68%. Comparing base (b4ec43c) to head (c080c34).

Files with missing lines Patch % Lines
pnpm/crates/cli/src/cli_args/list.rs 71.14% 58 Missing ⚠️
...pm/crates/cli/src/cli_args/deps_tree/dependents.rs 79.51% 51 Missing ⚠️
pnpm/crates/cli/src/cli_args/deps_tree/finders.rs 75.00% 41 Missing ⚠️
pnpm/crates/cli/src/cli_args/list/render.rs 90.67% 32 Missing ⚠️
pnpm/crates/cli/src/cli_args/why/render.rs 86.66% 30 Missing ⚠️
pnpm/crates/cli/src/cli_args/deps_tree/build.rs 91.88% 25 Missing ⚠️
pnpm/crates/cli/src/cli_args/deps_tree/render.rs 90.37% 13 Missing ⚠️
pnpm/crates/global/src/list.rs 0.00% 13 Missing ⚠️
pnpm/crates/cli/src/cli_args/deps_tree.rs 50.00% 9 Missing ⚠️
pnpm/crates/cli/src/cli_args/why.rs 92.75% 5 Missing ⚠️
... and 6 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13178      +/-   ##
==========================================
+ Coverage   86.56%   86.68%   +0.12%     
==========================================
  Files         510      522      +12     
  Lines       86274    87556    +1282     
==========================================
+ Hits        74683    75900    +1217     
- Misses      11591    11656      +65     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: c080c34e93a8

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

The tables below show mean ± σ; Bencher thresholds on the minimum latency, which is far less perturbed by shared-runner contention (noise only adds time).

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.553 ± 0.146 2.401 2.788 1.49 ± 0.18
pacquet@main 2.611 ± 0.188 2.413 2.891 1.53 ± 0.20
pnpr@HEAD 1.720 ± 0.185 1.502 1.939 1.01 ± 0.15
pnpr@main 1.710 ± 0.183 1.486 1.968 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.55281208376,
      "stddev": 0.14603468254547008,
      "median": 2.53878113516,
      "user": 2.1235576199999997,
      "system": 1.6590299600000002,
      "min": 2.40066588866,
      "max": 2.7878912746599998,
      "times": [
        2.66604369466,
        2.42080191066,
        2.56347906266,
        2.57778851766,
        2.7878912746599998,
        2.40066588866,
        2.5140832076599997,
        2.76304215966,
        2.42166693566,
        2.41265818566
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.6106125086599996,
      "stddev": 0.1879269863914833,
      "median": 2.54856050316,
      "user": 2.18775592,
      "system": 1.7181984599999995,
      "min": 2.41267553366,
      "max": 2.89050769766,
      "times": [
        2.89050769766,
        2.4624638706599997,
        2.42826727266,
        2.41267553366,
        2.4988466156599998,
        2.81937036666,
        2.77846804666,
        2.78287222266,
        2.43437906966,
        2.59827439066
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.7199196651600002,
      "stddev": 0.18507301016657152,
      "median": 1.77143237366,
      "user": 2.00679042,
      "system": 1.85317746,
      "min": 1.50232023166,
      "max": 1.93919684266,
      "times": [
        1.93919684266,
        1.7361638096599998,
        1.92040750166,
        1.50870385666,
        1.8396608096599998,
        1.5237759446599999,
        1.50232023166,
        1.80670093766,
        1.8945306416599998,
        1.52773607566
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.70953708166,
      "stddev": 0.18304076453920765,
      "median": 1.65011773066,
      "user": 2.00917502,
      "system": 1.8779766600000003,
      "min": 1.4864277506599999,
      "max": 1.96827893966,
      "times": [
        1.61539823766,
        1.7244923216599999,
        1.6313107696599998,
        1.5959211336599999,
        1.50826070266,
        1.96600786666,
        1.93034840266,
        1.96827893966,
        1.4864277506599999,
        1.66892469166
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 407.1 ± 19.7 380.5 436.2 1.03 ± 0.08
pacquet@main 394.2 ± 21.7 374.6 449.4 1.00
pnpr@HEAD 432.9 ± 33.5 377.8 479.9 1.10 ± 0.10
pnpr@main 421.8 ± 20.7 386.8 445.0 1.07 ± 0.08
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.40706058334,
      "stddev": 0.019733141152163635,
      "median": 0.40932158434000004,
      "user": 0.33595655999999996,
      "system": 0.74481932,
      "min": 0.38054218484,
      "max": 0.43618589584000006,
      "times": [
        0.39383394184000003,
        0.38217882284000004,
        0.42343720084,
        0.38054218484,
        0.40238285484,
        0.39012588084000005,
        0.41626031384000006,
        0.43618589584000006,
        0.42250281684,
        0.42315592084000003
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.39420174874,
      "stddev": 0.021691186438656092,
      "median": 0.38587549434,
      "user": 0.34204315999999996,
      "system": 0.7232829199999999,
      "min": 0.37461589584000005,
      "max": 0.44941996384000005,
      "times": [
        0.38271790284,
        0.38674579284000005,
        0.44941996384000005,
        0.38397220984,
        0.40951526384000003,
        0.37461589584000005,
        0.39751754284,
        0.38108737884000005,
        0.39142034084000005,
        0.38500519584000004
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.43285601524000006,
      "stddev": 0.03345988691226418,
      "median": 0.43043557634000007,
      "user": 0.36916416,
      "system": 0.7693085199999998,
      "min": 0.37778608284000004,
      "max": 0.47989522284,
      "times": [
        0.43353788284000006,
        0.42733326984000003,
        0.47028275584000007,
        0.47989522284,
        0.45253494384000004,
        0.42191674984000005,
        0.46016461684000004,
        0.37778608284000004,
        0.39010659284000004,
        0.41500203484000003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.42182369263999997,
      "stddev": 0.020732692940301948,
      "median": 0.42679857384000003,
      "user": 0.37619066000000007,
      "system": 0.72820402,
      "min": 0.38681549284000005,
      "max": 0.44504038284,
      "times": [
        0.44244488284000005,
        0.44504038284,
        0.39493241184000005,
        0.42942582484,
        0.42046799684,
        0.43030382084,
        0.42417132284000003,
        0.44254233084000005,
        0.40209245984,
        0.38681549284000005
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.212 ± 0.058 3.124 3.293 1.70 ± 0.14
pacquet@main 3.338 ± 0.137 3.172 3.580 1.77 ± 0.16
pnpr@HEAD 1.886 ± 0.153 1.714 2.114 1.00
pnpr@main 1.950 ± 0.145 1.770 2.191 1.03 ± 0.11
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.2118830919400003,
      "stddev": 0.057946482298114846,
      "median": 3.21543589494,
      "user": 3.2307587599999996,
      "system": 2.27260198,
      "min": 3.12363440344,
      "max": 3.29260960044,
      "times": [
        3.29260960044,
        3.21796684944,
        3.20149403044,
        3.12363440344,
        3.21290494044,
        3.27454017844,
        3.2194531304400003,
        3.1458130894400003,
        3.27603087044,
        3.15438382644
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 3.33786634944,
      "stddev": 0.13725129394971033,
      "median": 3.3272809064400004,
      "user": 3.43332536,
      "system": 2.3187784799999998,
      "min": 3.17175218044,
      "max": 3.57991168244,
      "times": [
        3.2399539014400003,
        3.43630521044,
        3.17175218044,
        3.1896068744400004,
        3.40343844544,
        3.28514286444,
        3.2218496184400003,
        3.48128376844,
        3.3694189484400003,
        3.57991168244
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.88551626904,
      "stddev": 0.1530804675268083,
      "median": 1.82793165744,
      "user": 2.10726036,
      "system": 2.06718388,
      "min": 1.71416200844,
      "max": 2.11356824344,
      "times": [
        1.81531982544,
        1.72825892744,
        1.8192845954399999,
        2.1011222004400003,
        1.95075593844,
        2.11356824344,
        2.03355305044,
        1.83657871944,
        1.71416200844,
        1.74255918144
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.9501934003399999,
      "stddev": 0.144928222514866,
      "median": 1.89954459594,
      "user": 2.12284896,
      "system": 2.0955052800000002,
      "min": 1.7696718784399998,
      "max": 2.19072693844,
      "times": [
        1.89230878444,
        1.80948065544,
        2.19072693844,
        2.15870088544,
        1.89643513744,
        1.7696718784399998,
        2.0129705174400003,
        1.8287020064400001,
        2.04028314544,
        1.90265405444
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.172 ± 0.128 0.977 1.346 2.67 ± 0.31
pacquet@main 1.192 ± 0.178 0.906 1.478 2.71 ± 0.42
pnpr@HEAD 0.470 ± 0.020 0.436 0.512 1.07 ± 0.06
pnpr@main 0.439 ± 0.017 0.412 0.470 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.17196433868,
      "stddev": 0.12845330499933308,
      "median": 1.14989769228,
      "user": 1.48925404,
      "system": 1.1245771999999998,
      "min": 0.97693576628,
      "max": 1.34644151428,
      "times": [
        1.31424309028,
        1.15706895728,
        0.97693576628,
        1.33855340028,
        1.09915463128,
        1.14272642728,
        1.21042913628,
        1.34644151428,
        1.09987141528,
        1.03421904828
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.19225146758,
      "stddev": 0.17821250040102074,
      "median": 1.16506969778,
      "user": 1.48374294,
      "system": 1.0964203999999997,
      "min": 0.90551061428,
      "max": 1.4782670172799999,
      "times": [
        1.28374616728,
        1.32957572328,
        1.14829245428,
        1.05184393728,
        1.4782670172799999,
        1.38617957628,
        1.17635016428,
        1.15378923128,
        0.90551061428,
        1.00895979028
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.4700360979800001,
      "stddev": 0.019553489414743205,
      "median": 0.46813303228,
      "user": 0.32842953999999996,
      "system": 0.8070216,
      "min": 0.43571202728,
      "max": 0.5122425752800001,
      "times": [
        0.46964531028,
        0.45471446328000004,
        0.46662075428,
        0.43571202728,
        0.5122425752800001,
        0.46991301628,
        0.47576818128000004,
        0.48321245428000004,
        0.46640415728,
        0.46612804028
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.43914644608,
      "stddev": 0.017020878913809094,
      "median": 0.43511566228,
      "user": 0.31169364,
      "system": 0.7533637,
      "min": 0.41201831628,
      "max": 0.46959057228,
      "times": [
        0.46959057228,
        0.42778758128,
        0.45279702828,
        0.45624701128,
        0.43061061728,
        0.43687964428000003,
        0.44625396628,
        0.42592804328,
        0.43335168028,
        0.41201831628
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.313 ± 0.033 2.264 2.369 5.41 ± 0.35
pacquet@main 2.458 ± 0.129 2.308 2.695 5.75 ± 0.47
pnpr@HEAD 0.477 ± 0.016 0.450 0.496 1.12 ± 0.08
pnpr@main 0.427 ± 0.027 0.381 0.466 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.3129676329200004,
      "stddev": 0.032646899551051774,
      "median": 2.3168876675199996,
      "user": 1.68462954,
      "system": 1.2379586999999996,
      "min": 2.26422314302,
      "max": 2.36916584202,
      "times": [
        2.36916584202,
        2.31842899802,
        2.32974279002,
        2.33661069602,
        2.26422314302,
        2.29110805102,
        2.31534633702,
        2.28759327702,
        2.27691198802,
        2.34054520702
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.45767943752,
      "stddev": 0.12878207247223103,
      "median": 2.45428263802,
      "user": 1.8617206400000001,
      "system": 1.2793626999999996,
      "min": 2.30758000702,
      "max": 2.69460159102,
      "times": [
        2.43677012802,
        2.30758000702,
        2.39277308302,
        2.34811682502,
        2.30898780802,
        2.62745628602,
        2.50224252902,
        2.48647097002,
        2.47179514802,
        2.69460159102
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.47691482462,
      "stddev": 0.015682815668242974,
      "median": 0.47970496852000005,
      "user": 0.36469873999999997,
      "system": 0.7642233999999999,
      "min": 0.44953401702000007,
      "max": 0.49567803002000005,
      "times": [
        0.4808668970200001,
        0.47854304002000003,
        0.44953401702000007,
        0.4538077750200001,
        0.47033434702000004,
        0.49500139002000004,
        0.48660430002000005,
        0.47294615202000007,
        0.48583229802000005,
        0.49567803002000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.4273352254200001,
      "stddev": 0.026968182102965206,
      "median": 0.43683375102000005,
      "user": 0.32325644000000003,
      "system": 0.7309913,
      "min": 0.38133459502000006,
      "max": 0.46565033102000003,
      "times": [
        0.43625999702000007,
        0.43850847502000007,
        0.41166275302000005,
        0.46565033102000003,
        0.39635241302000007,
        0.38133459502000006,
        0.44223474902000004,
        0.43740750502000003,
        0.40762976502000003,
        0.45631167102000003
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 581.1 ± 55.9 509.7 710.3 5.11 ± 0.61
pacquet@main 552.8 ± 27.7 515.6 611.1 4.86 ± 0.42
pnpr@HEAD 114.4 ± 7.9 103.5 136.1 1.01 ± 0.10
pnpr@main 113.8 ± 8.1 100.2 129.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.58105037632,
      "stddev": 0.055942420322965286,
      "median": 0.5747410992199999,
      "user": 0.56751374,
      "system": 0.13609649999999998,
      "min": 0.50971949472,
      "max": 0.71033482272,
      "times": [
        0.52837604972,
        0.57427837272,
        0.5979864447200001,
        0.57449074772,
        0.60256314272,
        0.71033482272,
        0.60364838372,
        0.57499145072,
        0.53411485372,
        0.50971949472
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.5527888682200001,
      "stddev": 0.027690472000156147,
      "median": 0.54701005622,
      "user": 0.53816504,
      "system": 0.1305097,
      "min": 0.51564391972,
      "max": 0.61114629572,
      "times": [
        0.54725258172,
        0.51564391972,
        0.54239825072,
        0.54245253872,
        0.52212675172,
        0.5751995547200001,
        0.57256765672,
        0.61114629572,
        0.5467675307200001,
        0.55233360172
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.11444712826166668,
      "stddev": 0.007851993050948034,
      "median": 0.11289205222000001,
      "user": 0.032941464999999996,
      "system": 0.02128208333333333,
      "min": 0.10349174272,
      "max": 0.13606716972000002,
      "times": [
        0.11499845672,
        0.12075162372,
        0.13003570772,
        0.11615198172,
        0.11524264372000001,
        0.11489313972000001,
        0.13606716972000002,
        0.10707374872000001,
        0.11391726272000001,
        0.11193342472000001,
        0.11186588872000001,
        0.11073346572000001,
        0.11385067972000001,
        0.11128741372,
        0.12244861972000001,
        0.10809656972000001,
        0.12242719772,
        0.10687960772,
        0.10377616372000001,
        0.10898499372,
        0.11033706572,
        0.11014062972000001,
        0.10349174272,
        0.12134588072000001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.11375116975846154,
      "stddev": 0.00813849548905733,
      "median": 0.11240437072000001,
      "user": 0.032564224615384614,
      "system": 0.020391615384615383,
      "min": 0.10022321872,
      "max": 0.12991116572,
      "times": [
        0.10487298972,
        0.12991116572,
        0.12327250472000001,
        0.11143601472,
        0.11349304672,
        0.10516685872,
        0.11568290272000001,
        0.10922091772,
        0.10474973072,
        0.10653368972,
        0.11550641072000001,
        0.10692751372,
        0.11027654772,
        0.11451999472,
        0.12779747672,
        0.10500759372,
        0.11265729972,
        0.10946410472000001,
        0.12308488572000001,
        0.12691873272,
        0.11363476072,
        0.10931585672000001,
        0.10022321872,
        0.11215144172000001,
        0.12377867072000001,
        0.12192608372000001
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.847 ± 0.146 4.630 5.080 1.35 ± 0.05
pacquet@main 4.737 ± 0.149 4.608 5.141 1.32 ± 0.05
pnpr@HEAD 3.645 ± 0.118 3.534 3.907 1.02 ± 0.04
pnpr@main 3.580 ± 0.069 3.513 3.690 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.8469743454800005,
      "stddev": 0.1458873811609164,
      "median": 4.826075148879999,
      "user": 3.11606976,
      "system": 2.2631972599999997,
      "min": 4.62971798338,
      "max": 5.08015778338,
      "times": [
        4.81297531038,
        4.965100737379999,
        4.83917498738,
        4.97954142738,
        4.724053436379999,
        4.80034177338,
        4.680744897379999,
        4.95793511838,
        5.08015778338,
        4.62971798338
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.737017295980001,
      "stddev": 0.14891400402821475,
      "median": 4.70326749038,
      "user": 2.89279796,
      "system": 2.13855636,
      "min": 4.60805465938,
      "max": 5.14111236638,
      "times": [
        4.71687236138,
        5.14111236638,
        4.64844444138,
        4.75132603338,
        4.68694687238,
        4.660322648379999,
        4.75022522138,
        4.68966261938,
        4.60805465938,
        4.7172057363799995
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.64537687348,
      "stddev": 0.11830836798511633,
      "median": 3.60740493588,
      "user": 1.8578584599999999,
      "system": 1.7001555600000002,
      "min": 3.53401531438,
      "max": 3.90656308438,
      "times": [
        3.53401531438,
        3.5918105603800004,
        3.58731915738,
        3.6788302493800003,
        3.64062715338,
        3.90656308438,
        3.5515921823800003,
        3.55282872638,
        3.62299931138,
        3.7871829953800002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.5799336659799996,
      "stddev": 0.06916238147053823,
      "median": 3.5516830713800003,
      "user": 1.6794376599999996,
      "system": 1.5990288599999998,
      "min": 3.5134605433800004,
      "max": 3.6899771933800003,
      "times": [
        3.5134605433800004,
        3.55598052738,
        3.5306464443800003,
        3.57703941938,
        3.6899771933800003,
        3.51528782038,
        3.68150530738,
        3.6555037353800004,
        3.54738561538,
        3.53255005338
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/13178
Testbedpacquet

🚨 4 Alerts

BenchmarkMeasure
Units
ViewBenchmark Result
(Result Δ%)
Upper Boundary
(Limit %)
isolated-linker.fresh-install.cold-cache.hot-storeLatency
seconds (s)
📈 plot
🚷 threshold
🚨 alert (🔔)
2.26 s
(+22.85%)Baseline: 1.84 s
2.21 s
(102.38%)

isolated-linker.fresh-install.hot-cache.hot-storeLatency
milliseconds (ms)
📈 plot
🚷 threshold
🚨 alert (🔔)
976.94 ms
(+81.41%)Baseline: 538.53 ms
646.23 ms
(151.17%)

isolated-linker.fresh-resolve.hot-cache.offlineLatency
milliseconds (ms)
📈 plot
🚷 threshold
🚨 alert (🔔)
509.72 ms
(+56.64%)Baseline: 325.40 ms
390.48 ms
(130.54%)

isolated-linker.fresh-restore.hot-cache.hot-storeLatency
milliseconds (ms)
📈 plot
🚷 threshold
🚨 alert (🔔)
380.54 ms
(+56.56%)Baseline: 243.07 ms
291.68 ms
(130.47%)

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
3,123.63 ms
(+16.58%)Baseline: 2,679.30 ms
3,215.16 ms
(97.15%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
🚨 view alert (🔔)
2,264.22 ms
(+22.85%)Baseline: 1,843.02 ms
2,211.62 ms
(102.38%)

isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
🚨 view alert (🔔)
976.94 ms
(+81.41%)Baseline: 538.53 ms
646.23 ms
(151.17%)

isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
🚨 view alert (🔔)
509.72 ms
(+56.64%)Baseline: 325.40 ms
390.48 ms
(130.54%)

isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,400.67 ms
(+1.84%)Baseline: 2,357.30 ms
2,828.77 ms
(84.87%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,629.72 ms
(+4.62%)Baseline: 4,425.48 ms
5,310.58 ms
(87.18%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
🚨 view alert (🔔)
380.54 ms
(+56.56%)Baseline: 243.07 ms
291.68 ms
(130.47%)

🐰 View full continuous benchmarking report in Bencher

Base unresolvable link: finder candidates on the parent importer's
directory (the same base the tree materialization uses), so --find-by
reads the manifest the edge actually refers to for nested importers.
Build the dependency graph once per list invocation and share it
between finder evaluation and tree building. Identify the --long path
line by its virtual-store dirname in the long-format test so the
assertion holds on Windows path separators. Trim restating doc
comments in the finder worker protocol and correct the
find_global_install_dirs contract note.
Copilot AI review requested due to automatic review settings July 20, 2026 16: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.

@zkochan

zkochan commented Jul 20, 2026

Copy link
Copy Markdown
Member Author

Addressed the review findings in 40e551a:

  1. Finder link path misbased — fixed: unresolvable link: candidates now resolve against the parent importer's directory, the same base the tree materialization uses.
  2. read_manifest() uses blocking fs — keeping the synchronous reads: they only run under --find-by (a cold, interactive query path), they read small package.json files, and the CAFS branch goes through the SQLite-backed store index, which is inherently blocking. This matches how the other read-only query commands in the Rust CLI (licenses, list itself) do manifest I/O; the async-fs guidance in the repo instructions is scoped to the TypeScript CLI.
  3. List builds graph twice — fixed: list now builds the dependency graph once and shares it between finder evaluation and tree building (build_dependencies_tree takes the prebuilt graph).
  4. Doc comments restate code — trimmed: get_finder_names lost its restating doc, and call_finder now documents only the non-obvious part (the manifest is pre-read because a JS callback cannot call back over the pipe).

Also fixed the Windows CI failure (the long-format test asserted a forward-slash path) and the earlier Doc job failure (a bad intra-doc link).


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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 40e551a

…ackage_path

Never join or dereference a lockfile-derived virtual-store dirname,
package name, or alias that carries traversal segments or an absolute
path — the same guard pnpm licenses applies before reading store paths
built from lockfile keys.
Copilot AI review requested due to automatic review settings July 20, 2026 16:55

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-code-review qodo-code-review Bot mentioned this pull request Jul 25, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants