Skip to content

feat(pacquet): add patch workflow commands - #12609

Merged
zkochan merged 11 commits into
pnpm:mainfrom
spencer17x:feat/pacquet-patch-commands
Jun 24, 2026
Merged

zkochan merged 11 commits into
pnpm:mainfrom
spencer17x:feat/pacquet-patch-commands

Conversation

@spencer17x

@spencer17x spencer17x commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Port the patch workflow commands to pacquet: patch, patch-commit, and patch-remove.
  • Add pacquet support for patchesDir, patch state handling, patched dependency manifest edits, and lockfile patch metadata.
  • Align patch workflow behavior with pnpm for cleanup, optional dependency edges, and colored success output.

Related to #11633.

Squash Commit Body

Port pnpm's package patch workflow to pacquet.

This adds pacquet implementations for patch, patch-commit, and patch-remove,
including edit-dir state, patch file creation and removal, patchedDependencies
manifest updates, reinstall integration, and lockfile patch metadata.

The implementation also adds patchesDir support to pacquet configuration and
extends the workspace manifest writer so patchedDependencies can be updated
without disturbing unrelated workspace fields. Patch removal now avoids leaving
empty pnpm-workspace.yaml files behind and preserves optional lockfile child
edges when removing patches.

Tests cover package selection, edit-dir state, patch file reuse, custom patch
directories, patch removal validation, workspace-project behavior, symlink and
traversal rejection, and the patch reinstall paths.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting.
  • Added or updated tests.

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

Summary by CodeRabbit

  • New Features
    • Added patch workflow commands: pacquet patch, pacquet patch-commit, and pacquet patch-remove.
    • Added patchesDir / PNPM_CONFIG_PATCHES_DIR support to control where generated patch files are written.
    • Workspace manifest patchedDependencies is now created/updated/removed as part of the patch lifecycle.
  • Bug Fixes
    • Hardened patch file/directory handling to prevent traversal and symlink escape; improved patch-state persistence safety.
  • Tests
    • Added/expanded unit and integration coverage for the full patch lifecycle and reporter modes (ndjson, silent).

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds patch, patch-commit, and patch-remove CLI subcommands to pacquet. Includes package-manager core for lockfile-based candidate selection, tarball extraction, and git diff-based patch generation; workspace manifest writer support for patchedDependencies YAML editing; edit-dir state persistence; filesystem-safe patch removal; patchesDir config propagation; and optional_children propagation through the peer resolver and lockfile generator.

Changes

Patch workflow implementation

Layer / File(s) Summary
patchesDir config field, env overlay, and workspace YAML
pacquet/crates/config/src/lib.rs, pacquet/crates/config/src/workspace_yaml.rs, pacquet/crates/config/src/env_overlay.rs, pacquet/crates/config/src/tests.rs, pacquet/crates/config/src/workspace_yaml/tests.rs, pacquet/crates/package-manager/src/install_package_from_registry/tests.rs
Adds patches_dir: Option<String> to Config and WorkspaceSettings, wires env-overlay parsing for PNPM_CONFIG_PATCHES_DIR, propagates the field from YAML apply_to, and updates tests.
optional_children propagation in resolver and lockfile
pacquet/crates/resolving-deps-resolver/src/dependencies_graph.rs, pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs, pacquet/crates/resolving-deps-resolver/src/resolve_peers/tests.rs, pacquet/crates/resolving-deps-resolver/src/dedupe_injected_deps/tests.rs, pacquet/crates/resolving-deps-resolver/src/dedupe_peer_dependents/tests.rs, pacquet/crates/package-manager/src/dependencies_graph_to_lockfile.rs, pacquet/crates/package-manager/src/dependencies_graph_to_lockfile/tests.rs
Adds optional_children: HashSet<String> to DependenciesGraphNode, tracks it in NodeRecord, propagates it through resolve_node, build_final_graph, and synthetic_peer_variant_node, uses it as the source of truth in optional_children_of for lockfile snapshot generation, and adds a regression test.
Workspace manifest writer: patchedDependencies support
pacquet/crates/workspace-manifest-writer/src/model.rs, pacquet/crates/workspace-manifest-writer/src/edit.rs, pacquet/crates/workspace-manifest-writer/src/lib.rs, pacquet/crates/workspace-manifest-writer/src/tests.rs
Parses patchedDependencies from pnpm-workspace.yaml into Manifest, adds TopLevelSpan.block_end for block removal, exposes set_patched_dependencies and write_or_remove_manifest, and adds comprehensive upsert/remove/idempotency/error-path tests.
Package-manager patch candidate selection and extraction
pacquet/crates/package-manager/src/lib.rs, pacquet/crates/package-manager/src/patch.rs, pacquet/crates/package-manager/src/patch/tests.rs
Adds PatchCandidate, PatchCandidateSet, PatchTarget structs; implements patch_candidates_from_lockfile, default_patch_target, and WritePackageForPatch::run (tarball download, git-hosted CAS rehydration, indexed-dir import); re-exports from the crate; includes unit and async extraction tests.
Package-manager diff and packlist filtering for patch-commit
pacquet/crates/package-manager/src/patch_commit.rs, pacquet/crates/package-manager/src/patch_commit/tests.rs
Implements prepare_pkg_files_for_diff (packlist-filtered hard-link copy into a PID-suffixed temp dir), diff_folders (git diff with output normalization and .DS_Store removal), PkgFilesForDiff enum, PatchCommitFs abstraction, and associated unit tests including mock filesystem failure paths.
CLI edit-dir state persistence (patch_state)
pacquet/crates/cli/src/cli_args/patch_state.rs, pacquet/crates/cli/src/cli_args/patch_state/tests.rs
Defines EditDirState and StateFileError, implements read_edit_dir_state/write_edit_dir_state backed by .pnpm_patches/state.json with edit-dir key normalization/canonicalization (including fallback for missing paths), and a full test suite covering Unix-specific edge cases.
CLI patch subcommand (PatchArgs)
pacquet/crates/cli/src/cli_args/patch.rs, pacquet/crates/cli/src/cli_args/patch/tests.rs
Defines PatchArgs and PatchError; implements PatchArgs::run (edit-dir validation, lockfile candidate selection, WritePackageForPatch, state write, existing-patch application, success output); adds PatchPrompt trait with DialoguerPatchPrompt; and unit tests for selection, prompting, output rendering, and path sanitization.
CLI patch-commit subcommand (PatchCommitArgs)
pacquet/crates/cli/src/cli_args/patch_commit.rs, pacquet/crates/cli/src/cli_args/patch_commit/tests.rs, pacquet/crates/cli/src/cli_args/install.rs
Defines PatchCommitArgs and PatchCommitError; implements orchestration (manifest read, edit-state load, lockfile target resolution via patch_target_from_state, diff generation, conditional patch-file write, workspace manifest update); adds InstallArgs::for_patch_manifest_change() baseline constructor; and unit tests for target resolution, path normalization, and cleanup helpers.
CLI patch-remove subcommand (PatchRemoveArgs)
pacquet/crates/cli/src/cli_args/patch_remove.rs, pacquet/crates/cli/src/cli_args/patch_remove/tests.rs
Defines PatchRemoveArgs and PatchRemoveError; implements selection (args or interactive multi-select), PatchRemovalContext/PatchRemovalTarget path-safety checks (canonicalization, containment enforcement, no-directory-delete), file unlinking, empty-dir cleanup, and manifest update; includes extensive tests for traversal prevention and Unix symlink escape resistance.
CLI command enum, dispatch wiring, and Cargo dependency
pacquet/crates/cli/Cargo.toml, pacquet/crates/cli/src/cli_args.rs
Adds pacquet-patching workspace dep; adds Patch/PatchCommit/PatchRemove variants to CliCommand; refactors CliArgs::run into a single command_future match with boxed futures; wires post-commit/post-remove install runs via InstallArgs::for_patch_manifest_change; adds PatchCommit/PatchRemove to is_install_family.
CLI integration tests: patch lifecycle and reporter coverage
pacquet/crates/cli/tests/patch.rs, pacquet/crates/cli/tests/add.rs, pacquet/crates/cli/tests/approve_builds.rs, pacquet/crates/cli/tests/create.rs, pacquet/crates/cli/tests/dlx.rs, pacquet/crates/cli/tests/remove.rs, pacquet/crates/cli/tests/runtime.rs, pacquet/crates/cli/tests/test_command.rs, pacquet/crates/cli/tests/update.rs
Adds 1004-line patch lifecycle integration tests (patch/patch-commit/patch-remove failure modes, state correctness, reporter propagation, symlink escape resistance) and reporter-coverage tests for add, approve-builds, rebuild, create, dlx, remove, runtime, test, and update commands under ndjson and silent reporter flags.

Sequence Diagrams

sequenceDiagram
    participant User
    participant CliArgs_run
    participant PatchArgs_run
    participant patch_candidates_from_lockfile
    participant WritePackageForPatch
    participant write_edit_dir_state

    User->>CliArgs_run: pacquet patch [email protected]
    CliArgs_run->>PatchArgs_run: dir + state
    PatchArgs_run->>patch_candidates_from_lockfile: raw_dependency + lockfile
    patch_candidates_from_lockfile-->>PatchArgs_run: PatchCandidateSet
    PatchArgs_run->>WritePackageForPatch: PatchTarget + edit_dir
    WritePackageForPatch-->>PatchArgs_run: Ok(())
    PatchArgs_run->>write_edit_dir_state: EditDirState { patchedPkg, applyToAll }
    PatchArgs_run-->>User: print patch-commit instructions
Loading
sequenceDiagram
    participant User
    participant CliArgs_run
    participant PatchCommitArgs_run
    participant prepare_pkg_files_for_diff
    participant diff_folders
    participant set_patched_dependencies
    participant InstallArgs

    User->>CliArgs_run: pacquet patch-commit ./edit-dir
    CliArgs_run->>PatchCommitArgs_run: dir + state
    PatchCommitArgs_run->>prepare_pkg_files_for_diff: src (edit dir)
    prepare_pkg_files_for_diff-->>PatchCommitArgs_run: PkgFilesForDiff
    PatchCommitArgs_run->>diff_folders: original vs edited
    diff_folders-->>PatchCommitArgs_run: patch text
    PatchCommitArgs_run->>set_patched_dependencies: updated patchedDependencies
    PatchCommitArgs_run-->>CliArgs_run: Ok(true)
    CliArgs_run->>InstallArgs: for_patch_manifest_change().run()
    InstallArgs-->>User: reinstalled
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • pnpm/pnpm#11752: Both PRs modify WorkspaceSettings::from_pnpm_config_env to parse PATCHES_DIR/pnpm_config_patches_dir environment variables in the config env-overlay layer.
  • pnpm/pnpm#11906: Both PRs modify pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs inside the peer-resolution pipeline—main PR adds optional-child tracking in resolve_node, while retrieved PR restructures resolve_node with caching logic—so the changes are related at the same core function level.
  • pnpm/pnpm#12093: Both PRs modify the CLI dispatch logic in pacquet/crates/cli/src/cli_args.rs—main PR refactors CliArgs::run command dispatch to add patch subcommands, while retrieved PR adjusts the command dispatch to honor --recursive—so they overlap at the same function/dispatch level.

Suggested reviewers

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

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

❤️ Share

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

@spencer17x
spencer17x marked this pull request as ready for review June 23, 2026 12:29
@spencer17x
spencer17x requested a review from zkochan as a code owner June 23, 2026 12:29
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add pacquet patch workflow commands (patch, patch-commit, patch-remove)
✨ Enhancement 🐞 Bug fix 🧪 Tests ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

Description

• Add pacquet patch, patch-commit, and patch-remove commands with pnpm-aligned behavior.
• Support patchesDir config and safe patchedDependencies edits in pnpm-workspace.yaml.
• Preserve optional-dependency lockfile edges after patch removal; add broad regression coverage.
Diagram

