Skip to content

refactor(pnpm): render output, answer bit why, and own the lockfile through @pnpm/napi - #10653

Merged
zkochan merged 6 commits into
teambit:masterfrom
zkochan:use-napi-reporter-and-why
Aug 24, 2026
Merged

zkochan merged 6 commits into
teambit:masterfrom
zkochan:use-napi-reporter-and-why

Conversation

@zkochan

@zkochan zkochan commented Aug 22, 2026 •

Copy link
Copy Markdown
Member

Installs already run on pnpm's Rust engine, but seven pnpm v11 JavaScript packages stayed behind it:

Package What it was doing
@pnpm/logger + @pnpm/cli.default-reporter re-rendering the v12 engine's event stream as pnpm's terminal output
@pnpm/deps.inspection.tree-builder + @pnpm/deps.inspection.list answering bit why
@pnpm/lockfile.fs reading and writing pnpm-lock.yaml
@pnpm/lockfile.filtering narrowing a lockfile to a component's importer
@pnpm/installing.modules-yaml reading .modules.yaml

Every one of them has to keep agreeing with a v12 engine about events and file formats it already owns — a coupling Bit ends up maintaining. @pnpm/napi now does all of it itself (pnpm/pnpm#14082), so all seven are dropped.

Output

install / rebuild get options.reporter, and the engine renders with the reporter pnpm install itself uses. Every reporting option Bit set maps across one-for-one, including the two that needed pnpm extension points:

  • the approve-builds instruction text → ignoredBuildsInstructionText
  • hiding linked @teambit/* core aspects from the packages-diff summary → hideLinkedPkgsDiff: ['@teambit/*']. filterPkgsDiff was a callback, and the engine's reporter is synchronous, so it can't be called across the addon boundary; as a name pattern it hides the same entries (linked ones only — an installed @teambit/* still shows).

Rendered chunks come back through an onOutput callback rather than being written by the engine. That's required, not stylistic: cli-raw.route.ts monkey-patches process.stdout.write to mirror output to a tty, and the CLI server swaps in a ServerSendOutStream that forwards to connected editors — a write from Rust would bypass both. ReportOptions.process (a whole spread process object that existed only to carry that stream) becomes outputStream.

bit why

getDependents reads the lockfile and returns the reverse trees; renderDependents prints them. The nameFormatter callback that rendered component ids instead of package names has no equivalent across the addon boundary, so Bit asks the engine for each node's componentId manifest field (manifestFields: ['componentId']) and writes displayName onto the trees before rendering — same output. .bit_roots importers are excluded via excludeProjectPatterns instead of a JS-side lockfile read.

This also drops the readWantedLockfile + per-importer package.json reads findUsages was doing in JS.

log-converter.ts goes too — it was the last @pnpm/logger reference and nothing imported it.

Lockfile

readLockfile / writeLockfile / filterLockfileByImporters / readModulesManifest replace the four JS entry points. The lockfile now crosses the boundary in the file's own shape rather than the in-memory one, which removes a conversion rather than adding one: calcDependenciesGraph used to read the object shape, mutate it, filter, and then convertToLockfileFile for the graph converter — which consumes the file shape. It now reads, mutates, and filters that shape throughout. The mutation reads ref.version where it read a bare string ref, and drops specifiers, which the file shape inlines next to each version.

The bit: block survives a read → edit → write through the engine: pnpm no longer drops top-level keys it does not define. Bit still re-asserts it after an install — an install builds a fresh lockfile, and Bit is writing that block's new depsRequiringBuild anyway.

getLockfileImporterId is inlined (one path.relative call), which was the only reason the ESM shim loaded @pnpm/lockfile.fs. The shim now loads @pnpm/deps.path alone.

What stays JavaScript, and why

  • @pnpm/deps.path — pure dep-path string parsing whose helpers run once per graph edge, millions of times on a large workspace. That is exactly the shape that should not go behind an FFI call.
  • @pnpm/lockfile.types, @pnpm/types, @pnpm/error — type-only, no runtime.
  • @pnpm/semver-diff, @pnpm/colorize-semver-diff, @pnpm/network.ca-file, @pnpm/node-fetch, @pnpm/network.fetch, @pnpm/plugin-trusted-deps, @pnpm/config.parse-overrides, @pnpm/registry-mock — small and unrelated to the engine (config.parse-overrides is used by the yarn package manager; registry-mock is e2e infra).

Verified

  • npm run lint (tsc --noEmit + oxlint --deny-warnings) clean
  • lynx.install driven through babel-register against a real [email protected] install: the engine rendered the progress line, the Packages: +2 summary, the dependencies diff, and the footer, and every chunk arrived on a host-supplied stream (a Writable standing in for ServerSendOutStream) — nothing was written to the process's own stdout
  • PnpmPackageManager#findUsages('is-number') against that workspace printed the expected tree, with is-odd rendered as acme.numbers/is-odd after a componentId was added to its manifest — i.e. the display-name path that replaced nameFormatter
  • the lockfile paths, end to end on a real install: the bit: block written by lynx.install, read back, edited, written, and re-read with importers/packages/snapshots intact; the current lockfile read and pnpmPruneModules keeping the right virtual-store dirs; .modules.yaml read through the engine; filterLockfileByImporters returning the component's closure
  • calcDependenciesGraph on a fixture where a component injects one workspace sibling via file: and links another: the injected sibling survives in the component's graph, the linked one is stripped, and an unrelated package is filtered out — the file-shape rewrite of that mutation
  • lockfile-deps-graph-converter.spec.ts (22 tests) passes

Blocked on

pnpm/pnpm#14082 landing and being released. The @pnpm/napi pin here is set to 12.0.0-rc.9 (the next prerelease); bump it if the release lands under a different number. Everything above was verified against a local build of that branch.

…npm/napi

Installs run on pnpm's Rust engine, but four pnpm v11 JavaScript packages
stayed behind it: `@pnpm/logger` and `@pnpm/cli.default-reporter` re-rendered
the engine's event stream, and `@pnpm/deps.inspection.tree-builder` +
`@pnpm/deps.inspection.list` answered `bit why`. Both jobs depend on a v11
package staying compatible with a v12 engine's events and lockfile — a
coupling Bit ends up maintaining. `@pnpm/napi` now does both itself
(pnpm/pnpm#TBD), so all four are dropped.

Output: `install` / `rebuild` get `options.reporter`, and the engine renders
with the reporter `pnpm install` itself uses. Every reporting option Bit set
maps across, including the two it relied on pnpm extension points for — the
approve-builds instruction text, and hiding linked `@teambit/*` core aspects
from the packages-diff summary (`filterPkgsDiff` is a callback the engine
cannot call synchronously, so it is expressed as a name pattern instead).

Rendered chunks come back through an `onOutput` callback rather than being
written by the engine. That is required, not stylistic: Bit monkey-patches
`process.stdout.write` to mirror output to a tty, and the CLI server swaps in
a stream that forwards to connected editors, both of which a write from Rust
would bypass. `ReportOptions.process` — a whole spread `process` object that
existed only to carry that stream — becomes `outputStream`.

`bit why`: `getDependents` reads the lockfile and returns the reverse trees,
`renderDependents` prints them. The `nameFormatter` callback that rendered
component ids instead of package names has no equivalent across the addon
boundary, so Bit asks the engine for the `componentId` manifest field and
writes `displayName` onto the trees before rendering them — same output.

Also removes `log-converter.ts`, the last `@pnpm/logger` reference, which
nothing imported.

Needs an `@pnpm/napi` release containing the engine-side change; the pin is
set to the next prerelease.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

refactor(pnpm): use @pnpm/napi for install output and bit why

✨ Enhancement ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Route install/rebuild terminal rendering through @pnpm/napi’s built-in reporter.
• Move bit why dependent-tree generation/rendering into the native engine.
• Drop legacy pnpm v11 JS reporter/inspection packages and simplify stream wiring.
Diagram

graph TD
  A["Bit CLI"] --> B["PnpmPackageManager"] --> C["lynx.ts"] --> D{{"@pnpm/napi"}}
  C --> E["ReporterOptions"] --> F["onOutput(chunk)"] --> G(("OutputStream"))
  B --> H["findUsages (why)"] --> D

  subgraph Legend
    direction LR
    _mod["Bit module"] ~~~ _ext{{"External/native"}} ~~~ _stream(("Stream"))
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Keep pnpm v11 JS reporter + log event bridging
  • ➕ Avoids reliance on new @pnpm/napi reporter surface area
  • ➕ Keeps fully JS-controlled formatting/hooks
  • ➖ Continues fragile coupling to v12 engine event/lockfile formats
  • ➖ Maintains extra dependencies and duplicate rendering logic
  • ➖ Still requires event re-serialization/compat shims
2. Let Rust engine write directly to process stdout/stderr
  • ➕ Simpler interface (no chunk callback)
  • ➕ Potentially less JS overhead
  • ➖ Bypasses Bit’s stdout monkey-patching and CLI server forwarding streams
  • ➖ Harder to integrate with editor-connected output plumbing
  • ➖ Makes output routing/teeing platform-dependent

Recommendation: Proceed with the PR’s approach: using @pnpm/napi’s built-in reporter + onOutput preserves Bit’s stream plumbing while removing ongoing maintenance of wire-compat JS packages. The remaining trade-off (loss of callback-style hooks like nameFormatter/filterPkgsDiff) is mitigated by manifestFields/componentId post-processing and pattern-based hideLinkedPkgsDiff, keeping output effectively equivalent with less cross-version coupling.

Files changed (3) +107 / -114

Refactor (2) +106 / -109
lynx.tsDelegate install/rebuild output rendering to @pnpm/napi reporter +71/-59

Delegate install/rebuild output rendering to @pnpm/napi reporter

• Replaces the v11 JS default-reporter + logger event bridging with engine-side reporter configuration. Introduces OutputStream/outputStream to route rendered chunks through a JS stream via an onOutput callback (needed for Bit’s stdout patching and CLI-server forwarding). Maps Bit reporting options to nodeApi.ReporterOptions, including ignoredBuildsInstructionText and hiding linked @teambit/* diffs.

scopes/dependencies/pnpm/lynx.ts

pnpm.package-manager.tsImplement 'bit why' via @pnpm/napi dependents APIs and update reporting stream wiring +35/-50

Implement 'bit why' via @pnpm/napi dependents APIs and update reporting stream wiring

• Replaces JS lockfile/package.json reading and deps.inspection tree building with nodeApi.getDependents + nodeApi.renderDependents, excluding '.bit_roots' importers via excludeProjectPatterns. Adds a post-pass that writes displayName from manifest.componentId (requested via manifestFields) to preserve Bit-style names. Updates reportOptions to use outputStream (ServerSendOutStream) instead of spreading a full process object.

scopes/dependencies/pnpm/pnpm.package-manager.ts

Other (1) +1 / -5
workspace.jsoncDrop pnpm v11 reporter/inspection deps and bump @pnpm/napi prerelease +1/-5

Drop pnpm v11 reporter/inspection deps and bump @pnpm/napi prerelease

• Removes @pnpm/logger, @pnpm/cli.default-reporter, and deps.inspection.* packages and updates the @pnpm/napi pin to 12.0.0-rc.9 to pick up reporter + dependents support.

workspace.jsonc

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

qodo-free-for-open-source-projects Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Eager native engine load 🐞 Bug ➹ Performance
Description
pnpm-prune-modules.ts now imports @pnpm/napi at module top-level, which can map/load the native
engine as soon as pnpm.package-manager.ts is imported (even if pruning is never invoked). This
contradicts the file’s own lazy-load intent and can increase startup cost or cause native-load
failures in code paths that previously didn't require the engine binary.
Code

scopes/dependencies/pnpm/pnpm-prune-modules.ts[4]

+import * as nodeApi from '@pnpm/napi';
Evidence
The PR introduces a new eager runtime import of @pnpm/napi in pnpm-prune-modules.ts. That module
is imported by pnpm.package-manager.ts at top-level, so evaluating pnpm.package-manager.ts will
evaluate pnpm-prune-modules.ts, triggering the eager native import. pnpm.package-manager.ts
itself explicitly documents that @pnpm/napi should be required lazily to avoid mapping the native
binary into every bit process, showing the intent that this new eager import violates.

scopes/dependencies/pnpm/pnpm-prune-modules.ts[2-6]
scopes/dependencies/pnpm/pnpm.package-manager.ts[25-35]
scopes/dependencies/pnpm/pnpm.package-manager.ts[62-69]

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

## Issue description
`scopes/dependencies/pnpm/pnpm-prune-modules.ts` imports `@pnpm/napi` at top-level, which eagerly loads the native engine when the module is evaluated. Since `PnpmPackageManager` imports `pnpmPruneModules` at module load time, this defeats the lazy-loading strategy intended to avoid mapping the native binary into every `bit` process.
### Issue Context
`PnpmPackageManager` explicitly documents a convention of requiring `@pnpm/napi` lazily to avoid startup overhead. `pnpm-prune-modules.ts` should follow the same pattern.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[2-26]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[25-35]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[62-69]
### Suggested change
1. Remove the top-level `import * as nodeApi from '@pnpm/napi'`.
2. Add a small local `loadNodeApi()` helper (like the one in `pnpm.package-manager.ts`) and call it inside `pnpmPruneModules()` right before `readLockfile()`.
Example sketch:

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


2. Prune may delete everything ✓ Resolved 🐞 Bug ≡ Correctness
Description
pnpmPruneModules() derives the set of required virtual-store directories only from
lockfile.snapshots; if snapshots is absent/empty (or the lockfile can’t be read),
dirsShouldBePresent becomes empty and the function may delete all package directories under
node_modules/.pnpm. This can break the workspace by removing installed packages even though the
lockfile still lists them under packages (a shape other parts of the codebase still assume for
lock.yaml).
Code

scopes/dependencies/pnpm/pnpm-prune-modules.ts[R16-18]

+  const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' });
+  const snapshots = (lockfile?.snapshots ?? {}) as Record<string, unknown>;
+  const dirsShouldBePresent = Object.keys(snapshots).map((depPath) => depPathToDirName(depPath));
Evidence
The changed code uses only lockfile.snapshots to compute the allowlist. If snapshots is
missing/empty, dirsShouldBePresent becomes [], making every directory “extraneous”. Elsewhere in
the repo, current lockfile parsing still reads from lockfile.packages, showing that packages is
a plausible/expected shape for lock.yaml content.

scopes/dependencies/pnpm/pnpm-prune-modules.ts[16-18]
scopes/dependencies/dependencies/dependencies.main.runtime.ts[620-624]
components/legacy/e2e-helper/e2e-fs-helper.ts[73-76]
pnpm-lock.yaml[28509-28530]
pnpm-lock.yaml[49695-49710]

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

## Issue description
`pnpmPruneModules()` computes `dirsShouldBePresent` from `lockfile.snapshots` only. If the current lockfile read via `nodeApi.readLockfile({ kind: 'current' })` returns `null` or returns an object without `snapshots`, the computed set becomes empty and the function can delete all virtual-store package directories.
### Issue Context
Other code paths that parse `node_modules/.pnpm/lock.yaml` still expect package dep paths under `lockfile.packages`.
### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[16-18]
### Suggested change
- Treat the dep-path source as `lockfile.snapshots ?? lockfile.packages` (or the union of both), and if neither exists (or the lockfile is null), return early (do not prune).
- Consider adding a small safety check: if the derived dep-path key set is empty but `pkgDirs` is non-empty, skip pruning unless you can prove the lockfile has no entries.

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


3. Rebuild bypasses output stream ✓ Resolved 🐞 Bug ≡ Correctness
Description
The rebuild() path constructs fresh rebuildReportOptions without carrying over
reportOptions.outputStream, so reporterOutputStream() falls back to process.stdout and
bypasses Bit’s CLI-server forwarding stream. In BIT_CLI_SERVER_NO_TTY mode this means rebuild
output will not be sent to connected clients/editors (and may bypass stdout monkey-patching
expectations).
Code

scopes/dependencies/pnpm/lynx.ts[R479-482]

+      const rebuildReportOptions: ReportOptions = { appendOnly: true, hideLifecycleOutput: true };
+      await nodeApi.rebuild(
+        {
+          ...installOptions,
Evidence
PnpmPackageManager.install() configures a ServerSendOutStream via reportOptions.outputStream
for CLI-server/no-tty mode, but lynx.install()’s returned rebuild() ignores it: it creates new
report options without outputStream, and reporterOutputStream() then defaults to
process.stdout, bypassing the server stream that actually forwards output to clients.

scopes/dependencies/pnpm/pnpm.package-manager.ts[241-253]
scopes/dependencies/pnpm/lynx.ts[476-489]
scopes/dependencies/pnpm/lynx.ts[616-618]
components/legacy/logger/pino-logger.ts[114-118]

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

## Issue description
`rebuild()` creates a new `rebuildReportOptions` object that omits `outputStream`. As a result, `reporterOutputStream()` defaults to `process.stdout` and rebuild output can bypass the CLI server’s forwarding stream.
### Issue Context
`install()` is called with `reportOptions.outputStream` set to a `ServerSendOutStream` when `BIT_CLI_SERVER_NO_TTY` is enabled. The rebuild path should reuse that same output routing.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[472-490]
- scopes/dependencies/pnpm/lynx.ts[573-618]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[241-253]
### Concrete fix
In `rebuild`, build report options by extending the existing ones, e.g.:
- `const rebuildReportOptions: ReportOptions = { ...options.reportOptions, appendOnly: true, hideLifecycleOutput: true };`
- Use `toReporterOptions(rebuildReportOptions)` and `reporterOutput(rebuildReportOptions)` so both reporter config and onOutput target the same stream.

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



Remediation recommended

4. Component IDs never render 🐞 Bug ≡ Correctness
Description
applyComponentIdNames() treats the manifest's componentId as an object, but Bit writes that
field as a serialized string, so scope and name are always undefined and bit why continues
rendering package names instead of component IDs.
Code

scopes/dependencies/pnpm/pnpm.package-manager.ts[R572-575]

+    const componentId = node.manifest?.componentId as { scope?: string; name?: string } | undefined;
+    if (componentId?.scope && componentId.name) {
+      node.displayName = `${componentId.scope}/${componentId.name}`;
+    }
Evidence
The new mapper reads object properties from componentId, while the package-manifest producer
stores component.id.serialize() directly as that field. Therefore the condition guarding
displayName cannot pass for Bit-generated manifests.

scopes/dependencies/pnpm/pnpm.package-manager.ts[570-576]
scopes/component/sources/package-json-file.ts[144-154]

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

## Issue description
`applyComponentIdNames()` assumes `manifest.componentId` is an object with `scope` and `name`, while Bit package manifests store it as a serialized component-ID string. Parse the string and set `displayName` to the equivalent scope/name form expected by `bit why`.
## Issue Context
Preserve the prior intended output without the component version, and safely leave nodes without a valid component ID unchanged.
## Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[570-576]
- scopes/component/sources/package-json-file.ts[149-154]

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


5. Reporter width can be invalid ✓ Resolved 🐞 Bug ☼ Reliability
Description
toReporterOptions() sets width to stream.columns - 2 whenever columns is present, which can
produce 0 or negative widths on very narrow terminals. This can cause malformed rendering or errors
in the engine reporter that expects a positive width.
Code

scopes/dependencies/pnpm/lynx.ts[R594-597]

+    width: stream.columns ? stream.columns - 2 : 80,
+    // chalk is the switch Bit already flips for its own output (the CLI
+    // server enables it per request and resets it afterwards), so the
+    // engine follows it rather than probing the terminal itself.
Evidence
The new reporter configuration directly computes width from columns without bounds checks, so
any small columns value yields an invalid width.

scopes/dependencies/pnpm/lynx.ts[208-214]
scopes/dependencies/pnpm/lynx.ts[580-599]

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

## Issue description
`width` is derived as `stream.columns - 2` when `columns` is set. If `columns <= 2`, `width` becomes `0` or negative.
### Issue Context
`OutputStream.columns` is optional, but when present it can be small (e.g., tiny terminals, misreported dimensions, or tests).
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[580-599]
### Concrete fix
Clamp to a sane minimum, e.g.:
- `const cols = stream.columns;`
- `width: typeof cols === 'number' ? Math.max(20, cols - 2) : 80` (pick an appropriate minimum for pnpm output), or at least `Math.max(1, cols - 2)`.

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


Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread scopes/dependencies/pnpm/lynx.ts Outdated
Comment on lines +479 to +482
const rebuildReportOptions: ReportOptions = { appendOnly: true, hideLifecycleOutput: true };
await nodeApi.rebuild(
{
...installOptions,

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

1. Rebuild bypasses output stream 🐞 Bug ≡ Correctness

The rebuild() path constructs fresh rebuildReportOptions without carrying over
reportOptions.outputStream, so reporterOutputStream() falls back to process.stdout and
bypasses Bit’s CLI-server forwarding stream. In BIT_CLI_SERVER_NO_TTY mode this means rebuild
output will not be sent to connected clients/editors (and may bypass stdout monkey-patching
expectations).
Agent Prompt
### Issue description
`rebuild()` creates a new `rebuildReportOptions` object that omits `outputStream`. As a result, `reporterOutputStream()` defaults to `process.stdout` and rebuild output can bypass the CLI server’s forwarding stream.

### Issue Context
`install()` is called with `reportOptions.outputStream` set to a `ServerSendOutStream` when `BIT_CLI_SERVER_NO_TTY` is enabled. The rebuild path should reuse that same output routing.

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[472-490]
- scopes/dependencies/pnpm/lynx.ts[573-618]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[241-253]

### Concrete fix
In `rebuild`, build report options by extending the existing ones, e.g.:
- `const rebuildReportOptions: ReportOptions = { ...options.reportOptions, appendOnly: true, hideLifecycleOutput: true };`
- Use `toReporterOptions(rebuildReportOptions)` and `reporterOutput(rebuildReportOptions)` so both reporter config and onOutput target the same stream.

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

Comment thread scopes/dependencies/pnpm/lynx.ts Resolved
Three pnpm v11 JavaScript packages were still in the install path, all of
them about a file the engine already owns: `@pnpm/lockfile.fs` read and
wrote `pnpm-lock.yaml`, `@pnpm/lockfile.filtering` narrowed one to a
component's importer, and `@pnpm/installing.modules-yaml` read
`.modules.yaml`. `@pnpm/napi` now exposes all three (pnpm/pnpm#14082), so
they are dropped.

The lockfile now crosses the boundary in the file's own shape rather than
the in-memory one, which removes a conversion rather than adding one:
`calcDependenciesGraph` used to read the object shape, mutate it, filter,
and then convert to the file shape for the graph converter — which consumes
the file shape. It now reads, mutates, and filters that shape throughout.
The mutation reads `ref.version` where it read a bare string ref, and drops
`specifiers`, which the file shape inlines next to each version.

The `bit:` block Bit records beside pnpm's keys survives a read/edit/write
through the engine: pnpm no longer drops top-level keys it does not define.
Bit still re-asserts the block after an install — an install builds a fresh
lockfile, and Bit is writing that block's new `depsRequiringBuild` anyway.

`getLockfileImporterId` is inlined; it is one `path.relative` call, and it
was the only reason the ESM shim loaded `@pnpm/lockfile.fs`. The shim now
loads `@pnpm/deps.path` alone, which stays a JavaScript dependency on
purpose: it is pure dep-path string parsing whose helpers run once per graph
edge, and that is not a shape to put behind an FFI call. Every other
remaining `@pnpm/*` dependency is type-only or unrelated to the engine.

Needs the same `@pnpm/napi` release as the reporter and dependents change.
@zkochan zkochan changed the title refactor(pnpm): render install output and answer bit why through @pnpm/napi refactor(pnpm): render output, answer bit why, and own the lockfile through @pnpm/napi Aug 22, 2026
Comment on lines +16 to +18
const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' });
const snapshots = (lockfile?.snapshots ?? {}) as Record<string, unknown>;
const dirsShouldBePresent = Object.keys(snapshots).map((depPath) => depPathToDirName(depPath));

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

1. Prune may delete everything 🐞 Bug ≡ Correctness

pnpmPruneModules() derives the set of required virtual-store directories only from
lockfile.snapshots; if snapshots is absent/empty (or the lockfile can’t be read),
dirsShouldBePresent becomes empty and the function may delete all package directories under
node_modules/.pnpm. This can break the workspace by removing installed packages even though the
lockfile still lists them under packages (a shape other parts of the codebase still assume for
lock.yaml).
Agent Prompt
### Issue description
`pnpmPruneModules()` computes `dirsShouldBePresent` from `lockfile.snapshots` only. If the current lockfile read via `nodeApi.readLockfile({ kind: 'current' })` returns `null` or returns an object without `snapshots`, the computed set becomes empty and the function can delete all virtual-store package directories.

### Issue Context
Other code paths that parse `node_modules/.pnpm/lock.yaml` still expect package dep paths under `lockfile.packages`.

### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[16-18]

### Suggested change
- Treat the dep-path source as `lockfile.snapshots ?? lockfile.packages` (or the union of both), and if neither exists (or the lockfile is null), return early (do not prune).
- Consider adding a small safety check: if the derived dep-path key set is empty but `pkgDirs` is non-empty, skip pruning unless you can prove the lockfile has no entries.

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

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

Copy link
Copy Markdown

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

Three findings from review of the engine rewiring:

`rebuild` built its reporting options from scratch, so the CLI server's
forwarding stream — and the width and throttle the caller chose — reached
the install's output but not the rebuild's. It now extends the install's
options rather than replacing them.

The reporter width came from `columns - 2` unconditionally, which is zero or
negative on a one- or two-column terminal. Floored at one column (the engine
floors it too, so neither side can hand the renderer a width it cannot
honor).

`pnpmPruneModules` treated an unreadable current lockfile as "nothing
belongs in the virtual store" and would delete every package directory,
leaving the workspace needing a reinstall. A missing lockfile now stops the
prune. This behavior predates the rewiring — the old code read
`lockfile?.packages ?? {}` — but the line was being rewritten anyway and the
hazard is real.

Note for review: the dep paths come from `snapshots`, not `packages`. Those
are the same map in the in-memory lockfile shape this code used to read, but
in the file shape it now reads, `snapshots` is keyed by the peer-suffixed
dep path — which is what the virtual store's directory names are derived
from — while `packages` is keyed without the suffix and would not match.
@zkochan

zkochan commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

All three Qodo findings fixed in 8b77421.

Rebuild bypassed the output stream — real, and the fix is worth more than the report suggests. rebuild built its reporting options from scratch, so the CLI server's forwarding stream never reached it; it now extends the install's options, which also carries the width and throttle the caller chose. Verified: with a stand-in host stream, both the install and the rebuild render into it and nothing reaches process.stdout.

Width can be invalid — real. Floored at one column here, and also floored in the engine (pnpm/pnpm#14082), so neither side can hand the renderer a width it cannot honor.

Prune may delete everything — the hazard is real and now guarded: a missing current lockfile stops the prune instead of reading as "nothing belongs here". Worth noting it predates this PR — the old code was Object.keys(lockfile?.packages ?? {}), equally empty on a null lockfile — but the line was being rewritten anyway.

I did not take the suggested snapshots ?? packages fallback, because it would be wrong. In the in-memory lockfile shape this code used to read, packages is the snapshot map, keyed by the peer-suffixed dep path. In the file shape it now reads they are two different maps: snapshots keeps the peer-suffixed keys — which is what depPathToDirName turns into virtual-store directory names — while packages is keyed without the suffix. Falling back to packages would compute directory names that match nothing and delete every peer-suffixed package.

Verified end to end: install and rebuild both rendering to a host stream that reports a 1-column terminal, and a prune against a deleted lock.yaml leaving the virtual store untouched.

import path from 'path';
import { difference } from 'lodash';
import type * as LockfileFs from '@pnpm/lockfile.fs';
import * as nodeApi from '@pnpm/napi';

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

1. Eager native engine load 🐞 Bug ➹ Performance

pnpm-prune-modules.ts now imports @pnpm/napi at module top-level, which can map/load the native
engine as soon as pnpm.package-manager.ts is imported (even if pruning is never invoked). This
contradicts the file’s own lazy-load intent and can increase startup cost or cause native-load
failures in code paths that previously didn't require the engine binary.
Agent Prompt
### Issue description
`scopes/dependencies/pnpm/pnpm-prune-modules.ts` imports `@pnpm/napi` at top-level, which eagerly loads the native engine when the module is evaluated. Since `PnpmPackageManager` imports `pnpmPruneModules` at module load time, this defeats the lazy-loading strategy intended to avoid mapping the native binary into every `bit` process.

### Issue Context
`PnpmPackageManager` explicitly documents a convention of requiring `@pnpm/napi` lazily to avoid startup overhead. `pnpm-prune-modules.ts` should follow the same pattern.

### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[2-26]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[25-35]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[62-69]

### Suggested change
1. Remove the top-level `import * as nodeApi from '@pnpm/napi'`.
2. Add a small local `loadNodeApi()` helper (like the one in `pnpm.package-manager.ts`) and call it inside `pnpmPruneModules()` right before `readLockfile()`.

Example sketch:
```ts
import type * as NodeApi from '@pnpm/napi';

function loadNodeApi(): typeof NodeApi {
  // eslint-disable-next-line global-require, import/no-dynamic-require
  return require('@pnpm/napi') as typeof NodeApi;
}

export async function pnpmPruneModules(rootDir: string) {
  const nodeApi = loadNodeApi();
  const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' });
  ...
}
```

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

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8b77421

…leased rc.9

12.0.0-rc.9 is published, so the pin this branch already carries resolves for
real. Installing it drops @pnpm/installing.modules-yaml from the root
node_modules along with the rest of the JS packages this branch replaced
(cli.default-reporter, deps.inspection.*, lockfile.fs, lockfile.filtering,
@pnpm/logger) - and three e2e suites still imported that package to read
.modules.yaml, so they no longer resolved it.

rc.9 exposes readModulesManifest, so the read goes through the engine like the
rest of the pnpm integration, and the helper the three suites each carried their
own copy of now lives in one place.

The helper reaches the addon through a static namespace import. The addon
assigns module.exports from a call, so cjs-module-lexer detects no named exports
and node's esm loader - which is what babel-register's untransformed `import()`
reaches - hands back a namespace holding only `default`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6a7f566

…t fix

rc.8's hoister collapsed every peer variant of a package version onto
one copy, which for injected directory deps rewired one root
component's copy onto another's — the hoisted root-components e2e
failed with `expected '1.0.0' to match /^2\./`. rc.10 ships the fix
(pnpm/pnpm#14126): directory `file:` snapshots keep their peer
suffix, so each root component's injected copies stay its own.

Verified against the published binary: the hoisted root-components
suite passes (12 passing, the two previously failing react-17 tests
included).

Co-Authored-By: Claude Fable 5 <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 8bec2ec

Comment on lines +572 to +575
const componentId = node.manifest?.componentId as { scope?: string; name?: string } | undefined;
if (componentId?.scope && componentId.name) {
node.displayName = `${componentId.scope}/${componentId.name}`;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

1. Component ids never render 🐞 Bug ≡ Correctness

applyComponentIdNames() treats the manifest's componentId as an object, but Bit writes that
field as a serialized string, so scope and name are always undefined and bit why continues
rendering package names instead of component IDs.
Agent Prompt
## Issue description
`applyComponentIdNames()` assumes `manifest.componentId` is an object with `scope` and `name`, while Bit package manifests store it as a serialized component-ID string. Parse the string and set `displayName` to the equivalent scope/name form expected by `bit why`.

## Issue Context
Preserve the prior intended output without the component version, and safely leave nodes without a valid component ID unchanged.

## Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[570-576]
- scopes/component/sources/package-json-file.ts[149-154]

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

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

Copy link
Copy Markdown

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

@zkochan
zkochan enabled auto-merge (squash) August 24, 2026 15:40
@github-actions github-actions Bot mentioned this pull request Aug 24, 2026
@zkochan
zkochan merged commit d065a39 into teambit:master Aug 24, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants