Skip to content

feat(pacquet): support recursive outdated queries - #13202

Merged
zkochan merged 6 commits into
mainfrom
outdated-recursive
Jul 21, 2026
Merged

zkochan merged 6 commits into
mainfrom
outdated-recursive

Conversation

@zkochan

@zkochan zkochan commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add recursive workspace support to pacquet's pnpm outdated, including filters and both shared and dedicated lockfiles.
  • Aggregate matching outdated dependencies across projects and report their dependents in table, list, and JSON output, matching the TypeScript CLI.
  • Make pacquet's pnpm list/ls and pnpm ll/la recursive by default inside workspaces, as they are in the TypeScript CLI.

The TypeScript CLI already supports these behaviors, so this PR only changes the Rust implementation. This is a partial fix for the recursive-command parity audit; the remaining commands stay tracked in #13201.

Related to #13201.

Squash Commit Body

Pacquet rejected recursive outdated queries and kept list/ll scoped to the active project even though the TypeScript CLI traverses selected workspace projects.

Reuse the existing workspace discovery and filtering path to select projects for outdated. Load a shared lockfile once or each selected project's dedicated lockfile as appropriate, preserve importer identity, and group equivalent findings across projects so every output format can expose the affected dependents. Keep the existing nonzero exit status when outdated dependencies are found.

Promote list and ll to recursive mode by default when invoked inside a workspace. Limit the shared promotion mechanism to commands whose recursive paths already support both lockfile layouts; the other audited commands remain tracked separately.

Related to pnpm/pnpm#13201.

Checklist

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

Written by an agent (Codex, GPT-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 ll now run recursively by default within workspaces (standalone projects remain non-recursive).
    • pnpm outdated --recursive is now supported, aggregating workspace results and reporting dependents in table/list/JSON.
  • Bug Fixes
    • Improved recursive outdated behavior and output ordering.
    • Enhanced dependents rendering to sanitize terminal output; centralized and clarified shared lockfile error handling.
    • Reduced repeated registry lookups via cache-aware fetching.
  • Tests
    • Added/updated coverage for recursive-by-default promotion, recursive outdated dependents/filtering, and cache deduplication/retry behavior.

Copilot AI review requested due to automatic review settings July 21, 2026 20:54

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 21, 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

Changes

Recursive workspace queries

Layer / File(s) Summary
Recursive defaults and CLI wiring
pnpm/crates/cli/src/cli_args/cli_command.rs, pnpm/crates/cli/src/lib.rs, pnpm/crates/cli/src/cli_args/tests.rs, pnpm/crates/cli/tests/list.rs, .changeset/recursive-outdated-queries.md
list and ll become recursive by default inside workspaces, while standalone projects and outdated remain non-recursive by default.
Cached recursive outdated collection
pnpm/crates/cli/src/cli_args/outdated.rs
Recursive outdated queries inspect selected workspace projects, read shared or project lockfiles, cache package metadata, and aggregate outdated dependencies with their dependents.
Recursive outdated sorting and output
pnpm/crates/cli/src/cli_args/outdated.rs, pnpm/crates/cli/src/cli_args/sanitize.rs, pnpm/crates/cli/src/cli_args/outdated/tests.rs, pnpm/crates/cli/tests/outdated.rs
Recursive results are sorted and rendered in table, list, and JSON formats, with sanitized dependent project details and validation for lockfiles, filtering, dedicated project lockfiles, and cached fetches.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Workspace
  participant Lockfiles
  participant PackumentCache
  participant Output

  CLI->>Workspace: Resolve selected projects
  Workspace-->>CLI: Workspace projects and configuration
  CLI->>Lockfiles: Load shared or project lockfiles
  Lockfiles-->>CLI: Dependency lock data
  CLI->>PackumentCache: Fetch package metadata
  PackumentCache-->>CLI: Cached package metadata
  CLI->>Output: Render aggregated outdated packages and dependents
Loading

Possibly related issues

Suggested labels: product: pacquet

Suggested reviewers: copilot, yeshyungseok

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

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

pacquet: make outdated workspace-recursive and default list/ll to recursive

✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Add pnpm outdated -r support across selected workspace projects, including filters.
• Aggregate outdated deps across projects and report dependents in table/list/JSON outputs.
• Promote pnpm list/ll to recursive-by-default when run inside a workspace.
Diagram

graph TD
  A["pacquet CLI"] --> B["CliArgs parse"] --> C["Promote recursive"] --> D["outdated -r"] --> E["Workspace discover"] --> F["Project selection"] --> G{"Shared lockfile?"}
  G -->|"yes"| H[("Workspace lockfile") ] --> I["Collect per importer"] --> J["Aggregate dependents"] --> K["Render (table/list/json)"]
  G -->|"no"| L[("Project lockfile") ] --> I
  subgraph Legend
    direction LR
    _p["Process"] ~~~ _d{"Decision"} ~~~ _db[("Lockfile")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use a typed map key (tuple) instead of a string key with separators
  • ➕ Avoids delimiter/escaping concerns in aggregation keys
  • ➕ Makes grouping logic more self-documenting and type-safe
  • ➕ Can naturally use BTreeMap for deterministic iteration if desired
  • ➖ Requires implementing ordering/hashing for a composite key type
  • ➖ Slightly more boilerplate than the current String key approach
2. Return a package->dependents map from collection instead of post-processing
  • ➕ Concentrates aggregation and grouping in one place
  • ➕ Could reduce intermediate allocations when many projects share deps
  • ➖ Bigger refactor of existing collect_outdated_for_importer flow
  • ➖ Harder to keep parity with non-recursive output without duplication

Recommendation: Current approach is sound for parity: it reuses existing workspace selection, supports both lockfile layouts, preserves importer identity for shared lockfiles, and adds dependents-aware renderers without destabilizing the non-recursive path. The main potential improvement would be swapping the aggregation key to a typed composite to reduce risk and improve readability, but it’s not required to land this behavior.

Files changed (7) +454 / -35

Enhancement (3) +285 / -26
cli_command.rsMark 'list'/'ll' as recursive-by-default and add promotion hook +15/-0

Mark 'list'/'ll' as recursive-by-default and add promotion hook

• Adds a 'promote_recursive_by_default' helper that enables '--recursive' automatically when running inside a workspace. Introduces 'CliCommand::recursive_by_default()' to scope the behavior to 'list' and 'll'.

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

outdated.rsImplement workspace-recursive 'outdated' with dependent aggregation and outputs +269/-26

Implement workspace-recursive 'outdated' with dependent aggregation and outputs

• Replaces the prior rejection of '--recursive' with a recursive execution path that discovers/selects workspace projects, loads shared or dedicated lockfiles, and collects outdated results per importer. Aggregates equivalent outdated findings across projects and extends table/list/JSON renderers to include dependent project names and locations; refactors sorting/comparison helpers and centralizes the no-lockfile error.

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

lib.rsInvoke recursive-by-default promotion during CLI initialization +1/-0

Invoke recursive-by-default promotion during CLI initialization

• Calls 'args.promote_recursive_by_default()' after filter-based promotion so the default-recursive behavior applies consistently during command dispatch.

pnpm/crates/cli/src/lib.rs

Tests (3) +164 / -9
tests.rsAdd unit tests for recursive-by-default promotion behavior +52/-0

Add unit tests for recursive-by-default promotion behavior

• Adds tests verifying 'list' is promoted to recursive mode inside a workspace, remains non-recursive outside, and that non-marked commands (e.g. 'outdated') are not promoted.

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

list.rsAdd integration coverage for default-recursive 'list' in workspaces +39/-1

Add integration coverage for default-recursive 'list' in workspaces

• Adds an integration test asserting 'pacquet list' (with JSON output) includes all workspace projects by default when invoked from the workspace root. Updates an existing test to explicitly scope output to the root project using '--filter .' now that recursion is the default in workspaces.

pnpm/crates/cli/tests/list.rs

outdated.rsAdd integration tests for recursive 'outdated' aggregation and lockfile layouts +73/-8

Add integration tests for recursive 'outdated' aggregation and lockfile layouts

• Replaces the prior 'recursive is rejected' test with coverage that recursive outdated aggregates dependents across projects and respects '--filter' selection in JSON output. Adds a dedicated-lockfile workspace case ('sharedWorkspaceLockfile: false') to ensure recursive outdated loads per-project lockfiles and still reports dependents.

pnpm/crates/cli/tests/outdated.rs

Documentation (1) +5 / -0
recursive-outdated-queries.mdAdd release note for recursive 'outdated' and default-recursive 'list'/'ll' +5/-0

Add release note for recursive 'outdated' and default-recursive 'list'/'ll'

• Introduces a changeset documenting workspace-recursive 'pnpm outdated' and the new default-recursive behavior for 'pnpm list' and 'pnpm ll' in workspaces.

.changeset/recursive-outdated-queries.md

@greptile-apps

greptile-apps Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Reviews (6): Last reviewed commit: "fix(cli): handle non-UTF-8 outdated path..." | Re-trigger Greptile

@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     12.7±1.29ms    29.6 MB/sec    1.12     14.2±1.68ms    26.3 MB/sec
packument/parse                1.01     41.3±0.53µs  1605.0 MB/sec    1.00     40.9±1.70µs  1620.1 MB/sec
tarball/download_dependency    1.00      2.6±0.25ms  1688.5 KB/sec    1.07      2.8±0.28ms  1576.2 KB/sec

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Non-UTF8 path JSON panic ✓ Resolved 🐞 Bug ⛨ Security
Description
render_recursive_json serializes DependentProject.location (a PathBuf) directly via
serde_json::json!, which can panic if any workspace project path is not valid UTF-8. This creates
a repo-controlled denial-of-service for pnpm outdated --recursive --format json on filesystems
that allow non-UTF8 directory names.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R897-900]

+            "dependentPackages": entry.dependents.iter().map(|dependent| serde_json::json!({
+                "name": dependent.name,
+                "location": dependent.location,
+            })).collect::<Vec<_>>(),
Evidence
The new recursive JSON output includes a raw PathBuf field, while existing JSON outputs in this
repo explicitly convert paths to UTF-8 strings using to_string_lossy(), indicating direct
PathBuf JSON serialization is not treated as safe/portable here.

pnpm/crates/cli/src/cli_args/outdated.rs[886-914]
pnpm/crates/cli/src/cli_args/list.rs[327-337]
pnpm/crates/cli/src/cli_args/recursive.rs[203-214]

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

### Issue description
`render_recursive_json` embeds a `PathBuf` directly into a JSON value (`"location": dependent.location`). On Unix, paths may contain non-UTF8 bytes, and JSON output should never panic/crash because a repo chose such a directory name.

### Issue Context
Other CLI JSON outputs already convert paths to UTF-8 strings (lossy) before serializing, suggesting that JSON-facing structures should avoid `PathBuf` serialization directly.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[886-914]
- pnpm/crates/cli/src/cli_args/outdated.rs[391-395]

### Suggested fix
Convert `dependent.location` to a `String` before feeding it into `json!`, e.g.:
- store `location: String` in `DependentProject` (set via `project_dir.to_string_lossy().into_owned()`), **or**
- in `render_recursive_json`, use `dependent.location.to_string_lossy()` and serialize that string.

(Prefer matching `list`/`recursive` summary behavior that already uses `to_string_lossy()` for JSON.)

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


2. fetch_package_cached() panics on lock ✓ Resolved 📘 Rule violation ⛨ Security
Description
fetch_package_cached() locks the packument cache via `cache.lock().expect("packument cache mutex
poisoned")`, which will panic if the mutex is poisoned (e.g., due to an earlier panic while holding
the lock) and crash pnpm outdated instead of returning a structured error. This creates a
user-visible crash/DoS path in a CLI flow that should match pnpm’s behavior contract when handling
potentially untrusted workspace/registry inputs.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R231-233]

+    let entry = {
+        let mut cache = cache.lock().expect("packument cache mutex poisoned");
+        Arc::clone(cache.entry(key).or_default())
Evidence
The cited code in outdated.rs acquires the shared cache mutex using expect(...), and in Rust a
poisoned mutex causes lock() to return an error that expect converts into an immediate panic,
producing a hard abort during normal execution if poisoning occurs. The compliance guidance (PR
Compliance ID 1 / review guide) requires pacquet to preserve pnpm’s user-visible behavior contracts
and explicitly flags panic-driven aborts as a DoS pattern to avoid, so this panic-on-poisoning
behavior is directly evidenced as both a contract divergence and a security robustness concern on a
user-facing command path.

CLAUDE.md: Keep TypeScript pnpm CLI and Rust pacquet behavior in sync for user-visible changes
pnpm/crates/cli/src/cli_args/outdated.rs[231-233]
pnpm/crates/cli/src/cli_args/outdated.rs[223-243]
REVIEW_GUIDE.md[48-60]

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

## Issue description
`fetch_package_cached()` currently calls `cache.lock().expect("packument cache mutex poisoned")`, which will panic and abort the CLI if the mutex becomes poisoned.

## Issue Context
This cache is exercised on a user-facing command path (`outdated`, including recursive). A panic is a user-visible behavior contract break for pnpm/pacquet, and it also creates a denial-of-service vector where a single poisoned lock can crash subsequent fetches during the invocation. While poisoning may be rare and the lock is held briefly, the project guidance explicitly calls out avoiding panic-on-(potentially) untrusted-input/CLI DoS patterns; prefer either recovering from poisoning or converting it into a structured error (e.g., `miette`) rather than panicking.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[223-243]
- REVIEW_GUIDE.md[48-60]

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


3. fetch_package_cached() ignores registry errors ✓ Resolved 📘 Rule violation ☼ Reliability
Description
fetch_package_cached() turns registry fetch failures into None via .ok(), and because the
caller uses ? in an Option-returning closure the dependency is silently omitted from the
outdated report instead of surfacing a contextual, user-actionable error. Additionally, the cache
memoizes that None in a OnceCell, so a single transient/auth/network failure can suppress
outdated reporting for the same package across all dependents for the rest of the run, producing
incomplete/incorrect outdated --recursive output.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R224-229]

