Skip to content

fix(fs): junction fallback and link removal without symlink privilege on Windows - #13707

Merged
zkochan merged 3 commits into
mainfrom
fix-13694
Aug 7, 2026
Merged

zkochan merged 3 commits into
mainfrom
fix-13694

Conversation

@zkochan

@zkochan zkochan commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes two Windows failures in the Rust CLI reported in #13694 (Closes #13694):

  1. os error 1314 during install. The junction fallback in pacquet_fs::symlink_dir only matched io::ErrorKind::PermissionDenied, but Rust std maps ERROR_PRIVILEGE_NOT_HELD (1314) to Uncategorized. On a machine without Developer Mode or elevation, CreateSymbolicLinkW fails with 1314, so the fallback never fired and the install aborted. The fallback now also matches the raw os error. (pnpm v11 worked because the symlink-dir npm package falls back to junctions.)

  2. os error 5 from pnpm clean (and pnpm deploy --force). Removal sites dispatched on is_dir(), which on Windows is false for junctions, directory symlinks (name-surrogate reparse points), and dangling links, so directory-shaped links were routed to DeleteFileW, which fails on them with ERROR_ACCESS_DENIED. clean always hits this: .pnpm sorts before the package names, so every top-level package link dangles by the time it is removed. Added pacquet_fs::remove_dirent, which removes any dirent without following links (dir-shaped links are unlinked via RemoveDirectoryW), and switched clean, deploy, and the virtual-store pruner to it.

The TypeScript CLI is unaffected — it links via the symlink-dir package and removes with rimraf, both junction-safe — so this is a Rust-only fix with a pacquet-only changeset.

Behavioral note on deploy: a deploy target that is a non-name-surrogate reparse directory (e.g. a dedup-enabled folder) was previously removed with a bare RemoveDirectoryW, which fails on a non-empty directory; it now goes through remove_dir_all, whose traversal is already link-safe.

Squash Commit Body

Two Windows failures from pnpm/pnpm#13694:

1. The junction fallback in symlink_dir only matched PermissionDenied,
   but Rust std maps ERROR_PRIVILEGE_NOT_HELD (os error 1314) to
   Uncategorized, so installs failed outright for users without
   Developer Mode or elevation instead of falling back to junctions.
   Match the raw os error too.

2. Removal sites dispatched on is_dir(), which is false on Windows for
   junctions, directory symlinks (name-surrogate reparse points), and
   dangling links, routing them to DeleteFileW, which fails on
   directory-shaped entries with ERROR_ACCESS_DENIED (os error 5).
   Add pacquet_fs::remove_dirent, which unlinks directory-shaped links
   with RemoveDirectoryW without following them, and use it in clean,
   deploy, and the virtual-store pruner.

The TypeScript CLI is unaffected: it removes with rimraf and links via
the symlink-dir package, both of which already handle junctions.

Closes pnpm/pnpm#13694

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

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


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed package-link removal failures during pnpm clean and pnpm deploy --force.
    • Improved handling of regular files, directories, symlinks, dangling links, and Windows junctions during cleanup.
    • Windows now falls back to NTFS junctions when symlink creation lacks required privileges.
    • Added coverage for cleanup and Windows privilege-fallback scenarios.

Copilot AI lite review requested due to automatic review settings August 7, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@zkochan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 seconds

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c10acf6b-9091-4baa-b72b-89ae137651fa

📥 Commits

Reviewing files that changed from the base of the PR and between 4daf2b7 and ff8e38a.

📒 Files selected for processing (1)
  • pnpm/crates/cli/tests/suite/clean.rs
📝 Walkthrough

Walkthrough

Adds remove_dirent for link-safe removal of files, directories, symlinks, dangling links, and Windows junctions. Cleanup commands use it. Windows symlink creation now falls back on error 1314.

Changes

Filesystem link handling

Layer / File(s) Summary
Link-safe removal helper
pnpm/crates/fs/src/lib.rs, pnpm/crates/fs/src/remove_dirent.rs, pnpm/crates/fs/src/remove_dirent/tests.rs
Adds and exports remove_dirent. Tests cover files, directories, symlinks, dangling links, and Windows junctions.
Windows privilege fallback
pnpm/crates/fs/src/symlink_dir.rs, pnpm/crates/fs/src/symlink_dir/tests.rs, .changeset/windows-symlink-privilege-fallback.md
Treats ERROR_PRIVILEGE_NOT_HELD as a junction-fallback condition and adds a Windows regression test.
Cleanup path integration
pnpm/crates/cli/src/cli_args/clean.rs, pnpm/crates/cli/src/cli_args/deploy.rs, pnpm/crates/package-manager/src/prune_virtual_store.rs, pnpm/crates/cli/tests/suite/clean.rs
Routes cleanup and virtual-store pruning through remove_dirent while preserving not-found handling and diagnostics. Adds a clean integration test for package links.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant pnpm as pnpm clean/deploy
  participant remove_dirent
  participant FS as Filesystem
  pnpm->>remove_dirent: remove path
  remove_dirent->>FS: inspect entry without following links
  FS-->>remove_dirent: entry type
  remove_dirent->>FS: unlink link or remove directory
  remove_dirent-->>pnpm: success or not-found
Loading
sequenceDiagram
  participant symlink_dir
  participant WindowsAPI
  participant Junction
  symlink_dir->>WindowsAPI: create symlink
  WindowsAPI-->>symlink_dir: error 1314
  symlink_dir->>Junction: create NTFS junction
Loading

Possibly related PRs

  • pnpm/pnpm#13009: Both changes modify Windows junction handling in symlink_dir.rs.
  • pnpm/pnpm#13151: Both changes address stale links during cleanup workflows.
  • pnpm/pnpm#13306: Both changes use shared Windows symlink and junction cleanup logic.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-13694

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

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix Windows symlink privilege fallback and safe removal of dir-shaped links

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Fall back to NTFS junctions when Windows symlink creation fails with os error 1314.
• Remove junctions/dir symlinks safely without following targets to avoid os error 5.
• Add regression tests for dangling link cleanup and Windows-specific fallback behavior.
Diagram

graph TD
  A["CLI clean"] --> D(["pacquet_fs::remove_dirent"]) --> F{{"Windows unlink APIs"}}
  B["CLI deploy"] --> D --> F
  C["Virtual store pruner"] --> D --> F
  E["Link packages"] --> G(["pacquet_fs::symlink_dir"]) --> H{{"Windows link APIs"}}
  subgraph Legend
    direction LR
    _cli["CLI / command"] ~~~ _fs(["FS helper"]) ~~~ _os{{"Windows API"}}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use explicit reparse-point detection (Win32)
  • ➕ Can distinguish junctions vs symlinks vs other reparse-point directories more precisely
  • ➕ Avoids relying on FILE_ATTRIBUTE_DIRECTORY as a proxy for "dir-shaped link"
  • ➖ Requires more Windows-specific code (winapi bindings, additional error surface)
  • ➖ Harder to keep cross-platform behavior consistent
2. Always attempt RemoveDirectory then fall back to DeleteFile
  • ➕ Very small helper; avoids metadata/attribute inspection
  • ➕ Naturally handles dir-shaped entries first
  • ➖ More syscall attempts per removal (potential perf impact in large trees)
  • ➖ Error handling becomes trickier to keep deterministic across platforms
3. Centralize all removal through a dedicated filesystem abstraction layer
  • ➕ Makes future platform quirks (macOS, Linux) easier to manage consistently
  • ➕ Reduces ad-hoc removal logic across crates
  • ➖ Larger refactor than needed for the reported regressions
  • ➖ Higher review and rollout risk for a targeted Windows fix

Recommendation: The chosen approach (introducing remove_dirent and routing clean/deploy/pruner through it, plus expanding the symlink fallback condition to include raw os error 1314) is the best tradeoff: it targets the Windows-specific failure modes with minimal behavioral change elsewhere, keeps link traversal safe by using symlink_metadata, and is well-covered by focused regression tests. The more Win32-specific alternatives provide extra precision but add complexity disproportionate to the bug scope.

Files changed (10) +210 / -32

Bug fix (5) +55 / -32
clean.rsUse link-safe removal for 'pnpm clean' +2/-4

Use link-safe removal for 'pnpm clean'

• Replaces the 'is_dir()'-based remove dispatch with 'pacquet_fs::remove_dirent' to correctly unlink junctions/dir symlinks and dangling links on Windows. Keeps the existing NotFound-is-OK behavior.

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