graph TD
  A["pacquet CLI"] --> B["patch commands"] --> C["package-manager patch"] --> D[("pnpm-lock.yaml")]
  B --> E["edit-dir state"]
  B --> F["patch files"]
  B --> G["workspace manifest"]
  G --> B
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Pure-Rust diff generator (no external `git` dependency)
  • ➕ Avoids runtime reliance on a git binary in PATH
  • ➕ More predictable behavior in constrained CI/containers
  • ➖ Hard to exactly match pnpm’s patch format/flags and edge cases
  • ➖ Adds sizable new surface area to maintain (diff normalization, filtering, etc.)
2. Store edit-dir state inside the edit directory (instead of `.pnpm_patches/state.json`)
  • ➕ State becomes self-contained and moves with the edit dir
  • ➕ Reduces coupling to modules_dir layout
  • ➖ Diverges from pnpm-compatible state behavior and tooling expectations
  • ➖ Harder to manage multiple concurrent edit dirs consistently
3. Avoid `pnpm-workspace.yaml` edits; store all patch mapping in lockfile only
  • ➕ Single write target; no YAML patching/format preservation needed
  • ➕ Fewer workspace-manifest edge cases
  • ➖ Breaks pnpm-compatible workflow (patchedDependencies is user-facing config)
  • ➖ Harder for users to inspect/edit patch mapping without lockfile knowledge

Recommendation: The PR’s approach is the best fit for pnpm compatibility: keep patchedDependencies in pnpm-workspace.yaml, track edit-dir state under .pnpm_patches/state.json, and use git diff --no-index with output normalization to match pnpm’s patch format. If git availability becomes a recurring constraint, consider adding an optional pure-Rust diff fallback in a follow-up.

Files changed (42) +5204 / -145

Enhancement (12) +2093 / -115
cli_args.rsRegister patch commands and refactor async dispatch +203/-91

Register patch commands and refactor async dispatch

• Adds 'patch', 'patch-commit', and 'patch-remove' subcommands and refactors command execution to return a boxed future for consistent async handling. Ensures patch-commit/patch-remove trigger a targeted reinstall when they modify patch metadata.

pacquet/crates/cli/src/cli_args.rs

install.rsAdd install preset for patch-related manifest changes +30/-0

Add install preset for patch-related manifest changes

• Introduces 'InstallArgs::for_patch_manifest_change()' used after patch-commit/patch-remove to refresh installs in a controlled way.

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

patch.rsImplement 'pacquet patch' workflow command +315/-0

Implement 'pacquet patch' workflow command

• Implements lockfile-based target selection (with interactive prompt fallback), extracts the target package into an edit directory, records edit-dir state, optionally applies an existing patch file, and prints pnpm-style success guidance (with optional colors).

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

patch_commit.rsImplement 'pacquet patch-commit' workflow command +278/-0

Implement 'pacquet patch-commit' workflow command

• Validates patch dir via edit-dir state, rebuilds a clean source copy, diffs (packlist/files-aware), writes the patch file under '--patches-dir'/'patchesDir', and updates 'pnpm-workspace.yaml' 'patchedDependencies'. Returns whether a manifest change occurred so the CLI can conditionally reinstall.

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

patch_remove.rsImplement 'pacquet patch-remove' with safety checks and cleanup +338/-0

Implement 'pacquet patch-remove' with safety checks and cleanup

• Implements patch removal by args or interactive selection, validates patch paths remain inside the configured patches directory (including realpath/symlink checks), deletes patch files, prunes empty directories, and updates 'patchedDependencies' in the workspace manifest.

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

patch_state.rsAdd edit-dir patch state file support +139/-0

Add edit-dir patch state file support

• Adds read/write support for '.pnpm_patches/state.json', keyed by normalized/canonical edit-dir paths, with structured diagnostics for filesystem and serialization failures.

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

lib.rsExpose patch-related modules from package-manager +4/-0

Expose patch-related modules from package-manager

• Registers and re-exports new 'patch' and 'patch_commit' modules for consumption by the CLI layer.

pacquet/crates/package-manager/src/lib.rs

patch.rsAdd patch target selection and package extraction helpers +319/-0

Add patch target selection and package extraction helpers

• Implements lockfile-based patch candidates (including semver-range filtering), default target selection, and package extraction to an edit directory. Supports registry/tarball resolutions (including git-hosted tarball fetch path) and rejects unsupported resolution kinds with pnpm-aligned diagnostics.

pacquet/crates/package-manager/src/patch.rs

patch_commit.rsAdd packlist-aware diff generation for patch-commit +283/-0

Add packlist-aware diff generation for patch-commit

• Implements packlist/files-field filtering into a temporary directory when needed, runs 'git diff --no-index', normalizes output to strip absolute paths, and filters '.DS_Store' diff blocks.

pacquet/crates/package-manager/src/patch_commit.rs

edit.rsAdd YAML patching support for 'patchedDependencies' +120/-18

Add YAML patching support for 'patchedDependencies'

• Adds 'patchedDependencies' upsert/remove logic with minimal text churn, including removal of omitted keys and full block deletion when empty. Refactors shared upsert logic to support multiple top-level blocks safely.

pacquet/crates/workspace-manifest-writer/src/edit.rs

lib.rsAdd 'set_patched_dependencies' and delete empty workspace manifests +58/-6

Add 'set_patched_dependencies' and delete empty workspace manifests

• Introduces 'set_patched_dependencies()' to update 'pnpm-workspace.yaml' while preserving formatting, and adds write-or-remove behavior to avoid leaving empty workspace manifest files behind.

pacquet/crates/workspace-manifest-writer/src/lib.rs

model.rsExtend workspace manifest model for patchedDependencies +6/-0

Extend workspace manifest model for patchedDependencies

• Adds model support to parse/track 'patchedDependencies' needed by the writer and edit operations.

pacquet/crates/workspace-manifest-writer/src/model.rs

Bug fix (2) +32 / -1
dependencies_graph_to_lockfile.rsPreserve optional child edges when generating snapshots +1/-1

Preserve optional child edges when generating snapshots

• Seeds optional-child detection from resolver-provided optional edges so optionality survives lockfile reuse and patch removal scenarios where synthetic manifests may omit 'optionalDependencies'.

pacquet/crates/package-manager/src/dependencies_graph_to_lockfile.rs

resolve_peers.rsPropagate optional child edges from resolved tree into graph nodes +31/-0

Propagate optional child edges from resolved tree into graph nodes

• Captures optional child aliases during peer resolution, persists them into the dependency graph, and merges optional-children sets when consolidating nodes. This enables correct optional dependency handling downstream in lockfile generation.

pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs

Refactor (1) +6 / -0
dependencies_graph.rsTrack optional child aliases on dependency graph nodes +6/-0

Track optional child aliases on dependency graph nodes

• Adds 'optional_children' to 'DependenciesGraphNode' so optional edges can be preserved even when lockfile snapshot reuse produces synthetic manifests without 'optionalDependencies'.

pacquet/crates/resolving-deps-resolver/src/dependencies_graph.rs

Other (27) +3073 / -29
Cargo.tomlAdd CLI dependency for applying existing patches +1/-0

Add CLI dependency for applying existing patches

• Adds 'pacquet-patching' to the CLI crate so 'pacquet patch' can apply existing patch files from 'patchedDependencies'.

pacquet/crates/cli/Cargo.toml

tests.rsUnit tests for 'patch' selection and output rendering +213/-0

Unit tests for 'patch' selection and output rendering

• Adds tests for default vs prompted selection, git-hosted tarball bare spec handling, cancellation behavior, edit-dir validation, and colored/plain success output.

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

tests.rsUnit tests for patch-commit targeting and path normalization +142/-0

Unit tests for patch-commit targeting and path normalization

• Covers fallback target selection when state is stale, 'patchesDir' normalization, and cleanup behavior for temporary directories.

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

tests.rsUnit tests for patch-remove selection and path safety +345/-0

Unit tests for patch-remove selection and path safety

• Adds coverage for prompting behavior, cancellation, traversal/out-of-project rejection, and symlink-escape scenarios (Unix).

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

tests.rsUnit tests for patch state read/write semantics +180/-0

Unit tests for patch state read/write semantics

• Covers missing-file behavior, malformed JSON, canonicalization/normalization rules, relative path handling via cwd, and expected failure modes.

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

add.rsRun 'add' integration coverage under ndjson/silent reporters +19/-0

Run 'add' integration coverage under ndjson/silent reporters

• Adds an integration test ensuring 'pacquet add' succeeds and persists manifest changes under '--reporter=ndjson' and '--reporter=silent'.

pacquet/crates/cli/tests/add.rs

approve_builds.rsRun approve-builds/rebuild integration coverage under ndjson/silent +33/-0

Run approve-builds/rebuild integration coverage under ndjson/silent

• Extends integration tests to ensure build approval and rebuild flows work under non-default reporters.

pacquet/crates/cli/tests/approve_builds.rs

create.rsValidate create error-path behavior across reporters +23/-16

Validate create error-path behavior across reporters

• Updates the missing-args test to assert pnpm-compatible error reporting under default, ndjson, and silent reporters.

pacquet/crates/cli/tests/create.rs

dlx.rsValidate dlx error-path behavior across reporters +17/-10

Validate dlx error-path behavior across reporters

• Updates the missing-command test to assert consistent diagnostics under default, ndjson, and silent reporters.

pacquet/crates/cli/tests/dlx.rs

patch.rsAdd end-to-end tests for patch/commit/remove workflows +920/-0

Add end-to-end tests for patch/commit/remove workflows

• Adds comprehensive integration coverage for patch selection, edit-dir state, patch file reuse, custom patch directories, patch removal validation/cleanup, workspace-project behavior, traversal/symlink rejection, and reinstall paths.

pacquet/crates/cli/tests/patch.rs

remove.rsRun 'remove' integration coverage under ndjson/silent reporters +20/-0

Run 'remove' integration coverage under ndjson/silent reporters

• Adds an integration test ensuring 'pacquet remove' works correctly under alternate reporters and updates the manifest as expected.

pacquet/crates/cli/tests/remove.rs

runtime.rsAdjust runtime-related integration coverage for updated CLI dispatch +23/-0

Adjust runtime-related integration coverage for updated CLI dispatch

• Updates runtime-related tests to align with the refactored CLI async dispatch/reporter handling introduced alongside patch commands.

pacquet/crates/cli/tests/runtime.rs

test_command.rsAdjust test-command integration coverage for updated CLI dispatch +26/-0

Adjust test-command integration coverage for updated CLI dispatch

• Updates test-command integration coverage to match the new command dispatch structure used by the CLI.

pacquet/crates/cli/tests/test_command.rs

update.rsRun 'update' integration coverage under ndjson/silent reporters +20/-0

Run 'update' integration coverage under ndjson/silent reporters

• Extends update-related integration tests to ensure successful execution under alternate reporters.

pacquet/crates/cli/tests/update.rs

env_overlay.rsAdd 'PATCHES_DIR' env overlay mapping +1/-0

Add 'PATCHES_DIR' env overlay mapping

• Adds support for 'PNPM_CONFIG_PATCHES_DIR' so 'patchesDir' can be configured via environment overlay.

pacquet/crates/config/src/env_overlay.rs

lib.rsAdd 'patches_dir' to config model +5/-0

Add 'patches_dir' to config model

• Extends 'Config' with 'patches_dir' (raw 'patchesDir') used by patch-commit to choose the patch output directory.

pacquet/crates/config/src/lib.rs

tests.rsAdd test for env-provided patchesDir +28/-0

Add test for env-provided patchesDir

• Adds a regression test asserting 'PNPM_CONFIG_PATCHES_DIR' populates 'Config.patches_dir'.

pacquet/crates/config/src/tests.rs

workspace_yaml.rsParse/apply 'patchesDir' from pnpm-workspace.yaml +6/-0

Parse/apply 'patchesDir' from pnpm-workspace.yaml

• Adds 'patches_dir' to workspace settings, includes string substitution support, and propagates it into runtime config when present.