+        .get_or_init(|| async {
+            Package::fetch_from_registry(package_name, http_client, registry, auth_headers)
+                .await
+                .ok()
+                .map(Arc::new)
+        })
Evidence
PR Compliance ID 9 requires avoiding broadly swallowed errors and handling user-reachable failures
with precise, contextual messaging, but the new cache helper stores the result of the registry fetch
using .await.ok(), converting any failure into None. The returned Option is then consumed with
fetch_package_cached(...).await? inside an Option-returning closure, so None short-circuits to
“no result” and the dependency is dropped from the report; because the None is stored in a
OnceCell keyed by (registry, package), subsequent callers for the same key reuse the cached
None, spreading the omission to other dependents in recursive mode.

CLAUDE.md: Use PnpmError for user-reachable errors and avoid swallowing errors
pnpm/crates/cli/src/cli_args/outdated.rs[181-205]
pnpm/crates/cli/src/cli_args/outdated.rs[211-232]
pnpm/crates/cli/src/cli_args/outdated.rs[176-206]
pnpm/crates/registry/src/package.rs[98-126]

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

## Issue description
`fetch_package_cached()` swallows registry fetch errors by converting them to `None` (via `.ok()`), and callers use `?` in an `Option`-returning closure, which silently omits dependencies from `outdated` output rather than surfacing a contextual, user-actionable error. Because the cache memoizes this `None` in a `OnceCell`, a single transient/auth/network failure can permanently suppress outdated reporting for that package for the remainder of the command run, especially impacting `outdated --recursive`.

## Issue Context
- The cache uses `OnceCell<Option<Arc<Package>>>` and stores `None` when `Package::fetch_from_registry` fails.
- The caller pattern `fetch_package_cached(...).await?` inside an `Option`-returning closure causes `None` to short-circuit to “no result,” dropping that dependency from the report.
- In recursive mode, many projects share dependencies, so a single transient failure can hide outdated results across the workspace.
- PR Compliance ID 9 expects errors not be broadly swallowed and user-reachable failures to be handled with precise, contextual errors.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[181-205]
- pnpm/crates/cli/src/cli_args/outdated.rs[211-232]

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


View more (3)
4. run_recursive ignores stdout errors ✓ Resolved 📘 Rule violation ◔ Observability
Description
The recursive outdated path ignores errors from writeln! and flush, which can hide broken pipe
/ I/O failures and report success-like behavior despite failing to emit output. This violates the
requirement to avoid swallowing errors in user-facing paths.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R564-566]

+        let mut stdout = std::io::stdout();
+        let _ = writeln!(stdout, "{output}");
+        let _ = stdout.flush();
Evidence
PR Compliance ID 9 explicitly disallows broadly swallowing errors in user-reachable code. The added
recursive code path writes to stdout and flushes while discarding the Result, preventing callers
from seeing or handling output failures.

CLAUDE.md: Use PnpmError for user-reachable errors and avoid swallowing errors
pnpm/crates/cli/src/cli_args/outdated.rs[559-567]

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

## Issue description
`run_recursive` discards stdout write and flush errors.

## Issue Context
In CLI commands, failing to write output (e.g. broken pipe) should be handled deterministically (either propagate an error, or explicitly ignore broken-pipe only and return Ok).

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[559-567]

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


5. Terminal escape injection ✓ Resolved 🐞 Bug ⛨ Security
Description
Recursive outdated prints workspace project names (from package.json) into table/list output
without sanitizing control characters. A malicious repo can embed terminal escape sequences in a
project name to spoof/hide output in a developer terminal or CI logs.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R833-838]

+fn render_dependents(entry: &OutdatedInWorkspace) -> String {
+    let mut names: Vec<&str> =
+        entry.dependents.iter().map(|dependent| dependent.name.as_str()).collect();
+    names.sort_unstable();
+    names.join(", ")
+}
Evidence
DependentProject.name is sourced from the workspace project's manifest and then joined into the
rendered output without any sanitization. The CLI already provides a sanitize helper and uses it
in other output renderers to prevent raw control chars reaching the terminal.

pnpm/crates/cli/src/cli_args/outdated.rs[402-476]
pnpm/crates/cli/src/cli_args/outdated.rs[775-801]
pnpm/crates/cli/src/cli_args/outdated.rs[833-838]
pnpm/crates/cli/src/cli_args/sanitize.rs[4-14]
pnpm/crates/cli/src/cli_args/deps_tree/render.rs[99-108]

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

## Issue description
Recursive `outdated` renders `DependentProject.name` (manifest-controlled) directly into human-readable table/list output, allowing terminal control/escape injection.

## Issue Context
The repo already has terminal-safety sanitizers used in other renderers. Recursive outdated should apply the same policy to all manifest-derived strings rendered to stdout.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[468-488]
- pnpm/crates/cli/src/cli_args/outdated.rs[775-801]
- pnpm/crates/cli/src/cli_args/outdated.rs[833-838]
- pnpm/crates/cli/src/cli_args/sanitize.rs[4-14]

## Suggested fix
- For table/list output paths, sanitize/escape control characters in dependent names (and ideally also in any other manifest/registry strings rendered to the terminal).
- Prefer escaping (like `escape_unicode`) or stripping *all* control chars including `\n`/`\t` for single-cell table/list fields, so names cannot break layout.
- Keep JSON output as structured JSON (no terminal injection risk there).

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


6. Recursive JSON drops entries ✗ Dismissed 🐞 Bug ≡ Correctness
Description
render_recursive_json keys the JSON object only by package_name, so multiple distinct outdated
entries for the same package overwrite each other. This silently loses dependents and/or outdated
rows (e.g., differing dependencyType/current/target across workspace projects).
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R803-828]

