Skip to content

fix(workspace-manifest-writer): edit inline (flow) YAML blocks in place - #14112

Merged
zkochan merged 6 commits into
mainfrom
fix-14108
Aug 23, 2026
Merged

zkochan merged 6 commits into
mainfrom
fix-14108

Conversation

@zkochan

@zkochan zkochan commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #14108.

The issue reports that the two stacks disagree on writing to a flow-style
block in pnpm-workspace.yaml: the TypeScript writer edits it in place, the
Rust one refuses. Probing the Rust writer while scoping the fix turned up
something worse than the refusal — only overrides: and auditConfig: had
the inline guard. Every other block spliced a block-style line in after the
inline value and left an unparsable document behind:

# before: catalog: { foo: ^1.0.0 }   +  `pnpm add --save-catalog bar`
catalog: { foo: ^1.0.0 }
  bar: ^2.0.0

Same for configDependencies, allowBuilds, and patchedDependencies.

The direction taken is the one the issue lists first: pacquet learns to
edit flow-style nodes in place, matching TS.
The TypeScript writer keeps
today's behavior (refusing there would break audit --fix, link, and
catalog writes for anyone whose manifest uses flow style, and it already
handles the case well — flow style, entry quoting, and trailing comments all
survive).

pacquet side (pnpm/crates/workspace-manifest-writer):

  • New flow module: parses a single-line flow collection into entry spans
    and rebuilds it with one entry upserted, replaced, or dropped. Untouched
    entries keep their exact text, and everything outside the brackets stays
    verbatim.
  • edit.rs classifies each key path as block / editable-flow / unsupported,
    and the entry splices, the removal splices, the catalog, allowBuilds,
    patchedDependencies and configDependencies writers, and the
    catalogPrune / allowBuilds cleanup passes all route through it.
  • Rendering matches what the yaml library emits ({ a: 1, b: 2 },
    [ a, b ]), including where a new key sorts in, so both stacks now write
    the same bytes for the same edit.
  • ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK now guards
    every writer instead of two, and fires only for shapes a splice really
    cannot edit: a multi-line flow collection (whose interleaved comments a
    one-line rebuild would drop), an alias, or a scalar where a collection
    belongs. Removing a block never triggers it, so patchedDependencies: null
    still clears cleanly.

Every expectation in the new flow_style suite was taken from running the
TypeScript writer on the same input; the mirrored suite lives in
pnpm11/workspace/workspace-manifest-writer/test/flowStyle.test.ts so the
two stay pinned together.

Known remaining divergences, all in shapes pacquet now refuses with an
actionable error rather than corrupting: TS reformats a multi-line flow
collection (re-indenting the whole block), resolves aliases by unwrapping
them into the value, and edits a manifest written as one whole-document
flow mapping
({ overrides: { foo: 1.0.0 } }) in place. Matching the first
would mean reproducing the yaml emitter's flow-wrapping algorithm; the other
two are exotic enough that a clear error beats the machinery. All three
corrupted the file before this PR.

Note for #11384: its
audit_fix_cleanup_reports_the_write_error_for_an_inline_audit_config asserts
the old refusal for a flow auditConfig. Once this lands, that test should
assert the successful in-place edit instead — and the TS mirror CodeRabbit
asked for there becomes writable.

Squash Commit Body

The workspace-manifest writer's splices are line-oriented, so a block a user
wrote inline — `catalog: { foo: ^1.0.0 }`, `overrides: { foo: 1.0.0 }`,
`minimumReleaseAgeExclude: [[email protected]]` — had no entry lines to splice.
`overrides:` and `auditConfig:` refused the write; every other block spliced a
block-style line in after the inline value and left an unparsable document
behind.

The TypeScript writer round-trips the document through the yaml library and
edits such a block in place, keeping its flow style, its other entries and
their quoting, and any trailing comment. pacquet now does the same: a new
`flow` module parses a single-line flow collection into entry spans and
rebuilds it with one entry upserted, replaced, or dropped, and the entry
splices, the removal splices, the catalog/allowBuilds/patchedDependencies
writers, and the cleanup passes all route through it. The rendering matches
what the yaml library emits (`{ a: 1, b: 2 }`, `[ a, b ]`), so both stacks
produce the same bytes for the same edit — pinned by the new `flow_style`
suite and its mirror in
pnpm11/workspace/workspace-manifest-writer/test/flowStyle.test.ts.

A flow collection spanning several lines can carry comments between its
entries that a one-line rebuild would drop, so those — along with aliases and
scalars standing where a collection belongs — are still refused with
ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK, now on every
writer rather than only two.

Closes pnpm/pnpm#14108

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
    (TypeScript already behaved this way; it gains the mirrored tests that pin
    the contract.)
  • 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[1m]).


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 support for editing single-line flow-style YAML mappings and sequences in workspace manifests.
    • Updates preserve existing entries, comments, quoting, and formatting.
    • Supported settings include catalogs, overrides, configuration dependencies, build permissions, patches, and audit rules.
  • Bug Fixes

    • Unsupported or ambiguous inline YAML values are now left unchanged with clearer errors.
  • Tests

    • Added comprehensive coverage for flow-style manifest updates, removals, pruning, and unsupported formats.

Copilot AI lite review requested due to automatic review settings August 23, 2026 14:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Approval pending

CodeRabbit is reviewing the latest commit. It will check approval again when the review finishes.

✨ 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-14108

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

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix Rust workspace manifest writer to edit single-line flow YAML blocks in place

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Edit single-line flow-style YAML mappings/sequences in-place instead of corrupting documents.
• Refuse only truly-unsafe inline shapes (multi-line flow, alias, wrong scalar) with actionable
 error.
• Add Rust+TS parity tests to pin output bytes across both workspace-manifest writers.
Diagram

graph TD
  A["pnpm CLI commands"] --> B["workspace-manifest-writer (Rust)"] --> C["edit.rs (splices + routing)"] --> D["flow.rs (parse + rebuild)"]
  B --> E["unsupported inline guard"]
  B --> F["tests: Rust + TS parity suite"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Round-trip via YAML AST for all edits
  • ➕ Simplifies correctness by using parser/serializer invariants
  • ➕ Naturally handles multi-line flow collections and anchors/aliases
  • ➖ Would lose some format-preserving guarantees unless a style-preserving emitter is used
  • ➖ Potentially larger diffs (reformatting) and higher runtime cost
  • ➖ Harder to exactly match existing TS writer byte-for-byte behavior
2. Always refuse flow style and require block style
  • ➕ Much simpler implementation and lower maintenance burden
  • ➖ Breaks existing workflows (audit --fix, link, catalog writes) for users with flow-style manifests
  • ➖ Regresses from TS behavior and undermines cross-implementation parity
3. Auto-reformat flow blocks into block style on edit
  • ➕ Avoids needing a robust flow editor
  • ➕ Makes subsequent line-based splices straightforward
  • ➖ Surprising user-visible formatting changes; increases diff churn
  • ➖ Would diverge from TS writer behavior and could drop subtle formatting/comments

Recommendation: The chosen approach (surgically editing only single-line flow collections and refusing unsafe inline shapes) is the best fit: it fixes data corruption, preserves user formatting/comments, and matches the TypeScript writer’s output. The key follow-up is to keep the Rust/TS parity suites in lockstep as the contract for ordering and spacing rules evolves.

Files changed (6) +956 / -294

Enhancement (1) +319 / -0
flow.rsAdd single-line flow collection parser + minimal rebuild splicer +319/-0

Add single-line flow collection parser + minimal rebuild splicer

• Implements parsing of single-line flow mappings/sequences into entry spans, preserving untouched entry text and surrounding line content. Provides upsert/remove/set operations that rebuild the collection using yaml-like spacing rules while refusing multi-line flow/comment-interleaving cases.

pnpm/crates/workspace-manifest-writer/src/flow.rs

Bug fix (2) +266 / -271
edit.rsRoute inline flow edits through flow module; broaden inline-shape detection +203/-256

Route inline flow edits through flow module; broaden inline-shape detection

• Introduces inline-shape classification (Block/Flow/Unsupported), detects inline value offsets for nested paths, and updates all relevant writers/removal paths to support single-line flow mappings/sequences. Removal/upsert helpers now handle both block and flow style, while unsupported inline shapes cause safe no-ops (or are rejected by higher-level guards) to avoid corruption.

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

lib.rsCentralize unsupported-inline guarding and expand it to all writers +63/-15

Centralize unsupported-inline guarding and expand it to all writers

• Adds a helper to detect the first unsupported inline path and uses it across catalog, overrides, allowBuilds, configDependencies, patchedDependencies, and auditConfig entry points. Updates the error message to clarify which inline shapes are refused (multi-line flow, alias, scalar mismatch).

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

Tests (2) +366 / -23
tests.rsAdd flow-style regression and parity tests for Rust writer +235/-23

Add flow-style regression and parity tests for Rust writer

• Updates existing tests to expect in-place flow edits (instead of refusal or block-style rewrites) and adds a comprehensive 'flow_style' suite covering catalog, overrides, allowBuilds, patchedDependencies, configDependencies, minimumReleaseAgeExclude, and refusal cases (multi-line flow, alias).

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

flowStyle.test.tsAdd TS parity suite defining expected flow-style edit output +131/-0

Add TS parity suite defining expected flow-style edit output

• Introduces Jest tests that run the TypeScript writer on flow-style manifests and assert exact output bytes. Serves as a contract mirrored by the Rust 'flow_style' suite to keep ordering/spacing/comment handling consistent across implementations.

pnpm11/workspace/workspace-manifest-writer/test/flowStyle.test.ts

Documentation (1) +5 / -0
flow-style-workspace-manifest-edits.mdDocument patch release for flow-style workspace edits +5/-0

Document patch release for flow-style workspace edits

• Adds a pacquet patch changeset describing that flow-style YAML blocks are now edited in place instead of failing or corrupting pnpm-workspace.yaml.

.changeset/flow-style-workspace-manifest-edits.md

Copilot AI review requested due to automatic review settings August 23, 2026 14:30

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 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 Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5

The PR is not yet safe to merge because pruning an unsupported multi-line minimumReleaseAgeExclude sequence can report success without applying the required update.

The destructive replacement from the previous thread is prevented, but the replacement branch now returns a no-op signal and the prune caller lacks the preflight needed to turn that condition into the documented unsupported-inline error.

Files Needing Attention: pnpm/crates/workspace-manifest-writer/src/edit.rs, pnpm/crates/workspace-manifest-writer/src/lib.rs

Reviews (2): Last reviewed commit: "fix(workspace-manifest-writer): span a m..." | Re-trigger Greptile

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Wrong-kind flow bypass 🐞 Bug ≡ Correctness
Description
has_unsupported_inline_value() returns false when a key’s inline value is a single-line flow
collection of the *wrong kind* (e.g. allowBuilds: [ ... ]), so callers don’t refuse the write. The
subsequent mapping writers fall back to block-style splicing and can append   key: value lines
after an inline value, producing an invalid/unparsable YAML document.
Code

pnpm/crates/workspace-manifest-writer/src/edit.rs[R63-67]

+pub(crate) fn has_unsupported_inline_value(text: &str, path: &[&str]) -> bool {
+    document_root_is_inline(text)
+        || (matches!(locate_mapping(text, path), Inline::Unsupported)
+            && matches!(locate_sequence(text, path), Inline::Unsupported))
+}
Relevance

●●● Strong

Recent workspace-writer precedents accept concrete corruption and shape-handling bugs, especially
when the finding matches the PR’s safety intent.

PR-#13917
PR-#13172
PR-#14103

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The guard deems an inline value unsupported only if *both* mapping and sequence parses fail; a
wrong-kind flow value will succeed for one kind and therefore bypass the guard. Mapping writers then
only special-case flow mappings; if locate_mapping() is Unsupported, they fall back to
locate() and splice block-style entries, which is exactly the corruption pattern described in the
PR description.

pnpm/crates/workspace-manifest-writer/src/edit.rs[50-67]
pnpm/crates/workspace-manifest-writer/src/lib.rs[122-131]
pnpm/crates/workspace-manifest-writer/src/edit.rs[1025-1035]

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

### Issue description
`edit::has_unsupported_inline_value()` currently treats an inline value as “unsupported” only if *both* `locate_mapping()` and `locate_sequence()` return `Inline::Unsupported`. This means a single-line flow **sequence** at a path where callers expect a **mapping** (or vice versa) is treated as supported, so the write proceeds and block-style splicing can corrupt the YAML.

### Issue Context
Callers use `unsupported_inline_key()` (in `lib.rs`) to refuse writes before mutating text. Because the guard is not kind-aware, a wrong-kind flow value can slip through, and functions like `write_rendered_entry_at()` will then take the non-flow branch and splice block-style entries into a line that already contains an inline value.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/edit.rs[50-67]
- pnpm/crates/workspace-manifest-writer/src/lib.rs[122-131]
- pnpm/crates/workspace-manifest-writer/src/edit.rs[1029-1036]

### Suggested fix
- Replace `has_unsupported_inline_value(text, path)` with a kind-aware API, e.g.:
 - `has_unsupported_inline_mapping(text, path)` (uses `locate_mapping` only)
 - `has_unsupported_inline_sequence(text, path)` (uses `locate_sequence` only)
 - or `has_unsupported_inline_value(text, path, expected_kind)`.
- Update each caller to pass the expected kind for that path:
 - `catalog`, `catalogs`, `configDependencies`, `allowBuilds`, `patchedDependencies`, `overrides` => mapping
 - `minimumReleaseAgeExclude`, `auditConfig.ignoreGhsas` => sequence
- Add regression tests for wrong-kind single-line flow values (e.g. `allowBuilds: [ foo ]` and a write attempt) to assert the writer refuses rather than corrupting the document.

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



Remediation recommended

2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and omits a pnpm bump entry, which violates the
changeset requirement for pnpm. This can cause pnpm release notes/versioning to miss the intended
user-visible change described in the changeset.
Code

.changeset/flow-style-workspace-manifest-edits.md[R1-3]

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

●● Moderate

Recent changeset precedents conflict: several exact pnpm-entry findings were accepted, while equally
recent ones were rejected.

PR-#14078
PR-#14088
PR-#14020

ⓘ Recommendations generated based on similar findings in past PRs

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

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/flow-style-workspace-manifest-edits.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 `.changeset/flow-style-workspace-manifest-edits.md` is missing a `pnpm` package entry in its front-matter, which violates the repository compliance rule for changesets.

## Issue Context
This changeset currently declares only `"pacquet": patch`.

## Fix Focus Areas
- .changeset/flow-style-workspace-manifest-edits.md[1-3]

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


3. Quadratic key-removal scan 🐞 Bug ➹ Performance
Description
flow::remove_keys() checks membership with keys.contains(key) inside the per-entry filter,
making removals O(entries * keys). With large flow mappings and large removal sets (e.g. cleanup
passes), this adds avoidable CPU overhead on a potentially hot CLI path.
Code

pnpm/crates/workspace-manifest-writer/src/flow.rs[R108-112]

+    let entries: Vec<String> = collection
+        .entries
+        .iter()
+        .filter(|entry| !entry.key.as_ref().is_some_and(|key| keys.contains(key)))
+        .map(|entry| text[entry.span.clone()].to_string())
Relevance

●● Moderate

Performance findings have mixed outcomes, and no close flow.rs precedent establishes that this
optimization is team-required.

PR-#14082
PR-#13917

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation calls keys.contains(key) inside the filter for each entry, which is linear in
keys each time, producing O(n*m) behavior.

pnpm/crates/workspace-manifest-writer/src/flow.rs[105-114]

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

### Issue description
`flow::remove_keys()` performs a linear search (`Vec::contains`) for each entry being considered. This makes removal O(n*m) and is avoidable.

### Issue Context
This code runs during workspace-manifest edits/cleanup. While manifests are usually small, pnpm is a CLI and users can have large workspaces; avoiding superlinear behavior is preferable.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/flow.rs[105-115]

### Suggested fix
- Convert `keys: &[String]` to a `HashSet<&str>` (or `HashSet<String>` if needed) once inside `remove_keys()` and use O(1) membership checks.
- Alternatively change the API to accept a `&HashSet<String>` from callers that already have one (several callsites already deal in sets).

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


Grey Divider

Context sources
✅ Compliance rules (platform): 27 rules

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display preferences

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 493b739 ⚖️ Balanced

Results up to commit a2642d8 ⚖️ Balanced


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


Action required
1. Wrong-kind flow bypass 🐞 Bug ≡ Correctness
Description
has_unsupported_inline_value() returns false when a key’s inline value is a single-line flow
collection of the *wrong kind* (e.g. allowBuilds: [ ... ]), so callers don’t refuse the write. The
subsequent mapping writers fall back to block-style splicing and can append   key: value lines
after an inline value, producing an invalid/unparsable YAML document.
Code

pnpm/crates/workspace-manifest-writer/src/edit.rs[R63-67]

+pub(crate) fn has_unsupported_inline_value(text: &str, path: &[&str]) -> bool {
+    document_root_is_inline(text)
+        || (matches!(locate_mapping(text, path), Inline::Unsupported)
+            && matches!(locate_sequence(text, path), Inline::Unsupported))
+}
Relevance

●●● Strong

Recent workspace-writer precedents accept concrete corruption and shape-handling bugs, especially
when the finding matches the PR’s safety intent.

PR-#13917
PR-#13172
PR-#14103

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The guard deems an inline value unsupported only if *both* mapping and sequence parses fail; a
wrong-kind flow value will succeed for one kind and therefore bypass the guard. Mapping writers then
only special-case flow mappings; if locate_mapping() is Unsupported, they fall back to
locate() and splice block-style entries, which is exactly the corruption pattern described in the
PR description.

pnpm/crates/workspace-manifest-writer/src/edit.rs[50-67]
pnpm/crates/workspace-manifest-writer/src/lib.rs[122-131]
pnpm/crates/workspace-manifest-writer/src/edit.rs[1025-1035]

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

### Issue description
`edit::has_unsupported_inline_value()` currently treats an inline value as “unsupported” only if *both* `locate_mapping()` and `locate_sequence()` return `Inline::Unsupported`. This means a single-line flow **sequence** at a path where callers expect a **mapping** (or vice versa) is treated as supported, so the write proceeds and block-style splicing can corrupt the YAML.

### Issue Context
Callers use `unsupported_inline_key()` (in `lib.rs`) to refuse writes before mutating text. Because the guard is not kind-aware, a wrong-kind flow value can slip through, and functions like `write_rendered_entry_at()` will then take the non-flow branch and splice block-style entries into a line that already contains an inline value.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/edit.rs[50-67]
- pnpm/crates/workspace-manifest-writer/src/lib.rs[122-131]
- pnpm/crates/workspace-manifest-writer/src/edit.rs[1029-1036]

### Suggested fix
- Replace `has_unsupported_inline_value(text, path)` with a kind-aware API, e.g.:
 - `has_unsupported_inline_mapping(text, path)` (uses `locate_mapping` only)
 - `has_unsupported_inline_sequence(text, path)` (uses `locate_sequence` only)
 - or `has_unsupported_inline_value(text, path, expected_kind)`.
- Update each caller to pass the expected kind for that path:
 - `catalog`, `catalogs`, `configDependencies`, `allowBuilds`, `patchedDependencies`, `overrides` => mapping
 - `minimumReleaseAgeExclude`, `auditConfig.ignoreGhsas` => sequence
- Add regression tests for wrong-kind single-line flow values (e.g. `allowBuilds: [ foo ]` and a write attempt) to assert the writer refuses rather than corrupting the document.

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



Remediation recommended
2. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset file lists only pacquet and omits a pnpm bump entry, which violates the
changeset requirement for pnpm. This can cause pnpm release notes/versioning to miss the intended
user-visible change described in the changeset.
Code

.changeset/flow-style-workspace-manifest-edits.md[R1-3]

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

●● Moderate

Recent changeset precedents conflict: several exact pnpm-entry findings were accepted, while equally
recent ones were rejected.

PR-#14078
PR-#14088
PR-#14020

ⓘ Recommendations generated based on similar findings in past PRs

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

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/flow-style-workspace-manifest-edits.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 `.changeset/flow-style-workspace-manifest-edits.md` is missing a `pnpm` package entry in its front-matter, which violates the repository compliance rule for changesets.

## Issue Context
This changeset currently declares only `"pacquet": patch`.

## Fix Focus Areas
- .changeset/flow-style-workspace-manifest-edits.md[1-3]

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


3. Quadratic key-removal scan 🐞 Bug ➹ Performance
Description
flow::remove_keys() checks membership with keys.contains(key) inside the per-entry filter,
making removals O(entries * keys). With large flow mappings and large removal sets (e.g. cleanup
passes), this adds avoidable CPU overhead on a potentially hot CLI path.
Code

pnpm/crates/workspace-manifest-writer/src/flow.rs[R108-112]

+    let entries: Vec<String> = collection
+        .entries
+        .iter()
+        .filter(|entry| !entry.key.as_ref().is_some_and(|key| keys.contains(key)))
+        .map(|entry| text[entry.span.clone()].to_string())
Relevance

●● Moderate

Performance findings have mixed outcomes, and no close flow.rs precedent establishes that this
optimization is team-required.

PR-#14082
PR-#13917

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation calls keys.contains(key) inside the filter for each entry, which is linear in
keys each time, producing O(n*m) behavior.

pnpm/crates/workspace-manifest-writer/src/flow.rs[105-114]

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

### Issue description
`flow::remove_keys()` performs a linear search (`Vec::contains`) for each entry being considered. This makes removal O(n*m) and is avoidable.

### Issue Context
This code runs during workspace-manifest edits/cleanup. While manifests are usually small, pnpm is a CLI and users can have large workspaces; avoiding superlinear behavior is preferable.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/flow.rs[105-115]

### Suggested fix
- Convert `keys: &[String]` to a `HashSet<&str>` (or `HashSet<String>` if needed) once inside `remove_keys()` and use O(1) membership checks.
- Alternatively change the API to accept a `&HashSet<String>` from callers that already have one (several callsites already deal in sets).

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


Grey Divider

Qodo Logo

Comment on lines +63 to +67
pub(crate) fn has_unsupported_inline_value(text: &str, path: &[&str]) -> bool {
document_root_is_inline(text)
|| (matches!(locate_mapping(text, path), Inline::Unsupported)
&& matches!(locate_sequence(text, path), Inline::Unsupported))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Wrong-kind flow bypass 🐞 Bug ≡ Correctness

has_unsupported_inline_value() returns false when a key’s inline value is a single-line flow
collection of the *wrong kind* (e.g. allowBuilds: [ ... ]), so callers don’t refuse the write. The
subsequent mapping writers fall back to block-style splicing and can append   key: value lines
after an inline value, producing an invalid/unparsable YAML document.
Agent Prompt
### Issue description
`edit::has_unsupported_inline_value()` currently treats an inline value as “unsupported” only if *both* `locate_mapping()` and `locate_sequence()` return `Inline::Unsupported`. This means a single-line flow **sequence** at a path where callers expect a **mapping** (or vice versa) is treated as supported, so the write proceeds and block-style splicing can corrupt the YAML.

### Issue Context
Callers use `unsupported_inline_key()` (in `lib.rs`) to refuse writes before mutating text. Because the guard is not kind-aware, a wrong-kind flow value can slip through, and functions like `write_rendered_entry_at()` will then take the non-flow branch and splice block-style entries into a line that already contains an inline value.

### Fix Focus Areas
- pnpm/crates/workspace-manifest-writer/src/edit.rs[50-67]
- pnpm/crates/workspace-manifest-writer/src/lib.rs[122-131]
- pnpm/crates/workspace-manifest-writer/src/edit.rs[1029-1036]

### Suggested fix
- Replace `has_unsupported_inline_value(text, path)` with a kind-aware API, e.g.:
  - `has_unsupported_inline_mapping(text, path)` (uses `locate_mapping` only)
  - `has_unsupported_inline_sequence(text, path)` (uses `locate_sequence` only)
  - or `has_unsupported_inline_value(text, path, expected_kind)`.
- Update each caller to pass the expected kind for that path:
  - `catalog`, `catalogs`, `configDependencies`, `allowBuilds`, `patchedDependencies`, `overrides` => mapping
  - `minimumReleaseAgeExclude`, `auditConfig.ignoreGhsas` => sequence
- Add regression tests for wrong-kind single-line flow values (e.g. `allowBuilds: [ foo ]` and a write attempt) to assert the writer refuses rather than corrupting the document.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This one isn't reachable: a wrong-kind value never gets past Manifest::parse. Every block these writers touch is typed (allowBuilds, overrides, catalog, catalogs, configDependencies, patchedDependencies are IndexMaps; auditConfig.ignoreGhsas and minimumReleaseAgeExclude are Vec<String>), so the manifest is rejected before any guard runs:

$ # allowBuilds: [ foo ]  +  set_allow_builds([("bar", true)])
Failed to parse "…/pnpm-workspace.yaml" as YAML: error: line 1 column 14:
unexpected event: expected mapping start

Same for overrides: [ foo ] and auditConfig: { ignoreGhsas: { a: b } }. The file is left untouched in each case.

That's the real guarantee, so rather than add a kind-aware API whose extra branch no input can reach, I pinned the guarantee with a test — flow_style::a_flow_collection_of_the_wrong_kind_fails_to_parse (493b739) — which fails if a block ever loses its typed decode.

Kind-awareness does exist one level down, where it can bite: locate_mapping / locate_sequence classify a flow collection of the wrong kind as Unsupported, so no writer can splice a mapping entry into a sequence or the reverse.


Written by an agent (Claude Code, claude-opus-5[1m]).

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

@github-actions

github-actions Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.05     12.1±0.06ms    31.0 MB/sec    1.00     11.6±0.04ms    32.4 MB/sec
packument/parse                                  1.00     37.8±0.11µs  1755.9 MB/sec    1.00     37.8±0.10µs  1753.0 MB/sec
tarball/download_dependency                      1.01      2.4±0.08ms  1827.1 KB/sec    1.00      2.4±0.07ms  1839.7 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.00    177.0±1.06ms 90.4 KElem/sec    1.00    177.6±1.51ms 90.1 KElem/sec
workspace_resolution/hoist_heavy                 1.05    271.7±1.02ms        ? ?/sec    1.00    259.7±0.76ms        ? ?/sec

@codecov-commenter

codecov-commenter commented Aug 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.83887% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.46%. Comparing base (6639800) to head (493b739).

Files with missing lines Patch % Lines
pnpm/crates/workspace-manifest-writer/src/flow.rs 91.39% 16 Missing ⚠️
pnpm/crates/workspace-manifest-writer/src/lib.rs 87.03% 7 Missing ⚠️
pnpm/crates/workspace-manifest-writer/src/edit.rs 96.68% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14112      +/-   ##
==========================================
+ Coverage   88.44%   88.46%   +0.02%     
==========================================
  Files         673      674       +1     
  Lines      113365   113563     +198     
==========================================
+ Hits       100270   100468     +198     
  Misses      13095    13095              

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

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

@blacksmith-sh

blacksmith-sh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Found 12 test failures on Blacksmith runners:

Failures

Test View Logs
test/configurationalDependencies.test.ts/
packageManagerDependencies is refreshed when pnpm is invoked via corepack (#11397)
View Logs
test/configurationalDependencies.test.ts/
packageManagerDependencies is refreshed when pnpm is invoked via corepack (#11397)
View Logs
test/configurationalDependencies.test.ts/
packageManagerDependencies is refreshed when pnpm is invoked via corepack (#11397)
View Logs
test/configurationalDependencies.test.ts/
packageManagerDependencies is refreshed when pnpm is invoked via corepack (#11397)
View Logs
test/packageManagerCheck.test.ts/
devEngines.packageManager with version range should match current version
View Logs
test/packageManagerCheck.test.ts/
devEngines.packageManager with version range should match current version
View Logs
test/packageManagerCheck.test.ts/
devEngines.packageManager with version range should match current version
View Logs
test/packageManagerCheck.test.ts/
devEngines.packageManager with version range should match current version
View Logs
test/packageManagerCheck.test.ts/
pnpm --version exits promptly when devEngines.packageManager matches the running pnpm
View Logs
test/packageManagerCheck.test.ts/
pnpm --version exits promptly when devEngines.packageManager matches the running pnpm
View Logs

...and 2 more test failures. View all on Blacksmith

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

The workspace-manifest writer's splices are line-oriented, so a block a
user wrote inline — `catalog: { foo: ^1.0.0 }`, `overrides: { foo: 1.0.0 }`,
`minimumReleaseAgeExclude: [[email protected]]` — had no entry lines to splice.
`overrides:` and `auditConfig:` refused the write; every other block spliced
a block-style line in after the inline value and left an unparsable
document behind:

    catalog: { foo: ^1.0.0 }
      bar: ^2.0.0

The TypeScript writer round-trips the document through the yaml library and
edits such a block in place, keeping its flow style, its other entries and
their quoting, and any trailing comment. pacquet now does the same: a new
`flow` module parses a single-line flow collection into entry spans and
rebuilds it with one entry upserted, replaced, or dropped, and the entry
splices, the removal splices, the catalog/allowBuilds/patchedDependencies
writers, and the cleanup passes all route through it. The rendering matches
what the yaml library emits (`{ a: 1, b: 2 }`, `[ a, b ]`), so both stacks
now produce the same bytes for the same edit — pinned by the new
`flow_style` suite here and its mirror in
pnpm11/workspace/workspace-manifest-writer/test/flowStyle.test.ts.

A flow collection spanning several lines can carry comments between its
entries that a one-line rebuild would drop, so those — along with aliases
and scalars standing where a collection belongs — are still refused with
ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK, now on every
writer rather than only two.

Closes #14108
The mirrored TypeScript suite typechecks against the current
`AuditConfig` and `Project` types: build the pruning fixture with
`prepare` + `findPackages` rather than a hand-rolled project literal, and
drop the `auditConfig` sibling key that does not exist on this branch.
The Rust `ignore_ghsas_are_added_to_a_flow_audit_config` case moves to the
same input so the two suites stay a mirror.
A pnpm-workspace.yaml written as a single flow mapping
(`{ overrides: { foo: 1.0.0 } }`) has no top-level key lines, so the
writers found no block to edit and appended a fresh block-style one after
it, leaving an unparsable document. Every writer now reports
ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK for that shape
instead, `pnpm config set` included.
A flow collection written across several lines closes at column zero, which
`top_level_span` read as the next top-level key. Replacing or removing such
a block left its closing bracket behind:

    minimumReleaseAgeExclude:
      - [email protected]
    ]

The span now runs to the bracket that closes the value, so a removal takes
the whole block and `pnpm config set`/`delete` no longer strand one. The
list writers refuse a multi-line inline value outright rather than
re-rendering it in block style, which would drop the comments between its
entries — the stance the mapping writers already take.

Reported by Greptile on #14112.
Copilot AI review requested due to automatic review settings August 23, 2026 14:49

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.

// Rendering the whole block afresh would drop the comments an
// inline value this writer cannot edit may hold, so leave it be;
// the public writer refuses such a manifest outright.
Inline::Unsupported => return 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 Unsupported prune silently succeeds

When minimumReleaseAgeExcludePrune changes a multi-line flow sequence, this branch returns false without the unsupported-inline preflight used by the public setter. The workspace update therefore succeeds without applying the prune, leaving stale minimumReleaseAgeExclude entries in the manifest instead of reporting ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

That one is deliberate, for two reasons.

Erroring here would diverge from the TypeScript writer more than skipping does. TS never fails on this shape — it prunes and re-emits:

# in
minimumReleaseAgeExclude: [
  [email protected], # pinned
  [email protected],
]
# out (TS, minimumReleaseAgeExcludePrune)
minimumReleaseAgeExclude:
  [
    [email protected] # pinned
  ]

So the options are "prune silently" (TS) versus "prune silently, or skip" (pacquet). Raising ERR_PNPM_WORKSPACE_MANIFEST_WRITER_UNSUPPORTED_INLINE_BLOCK would make pnpm install fail over a manifest formatting choice, in a stack whose counterpart succeeds — a worse parity break than postponing a cleanup.

It matches every other cleanup pass in this crate. catalogPrune (remove_unused_default_catalog, remove_unused_named_catalogs) and prune_allow_builds already return false for a block they cannot edit entry by entry, and always have. These passes are housekeeping that runs on every install; refusing to install is not on their menu. The user-initiated writers are the ones that must speak up, which is why set_minimum_release_age_excludes grew the preflight in 493b739.

Nothing is lost by skipping: the entries stay exactly as written, and the prune runs on the next install once the block is block style.

The gap worth closing eventually is a surgical entry delete inside a multi-line flow collection (drop the entry's span plus its comma, leave the surrounding comments), which would let both the prune and the setter handle this shape without flattening. That is a larger change than this PR, and I would rather not grow the flow parser under a bug fix.


Written by an agent (Claude Code, claude-opus-5[1m]).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 493b739

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

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

No code suggestions found for the PR.

@zkochan
zkochan merged commit f468e3e into main Aug 23, 2026
35 of 40 checks passed
@zkochan
zkochan deleted the fix-14108 branch August 23, 2026 15:03
KuSh added a commit to KuSh/pnpm that referenced this pull request Aug 25, 2026
…rite refusal

pnpm#14112 taught the shared workspace-manifest writer to edit
flow-style YAML blocks in place, matching the TypeScript writer. Update
both stacks' cleanupUnusedIgnoredGhsas coverage of a flow-style
auditConfig to assert the successful in-place edit instead of the
now-obsolete write refusal, and add the mirrored TypeScript test that
was previously impossible because of that divergence.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MgTb23fbaanpxBTp9p4WPe
zkochan pushed a commit to KuSh/pnpm that referenced this pull request Aug 25, 2026
…rite refusal

pnpm#14112 taught the shared workspace-manifest writer to edit
flow-style YAML blocks in place, matching the TypeScript writer. Update
both stacks' cleanupUnusedIgnoredGhsas coverage of a flow-style
auditConfig to assert the successful in-place edit instead of the
now-obsolete write refusal, and add the mirrored TypeScript test that
was previously impossible because of that divergence.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MgTb23fbaanpxBTp9p4WPe
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-workspace.yaml flow-style auditConfig: TS silently edits it, pacquet refuses

3 participants