pacquet/crates/config/src/workspace_yaml.rs

tests.rsExtend workspace yaml tests for patchesDir +11/-0

Extend workspace yaml tests for patchesDir

• Adds coverage ensuring 'patchesDir' is parsed and applied correctly.

pacquet/crates/config/src/workspace_yaml/tests.rs

tests.rsRegression test for optional child edge preservation +102/-2

Regression test for optional child edge preservation

• Adds a test building a resolved tree with an optional edge and asserts the lockfile snapshot keeps the child optional (and not rewritten as a regular dependency).

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

tests.rsUpdate package-manager config test fixture for patchesDir field +1/-0

Update package-manager config test fixture for patchesDir field

• Extends test config construction to include the new 'patches_dir' field.

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

tests.rsUnit tests for patch candidate selection behavior +474/-0

Unit tests for patch candidate selection behavior

• Covers exact/range/bare-name selection, error hints for missing versions, apply-to-all defaulting, and handling of unsupported resolution kinds.

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

tests.rsUnit tests for diff normalization and filtered temp dir creation +240/-0

Unit tests for diff normalization and filtered temp dir creation

• Verifies absolute-path stripping, '.DS_Store' filtering, files-field filtering, and error propagation from filesystem operations.

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

tests.rsUpdate resolver tests for new optional-children field +1/-0

Update resolver tests for new optional-children field

• Adjusts resolver test fixtures to initialize/expect the new optional-children tracking on graph nodes.

pacquet/crates/resolving-deps-resolver/src/dedupe_injected_deps/tests.rs

tests.rsUpdate resolver tests for new optional-children field +1/-0

Update resolver tests for new optional-children field

• Adjusts peer-dedupe resolver test fixtures to account for the new optional-children tracking on graph nodes.

pacquet/crates/resolving-deps-resolver/src/dedupe_peer_dependents/tests.rs

tests.rsExtend peer resolution tests for optional edge propagation +9/-0

Extend peer resolution tests for optional edge propagation

• Adds/updates tests to ensure optional-child metadata is preserved through peer resolution and merging paths.

pacquet/crates/resolving-deps-resolver/src/resolve_peers/tests.rs

tests.rsAdd format-sensitive tests for patchedDependencies edits/removals +212/-1

Add format-sensitive tests for patchedDependencies edits/removals

• Adds extensive tests validating block creation, quoting behavior, no-op updates, omitted-entry removal, and file removal when the manifest becomes empty.

pacquet/crates/workspace-manifest-writer/src/tests.rs

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Ambiguous patch target rebuild ✓ Resolved 🐞 Bug ≡ Correctness
Description
PatchCommitArgs reconstructs the PatchTarget by selecting the first lockfile candidate whose
version matches the edited directory’s package.json, but pacquet patch state persists only
patchedPkg/applyToAll, not the selected package_key/git_tarball_url. If multiple lockfile
candidates share the same version (e.g., different resolutions), patch-commit can diff against the
wrong source and write a patch entry for the wrong installed candidate.
Code

pacquet/crates/cli/src/cli_args/patch_commit.rs[R248-277]