+fn render_recursive_json(outdated: &[OutdatedInWorkspace], long: bool) -> String {
+    let mut map = serde_json::Map::new();
+    for entry in outdated {
+        let package = &entry.package;
+        let dependency_type: &'static str = package.belongs_to.into();
+        let mut value = serde_json::json!({
+            "current": package.current.to_string(),
+            "latest": package.target.to_string(),
+            "wanted": package.current.to_string(),
+            "isDeprecated": package.deprecated.is_some(),
+            "dependencyType": dependency_type,
+            "dependentPackages": entry.dependents.iter().map(|dependent| serde_json::json!({
+                "name": dependent.name,
+                "location": dependent.location,
+            })).collect::<Vec<_>>(),
+        });
+        if long {
+            value["latestManifest"] = serde_json::json!({
+                "name": package.package_name,
+                "version": package.target.to_string(),
+                "deprecated": package.deprecated,
+                "homepage": package.homepage,
+            });
+        }
+        map.insert(package.package_name.clone(), value);
+    }
Evidence
Workspace aggregation can create multiple OutdatedInWorkspace entries that share package_name
but differ in other dimensions; the JSON renderer overwrites on package_name only due to
Map::insert semantics.

pnpm/crates/cli/src/cli_args/outdated.rs[477-488]
pnpm/crates/cli/src/cli_args/outdated.rs[803-831]

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

## Issue description
`render_recursive_json` uses `serde_json::Map` keyed only by `package.package_name`. When recursive aggregation produces multiple entries for the same package name, later inserts overwrite earlier ones, losing data.

## Issue Context
Recursive aggregation distinguishes entries at least by `(package_name, current, dependencyType)` but JSON output collapses them back to `package_name` only.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[477-488]
- pnpm/crates/cli/src/cli_args/outdated.rs[803-831]

## Suggested fix
Pick an output schema that preserves uniqueness:
- Option A: top-level JSON array of entries (each includes name/current/target/dependencyType/dependentPackages).
- Option B: keep top-level object keyed by package name but make the value an array when multiple entries exist (or a nested object keyed by `dependencyType`+`current`+`target`).
Also consider aligning the non-recursive `render_json` behavior similarly if it can have the same collision class.

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



Remediation recommended

7. render_recursive_* duplicates renderers 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new recursive outdated renderers largely duplicate the existing table/list/JSON render paths,
increasing maintenance burden and risk of inconsistent output formatting over time. This violates
the repo guidance to avoid non-trivial duplicated logic when shared utilities can be extracted.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R825-914]

+fn render_recursive_table(outdated: &[OutdatedInWorkspace], long: bool) -> String {
+    if outdated.is_empty() {
+        return String::new();
+    }
+    use tabled::builder::Builder;
+    use tabled::settings::Style;
+
+    let mut header: Vec<String> = ["Package", "Current", "Latest", "Dependents"]
+        .iter()
+        .map(|heading| bright_blue(heading))
+        .collect();
+    if long {
+        header.push(bright_blue("Details"));
+    }
+    let mut builder = Builder::default();
+    builder.push_record(header);
+    for entry in outdated {
+        let mut row = vec![
+            render_package_name(&entry.package),
+            entry.package.current.to_string(),
+            render_latest(&entry.package),
+            render_dependents(entry),
+        ];
+        if long {
+            row.push(render_details(&entry.package));
+        }
+        builder.push_record(row);
+    }
+    let mut table = builder.build();
+    table.with(Style::modern());
+    table.to_string()
+}
+
+fn render_recursive_list(outdated: &[OutdatedInWorkspace], long: bool) -> String {
+    outdated
+        .iter()
+        .map(|entry| {
+            let package = &entry.package;
+            let label = if entry.dependents.len() == 1 { "Dependent:" } else { "Dependents:" };
+            let mut info = format!(
+                "{}\n{} {} {}\n{} {}",
+                bold(&render_package_name(package)),
+                package.current,
+                grey("=>"),
+                render_latest(package),
+                bold(label),
+                render_dependents(entry),
+            );
+            if long {
+                let details = render_details(package);
+                if !details.is_empty() {
+                    info.push('\n');
+                    info.push_str(&details);
+                }
+            }
+            info
+        })
+        .collect::<Vec<_>>()
+        .join("\n\n")
+}
+
+fn render_recursive_json(outdated: &[OutdatedInWorkspace], long: bool) -> String {
+    let mut map = serde_json::Map::new();
+    for entry in outdated {
+        let package = &entry.package;
+        let dependency_type: &'static str = package.belongs_to.into();
+        let mut value = serde_json::json!({
+            "current": package.current.to_string(),
+            "latest": package.target.to_string(),
+            "wanted": package.current.to_string(),
+            "isDeprecated": package.deprecated.is_some(),
+            "dependencyType": dependency_type,
+            "dependentPackages": entry.dependents.iter().map(|dependent| serde_json::json!({
+                "name": dependent.name,
+                "location": dependent.location.to_string_lossy(),
+            })).collect::<Vec<_>>(),
+        });
+        if long {
+            value["latestManifest"] = serde_json::json!({
+                "name": package.package_name,
+                "version": package.target.to_string(),
+                "deprecated": package.deprecated,
+                "homepage": package.homepage,
+            });
+        }
+        map.insert(package.package_name.clone(), value);
+    }
+    serde_json::to_string_pretty(&serde_json::Value::Object(map))
+        .expect("serialize recursive outdated report to JSON")
+}
Evidence
PR Compliance ID 4 requires avoiding non-trivial duplication. In outdated.rs, the newly added
recursive rendering functions replicate the structure of the existing renderers with small
variations (extra Dependents column/field), indicating an opportunity to extract shared helpers
and reduce duplicated maintenance surface.

CLAUDE.md; AGENTS.md: Avoid code duplication by reusing or extracting shared utilities and prefer well-maintained libraries
pnpm/crates/cli/src/cli_args/outdated.rs[749-823]
pnpm/crates/cli/src/cli_args/outdated.rs[825-914]

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

## Issue description
Recursive outdated rendering introduces duplicated logic across `render_recursive_table`, `render_recursive_list`, and `render_recursive_json` that mirrors the non-recursive renderers, making future changes error-prone.

## Issue Context
The compliance checklist requires avoiding non-trivial code duplication by reusing/extracting shared utilities.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[749-914]

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


8. Packument cache unbounded 🐞 Bug ➹ Performance ⭐ New
Description
fetch_package_cached retains each fetched Package (packument) in an in-memory HashMap for the
full recursive run with no size bound or eviction. On very large workspaces / many unique deps, this
can raise peak memory significantly (command-bounded growth) and increase OOM risk.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R223-243]

+async fn fetch_package_cached(
+    cache: &PackumentCache,
+    package_name: &str,
+    http_client: &ThrottledClient,
+    registry: &str,
+    auth_headers: &pacquet_network::AuthHeaders,
+) -> Result<Arc<Package>, RegistryError> {
+    let key = (registry.to_string(), package_name.to_string());
+    let entry = {
+        let mut cache = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+        Arc::clone(cache.entry(key).or_default())
+    };
+    let package = entry
+        .get_or_try_init(|| async {
+            Package::fetch_from_registry(package_name, http_client, registry, auth_headers)
+                .await
+                .map(Arc::new)
+        })
+        .await?;
+    Ok(Arc::clone(package))
}
Evidence
The new cache stores Arc<Package> entries in a HashMap for the duration of the recursive run.
Package holds a versions map, and the PackageVersions module explicitly documents
multi-thousand-release packuments and why hydrating/holding them is expensive—retaining many such
packuments simultaneously can materially increase peak memory.

pnpm/crates/cli/src/cli_args/outdated.rs[46-47]
pnpm/crates/cli/src/cli_args/outdated.rs[223-243]
pnpm/crates/cli/src/cli_args/outdated.rs[513-541]
pnpm/crates/registry/src/package.rs[14-20]
pnpm/crates/registry/src/package_versions.rs[1-16]

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

### Issue description
Recursive outdated now deduplicates packument fetches by caching full `Package` objects per `(registry, package)` for the entire run. This is bounded by command lifetime but unbounded in size within a run, so peak memory scales with the number/size of unique packuments.

### Issue Context
- `Package` includes `versions`, which can represent very large packuments (many releases).
- The cache is shared across all workspace project queries, so it can accumulate many unique entries.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[46-47]
- pnpm/crates/cli/src/cli_args/outdated.rs[223-243]
- pnpm/crates/cli/src/cli_args/outdated.rs[513-541]
- pnpm/crates/registry/src/package.rs[14-64]
- pnpm/crates/registry/src/package_versions.rs[1-16]

### What to change
Pick one:
1) **Add a bounded cache** (LRU) for packuments (e.g., max entries or approximate bytes) and evict least-recently-used entries.
2) **Cache derived results instead of full packuments**, e.g. cache `(target_version, deprecated, homepage)` per `(registry, package, range, TargetVersion)`; this keeps memory small while still deduplicating expensive work.

### Acceptance criteria
- Peak memory does not scale linearly without bound in large workspaces.
- No correctness regressions vs. current recursive behavior (still dedupes concurrent fetches; still respects `--compatible` range differences).

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


9. Unsorted JSON dependents 🐞 Bug ☼ Reliability
Description
render_recursive_json emits dependentPackages in the existing insertion order, unlike the
table/list path which explicitly sorts dependent names. This makes recursive JSON output order
depend on workspace selection/traversal order and therefore unstable if that upstream order changes.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R886-901]

+fn render_recursive_json(outdated: &[OutdatedInWorkspace], long: bool) -> String {
+    let mut map = serde_json::Map::new();
+    for entry in outdated {
+        let package = &entry.package;
+        let dependency_type: &'static str = package.belongs_to.into();
+        let mut value = serde_json::json!({
+            "current": package.current.to_string(),
+            "latest": package.target.to_string(),
+            "wanted": package.current.to_string(),
+            "isDeprecated": package.deprecated.is_some(),
+            "dependencyType": dependency_type,
+            "dependentPackages": entry.dependents.iter().map(|dependent| serde_json::json!({
+                "name": dependent.name,
+                "location": dependent.location,
+            })).collect::<Vec<_>>(),
+        });
Evidence
The JSON renderer maps dependents as-is, while the terminal renderer sorts dependent names. The
integration test asserts a fixed dependent order in JSON, demonstrating the project expects stable
ordering semantics for this field.

pnpm/crates/cli/src/cli_args/outdated.rs[886-914]
pnpm/crates/cli/src/cli_args/outdated.rs[916-924]
pnpm/crates/cli/tests/outdated.rs[254-265]

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 recursive JSON renderer emits `dependentPackages` without sorting, while the human-readable renderer sorts dependents. This inconsistency makes JSON output ordering dependent on upstream project discovery/selection order.

### Issue Context
`render_dependents()` already sorts names for terminal output; the JSON path should apply a stable ordering as well (e.g., by `name`, then `location`).

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[886-914]
- pnpm/crates/cli/src/cli_args/outdated.rs[916-924]
- pnpm/crates/cli/tests/outdated.rs[254-265]

### Suggested fix
Before building `dependentPackages`, clone/sort a local `Vec<DependentProject>` (or a list of `(name, location)` pairs) and iterate that sorted list when constructing the JSON array. Use a total ordering (e.g., `name` then `location`) so output is deterministic.

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


View more (7)
10. Unsanitized registry error output 🐞 Bug ⛨ Security
Description
collect_outdated_for_importer_with_cache formats RegistryError into
ERR_PNPM_OUTDATED_REGISTRY_ERROR using only credential redaction, so any control characters that
survive into the error display can be emitted to the terminal/CI logs. This is a newly user-visible
error path (fetch failures are no longer silently skipped), enabling diagnostic spoofing when
registry/config/network-derived text contains such characters.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R190-196]

+            .map_err(|error| {
+                let reason = pacquet_network::redact_url_credentials(&error.to_string());
+                miette::miette!(
+                    code = "ERR_PNPM_OUTDATED_REGISTRY_ERROR",
+                    r#"Failed to fetch metadata for "{package_name}": {reason}"#,
+                )
+            })?;
Evidence
The new error construction uses redact_url_credentials(error.to_string()) directly in a one-line
diagnostic without sanitizing control characters. Elsewhere in the CLI, redacted strings are
explicitly sanitized before printing, indicating the intended safety contract for terminal-facing
text.

pnpm/crates/cli/src/cli_args/outdated.rs[175-213]
pnpm/crates/registry/src/package.rs[98-126]
pnpm/crates/cli/src/cli_args/bugs.rs[299-306]
pnpm/crates/cli/src/cli_args/sanitize.rs[4-24]

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

## Issue description
`ERR_PNPM_OUTDATED_REGISTRY_ERROR` is constructed from `error.to_string()` with credential redaction but no terminal-output sanitization, so control characters can reach stderr.

## Issue Context
The repo already has a `sanitize` helper used before printing redacted URLs (e.g. `bugs` command). Apply the same pattern here for the final rendered error text (at least the `{reason}` string; optionally also `{package_name}` defensively).

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[190-196]
- pnpm/crates/cli/src/cli_args/sanitize.rs[17-24]

## Suggested fix
- After `redact_url_credentials`, run `sanitize_inline` (or `sanitize` if you want to preserve newlines intentionally) on the resulting `reason` string.
- Consider also sanitizing `package_name` in the formatted message (defense-in-depth).

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


11. outdated_indexes uses formatted key 📘 Rule violation ➹ Performance
Description
Recursive outdated aggregation builds a String key via format!("{}\0{}\0{}", ...) inside the
inner loop, causing repeated allocations and a delimiter-collision risk if any component contains
\0. This can add avoidable overhead on large workspaces and can theoretically mis-group entries
when the delimiter appears in input.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R555-566]

+        let mut outdated_indexes: HashMap<String, usize> = HashMap::new();
+        for result in project_results {
+            let (project_outdated, dependent) = result?;
+            for package in project_outdated {
+                let dependency_type: &'static str = package.belongs_to.into();
+                let key =
+                    format!("{}\0{}\0{}", package.package_name, package.current, dependency_type);
+                if let Some(&index) = outdated_indexes.get(&key) {
+                    outdated[index].dependents.push(dependent.clone());
+                } else {
+                    outdated_indexes.insert(key, outdated.len());
+                    outdated
Evidence
PR Compliance ID 9 requires hoisting invariants and avoiding repeated allocations inside loops. The
code constructs a new String key with format! for every outdated dependency during workspace
aggregation, which is a repeated allocation inside a hot loop and uses a delimiter-based encoding.

CLAUDE.md: Async and loops: prefer async fs/async-await; parallelize independent work; hoist invariants out of loops
pnpm/crates/cli/src/cli_args/outdated.rs[555-566]

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

## Issue description
`run_recursive()` constructs a composite grouping key with `format!("{}\0{}\0{}", ...)` inside the per-package loop. This allocates repeatedly and relies on `\0` never appearing in the components.

## Issue Context
This is in the recursive workspace aggregation path and can run over many projects/packages; repeated string allocations and delimiter-based keys are avoidable.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[555-566]

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


12. Unbounded recursive fan-out 🐞 Bug ➹ Performance
Description
OutdatedArgs::run_recursive uses join_all over all selected workspace projects, and each project’s
outdated collection uses another join_all over its dependencies, creating an unbounded number of
scheduled futures for large workspaces even though HTTP concurrency is throttled. This can
noticeably increase memory and scheduling overhead on big monorepos running pnpm outdated -r.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R514-554]

+        let project_queries =
+            project_inputs.iter().map(|(project_dir, project, project_lockfile)| async {
+                let (lockfile, importer_id) = if config.shared_workspace_lockfile {
+                    (
+                        shared_lockfile,
+                        pacquet_workspace::importer_id_from_root_dir(&workspace_root, project_dir),
+                    )
+                } else {
+                    (project_lockfile.as_ref(), Lockfile::ROOT_IMPORTER_KEY.to_string())
+                };
+                let Some(lockfile) = lockfile else {
+                    let lockfile_dir = if config.shared_workspace_lockfile {
+                        workspace_root.as_path()
+                    } else {
+                        project_dir.as_path()
+                    };
+                    return Err(no_lockfile_error(lockfile_dir));
+                };
+                let project_outdated = collect_outdated_for_importer_with_cache(
+                    &project.manifest,
+                    Some(lockfile),
+                    &importer_id,
+                    config,
+                    &state.http_client,
+                    &query,
+                    &packument_cache,
+                )
+                .await?;
+                let dependent = DependentProject {
+                    name: project
+                        .manifest
+                        .value()
+                        .get("name")
+                        .and_then(|name| name.as_str())
+                        .map_or_else(|| project_dir.to_string_lossy().into_owned(), str::to_owned),
+                    location: (*project_dir).clone(),
+                };
+                Ok::<_, miette::Report>((project_outdated, dependent))
+            });
+        let project_results = futures_util::future::join_all(project_queries).await;
+        let mut outdated: Vec<OutdatedInWorkspace> = Vec::new();
Evidence
The recursive path clearly builds a join_all over project futures, and the per-project collector
builds a join_all over dependency futures; the review guide explicitly warns against adding large
amounts of work in common flows without a bounded design.

pnpm/crates/cli/src/cli_args/outdated.rs[158-220]
pnpm/crates/cli/src/cli_args/outdated.rs[514-554]
REVIEW_GUIDE.md[115-127]

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

## Issue description
Recursive outdated currently fans out with `join_all` across projects and again across dependencies, which can create very large future graphs in large workspaces.

## Issue Context
The HTTP client throttles network requests, but it does not bound the number of futures created/polled. Bounding project-level concurrency (and optionally dependency-level concurrency) reduces memory pressure and scheduler overhead.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[158-220]
- pnpm/crates/cli/src/cli_args/outdated.rs[514-578]

## Suggested fix
- Replace `futures_util::future::join_all(project_queries).await` with a bounded stream:
 - `futures_util::stream::iter(project_inputs)`
 - `.map(|...| async move { ... })`
 - `.buffer_unordered(N)` (pick a conservative N like 8–32, or derive from config)
 - `.try_collect::<Vec<_>>()`
- Consider similarly replacing the dependency-level `join_all(fetches)` with a buffered stream to avoid creating all dependency futures at once for projects with very large direct dependency sets.
- Add a perf/regression test or at least a micro-benchmark for a workspace with many projects/deps to validate reduced peak memory/CPU.

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


13. Workspace error suppressed 🐞 Bug ≡ Correctness
Description
CliArgs::promote_recursive_by_default() treats find_workspace_dir() errors as “not in a workspace”,
so misnamed workspace manifests that are supposed to hard-error are silently ignored and list/ll may
run non-recursively in a broken workspace. This can yield unexpectedly scoped output and makes
workspace configuration mistakes hard to diagnose.
Code

pnpm/crates/cli/src/cli_args/cli_command.rs[R246-252]

+    pub fn promote_recursive_by_default(&mut self) {
+        if !self.recursive
+            && self.command.recursive_by_default()
+            && pacquet_workspace::find_workspace_dir(&self.dir).is_ok_and(|dir| dir.is_some())
+        {
+            self.recursive = true;
+        }
Evidence
The promotion code uses is_ok_and(...), which returns false for any error, while the workspace
root finder explicitly raises an error for misnamed workspace manifests instead of treating them as
“no workspace”.

pnpm/crates/cli/src/cli_args/cli_command.rs[244-253]
pnpm/crates/workspace/src/root_finder.rs[15-25]
pnpm/crates/workspace/src/root_finder.rs[34-53]
pnpm/crates/workspace/src/root_finder.rs[105-131]

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

## Issue description
`promote_recursive_by_default()` currently checks `find_workspace_dir(...).is_ok_and(|dir| dir.is_some())`, which collapses `Err(_)` into `false` and suppresses intentional workspace-manifest errors (e.g. misnamed `pnpm-workspace.yaml` variants).

## Issue Context
The workspace root finder explicitly rejects misnamed workspace manifest filenames with a dedicated error type. The new promotion logic should not silently ignore that diagnostic.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/cli_command.rs[244-253]
- pnpm/crates/workspace/src/root_finder.rs[15-53]
- pnpm/crates/workspace/src/root_finder.rs[105-131]

## Suggested fix
- Change `promote_recursive_by_default` to return `miette::Result<()>` (or a `Result<bool, ...>`), call `find_workspace_dir(&self.dir)` and:
 - `Ok(Some(_))` -> set `self.recursive = true`
 - `Ok(None)` -> do nothing
 - `Err(e)` -> propagate so the CLI exits with the intended workspace-manifest error.
- Add a unit test that creates a misnamed workspace manifest (e.g. `pnpm-workspace.yml`) and asserts the error is surfaced when invoking `list`/`ll` inside that directory.

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


14. Blocking lockfile loads ✓ Resolved 🐞 Bug ➹ Performance
Description
In dedicated-lockfile workspaces, run_recursive reads/parses each project lockfile via synchronous
std::fs::read_to_string inside concurrently-polled async tasks, which blocks Tokio worker threads.
This can significantly reduce throughput on large workspaces or slow filesystems and delays the
network-bound outdated checks.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R505-507]

+                    project_lockfile =
+                        Lockfile::load_wanted_from_dir(project_dir).into_diagnostic()?;
+                    (project_lockfile.as_ref(), Lockfile::ROOT_IMPORTER_KEY.to_string())
Evidence
The recursive path constructs many per-project async blocks and awaits them with join_all. In the
dedicated-lockfile branch, each block calls Lockfile::load_wanted_from_dir, which is implemented
using synchronous fs::read_to_string, so this work runs on Tokio worker threads and can block
them.

pnpm/crates/cli/src/cli_args/outdated.rs[455-540]
pnpm/crates/lockfile/src/load_lockfile.rs[80-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
`run_recursive` loads per-project lockfiles synchronously inside async tasks (dedicated lockfile mode). This blocks Tokio worker threads during file IO + YAML parse and can degrade performance in large workspaces.

### Issue Context
This affects the `sharedWorkspaceLockfile: false` path where each selected project reads its own `pnpm-lock.yaml`.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[497-540]
- pnpm/crates/lockfile/src/load_lockfile.rs[80-121]

### Suggested fix approach
- Offload dedicated lockfile loading to blocking threads:
 - Wrap `Lockfile::load_wanted_from_dir(project_dir)` in `tokio::task::spawn_blocking` and await it inside the async block.
 - Consider limiting concurrent blocking loads (e.g., semaphore) to avoid saturating the blocking pool on very large workspaces.
- Alternatively, pre-load lockfiles sequentially before starting the async network fan-out, then run only the registry fetches concurrently.

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


15. Grouping ignores target 🐞 Bug ≡ Correctness
Description
Workspace aggregation groups by (package_name, current, dependencyType) and ignores target, but
--compatible target resolution depends on each project's manifest range. This can merge entries
that should remain separate and display an incorrect target for some dependents.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R477-487]

+            for package in project_outdated {
+                let dependency_type: &'static str = package.belongs_to.into();
+                let key =
+                    format!("{}\0{}\0{}", package.package_name, package.current, dependency_type);
+                if let Some(&index) = outdated_indexes.get(&key) {
+                    outdated[index].dependents.push(dependent.clone());
+                } else {
+                    outdated_indexes.insert(key, outdated.len());
+                    outdated
+                        .push(OutdatedInWorkspace { package, dependents: vec![dependent.clone()] });
+                }
Evidence
The aggregation key is built without target, while the computed target version depends on each
dependency's range string; different ranges can yield different targets in compatible mode.

pnpm/crates/cli/src/cli_args/outdated.rs[184-202]
pnpm/crates/cli/src/cli_args/outdated.rs[477-488]

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 recursive outdated, the aggregation key omits `target`. Under `TargetVersion::WithinRange` (`--compatible`), two projects can resolve different targets from different semver ranges, but the code merges them and retains only the first `OutdatedPackage`.

## Issue Context
`resolve_target` uses the manifest range to compute the target version; that range can vary per workspace project.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[184-202]
- pnpm/crates/cli/src/cli_args/outdated.rs[477-488]

## Suggested fix
- Extend the aggregation identity to include `package.target` (and, if needed, the effective range/specifier) so only truly equivalent findings are merged.
- Alternatively, keep a single group but store per-dependent target info and reflect that in output; however that is a bigger schema change.

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


16. Redundant registry fetches ✓ Resolved 🐞 Bug ➹ Performance
Description
Recursive outdated calls collect_outdated_for_importer per selected project, and that function
fetches packuments via an unconditional registry GET. In large workspaces with overlapping
dependencies, this can trigger many redundant network requests and noticeably increase runtime and
registry load.
Code

pnpm/crates/cli/src/cli_args/outdated.rs[R431-467]

+        for (project_dir, node) in &selection.selected {
+            let project = node.package.project;
+            let has_any_dependency = project
+                .manifest
+                .dependencies([
+                    DependencyGroup::Prod,
+                    DependencyGroup::Dev,
+                    DependencyGroup::Optional,
+                ])
+                .next()
+                .is_some();
+            if !has_any_dependency {
+                continue;
+            }
+
+            let project_lockfile;
+            let (lockfile, importer_id) = if config.shared_workspace_lockfile {
+                (
+                    shared_lockfile,
+                    pacquet_workspace::importer_id_from_root_dir(&workspace_root, project_dir),
+                )
+            } else {
+                project_lockfile = Lockfile::load_wanted_from_dir(project_dir).into_diagnostic()?;
+                (project_lockfile.as_ref(), Lockfile::ROOT_IMPORTER_KEY.to_string())
+            };
+            let Some(lockfile) = lockfile else {
+                return Err(no_lockfile_error(project_dir));
+            };
+            let project_outdated = collect_outdated_for_importer(
+                &project.manifest,
+                Some(lockfile),
+                &importer_id,
+                config,
+                &state.http_client,
+                &query,
+            )
+            .await?;
Evidence
The recursive loop invokes collect_outdated_for_importer for each project; collection fetches
packuments from the registry; and the fetch implementation is a plain GET without any caching/dedup
at this layer. The resolver crate explicitly describes an existing caching/dedup approach for this
exact problem class.

pnpm/crates/cli/src/cli_args/outdated.rs[402-467]
pnpm/crates/cli/src/cli_args/outdated.rs[116-179]
pnpm/crates/registry/src/package.rs[98-126]
pnpm/crates/resolving-npm-resolver/src/pick_package.rs[6-45]

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

## Issue description
Recursive outdated repeats packument fetches across projects. `collect_outdated_for_importer` fetches per dependency using `Package::fetch_from_registry`, which always issues a network request.

## Issue Context
The resolver already documents a packument cache/dedup mechanism to avoid N duplicated HTTP GETs for the same package within one run.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/outdated.rs[402-467]
- pnpm/crates/cli/src/cli_args/outdated.rs[116-179]
- pnpm/crates/registry/src/package.rs[98-126]
- pnpm/crates/resolving-npm-resolver/src/pick_package.rs[6-45]

## Suggested fix
- Introduce a per-run, cross-project packument cache (e.g., `DashMap<(registry, package_name), Arc<Package>>` plus a per-key lock/OnceCell) and use it in `collect_outdated_for_importer`.
- Or route metadata fetching through the existing resolver cache layer if it’s appropriate for `outdated`.
- Keep concurrency bounds via `ThrottledClient`, but avoid re-fetching identical packuments across workspace projects.

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



Informational

17. Bidi spoofing still possible 🐞 Bug ⛨ Security
Description
sanitize_inline removes only Unicode control characters (char::is_control), but leaves Unicode
format characters (e.g., bidi override/isolate marks) that can visually reorder/spoof the new
recursive dependents field in human-readable output. This leaves a presentation-level spoofing
vector in terminal output despite the new sanitization step.
Code

pnpm/crates/cli/src/cli_args/sanitize.rs[R17-23]

[Comment truncated to fit github's 65,536-char limit.]

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

431-489: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Sequential per-project registry checks in the recursive loop.

Each iteration of the for (project_dir, node) in &selection.selected loop awaits collect_outdated_for_importer before moving to the next project, serializing registry lookups across the whole workspace. For workspaces with many packages this could add up; consider running these concurrently (e.g. futures::stream::iter(...).buffer_unordered(n)) once correctness in the aggregation/rendering (see above) is settled.

🤖 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/outdated.rs` around lines 431 - 489, Update the
per-project processing in the loop over selection.selected to run
collect_outdated_for_importer concurrently, using the project’s lockfile,
importer_id, and dependent metadata as each task’s result. Buffer concurrency
with the established limit or an appropriate bounded value, then perform the
existing outdated_indexes aggregation after results complete so output grouping
and rendering remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm/crates/cli/src/cli_args/outdated.rs`:
- Around line 402-502: Thread self.sort_by through run_recursive into
sort_workspace_outdated, updating its signature and the compare_outdated call so
recursive output honors the requested sorting. Preserve the existing default
ordering when no sort option is provided.
- Around line 446-458: Update the missing-lockfile error in the lockfile
selection flow around config.shared_workspace_lockfile and the shared_lockfile
binding to report workspace_root for shared-lockfile workspaces, while retaining
project_dir for project-specific lockfiles. Ensure the error path passes the
directory corresponding to the lockfile that was actually attempted.
- Around line 803-831: Update render_recursive_json so entries with the same
package name but different current versions or dependencyType values are not
overwritten by map.insert. Use a composite identity consistent with
run_recursive, or group each package name’s values in an array, while preserving
the existing JSON fields and long-mode latestManifest data for every workspace
entry.

---

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/outdated.rs`:
- Around line 431-489: Update the per-project processing in the loop over
selection.selected to run collect_outdated_for_importer concurrently, using the
project’s lockfile, importer_id, and dependent metadata as each task’s result.
Buffer concurrency with the established limit or an appropriate bounded value,
then perform the existing outdated_indexes aggregation after results complete so
output grouping and rendering remain unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2eaf9a3a-6aa1-4e83-8967-ebaa6d0853f4

📥 Commits

Reviewing files that changed from the base of the PR and between 7763777 and d332355.

📒 Files selected for processing (7)
  • .changeset/recursive-outdated-queries.md
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/outdated.rs
  • pnpm/crates/cli/src/cli_args/tests.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/tests/list.rs
  • pnpm/crates/cli/tests/outdated.rs

@codecov-commenter

codecov-commenter commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.95082% with 52 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.78%. Comparing base (23978d2) to head (dc70f9f).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/cli/src/cli_args/outdated.rs 82.13% 52 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13202      +/-   ##
==========================================
+ Coverage   86.68%   86.78%   +0.10%     
==========================================
  Files         523      525       +2     
  Lines       87948    89206    +1258     
==========================================
+ Hits        76238    77421    +1183     
- Misses      11710    11785      +75     

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

Copilot AI review requested due to automatic review settings July 21, 2026 21:16

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 21, 2026

Copy link
Copy Markdown
Member Author

Addressed the actionable summary-only performance feedback in c17529143b as well:

  • selected workspace projects now collect outdated metadata concurrently, matching the TypeScript Promise.all fan-out;
  • a command-scoped (registry, package) cache coalesces identical concurrent packument requests across projects;
  • focused coverage verifies that two concurrent consumers issue one registry request.

The target-grouping, recursive JSON-keying, and recursive --sort-by observations describe current TypeScript behavior. They remain unchanged here so this Rust-parity PR does not introduce a different user-visible contract; any corrections should land in both implementations together.


Written by an agent (Codex, GPT-5).

@qodo-code-review

Copy link
Copy Markdown

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/outdated.rs (1)

183-233: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Fetch failures are cached forever in the shared PackumentCache, silently poisoning results for every other workspace project.

fetch_package_cached stores whatever Package::fetch_from_registry(...).ok() returns — including None on any error (timeout, 5xx, connection reset, not just a genuine 404) — inside the OnceCell for the (registry, package_name) key. Previously each collect_outdated_for_importer call got its own throwaway PackumentCache::default(), so a fetch failure only affected that one project's single call. Now, in run_recursive, one packument_cache is shared across every selected workspace project for the whole command run (line 482), so a single transient failure fetching a commonly-depended-on package will permanently suppress that package from the aggregated outdated report for all other projects that depend on it during this run — with no retry.

🔧 Proposed fix: don't let a failed fetch permanently poison the cache
 async fn fetch_package_cached(
     cache: &PackumentCache,
     package_name: &str,
     http_client: &ThrottledClient,
     registry: &str,
     auth_headers: &pacquet_network::AuthHeaders,
 ) -> Option<Arc<Package>> {
     let key = (registry.to_string(), package_name.to_string());
     let entry = {
         let mut cache = cache.lock().expect("packument cache mutex poisoned");
-        Arc::clone(cache.entry(key).or_default())
+        Arc::clone(cache.entry(key.clone()).or_default())
     };
-    entry
+    let result = entry
         .get_or_init(|| async {
             Package::fetch_from_registry(package_name, http_client, registry, auth_headers)
                 .await
                 .ok()
                 .map(Arc::new)
         })
         .await
-        .clone()
+        .clone();
+    if result.is_none() {
+        // Don't let one transient failure permanently poison the shared
+        // cache for every other project in this recursive run.
+        cache.lock().expect("packument cache mutex poisoned").remove(&key);
+    }
+    result
 }

Concurrent callers that grabbed the same OnceCell before eviction still coalesce onto the one in-flight request; eviction only affects later, non-concurrent lookups so they can retry.

As per path instructions, REVIEW_GUIDE.md directs reviewers to "check changed network/registry/cache logic for cache-poisoning or trust-boundary mistakes (especially concurrent packument requests)."

🤖 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/outdated.rs` around lines 183 - 233, Update
fetch_package_cached so failed Package::fetch_from_registry results are not
retained in the shared PackumentCache: only cache successful fetches, and evict
the corresponding (registry, package_name) entry after an error or None result.
Preserve OnceCell coalescing for callers already sharing an in-flight request,
while allowing later lookups to retry transient failures.

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/outdated.rs`:
- Around line 183-233: Update fetch_package_cached so failed
Package::fetch_from_registry results are not retained in the shared
PackumentCache: only cache successful fetches, and evict the corresponding
(registry, package_name) entry after an error or None result. Preserve OnceCell
coalescing for callers already sharing an in-flight request, while allowing
later lookups to retry transient failures.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e78dc47-5f6e-4f37-a5d6-8f302f49db76

📥 Commits

Reviewing files that changed from the base of the PR and between d332355 and c175291.

📒 Files selected for processing (4)
  • pnpm/crates/cli/src/cli_args/outdated.rs
  • pnpm/crates/cli/src/cli_args/outdated/tests.rs
  • pnpm/crates/cli/src/cli_args/sanitize.rs
  • pnpm/crates/cli/tests/outdated.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • pnpm/crates/cli/tests/outdated.rs

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 21, 2026
Copilot AI review requested due to automatic review settings July 21, 2026 21:31

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 21, 2026

Copy link
Copy Markdown
Member Author

Also addressed the new summary-only dedicated-lockfile performance finding in 2d07d43f2a: project lockfiles are now loaded sequentially before constructing the concurrent registry-query futures, so synchronous lockfile reads and YAML parsing no longer run inside the network fan-out.

The repeated target-grouping observation remains intentionally aligned with the TypeScript recursive implementation, whose aggregation key is [packageName, current, belongsTo].


Written by an agent (Codex, GPT-5).

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