deploy.rsSimplify deploy path deletion via 'remove_dirent' +7/-14

Simplify deploy path deletion via 'remove_dirent'

• Removes the prior deploy-target deletion branching (dir vs symlink dir vs file) and delegates deletion to 'pacquet_fs::remove_dirent'. Preserves NotFound handling and improves error context by wrapping failures with the target path.

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

remove_dirent.rsIntroduce 'remove_dirent' for link-safe deletion (Windows-aware) +33/-0

Introduce 'remove_dirent' for link-safe deletion (Windows-aware)

• Adds a removal helper that deletes files, directories, and directory-shaped links without following link targets. On Windows, uses metadata file attributes to detect directory-shaped links and removes them with 'remove_dir' to avoid 'ERROR_ACCESS_DENIED' from 'DeleteFileW'.

pnpm/crates/fs/src/remove_dirent.rs

symlink_dir.rsFallback to junctions on raw Windows privilege error (1314) +11/-6

Fallback to junctions on raw Windows privilege error (1314)

• Updates Windows fallback logic so symlink creation failures due to missing privileges ('ERROR_PRIVILEGE_NOT_HELD', 1314) trigger the junction fallback even though Rust maps it to 'ErrorKind::Uncategorized'. Updates docs/comments to reflect privilege-based probing/caching.

pnpm/crates/fs/src/symlink_dir.rs

prune_virtual_store.rsUse 'remove_dirent' when pruning virtual store entries +2/-8

Use 'remove_dirent' when pruning virtual store entries

• Replaces the 'symlink_metadata' + 'is_dir()' removal branching with 'pacquet_fs::remove_dirent', ensuring junctions/dir symlinks and dangling links are removed reliably without following targets.

pnpm/crates/package-manager/src/prune_virtual_store.rs

Refactor (1) +2 / -0
lib.rsExport new 'remove_dirent' helper +2/-0

Export new 'remove_dirent' helper

• Registers the new module and re-exports 'remove_dirent' from the fs crate public API so other crates can use link-safe deletion consistently.

pnpm/crates/fs/src/lib.rs

Tests (3) +148 / -0
clean.rsAdd regression test for removing dangling package links +28/-0

Add regression test for removing dangling package links

• Adds a test that models the isolated-linker layout where '.pnpm' is removed before top-level package links, leaving dangling links. Verifies 'pacquet clean' succeeds and removes both the virtual store directory and the package link.

pnpm/crates/cli/tests/clean.rs

tests.rsComprehensive tests for 'remove_dirent' (dangling links, junctions) +108/-0

Comprehensive tests for 'remove_dirent' (dangling links, junctions)

• Adds coverage for removing regular files, directory trees, directory links without touching targets, and dangling links. Includes Windows-only tests for junction removal and dangling junction cleanup, plus a Unix-only test for file symlink removal.

pnpm/crates/fs/src/remove_dirent/tests.rs

tests.rsTest junction fallback for 'ERROR_PRIVILEGE_NOT_HELD' (1314) +12/-0

Test junction fallback for 'ERROR_PRIVILEGE_NOT_HELD' (1314)

• Adds a Windows-specific test asserting that error 1314 does not map to PermissionDenied and still triggers the junction fallback predicate.

pnpm/crates/fs/src/symlink_dir/tests.rs

Documentation (1) +5 / -0
windows-symlink-privilege-fallback.mdDocument Windows junction fallback and link-safe cleanup fix +5/-0

Document Windows junction fallback and link-safe cleanup fix

• Adds a pacquet patch changeset describing two Windows-only fixes: falling back to junctions when symlink privilege is missing (os error 1314), and preventing cleanup failures when removing package links (os error 5).

.changeset/windows-symlink-privilege-fallback.md

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 7, 2026
@greptile-apps

greptile-apps Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (4): Last reviewed commit: "test(cli): require NotFound for the .pnp..." | Re-trigger Greptile

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.18     14.4±1.90ms    26.1 MB/sec    1.00     12.2±0.38ms    30.8 MB/sec
packument/parse                                  1.00     37.8±0.72µs  1756.1 MB/sec    1.03     39.0±0.15µs  1700.0 MB/sec
tarball/download_dependency                      1.52      3.8±1.15ms  1143.6 KB/sec    1.00      2.5±0.18ms  1734.5 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.05   197.5±21.23ms 81.0 KElem/sec    1.00    187.4±9.06ms 85.4 KElem/sec
workspace_resolution/hoist_heavy                 1.18    303.6±4.10ms        ? ?/sec    1.00    257.8±8.67ms        ? ?/sec

@qodo-code-review

qodo-code-review Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Clean test order assumption 🐞 Bug ☼ Reliability ⭐ New
Description
clean_removes_package_links_into_the_virtual_store assumes .pnpm is removed before package links
so the link dangles, but clean iterates read_dir without sorting, so the link may be removed
first and the test can pass without validating dangling-link unlinking.
Code

pnpm/crates/cli/tests/suite/clean.rs[R44-47]

+/// The real isolated-linker layout: `node_modules/<name>` is a link
+/// (symlink or junction) into `.pnpm`. `.pnpm` sorts before the package
+/// names, so by the time `clean` reaches the link it dangles — removal
+/// must unlink it rather than follow it
Relevance

●●● Strong

Team often hardens tests to avoid false-greens/flakiness; ordering assumptions are typically fixed.

PR-#13425
PR-#13375

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test asserts .pnpm is processed first to guarantee a dangling link, but clean does not sort
directory entries; it iterates the raw read_dir iterator. Therefore the test may not actually hit
the dangling-link case on some filesystems/runs.

pnpm/crates/cli/tests/suite/clean.rs[44-48]
pnpm/crates/cli/src/cli_args/clean.rs[166-175]

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 new regression test relies on an implicit directory enumeration order (that `.pnpm` is processed before `greenly`) to create a dangling link during `clean`. Because `clean` iterates `std::fs::read_dir` without sorting, the test may remove `greenly` before `.pnpm`, meaning the link is **not** dangling when removed; this makes the test fail to reliably cover the bug scenario.

### Issue Context
`read_dir` ordering is filesystem-dependent and not guaranteed to be lexicographic. The test comment states `.pnpm` sorts before package names, but the implementation does not sort.

### Fix Focus Areas
- pnpm/crates/cli/tests/suite/clean.rs[44-72]

### Suggested fix
Update the test setup so the `node_modules/<pkg>` link is guaranteed to be dangling **regardless of enumeration order**, e.g.:
- Create the link into `.pnpm/.../node_modules/<pkg>` as it does now.
- Then explicitly delete the link target directory (`.../.pnpm/.../node_modules/<pkg>`) *before* running `pacquet clean`.

That way, even if `clean` processes the package entry first, it must still correctly unlink a dangling directory-shaped link.

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


2. Reparse deletion bypass 🐞 Bug ⛨ Security
Description
remove_path_if_exists now deletes deploy paths via pacquet_fs::remove_dirent, which will recurse
with fs::remove_dir_all for any entry where symlink_metadata().is_dir() is true, without
considering Windows FILE_ATTRIBUTE_REPARSE_POINT. This can recursively delete through
reparse-point directories that deploy already labels “unsafe”, risking unintended deletion beyond
the intended deploy tree when a reparse-point directory is present and --force is used.
Code

pnpm/crates/cli/src/cli_args/deploy.rs[R696-699]

+    match remove_dirent(path) {
+        Ok(()) => Ok(()),
+        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+        Err(error) => Err(error)
Relevance

●● Moderate

Potential Windows reparse-point deletion risk is plausible, but no close historical accept/reject
precedent found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Deploy explicitly treats Windows reparse points as unsafe (FILE_ATTRIBUTE_REPARSE_POINT), but the
new deploy removal path no longer consults that policy and instead uses remove_dirent, which may
recurse purely based on metadata.is_dir(). This makes it possible to delete through a
reparse-point directory rather than unlinking it.

pnpm/crates/cli/src/cli_args/deploy.rs[695-715]
pnpm/crates/fs/src/remove_dirent.rs[16-29]

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

### Issue description
`pnpm deploy --force` removal now calls `pacquet_fs::remove_dirent` directly. `remove_dirent` will recurse with `remove_dir_all` when `symlink_metadata(path)?.is_dir()` is true, but it does not check Windows `FILE_ATTRIBUTE_REPARSE_POINT`. Deploy already has an explicit policy (`is_unsafe_deploy_link`) treating reparse points as unsafe, so this change can delete through a reparse-point directory instead of unlinking it.

### Issue Context
- On Windows, some reparse-point directories can present as directories to `symlink_metadata().is_dir()`. In those cases, `remove_dirent` will choose `remove_dir_all`, which can traverse into the redirected location.
- Deploy code already defines `is_unsafe_deploy_link` (checking `FILE_ATTRIBUTE_REPARSE_POINT`) and uses it in other safety checks; the removal path no longer uses it.

### Fix Focus Areas
- pnpm/crates/fs/src/remove_dirent.rs[16-29]
- pnpm/crates/cli/src/cli_args/deploy.rs[695-715]

### Suggested fix
Implement one of these (preferred: centralize in `remove_dirent` so all callers benefit):
1) **Harden `remove_dirent` on Windows**:
  - Before the `metadata.is_dir()` => `remove_dir_all` branch, check `FILE_ATTRIBUTE_REPARSE_POINT`.
  - If `REPARSE_POINT` is set, *do not recurse*; instead unlink the entry:
    - if `FILE_ATTRIBUTE_DIRECTORY` set => `fs::remove_dir(path)`
    - else => `fs::remove_file(path)`

2) **Or restore deploy-specific guard**:
  - In `remove_path_if_exists`, reintroduce a `symlink_metadata` + `is_unsafe_deploy_link` dispatch:
    - unsafe reparse dir => unlink only (`remove_symlink_dir`/`remove_dir`)
    - normal dir => `remove_dir_all`
    - file => `remove_file`
  - Keep Windows junction/symlink correctness (i.e., do not rely on `Path::is_dir()`).

Add/extend a Windows test that creates a reparse-point directory that still reports `metadata.is_dir() == true` (if available in your test environment) and ensure it is unlinked rather than recursively traversed.

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



Informational

3. Redundant test module comment 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The added module-level comment restates the file’s purpose without adding intent or rationale,
making it redundant noise. This violates the guideline to avoid comments that merely repeat what is
already obvious from the code/module name.
Code

pnpm/crates/fs/src/remove_dirent/tests.rs[1]

+//! Tests for the [`crate::remove_dirent`] module.
Relevance

●●● Strong

Repo reviewers frequently trim/rewrite redundant test/docs comments; redundant module header comment
likely removed.

PR-#13409
PR-#12991

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713467 requires avoiding redundant comments that restate the code. The added `//!
Tests for the [crate::remove_dirent] module.` line provides no additional context beyond what the
module/file already conveys.

Rule 713467: Avoid redundant comments that restate the code
pnpm/crates/fs/src/remove_dirent/tests.rs[1-1]

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

## Issue description
A new module-level comment is redundant because it only restates the module name/purpose without adding rationale.

## Issue Context
Compliance requires avoiding comments that simply restate what the code already makes clear.

## Fix Focus Areas
- pnpm/crates/fs/src/remove_dirent/tests.rs[1-1]

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


4. is_err hides failures ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
New tests assert link removal via symlink_metadata(...).is_err(), so unrelated I/O failures (e.g.
PermissionDenied) would satisfy the assertion even if the entry still exists. This can make the
regression tests false-green and hide Windows link-removal regressions.
Code

pnpm/crates/cli/tests/clean.rs[R64-67]

+    assert!(
+        fs::symlink_metadata(node_modules.join("greenly")).is_err(),
+        "the package link should be removed",
+    );
Relevance

●● Moderate

Mixed precedent: narrowing is_err() to NotFound was accepted before, but a very recent similar
suggestion was rejected.

PR-#13378
PR-#13700

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The newly added assertions use symlink_metadata(...).is_err() in both CLI and fs tests, which
accepts any error kind and can pass even when the entry is not actually removed. This mirrors a
previously accepted review note to narrow such assertions to NotFound.

pnpm/crates/cli/tests/clean.rs[44-67]
pnpm/crates/fs/src/remove_dirent/tests.rs[31-62]
PR-#13378

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 new tests use `fs::symlink_metadata(path).is_err()` to assert that a link/junction was removed. This passes for any error kind (including `PermissionDenied`), which can mask real regressions.

### Issue Context
There is past repo guidance to narrow these assertions to `ErrorKind::NotFound` to avoid false-green tests.

### Fix Focus Areas
- pnpm/crates/cli/tests/clean.rs[44-70]
- pnpm/crates/fs/src/remove_dirent/tests.rs[31-62]

### Suggested fix
Replace `is_err()` checks with a match that only accepts `NotFound`:
```rust
match fs::symlink_metadata(&path) {
 Err(e) if e.kind() == io::ErrorKind::NotFound => {}
 Ok(_) => panic!("expected removed: {}", path.display()),
 Err(e) => panic!("unexpected error for {}: {e}", path.display()),
}
```
Apply the same pattern to the similar assertions in `remove_dirent` tests.

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


5. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only lists pacquet and omits the required pnpm package entry, so the release
metadata will not reflect the pnpm-facing bug fix. This violates the changeset front-matter
requirements and risks an incorrect/partial release bump.
Code

.changeset/windows-symlink-privilege-fallback.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

● Weak

Multiple recent PRs rejected adding pnpm to pacquet-only changesets; team treats rule as
non-applicable here.

PR-#13594
PR-#13549
PR-#12996

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changeset front-matter to include an explicit pnpm entry with a
valid bump type. The added changeset front-matter includes only "pacquet": patch, with no pnpm
entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/windows-symlink-privilege-fallback.md[1-3]

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

## Issue description
The changeset front-matter omits the required `pnpm` entry.

## Issue Context
Compliance requires each changeset to explicitly include a `pnpm` package bump (`patch`/`minor`/`major`). This PR adds a `.changeset/...md` file that only lists `pacquet`.

## Fix Focus Areas
- .changeset/windows-symlink-privilege-fallback.md[1-3]

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


Grey Divider

Context used
✅ Compliance rules (platform): 26 rules

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Previous review results

Review updated until commit ff8e38a

Results up to commit 399769a ⚖️ Balanced


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


Remediation recommended
1. Reparse deletion bypass 🐞 Bug ⛨ Security
Description
remove_path_if_exists now deletes deploy paths via pacquet_fs::remove_dirent, which will recurse
with fs::remove_dir_all for any entry where symlink_metadata().is_dir() is true, without
considering Windows FILE_ATTRIBUTE_REPARSE_POINT. This can recursively delete through
reparse-point directories that deploy already labels “unsafe”, risking unintended deletion beyond
the intended deploy tree when a reparse-point directory is present and --force is used.
Code

pnpm/crates/cli/src/cli_args/deploy.rs[R696-699]

+    match remove_dirent(path) {
+        Ok(()) => Ok(()),
+        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
+        Err(error) => Err(error)
Relevance

●● Moderate

Potential Windows reparse-point deletion risk is plausible, but no close historical accept/reject
precedent found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Deploy explicitly treats Windows reparse points as unsafe (FILE_ATTRIBUTE_REPARSE_POINT), but the
new deploy removal path no longer consults that policy and instead uses remove_dirent, which may
recurse purely based on metadata.is_dir(). This makes it possible to delete through a
reparse-point directory rather than unlinking it.

pnpm/crates/cli/src/cli_args/deploy.rs[695-715]
pnpm/crates/fs/src/remove_dirent.rs[16-29]

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

### Issue description
`pnpm deploy --force` removal now calls `pacquet_fs::remove_dirent` directly. `remove_dirent` will recurse with `remove_dir_all` when `symlink_metadata(path)?.is_dir()` is true, but it does not check Windows `FILE_ATTRIBUTE_REPARSE_POINT`. Deploy already has an explicit policy (`is_unsafe_deploy_link`) treating reparse points as unsafe, so this change can delete through a reparse-point directory instead of unlinking it.

### Issue Context
- On Windows, some reparse-point directories can present as directories to `symlink_metadata().is_dir()`. In those cases, `remove_dirent` will choose `remove_dir_all`, which can traverse into the redirected location.
- Deploy code already defines `is_unsafe_deploy_link` (checking `FILE_ATTRIBUTE_REPARSE_POINT`) and uses it in other safety checks; the removal path no longer uses it.

### Fix Focus Areas
- pnpm/crates/fs/src/remove_dirent.rs[16-29]
- pnpm/crates/cli/src/cli_args/deploy.rs[695-715]

### Suggested fix
Implement one of these (preferred: centralize in `remove_dirent` so all callers benefit):
1) **Harden `remove_dirent` on Windows**:
  - Before the `metadata.is_dir()` => `remove_dir_all` branch, check `FILE_ATTRIBUTE_REPARSE_POINT`.
  - If `REPARSE_POINT` is set, *do not recurse*; instead unlink the entry:
    - if `FILE_ATTRIBUTE_DIRECTORY` set => `fs::remove_dir(path)`
    - else => `fs::remove_file(path)`

2) **Or restore deploy-specific guard**:
  - In `remove_path_if_exists`, reintroduce a `symlink_metadata` + `is_unsafe_deploy_link` dispatch:
    - unsafe reparse dir => unlink only (`remove_symlink_dir`/`remove_dir`)
    - normal dir => `remove_dir_all`
    - file => `remove_file`
  - Keep Windows junction/symlink correctness (i.e., do not rely on `Path::is_dir()`).

Add/extend a Windows test that creates a reparse-point directory that still reports `metadata.is_dir() == true` (if available in your test environment) and ensure it is unlinked rather than recursively traversed.

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



Informational
2. is_err hides failures ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
New tests assert link removal via symlink_metadata(...).is_err(), so unrelated I/O failures (e.g.
PermissionDenied) would satisfy the assertion even if the entry still exists. This can make the
regression tests false-green and hide Windows link-removal regressions.
Code

pnpm/crates/cli/tests/clean.rs[R64-67]

+    assert!(
+        fs::symlink_metadata(node_modules.join("greenly")).is_err(),
+        "the package link should be removed",
+    );
Relevance

●● Moderate

Mixed precedent: narrowing is_err() to NotFound was accepted before, but a very recent similar
suggestion was rejected.

PR-#13378
PR-#13700

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The newly added assertions use symlink_metadata(...).is_err() in both CLI and fs tests, which
accepts any error kind and can pass even when the entry is not actually removed. This mirrors a
previously accepted review note to narrow such assertions to NotFound.

pnpm/crates/cli/tests/clean.rs[44-67]
pnpm/crates/fs/src/remove_dirent/tests.rs[31-62]
PR-#13378

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 new tests use `fs::symlink_metadata(path).is_err()` to assert that a link/junction was removed. This passes for any error kind (including `PermissionDenied`), which can mask real regressions.

### Issue Context
There is past repo guidance to narrow these assertions to `ErrorKind::NotFound` to avoid false-green tests.

### Fix Focus Areas
- pnpm/crates/cli/tests/clean.rs[44-70]
- pnpm/crates/fs/src/remove_dirent/tests.rs[31-62]

### Suggested fix
Replace `is_err()` checks with a match that only accepts `NotFound`:
```rust
match fs::symlink_metadata(&path) {
 Err(e) if e.kind() == io::ErrorKind::NotFound => {}
 Ok(_) => panic!("expected removed: {}", path.display()),
 Err(e) => panic!("unexpected error for {}: {e}", path.display()),
}
```
Apply the same pattern to the similar assertions in `remove_dirent` tests.

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


3. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only lists pacquet and omits the required pnpm package entry, so the release
metadata will not reflect the pnpm-facing bug fix. This violates the changeset front-matter
requirements and risks an incorrect/partial release bump.
Code

.changeset/windows-symlink-privilege-fallback.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

● Weak

Multiple recent PRs rejected adding pnpm to pacquet-only changesets; team treats rule as
non-applicable here.

PR-#13594
PR-#13549
PR-#12996

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changeset front-matter to include an explicit pnpm entry with a
valid bump type. The added changeset front-matter includes only "pacquet": patch, with no pnpm
entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/windows-symlink-privilege-fallback.md[1-3]

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

## Issue description
The changeset front-matter omits the required `pnpm` entry.

## Issue Context
Compliance requires each changeset to explicitly include a `pnpm` package bump (`patch`/`minor`/`major`). This PR adds a `.changeset/...md` file that only lists `pacquet`.

## Fix Focus Areas
- .changeset/windows-symlink-privilege-fallback.md[1-3]

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


Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.33333% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.20%. Comparing base (b11fa81) to head (ff8e38a).

Files with missing lines Patch % Lines
pnpm/crates/cli/src/cli_args/deploy.rs 33.33% 4 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13707   +/-   ##
=======================================
  Coverage   88.19%   88.20%           
=======================================
  Files         615      616    +1     
  Lines       99955    99951    -4     
=======================================
+ Hits        88157    88160    +3     
+ Misses      11798    11791    -7     

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

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

Copilot AI review requested due to automatic review settings August 7, 2026 13:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@zkochan

zkochan commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Responses to the Qodo review findings:

1. Reparse deletion bypass (deploy) — not applicable. Every redirecting reparse point (symlink or junction/mount point) carries the name-surrogate bit, so symlink_metadata().is_dir() is false for it in Rust (FileType::is_dir excludes name-surrogate reparse points) and remove_dirent unlinks it via RemoveDirectoryW without recursing. A reparse-point directory that is not a name surrogate (dedup, WCI placeholders) is a physically real directory whose contents live at that path — recursing into it is correct, and the previous code's bare RemoveDirectoryW on it would simply have failed with ERROR_DIR_NOT_EMPTY. Additionally, std::fs::remove_dir_all itself is reparse-safe since the CVE-2022-21658 rework: it opens every node with FILE_FLAG_OPEN_REPARSE_POINT and deletes links rather than traversing them, so even a link that appears mid-walk cannot redirect the deletion.

2. is_err() hides failures — accepted; fixed in 1b539e9. The removal assertions now require ErrorKind::NotFound and print the unexpected result otherwise.

3. Changeset missing pnpm entry — intentional per repository policy. In this repo's changesets, pnpm always means the TypeScript CLI package, and a changeset whose implementation is Rust-only must target pacquet and omit "pnpm" (see the "Changesets for the Rust products" section of CLAUDE.md). The TypeScript CLI is unaffected by this bug, so there is nothing to release on that side.


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

@qodo-code-review

Copy link
Copy Markdown

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

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

zkochan and others added 2 commits August 7, 2026 15:11
… on Windows

Two Windows failures from #13694:

1. The junction fallback in symlink_dir only matched PermissionDenied,
   but Rust std maps ERROR_PRIVILEGE_NOT_HELD (os error 1314) to
   Uncategorized, so installs failed outright for users without
   Developer Mode or elevation instead of falling back to junctions.
   Match the raw os error too.

2. Removal sites dispatched on is_dir(), which is false on Windows for
   junctions, directory symlinks (name-surrogate reparse points), and
   dangling links, routing them to DeleteFileW, which fails on
   directory-shaped entries with ERROR_ACCESS_DENIED (os error 5).
   Add pacquet_fs::remove_dirent, which unlinks directory-shaped links
   with RemoveDirectoryW without following them, and use it in clean,
   deploy, and the virtual-store pruner.

The TypeScript CLI is unaffected: it removes with rimraf and links via
the symlink-dir package, both of which already handle junctions.

Closes #13694

Co-Authored-By: Claude Fable 5 <[email protected]>
A permission or I/O error inspecting the link would have satisfied
is_err() while the entry still existed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings August 7, 2026 13:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai coderabbitai Bot 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: 1

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

Inline comments:
In `@pnpm/crates/cli/tests/suite/clean.rs`:
- Line 63: Replace the .pnpm Path::exists() assertion with fs::symlink_metadata
and assert that it returns an ErrorKind::NotFound error, matching the existing
package-link removal assertion and ensuring other metadata failures cause the
test to fail.
🪄 Autofix

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: 86929f2b-e502-4db0-b69a-700a16792b51

📥 Commits

Reviewing files that changed from the base of the PR and between 1b539e9 and 4daf2b7.

📒 Files selected for processing (1)
  • pnpm/crates/cli/tests/suite/clean.rs

Comment thread pnpm/crates/cli/tests/suite/clean.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 4daf2b7

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

Copilot AI review requested due to automatic review settings August 7, 2026 13:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@qodo-code-review

Copy link
Copy Markdown

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

@zkochan
zkochan merged commit 3bbefa9 into main Aug 7, 2026
36 checks passed
@zkochan
zkochan deleted the fix-13694 branch August 7, 2026 13:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[pnpm v12] 🐛 Bug: Failed to create symlink (os error 1314) & Access is denied. (os error 5)

3 participants