Skip to content

fix(cli): close the six pnpm-12-on-n8n defects - #13375

Merged
zkochan merged 6 commits into
mainfrom
fix-13322
Jul 25, 2026
Merged

zkochan merged 6 commits into
mainfrom
fix-13322

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #13322 — the six pacquet-side defects found while installing and building n8n with pnpm 12. Each one is a divergence from the TypeScript CLI, so every fix moves pacquet onto pnpm's existing behavior rather than inventing new behavior. Three of the six were outright blockers for that repo.

Finding 2 — an allowBuilds placeholder hard-blocked every command. When an install ignores build scripts, pnpm scaffolds one allowBuilds entry per package with the placeholder string set this to true or false. WorkspaceSettings demanded a boolean and refused to load the config at all, so a single pnpm 11 run poisoned the workspace for every pnpm 12 command. The value is now an AllowBuild enum; only decided entries reach Config::allow_builds, which is what pnpm's createAllowBuildFunction does with a non-boolean. The raw value stays on WorkspaceSettings, so pnpm config list and the updateConfig hook still see what the file says.

Finding 3 — the patch applier was stricter than pnpm's. diffy's matcher is byte-exact; @pnpm/patch-package, which pnpm applies patches through, compares lines with trailing whitespace stripped and retries a hunk up to twenty lines either side of its recorded position. Three of n8n's fifteen patches depend on that looseness — a hunk whose last line is context in a file with no final newline, and an LF patch against a CRLF file. pacquet-patching now applies hunks itself with pnpm's tolerances, keeping diffy for parsing. The file is modeled as split('\n') throughout, as patch-package does, so untouched CRLF lines keep their \r and a file without a final newline keeps that shape.

Finding 4 — npm_config_user_agent was unset or truncated. Unset for install lifecycle scripts, the bare string pnpm for pnpm run / exec / dlx. n8n's preinstall guard compares the leading name/version token against pnpm and rejected the install. Config::user_agent is now threaded to all of them.

Finding 5 — regexp script selectors. pnpm run "/^typecheck:.+/" (and the bare pnpm "/…/" fallback) now selects every matching script, in single-project and recursive runs alike, mirroring tryBuildRegExpFromCommand + getSpecifiedScripts. An exact script name still wins over the pattern reading, and flags are rejected with ERR_PNPM_UNSUPPORTED_SCRIPT_COMMAND_FORMAT.

Finding 6 — concurrent packageManager switches raced. Turbo spawns several pnpm run children at once; on a cold cache each installed the pinned engine into the same host-wide global-virtual-store slot. Two things went wrong: the slot's destructive re-stage removed a directory another process was still writing, and every process re-linked the native binary with unlink-then-hardlink, pulling the executable out from under a sibling that was running it. The install is now serialized by an advisory lock, and the relink skips an already-correct destination and otherwise swaps via rename. The new integration test spawns 7 concurrent engine installs and fails reliably without either half of the fix.

Finding 8 — reporting divergences. A frozen install whose recorded settings drifted now reports ERR_PNPM_LOCKFILE_CONFIG_MISMATCH naming the one field, as pnpm does, instead of ERR_PNPM_OUTDATED_LOCKFILE with the whole overrides map dumped. Ignored build scripts keep their (patch_hash=…) suffix, matching dedupePackageNamesFromIgnoredBuilds. And a deprecated package is reported once — pacquet's resolver re-emits a package it later meets at a shallower depth, so the reporter folds the repeats away, which also stops a direct deprecation being counted among the deprecated subdependencies.

What review changed

Four defects surfaced during review, three of them in this PR's own code:

  • A failed script could be reported as passed. Letting one project run several scripts meant a later script's success — and, less obviously, the per-script Status::Running write — erased an earlier failure from the per-project summary that count_failures reads. Under --no-bail the run exited zero. The same bug exists in the TypeScript stack, where RegExp selectors have shipped for a while, so pnpm -r run "/pattern/" --no-bail is affected today; fixed in both, which is why this PR now touches exec/commands and its changeset names the TypeScript package.
  • Approving a placeholder-bearing package corrupted its entry. replace_bool_value_at ended the value span at its first whitespace, so deciding a package whose allowBuilds entry still read set this to true or false wrote true this to true or false — a plain scalar YAML reads as a string, leaving the package undecided and the approval silently ineffective. Only reachable because finding 2 made such a config load at all.
  • A stale lock holder released its successor's lock. A DirLock past abandoned_after had already lost its directory to the next process; dropping it removed that one, handing the engine slot to two processes at once — the exact race the lock exists to prevent. Acquisition now records an owner token and release only removes a lock still carrying it.
  • The lock's takeover tests were timing-fragile. A zero abandonment threshold asks the wall clock and the filesystem's mtime clock to agree; on a runner whose wall clock leads, the subtraction underflows and the lock reads as fresh. This is the likely cause of the first Code Coverage failure, which did not reproduce locally.

Also from review: the selector is compiled once per command instead of once per project (which also reports a rejected pattern once rather than per project), and force_link's rename retries briefly against the sharing violations a concurrently-running executable invites on Windows.

Declined, with reasoning on the threads: switching to JavaScript RegExp semantics (needs a new dependency; the fallback matches pnpm's own behavior for an uncompilable pattern), filtering rather than aborting on a hidden script matched by a selector (pnpm aborts too), and making the changeset pacquet-only (the fix lands in both stacks).

Notes for reviewers

  • All six are pacquet-only bugs. The TypeScript CLI already behaves this way, so there is nothing to mirror. The changesets target pacquet only.
  • New workspace dependency: regex (approved before adding), needed for finding 5. It was already in Cargo.lock transitively, so no new supply-chain surface. regex lacks JavaScript's lookahead and backreferences; a pattern it can't compile falls through to the plain-name reading and surfaces as the usual "missing script" error, which is also what pnpm does with an invalid literal.
  • DirLock gives up rather than failing. After a bounded wait it reports that it could not take the lock and the caller proceeds unserialized — a lost lock is never worse than today's behavior. A lock directory older than a separate, larger abandonment bound is taken over, so a process that dies holding it can't wedge the host.
  • One thing finding 4 does not fix: the user agent still reports node/? where pnpm reports node/v24.18.0. Filling that in costs a node --version spawn on every command, which is a perf trade-off worth deciding separately.

Squash Commit Body

Six independent pacquet-side defects found while installing and building
n8n with pnpm 12. Each is a divergence from the TypeScript CLI, so every
fix moves pacquet onto pnpm's existing behavior rather than inventing new
behavior.

Finding 2 — an `allowBuilds` placeholder written by pnpm made
`WorkspaceSettings` refuse to load the config at all. The value is now an
`AllowBuild` enum; only decided entries reach `Config::allow_builds`,
matching `createAllowBuildFunction`. The raw value stays on
`WorkspaceSettings` so `pnpm config list` and the `updateConfig` hook
still see what the file says.

Finding 3 — `diffy`'s matcher is byte-exact, while `@pnpm/patch-package`
compares lines with trailing whitespace stripped and retries a hunk
within twenty lines of its recorded position. `pacquet-patching` now
applies hunks itself with those tolerances, keeping `diffy` for parsing.
The file is modeled as `split('\n')` throughout, so untouched CRLF lines
keep their `\r` and a file without a final newline keeps that shape.

Finding 4 — `Config::user_agent` is threaded to install lifecycle
scripts, `pnpm run`, `exec`, and `dlx`, which previously saw nothing or
the bare string `pnpm`. It still reports `node/?` rather than the host
Node version; filling that in costs a `node --version` spawn on every
command, which is a separate trade-off to make.

Finding 5 — `/pattern/` script selectors select every matching script in
single-project and recursive runs, mirroring `tryBuildRegExpFromCommand`
+ `getSpecifiedScripts`. This adds `regex` to the workspace
dependencies; it was already in the lock transitively.

Finding 6 — concurrent `packageManager` switches raced on the shared
global-virtual-store slot: the destructive re-stage removed a directory
another process was still writing, and the native-binary relink used
unlink-then-hardlink, pulling the executable out from under a sibling
running it. The install is now serialized by an advisory lock (a new
`pacquet_fs::DirLock`, which gives up rather than failing so a lost lock
is never worse than today), and the relink skips an already-correct
destination and otherwise swaps via rename.

Finding 8 — settings drift under a frozen install reports
`ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` naming the one field instead of
`ERR_PNPM_OUTDATED_LOCKFILE` with the whole map dumped; ignored build
scripts keep their `(patch_hash=…)` suffix; and a deprecated package is
reported once, since pacquet's resolver re-emits one it later meets at a
shallower depth.

All six are pacquet-only bugs; the TypeScript CLI already behaves this
way, so there is nothing to mirror.

Closes pnpm/pnpm#13322

Checklist

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

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

Summary by CodeRabbit

  • New Features

    • Added regular-expression script selectors for single-project and recursive run commands.
    • Configured user-agent values are now available to lifecycle scripts and spawned commands.
    • Improved patch application for line-ending differences, missing final newlines, and shifted context.
  • Bug Fixes

    • Prevented concurrent package-manager installations from interfering with each other.
    • Frozen installs now identify the specific configuration causing a lockfile mismatch.
    • Undecided allowBuilds placeholders no longer block commands.
    • Deprecated packages and ignored builds are reported more accurately.
    • Recursive runs preserve failures even when later scripts succeed.

zkochan added 2 commits July 25, 2026 19:31
Six independent pacquet-side defects found while installing and building
n8n with pnpm 12, all reported in #13322. Each is a divergence
from the TypeScript CLI, so every fix here moves pacquet onto pnpm's
existing behavior rather than inventing new behavior.

Finding 2 — `allowBuilds` placeholders. When an install ignores build
scripts, pnpm scaffolds one `allowBuilds` entry per package with the
placeholder string `set this to true or false`. `WorkspaceSettings`
demanded a boolean and refused to load the config at all, so a single
pnpm 11 run poisoned the workspace for every pnpm 12 command. The value
is now an `AllowBuild` enum; only decided entries reach
`Config::allow_builds`, which is what pnpm's `createAllowBuildFunction`
does with a non-boolean. Keeping the raw value on `WorkspaceSettings`
means `pnpm config list` and the `updateConfig` hook still see what the
file says.

Finding 3 — the patch applier. `diffy`'s matcher is byte-exact;
`@pnpm/patch-package`, which pnpm applies patches through, compares
lines with trailing whitespace stripped and retries a hunk up to twenty
lines either side of its recorded position. Three of n8n's fifteen
patches depend on that looseness. `pacquet-patching` now applies hunks
itself with pnpm's tolerances, keeping `diffy` for parsing. The file is
modeled as `split('\n')` throughout, as patch-package does, so untouched
CRLF lines keep their `\r` and a file without a final newline keeps that
shape.

Finding 4 — `npm_config_user_agent`. It was unset for install lifecycle
scripts and the bare string `pnpm` for `pnpm run` / `exec` / `dlx`;
n8n's `preinstall` guard compares the leading `name/version` token
against `pnpm` and rejected the install. `Config::user_agent` is now
threaded to all of them. It still reports `node/?` rather than the host
Node version — filling that in costs a `node --version` spawn on every
command, which is a separate trade-off to make.

Finding 5 — regexp script selectors. `pnpm run "/^typecheck:.+/"` (and
the bare `pnpm "/…/"` fallback) now selects every matching script, in
single-project and recursive runs alike, mirroring
`tryBuildRegExpFromCommand` + `getSpecifiedScripts`. An exact script
name still wins over the pattern reading, and flags are rejected. This
adds `regex` to the workspace dependencies; it was already in the lock
transitively.

Finding 6 — concurrent `packageManager` switches. Turbo spawns several
`pnpm run` children at once; on a cold cache each one installed the
pinned engine into the same host-wide global-virtual-store slot. Two
things went wrong: the slot's destructive re-stage removed a directory
another process was still writing, and every process re-linked the
native binary with unlink-then-hardlink, pulling the executable out from
under a sibling that was running it. The install is now serialized by an
advisory lock (a new `pacquet_fs::DirLock`, which gives up rather than
failing so a lost lock is never worse than today), and the relink skips
an already-correct destination and otherwise swaps via rename.

Finding 8 — reporting divergences. A frozen install whose recorded
settings drifted now reports `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` naming
the one field, as pnpm does, instead of `ERR_PNPM_OUTDATED_LOCKFILE`
with the whole `overrides` map dumped. Ignored build scripts keep their
`(patch_hash=…)` suffix, matching `dedupePackageNamesFromIgnoredBuilds`.
And a deprecated package is reported once: pacquet's resolver re-emits a
package it later meets at a shallower depth, so the reporter now folds
the repeats away, which also stops a direct deprecation being counted
among the deprecated subdependencies.

All six are pacquet-only bugs; the TypeScript CLI already behaves this
way, so there is nothing to mirror.

Closes #13322
Descriptive parameter names, `prefix_then_alphabetical` derive order,
raw strings instead of escapes, and trailing commas in multi-line macro
invocations — the pre-push dylint pass.
Copilot AI review requested due to automatic review settings July 25, 2026 17:42

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

PR Summary by Qodo

fix(cli): close pnpm-12-on-n8n compatibility defects

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Make workspace config parsing tolerant of pnpm-scaffolded allowBuilds placeholders.
• Match pnpm behavior for patch application, user agent env, script selectors, and lockfile errors.
• Prevent concurrent pinned-engine installs from racing in the shared global store slot.
Diagram

graph TD
  CLI["CLI commands"] --> CFG["Config (user agent)"] --> PM["Package manager"]
  CLI --> RUN["Run/Exec/Dlx"] --> UA["npm_config_user_agent"]
  CFG --> WS["Workspace YAML"] --> AB["allowBuilds policy"] --> PM
  PM --> PATCH["Patching"]
  PM --> ENG["Pinned engine install"] --> LOCK["DirLock"] --> STORE[("Store tmp/slot")]
  PATCH --> TOL["Tolerant hunk apply"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Represent `allowBuilds` as `Option` with custom deserializer
  • ➕ Avoids introducing a new public enum type
  • ➕ Could keep Config::allow_builds mapping logic closer to parsing
  • ➖ Loses the raw placeholder string value (hurts config list fidelity)
  • ➖ Harder to distinguish placeholder vs arbitrary string without extra fields
2. Use OS-level file locks (flock/LockFileEx) for engine install serialization
  • ➕ Standard locking primitive with clearer semantics in many environments
  • ➕ Can store metadata (pid, timestamp) in a lock file
  • ➖ Cross-platform pitfalls and dependency complexity
  • ➖ More failure modes on network filesystems; directory-creation lock is simpler and already atomic
3. Adopt an existing patch-application crate matching `patch-package` semantics
  • ➕ Potentially less custom code to maintain long-term
  • ➕ Might cover additional edge cases beyond current needs
  • ➖ Hard to guarantee exact pnpm/patch-package behavior match
  • ➖ Adds dependency surface and audit overhead; current approach reuses diffy parsing and only customizes matching

Recommendation: The PR’s approach (model pnpm behavior explicitly and keep raw config values) is the best fit for compatibility goals. The AllowBuild enum preserves file fidelity while keeping policy decisions identical to pnpm’s boolean-only matcher; the tolerant patch applier is narrowly scoped to pnpm’s documented looseness; and the directory-based lock is a pragmatic cross-platform guard for the shared engine slot without introducing heavier platform-specific locking dependencies.

Files changed (42) +1320 / -150

Enhancement (3) +170 / -96
run.rsImplement /regexp/ script selectors and propagate user agent +79/-12

Implement /regexp/ script selectors and propagate user agent

• Adds '/pattern/' selector support (with exact-name precedence), rejects regexp flags with 'ERR_PNPM_UNSUPPORTED_SCRIPT_COMMAND_FORMAT', and ensures 'npm_config_user_agent' uses the configured user agent in run stages.

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

recursive.rsEnable regexp selectors for recursive run (multi-script per project) +88/-81

Enable regexp selectors for recursive run (multi-script per project)

• Reuses the shared script selector to run every matching script per selected project, preserving recursion guards and hidden-script rules.

pnpm/crates/cli/src/cli_args/run/recursive.rs

lib.rsRe-export AllowBuild and decided_allow_builds helpers +3/-3

Re-export AllowBuild and decided_allow_builds helpers

• Exports the new 'AllowBuild' enum and the 'decided_allow_builds' reducer from the config crate public surface.

pnpm/crates/config/src/lib.rs

Bug fix (15) +427 / -34
dlx.rsThread configured user agent into dlx execution env +24/-4

Thread configured user agent into dlx execution env

• Introduces a 'SpawnEnv' struct to pass extra env/bin paths plus configured user agent into 'run_bin', and sets 'npm_config_user_agent' accordingly.

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

exec.rsSet npm_config_user_agent from Config for exec +1/-4

Set npm_config_user_agent from Config for exec

• Replaces hardcoded 'pnpm' user agent with 'config.user_agent' when spawning 'pnpm exec' processes.

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

global.rsIgnore undecided allowBuilds entries for global installs +4/-2

Ignore undecided allowBuilds entries for global installs

• Switches global allowBuilds ingestion to drop placeholder/undecided entries via 'decided_allow_builds', aligning with pnpm behavior.

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

install_pnpm.rsMake native-binary relink safe under concurrent engine installs +22/-4

Make native-binary relink safe under concurrent engine installs

• Avoids unlinking an in-use destination by checking inode equality, stages the hardlink into a temp name, sets permissions on the staged file, then atomically renames into place.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs

install_pnpm_to_store.rsSerialize pinned-engine installation with a host-wide directory lock +36/-0

Serialize pinned-engine installation with a host-wide directory lock

• Adds a 'DirLock' guard around engine materialization in the shared store slot, re-checks cache after waiting, and continues best-effort if the lock can’t be acquired.

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs

workspace_yaml.rsParse allowBuilds placeholders and drop undecided entries when applying +37/-3

Parse allowBuilds placeholders and drop undecided entries when applying

• Introduces 'AllowBuild' (bool or string), keeps raw values in 'WorkspaceSettings', and filters to decided entries when applying settings into 'Config'.

pnpm/crates/config/src/workspace_yaml.rs

state.rsDeduplicate deprecation reporting and avoid double-counting direct deps +18/-2

Deduplicate deprecation reporting and avoid double-counting direct deps

• Adds bookkeeping to report a deprecated package once, prevents subdep summaries from counting packages later discovered as direct dependencies, and aligns output with pnpm’s reporting semantics.

pnpm/crates/default-reporter/src/state.rs

freshness.rsMap staleness reasons to pnpm setting names +39/-0

Map staleness reasons to pnpm setting names

• Adds 'StalenessReason::setting_name()' to distinguish config drift from manifest drift and to report pnpm-compatible setting identifiers.

pnpm/crates/lockfile/src/freshness.rs

build_modules.rsPropagate user agent into build scripts and preserve ignored-build patch hashes +14/-2

Propagate user agent into build scripts and preserve ignored-build patch hashes

• Threads 'user_agent' into lifecycle build execution environment and records ignored builds using package ids that retain '(patch_hash=...)' so distinct patched copies remain distinguishable.

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

install.rsIntroduce ERR_PNPM_LOCKFILE_CONFIG_MISMATCH for config drift +21/-2

Introduce ERR_PNPM_LOCKFILE_CONFIG_MISMATCH for config drift

• Adds a dedicated 'LockfileConfigMismatch' install error and maps freshness failures to it when drift is in configuration (e.g., overrides, catalogs), while retaining OutdatedLockfile for manifest drift.

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

install_frozen_lockfile.rsPass user agent into build phase execution +1/-0

Pass user agent into build phase execution

• Wires 'config.user_agent' into the frozen-lockfile build phase via 'BuildModules'.

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

install_package_by_snapshot.rsStamp user agent onto lifecycle script environments +2/-2

Stamp user agent onto lifecycle script environments

• Ensures lifecycle scripts executed during snapshot installs receive 'npm_config_user_agent' derived from config.

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

patch.rsStamp user agent onto patch-related script environments +1/-1

Stamp user agent onto patch-related script environments

• Ensures patch command execution uses the configured user agent in the executor environment.

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

apply.rsSwitch patch application to pnpm-tolerant matcher +10/-8

Switch patch application to pnpm-tolerant matcher

• Replaces 'diffy::apply' usage with a custom tolerant applier while retaining 'diffy' parsing, and preserves error messaging shape for diagnostics.

pnpm/crates/patching/src/apply.rs

tolerant.rsImplement tolerant hunk matching (trim whitespace + fuzz window) +197/-0

Implement tolerant hunk matching (trim whitespace + fuzz window)

• Adds a patch applier that matches pnpm/patch-package tolerances: trailing whitespace-insensitive comparisons, retry offsets within ±20 lines, and correct handling of missing final newlines and CRLF/LF mixes.

pnpm/crates/patching/src/apply/tolerant.rs

Tests (12) +594 / -20
tests.rsAdd unit tests for regexp script selection semantics +66/-5

Add unit tests for regexp script selection semantics

• Extends selector tests to cover exact-match precedence, start fallback isolation, selection of multiple scripts, flag rejection, and treating malformed literals as plain names.

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

approve_builds.rsTest allowBuilds placeholder no longer breaks commands +31/-0

Test allowBuilds placeholder no longer breaks commands

• Adds an integration test that inserts pnpm’s placeholder string into 'pnpm-workspace.yaml' and verifies commands still run and reporting treats it as undecided.

pnpm/crates/cli/tests/approve_builds.rs

lifecycle_scripts.rsTest npm_config_user_agent is set for install and run scripts +44/-0

Test npm_config_user_agent is set for install and run scripts

• Adds an integration test asserting 'npm_config_user_agent' includes 'pnpm/<version>' in install lifecycle and 'pnpm run' contexts.

pnpm/crates/cli/tests/lifecycle_scripts.rs

run.rsIntegration tests for regexp selectors and flag rejection +54/-0

Integration tests for regexp selectors and flag rejection

• Adds Unix-only tests verifying '/pattern/' executes all matching scripts for both 'pnpm run' and 'pnpm <selector>' fallback, and that flags are rejected with the pnpm error code.

pnpm/crates/cli/tests/run.rs

run_recursive.rsIntegration test for recursive regexp selector running multiple scripts +47/-0

Integration test for recursive regexp selector running multiple scripts

• Adds a workspace test verifying recursive runs execute every matching script per project and skip projects with no matches.

pnpm/crates/cli/tests/run_recursive.rs

with.rsIntegration test for concurrent pinned-engine installs +43/-0

Integration test for concurrent pinned-engine installs

• Adds a concurrency test that spawns multiple 'pnpm with <version>' children simultaneously and asserts all succeed on a cold cache.

pnpm/crates/cli/tests/with.rs

tests.rsTest allowBuilds placeholder parsing and policy application +29/-4

Test allowBuilds placeholder parsing and policy application

• Updates allowBuilds assertions to use 'AllowBuild::decided', and adds a test ensuring placeholder strings deserialize and do not become explicit denies in applied config.

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

tests.rsTest deprecation reporting is emitted once per package +51/-1

Test deprecation reporting is emitted once per package

• Adds a regression test ensuring repeated deprecation events collapse to a single output line and are not double-counted in summaries.

pnpm/crates/default-reporter/src/tests.rs

tests.rsUnit tests for DirLock behavior +48/-0

Unit tests for DirLock behavior

• Adds tests covering acquire/release, contention timeout, and abandoned lock takeover.

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

tests.rsUpdate build_modules tests for new user_agent parameter +20/-0

Update build_modules tests for new user_agent parameter

• Plumbs a 'user_agent' value through all 'BuildModules' test constructions to match the new required field.

pnpm/crates/package-manager/src/build_modules/tests.rs

tests.rsUpdate frozen-lockfile drift tests to expect config-mismatch error +6/-10

Update frozen-lockfile drift tests to expect config-mismatch error

• Adjusts tests to assert 'LockfileConfigMismatch' with the correct pnpm setting name for overrides and package extensions drift.

pnpm/crates/package-manager/src/install/tests.rs

tests.rsAdd regression tests for tolerant patch application edge cases +155/-0

Add regression tests for tolerant patch application edge cases

• Covers missing final newline context hunks, CRLF/LF tolerance, fuzzing window relocation, newline add/remove semantics, baseline matching across multiple hunks, and mismatch rejection.

pnpm/crates/patching/src/apply/tolerant/tests.rs

Documentation (7) +35 / -0
allow-builds-placeholder-is-parsable.mdDocument allowBuilds placeholder compatibility fix +5/-0

Document allowBuilds placeholder compatibility fix

• Adds a changeset noting that pnpm-scaffolded placeholder strings in 'allowBuilds' no longer break config parsing, and undecided entries keep default-deny behavior.

.changeset/allow-builds-placeholder-is-parsable.md

concurrent-package-manager-switch.mdDocument fix for concurrent pinned-engine install race +5/-0

Document fix for concurrent pinned-engine install race

• Adds a changeset describing serialization of pinned pnpm engine installs to avoid store-slot clobbering under concurrent 'pnpm run' children.

.changeset/concurrent-package-manager-switch.md

deprecated-and-ignored-build-lists.mdDocument deprecation dedupe and ignored-build keying changes +5/-0

Document deprecation dedupe and ignored-build keying changes

• Adds a changeset describing deprecation logging being emitted once per package and ignored builds being reported with patch-hash suffixes.

.changeset/deprecated-and-ignored-build-lists.md

lockfile-config-mismatch-code.mdDocument ERR_PNPM_LOCKFILE_CONFIG_MISMATCH for settings drift +5/-0

Document ERR_PNPM_LOCKFILE_CONFIG_MISMATCH for settings drift

• Adds a changeset describing a more specific frozen-install failure when lockfile settings drift from current configuration.

.changeset/lockfile-config-mismatch-code.md

npm-config-user-agent-in-scripts.mdDocument propagation of npm_config_user_agent to all scripts +5/-0

Document propagation of npm_config_user_agent to all scripts

• Adds a changeset describing consistent 'npm_config_user_agent' in lifecycle scripts, run/exec, and dlx contexts.

.changeset/npm-config-user-agent-in-scripts.md

patch-applier-tolerances.mdDocument pnpm-tolerant patch application behavior +5/-0

Document pnpm-tolerant patch application behavior

• Adds a changeset describing tolerant patch matching for CRLF/LF, missing final newline, and nearby-hunk retry behavior.

.changeset/patch-applier-tolerances.md

regexp-script-selectors.mdDocument RegExp-based script selectors for run +5/-0

Document RegExp-based script selectors for run

• Adds a changeset describing '/pattern/' selectors executing all matching scripts and rejecting flags, matching pnpm behavior.

.changeset/regexp-script-selectors.md

Other (5) +94 / -0
Cargo.lockLockfile update for new dependencies +2/-0

Lockfile update for new dependencies

• Updates the workspace lockfile to include 'regex' and 'same-file' and their transitive dependencies.

Cargo.lock

Cargo.tomlAdd workspace dependencies for regex support and same-file checks +1/-0

Add workspace dependencies for regex support and same-file checks

• Adds 'regex' and 'same-file' to workspace dependencies to support script selector parsing and inode equality checks.

Cargo.toml

Cargo.tomlWire new deps into CLI crate +2/-0

Wire new deps into CLI crate

• Adds 'regex' and 'same-file' as workspace dependencies for CLI functionality changes.

pnpm/crates/cli/Cargo.toml

dir_lock.rsAdd cross-process advisory directory lock utility +87/-0

Add cross-process advisory directory lock utility

• Implements 'DirLock' using atomic directory creation with bounded wait and abandoned-lock takeover, and releases the lock on drop.

pnpm/crates/fs/src/dir_lock.rs

lib.rsExport DirLock from fs crate +2/-0

Export DirLock from fs crate

• Registers the new 'dir_lock' module and re-exports 'DirLock' for use by other crates.

pnpm/crates/fs/src/lib.rs

@greptile-apps

greptile-apps Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5

The PR is not yet safe to merge because the directory-lock ownership fix still permits a stale holder to remove a successor during owner-token publication.

The successor lock directory becomes visible before its owner token is written, while stale-holder cleanup interprets a missing token as ownership and removes that directory; this can reintroduce concurrent writes to the shared engine slot.

Files Needing Attention: pnpm/crates/fs/src/dir_lock.rs

Reviews (5): Last reviewed commit: "fix(cli): stop a no-op script erasing it..." | Re-trigger Greptile

Comment thread pnpm/crates/fs/src/dir_lock.rs Resolved
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b378a458-5920-4cf1-b92b-be27377846f7

📥 Commits

Reviewing files that changed from the base of the PR and between 606a89b and d2fd3c9.

📒 Files selected for processing (7)
  • pnpm/crates/cli/src/cli_args/run/recursive.rs
  • pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pnpm/crates/cli/tests/lifecycle_scripts.rs
  • pnpm/crates/cli/tests/run_recursive.rs
  • pnpm/crates/workspace-manifest-writer/src/edit.rs
  • pnpm/crates/workspace-manifest-writer/src/tests.rs
  • pnpm11/exec/commands/src/runRecursive.ts

📝 Walkthrough

Walkthrough

This PR aligns Rust and TypeScript CLI behavior with pnpm across build policy parsing, lifecycle environments, regexp script execution, concurrent engine installation, lockfile diagnostics, deprecation reporting, and tolerant patch application.

Changes

pnpm 12 compatibility fixes

Layer / File(s) Summary
Allow-build policy and reporting
pnpm/crates/config/..., pnpm/crates/package-manager/..., pnpm/crates/default-reporter/..., pnpm/crates/workspace-manifest-writer/...
Preserves undecided allowBuilds placeholders, filters them from policy application, records patch-aware ignored-build keys, deduplicates deprecation output, and preserves YAML comments.
Configured user-agent propagation
pnpm/crates/cli/src/cli_args/{dlx,exec,run}.rs, pnpm/crates/package-manager/..., pnpm/crates/cli/tests/lifecycle_scripts.rs
Passes the configured user-agent through spawned commands, lifecycle hooks, builds, fetchers, and tests.
Regexp script selectors and failure tracking
pnpm/crates/cli/src/cli_args/run*, pnpm/crates/cli/tests/run*.rs, pnpm11/exec/commands/..., Cargo.toml
Adds regexp matching for single-project and recursive runs, exact-name precedence, unsupported-flag diagnostics, and failure-preserving recursive summaries.
Concurrent engine installation
pnpm/crates/fs/..., pnpm/crates/cli/src/cli_args/{self_update,with}/..., pnpm/crates/cli/tests/with.rs
Adds directory locking and atomic engine-slot replacement for concurrent cold-cache installs.
Lockfile configuration mismatch errors
pnpm/crates/lockfile/src/freshness.rs, pnpm/crates/package-manager/src/install*
Reports setting-specific lockfile mismatches with ERR_PNPM_LOCKFILE_CONFIG_MISMATCH.
Tolerant patch application
pnpm/crates/patching/src/apply/...
Applies hunks with whitespace, newline, CRLF/LF, and nearby-line-position tolerance.

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

Assessment against linked issues

Objective Addressed Explanation
Accept allowBuilds placeholders and align deprecated/ignored-build reporting [`#13322`] ✅
Propagate configured user agents and support regexp script selectors [`#13322`] ✅
Make concurrent package-manager switching safe [`#13322`] ✅
Align patch application and lockfile mismatch behavior [`#13322`] ✅
Preserve broader compatibility requirements, including legacy lockfile reading and peer-dependency suffix generation [`#13322`] ❓ Those behaviors are not represented in the provided changes.

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#13074 — Modifies regexp script-selector matching and execution behavior.
  • pnpm/pnpm#13081 — Relates to lockfile freshness and configuration mismatch reporting.
  • pnpm/pnpm#13246 — Relates to the allowBuilds persistence and editing path.

Suggested labels: product: pacquet, product: pnpm@11

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-13322

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Action required

1. pnpm11 status can end running 🐞 Bug ≡ Correctness
Description
The new failedPrefixes guard prevents overwriting failure with passed, but a later matched script
can still set the project status back to 'running' after a failure; its success then won’t set
'passed' due to the guard, leaving the final summary status as 'running'. This can happen under
limited concurrency when later tasks start after earlier failures.
Code

pnpm11/exec/commands/src/runRecursive.ts[R182-188]

+          if (!failedPrefixes.has(prefix)) {
+            result[prefix].status = 'passed'
+            result[prefix].duration = getExecutionDuration(startTime)
+          }
        } catch (err: unknown) {
          assert(util.types.isNativeError(err))
+          failedPrefixes.add(prefix)
Relevance

⭐⭐⭐ High

Another correctness/status overwrite in runRecursive; similar fixes accepted to preserve
failure/passed summaries.

PR-#13074
PR-#12925

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation sets status to 'running' when a script starts, and the new guard only prevents
setting 'passed' after failure; therefore a later start can overwrite failure to running, and later
success won’t correct it.

pnpm11/exec/commands/src/runRecursive.ts[119-135]
pnpm11/exec/commands/src/runRecursive.ts[182-196]

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

### Issue description
`failedPrefixes` blocks the 'passed' write after a failure, but the code still writes `result[prefix].status = 'running'` unconditionally when any later matched script starts. If that later script succeeds, the guarded success path won’t set 'passed', so the project can remain 'running' at end.

### Issue Context
This ordering is plausible when `limitRun` concurrency is below the number of selected scripts for a given prefix.

### Fix Focus Areas
- pnpm11/exec/commands/src/runRecursive.ts[100-107]
- pnpm11/exec/commands/src/runRecursive.ts[182-188]

### Suggested fix
- Gate the 'running' assignment similarly:
 - e.g. `if (!failedPrefixes.has(prefix)) result[prefix].status = 'running'`
- Or make the completion path explicitly restore/retain 'failure' regardless of intermediate 'running' writes (status transitions should be monotonic once failed).

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


2. DirLock drops successor lock ✓ Resolved 🐞 Bug ☼ Reliability
Description
DirLock::drop treats a missing owner file as releasable and removes the lock directory, so a stale
holder can delete a successor’s lock if it drops after the successor’s create_dir but before the
successor writes OWNER_FILE. This defeats the cross-process serialization and can reintroduce
concurrent engine installs into the same shared slot.
Code

pnpm/crates/fs/src/dir_lock.rs[R95-100]

+        match fs::read_to_string(self.path.join(OWNER_FILE)) {
+            Ok(owner) if owner != self.token => return,
+            Err(error) if error.kind() != io::ErrorKind::NotFound => return,
+            _ => {}
+        }
+        let _ = fs::remove_dir_all(&self.path);
Relevance

⭐⭐ Medium

Race seems plausible but requires design-level reasoning; unclear if maintainers will change locking
semantics now.

PR-#12991
PR-#13306

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The lock directory is created before writing OWNER_FILE, leaving a race window; Drop currently
treats OWNER_FILE NotFound as acceptable and removes the directory, which can delete a successor
lock created in that window.

pnpm/crates/fs/src/dir_lock.rs[53-86]
pnpm/crates/fs/src/dir_lock.rs[89-101]

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

### Issue description
`DirLock::drop()` can remove a successor’s lock directory if it observes `OWNER_FILE` as missing (a valid transient state right after the successor wins `create_dir`). This can reintroduce the very race the lock is meant to prevent.

### Issue Context
- `DirLock::acquire()` creates the directory, then best-effort writes `OWNER_FILE`.
- `DirLock::drop()` currently proceeds to `remove_dir_all()` when `OWNER_FILE` is `NotFound`.

### Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[63-70]
- pnpm/crates/fs/src/dir_lock.rs[91-100]

### Suggested fix
- Make `Drop` conservative: if `OWNER_FILE` is missing, **do not** remove the directory (assume it may be a successor that hasn’t published ownership yet).
- Consider tightening `acquire()` so ownership publication is not best-effort for correctness (e.g., if writing `OWNER_FILE` fails, remove the directory and treat acquisition as failed / retry), so `OWNER_FILE` absence becomes truly exceptional.

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



Remediation recommended

3. Passed overwritten as skipped ✓ Resolved 🐞 Bug ≡ Correctness
Description
In recursive runs with a /pattern/ selector, a project can run one matched script successfully and
then hit a later matched script that is empty/no-op; mark_skipped() will overwrite the project’s
Status::Passed with Status::Skipped. This produces an incorrect per-project summary and can mislead
tooling consuming the report summary.
Code

pnpm/crates/cli/src/cli_args/run/recursive.rs[R270-277]

+/// Record that a selected script had nothing to run, unless one of this
+/// project's other selected scripts already failed — see the
+/// `project_failed` bookkeeping in [`run_recursive`].
+fn mark_skipped(entry: &mut ExecutionStatus, project_failed: bool) {
+    if !project_failed {
+        entry.status = Status::Skipped;
+    }
+}
Relevance

⭐⭐⭐ High

Correctness bug: skip should not override already-passed project status in summary.

PR-#13074
PR-#13202

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The loop sets Status::Passed on success, but later calls to mark_skipped for empty/no-op scripts
can overwrite that status because mark_skipped doesn’t check current status.

pnpm/crates/cli/src/cli_args/run/recursive.rs[136-241]
pnpm/crates/cli/src/cli_args/run/recursive.rs[270-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
`mark_skipped()` unconditionally sets `Status::Skipped` when `project_failed` is false. If a project already succeeded for an earlier selected script, a later selected script that is empty/no-op will incorrectly flip the project status from `passed` to `skipped`.

### Issue Context
This can happen because a `/pattern/` selector may match multiple scripts in one project, and some of those scripts may be empty bodies or pnpm no-ops.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/run/recursive.rs[144-166]
- pnpm/crates/cli/src/cli_args/run/recursive.rs[217-221]
- pnpm/crates/cli/src/cli_args/run/recursive.rs[269-277]

### Suggested fix
- Track whether the project has executed any real command (e.g., `project_ran_any`), and only set `Status::Skipped` when nothing has run yet.
 - Alternatively: in `mark_skipped`, only set `Skipped` if the current status is still `Queued` (or `Queued|Running` depending on invariants), and never overwrite `Passed`.

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


4. Historical comment in DirLock ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A new comment references prior behavior (before the file existed), which violates the requirement
that comments describe current behavior only. Keeping historical phrasing in source makes future
maintenance and auditing harder because it blurs the current contract and rationale.
Code

pnpm/crates/fs/src/dir_lock.rs[R65-68]

+                    // Best-effort: an unwritable owner file only costs
+                    // this holder the stale-successor check below, which
+                    // is what the code did before the file existed.
+                    let _ = fs::write(path.join(OWNER_FILE), &token);
Relevance

⭐⭐⭐ High

Repo enforces non-historical comment phrasing; likely to reword to present-tense behavior.

PR-#13306
PR-#13343
PR-#12991

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 772199 prohibits historical phrasing in comments. The added comment explicitly
references past implementation state ("before the file existed"), rather than documenting the
current behavior/contract.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/fs/src/dir_lock.rs[65-68]

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 comment in `DirLock::acquire` refers to historical behavior ("before the file existed"), which violates the rule that comments must describe current behavior rather than past implementations.

## Issue Context
This comment is adjacent to the best-effort write of the lock owner token file and should explain the *current* implications (what functionality is lost when the file can't be written), without referencing prior versions.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[65-68]

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


5. DirLock hides write errors 🐞 Bug ☼ Reliability
Description
DirLock::acquire collapses failures to write the owner token file into Ok(None) and discards the
underlying IO error, making “lock unavailable” indistinguishable from “lock mechanism failed”. In
the engine install path (which is explicitly trying to prevent concurrent destructive installs into
a shared slot), this can silently re-enable the race while obscuring the real root cause.
Code

pnpm/crates/fs/src/dir_lock.rs[R65-76]

+                    if fs::write(path.join(OWNER_FILE), &token).is_ok() {
+                        return Ok(Some(DirLock { path, token }));
+                    }
+                    // Without its owner record this lock cannot tell, at
+                    // release time, whether it is still the one it took.
+                    // Rather than hold an unidentifiable lock, give the
+                    // directory back and report the lock as not taken —
+                    // the caller's documented degradation is to proceed
+                    // unserialized, which is no worse than not having
+                    // tried.
+                    let _ = fs::remove_dir_all(&path);
+                    return Ok(None);
Relevance

⭐⭐ Medium

DirLock is documented to degrade to “no lock”; surfacing write errors may conflict with prior
best-effort error handling.

PR-#12841

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The lock acquisition path explicitly discards owner-file write failures and reports them as “lock
not taken”. The engine-install path describes the lock as preventing concurrent destructive slot
restaging, but uses a lock API that can degrade to no-lock without surfacing an IO failure reason.

pnpm/crates/fs/src/dir_lock.rs[62-76]
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[98-106]
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs[159-174]

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

## Issue description
`DirLock::acquire()` currently treats *any* failure to write the owner token file as a non-error (`Ok(None)`), after best-effort cleanup. This conflates genuine filesystem failures (disk full, permission/ACL issues, read-only FS, transient IO errors) with ordinary lock contention/timeout, so callers can’t distinguish “couldn’t get lock” from “lock is broken”.

## Issue Context
This lock is used to serialize destructive work on a shared engine-install slot; silently proceeding without a lock on real IO failures can reintroduce the race the lock was added to prevent and makes diagnosis harder.

## Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[65-76]

## Suggested fix
- Capture the `fs::write(...)` error and return it as `Err(io::Error)` (after best-effort cleanup), instead of returning `Ok(None)`.
- Keep `Ok(None)` reserved for contention/timeout/abandoned takeover cases.
- If some callers intentionally want “proceed without lock on any failure”, they can explicitly downgrade `Err` to `None` at the call site (but at least the distinction is available).

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


View more (3)
6. Comment scan mishandles quotes ✓ Resolved 🐞 Bug ≡ Correctness
Description
comment_start() treats any "/' byte as opening/closing a quoted scalar but doesn’t follow YAML
escaping rules (e.g., \" in double quotes, '' in single quotes) and can even treat quote
characters inside plain scalars as delimiters. This can mis-detect a trailing # comment boundary,
causing replace_bool_value_at() to drop a real comment or to preserve part of the old value as a
comment when rewriting allowBuilds entries.
Code

pnpm/crates/workspace-manifest-writer/src/edit.rs[R1108-1126]

+/// Byte offset of a value's trailing comment, if it has one. A `#` opens
+/// a comment only when whitespace precedes it and it sits outside a
+/// quoted scalar, so a `#` within the value itself is not mistaken for
+/// one.
+fn comment_start(value: &str) -> Option<usize> {
+    let bytes = value.as_bytes();
+    let mut quote: Option<u8> = None;
+    for (idx, &byte) in bytes.iter().enumerate() {
+        match quote {
+            Some(open) if byte == open => quote = None,
+            Some(_) => {}
+            None => match byte {
+                b'"' | b'\'' => quote = Some(byte),
+                b'#' if idx > 0 && bytes[idx - 1].is_ascii_whitespace() => return Some(idx),
+                _ => {}
+            },
+        }
+    }
+    None
Relevance

⭐⭐ Medium

Correct YAML quote/escape handling is subtle; no close precedent on implementing full YAML escaping
in this helper.

PR-#13172
PR-#13283

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new comment_start() implementation uses simplistic quote toggling and whitespace checks, and
the newly-added tests indicate correctness of # handling and trailing comment preservation matters
for this code path.

pnpm/crates/workspace-manifest-writer/src/edit.rs[1108-1126]
pnpm/crates/workspace-manifest-writer/src/tests.rs[1273-1301]

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

### Issue description
`comment_start()` is a hand-rolled scanner that tries to find the start of a trailing `#` comment while ignoring `#` inside quoted scalars. The current implementation toggles quote state on any `"`/`'` byte and doesn’t handle YAML escaping, so it can incorrectly classify `#` as a comment (or not a comment), which breaks the “preserve trailing comment” contract when `replace_bool_value_at()` rewrites a boolean.

### Issue Context
This logic is used while rewriting `allowBuilds` entries and is explicitly relied on by tests that expect comments to be preserved and `#` inside quotes not to be treated as a comment.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/edit.rs[1108-1128]

### What to change
- Make `comment_start()` YAML-shape-aware rather than quote-byte aware:
 - If the trimmed value starts with `"`: scan for the closing `"` while honoring backslash-escapes (`\\` and `\"`).
 - If it starts with `'`: scan for the closing `'` while honoring YAML single-quote escaping (`''` means a literal `'` and does **not** close the scalar).
 - Otherwise treat it as a plain scalar and find the first `#` preceded by whitespace (no quote tracking in the middle of the value).
- Add a regression test covering escaped quotes, e.g. a value like `"a \"#\" b" # why` should preserve only `# why` as the comment and not treat the `#` inside the escaped quotes as comment-start.

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


7. Rename lacks retry ✓ Resolved 🐞 Bug ☼ Reliability
Description
force_link() uses a single fs::rename(staged, dest) to swap in the linked binary; on Windows
this can fail transiently (AV/indexer handle contention) and currently causes self-update/engine
relinking to fail instead of retrying.
Code

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[R499-528]

+    // The engine's global-virtual-store slot is shared by every process
+    // on the host, and each of them re-links the native binary on its way
+    // through. Unlinking a `dest` that is already the wanted inode would
+    // pull the executable out from under a concurrent process running it,
+    // so the already-linked case is left alone, and a `dest` that must
+    // actually change is replaced by a rename rather than an unlink —
+    // a rename swaps the dirent and leaves a running process on the inode
+    // it opened.
+    if same_file::is_same_file(src, dest).unwrap_or(false) {
+        return Ok(());
+    }
+    let file_name = dest.file_name().unwrap_or(dest.as_os_str()).to_string_lossy().into_owned();
+    let staged = dest.with_file_name(format!(".{file_name}.{}.pacquet-tmp", std::process::id()));
+    match fs::remove_file(&staged) {
        Ok(()) => {}
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
        Err(err) => return Err(err),
    }
-    fs::hard_link(src, dest)?;
+    fs::hard_link(src, &staged)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
-        fs::set_permissions(dest, fs::Permissions::from_mode(0o755))?;
+        if let Err(err) = fs::set_permissions(&staged, fs::Permissions::from_mode(0o755)) {
+            let _ = fs::remove_file(&staged);
+            return Err(err);
+        }
    }
-    Ok(())
+    fs::rename(&staged, dest).inspect_err(|_| {
+        let _ = fs::remove_file(&staged);
+    })
Relevance

⭐⭐ Medium

Retry/backoff for Windows rename is plausible but adds policy/complexity; no close accepted/rejected
precedent found.

PR-#13076

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
force_link() currently does a bare fs::rename with no retry. Elsewhere, the repo explicitly
documents and mitigates transient Windows rename failures with a retry budget/backoff, indicating
this failure mode is expected in practice.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[496-528]
pnpm/crates/fs/src/ensure_file.rs[441-487]

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

### Issue description
`force_link()` performs a single `fs::rename` to atomically replace the destination binary. On Windows, `rename` can intermittently fail with `PermissionDenied`/`ResourceBusy` due to Defender or other tooling briefly holding the destination, making self-update / pinned-engine relinking flaky.

### Issue Context
The repo already encodes this behavior and mitigation in `ensure_file.rs` (`rename_with_retry`) specifically for transient Windows rename failures.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[496-528]
- pnpm/crates/fs/src/ensure_file.rs[441-487]

### Suggested fix
Implement a bounded retry loop around the final `rename(staged, dest)` in `force_link`, mirroring `rename_with_retry` semantics:
- retry only transient kinds (`PermissionDenied`, `ResourceBusy`)
- backoff with a small capped sleep
- total budget ~60s (or a smaller budget if appropriate for this path)
- preserve the current cleanup behavior of deleting `staged` on final failure.

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


8. Repeated regex compilation ✓ Resolved 🐞 Bug ➹ Performance
Description
run_recursive() calls specified_scripts() per project, and for /pattern/ selectors this
recompiles the same Regex for every workspace project, adding avoidable CPU work in large
workspaces.
Code

pnpm/crates/cli/src/cli_args/run.rs[R475-491]

+pub(super) fn specified_scripts(manifest: &Value, name: &str) -> Result<Vec<String>, RunError> {
+    let scripts = manifest.get("scripts").and_then(Value::as_object);
+    let has_script = scripts
        .and_then(|scripts| scripts.get(name))
        .and_then(Value::as_str)
        .is_some_and(|script| !script.is_empty());

    if has_script {
-        return vec![name.to_string()];
+        return Ok(vec![name.to_string()]);
    }
-    if name == "start" {
-        return vec![name.to_string()];
+    let Some(selector) = try_build_regex_from_command(name)? else {
+        return Ok(Vec::new());
+    };
+    let Some(scripts) = scripts else {
+        return Ok(Vec::new());
+    };
+    Ok(scripts.keys().filter(|script| selector.is_match(script)).cloned().collect())
Relevance

⭐⭐ Medium

Mixed precedent on reusing per-call constructed objects; some accepted, similar reuse suggestion
also previously rejected.

PR-#13207
PR-#12971

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
specified_scripts() compiles a regex via try_build_regex_from_command and Regex::new(pattern);
run_recursive() invokes specified_scripts() inside the per-project loop, so regex compilation
repeats once per project when using regex selectors.

pnpm/crates/cli/src/cli_args/run.rs[470-509]
pnpm/crates/cli/src/cli_args/run/recursive.rs[134-143]

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

### Issue description
Recursive runs recompile the same `/pattern/` selector regex once per project (`Regex::new(pattern)` inside `specified_scripts`), which is unnecessary overhead on large workspaces.

### Issue Context
- The selector depends only on the CLI argument (`script_name`), not on each manifest.
- Exact-name hits short-circuit before regex compilation; the repeated compilation happens for regex selectors that are not exact script names.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/run/recursive.rs[75-142]
- pnpm/crates/cli/src/cli_args/run.rs[470-509]

### Suggested fix
In `run_recursive`, parse the selector once before iterating projects:
- If `script_name` is an exact script name, keep current behavior.
- If it is a regex literal, compile `Regex` once and pass it into a helper that, per project:
 - returns `[script_name]` if an exact script exists
 - otherwise filters keys with the precompiled regex.
This avoids `Regex::new` in the per-project loop while preserving the “exact match wins” rule.

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



Informational

9. Literal expect message braces ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The new lifecycle script test uses expect("read {file}"), which does not interpolate in Rust and
will print the literal {file} on failure, making it harder to diagnose which of the three files
failed to read.
Code

pnpm/crates/cli/tests/lifecycle_scripts.rs[R1493-1497]

+        for file in ["preinstall-ua.txt", "run-ua.txt", "exec-ua.txt"] {
+            let user_agent = fs::read_to_string(workspace.join(file)).expect("read {file}");
+            let (name, rest) = user_agent.split_once('/').unwrap_or((&user_agent, ""));
+            assert_eq!(name, "pnpm", "{file}: {user_agent}");
+            assert!(!rest.is_empty(), "{file} carries a version: {user_agent}");
Relevance

⭐⭐⭐ High

Repo favors improving test failure diagnostics; fixing literal braces is trivial and low-risk.

PR-#13127
PR-#13372

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited line shows a non-interpolated string literal inside expect(), so failures will not
include the actual file value.

pnpm/crates/cli/tests/lifecycle_scripts.rs[1493-1497]

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 test uses `expect("read {file}")`, but Rust does not interpolate `{file}` in normal string literals, so the panic message is not informative.

### Issue Context
This loop reads three different output files; a good error message should name which one failed.

### Fix Focus Areas
- pnpm/crates/cli/tests/lifecycle_scripts.rs[1493-1497]

### What to change
Replace:
```rust
.expect("read {file}")
```
with one of:
```rust
.unwrap_or_else(|err| panic!("read {file}: {err}"))
```
or:
```rust
.expect(&format!("read {file}"))
```

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


10. Retry budget comment mismatch ✓ Resolved 🐞 Bug ➹ Performance
Description
swap_into_place() claims “~250ms” total retry time, but the implemented linear backoff sleeps
25ms×attempt over attempts 1..9 (~1125ms) plus I/O. This can add unexpected latency under contention
and misleads future maintainers.
Code

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[R540-552]

+    /// Ten tries over ~250ms: long enough to outlast a scanner's handle,
+    /// short enough not to stall a command that is genuinely blocked.
+    const ATTEMPTS: usize = 10;
+    const BACKOFF: std::time::Duration = std::time::Duration::from_millis(25);
+
+    for attempt in 1..ATTEMPTS {
+        match fs::rename(staged, dest) {
+            Ok(()) => return Ok(()),
+            // A missing staged file is not contention — nothing will
+            // change on a retry, so fail now with the real error.
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Err(err),
+            Err(_) => std::thread::sleep(BACKOFF * u32::try_from(attempt).unwrap_or(1)),
+        }
Relevance

⭐⭐⭐ High

They frequently fix misleading comments/behavior mismatches; adjust comment or backoff to match
budget.

PR-#13008
PR-#12992

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The code multiplies the sleep duration by the attempt number, making the total delay far larger than
the stated budget.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[531-555]

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 retry loop’s total sleep time is ~1.1s (25ms * (1+…+9)), but the comment says ~250ms.

### Issue Context
This code runs in engine relinking / self-update paths and can be hit under AV/indexer contention.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs[540-552]

### Suggested fix
- Either update the comment to reflect the real upper bound, or change the retry strategy to match the documented ~250ms budget (e.g., constant 25ms sleeps, fewer attempts, or a deadline-based loop).

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


11. Abandoned-lock test may flake ✓ Resolved 🐞 Bug ☼ Reliability
Description
DirLock treats a lock as abandoned only when age > abandoned_after; the test uses
abandoned_after = 0 and expects immediate takeover, which can be timing/filesystem dependent if
the directory mtime yields age == 0.
Code

pnpm/crates/fs/src/dir_lock.rs[R79-84]

+fn is_abandoned(path: &Path, abandoned_after: Duration) -> bool {
+    let Ok(modified) = fs::metadata(path).and_then(|meta| meta.modified()) else {
+        return false;
+    };
+    SystemTime::now().duration_since(modified).is_ok_and(|age| age > abandoned_after)
+}
Relevance

⭐⭐⭐ High

Team has repeatedly accepted de-flaking timing/state-sensitive tests; zero-duration boundary makes
this test nondeterministic.

PR-#12926
PR-#13256

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation checks age > abandoned_after, while the test sets abandoned_after to zero and
also uses wait = 0, so if age is computed as zero the acquire path will time out immediately and
return None instead of taking over.

pnpm/crates/fs/src/dir_lock.rs[79-84]
pnpm/crates/fs/src/dir_lock/tests.rs[33-44]

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

### Issue description
`DirLock`’s abandonment check uses a strict `age > abandoned_after`. The test case that uses `abandoned_after = Duration::ZERO` and `wait = Duration::ZERO` can be non-deterministic on platforms/filesystems where the directory’s `modified` time is equal to (or effectively rounded to) “now”, producing `age == 0` and therefore not abandoned.

### Issue Context
This is primarily a test robustness issue; production callers use non-zero thresholds (e.g., 30 minutes).

### Fix Focus Areas
- pnpm/crates/fs/src/dir_lock.rs[79-84]
- pnpm/crates/fs/src/dir_lock/tests.rs[33-44]

### Suggested fix
Prefer making the test deterministic by explicitly aging the lock directory before acquisition (e.g., set mtime into the past via a test-only helper/crate, or sleep briefly) rather than relying on `Duration::ZERO` semantics. Alternatively, if you want `0` to mean “always abandoned”, change the check to `age >= abandoned_after` and update docs/tests accordingly.

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


View more (1)
12. Duplicated guard comment block ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
In runRecursive.ts, the same four-line explanatory comment is duplicated back-to-back immediately
above the failedPrefixes guard and the subsequent result[prefix].status = 'running' assignment.
This redundancy adds noise in subtle failure-bookkeeping logic and increases the risk of future
edits updating only one copy.
Code

pnpm11/exec/commands/src/runRecursive.ts[R133-140]

+        // Guarded for the same reason as the 'passed' write below: a
+        // sibling script starting after this project already failed would
+        // otherwise reset it, and 'running' is no more a failure than
+        // 'passed' is as far as countFailures is concerned.
+        // Guarded for the same reason as the 'passed' write below: a
+        // sibling script starting after this project already failed would
+        // otherwise reset it, and 'running' is no more a failure than
+        // 'passed' is as far as countFailures is concerned.
Relevance

⭐ Low

Repo has rejected requests to remove/shorten “duplicated” call-site comments to avoid drift/noise.

PR-#13288
PR-#13133

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713467 calls for avoiding redundant comments, and the cited section shows the exact
same four comment lines appearing twice in a row immediately before the guard and the guarded status
write; because the text is duplicated verbatim, the second block adds no new rationale or intent
beyond the first, serving only as unnecessary repetition.

Rule 713467: Avoid redundant comments that restate the code
pnpm11/exec/commands/src/runRecursive.ts[133-140]
pnpm11/exec/commands/src/runRecursive.ts[133-143]

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

## Issue description
`runRecursive.ts` contains a duplicated multi-line comment block (the exact same 4-line explanation repeated twice) immediately above the `if (!failedPrefixes.has(prefix))` guard and adjacent to the guarded write `result[prefix].status = 'running'`, which violates guidance to avoid redundant comments and creates maintainability risk.

## Issue Context
This is a maintainability-only problem, but it sits in a sensitive section of failure-bookkeeping logic that affects summary status/exit codes; having duplicated rationale text can cause confusion and drift if someone edits only one copy later.

## Fix Focus Areas
- pnpm11/exec/commands/src/runRecursive.ts[133-140]

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


Grey Divider

Qodo Logo

@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     11.0±0.25ms    33.9 MB/sec    1.00     11.1±0.19ms    33.9 MB/sec
packument/parse                1.00     38.3±0.19µs  1733.6 MB/sec    1.05     40.1±0.08µs  1653.4 MB/sec
tarball/download_dependency    1.00      2.4±0.09ms  1843.3 KB/sec    1.00      2.4±0.06ms  1843.5 KB/sec

@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to d2fd3c9

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent deleting a successor lock

Avoid reclaiming stale locks using a non-atomic check-then-delete sequence, as
it can cause race conditions. Use OS-backed file locks or let the acquisition
time out instead.

pnpm/crates/fs/src/dir_lock.rs [81-87]

 if is_abandoned(&path, abandoned_after) {
-    // Best-effort: whoever removes it first wins the next
-    // `create_dir`, and a failure just means another waiter
-    // got there first.
-    let _ = fs::remove_dir_all(&path);
-    continue;
+    // A stale observation cannot safely authorize deleting this
+    // pathname because another process may already have replaced it.
+    // Let the bounded wait expire unless ownership can be reclaimed
+    // with an atomic, platform-specific locking primitive.
+    if SystemTime::now() >= deadline {
+        return Ok(None);
+    }
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: This correctly identifies a critical Time-of-Check to Time-of-Use (TOCTOU) race condition where a concurrent process can unintentionally delete a newly acquired valid lock, breaking mutual exclusion.

High
General
Mark all-no-op projects skipped

Track if any commands actually execute during the loop and explicitly mark the
project as Skipped if all matched scripts were no-ops or empty. Ensure the
recursion guard separately maintains the Queued status when triggered.

pnpm/crates/cli/src/cli_args/run/recursive.rs [149-245]

 let mut project_failed = false;
+let mut project_ran = false;
+let mut recursion_guarded = false;
 for selected in &specified {
     let Some(script) = manifest.script(selected, true)? else {
         continue;
     };
     ...
     if script.is_empty()
         || (args.script_args().is_empty() && script == "npx only-allow pnpm")
     {
         continue;
     }
     ...
+    if env::var_os("npm_lifecycle_event").is_some_and(|event| event == **selected)
+        && env::var_os("PNPM_SCRIPT_SRC_DIR")
+            .is_some_and(|src_dir| Path::new(&src_dir) == root)
+    {
+        recursion_guarded = true;
+        continue;
+    }
+    ...
+    project_ran = true;
+    ...
+}
+if !project_ran && !recursion_guarded {
+    result[root].status = Status::Skipped;
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This catches a regression introduced in the PR where a project whose matched scripts are all empty bodies or no-ops incorrectly remains in the Queued state instead of being properly marked as Skipped.

Medium
  • Update

Previous suggestions

Suggestions up to commit 606a89b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve successful project statuses

Only update the project status to Skipped if its current status is Queued.

pnpm/crates/cli/src/cli_args/run/recursive.rs [273-277]

 fn mark_skipped(entry: &mut ExecutionStatus, project_failed: bool) {
-    if !project_failed {
+    if !project_failed && matches!(entry.status, Status::Queued) {
         entry.status = Status::Skipped;
     }
 }
Suggestion importance[1-10]: 8

__

Why: It catches a valid bug where Status::Passed or Status::Running could be incorrectly overwritten by Status::Skipped if a subsequent selected script is an empty no-op.

Medium
Parse YAML comments without corruption

Update comment_start to correctly parse escaped quotes in YAML strings and
detect comments starting at the beginning of the value.

pnpm/crates/workspace-manifest-writer/src/edit.rs [1112-1127]

 fn comment_start(value: &str) -> Option<usize> {
+    #[derive(Clone, Copy)]
+    enum Quote {
+        Single,
+        Double,
+    }
+
     let bytes = value.as_bytes();
-    let mut quote: Option<u8> = None;
-    for (idx, &byte) in bytes.iter().enumerate() {
+    let mut quote = None;
+    let mut idx = 0;
+    while idx < bytes.len() {
         match quote {
-            Some(open) if byte == open => quote = None,
-            Some(_) => {}
-            None => match byte {
-                b'"' | b'\'' => quote = Some(byte),
-                b'#' if idx > 0 && bytes[idx - 1].is_ascii_whitespace() => return Some(idx),
-                _ => {}
+            Some(Quote::Double) => match bytes[idx] {
+                b'\\' => idx += 2.min(bytes.len() - idx),
+                b'"' => {
+                    quote = None;
+                    idx += 1;
+                }
+                _ => idx += 1,
+            },
+            Some(Quote::Single) if bytes[idx] == b'\'' => {
+                if bytes.get(idx + 1) == Some(&b'\'') {
+                    idx += 2;
+                } else {
+                    quote = None;
+                    idx += 1;
+                }
+            }
+            Some(Quote::Single) => idx += 1,
+            None => match bytes[idx] {
+                b'"' => {
+                    quote = Some(Quote::Double);
+                    idx += 1;
+                }
+                b'\'' => {
+                    quote = Some(Quote::Single);
+                    idx += 1;
+                }
+                b'#' if idx == 0 || bytes[idx - 1].is_ascii_whitespace() => {
+                    return Some(idx);
+                }
+                _ => idx += 1,
             },
         }
     }
     None
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies logic bugs in the PR's YAML string lexing (escaped quotes and offset-zero comments), though the provided code contains a compilation error as 2.min is parsed as a float literal.

Medium
Use unique staging file names

Add an atomic counter to the staging file name to prevent theoretical
intra-process collisions.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs [510-517]

+static STAGED_COUNTER: std::sync::atomic::AtomicU64 =
+    std::sync::atomic::AtomicU64::new(0);
+
 let file_name = dest.file_name().unwrap_or(dest.as_os_str()).to_string_lossy().into_owned();
-let staged = dest.with_file_name(format!(".{file_name}.{}.pacquet-tmp", std::process::id()));
-match fs::remove_file(&staged) {
-    Ok(()) => {}
-    Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
-    Err(err) => return Err(err),
-}
+let nonce = STAGED_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+let staged = dest.with_file_name(format!(
+    ".{file_name}.{}.{nonce}.pacquet-tmp",
+    std::process::id(),
+));
 fs::hard_link(src, &staged)?;
Suggestion importance[1-10]: 1

__

Why: The staging path already incorporates the destination file name and process ID, avoiding collisions, as intra-process concurrency for the exact same destination file does not occur here.

Low
Suggestions up to commit bf9a078
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle escaped YAML quote delimiters

Update the comment_start string scanner to correctly handle escaped double
quotes and doubled single quotes in YAML scalars.

pnpm/crates/workspace-manifest-writer/src/edit.rs [1112-1127]

 fn comment_start(value: &str) -> Option<usize> {
     let bytes = value.as_bytes();
+    let mut idx = 0;
     let mut quote: Option<u8> = None;
-    for (idx, &byte) in bytes.iter().enumerate() {
+
+    while idx < bytes.len() {
+        let byte = bytes[idx];
         match quote {
+            Some(b'"') if byte == b'\\' => {
+                idx = (idx + 2).min(bytes.len());
+                continue;
+            }
+            Some(b'\'') if byte == b'\'' && bytes.get(idx + 1) == Some(&b'\'') => {
+                idx += 2;
+                continue;
+            }
             Some(open) if byte == open => quote = None,
             Some(_) => {}
             None => match byte {
                 b'"' | b'\'' => quote = Some(byte),
                 b'#' if idx > 0 && bytes[idx - 1].is_ascii_whitespace() => return Some(idx),
                 _ => {}
             },
         }
+        idx += 1;
     }
     None
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion resolves a significant correctness issue where escaped or doubled quotes in YAML string scalars would prematurely close the string boundary, leading to misidentified comments and potential data corruption.

High
Make lock release ownership-safe

Use an OS-backed advisory file lock instead of a directory-based lock. This
prevents a TOCTOU race condition during lock release.

pnpm/crates/fs/src/dir_lock.rs [95-100]

-match fs::read_to_string(self.path.join(OWNER_FILE)) {
-    Ok(owner) if owner != self.token => return,
-    Err(error) if error.kind() != io::ErrorKind::NotFound => return,
-    _ => {}
+// Keep an exclusively locked file handle in `DirLock`; the OS releases
+// only this acquisition's lock when the handle is dropped.
+impl Drop for DirLock {
+    fn drop(&mut self) {
+        let _ = self.file.unlock();
+    }
 }
-let _ = fs::remove_dir_all(&self.path);
Suggestion importance[1-10]: 8

__

Why: Accurately identifies a TOCTOU race condition in the lock release logic, though replacing the mechanism entirely would require a redesign.

Medium
Suggestions up to commit 394240f
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent deleting newly acquired locks

Remove the non-atomic directory deletion of abandoned locks. Rely on the timeout
fallback instead to prevent processes from inadvertently deleting a lock
recently acquired by another process.

pnpm/crates/fs/src/dir_lock.rs [74-80]

-            if is_abandoned(&path, abandoned_after) {
-                // Best-effort: whoever removes it first wins the next
-                // `create_dir`, and a failure just means another waiter
-                // got there first.
-                let _ = fs::remove_dir_all(&path);
-                continue;
-            }
+            // Do not remove an apparently stale lock here: checking its
+            // age and deleting it cannot be made atomic, so the path may
+            // already belong to a new holder. The bounded wait below
+            // safely falls back to an unlocked install.
Suggestion importance[1-10]: 9

__

Why: This addresses a critical TOCTOU (Time-of-check to time-of-use) race condition where one process could delete another's newly acquired lock directory, breaking mutual exclusion.

High
Preserve completed project statuses

Prevent mark_skipped from overwriting a completed Status::Passed state for
projects with multiple matching scripts. Update the logic to only transition the
status if it is still Status::Queued.

pnpm/crates/cli/src/cli_args/run/recursive.rs [151-277]

             let Some(script) = manifest.script(selected, true)? else {
-                mark_skipped(&mut result[root], project_failed);
+                mark_skipped(&mut result[root]);
                 continue;
             };
             ...
             if script.is_empty()
                 || (args.script_args().is_empty() && script == "npx only-allow pnpm")
             {
-                mark_skipped(&mut result[root], project_failed);
+                mark_skipped(&mut result[root]);
                 continue;
             }
 ...
-fn mark_skipped(entry: &mut ExecutionStatus, project_failed: bool) {
-    if !project_failed {
+fn mark_skipped(entry: &mut ExecutionStatus) {
+    if entry.status == Status::Queued {
         entry.status = Status::Skipped;
     }
 }
Suggestion importance[1-10]: 8

__

Why: Overwriting a Passed status with Skipped for subsequent empty scripts incorrectly masks successful executions, making this a highly impactful bug fix for status reporting.

Medium
Uniquify concurrent staging paths

Use an atomic counter alongside the process ID when generating the staged
temporary filename. This ensures strict uniqueness across threads within the
same process.

pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs [510-511]

+    static STAGED_LINK_COUNTER: std::sync::atomic::AtomicU64 =
+        std::sync::atomic::AtomicU64::new(0);
+
     let file_name = dest.file_name().unwrap_or(dest.as_os_str()).to_string_lossy().into_owned();
-    let staged = dest.with_file_name(format!(".{file_name}.{}.pacquet-tmp", std::process::id()));
+    let nonce =
+        STAGED_LINK_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+    let staged = dest.with_file_name(format!(
+        ".{file_name}.{}.{nonce}.pacquet-tmp",
+        std::process::id(),
+    ));
Suggestion importance[1-10]: 4

__

Why: While DirLock effectively serializes this operation per version and avoids practical collisions, generating a truly unique staging file name adds an extra layer of safety against potential intra-process concurrency.

Low
General
Make failure test cross-platform

Replace exit 1 with node -e "process.exit(1)" in the test script. This
guarantees cross-platform compatibility and avoids potential issues on Windows.

pnpm11/exec/commands/test/runRecursive.ts [1332]

-'check:a': 'exit 1',
+'check:a': 'node -e "process.exit(1)"',
Suggestion importance[1-10]: 6

__

Why: Using node -e "process.exit(1)" ensures consistent cross-platform behavior and prevents potential test flakiness on Windows.

Low
✅ Suggestions up to commit affc990
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use valid Duration constructor

Change Duration::from_mins to Duration::from_secs multiplied by 60, since the
former does not exist in standard Rust.

pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs [166-169]

-const WAIT: Duration = Duration::from_mins(5);
-const ABANDONED_AFTER: Duration = Duration::from_mins(30);
+const WAIT: Duration = Duration::from_secs(5 * 60);
+const ABANDONED_AFTER: Duration = Duration::from_secs(30 * 60);
Suggestion importance[1-10]: 10

__

Why: This suggestion corrects a compilation error, as the std::time::Duration API does not have a from_mins constructor.

High
✅ Accumulate execution durations and preserve cross-script failure statuses
Suggestion Impact:The commit addresses the core failure-overwrite issue by tracking project_failed and preventing later successful or skipped scripts from replacing a prior failure. It differs from the suggestion by continuing execution rather than breaking after failure and by retaining per-script duration instead of accumulating project-wide duration.

code diff:

+            // A `/pattern/` selector can match several scripts in one
+            // project, but the summary carries a single status per
+            // project and `count_failures` derives the exit code from
+            // it. Once one of them has failed, nothing a later script
+            // does may overwrite that.
+            let mut project_failed = false;
             for selected in &specified {
                 let Some(script) = manifest.script(selected, true)? else {
-                    result[root].status = Status::Skipped;
+                    mark_skipped(&mut result[root], project_failed);
                     continue;
                 };
                 // Per-stage no-ops: an empty body (`!scripts[name]`) is
@@ -153,7 +161,7 @@
                 if script.is_empty()
                     || (args.script_args().is_empty() && script == "npx only-allow pnpm")
                 {
-                    result[root].status = Status::Skipped;
+                    mark_skipped(&mut result[root], project_failed);
                     continue;
                 }
                 // Recursion guard: skip a project when `npm_lifecycle_event`
@@ -178,7 +186,9 @@
                     return Err(super::RunError::HiddenScript { script: selected.clone() }.into());
                 }
 
-                result[root].status = Status::Running;
+                if !project_failed {
+                    result[root].status = Status::Running;
+                }
                 has_command += 1;
                 let start = Instant::now();
                 // Per-project pre/main/post via the same machinery
@@ -204,10 +214,13 @@
                 let duration = start.elapsed().as_secs_f64() * 1e3;
 
                 if status.success() {
-                    let entry = &mut result[root];
-                    entry.status = Status::Passed;
-                    entry.duration = Some(duration);
+                    if !project_failed {
+                        let entry = &mut result[root];
+                        entry.status = Status::Passed;
+                        entry.duration = Some(duration);
+                    }
                 } else {
+                    project_failed = true;
                     let prefix = root.to_string_lossy().into_owned();
                     let entry = &mut result[root];
                     entry.status = Status::Failure;
@@ -254,3 +267,12 @@
     Ok(())
 }
 
+/// Record that a selected script had nothing to run, unless one of this
+/// project's other selected scripts already failed — see the
+/// `project_failed` bookkeeping in [`run_recursive`].
+fn mark_skipped(entry: &mut ExecutionStatus, project_failed: bool) {
+    if !project_failed {
+        entry.status = Status::Skipped;
+    }

Track the project's overall execution state and accumulate durations to avoid
overwriting earlier script failures when multiple scripts execute in one
project.

pnpm/crates/cli/src/cli_args/run/recursive.rs [142-228]

+            let mut project_start = None;
             for selected in &specified {
                 let Some(script) = manifest.script(selected, true)? else {
-                    result[root].status = Status::Skipped;
+                    if result[root].status != Status::Passed {
+                        result[root].status = Status::Skipped;
+                    }
                     continue;
                 };
 ...
                 if script.is_empty()
                     || (args.script_args().is_empty() && script == "npx only-allow pnpm")
                 {
-                    result[root].status = Status::Skipped;
+                    if result[root].status != Status::Passed {
+                        result[root].status = Status::Skipped;
+                    }
                     continue;
                 }
 ...
                 if selected.starts_with('.') && env::var_os("npm_lifecycle_event").is_none() {
                     return Err(super::RunError::HiddenScript { script: selected.clone() }.into());
                 }
 
-                result[root].status = Status::Running;
-                has_command += 1;
-                let start = Instant::now();
+                if result[root].status != Status::Running {
+                    result[root].status = Status::Running;
+                    has_command += 1;
+                    project_start = Some(Instant::now());
+                }
 ...
                 let status = run_stages(&ctx, selected, script, args.script_args())?;
-                let duration = start.elapsed().as_secs_f64() * 1e3;
+                let duration = project_start.unwrap().elapsed().as_secs_f64() * 1e3;
 
                 if status.success() {
                     let entry = &mut result[root];
                     entry.status = Status::Passed;
                     entry.duration = Some(duration);
                 } else {
                     let prefix = root.to_string_lossy().into_owned();
                     let entry = &mut result[root];
                     entry.status = Status::Failure;
                     entry.duration = Some(duration);
                     entry.message = Some(format!(
                         "command failed with exit code {}",
                         status.code().unwrap_or(1),
                     ));
                     entry.prefix = Some(prefix.clone());
 
                     if bail {
                         if args.report_summary {
                             write_recursive_summary(workspace_root, &result)?;
                         }
                         return Err(RecursiveRunError::RecursiveRunFirstFail { prefix }.into());
                     }
+                    break;
                 }
             }
Suggestion importance[1-10]: 8

__

Why: This suggestion identifies and resolves a critical logical flaw where a project's failure status and duration could be improperly overwritten when multiple scripts run in sequence.

Medium
High-level
Sort matched hunks before applying modifications

Sort matched patch hunks sequentially by their resolved positions before
applying them. This prevents corrupted files if fuzzing causes hunks to be
applied out of their original order.

Examples:

pnpm/crates/patching/src/apply/tolerant.rs [36-66]

Solution Walkthrough:

Before:

let mut modifications = Vec::new();
for (index, hunk) in patch.hunks().iter().enumerate() {
    let parts = split_into_parts(hunk.lines());
    let matched = fuzzing_offsets().find_map(|offset| ...)?;
    modifications.extend(matched);
}

let mut offset = 0_isize;
for modification in modifications {
    // Applies modifications relying on sequential offset
    ...
}

After:

let mut matched_hunks = Vec::new();
for (index, hunk) in patch.hunks().iter().enumerate() {
    let parts = split_into_parts(hunk.lines());
    let (matched, match_index) = fuzzing_offsets().find_map(|offset| ...)?;
    matched_hunks.push((match_index, matched));
}

// Ensure strictly sequential processing for the offset logic
matched_hunks.sort_by_key(|(idx, _)| *idx);

let mut modifications = Vec::new();
for (_, matched) in matched_hunks {
    modifications.extend(matched);
}
// ... apply modifications
Suggestion importance[1-10]: 7

__

Why: Identifies a subtle but valid edge case in the patch applier algorithm where fuzzed offsets could cause overlapping/crossed hunk applications to break the offset accumulator.

Medium

Greptile and Qodo each found a real defect in the first pass.

**A failed script could be reported as passed.** Adding the `/pattern/`
selector let one project run several scripts, but the recursive summary
carries a single status per project and `count_failures` derives the exit
code from it. A later script's success overwrote an earlier one's
failure, so `--no-bail` reported the whole run green. The per-project
`Status::Running` and `Status::Skipped` writes had the same effect, so
the fix is a `project_failed` flag guarding all three rather than a
comparison at the success site alone.

The TypeScript stack has the same bug — `runRecursive.ts` assigns
`'passed'` unguarded, and regexp selectors have shipped there for a
while, so `pnpm -r run "/pattern/" --no-bail` is affected today. Fixed
there too, per the cardinal rule; TypeScript's control-flow narrowing
had been hiding it (it narrows the status to `'running'` and calls the
comparison unreachable), which is why the fix tracks failed prefixes in
a set rather than reading the status back.

**A stale lock holder released its successor's lock.** A `DirLock` whose
holder outran `abandoned_after` has already had its directory removed
and recreated by the next process in line; dropping it then removed that
successor's directory, handing the engine slot to two processes at once
— the very race the lock exists to prevent. Acquisition now records a
token in the lock directory and release only removes a lock that still
carries it.

**The lock's takeover tests were timing-fragile.** They used a zero
abandonment threshold, which asks the wall clock and the filesystem's
mtime clock to agree: on a runner whose wall clock sits ahead, the
subtraction underflows and the lock reads as fresh. This is the likely
cause of the Code Coverage job failing while the same suite passed
locally. They now age a lock well past a non-zero threshold.

**A rejected pattern was reported once per project.** The selector is
now compiled once per command instead of once per project, which also
answers the repeated-compilation finding: `ScriptSelector` resolves the
positional up front and applies it across the workspace.

**`force_link`'s rename now retries.** Replacing a file another process
holds open fails on Windows with a sharing violation, and this
destination is an executable several pnpm processes reach at once. Those
handles clear in milliseconds, so a short backoff turns a spurious
install failure into a pause.

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

🧹 Nitpick comments (4)
pnpm/crates/cli/tests/run_recursive.rs (1)

1449-1495: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add coverage for a partial pass/fail mix within one project's regexp matches.

This test only exercises the all-pass case. Add a --no-bail variant where one matched script fails and another (later, in declaration order) passes, then assert the project's summary status still reports failed — this would catch the status-overwrite issue flagged in recursive.rs.

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

In `@pnpm/crates/cli/tests/run_recursive.rs` around lines 1449 - 1495, Extend
recursive_run_executes_every_script_matching_a_regexp_selector with a --no-bail
scenario where an earlier regexp-matched script fails and a later
declaration-order match succeeds. Assert the command completes with the expected
non-bailing result and summary_statuses reports the project as "failed",
ensuring a passing script cannot overwrite the failed project status.
pnpm/crates/patching/src/apply/tolerant.rs (1)

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

Document why Push/Pop don't update offset.

Splice updates the running offset (Line 58) but Push/Pop don't, even though they change lines's length. This is correct only because EOF annotations (the sole source of Push/Pop) are structurally confined to the last hunk processed, so no subsequent Splice ever needs to account for their length delta — but that invariant isn't stated anywhere, making it easy for a future change (e.g. reordering hunk processing, or a hypothetical multi-file/multi-EOF scenario) to silently break this. A short comment capturing the invariant would prevent that.

As per path instructions, **/*.{ts,tsx,rs} comments "should explain non-obvious invariants, workarounds, deliberate exceptions, or contracts" — this is exactly such a case.

📝 Suggested comment
     let mut offset = 0_isize;
+    // `Push`/`Pop` change `lines`'s length but don't touch `offset`: EOF
+    // annotations are structurally confined to the file's final hunk, so
+    // no later Splice in this loop ever needs to account for their delta.
     for modification in modifications {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/patching/src/apply/tolerant.rs` around lines 48 - 66, Add a short
comment in the Modification::Pop/Modification::Push handling explaining that
these EOF annotations are structurally confined to the final hunk, so no later
Splice observes their length change and offset must not be updated. Keep the
existing offset behavior unchanged.

Source: Path instructions

pnpm/crates/package-manager/src/build_modules/tests.rs (1)

883-915: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Missing regression test for patch-aware ignored-builds identity.

The corresponding fix in build_modules.rs (re-deriving the ignored-builds key via get_pkg_id_with_patch_hash so patched vs. unpatched copies of the same package are tracked separately) has no dedicated test here. The existing build_modules_collects_ignored_builds / build_modules_excludes_explicit_deny_from_ignored fixtures have no patches configured, so they wouldn't fail if this logic regressed to the old dep_path-based key.

Consider adding a test with two snapshots of the same name@version — one carrying a patches entry, one not — both denied by policy, and assert ignored_builds contains two distinct entries.
Would you like me to draft this test?

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

In `@pnpm/crates/package-manager/src/build_modules/tests.rs` around lines 883 -
915, The test suite lacks coverage for patch-aware ignored-build identity. Add a
regression test alongside build_modules_collects_ignored_builds and
build_modules_excludes_explicit_deny_from_ignored that creates two denied
snapshots with the same name and version, but only one with a patches entry,
then assert ignored_builds contains two distinct entries keyed through
get_pkg_id_with_patch_hash.
pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs (1)

159-174: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Lock-acquisition I/O errors are silently collapsed into "couldn't get the lock."

DirLock::acquire returns io::Result<Option<DirLock>>: the outer Result is a genuine I/O failure (e.g., can't create the lock's parent directory), while the inner Option is "gave up waiting." .ok().flatten() discards the distinction, so a real I/O error is silently treated the same as ordinary contention, with no log/diagnostic. In practice the same I/O problem would likely resurface when create_dir_all(&tmp_install_dir) runs a few lines later (Line 127), but that's incidental, not a guarantee — a different transient failure (e.g., of the lock's own parent dir) would be swallowed with zero signal.

As per path instructions, pnpm/CODE_STYLE_GUIDE.md states "Error handling: minimize unwrap() in non-test code; use proper Result propagation... don't swallow errors."

♻️ Proposed fix: log the error case distinctly from a mere timeout
 fn engine_install_lock(config: &Config, package_name: &str, version: &str) -> Option<DirLock> {
     ...
     let name = format!("{}@{version}.lock", package_name.replace('/', "+"));
     let path = config.store_dir.tmp().join("engine-locks").join(name);
-    DirLock::acquire(path, WAIT, ABANDONED_AFTER).ok().flatten()
+    match DirLock::acquire(path, WAIT, ABANDONED_AFTER) {
+        Ok(lock) => lock,
+        Err(error) => {
+            tracing::warn!(%error, "failed to take the engine install lock; proceeding unserialized");
+            None
+        }
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs` around lines 159
- 174, Update engine_install_lock to handle the outer io::Result from
DirLock::acquire separately from the inner timeout Option: preserve None for
ordinary lock contention, but log or otherwise report the I/O error before
returning None. Do not use .ok().flatten(), so failures creating or accessing
the lock directory are not silently swallowed.

Source: Path instructions

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

Inline comments:
In `@pnpm/crates/cli/src/cli_args/global.rs`:
- Line 368: Update the allow-build application flow around decided_allow_builds
and apply_allow_build() to merge approvals from WorkspaceSettings.allow_builds
with the newly selected packages before calling set_allow_build(). Preserve
existing true/false entries from raw settings, including entries absent from
config.allow_builds, while still applying the current allow_builds decision.

In `@pnpm/crates/cli/src/cli_args/run.rs`:
- Around line 494-508: Update try_build_regex_from_command to compile and match
/pattern/ selectors using JavaScript RegExp semantics instead of Rust
regex::Regex, including look-around and backreference constructs. Preserve the
existing literal parsing, flag rejection, and plain-name fallback behavior,
while ensuring valid JavaScript selectors such as /^(build|test)$/ select
matching scripts rather than being treated as names.

In `@pnpm/crates/cli/src/cli_args/run/recursive.rs`:
- Around line 173-179: The inline hidden-script error check in the recursive run
loop should filter matched hidden scripts rather than immediately returning.
After regexp matching populates recursive specified selections, reuse
throw_or_filter_hidden_scripts for the specified matches so dot-prefixed entries
are removed unless every selected script in that project is hidden, preserving
write_recursive_summary and rejecting only when no match is actionable.
- Around line 142-227: Preserve the strongest per-project outcome across all
scripts matched by the selector in the recursive run loop. Update the status and
associated duration, message, and prefix handling around the `result[root]`
assignments in the `selected` loop so later `Skipped` or `Passed` results cannot
overwrite an earlier `Failure` (and later `Skipped` cannot overwrite a prior
executed result); retain failure details for `--no-bail` summaries and failure
counting.

In `@pnpm/crates/cli/tests/lifecycle_scripts.rs`:
- Around line 1444-1486: Expand
stamps_the_configured_user_agent_on_install_scripts_and_run to configure a
distinctive npm_config_user_agent and assert the exact value rather than only
checking the pnpm prefix. Add integration coverage for the changed propagation
paths: exec, dlx, dependency-build hooks, and git preparation, ensuring each
records and validates the configured value and would fail without the spawn-path
fix.

---

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs`:
- Around line 159-174: Update engine_install_lock to handle the outer io::Result
from DirLock::acquire separately from the inner timeout Option: preserve None
for ordinary lock contention, but log or otherwise report the I/O error before
returning None. Do not use .ok().flatten(), so failures creating or accessing
the lock directory are not silently swallowed.

In `@pnpm/crates/cli/tests/run_recursive.rs`:
- Around line 1449-1495: Extend
recursive_run_executes_every_script_matching_a_regexp_selector with a --no-bail
scenario where an earlier regexp-matched script fails and a later
declaration-order match succeeds. Assert the command completes with the expected
non-bailing result and summary_statuses reports the project as "failed",
ensuring a passing script cannot overwrite the failed project status.

In `@pnpm/crates/package-manager/src/build_modules/tests.rs`:
- Around line 883-915: The test suite lacks coverage for patch-aware
ignored-build identity. Add a regression test alongside
build_modules_collects_ignored_builds and
build_modules_excludes_explicit_deny_from_ignored that creates two denied
snapshots with the same name and version, but only one with a patches entry,
then assert ignored_builds contains two distinct entries keyed through
get_pkg_id_with_patch_hash.

In `@pnpm/crates/patching/src/apply/tolerant.rs`:
- Around line 48-66: Add a short comment in the
Modification::Pop/Modification::Push handling explaining that these EOF
annotations are structurally confined to the final hunk, so no later Splice
observes their length change and offset must not be updated. Keep the existing
offset behavior unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b14c05f2-8319-4b2e-b3ad-1e4776e50471

📥 Commits

Reviewing files that changed from the base of the PR and between d17710c and affc990.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !Cargo.lock
📒 Files selected for processing (41)
  • .changeset/allow-builds-placeholder-is-parsable.md
  • .changeset/concurrent-package-manager-switch.md
  • .changeset/deprecated-and-ignored-build-lists.md
  • .changeset/lockfile-config-mismatch-code.md
  • .changeset/npm-config-user-agent-in-scripts.md
  • .changeset/patch-applier-tolerances.md
  • .changeset/regexp-script-selectors.md
  • Cargo.toml
  • pnpm/crates/cli/Cargo.toml
  • pnpm/crates/cli/src/cli_args/dlx.rs
  • pnpm/crates/cli/src/cli_args/exec.rs
  • pnpm/crates/cli/src/cli_args/global.rs
  • pnpm/crates/cli/src/cli_args/run.rs
  • pnpm/crates/cli/src/cli_args/run/recursive.rs
  • pnpm/crates/cli/src/cli_args/run/tests.rs
  • pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pnpm/crates/cli/src/cli_args/with/install_pnpm_to_store.rs
  • pnpm/crates/cli/tests/approve_builds.rs
  • pnpm/crates/cli/tests/lifecycle_scripts.rs
  • pnpm/crates/cli/tests/run.rs
  • pnpm/crates/cli/tests/run_recursive.rs
  • pnpm/crates/cli/tests/with.rs
  • pnpm/crates/config/src/lib.rs
  • pnpm/crates/config/src/workspace_yaml.rs
  • pnpm/crates/config/src/workspace_yaml/tests.rs
  • pnpm/crates/default-reporter/src/state.rs
  • pnpm/crates/default-reporter/src/tests.rs
  • pnpm/crates/fs/src/dir_lock.rs
  • pnpm/crates/fs/src/dir_lock/tests.rs
  • pnpm/crates/fs/src/lib.rs
  • pnpm/crates/lockfile/src/freshness.rs
  • pnpm/crates/package-manager/src/build_modules.rs
  • pnpm/crates/package-manager/src/build_modules/tests.rs
  • pnpm/crates/package-manager/src/install.rs
  • pnpm/crates/package-manager/src/install/tests.rs
  • pnpm/crates/package-manager/src/install_frozen_lockfile.rs
  • pnpm/crates/package-manager/src/install_package_by_snapshot.rs
  • pnpm/crates/package-manager/src/patch.rs
  • pnpm/crates/patching/src/apply.rs
  • pnpm/crates/patching/src/apply/tolerant.rs
  • pnpm/crates/patching/src/apply/tolerant/tests.rs

Comment thread pnpm/crates/cli/src/cli_args/global.rs Resolved
Comment thread pnpm/crates/cli/src/cli_args/run.rs Resolved
Copilot AI review requested due to automatic review settings July 25, 2026 18:05

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: 5

🧹 Nitpick comments (1)
pnpm/crates/fs/src/dir_lock.rs (1)

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

Document the ownership contract rather than restating declarations.

These rustdoc comments repeat the constant/type names. Keep DirLock documentation focused on its token-validated release invariant; remove or replace the constant comments with rationale. As per coding guidelines, comments must explain non-obvious invariants, workarounds, exceptions, or contracts rather than restate code.

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

In `@pnpm/crates/fs/src/dir_lock.rs` around lines 22 - 29, Update the rustdoc
around POLL_INTERVAL, OWNER_FILE, and DirLock to avoid repeating their
declarations. Document the ownership contract and token-validated release
invariant for DirLock, and replace the constant comments with concise rationale
only where the behavior is non-obvious.

Source: Coding guidelines

🤖 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 @.changeset/recursive-run-keeps-failures.md:
- Around line 2-4: Update the changeset frontmatter to be pacquet-only by
removing the `@pnpm/exec.commands` and pnpm entries, while retaining "pacquet":
patch as the sole release target.

In `@pnpm/crates/cli/src/cli_args/run/tests.rs`:
- Around line 45-46: Update the comment describing the pnpm selector behavior
near the test to use the correct regex terminology: state that the pattern is
not implicitly anchored to the whole script name, while preserving the examples
about matching “build” and manifest declaration order.

In `@pnpm/crates/fs/src/dir_lock.rs`:
- Around line 65-69: Update the lock-acquisition path returning DirLock to
propagate fs::write(path.join(OWNER_FILE), &token) failures instead of ignoring
them. In the release logic, ensure missing or unreadable owner records fail
closed rather than being treated as releasable, including the NotFound handling
near the existing release check.
- Around line 95-100: Replace the read-then-remove ownership check around
OWNER_FILE and fs::remove_dir_all with an ownership-bound lock/lease protocol
that atomically verifies the current holder before cleanup, preventing a
successor lock from being deleted. Update the lock release implementation to
preserve successor ownership and add a deterministic interleaving regression
test that pauses after ownership validation, performs reclaim and successor
creation, then resumes release and verifies the successor directory remains
intact.

In `@pnpm11/exec/commands/src/runRecursive.ts`:
- Around line 182-188: Guard the `running` status assignment in the recursive
execution flow around `failedPrefixes` so it only runs when
`!failedPrefixes.has(prefix)`, preserving an existing `failure` status for
queued matching scripts. Extend the regression test covering failed projects to
use `workspaceConcurrency: 1` and verify the failure remains in the final
summary.

---

Nitpick comments:
In `@pnpm/crates/fs/src/dir_lock.rs`:
- Around line 22-29: Update the rustdoc around POLL_INTERVAL, OWNER_FILE, and
DirLock to avoid repeating their declarations. Document the ownership contract
and token-validated release invariant for DirLock, and replace the constant
comments with concise rationale only where the behavior is non-obvious.
🪄 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: 0106f966-70a0-42d4-acfd-ec9f9b131d14

📥 Commits

Reviewing files that changed from the base of the PR and between affc990 and 394240f.

📒 Files selected for processing (10)
  • .changeset/recursive-run-keeps-failures.md
  • pnpm/crates/cli/src/cli_args/run.rs
  • pnpm/crates/cli/src/cli_args/run/recursive.rs
  • pnpm/crates/cli/src/cli_args/run/tests.rs
  • pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pnpm/crates/cli/tests/run_recursive.rs
  • pnpm/crates/fs/src/dir_lock.rs
  • pnpm/crates/fs/src/dir_lock/tests.rs
  • pnpm11/exec/commands/src/runRecursive.ts
  • pnpm11/exec/commands/test/runRecursive.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • pnpm/crates/cli/src/cli_args/self_update/install_pnpm.rs
  • pnpm/crates/cli/src/cli_args/run/recursive.rs
  • pnpm/crates/cli/src/cli_args/run.rs

Comment thread pnpm/crates/fs/src/dir_lock.rs Resolved
Comment thread pnpm/crates/fs/src/dir_lock.rs Resolved
Comment thread pnpm/crates/fs/src/dir_lock.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 394240f

Deciding a package whose `allowBuilds` entry still held pnpm's
`set this to true or false` placeholder wrote
`true this to true or false`: the value span ended at its first
whitespace, and everything past that was preserved as if it were a
trailing comment. The result is a plain scalar, which YAML reads as a
string — so the approval silently did nothing and the entry stayed
undecided.

The span now runs to a real trailing comment (` #`, outside any quoted
scalar) or to the end of the line, which is what the "preserve the
comment" intent was reaching for.

Only reachable since this branch made a placeholder-bearing config load
at all, which is why it surfaces here. Found by a reviewer asking
whether `--allow-build` could drop unrelated entries; it cannot —
`set_allow_builds` edits the document per named entry rather than
rewriting the map — but the entry it does name was being corrupted.

Also extends the user-agent test to `pnpm exec`, whose child
environment is built separately from the lifecycle executor's.
Copilot AI review requested due to automatic review settings July 25, 2026 18: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.

Comment thread pnpm/crates/fs/src/dir_lock.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

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

The TypeScript counterpart had the same trap the Rust side did: with a
RegExp selector matching several scripts in one project, the per-script
`result[prefix].status = 'running'` write resets a project that has
already failed. Its later success is guarded, so the status is simply
left at 'running' — which countFailures counts no more than 'passed',
so `--no-bail` still exits zero.

Guarded by the same failed-prefix set as the 'passed' write. The test
now pins workspaceConcurrency to 1 so the two matched scripts run one
after the other: concurrently they both set 'running' before either
finishes, which hides this ordering.

Also from review:

- `DirLock::acquire` no longer hands back a lock whose owner record it
  could not write. Such a lock cannot tell at release time whether it is
  still the one it took, so the directory is given back and the lock
  reported as not taken — the documented degradation is to proceed
  unserialized, which is no worse than not having tried.
- The release-time ownership check is documented as narrowing rather
  than closing the takeover window; an atomic compare-and-remove has no
  portable filesystem API.
- Corrected a comment that called `/^build/` "not anchored" when what is
  meant is that the pattern is not implicitly anchored to the whole
  script name.
Copilot AI review requested due to automatic review settings July 25, 2026 18:20

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pnpm 12 on n8n: 6 defects found while validating the Rust CLI against the largest pnpm workspace

2 participants