+fn patch_target_from_state(
+    raw_dependency: &str,
+    name: &str,
+    version: &str,
+    apply_to_all: bool,
+    current_lockfile: &Lockfile,
+) -> Result<PatchTarget, PatchCommitError> {
+    let fallback = format!("{name}@{version}");
+    let set = patch_candidates_from_lockfile(raw_dependency, current_lockfile)
+        .or_else(|_| patch_candidates_from_lockfile(&fallback, current_lockfile))
+        .map_err(PatchCommitError::PatchTarget)?;
+    let candidate = set
+        .preferred_versions
+        .iter()
+        .chain(set.versions.iter())
+        .find(|candidate| candidate.version == version)
+        .ok_or_else(|| {
+            PatchCommitError::PatchTarget(PatchTargetError::VersionNotFound {
+                requested: fallback.clone(),
+                hint: format!("did you forget to install {fallback}?"),
+            })
+        })?;
+    Ok(PatchTarget {
+        alias: name.to_string(),
+        version: version.to_string(),
+        bare_specifier: candidate.git_tarball_url.clone().unwrap_or_else(|| version.to_string()),
+        apply_to_all,
+        git_tarball_url: candidate.git_tarball_url.clone(),
+        package_key: candidate.package_key.clone(),
+    })
Evidence
The state file written by pacquet patch contains only patched_pkg and apply_to_all, so
patch-commit cannot disambiguate which lockfile candidate was selected. patch-commit then
searches candidates and picks the first one whose candidate.version == version, which is ambiguous
when multiple candidates share a version but differ by resolution/package key.

pacquet/crates/cli/src/cli_args/patch.rs[176-180]
pacquet/crates/cli/src/cli_args/patch_state.rs[16-22]
pacquet/crates/cli/src/cli_args/patch_commit.rs[248-277]

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

## Issue description
`patch-commit` cannot reliably identify which lockfile entry was patched because the edit-dir state does not persist a unique identifier for the chosen candidate; it reselects by `version` only.
### Issue Context
`pacquet patch` may prompt the user to select among multiple candidates (including git-hosted tarballs). The chosen candidate’s `package_key` (and potentially `git_tarball_url` / `bare_specifier`) must be persisted to make `patch-commit` deterministic.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch_state.rs[16-22]
- pacquet/crates/cli/src/cli_args/patch.rs[176-180]
- pacquet/crates/cli/src/cli_args/patch_commit.rs[248-277]
### Implementation notes
- Extend `EditDirState` to include enough data to uniquely identify the target (preferred: serialized `package_key`, plus `git_tarball_url`/`bare_specifier` as needed).
- When writing state in `patch`, persist the selected `PatchTarget` identity.
- In `patch-commit`, resolve the target using the persisted identity (not just matching `version`).

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


2. State atomic write fails 🐞 Bug ☼ Reliability
Description
Both write_state_file_atomically() and write_patch_file_atomically() publish updates by renaming
a temp file over an existing destination without a replace-existing strategy, which can fail on
platforms where rename cannot overwrite. This can break repeat workflows like successive `pacquet
patch runs (updating state.json) and re-running pacquet patch-commit` for the same deterministic
patch filename.
Code

pacquet/crates/cli/src/cli_args/patch_state.rs[R184-214]

+fn write_state_file_atomically(target: &Path, content: &[u8]) -> io::Result<()> {
+    const MAX_TEMP_ATTEMPTS: usize = 16;
+
+    static COUNTER: AtomicU64 = AtomicU64::new(0);
+    let pid = std::process::id();
+    let parent = target.parent().unwrap_or_else(|| Path::new("."));
+    let file_name = target
+        .file_name()
+        .map_or_else(|| String::from("state.json"), |name| name.to_string_lossy().into_owned());
+
+    let mut last_already_exists = None;
+    for _ in 0..MAX_TEMP_ATTEMPTS {
+        let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
+        let tmp = parent.join(format!(".{file_name}.{pid}.{counter}.pacquet-tmp"));
+        let mut file = match OpenOptions::new().write(true).create_new(true).open(&tmp) {
+            Ok(file) => file,
+            Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {
+                last_already_exists = Some(source);
+                continue;
+            }
+            Err(source) => return Err(source),
+        };
+        if let Err(source) = file.write_all(content) {
+            drop(file);
+            let _ = fs::remove_file(&tmp);
+            return Err(source);
+        }
+        drop(file);
+        return fs::rename(&tmp, target).inspect_err(|_| {
+            let _ = fs::remove_file(&tmp);
+        });
Evidence
The cited implementations construct a temporary file and then “publish” it with `fs::rename(tmp,
target) without any handling for the common case where target` already exists (no replace, no
remove-then-rename fallback, and no equivalent overwrite-safe mechanism). This is problematic
because state.json is explicitly meant to be rewritten as the state map is updated over time, and
patch filenames are deterministic per patch_key, making it likely that the destination patch file
already exists during re-commit; thus, on platforms where rename cannot overwrite an existing
destination, these operations can fail and interrupt the intended repeated-update workflows.

pacquet/crates/cli/src/cli_args/patch_state.rs[184-215]
pacquet/crates/cli/src/cli_args/patch_commit.rs[372-405]
pacquet/crates/workspace-manifest-writer/src/lib.rs[229-245]

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 atomic writers for both the patch state (`state.json`) and patch files use a temp-file + `fs::rename(tmp, target)` publish step but do not guarantee that an existing destination file can be replaced, which can cause failures when updating files that already exist (a normal scenario for both state updates and deterministic patch filenames).
## Issue Context
`state.json` is expected to be updated over time as the workflow reads/modifies state (e.g., via `read_state_file_for_write` + `insert`), so overwriting is the common path rather than an edge case. Patch file paths are deterministic per `patch_key`, so repeated `pacquet patch-commit` calls commonly target the same filename and should be able to update/replace the existing patch file reliably; there is also an existing overwrite-safe approach in the workspace manifest writer that can be reused or factored into a shared helper.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch_state.rs[184-215]
- pacquet/crates/cli/src/cli_args/patch_commit.rs[372-405]
- pacquet/crates/workspace-manifest-writer/src/lib.rs[229-245]

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


3. Diff tempfile permission leak ✓ Resolved 🐞 Bug ⛨ Security
Description
diff_folders() captures git diff output into temp files under std::env::temp_dir() using
default creation permissions, which can make patch contents readable by other local users on
multi-user systems (umask-dependent). This can leak sensitive code changes (including secrets) while
pacquet patch-commit runs.
Code

pacquet/crates/package-manager/src/patch_commit.rs[R208-226]

+    fn new(stream: &'static str) -> Result<Self, PatchCommitError> {
+        static COUNTER: AtomicU64 = AtomicU64::new(0);
+        let pid = std::process::id();
+        let temp_dir = std::env::temp_dir();
+        for _ in 0..16 {
+            let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
+            let path = temp_dir.join(format!("pacquet-git-diff-{stream}-{pid}-{counter}.tmp"));
+            match OpenOptions::new().write(true).create_new(true).open(&path) {
+                Ok(writer) => return Ok(Self { path, writer }),
+                Err(source) if source.kind() == io::ErrorKind::AlreadyExists => {}
+                Err(source) => return Err(PatchCommitError::DiffSpawn { source }),
+            }
+        }
+        Err(PatchCommitError::DiffSpawn {
+            source: io::Error::new(
+                io::ErrorKind::AlreadyExists,
+                "exhausted temp-path attempts for git diff output",
+            ),
+        })
Evidence
diff_folders() routes git diff stdout/stderr to DiffTempFile handles, and DiffTempFile::new
creates those files in the system temp dir with OpenOptions::create_new(true) but without setting
restrictive permissions, so readability is governed by defaults/umask.

pacquet/crates/package-manager/src/patch_commit.rs[142-166]
pacquet/crates/package-manager/src/patch_commit.rs[201-226]

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

## Issue description
`pacquet patch-commit` writes `git diff` stdout/stderr into temp files created in the OS temp directory with default permissions. On Unix, this can produce world/group-readable files depending on umask, leaking patch contents to other local users.
### Issue Context
The temp files are used as `git` stdout/stderr sinks and then read back into memory; the data can include sensitive source code changes.
### Fix Focus Areas
- pacquet/crates/package-manager/src/patch_commit.rs[142-176]
- pacquet/crates/package-manager/src/patch_commit.rs[201-270]
### Suggested fix
- When creating `DiffTempFile`, set restrictive permissions on Unix (e.g. `0o600`) via `std::os::unix::fs::OpenOptionsExt::mode(0o600)`.
- Prefer using a secure tempfile API (e.g. `tempfile::Builder`) that creates owner-only files and randomizes names, while still allowing size checks (you can keep the current size-limit logic by `metadata().len()` on the tempfile path).
- Ensure the cleanup behavior remains best-effort (current `Drop` is fine).

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


View more (8)
4. Unsafe temp dir delete ✓ Resolved 🐞 Bug ⛨ Security
Description
prepare_pkg_files_for_diff_with_fs() deletes the deterministic temp directory (`<src
parent>/<name>_tmp_<pid>) using remove_dir_all` without checking whether it is a symlink/junction,
which can behave unsafely/inconsistently across platforms and may delete outside the edit dir. This
is reachable during patch-commit and can cause unintended filesystem deletion in untrusted
workspaces.
Code

pacquet/crates/package-manager/src/patch_commit.rs[R165-195]

+fn remove_existing_temp_dir_with_fs(
+    temp_dir: &Path,
+    fs_ops: &impl PatchCommitFs,
+) -> Result<(), PatchCommitError> {
+    match fs_ops.remove_dir_all(temp_dir) {
+        Ok(()) => Ok(()),
+        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(()),
+        Err(source) => Err(PatchCommitError::RemoveTempDir { dir: temp_dir.to_path_buf(), source }),
+    }
+}
+
+trait PatchCommitFs {
+    fn create_dir_all(&self, path: &Path) -> io::Result<()>;
+    fn hard_link(&self, source: &Path, target: &Path) -> io::Result<()>;
+    fn remove_dir_all(&self, path: &Path) -> io::Result<()>;
+}
+
+struct RealPatchCommitFs;
+
+impl PatchCommitFs for RealPatchCommitFs {
+    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
+        fs::create_dir_all(path)
+    }
+
+    fn hard_link(&self, source: &Path, target: &Path) -> io::Result<()> {
+        fs::hard_link(source, target)
+    }
+
+    fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
+        fs::remove_dir_all(path)
+    }
Evidence
The new code deletes the temp directory via remove_dir_all and the in-repo security guidance
explicitly warns that remove_dir_all is the wrong primitive for directory links/junctions, making
this cleanup step unsafe when the temp path is attacker-prepared as a link.

pacquet/crates/package-manager/src/patch_commit.rs[165-205]
pacquet/crates/env-installer/src/install_config_deps.rs[476-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
`remove_existing_temp_dir_with_fs()` uses `remove_dir_all` on a deterministic temp path adjacent to the patch/edit directory, without verifying the path isn’t a symlink/junction. The repo itself documents that `remove_dir_all` is the wrong primitive for links and behaves inconsistently across platforms, so this cleanup step can become a dangerous delete when the temp path is pre-planted as a link.
### Issue Context
This runs as part of patch generation (`prepare_pkg_files_for_diff_with_fs`) before creating the filtered temp directory.
### Fix Focus Areas
- pacquet/crates/package-manager/src/patch_commit.rs[165-205]
### Implementation notes
- Before removing, `symlink_metadata(temp_dir)` and if `file_type().is_symlink()` (and on Windows: junction-like behavior if applicable in your fs helpers), avoid `remove_dir_all`.
- Prefer using an existing symlink-aware removal helper (e.g. `pacquet_fs::remove_symlink_dir`) or refuse and error when the temp dir path is a link.
- Consider switching to a truly-random temp dir name under a controlled directory (not adjacent to `src`) to reduce predictability/pre-planting risk.

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


5. Non-file patch path allowed 🐞 Bug ⛨ Security
Description
checked_existing_patch_file_path() rejects directories but does not require the patch path to be a
regular file, so special files (e.g. FIFOs) under patchesDir can pass validation.
apply_patch_to_dir() then reads the patch via fs::read, which can block indefinitely or consume
unbounded data, causing a local DoS when running pacquet patch in an untrusted workspace.
Code

pacquet/crates/cli/src/cli_args/patch.rs[R441-473]

+fn checked_existing_patch_file_path(
+    lockfile_dir: &Path,
+    patches_dir_setting: &str,
+    patch_file: &str,
+) -> Result<PathBuf, PatchError> {
+    let ctx = ExistingPatchFileContext::new(lockfile_dir, patches_dir_setting)?;
+    let target_path = resolve_patch_path(&ctx.project_root, Path::new(patch_file));
+    if target_path == ctx.patches_dir || !is_subdir(&ctx.patches_dir, &target_path) {
+        return Err(PatchError::PatchFileOutsidePatchesDir { patch_file: patch_file.to_string() });
+    }
+
+    let parent_dir = target_path.parent().map_or_else(PathBuf::new, Path::to_path_buf);
+    let target_stats = lstat_patch_if_exists(&target_path)?;
+    let real_parent_dir = realpath_if_exists(&parent_dir);
+    let real_patches_dir = ctx.real_patches_dir.or_else(|| realpath_if_exists(&ctx.patches_dir));
+    if let (Some(real_parent_dir), Some(real_patches_dir)) = (&real_parent_dir, &real_patches_dir)
+        && !is_subdir(real_patches_dir, real_parent_dir)
+    {
+        return Err(PatchError::PatchFileOutsidePatchesDir { patch_file: patch_file.to_string() });
+    }
+    if target_stats.as_ref().is_some_and(fs::Metadata::is_dir) {
+        return Err(PatchError::PatchFileIsDirectory { patch_file: patch_file.to_string() });
+    }
+    if target_stats.as_ref().is_some_and(|stats| stats.file_type().is_symlink())
+        && real_patches_dir.as_ref().is_some_and(|real_patches_dir| {
+            dunce::canonicalize(&target_path)
+                .ok()
+                .is_none_or(|real_target| !is_subdir(real_patches_dir, &real_target))
+        })
+    {
+        return Err(PatchError::PatchFileOutsidePatchesDir { patch_file: patch_file.to_string() });
+    }
+    Ok(target_path)
Evidence
The path-checking code only rejects directories (and some symlink escapes), then
apply_patch_to_dir() reads the patch bytes with fs::read, which is unsafe for special file types
that can block or produce unbounded streams.

pacquet/crates/cli/src/cli_args/patch.rs[387-474]
pacquet/crates/patching/src/apply.rs[93-113]

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

## Issue description
`pacquet patch` validates that the configured patch path is not a directory and does some symlink escape checks, but it does not enforce that the patch is a regular file. Downstream, `apply_patch_to_dir()` reads the entire patch with `fs::read`, which can block on FIFOs or read unbounded data from special files.
### Issue Context
This is reachable via `patchedDependencies` entries in workspace config. In a malicious/untrusted repo, a patch entry can point at a special file under `patchesDir` and hang `pacquet patch`.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch.rs[441-474]
- pacquet/crates/patching/src/apply.rs[93-113]
### Suggested fix
- In `checked_existing_patch_file_path()`, if `target_stats` exists:
- Reject anything that is neither a regular file nor an allowed symlink-to-regular-file.
- If symlinks are allowed, canonicalize and then `metadata()` the resolved target and require it be a regular file.
- Consider also enforcing a reasonable maximum patch file size before reading to reduce memory DoS.

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


6. Symlinked state file write ✓ Resolved 🐞 Bug ⛨ Security
Description
write_edit_dir_state writes modules_dir/.pnpm_patches/state.json using create_dir_all +
fs::write without validating that .pnpm_patches (or the final file) isn’t a symlink, so an
attacker-controlled workspace can redirect the write outside the repo. Running pacquet patch in
such a workspace can overwrite/truncate an arbitrary file path reachable via that symlink with the
victim’s privileges.
Code

pacquet/crates/cli/src/cli_args/patch_state.rs[R93-96]

+    let state_dir = path.parent().expect("state file has parent");
+    fs::create_dir_all(state_dir)
+        .map_err(|source| StateFileError::Write { path: state_dir.to_path_buf(), source })?;
+    fs::write(&path, text).map_err(|source| StateFileError::Write { path, source })
Evidence
The new patch workflow writes state under modules_dir/.pnpm_patches/state.json using APIs that
follow symlinks in path components. Because the workspace and node_modules tree are
attacker-controlled per the repo’s security model, a pre-planted symlink at
node_modules/.pnpm_patches can redirect this write outside the project when pacquet patch runs.

pacquet/crates/cli/src/cli_args/patch_state.rs[82-97]
pacquet/crates/cli/src/cli_args/patch.rs[126-149]

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

## Issue description
`write_edit_dir_state()` writes `modules_dir/.pnpm_patches/state.json` via `fs::create_dir_all()` and `fs::write()`. If `.pnpm_patches/` (or `state.json`) is a symlink, these calls can be redirected outside the intended tree, enabling arbitrary file overwrite in an attacker-controlled workspace.
## Issue Context
This state write is invoked by `pacquet patch` after extraction, so it triggers in normal use.
## Fix Focus Areas
- Add symlink/realpath validation for `modules_dir/.pnpm_patches` before creating/writing.
- Avoid `fs::write` on a potentially-symlinked destination; use temp-file + rename (rename replaces the dirent rather than following a symlink).
- Ensure the *real* state dir stays within the *real* modules dir (canonicalize both and enforce `is_subdir`).
### Suggested implementation outline
1. Compute `state_dir = modules_dir.join(STATE_DIR)` and `state_path = state_dir.join(STATE_FILE)`.
2. If `state_dir` exists and `symlink_metadata(state_dir).file_type().is_symlink()` => error.
3. Create `state_dir` (prefer `create_dir` for a single component if possible).
4. Canonicalize `modules_dir` and `state_dir` and enforce `is_subdir(real_modules_dir, real_state_dir)`.
5. Write `state.json` atomically with `NamedTempFile::new_in(real_state_dir)` + `persist(state_path)` (or similar), and if `state_path` exists and is a symlink, reject.
## Fix Focus Areas (code references)
- pacquet/crates/cli/src/cli_args/patch_state.rs[82-97]
- pacquet/crates/cli/src/cli_args/patch.rs[126-149]

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


7. Patch dir symlink escape 🐞 Bug ⛨ Security
Description
The new patch workflow extracts a dependency into an edit directory and import_indexed_dir
creates/writes that destination with fs::create_dir_all, which follows symlinks in parent
components. If an attacker-controlled workspace pre-plants modules_dir/.pnpm_patches as a symlink
to an external location, pacquet patch can be coerced into writing the extracted package tree
outside the repo (arbitrary file writes).
Code

pacquet/crates/package-manager/src/patch.rs[R248-254]

+        import_indexed_dir::<Reporter>(
+            &AtomicU8::new(0),
+            PackageImportMethod::CloneOrCopy,
+            dest,
+            &cas_paths,
+            ImportIndexedDirOpts { force: true, keep_modules_dir: false },
+        )
Evidence
The CLI constructs the default edit directory under modules_dir/.pnpm_patches/... and passes it as
dest into WritePackageForPatch, which calls import_indexed_dir. import_indexed_dir uses
fs::create_dir_all(dest), which follows symlinks in parent components; therefore a symlinked
.pnpm_patches can redirect the extraction writes outside the intended directory tree.

pacquet/crates/cli/src/cli_args/patch.rs[126-140]
pacquet/crates/cli/src/cli_args/patch.rs[262-264]
pacquet/crates/package-manager/src/patch.rs[248-255]
pacquet/crates/package-manager/src/import_indexed_dir.rs[205-215]

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

## Issue description
`WritePackageForPatch` ultimately calls `import_indexed_dir(..., dest, ...)`, which does `fs::create_dir_all(dest)` and then materializes many files under it. The CLI’s default `dest` is under `modules_dir/.pnpm_patches/...`, but the patch workflow does not validate that `.pnpm_patches` is not a symlink (or that the real destination remains under the real `modules_dir`). This allows a malicious workspace to redirect extraction writes outside the project.
## Issue Context
Per REVIEW_GUIDE.md, workspace paths and `node_modules` contents must be treated as attacker-controlled. A repo can pre-create `node_modules/.pnpm_patches` as a symlink to an arbitrary writable location; `create_dir_all` and subsequent file writes will follow it.
## Fix Focus Areas
- In the CLI patch command, before invoking `WritePackageForPatch`, ensure the chosen `edit_dir` is safe:
- If using the default edit dir (under `modules_dir/.pnpm_patches`), reject when `.pnpm_patches` exists and is a symlink.
- After creation, canonicalize `modules_dir` and the `.pnpm_patches` directory and enforce `is_subdir` on real paths.
- Consider adding a reusable “safe destination dir” helper for patch workflows (similar to the `PatchFileWriteContext` checks used for `patch-commit`).
## Fix Focus Areas (code references)
- pacquet/crates/cli/src/cli_args/patch.rs[126-140]
- pacquet/crates/cli/src/cli_args/patch.rs[262-264]
- pacquet/crates/package-manager/src/patch.rs[248-255]

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


8. Patch reads arbitrary file ✓ Resolved 🐞 Bug ⛨ Security
Description
apply_existing_patch_file resolves a patchedDependencies entry to a filesystem path without
enforcing that it stays under the project/patches directory, then calls apply_patch_to_dir, which
reads the entire file. A malicious workspace can point this to an arbitrary absolute path or special
file, causing unintended local file reads and potential DoS (e.g., reading an unbounded device) when
a user runs pacquet patch.
Code

pacquet/crates/cli/src/cli_args/patch.rs[R272-292]

+fn apply_existing_patch_file(
+    config: &pacquet_config::Config,
+    target: &PatchTarget,
+    edit_dir: &Path,
+) -> Result<(), PatchError> {
+    let Some(patched_dependencies) = &config.patched_dependencies else { return Ok(()) };
+    let exact_key = format!("{}@{}", target.alias, target.bare_specifier);
+    let patch_file = patched_dependencies
+        .get(&exact_key)
+        .or_else(|| target.apply_to_all.then(|| patched_dependencies.get(&target.alias)).flatten());
+    let Some(patch_file) = patch_file else { return Ok(()) };
+    let base_dir = config
+        .workspace_dir
+        .as_deref()
+        .unwrap_or_else(|| config.modules_dir.parent().unwrap_or_else(|| Path::new(".")));
+    let patch_file_path = resolve_path(base_dir, Path::new(patch_file));
+    if !patch_file_path.exists() {
+        return Err(PatchError::PatchFileNotFound { patch_file_path });
+    }
+    pacquet_patching::apply_patch_to_dir(edit_dir, &patch_file_path)
+        .map_err(PatchError::ApplyExistingPatch)
Evidence
The patch path is taken from patchedDependencies and resolved without any “must be under
patchesDir/workspace” validation, and the downstream patch applier reads the entire referenced file
into memory.

pacquet/crates/cli/src/cli_args/patch.rs[272-293]
pacquet/crates/patching/src/apply.rs[93-129]

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

## Issue description
`pacquet patch` replays an existing patch from `config.patched_dependencies`, but it currently resolves the patch path and reads it without constraining it to a safe root (workspace/patchesDir). This enables arbitrary local file reads and can trigger denial-of-service if the path points to special files.
### Issue Context
- `apply_existing_patch_file` uses a simple join/absolute passthrough to produce `patch_file_path`.
- `pacquet_patching::apply_patch_to_dir` reads the patch file via `fs::read`, so the entire file is loaded into memory.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch.rs[272-293]
### What to change
- Resolve the patch path relative to **configured** `patches_dir` (or default `patches`) under the workspace root, not just `base_dir`.
- Reject:
- absolute paths
- paths containing `..` after normalization
- paths that canonicalize outside the allowed root
- non-regular files (symlink/device/FIFO) if possible via metadata checks
- Consider adding a size cap before reading (`metadata.len()`), and surface a clear error if exceeded.
- Reuse/centralize the same “patch path safety” logic already implemented for `patch-remove` to keep behavior consistent.

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


9. Symlink-follow patch file write ✓ Resolved 🐞 Bug ⛨ Security
Description
PatchCommitArgs::run creates the patches directory and writes the patch output with fs::write,
which follows symlinks and does not constrain the real path of patches_dir. In an untrusted
workspace, a symlinked patches/ directory or a pre-planted symlink at the target patch filename
can redirect the write outside the repo and overwrite arbitrary files when running `pacquet
patch-commit`.
Code

pacquet/crates/cli/src/cli_args/patch_commit.rs[R152-171]

+        let workspace_dir = state.config.workspace_dir.clone().unwrap_or_else(|| dir.to_path_buf());
+        let patches_dir_name = normalize_patches_dir_name(
+            self.patches_dir
+                .as_deref()
+                .or(state.config.patches_dir.as_deref())
+                .unwrap_or("patches"),
+        );
+        let patches_dir = workspace_dir.join(path_from_forward_slash(&patches_dir_name));
+        fs::create_dir_all(&patches_dir).map_err(|source| PatchCommitError::CreatePatchesDir {
+            path: patches_dir.clone(),
+            source,
+        })?;
+
+        let patch_key =
+            if state_value.apply_to_all { name.clone() } else { format!("{name}@{version}") };
+        let patch_file_name = format!("{}.patch", patch_key.replace('/', "__"));
+        let patch_file_path = patches_dir.join(&patch_file_name);
+        fs::write(&patch_file_path, patch_content).map_err(|source| {
+            PatchCommitError::WritePatch { path: patch_file_path.clone(), source }
+        })?;
Evidence
patch-commit writes with fs::write to a computed path under patches_dir without any realpath
containment or symlink-safe atomic write; elsewhere in the repo, atomic rename is explicitly used to
avoid following symlinks.

pacquet/crates/cli/src/cli_args/patch_commit.rs[152-171]
pacquet/crates/workspace-manifest-writer/src/lib.rs[229-245]
pacquet/crates/cli/src/cli_args/patch_remove.rs[176-193]

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

## Issue description
`pacquet patch-commit` writes the generated patch file via `fs::write` into a directory created with `create_dir_all`, without symlink/realpath containment checks. This is vulnerable to symlink redirection (both via the `patches` directory itself and via the final patch file path), enabling writes outside the workspace.
### Issue Context
There is already a safe pattern in the repo: write to a sibling temp file and `rename`/`persist` over the destination (atomic + does not follow destination symlinks).
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch_commit.rs[152-171]
### What to change
- Before writing, validate `patches_dir`:
- compute canonical (if exists) and ensure it is a subdir of `workspace_dir` canonical
- reject if `patches_dir` is (or resolves through) a symlink that escapes the workspace
- Replace `fs::write(&patch_file_path, patch_content)` with an atomic temp-file + rename approach (mirroring `workspace-manifest-writer`’s `write_atomic`), so that an existing symlink at `patch_file_path` is replaced rather than followed.
- Optionally, perform an `lstat` check: if `patch_file_path` exists and is a symlink, reject or ensure the atomic-rename path will replace it safely.
- Add a regression test: pre-create `patches/<expected>.patch` as a symlink to an outside target and assert `patch-commit` does not overwrite the target.

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


10. patch-commit uses eprintln! ✓ Resolved 📎 Requirement gap ◔ Observability
Description
patch-commit and patch emit user-visible messages directly to stderr/stdout via eprintln! and
print!, bypassing pacquet’s reporter pipeline and undermining reporter parity. This can corrupt
the NDJSON reporter stream (stderr) and prevents these messages from being represented as structured
reporter log events consistently across reporter modes.
Code

pacquet/crates/cli/src/cli_args/patch_commit.rs[R246-252]

+fn remove_dir_if_exists(path: &Path) {
+    match fs::remove_dir_all(path) {
+        Ok(()) => {}
+        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+        Err(error) => {
+            eprintln!("Failed to clean up temporary directory at {}: {error}", path.display());
+        }
Evidence
Rule 2 requires reporter parity and consistent reporting output across modes. The eprintln! added
in remove_dir_if_exists() writes plain text directly to stderr, which is also where
NdjsonReporter emits NDJSON records, so interleaving unstructured text can break NDJSON consumers
and cannot be captured as a structured reporter event. Separately, the print_success() path in
patch writes directly to stdout via print! instead of going through pacquet_reporter, meaning
reporter modes (including NDJSON and silent) cannot uniformly capture, format, or represent this
output as structured events, violating parity expectations.

Backfill missing log events in already-ported code (pacquet reporter parity)
pacquet/crates/cli/src/cli_args/patch_commit.rs[246-252]
pacquet/crates/cli/src/cli_args/patch.rs[295-297]

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

## Issue description
`patch-commit` and `patch` currently print messages directly to stderr/stdout (`eprintln!` and `print!`), which bypasses pacquet’s reporter event pipeline; in NDJSON mode this can interleave plain text into the NDJSON stream (stderr) and in all modes it prevents these messages from being emitted as structured reporter events for consistent reporter parity.
## Issue Context
The compliance requirement (Rule 2) targets reporter parity so NDJSON and default reporter output remain consistent and machine-consumable, and so user-visible messaging is captured/formatted uniformly across reporter modes (including NDJSON and silent). Direct printing should be replaced by reporter events (or otherwise gated by reporter mode) to avoid corrupting NDJSON output and to preserve consistent structured reporting.
## Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch_commit.rs[246-252]
- pacquet/crates/cli/src/cli_args/patch.rs[295-297]

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


11. Patch-commit path traversal ✓ Resolved 🐞 Bug ⛨ Security
Description
prepare_pkg_files_for_diff joins packlist paths onto src/temp_dir and hard-links them without
rejecting absolute paths or .. components, so a crafted packlist entry can escape the patch dir
and link/read/write outside it during patch generation. Because packlist force-includes main/bin
via unchecked pkg_dir.join(...), a malicious dependency can trigger this when a user runs `pacquet
patch-commit`.
Code

pacquet/crates/package-manager/src/patch_commit.rs[R111-124]

+    for file in files {
+        let source_path = src.join(path_from_forward_slash(&file));
+        let target = temp_dir.join(path_from_forward_slash(&file));
+        let parent =
+            target.parent().expect("filtered package file target should have a parent directory");
+        fs_ops.create_dir_all(parent).map_err(|source| PatchCommitError::CreateTempDir {
+            dir: parent.to_path_buf(),
+            source,
+        })?;
+        fs_ops.hard_link(&source_path, &target).map_err(|source| PatchCommitError::LinkFile {
+            source_path,
+            target,
+            source,
+        })?;
Evidence
The new patch-commit implementation hard-links paths derived from packlist without validating the
relative paths. Packlist explicitly joins main/bin values onto pkg_dir and accepts them if
they exist, without rejecting .. traversal, so those fields can feed unsafe paths into
patch-commit.

pacquet/crates/package-manager/src/patch_commit.rs[93-126]
pacquet/crates/git-fetcher/src/packlist.rs[219-242]
pacquet/crates/git-fetcher/src/cas_io.rs[37-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
`prepare_pkg_files_for_diff_with_fs` hard-links files using `src.join(path_from_forward_slash(file))` and `temp_dir.join(...)` without validating that `file` is a safe relative path. This enables path traversal (e.g. `../...`) to escape both `src` and `temp_dir`, potentially linking arbitrary host files into the temp tree (or even creating link targets outside the temp dir).
### Issue Context
Packlist can include paths derived from `package.json` fields (notably `main`/`bin`) and currently checks them with `pkg_dir.join(...).is_file()` without rejecting `..` components, so a malicious package can cause `packlist()` to emit traversal paths.
### Fix Focus Areas
- pacquet/crates/package-manager/src/patch_commit.rs[93-126]
### Suggested fix
1. Replace `path_from_forward_slash` + `PathBuf::join` usage with a safe-join helper that rejects:
- absolute paths
- `Component::ParentDir`, `Component::RootDir`, `Component::Prefix(_)`
- (optionally) empty components
2. Ensure both `source_path` stays under `src` and `target` stays under `temp_dir` after joining.
3. Consider reusing the existing “join_checked” pattern used elsewhere in the repo (same component validation logic).
4. Add a regression test that a `main` or `bin` field containing `../outside` is rejected before any filesystem writes occur.

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



Remediation recommended

12. Diff normalization memory amplification 🐞 Bug ➹ Performance
Description
patch-commit buffers git diff output into memory and then creates additional full-size String
buffers during normalization/filtering, which can significantly increase peak RSS for large diffs
(up to the 128MB cap) and potentially terminate the process under constrained memory.
Code

pacquet/crates/package-manager/src/patch_commit.rs[R144-177]

+pub fn diff_folders(folder_a: &Path, folder_b: &Path) -> Result<String, PatchCommitError> {
+    let folder_a_slash = slash_path(folder_a);
+    let folder_b_slash = slash_path(folder_b);
+    let stdout = DiffTempFile::new("stdout")?;
+    let stderr = DiffTempFile::new("stderr")?;
+    let status = Command::new("git")
+        .arg("-c")
+        .arg("core.safecrlf=false")
+        .arg("diff")
+        .arg("--src-prefix=a/")
+        .arg("--dst-prefix=b/")
+        .arg("--ignore-cr-at-eol")
+        .arg("--irreversible-delete")
+        .arg("--full-index")
+        .arg("--no-index")
+        .arg("--text")
+        .arg("--no-ext-diff")
+        .arg("--no-color")
+        .arg("--")
+        .arg(&folder_a_slash)
+        .arg(&folder_b_slash)
+        .env("GIT_CONFIG_NOSYSTEM", "1")
+        .env("GIT_CONFIG_GLOBAL", "/dev/null")
+        .stdout(stdout.writer.try_clone().map_err(|source| PatchCommitError::DiffSpawn { source })?)
+        .stderr(stderr.writer.try_clone().map_err(|source| PatchCommitError::DiffSpawn { source })?)
+        .status()
+        .map_err(|source| PatchCommitError::DiffSpawn { source })?;
+
+    let stderr = stderr.read_to_string("stderr")?;
+    if !stderr.is_empty() || !matches!(status.code(), Some(0 | 1)) {
+        return Err(PatchCommitError::DiffFailed { stderr });
+    }
+    let stdout = stdout.read_to_string("stdout")?;
+    Ok(normalize_diff_output(&stdout, &folder_a_slash, &folder_b_slash))
Evidence
The code reads git diff output into a String and then runs a normalization pipeline that
constructs additional strings proportional to the diff size, increasing peak memory usage on large
diffs.

pacquet/crates/package-manager/src/patch_commit.rs[144-178]
pacquet/crates/package-manager/src/patch_commit.rs[345-396]

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

## Issue description
`diff_folders()` reads the full git diff output into a `String`, then `normalize_diff_output()` builds another `String` with `with_capacity(diff.len())`, and finally `remove_ds_store_diff_blocks()` builds additional `String` buffers (`kept` and `current`). For near-limit diffs this multiplies peak memory usage (multiple large in-memory copies), which can cause `pacquet patch-commit` to OOM or become very slow under memory pressure.
### Issue Context
This is on the `patch-commit` path, not the install hot path, but users can generate large diffs (and the code explicitly supports diffs up to `MAX_DIFF_OUTPUT_BYTES`). Reducing transient allocations improves robustness.
### Fix Focus Areas
- pacquet/crates/package-manager/src/patch_commit.rs[144-178]
- pacquet/crates/package-manager/src/patch_commit.rs[345-407]
### Suggested direction
- Avoid producing multiple full-size `String` copies:
- Integrate the `.DS_Store` block filtering into `normalize_diff_output()` so you build only one output buffer.
- When possible, normalize path header lines in-place or write to the output buffer without allocating via repeated whole-string rewrites.
- Consider an early fast-path: if the diff contains no `.DS_Store` headers and no folder prefixes to strip, return `stdout` (or a lightly adjusted version) without rebuilding a second full buffer.
- Keep behavior identical (same normalization results), just reduce transient allocations.

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


13. Unbounded patch file read 🐞 Bug ⛨ Security
Description
pacquet patch auto-applies an existing patch file and passes it to apply_patch_to_dir, which
loads the entire patch via fs::read without any size limit. In an untrusted workspace, a very
large patch file under patchesDir can reliably cause memory exhaustion / termination when a user
runs pacquet patch.
Code

pacquet/crates/cli/src/cli_args/patch.rs[R410-435]

+fn apply_existing_patch_file(
+    config: &pacquet_config::Config,
+    target: &PatchTarget,
+    edit_dir: &Path,
+) -> Result<(), PatchError> {
+    let Some(patched_dependencies) = &config.patched_dependencies else { return Ok(()) };
+    let exact_key = format!("{}@{}", target.alias, target.bare_specifier);
+    let patch_file = patched_dependencies
+        .get(&exact_key)
+        .or_else(|| target.apply_to_all.then(|| patched_dependencies.get(&target.alias)).flatten());
+    let Some(patch_file) = patch_file else { return Ok(()) };
+    let base_dir = config
+        .workspace_dir
+        .as_deref()
+        .unwrap_or_else(|| config.modules_dir.parent().unwrap_or_else(|| Path::new(".")));
+    let patch_file_path = checked_existing_patch_file_path(
+        base_dir,
+        config.patches_dir.as_deref().unwrap_or("patches"),
+        patch_file,
+    )?;
+    if !patch_file_path.exists() {
+        return Err(PatchError::PatchFileNotFound { patch_file_path });
+    }
+    pacquet_patching::apply_patch_to_dir(edit_dir, &patch_file_path)
+        .map_err(PatchError::ApplyExistingPatch)
+}
Evidence
The new patch command always attempts to apply an existing patch file (unless --ignore-existing)
by calling apply_patch_to_dir. That function currently reads the patch file in full via
fs::read, so a huge patch file will be fully buffered in memory before parsing/applying.

pacquet/crates/cli/src/cli_args/patch.rs[410-435]
pacquet/crates/patching/src/apply.rs[93-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
`pacquet patch` can be forced to read an arbitrarily large patch file into memory when applying an existing `patchedDependencies` entry. This is a local DoS vector (OOM / kill) in untrusted workspaces.
### Issue Context
- New CLI behavior calls `pacquet_patching::apply_patch_to_dir` on an existing patch file.
- `apply_patch_to_dir` reads the full file into memory (`fs::read`) with no size cap.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch.rs[410-435]
- pacquet/crates/patching/src/apply.rs[93-131]
### Implementation notes
- Add a maximum patch file size (consider reusing the existing 128MiB constant style used elsewhere, or a smaller default like 16–32MiB).
- Enforce the limit before reading (e.g., `fs::metadata(patch_file_path)?.len()`), and return a dedicated error variant so callers can surface a clear diagnostic.
- Prefer implementing the size limit inside `pacquet_patching::apply_patch_to_dir` so *all* patch-application call sites benefit (not just `pacquet patch`).

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


14. Absolute patchesDir rewritten ✓ Resolved 🐞 Bug ≡ Correctness
Description
normalize_patches_dir_name() drops RootDir/Prefix components, so an absolute --patches-dir
(or config patchesDir) like /tmp/patches is silently transformed into a project-relative path
like tmp/patches. This makes patch files be written/read from an unintended location and defeats
the intended “outside project” guard for absolute inputs.
Code

pacquet/crates/cli/src/cli_args/patch_commit.rs[R423-437]

+fn normalize_patches_dir_name(input: &str) -> String {
+    let mut parts = Vec::new();
+    for component in Path::new(input).components() {
+        match component {
+            Component::CurDir => {}
+            Component::ParentDir => {
+                if !parts.is_empty() {
+                    parts.pop();
+                }
+            }
+            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
+            Component::RootDir | Component::Prefix(_) => {}
+        }
+    }
+    if parts.is_empty() { ".".to_string() } else { parts.join("/") }
Evidence
normalize_patches_dir_name explicitly ignores root/prefix components, which transforms absolute
paths into relative ones. The same “drop RootDir/Prefix” strategy also appears in patch path-join
helpers used by patch apply/remove, so the behavior is systemic across the new workflow.

pacquet/crates/cli/src/cli_args/patch_commit.rs[423-438]
pacquet/crates/cli/src/cli_args/patch_commit.rs[348-363]
pacquet/crates/cli/src/cli_args/patch.rs[506-517]
pacquet/crates/cli/src/cli_args/patch_remove.rs[255-266]

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

## Issue description
Absolute `patchesDir` inputs are currently sanitized by stripping root/prefix components, which changes their meaning instead of rejecting them as outside the project. This can cause patch files to be written/read in unexpected places.
### Issue Context
- `PatchCommitArgs::run` normalizes the patches-dir name before joining it onto `workspace_dir`.
- The normalization explicitly ignores `Component::RootDir` and `Component::Prefix(_)`, turning absolute paths into relative ones.
- Similar join helpers exist in other patch workflow commands.
### Fix Focus Areas
- pacquet/crates/cli/src/cli_args/patch_commit.rs[195-215]
- pacquet/crates/cli/src/cli_args/patch_commit.rs[423-438]
- pacquet/crates/cli/src/cli_args/patch_commit.rs[348-363]
- pacquet/crates/cli/src/cli_args/patch.rs[506-517]
- pacquet/crates/cli/src/cli_args/patch_remove.rs[255-266]
### Implementation notes
- In `patch-commit`, detect absolute `patchesDir` early (e.g., if `Path::new(input).is_absolute()` or contains `RootDir/Prefix`) and return `PatchesDirOutsideProject` (or a dedicated “absolute not allowed” diagnostic).
- Remove the root/prefix stripping behavior from `normalize_patches_dir_name` (or make it return a `Result` and error on absolute paths).
- Align `join_setting_path` helpers so they *preserve* absolute paths for validation (so `is_subdir(project_root, patches_dir)` correctly fails) rather than rewriting them.

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


Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 845ec80

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 11

🧹 Nitpick comments (3)
pacquet/crates/workspace-manifest-writer/src/model.rs (1)

28-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Keep patched-dependency selectors and patch-file references branded.

The new manifest model collapses the name[@Version] selector and patch-file reference into plain Strings, which then leaks into the public setter surface and makes key/value swaps type-correct. Introduce small wrapper types at this boundary and apply the same validation discipline as upstream.

As per coding guidelines, "pacquet/**/*.rs: Declare a newtype wrapper for branded string types rather than collapsing into plain String or &str."

Also applies to: 42-43

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

In `@pacquet/crates/workspace-manifest-writer/src/model.rs` around lines 28 - 29,
The patched_dependencies field uses plain String types for both the selector
keys and patch-file reference values, which lacks type safety and violates the
coding guidelines that require newtype wrappers for branded string types. Create
newtype wrapper types for the patched-dependency selector (the name[`@version`]
part) and the patch-file reference, then replace the IndexMap<String, String> in
the patched_dependencies field with the appropriate wrapped types using these
newtype wrappers as keys and values. Apply the same newtype wrapper approach to
the other occurrences mentioned at lines 42-43 to maintain consistency across
the manifest model.

Source: Coding guidelines

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

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

Replace wildcard super import with explicit symbols

Please switch to explicit imports to keep test dependencies clear and aligned with repository conventions.

♻️ Suggested fix
-use super::*;
+use super::{
+    PkgFilesForDiff, cleanup_after_diff, normalize_patches_dir_name, patch_target_from_state,
+    path_from_forward_slash, remove_dir_if_exists,
+};

As per coding guidelines, “No star imports inside module bodies. Write use super::{Foo, bar} instead of use super::*; for modules you control.” As per path instructions (pacquet/CODE_STYLE_GUIDE.md), “No star imports inside module bodies.”

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

In `@pacquet/crates/cli/src/cli_args/patch_commit/tests.rs` at line 1, Replace the
wildcard import statement `use super::*;` at the beginning of the tests.rs file
with explicit imports of only the symbols that are actually used within the test
module. Identify which items from the parent module are referenced in the tests
and list them explicitly in the use statement instead of using the wildcard
pattern to maintain clarity of dependencies and align with the repository's
coding guidelines.

Sources: Coding guidelines, Path instructions

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

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

Replace wildcard super import with explicit symbols

Use explicit imports here to comply with pacquet test/module style and keep symbol usage auditable.

As per coding guidelines, “No star imports inside module bodies. Write use super::{Foo, bar} instead of use super::*; for modules you control.” As per path instructions (pacquet/CODE_STYLE_GUIDE.md), “No star imports inside module bodies.”

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

In `@pacquet/crates/cli/src/cli_args/patch_remove/tests.rs` at line 1, The
wildcard import statement `use super::*;` in the test file violates the code
style guidelines. Replace this wildcard import with explicit imports by
identifying all the symbols actually used in the tests.rs file and replace the
`use super::*;` statement with `use super::{Symbol1, Symbol2, ...};` listing
only the specific symbols needed from the parent module. This ensures all symbol
usage remains auditable and complies with the pacquet CODE_STYLE_GUIDE.md
requirements.

Sources: Coding guidelines, Path instructions

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

Inline comments:
In `@pacquet/crates/cli/src/cli_args/patch_commit.rs`:
- Around line 124-145: The current code only calls cleanup_after_diff after both
prepare_pkg_files_for_diff and diff_folders succeed. If either operation fails
and returns an error via map_err, the cleanup is skipped and temporary
directories are left behind. Restructure the code to ensure cleanup_after_diff
is called on all paths, including error paths. This can be achieved by
extracting the operations that can fail, capturing any errors that occur,
performing cleanup unconditionally with the cleanup_after_diff function, and
then propagating the errors if they occurred. This ensures temporary directories
in clean_dir are always cleaned up regardless of whether diff preparation or the
diff operation succeeds or fails.

In `@pacquet/crates/cli/src/cli_args/patch_remove/tests.rs`:
- Around line 79-81: The test contains an early return that silently skips
execution when stdin is not a terminal, which hides potential failures in
non-interactive environments. Replace this silent skip with an explicit
precondition check that fails fast using assert! or panic! if stdin is not a
terminal, or alternatively refactor the code to remove the environment
dependency by introducing a test seam that allows mocking the terminal state
check in std::io::stdin().is_terminal().

In `@pacquet/crates/cli/src/cli_args/patch_state/tests.rs`:
- Line 1: Replace the glob import `use super::*;` at the beginning of the tests
module with explicit symbol imports. Identify all the symbols from the parent
module that are actually used within the test module, and create an explicit use
statement like `use super::{SymbolName1, SymbolName2};` instead. This makes it
clear which symbols are being imported and follows the pacquet Rust style
guidelines that prohibit star imports in module bodies.

In `@pacquet/crates/cli/src/cli_args/patch.rs`:
- Around line 93-97: The validation logic is checking the edit_dir filesystem
constraints before validating that package_name is provided. Reorder the
validations so that the package_name.ok_or(PatchError::MissingPackageName) check
occurs before the if let Some(edit_dir) block that calls resolve_path and
reject_non_empty_custom_edit_dir. This ensures that missing required inputs are
reported consistently, with package_name validation happening first before any
filesystem operations are attempted.

In `@pacquet/crates/cli/src/cli_args/patch/tests.rs`:
- Line 1: Replace the glob import `use super::*;` at the top of the tests module
with an explicit import list. Identify which items from the parent module are
actually used in the test code (such as structs, functions, or types referenced
in the test functions), and write `use super::{Item1, Item2, ...};` with only
those explicitly needed items instead of the wildcard import.
- Around line 64-67: The functions
select_patch_target_uses_dialoguer_when_no_default_target and the test at lines
74-76 silently return early when stdin is a terminal, which hides the fact that
the test did not actually execute and can mask regressions. Replace the silent
return statement with an explicit test skip macro (such as panic! with a
descriptive message or a proper skip! macro if available in your test framework)
to make it clear that the test environment is not set up correctly. This ensures
that test failures are visible rather than silently ignored.

In `@pacquet/crates/package-manager/src/patch_commit.rs`:
- Around line 243-250: The normalize_diff_output function is performing global
string replacements on the entire diff content, which can unintentionally modify
file content within the diff hunks when the replacement patterns match. Restrict
the path normalization to only the diff header/metadata lines (such as lines
starting with "---", "+++", "@@", and "diff" markers) instead of replacing
patterns globally across the entire diff. Split the diff into lines, apply the
normalization logic only to header lines, and reconstruct the diff with
unchanged file content hunks.

In `@pacquet/crates/package-manager/src/patch.rs`:
- Around line 216-218: The condition at line 216 checking git_hosted ==
Some(true) to gate GitHostedTarballFetcher is too restrictive and inconsistent
with the URL inference logic applied in lines 259-265, which already treats
codeload and pkg.pr.new URLs as git-hosted. Update the condition at line 216 to
include the same URL pattern checking logic used in lines 259-265, so that
tarball URLs with git hosting patterns are properly handled for extraction even
when the explicit git_hosted flag is not set.

In `@pacquet/crates/package-manager/src/patch/tests.rs`:
- Line 1: The glob import `use super::*;` at the beginning of the tests.rs file
violates pacquet's import conventions as specified in the CODE_STYLE_GUIDE.
Replace this with explicit imports of only the items that are actually used from
the parent module. Review the test code in this file to identify all symbols
imported from the parent scope and replace the glob import with explicit
individual imports of those specific items.

In `@pacquet/crates/workspace-manifest-writer/src/edit.rs`:
- Around line 715-723: When calculating block_end_idx to determine what to
delete when removing a top-level block like patchedDependencies, the current
logic skips non-structural lines and captures everything up to the next
structural element, which causes blank lines and comments that follow the block
to also be deleted. To fix this, adjust the logic to identify the actual end of
the block content (the last non-blank, non-comment line of that block) and then
preserve any trailing blank lines and comments that come after it, so successor
comments like the catalog section's prelude are not lost when the block is
removed.
- Around line 70-77: The condition checking whether to remove the
patchedDependencies block only handles the case where
manifest.patched_dependencies is None, but fails to handle the case where it
already exists but is empty. Modify the condition in the if statement that
checks manifest.patched_dependencies.is_none() to also check if the existing
patched_dependencies map is empty, so that stale empty patchedDependencies
blocks are properly removed from the manifest when the incoming
patched_dependencies map is empty. This ensures that both None and empty maps
result in block removal and cleanup.

---

Nitpick comments:
In `@pacquet/crates/cli/src/cli_args/patch_commit/tests.rs`:
- Line 1: Replace the wildcard import statement `use super::*;` at the beginning
of the tests.rs file with explicit imports of only the symbols that are actually
used within the test module. Identify which items from the parent module are
referenced in the tests and list them explicitly in the use statement instead of
using the wildcard pattern to maintain clarity of dependencies and align with
the repository's coding guidelines.

In `@pacquet/crates/cli/src/cli_args/patch_remove/tests.rs`:
- Line 1: The wildcard import statement `use super::*;` in the test file
violates the code style guidelines. Replace this wildcard import with explicit
imports by identifying all the symbols actually used in the tests.rs file and
replace the `use super::*;` statement with `use super::{Symbol1, Symbol2, ...};`
listing only the specific symbols needed from the parent module. This ensures
all symbol usage remains auditable and complies with the pacquet
CODE_STYLE_GUIDE.md requirements.

In `@pacquet/crates/workspace-manifest-writer/src/model.rs`:
- Around line 28-29: The patched_dependencies field uses plain String types for
both the selector keys and patch-file reference values, which lacks type safety
and violates the coding guidelines that require newtype wrappers for branded
string types. Create newtype wrapper types for the patched-dependency selector
(the name[`@version`] part) and the patch-file reference, then replace the
IndexMap<String, String> in the patched_dependencies field with the appropriate
wrapped types using these newtype wrappers as keys and values. Apply the same
newtype wrapper approach to the other occurrences mentioned at lines 42-43 to
maintain consistency across the manifest model.
🪄 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: 0730d779-1999-45e6-af00-e2a740aee59d

📥 Commits

Reviewing files that changed from the base of the PR and between ec7cf70 and 845ec80.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (42)
  • pacquet/crates/cli/Cargo.toml
  • pacquet/crates/cli/src/cli_args.rs
  • pacquet/crates/cli/src/cli_args/install.rs
  • pacquet/crates/cli/src/cli_args/patch.rs
  • pacquet/crates/cli/src/cli_args/patch/tests.rs
  • pacquet/crates/cli/src/cli_args/patch_commit.rs
  • pacquet/crates/cli/src/cli_args/patch_commit/tests.rs
  • pacquet/crates/cli/src/cli_args/patch_remove.rs
  • pacquet/crates/cli/src/cli_args/patch_remove/tests.rs
  • pacquet/crates/cli/src/cli_args/patch_state.rs
  • pacquet/crates/cli/src/cli_args/patch_state/tests.rs
  • pacquet/crates/cli/tests/add.rs
  • pacquet/crates/cli/tests/approve_builds.rs
  • pacquet/crates/cli/tests/create.rs
  • pacquet/crates/cli/tests/dlx.rs
  • pacquet/crates/cli/tests/patch.rs
  • pacquet/crates/cli/tests/remove.rs
  • pacquet/crates/cli/tests/runtime.rs
  • pacquet/crates/cli/tests/test_command.rs
  • pacquet/crates/cli/tests/update.rs
  • pacquet/crates/config/src/env_overlay.rs
  • pacquet/crates/config/src/lib.rs
  • pacquet/crates/config/src/tests.rs
  • pacquet/crates/config/src/workspace_yaml.rs
  • pacquet/crates/config/src/workspace_yaml/tests.rs
  • pacquet/crates/package-manager/src/dependencies_graph_to_lockfile.rs
  • pacquet/crates/package-manager/src/dependencies_graph_to_lockfile/tests.rs
  • pacquet/crates/package-manager/src/install_package_from_registry/tests.rs
  • pacquet/crates/package-manager/src/lib.rs
  • pacquet/crates/package-manager/src/patch.rs
  • pacquet/crates/package-manager/src/patch/tests.rs
  • pacquet/crates/package-manager/src/patch_commit.rs
  • pacquet/crates/package-manager/src/patch_commit/tests.rs
  • pacquet/crates/resolving-deps-resolver/src/dedupe_injected_deps/tests.rs
  • pacquet/crates/resolving-deps-resolver/src/dedupe_peer_dependents/tests.rs
  • pacquet/crates/resolving-deps-resolver/src/dependencies_graph.rs
  • pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs
  • pacquet/crates/resolving-deps-resolver/src/resolve_peers/tests.rs
  • pacquet/crates/workspace-manifest-writer/src/edit.rs
  • pacquet/crates/workspace-manifest-writer/src/lib.rs
  • pacquet/crates/workspace-manifest-writer/src/model.rs
  • pacquet/crates/workspace-manifest-writer/src/tests.rs

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

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

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.844 ± 0.180 4.605 5.072 1.70 ± 0.09
pacquet@main 4.749 ± 0.184 4.606 5.209 1.66 ± 0.09
pnpr@HEAD 2.857 ± 0.116 2.737 3.085 1.00 ± 0.06
pnpr@main 2.855 ± 0.116 2.769 3.078 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.84386498512,
      "stddev": 0.1801159634250337,
      "median": 4.90639931432,
      "user": 3.91348122,
      "system": 3.4719314799999994,
      "min": 4.605338563819999,
      "max": 5.07205690282,
      "times": [
        5.007821294819999,
        4.914481331819999,
        4.898317296819999,
        5.07205690282,
        4.649690361819999,
        4.605338563819999,
        4.65182695682,
        4.6654215388199995,
        5.00762542782,
        4.96607017582
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.7485944813200005,
      "stddev": 0.1843994248669637,
      "median": 4.68872068482,
      "user": 3.84284592,
      "system": 3.48265398,
      "min": 4.60551600982,
      "max": 5.20889151682,
      "times": [
        5.20889151682,
        4.60551600982,
        4.75617229482,
        4.91317441082,
        4.67545134282,
        4.612306289819999,
        4.63323487982,
        4.68074737282,
        4.7037566988199995,
        4.69669399682
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.8572372586200006,
      "stddev": 0.11616096990166727,
      "median": 2.8077358428199997,
      "user": 2.6707654199999995,
      "system": 2.99154648,
      "min": 2.7372306178200003,
      "max": 3.08457963282,
      "times": [
        2.80231900582,
        2.78521762082,
        2.7372306178200003,
        2.77860242682,
        3.08457963282,
        2.89045699782,
        3.03664246482,
        2.86247986582,
        2.81315267982,
        2.78169127382
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.85481021352,
      "stddev": 0.11640406115736134,
      "median": 2.81093229282,
      "user": 2.7116928200000006,
      "system": 2.9833508799999997,
      "min": 2.76926463782,
      "max": 3.07821263382,
      "times": [
        2.79328218782,
        2.77139013982,
        2.82858239782,
        3.07821263382,
        2.77362916082,
        2.78905121382,
        2.8358668428200002,
        2.76926463782,
        2.84911264782,
        3.05971027282
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 634.2 ± 14.9 611.2 657.9 1.00
pacquet@main 643.7 ± 74.3 608.3 853.4 1.01 ± 0.12
pnpr@HEAD 685.2 ± 44.7 657.3 808.2 1.08 ± 0.07
pnpr@main 691.4 ± 21.6 662.5 724.5 1.09 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6342055720800001,
      "stddev": 0.014904046398222586,
      "median": 0.6374179259800001,
      "user": 0.37711188,
      "system": 1.3180674199999998,
      "min": 0.6112208529800001,
      "max": 0.65791560798,
      "times": [
        0.61331377198,
        0.6392569599800001,
        0.6271774129800001,
        0.6388920979800001,
        0.6112208529800001,
        0.65791560798,
        0.6264250289800001,
        0.6501805259800001,
        0.63594375398,
        0.6417297079800001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.6436890008800001,
      "stddev": 0.07433201542483546,
      "median": 0.62111447498,
      "user": 0.37222817999999996,
      "system": 1.3138103199999998,
      "min": 0.6083497519800001,
      "max": 0.8534061689800001,
      "times": [
        0.62414030998,
        0.6083497519800001,
        0.6153928119800001,
        0.6414250319800001,
        0.6118569449800001,
        0.61992103598,
        0.6112214759800001,
        0.6223079139800001,
        0.62886856298,
        0.8534061689800001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6851887059800001,
      "stddev": 0.04468582948425904,
      "median": 0.6712068014800001,
      "user": 0.38990378,
      "system": 1.3426653199999996,
      "min": 0.6573103899800001,
      "max": 0.8081586209800001,
      "times": [
        0.6941001709800001,
        0.6573103899800001,
        0.67639059298,
        0.6630670279800001,
        0.66812651698,
        0.68439303898,
        0.67071379198,
        0.65792709798,
        0.8081586209800001,
        0.6716998109800001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.69144506118,
      "stddev": 0.021636002725739237,
      "median": 0.6847932644800001,
      "user": 0.39808978,
      "system": 1.3349900199999998,
      "min": 0.66247895298,
      "max": 0.7245015679800001,
      "times": [
        0.7156819469800001,
        0.6795126409800001,
        0.7173411469800001,
        0.6734141869800001,
        0.6809214939800001,
        0.6886650349800001,
        0.69970101498,
        0.66247895298,
        0.7245015679800001,
        0.67223262498
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.691 ± 0.042 4.618 4.749 1.51 ± 0.02
pacquet@main 4.670 ± 0.045 4.618 4.743 1.50 ± 0.03
pnpr@HEAD 3.105 ± 0.043 3.029 3.192 1.00
pnpr@main 3.259 ± 0.164 3.067 3.633 1.05 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.69108077862,
      "stddev": 0.041911601702744994,
      "median": 4.69769486612,
      "user": 3.7632375200000006,
      "system": 3.3806578199999997,
      "min": 4.61777393962,
      "max": 4.74923998862,
      "times": [
        4.74151287962,
        4.65938537462,
        4.63881160762,
        4.70955184362,
        4.61777393962,
        4.70000183462,
        4.74923998862,
        4.70930007362,
        4.68984234662,
        4.69538789762
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.67030218222,
      "stddev": 0.04505995619855229,
      "median": 4.67237513762,
      "user": 3.7258564200000004,
      "system": 3.37786792,
      "min": 4.61825662862,
      "max": 4.7431532906200005,
      "times": [
        4.61825662862,
        4.7431532906200005,
        4.71360922262,
        4.69970820962,
        4.69144507562,
        4.62098591062,
        4.63576505662,
        4.70251923062,
        4.62427399762,
        4.65330519962
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.1052385129199997,
      "stddev": 0.04311282930924551,
      "median": 3.10100305562,
      "user": 2.75906332,
      "system": 3.1276514199999994,
      "min": 3.02912417762,
      "max": 3.19186849562,
      "times": [
        3.07689387062,
        3.08451921062,
        3.13300921162,
        3.09096086062,
        3.11955329862,
        3.12974766662,
        3.02912417762,
        3.08566308662,
        3.19186849562,
        3.11104525062
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.25942839322,
      "stddev": 0.16371512206280953,
      "median": 3.21746800262,
      "user": 2.84413382,
      "system": 3.1941293199999996,
      "min": 3.06686897162,
      "max": 3.6329447096200003,
      "times": [
        3.1855423746200002,
        3.33878430862,
        3.16714392262,
        3.21377604962,
        3.22115995562,
        3.22887385562,
        3.41042877962,
        3.6329447096200003,
        3.12876100462,
        3.06686897162
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.321 ± 0.011 1.306 1.340 1.00
pacquet@main 1.347 ± 0.066 1.315 1.528 1.02 ± 0.05
pnpr@HEAD 1.420 ± 0.080 1.371 1.641 1.08 ± 0.06
pnpr@main 1.423 ± 0.056 1.369 1.546 1.08 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.3208064503000003,
      "stddev": 0.010751367068635347,
      "median": 1.3180746608,
      "user": 1.30897986,
      "system": 1.6746592399999998,
      "min": 1.3062492748,
      "max": 1.3397633818,
      "times": [
        1.3268707748000002,
        1.3196019258,
        1.3127748988,
        1.3397633818,
        1.3321144358,
        1.3287327118,
        1.3163249488000002,
        1.3090847548000002,
        1.3165473958,
        1.3062492748
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3471657922,
      "stddev": 0.065758247542314,
      "median": 1.3217762248,
      "user": 1.29355806,
      "system": 1.6724213399999996,
      "min": 1.3153613308,
      "max": 1.5284331048000002,
      "times": [
        1.3153613308,
        1.5284331048000002,
        1.3352632178000001,
        1.3185200638,
        1.3706572318,
        1.3202526818,
        1.3232307278000002,
        1.3219696158,
        1.3215828338,
        1.3163871138
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.4199301842000003,
      "stddev": 0.07992595927292698,
      "median": 1.3944374523,
      "user": 0.60286716,
      "system": 1.5252379399999998,
      "min": 1.3709345768,
      "max": 1.6414745508000002,
      "times": [
        1.4330181258,
        1.3986379178000001,
        1.6414745508000002,
        1.4050194788,
        1.3901144168000001,
        1.3902369868000002,
        1.4112301878000002,
        1.3709345768,
        1.3823905408000001,
        1.3762450598
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.4234076152,
      "stddev": 0.05555189469225387,
      "median": 1.4062000468,
      "user": 0.56837946,
      "system": 1.58017714,
      "min": 1.3688048108000002,
      "max": 1.5457492918,
      "times": [
        1.4987499098000001,
        1.4163767638000002,
        1.3805045338000002,
        1.5457492918,
        1.4207341338000001,
        1.3688048108000002,
        1.4097234878,
        1.3897598318000002,
        1.4009967828,
        1.4026766058
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.984 ± 0.046 2.934 3.068 2.16 ± 0.04
pacquet@main 2.968 ± 0.042 2.907 3.074 2.15 ± 0.04
pnpr@HEAD 1.394 ± 0.025 1.369 1.439 1.01 ± 0.02
pnpr@main 1.383 ± 0.013 1.363 1.406 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.9836764386,
      "stddev": 0.045925629289568205,
      "median": 2.9661189188,
      "user": 1.7682644,
      "system": 1.9415396399999996,
      "min": 2.9338660158,
      "max": 3.0683503387999997,
      "times": [
        3.0683503387999997,
        2.9589355837999998,
        2.9794030688,
        2.9700854478,
        2.9582009387999997,
        2.9826171718,
        2.9621523898,
        2.9338660158,
        3.0656432388,
        2.9575101918
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.9676458549999998,
      "stddev": 0.042182166703226595,
      "median": 2.9609725373,
      "user": 1.718552,
      "system": 1.92517614,
      "min": 2.9068728478,
      "max": 3.0741908928,
      "times": [
        2.9663082517999997,
        2.9540287128,
        2.9635405508,
        2.9718689188,
        2.9470326638,
        2.9562423518,
        2.9779688358,
        2.9068728478,
        3.0741908928,
        2.9584045238
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.3941819587000002,
      "stddev": 0.02462462736743403,
      "median": 1.3838943093000002,
      "user": 0.5885028,
      "system": 1.56880074,
      "min": 1.3689568348,
      "max": 1.4392705518000002,
      "times": [
        1.4392705518000002,
        1.3752344318,
        1.3802787848,
        1.3726620408,
        1.3867563318000002,
        1.3810322868000002,
        1.3963828718,
        1.4290346898000001,
        1.3689568348,
        1.4122107628000002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.382501108,
      "stddev": 0.013362506044059079,
      "median": 1.3811751618,
      "user": 0.5701012,
      "system": 1.51606794,
      "min": 1.3626989408,
      "max": 1.4057185708000002,
      "times": [
        1.3939658978,
        1.3669196378000001,
        1.3947509368000002,
        1.4057185708000002,
        1.3626989408,
        1.3775285758000002,
        1.3874669708,
        1.3749798688000001,
        1.3848217478,
        1.3761599328
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12609
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,691.08 ms
(+3.33%)Baseline: 4,539.88 ms
5,447.86 ms
(86.11%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
2,983.68 ms
(-1.70%)Baseline: 3,035.15 ms
3,642.18 ms
(81.92%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,320.81 ms
(-1.67%)Baseline: 1,343.22 ms
1,611.86 ms
(81.94%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,843.86 ms
(+13.31%)Baseline: 4,275.01 ms
5,130.01 ms
(94.42%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
634.21 ms
(+1.65%)Baseline: 623.90 ms
748.67 ms
(84.71%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12609
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

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

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
3,105.24 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,394.18 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
1,419.93 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,857.24 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
685.19 ms
🐰 View full continuous benchmarking report in Bencher

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 93d3400

@codecov-commenter

codecov-commenter commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.35548% with 120 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.49%. Comparing base (ec7cf70) to head (88fc1cb).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
pacquet/crates/cli/src/cli_args/patch_commit.rs 82.39% 47 Missing ⚠️
pacquet/crates/cli/src/cli_args/patch.rs 89.04% 38 Missing ⚠️
pacquet/crates/package-manager/src/patch_commit.rs 92.77% 18 Missing ⚠️
pacquet/crates/package-manager/src/patch.rs 95.41% 11 Missing ⚠️
pacquet/crates/cli/src/cli_args/patch_state.rs 94.95% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12609      +/-   ##
==========================================
+ Coverage   88.12%   88.49%   +0.37%     
==========================================
  Files         329      335       +6     
  Lines       47045    48785    +1740     
==========================================
+ Hits        41459    43173    +1714     
- Misses       5586     5612      +26     

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

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 93d3400

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 374dbe6

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 374dbe6

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 93da093

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 93da093

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 53ec35e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 53ec35e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 33c835e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 33c835e

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1382c02

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1382c02

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

@zkochan
zkochan added this pull request to the merge queue Jun 24, 2026
Merged via the queue into pnpm:main with commit 003bb9a Jun 24, 2026
30 checks passed
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 state: automerge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants