Skip to content

feat(pacquet): add the -w / --workspace-root option - #13294

Closed
zkochan wants to merge 2 commits into
mainfrom
workspace-root-flag
Closed

zkochan wants to merge 2 commits into
mainfrom
workspace-root-flag

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

pnpm add -D oxlint@latest oxfmt@latest oxlint-tsgolint@latest -w (#13031) still fails on current main. The multi-package half was fixed earlier; what remains is the flag:

$ pnpm add -D oxlint@latest oxfmt@latest -w
error: unexpected argument '-w' found

pacquet had no -w / --workspace-root at all. This adds it, implemented where pnpm implements it — as a universal option resolved before dispatch that rewrites --dir to the workspace root. Every command already resolves its project from dir, so no command needs to know the flag exists.

Both of pnpm's guards come along:

case code
-w with --global ERR_PNPM_OPTIONS_CONFLICT
-w outside a workspace ERR_PNPM_NOT_IN_WORKSPACE

--global is per-command in pacquet rather than universal, so CliCommand::is_global asks the ten commands that expose it; config keeps its copy on each subcommand's ConfigFlags, hence the small accessor there.

One subtlety worth calling out for review: the upward walk runs on a canonicalized path. At this point --dir still holds whatever was typed, and its default . has no parent to climb — searching from it reports "not in a workspace" from every directory. Dispatch canonicalizes dir again later, which is idempotent.

Verification

Behavior checked against the built TypeScript bundle rather than inferred from its source — identical in all four cases:

invocation (from packages/foo/src/utils) TypeScript CLI pacquet
pnpm prefix …/wroot/packages/foo same
pnpm prefix -w …/wroot same
pnpm prefix -g -w --workspace-root may not be used with --global same + ERR_PNPM_OPTIONS_CONFLICT
pnpm prefix -w outside a workspace --workspace-root may only be used inside a workspace same + ERR_PNPM_NOT_IN_WORKSPACE

Four tests in crates/cli/tests/workspace_root.rs, including the reported add -D … -w shape asserting the deps land in the root manifest and not in the member the command ran from. I checked the tests fail against a deliberately neutered re-anchor before committing (2 of 4 fail, the two behavioral ones).

just ready green (6936 tests) and cargo dylint clean.

Fixes #13031.

Squash Commit Body

pnpm's `-w` runs a command on the root workspace project from anywhere
inside the workspace; pacquet had no such flag, so the reported
`pnpm add -D oxlint@latest oxfmt@latest oxlint-tsgolint@latest -w` failed
with "unexpected argument '-w' found". Multi-package `add` was fixed
earlier, leaving the flag as the remaining half of that report.

Implemented where pnpm implements it — as a universal option resolved
before dispatch, by rewriting `--dir` to the workspace root. Every command
already resolves its project from `dir`, so none of them need to know the
flag exists.

The upward walk runs on a canonicalized path: `--dir` still holds whatever
was typed at this point, and its default `.` has no parent to climb, so
searching from it would report "not in a workspace" from every directory.

Both of pnpm's guards come along: `--global` has no workspace root to act
on (`ERR_PNPM_OPTIONS_CONFLICT`), and outside a workspace there is nothing
to re-anchor to (`ERR_PNPM_NOT_IN_WORKSPACE`). `--global` is per-command in
pacquet rather than universal, so `CliCommand::is_global` asks the ten
commands that expose it; `config` keeps its copy on each subcommand's
`ConfigFlags`, hence the accessor there.

Verified against the TypeScript CLI: `prefix -w`, plain `prefix`, `-g -w`,
and `-w` outside a workspace all produce identical results in both stacks.

Fixes pnpm/pnpm#13031.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
    (pacquet-only catch-up: the TypeScript CLI already has -w.)
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.
  • Updated the documentation if needed. (The flag documents itself in --help; pnpm.io already documents -w.)

Follow-up, deliberately not in this PR

pnpm also refuses a bare pnpm add at the workspace root when the workspace defines more than one package pattern, telling the user to pass -w (ERR_PNPM_ADDING_TO_ROOT, bypassed by ignoreWorkspaceRootCheck). pacquet knows the ignore-workspace-root-check config key but has no such guard. That is a separate behavior change — it makes a currently-working command start failing — so it belongs in its own PR rather than riding along with the flag it references.


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


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

Summary by CodeRabbit

  • New Features
    • Added -w / --workspace-root to run commands against the workspace root from any workspace directory.
    • Workspace-local dependency installs can now save dependencies to the root project manifest.
  • Bug Fixes
    • Added clear errors when combining --workspace-root with global mode or using it outside a workspace.
  • Documentation
    • Documented the new workspace-root option and its expected error conditions.

zkochan and others added 2 commits July 25, 2026 10:57
Edge-aware `engineStrict` landed in ea1d6ef: `compute_skipped_snapshots`
dispatches on inbound edges from the lockfile walk, so an incompatible
package reached through a regular dependency edge fails the install even
when it is also optionally reachable. The real port
(`fail_on_unsupported_dependency_of_optional_dependency`, asserting
`ERR_PNPM_UNSUPPORTED_PLATFORM`) was written in the same change and passes,
and TEST_PORTING.md records the item as ported.

The `known_failures` stub for the same upstream test survived that landing,
so `just known-failures` still advertised the gap and a same-named stub sat
alongside the real test claiming pacquet skips this shape. Remove the module
— it held nothing else — along with a leftover `eprintln!` of the captured
stderr in the real test.

Leaves two live stubs, both pinned cross-stack divergences awaiting a
product decision rather than an implementation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pnpm's `-w` runs a command on the root workspace project from anywhere
inside the workspace; pacquet had no such flag, so the reported
`pnpm add -D oxlint@latest oxfmt@latest oxlint-tsgolint@latest -w` failed
with "unexpected argument '-w' found". Multi-package `add` was fixed
earlier, leaving the flag as the remaining half of that report.

Implemented where pnpm implements it — as a universal option resolved
before dispatch, by rewriting `--dir` to the workspace root. Every command
already resolves its project from `dir`, so none of them need to know the
flag exists.

The upward walk runs on a canonicalized path: `--dir` still holds whatever
was typed at this point, and its default `.` has no parent to climb, so
searching from it would report "not in a workspace" from every directory.

Both of pnpm's guards come along: `--global` has no workspace root to act
on (`ERR_PNPM_OPTIONS_CONFLICT`), and outside a workspace there is nothing
to re-anchor to (`ERR_PNPM_NOT_IN_WORKSPACE`). `--global` is per-command in
pacquet rather than universal, so `CliCommand::is_global` asks the ten
commands that expose it; `config` keeps its copy on each subcommand's
`ConfigFlags`, hence the accessor there.

Verified against the TypeScript CLI: `prefix -w`, plain `prefix`, `-g -w`,
and `-w` outside a workspace all produce identical results in both stacks.

Fixes #13031.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 09:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds -w / --workspace-root handling to resolve commands against the workspace root, reject incompatible or non-workspace usage, integrate resolution into CLI startup, and test the behavior. Release metadata documents the option and its diagnostic outcomes.

Changes

Workspace root execution

Layer / File(s) Summary
Workspace root argument and resolution
pnpm/crates/cli/src/cli_args/cli_command.rs, pnpm/crates/cli/src/cli_args/config.rs
Adds the global workspace-root flag, detects global command modes, resolves the workspace directory, and defines structured validation errors.
CLI startup and dispatch integration
pnpm/crates/cli/src/lib.rs, pnpm/crates/cli/src/cli_args/dispatch.rs
Applies workspace-root resolution before recursive promotion and dispatches using the resolved directory.
Behavior coverage and release metadata
pnpm/crates/cli/tests/workspace_root.rs, .changeset/pacquet-workspace-root-flag.md, pnpm/crates/cli/tests/optional_dependencies.rs
Tests root installs, directory anchoring, global conflicts, and non-workspace errors; documents the option and removes unrelated test scaffolding and debug output.

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

Assessment against linked issues

Objective Addressed Explanation
Support pnpm add -D with -w for multiple packages [#13031] ❓ The PR adds workspace-root handling, but the provided tests cover only one added package and do not verify multiple package arguments.

Out-of-scope changes

Code Change Explanation
Remove the known_failures module and stderr debug output (pnpm/crates/cli/tests/optional_dependencies.rs:255,906) These changes concern optional-dependency engine tests and are not related to the linked workspace-root package-addition objective.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant run_cli
  participant CliArgs
  participant WorkspaceFinder
  participant RootProject
  User->>run_cli: Invoke command with -w
  run_cli->>CliArgs: apply_workspace_root()
  CliArgs->>WorkspaceFinder: find_workspace_dir(dir)
  WorkspaceFinder-->>CliArgs: workspace root
  CliArgs->>RootProject: Rewrite command directory
  RootProject-->>User: Execute command at workspace root
Loading

Possibly related PRs

  • pnpm/pnpm#13281: Implements the same workspace-root CLI plumbing and validation coverage.
  • pnpm/pnpm#13282: Shares the optional-dependency test cleanup.

Suggested labels: product: pacquet

Suggested reviewers: copilot, safort

✨ 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 workspace-root-flag

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

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

feat(pacquet): add -w/--workspace-root by re-anchoring --dir at workspace root

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Add global -w/--workspace-root to run commands against the workspace root project.
• Validate -w conflicts with --global and requires being inside a workspace.
• Add regression tests covering add/prefix behavior and error codes.
Diagram

graph TD
  A["CliArgs"] --> B{"-w/--workspace-root?"} -->|"no"| G["Dispatch (dir)"]
  B -->|"yes"| C{"Validate + resolve root"} -->|"conflict w/ --global"| D["ERR_PNPM_OPTIONS_CONFLICT"]
  C -->|"not in workspace"| E["ERR_PNPM_NOT_IN_WORKSPACE"]
  C -->|"ok"| F["Rewrite --dir to root"] --> G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Per-command -w handling
  • ➕ Avoids any mutation of the shared dir argument in CliArgs
  • ➕ Lets individual commands tailor semantics if they diverge later
  • ➖ Duplicates logic across many commands
  • ➖ More likely to drift from pnpm’s universal-option behavior
  • ➖ Harder to guarantee consistent validation and error codes
2. Resolve workspace root lazily during project resolution
  • ➕ Keeps CliArgs immutable; resolution happens where project selection already lives
  • ➖ Requires threading the -w flag through more layers
  • ➖ Higher risk of missing early consumers (e.g., fast paths/promotions) that read dir
  • ➖ Still effectively becomes a global pre-dispatch concern

Recommendation: Keep the current approach: treat -w as a universal option resolved before dispatch by rewriting dir. This matches pnpm semantics, avoids per-command changes, and ensures early CLI behaviors that depend on dir (recursive promotions/fast paths) see the correct anchored directory.

Files changed (7) +215 / -33

Enhancement (2) +80 / -0
cli_command.rsAdd -w flag, pre-dispatch dir rewrite, and pnpm-aligned diagnostics +77/-0

Add -w flag, pre-dispatch dir rewrite, and pnpm-aligned diagnostics

• Introduces a global -w/--workspace-root flag on CliArgs and implements apply_workspace_root() to canonicalize dir, locate the workspace root, and rewrite dir accordingly. Adds WorkspaceRootError with miette diagnostics and implements CliCommand::is_global() to detect per-command -g usage for conflict checks.

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

lib.rsApply workspace-root rewrite before promotions and fast paths +3/-0

Apply workspace-root rewrite before promotions and fast paths

• Calls args.apply_workspace_root() early in run_cli(), before recursive promotions and any install fast path that resolves project state from dir. Ensures consistent behavior across all commands.

pnpm/crates/cli/src/lib.rs

Refactor (2) +16 / -0
config.rsExpose ConfigArgs::is_global() for workspace-root conflict checks +13/-0

Expose ConfigArgs::is_global() for workspace-root conflict checks

• Adds an accessor to detect whether config subcommands received -g/--global, since the flag is stored on each subcommand’s ConfigFlags. Enables uniform conflict detection with -w without restructuring config args.

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

dispatch.rsAcknowledge workspace_root flag as consumed pre-dispatch +3/-0

Acknowledge workspace_root flag as consumed pre-dispatch

• Updates dispatch argument destructuring to ignore workspace_root with a comment clarifying it is applied before dispatch by rewriting dir. Prevents unused-field noise and documents control flow.

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

Tests (2) +114 / -33
optional_dependencies.rsRemove stale known-failure stub and clean up debug stderr print +0/-33

Remove stale known-failure stub and clean up debug stderr print

• Deletes the obsolete known-failures module for edge-aware engineStrict now that the real test exists and passes. Removes a leftover eprintln! of captured stderr from the real test assertion.

pnpm/crates/cli/tests/optional_dependencies.rs

workspace_root.rsAdd end-to-end tests for -w/--workspace-root semantics and errors +114/-0

Add end-to-end tests for -w/--workspace-root semantics and errors

• Adds four tests covering: saving added devDependencies to the root manifest from a member dir, prefix -w reporting the workspace root from a nested directory, -w conflicting with -g, and -w outside a workspace returning the pnpm error code. Builds minimal workspace fixtures on disk to validate behavior.

pnpm/crates/cli/tests/workspace_root.rs

Documentation (1) +5 / -0
pacquet-workspace-root-flag.mdAdd changeset entry documenting -w/--workspace-root behavior +5/-0

Add changeset entry documenting -w/--workspace-root behavior

• Adds a minor-version changeset describing the new -w/--workspace-root option. Documents intended behavior and the two pnpm-matching guard errors for conflict and non-workspace usage.

.changeset/pacquet-workspace-root-flag.md

@github-actions

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.05     11.8±0.11ms    31.9 MB/sec    1.00     11.1±0.03ms    33.6 MB/sec
packument/parse                1.00     41.0±0.21µs  1618.4 MB/sec    1.01     41.3±0.14µs  1606.5 MB/sec
tarball/download_dependency    1.00      2.3±0.06ms  1911.1 KB/sec    1.01      2.3±0.07ms  1901.4 KB/sec

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Global conflict missed 🐞 Bug ≡ Correctness
Description
CliCommand::is_global omits ApproveBuilds, so pnpm approve-builds --global -w bypasses the new
ERR_PNPM_OPTIONS_CONFLICT guard even though the command exposes --global. This violates the PR’s
stated invariant that -w and --global conflict at the universal-option layer.
Code

pnpm/crates/cli/src/cli_args/cli_command.rs[R566-579]

+    fn is_global(&self) -> bool {
+        match self {
+            CliCommand::Add(args) => args.global,
+            CliCommand::Bin(args) => args.global,
+            CliCommand::Config(args) => args.is_global(),
+            CliCommand::List(args) | CliCommand::Ll(args) => args.global,
+            CliCommand::Outdated(args) => args.global,
+            CliCommand::Prefix(args) => args.global,
+            CliCommand::Remove(args) => args.global,
+            CliCommand::Root(args) => args.global,
+            CliCommand::Runtime(args) => args.global,
+            CliCommand::Update(args) => args.global,
+            _ => false,
+        }
Relevance

⭐⭐⭐ High

Looks like an obvious missed match arm; similar approve-builds global handling fixes were accepted
before.

PR-#13008

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new is_global() implementation doesn’t check ApproveBuilds, while ApproveBuildsArgs does
define a global boolean flag.

pnpm/crates/cli/src/cli_args/cli_command.rs[562-580]
pnpm/crates/cli/src/cli_args/cli_command.rs[515-519]
pnpm/crates/cli/src/cli_args/approve_builds.rs[16-31]

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

### Issue description
`CliArgs::apply_workspace_root()` rejects `-w/--workspace-root` when `self.command.is_global()` is true. The new `CliCommand::is_global()` match does not include `CliCommand::ApproveBuilds(_)`, even though `approve-builds` defines a `--global` flag, so the intended conflict guard is skipped.

### Issue Context
Even if `approve-builds --global` is currently “not supported yet”, it is still the `--global` flag and should trigger the same universal conflict behavior as other commands when combined with `-w`.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/cli_command.rs[562-580]

### Suggested fix
- Add a match arm:
 - `CliCommand::ApproveBuilds(args) => args.global,`
- (Optional) Add a small test asserting `approve-builds --global -w` yields `ERR_PNPM_OPTIONS_CONFLICT`.

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



Informational

2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only declares a bump for pacquet and omits the required pnpm package entry.
This can cause the user-visible CLI feature change to ship without the correct pnpm version bump.
Code

.changeset/pacquet-workspace-root-flag.md[R1-3]

+---
+"pacquet": minor
+---
Relevance

⭐ Low

Multiple prior reviews rejected adding required "pnpm" entry to pacquet-only changesets.

PR-#13283
PR-#13285
PR-#13234

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each changeset to explicitly include the pnpm package with a
valid bump type. The added changeset front-matter lists only pacquet, omitting pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-workspace-root-flag.md[1-3]

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

## Issue description
The new changeset file does not include a `pnpm` entry in its front-matter, which violates the requirement that changesets explicitly declare the `pnpm` package bump type.

## Issue Context
This PR introduces a user-visible CLI flag (`-w` / `--workspace-root`). The changeset should reflect the appropriate `pnpm` bump type alongside `pacquet`.

## Fix Focus Areas
- .changeset/pacquet-workspace-root-flag.md[1-3]

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


3. Workspace errors collapsed 🐞 Bug ≡ Correctness
Description
CliArgs::apply_workspace_root converts any find_workspace_dir error (including the dedicated
bad-workspace-manifest-name error) into ERR_PNPM_NOT_IN_WORKSPACE, losing the real diagnostic and
making misnamed pnpm-workspace.yaml cases look like “not in a workspace”. This changes/weakens
existing workspace-discovery error reporting specifically for -w flows.
Code

pnpm/crates/cli/src/cli_args/cli_command.rs[R281-284]

+        let from = dunce::canonicalize(&self.dir).unwrap_or_else(|_| self.dir.clone());
+        let workspace_dir = pacquet_workspace::find_workspace_dir(&from)
+            .map_err(|_| WorkspaceRootError::NotInWorkspace)?
+            .ok_or(WorkspaceRootError::NotInWorkspace)?;
Relevance

⭐ Low

Repo precedent rejected preserving workspace-root finder diagnostics; they accept collapsing errors
to “not in workspace”.

PR-#13202
PR-#13281

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new apply_workspace_root explicitly discards the underlying find_workspace_dir error, while
the workspace root-finder defines and returns a dedicated error for misnamed workspace manifest
files.

pnpm/crates/cli/src/cli_args/cli_command.rs[264-287]
pnpm/crates/workspace/src/root_finder.rs[47-132]

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

### Issue description
`CliArgs::apply_workspace_root()` currently maps *all* errors from `pacquet_workspace::find_workspace_dir()` to `WorkspaceRootError::NotInWorkspace`, which hides meaningful diagnostics such as `ERR_PNPM_BAD_WORKSPACE_MANIFEST_NAME` (raised when a misnamed `pnpm-workspace.yaml` variant is found). This makes `-w` produce misleading errors and diverges from the rest of the workspace-discovery behavior.

### Issue Context
- `pacquet_workspace::find_workspace_dir()` can return `FindWorkspaceDirError::BadName(...)` when it encounters misnamed workspace manifest variants.
- `apply_workspace_root()` should only emit `ERR_PNPM_NOT_IN_WORKSPACE` when the workspace root genuinely can’t be found; other discovery failures should be preserved.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/cli_command.rs[271-286]
- pnpm/crates/cli/src/cli_args/cli_command.rs[609-631]

### Suggested fix
- Replace `.map_err(|_| WorkspaceRootError::NotInWorkspace)?` with logic that:
 - returns `WorkspaceRootError::NotInWorkspace` only for the `Ok(None)` case.
 - propagates workspace discovery errors (e.g., `FindWorkspaceDirError::BadName`) either by:
   - adding a new `WorkspaceRootError` variant with `#[diagnostic(transparent)]` wrapping `FindWorkspaceDirError`/`BadWorkspaceManifestNameError`, or
   - changing `apply_workspace_root` to return `miette::Result<()>` and using `?` to bubble up the real diagnostic.

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


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@greptile-apps

greptile-apps Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5

The PR should not merge until workspace-root participates correctly in recursive project selection and every command exposing global mode is covered by the conflict guard.

Rewriting dir alone omits the root package from recursive or filtered -w operations, and the incomplete global-command match causes approve-builds --global -w to emit the wrong public error.

Files Needing Attention: pnpm/crates/cli/src/cli_args/cli_command.rs, pnpm/crates/cli/tests/workspace_root.rs

Reviews (1): Last reviewed commit: "feat(pacquet): add the -w / --workspace-..." | Re-trigger Greptile

Comment on lines +284 to +285
.ok_or(WorkspaceRootError::NotInWorkspace)?;
self.dir = workspace_dir;

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.

P1 Workspace root omitted recursively

When -w is combined with -r or --filter, this code only changes dir and does not add the root project to project selection, causing recursive or filtered operations to omit the workspace root while the TypeScript CLI includes it.

Context Used: pnpm/CLAUDE.md (source)

Knowledge Base Used: Rust CLI core: argument parsing, dispatch, config, and reporting

Comment on lines +566 to +580
fn is_global(&self) -> bool {
match self {
CliCommand::Add(args) => args.global,
CliCommand::Bin(args) => args.global,
CliCommand::Config(args) => args.is_global(),
CliCommand::List(args) | CliCommand::Ll(args) => args.global,
CliCommand::Outdated(args) => args.global,
CliCommand::Prefix(args) => args.global,
CliCommand::Remove(args) => args.global,
CliCommand::Root(args) => args.global,
CliCommand::Runtime(args) => args.global,
CliCommand::Update(args) => args.global,
_ => false,
}
}

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.

P1 Approve-builds bypasses conflict guard

When approve-builds --global is combined with --workspace-root, this match returns false because it omits ApproveBuilds, so the universal conflict check is bypassed and the command reports ERR_PNPM_APPROVE_BUILDS_NOT_SUPPORTED_WITH_GLOBAL instead of the required ERR_PNPM_OPTIONS_CONFLICT.

Context Used: pnpm/CLAUDE.md (source)

Knowledge Base Used: Rust CLI core: argument parsing, dispatch, config, and reporting

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@pnpm/crates/cli/src/cli_args/cli_command.rs`:
- Around line 264-285: Update apply_workspace_root to propagate
dunce::canonicalize failures instead of falling back to the raw self.dir; pass
only the canonical path to find_workspace_dir, map a successful None result to
WorkspaceRootError::NotInWorkspace, and add a regression test covering a
traversal path that resolves outside the workspace with a missing target.
🪄 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: 6e9e1ff9-da43-4531-b1ae-030039cfd665

📥 Commits

Reviewing files that changed from the base of the PR and between 0cb0127 and 468a9fe.

📒 Files selected for processing (7)
  • .changeset/pacquet-workspace-root-flag.md
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/config.rs
  • pnpm/crates/cli/src/cli_args/dispatch.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/tests/optional_dependencies.rs
  • pnpm/crates/cli/tests/workspace_root.rs
💤 Files with no reviewable changes (1)
  • pnpm/crates/cli/tests/optional_dependencies.rs

Comment on lines +264 to +285
/// Re-anchor `--dir` at the workspace root for `-w` /
/// `--workspace-root`, so the command runs on the root project from
/// anywhere inside the workspace.
///
/// Rewriting `dir` is the whole implementation, matching pnpm: every
/// command already resolves its project from `dir`, so none of them
/// need to know the flag exists.
pub fn apply_workspace_root(&mut self) -> Result<(), WorkspaceRootError> {
if !self.workspace_root {
return Ok(());
}
if self.command.is_global() {
return Err(WorkspaceRootError::ConflictsWithGlobal);
}
// The upward walk needs a real path to climb: `--dir` still holds
// whatever was typed, and its default `.` has no parent to walk to.
// Dispatch canonicalizes `dir` again later, which is idempotent.
let from = dunce::canonicalize(&self.dir).unwrap_or_else(|_| self.dir.clone());
let workspace_dir = pacquet_workspace::find_workspace_dir(&from)
.map_err(|_| WorkspaceRootError::NotInWorkspace)?
.ok_or(WorkspaceRootError::NotInWorkspace)?;
self.dir = workspace_dir;

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 6 --type rust 'fn\s+find_workspace_dir\b' pnpm
rg -n -C 4 --type rust 'apply_workspace_root|workspace_root_outside_a_workspace' pnpm

Repository: pnpm/pnpm

Length of output: 4761


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- cli_command.rs relevant section ---\n'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs

printf '\n--- root_finder.rs relevant section ---\n'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs

printf '\n--- workspace_root.rs relevant tests ---\n'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs

printf '\n--- TypeScript pnpm implementation search for --workspace-root/dir handling ---\n'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || true

Repository: pnpm/pnpm

Length of output: 238


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Behavioral probe: model path walking semantics relevant to `../../outside-missing` and existing workspace
python3 - <<'PY'
from pathlib import Path
import os, tempfile
import shutil

def walk_to_root(cwd: str):
    """Minimal model of the existing Rust walk: start from given entry point, keep climbing parent for missing cwd only,
       then return first entry point that passes manifest predicate if any, or None."""
    p = Path(cwd)
    visited_entries = {str(p)}
    attempts = 0
    while True:
        attempts += 1
        if p.name == ".pnpm-workspace.yaml":
            return p.parent
        if p.name == "pnpm-workspace.yaml":
            return p.parent
        if p == Path.cwd():
            return None
        q = p.parent
        if not (q / "package.json").exists():
            if p not in visited_entries:
                return None
            p = q
            continue
        if len(attempts) > 20:
            raise RuntimeError("infinite")
        p = q

with tempfile.TemporaryDirectory() as td:
    td = Path(td)
    root = td / "root"
    root.mkdir()
    dir1 = root / "dir1"
    dir1.mkdir()
    (root / "package.json").write_text("{}")
    (root / ".pnpm-workspace.yaml").write_text("packages:\n  - 'dir1'\n")
    candidate = dir1 / ".." / ".." / "outside-missing"
    # Real existing-candidate lookup is not in this scenario; Rust path.walk behavior for candidate that is not symlink here:
    print(f"exists before: {candidate.exists()}")
    print(f"root_finder equivalent root (from effective dir1): {walk_to_root(str(dir1))}")
    # The issue is only if `from` is syntactically canonicalized when current_dir is workspace/root.
    old = os.getcwd()
    try:
        os.chdir(str(root))
        print(f"root_finder equivalent root from syntactic sibling via symlink-less traversal when cwd=root:", end=" ")
        print(walk_to_root(str(candidate)))
    finally:
        os.chdir(old)
PY

Repository: pnpm/pnpm

Length of output: 330


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- cli_command.rs relevant section ---'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs

echo
echo '--- root_finder.rs relevant section ---'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs

echo
echo '--- workspace_root.rs relevant tests ---'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs

echo
echo '--- TypeScript pnpm implementation search for --workspace-root/dir handling ---'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || true

echo
echo '--- deterministic path-walk probe ---'
python3 - <<'PY'
from pathlib import Path
import tempfile

def root_finder_like_walk(cwd: str):
    p = Path(cwd)
    attempts = 0
    while True:
        attempts += 1
        name = p.name if p.name else None
        if name == ".pnpm-workspace.yaml":
            return p.parent
        if name == "pnpm-workspace.yaml":
            return p.parent
        if p == Path.cwd():
            return None
        q = p.parent
        if not (q / "package.json").exists():
            if not q.exists():
                return None
            p = q
            continue
        if attempts > 20:
            raise RuntimeError("infinite")
        p = q

with tempfile.TemporaryDirectory() as td:
    td = Path(td)
    root = td / "root"
    root.mkdir()
    dir1 = root / "dir1"
    dir1.mkdir()
    (root / "package.json").write_text("{}")
    (root / ".pnpm-workspace.yaml").write_text("packages:\n  - 'dir1'\n")
    candidate = dir1 / ".." / ".." / "outside-missing"
    print(f"current dir: {Path.cwd()}")
    print(f"candidate: {candidate}")
    print(f"candidate exists: {candidate.exists()}")
    print(f"root_finder_like_walk from candidate: {root_finder_like_walk(str(candidate))}")
PY

Repository: pnpm/pnpm

Length of output: 139


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- cli_command.rs relevant section ---'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs

echo
echo '--- root_finder.rs relevant section ---'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs

echo
echo '--- workspace_root.rs relevant tests ---'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs

echo
echo '--- TypeScript pnpm implementation search for --workspace-root/dir handling ---'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || true

echo
echo '--- deterministic path-walk probe ---'
python3 - <<'PY'
from pathlib import Path
import tempfile

def root_finder_like_walk(cwd: str):
    p = Path(cwd)
    attempts = 0
    while True:
        attempts += 1
        name = p.name if p.name else None
        if name == ".pnpm-workspace.yaml":
            return p.parent
        if name == "pnpm-workspace.yaml":
            return p.parent
        if p == Path.cwd():
            return None
        q = p.parent
        if not (q / "package.json").exists():
            if not q.exists():
                return None
            p = q
            continue
        if attempts > 20:
            raise RuntimeError("infinite")
        p = q

with tempfile.TemporaryDirectory() as td:
    td = Path(td)
    root = td / "root"
    root.mkdir()
    dir1 = root / "dir1"
    dir1.mkdir()
    (root / "package.json").write_text("{}")
    (root / ".pnpm-workspace.yaml").write_text("packages:\n  - 'dir1'\n")
    candidate = dir1 / ".." / ".." / "outside-missing"
    print(f"current dir: {Path.cwd()}")
    print(f"candidate: {candidate}")
    print(f"candidate exists: {candidate.exists()}")
    print(f"root_finder_like_walk from candidate: {root_finder_like_walk(str(candidate))}")
PY

Repository: pnpm/pnpm

Length of output: 139


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re, sys

for path in [
    Path('pnpm/crates/cli/src/cli_args/cli_command.rs'),
    Path('pnpm/crates/workspace/src/root_finder.rs'),
    Path('pnpm/crates/cli/tests/workspace_root.rs'),
]:
    print(f'\n### {path} exists={path.exists()} size={path.stat().st_size if path.exists() else "n/a"}')
    txt = path.read_text(errors='replace')
    for needle in ['apply_workspace_root', 'find_workspace_dir', 'workspace_root_outside_a_workspace', 'not_in_workspace']:
        matches = [m.start() for m in re.finditer(re.escape(needle), txt, re.I)]
        print(f'{needle}: matches={len(matches)}')

path = Path('pnpm/crates/workspace/src/root_finder.rs')
txt = path.read_text(errors='replace')
print('\n--- root_finder walk implementation ---')
for i,line in enumerate(txt.splitlines(),1):
    if 'find_workspace_dir_by_walk' in line or 'canonicalize' in line or 'fs::read_dir' in line or 'package.json' in line or '.pnpm-workspace.yaml' in line:
        print(f'{i}: {line}')
PY

Repository: pnpm/pnpm

Length of output: 975


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

def view(path, lines):
    print(f'\n### {path}')
    txt = path.read_text(errors='replace')
    all_lines = txt.splitlines()
    for start,end in [(max(1,line-5), line+5) for line in lines]:
        print(f'-- lines {start}-{end} --')
        for i in range(start, min(end, len(all_lines))+1):
            print(f'{i:4}: {all_lines[i-1]}')

view(Path('pnpm/crates/workspace/src/root_finder.rs'), [1, 60, 105, 140])
view(Path('pnpm/crates/cli/src/cli_args/cli_command.rs'), [140, 260, 281])
view(Path('pnpm/crates/cli/tests/workspace_root.rs'), [80, 105, 130, 160])

for p in [Path('pnpm/crates/workspace/src/root_finder.rs'), Path('pnpm/crates/cli/tests/workspace_root.rs')]:
    txt = p.read_text(errors='replace')
    print(f'\n--- package.json occurrences in {p} ---')
    for i,l in enumerate(txt.splitlines(),1):
        if 'package.json' in l:
            print(f'{i}: {l}')
PY

Repository: pnpm/pnpm

Length of output: 5162


🌐 Web query:

pnpm workspace-root flag package manager official docs

💡 Result:

The --workspace-root (or -w) flag is a global CLI flag in pnpm that allows you to execute commands as if they were started from the root of the workspace, regardless of your current working directory [1][2]. When you use this flag, pnpm redirects the command to the workspace root, which is useful in several scenarios: 1. Adding Dependencies to the Root: By default, pnpm prevents you from adding dependencies to the root workspace package to avoid accidental dependencies being declared at the root level [3]. Using the -w flag bypasses this safety check, allowing you to add, remove, or update packages in the root package.json [3]. 2. Recursive Command Execution: When used with recursive commands (such as pnpm -r or pnpm -w), it alters how the filter works [4]. While recursive commands typically exclude the root project by default [5], adding the --workspace-root flag includes the root project in the execution scope [4]. The workspace root itself is defined by the existence of a pnpm-workspace.yaml file in a directory [6][7].

Citations:


🌐 Web query:

pnpm workspace root flag outside workspace ERR_PNPM_NOT_IN_WORKSPACE behavior

💡 Result:

The ERR_PNPM_NOT_IN_WORKSPACE error is triggered when a pnpm command that requires a workspace environment is executed outside of a valid pnpm workspace [1]. A pnpm workspace is identified by the presence of a pnpm-workspace.yaml file in the root directory [2][3][4]. The workspace-root flag, available as -w or --workspace-root, is designed to allow commands to execute as if they were started from the root of the workspace rather than the current working directory [5][6][7]. When you use -w, you are explicitly instructing pnpm to locate and operate within the context of the workspace root [5][6]. However, the -w flag does not override the requirement that a workspace must exist [1]. If you run a command with the -w flag in a directory that is not part of a pnpm workspace, or in a directory where a pnpm workspace cannot be discovered, pnpm will still raise an ERR_PNPM_NOT_IN_WORKSPACE error because the fundamental prerequisite for a workspace-level operation is missing [1]. In summary: 1. ERR_PNPM_NOT_IN_WORKSPACE: Indicates that the command requires a workspace, but none was found [1]. 2. Workspace-root flag (-w): Tells pnpm to execute at the root of the workspace [5][7]. 3. Interaction: The -w flag is a tool for navigating within an existing workspace; it cannot create a workspace context where one does not exist [1]. If you are outside a workspace, the flag cannot bypass the need for a pnpm-workspace.yaml file [2][1].

Citations:


🌐 Web query:

pnpm workspace-root flag outside workspace directory symlink traversal

💡 Result:

There is no direct "workspace-root flag outside workspace directory symlink traversal" vulnerability described as a singular, unified issue in pnpm. However, path traversal and unauthorized symlink creation issues—often involving symlinks and workspace-related operations—have been identified and addressed in recent pnpm versions [1][2][3][4]. The core concern regarding the --workspace-root (-w) flag involves how pnpm determines the workspace root. In some versions, the flag resolves the directory using canonicalization (which follows symlinks) [5]. If a directory is a symlink pointing outside the expected project structure, pnpm may incorrectly identify the workspace root, potentially leading to operations being performed in an unintended directory [5]. Developers have noted this as a security risk, recommending the use of absolute, lexically-normalized paths that do not resolve symlinks for workspace discovery [5]. Separately, pnpm has faced significant path traversal vulnerabilities related to how it handles dependency and configuration paths, which can be exploited even with --ignore-scripts: 1. CVE-2026-50016: This vulnerability involves transitive dependency aliases (e.g., from registry metadata) containing path traversal segments [4][6]. During installation, pnpm used these aliases to construct filesystem paths for symlinking without proper validation, allowing malicious packages to overwrite project files or directories with symlinks [4]. 2. CVE-2026-59195 (GHSA-qrv3-253h-g69c): This involves path traversal in the configDependencies block of pnpm-lock.yaml [1][2][7][3]. Malicious repositories could use crafted package names or versions containing traversal characters to escape the node_modules/.pnpm-config directory, enabling arbitrary symlink creation on the host filesystem [1][2][7]. These vulnerabilities have been patched in recent pnpm releases (e.g., versions 10.34.4, 11.8.0, and others depending on the specific advisory) by implementing strict path validation and rejecting traversal components in configuration and dependency names [2][3][6]. Users are advised to upgrade to the latest versions to mitigate these risks [3].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

# Read only the deterministic Rust walk-body shape from the repository source.
src = Path('pnpm/crates/workspace/src/root_finder.rs').read_text()
body = re.search(r'fn find_workspace_dir_by_walk\(cwd: &Path\)(.*?)\n\}', src, re.S).group(1)
print('find_workspace_dir_by_walk body:')
for i, line in enumerate(body.splitlines(), 1):
    print(f'{i:3}: {line}')

print('\nContains package.json check:', 'package.json' in body)
print('Uses Path::ancestors:', 'cwd.ancestors()' in body or 'ancestors()' in body)
print('Uses package.json manifest check:', 'package.json' in body)

# Compare against the reviewed fallback behavior: non-canonical path can contain ".."
# ancestors that syntactically climb outside the current-process cwd first.
example = Path('/tmp/root').joinpath('dir1').joinpath('..').joinpath('..').joinpath('outside-missing')
print('\nLexical ancestors of problematic --dir from cwd /tmp/root:')
for i, part in enumerate(example.parents):
    print(f'{i+1}: {part}')
PY

Repository: pnpm/pnpm

Length of output: 1727


🌐 Web query:

pnpm PR 13281 workspace-root outside workspace pnpm-workspace.yaml workspaceRoot

💡 Result:

The pnpm Pull Request #13281 introduces the --workspace-root (or -w) CLI flag to provide explicit control when executing pnpm commands in a workspace environment [1]. Key features and behaviors of this PR include: - Target Workspace Root: It allows running pnpm commands (such as add) specifically against the root of the workspace, even when executed from a subdirectory [1]. - Command Redirection: When -w is used, it redirects the --dir option to the workspace root, ensuring the command interacts with the root package.json rather than the nearest project manifest [1]. - Error Handling: The PR adds logic to explicitly reject invalid usages of this flag, specifically when running with --global or when outside of a workspace context [1]. It uses standard pnpm error codes like ERR_PNPM_OPTIONS_CONFLICT and ERR_PNPM_NOT_IN_WORKSPACE [1]. - Recursive Commands: It adjusts recursive command selectors to allow targeting only the root project or including it alongside other filtered projects [1]. In the context of pnpm workspaces, the pnpm-workspace.yaml file is the authoritative marker that defines the workspace root [2][3]. Commands are typically executed relative to the nearest detected pnpm-workspace.yaml [4]. The --workspace-root flag provides a mechanism to override default behaviors (such as adding dependencies to a sub-package) by forcing the operation to the defined workspace root [1].

Citations:


Reject non-canonical --dir values before locating the workspace.

When canonicalization fails, apply_workspace_root passes the raw --dir to find_workspace_dir(), whose cwd.ancestors() walk remains lexical. A value like <workspace>/../../outside-missing climbs through <workspace>/.. before resolving to the intended outside directory, so -w can select the workspace root even though the requested location is outside it. Propagate canonicalization failures, and map only a successful lookup returning None to ERR_PNPM_NOT_IN_WORKSPACE; add a regression test for this traversal case.

🤖 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/cli_command.rs` around lines 264 - 285, Update
apply_workspace_root to propagate dunce::canonicalize failures instead of
falling back to the raw self.dir; pass only the canonical path to
find_workspace_dir, map a successful None result to
WorkspaceRootError::NotInWorkspace, and add a regression test covering a
traversal path that resolves outside the workspace with a missing target.

Source: Path instructions

@zkochan

zkochan commented Jul 25, 2026

Copy link
Copy Markdown
Member Author

Closing as a duplicate — -w / --workspace-root landed in #13281 (merged as a8a2325e07) while this was in review, and that implementation is a superset of this one.

We converged on the same design independently: declare -w CLI-wide, re-anchor --dir at the workspace root before dispatch, and reject --global / a missing workspace with ERR_PNPM_OPTIONS_CONFLICT / ERR_PNPM_NOT_IN_WORKSPACE — down to the same CliCommand::is_global reassembly and the same changeset filename. #13281 additionally handles the recursive case, pushing a {<root>} inclusion selector through AutoExcludeRoot::root_selector so -w with -r / --filter narrows the run to the root project, and threads the flag into Config.

The two bot findings on this PR both point at that difference and are already correct on main:

  • "Workspace root omitted recursively" — feat(cli): support the --workspace-root (-w) flag #13281's root_selector covers it; rewriting dir alone, as this PR did, does not.
  • "Approve-builds bypasses conflict guard" — main's is_global includes CliCommand::ApproveBuilds. This PR missed it because approve_builds.rs declares --global without a short flag, and I had enumerated the commands by grepping for short = 'g'.

Nothing here is worth salvaging: the merged PR's tests in crates/cli/tests/add.rs already cover the reported add -w from a subdirectory, plus a nonexistent---dir edge case this PR did not.


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

@zkochan zkochan closed this Jul 25, 2026
@zkochan
zkochan deleted the workspace-root-flag branch July 25, 2026 09:29
zkochan added a commit that referenced this pull request Jul 25, 2026
…kspace (#13297)

`pnpm --dir ../../elsewhere add -w foo` from inside a workspace added to
that workspace's root instead of failing, when `../../elsewhere` did not
exist. pnpm reports ERR_PNPM_NOT_IN_WORKSPACE.

`apply_workspace_root` falls back to `std::path::absolute` when the `--dir`
cannot be canonicalized, which is what keeps a nonexistent `--dir` inside
the workspace working. On Unix that leaves `..` components in place, and
`find_workspace_dir` walks ancestors lexically — so the walk climbed back
up through the very `..` components that had taken it out of the workspace
and found the workspace it had just left.

Resolve `..` in the fallback with `pacquet_fs::lexical_normalize` (the
existing filesystem-free normalizer) before the walk. A nonexistent `--dir`
that stays inside the workspace still resolves to the root, and an existing
directory outside it still errors — both already covered by tests.

Found by CodeRabbit on #13294, a duplicate of #13281
closed in favor of it; the finding applies to the merged implementation.
Verified against the TypeScript CLI: all three `--dir` shapes now agree.
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…kspace (pnpm#13297)

`pnpm --dir ../../elsewhere add -w foo` from inside a workspace added to
that workspace's root instead of failing, when `../../elsewhere` did not
exist. pnpm reports ERR_PNPM_NOT_IN_WORKSPACE.

`apply_workspace_root` falls back to `std::path::absolute` when the `--dir`
cannot be canonicalized, which is what keeps a nonexistent `--dir` inside
the workspace working. On Unix that leaves `..` components in place, and
`find_workspace_dir` walks ancestors lexically — so the walk climbed back
up through the very `..` components that had taken it out of the workspace
and found the workspace it had just left.

Resolve `..` in the fallback with `pacquet_fs::lexical_normalize` (the
existing filesystem-free normalizer) before the walk. A nonexistent `--dir`
that stays inside the workspace still resolves to the root, and an existing
directory outside it still errors — both already covered by tests.

Found by CodeRabbit on pnpm#13294, a duplicate of pnpm#13281
closed in favor of it; the finding applies to the merged implementation.
Verified against the TypeScript CLI: all three `--dir` shapes now agree.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pnpm 12: adding multiple packages is failing

2 participants