Skip to content

deps: migrate pnpm internals to v12 - #10293

Closed
zkochan wants to merge 1 commit into
teambit:masterfrom
zkochan:pnpm11
Closed

zkochan wants to merge 1 commit into
teambit:masterfrom
zkochan:pnpm11

Conversation

@zkochan

@zkochan zkochan commented Apr 14, 2026

Copy link
Copy Markdown
Member

Summary

  • Rename 17 @pnpm/* deps in workspace.jsonc to v11's @pnpm/<domain>.<leaf> naming (e.g. @pnpm/core → @pnpm/installing.deps-installer, @pnpm/config → @pnpm/config.reader), bump in-monorepo packages to 1100.0.0.
  • Adapt to v11 breaking API changes: mutateModules now uses allowBuilds: Record<string, boolean | string> (plus dangerouslyAllowAllBuilds) in place of the removed neverBuiltDependencies / onlyBuiltDependencies / ignoredBuiltDependencies trio.
  • Config.rawConfig → Config.authConfig rename; read network settings (maxSockets, fetchRetries, etc.) from typed Config fields instead of rawConfig ini lookups.
  • Convert flat auth rawConfig to the new configByUri: Record<string, RegistryConfig> shape for CreateStoreControllerOptions; switch generateResolverAndFetcher to createResolver since both callers only use .resolve (avoids the now-required storeIndex on createClient).
  • Rename sortPackages → sortProjects, createPkgGraph → createProjectsGraph, createOrConnectStoreController → createStoreController; supply now-required globalVirtualStoreDir to getPeerDependencyIssues.

Test plan

  • npm run check-types passes
  • bit compile — 310/310 components compile
  • install new dependencies (using pnpm) e2e — 5/5 pass
  • install missing dependencies (when all packages exist) e2e — 2/2 pass (covers add/tag/export/import/reinstall)
  • skipping compilation on install e2e — 2/2 pass
  • Broader e2e suite
  • CI green

@zkochan
zkochan force-pushed the pnpm11 branch 2 times, most recently from 3d42363 to 37f4352 Compare May 5, 2026 13:41
@zkochan
zkochan marked this pull request as ready for review May 6, 2026 08:20
Copilot AI review requested due to automatic review settings May 6, 2026 08:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR migrates Bit’s internal pnpm integration to pnpm v11-era packages (1100.x), updating dependency names and adapting Bit’s pnpm/yarn package-manager glue code to pnpm’s breaking API and module-format (ESM) changes.

Changes:

  • Renames and bumps @pnpm/* dependencies in workspace.jsonc to pnpm v11 package naming and versions.
  • Updates pnpm/yarn integration code for pnpm v11 APIs (config/auth shape, resolver creation, store controller creation, peer issues options, project graph/sorting).
  • Adds CJS shims + adjusts Babel config to safely load ESM-only pnpm modules in test/build environments without breaking mocha/Babel require chains.

Reviewed changes

Copilot reviewed 25 out of 26 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
workspace.jsonc Renames pnpm internal deps to v11 package names and bumps versions.
scopes/workspace/workspace/workspace-aspects-loader.ts Removes unreachable code in error handling path.
scopes/typescript/typescript/schema-extractor-context.ts Removes unreachable return after throwing.
scopes/scope/objects/models/dependencies-graph.ts Updates pnpm dep-path import to new package name.
scopes/pkg/pkg/packer.ts Switches pnpm pack command loading to ESM-safe dynamic loader shim.
scopes/pkg/pkg/load-pnpm-pack.cjs New CJS shim to import() ESM-only pnpm releasing commands for packing.
scopes/harmony/aspect/babel/babel-config.ts Adjusts preset-env to avoid transforming dynamic import().
scopes/dependencies/yarn/yarn.package-manager.ts Updates pnpm overrides parser import to v11 package.
scopes/dependencies/pnpm/read-config.ts Switches pnpm config reader import to v11 package.
scopes/dependencies/pnpm/pnpm.package-manager.ts Adapts network config reading + lockfile graph converter init + updated pnpm module imports.
scopes/dependencies/pnpm/pnpm-error-to-bit-error.spec.ts Avoids importing ESM-only @pnpm/error by stubbing a PnpmError-like object.
scopes/dependencies/pnpm/lynx.ts Migrates pnpm install/resolver/store controller APIs and script/build policy wiring to v11.
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts Adds async init + ESM loading shim for ESM-only pnpm modules; adjusts types.
scopes/dependencies/pnpm/lockfile-deps-graph-converter.spec.ts Ensures converter init runs before tests; minor structure tweaks.
scopes/dependencies/pnpm/load-pnpm-esm.cjs New CJS shim to import() ESM-only @pnpm/deps.path and @pnpm/lockfile.fs.
scopes/dependencies/pnpm/get-registries.ts Uses config.authConfig in place of rawConfig for credential extraction.
scopes/dependencies/pnpm/get-proxy-config.ts Updates config type import and no-proxy config source.
scopes/dependencies/dependency-resolver/package-manager.ts Updates pnpm peer issues type import to v11 package.
scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts Updates npm resolver import to v11 package.
scopes/component/modules/merge-helper/merge-files.ts Removes unreachable throw err after throwing a new error.
e2e/harmony/pnpm-default-hoisting.e2e.ts Uses ESM-safe dynamic import for modules manifest reading.
e2e/harmony/pkg-manager-config.e2e.ts Removes pnpm-specific capsule rc test section; keeps Yarn case.
e2e/harmony/dependency-resolver.e2e.ts Uses ESM-safe dynamic import for modules manifest reading.
components/legacy/e2e-helper/npm-ci-registry.ts Switches pnpm fetch import to dynamic ESM import (@pnpm/network.fetch).
babel.config.js Ensures Babel doesn’t transform dynamic import() (needed for ESM-only pnpm deps).

Comment on lines +33 to +41
export async function init(): Promise<void> {
if (loaded) return;
const { loadEsm } = require('./load-pnpm-esm.cjs') as {
loadEsm: () => Promise<{ dp: typeof Dp; getLockfileImporterId: typeof GetLockfileImporterId }>;
};
const m = await loadEsm();
dp = m.dp;
getLockfileImporterId = m.getLockfileImporterId;
loaded = true;
Comment on lines 68 to 70
after(() => {
npmCiRegistry.destroy();
});
Copilot AI review requested due to automatic review settings May 7, 2026 12:51

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated 3 comments.

Comment on lines 1 to 4
import semver from 'semver';
import type { LockfilePackageInfo } from '@pnpm/lockfile.types';
import * as dp from '@pnpm/dependency-path';
import * as dp from '@pnpm/deps.path';

Comment on lines 10 to 13
(supportNpmCiRegistryTesting ? describe : describe.skip)(
'package manager rc file is read from the workspace directory when installation is in a capsule',
'workspace .yarnrc.yml is read by Yarn when installation is in a capsule',
function () {
this.timeout(0);
import { buildDependentsTree } from '@pnpm/reviewing.dependencies-hierarchy';
import { renderDependentsTree } from '@pnpm/list';
import type { Modules } from '@pnpm/installing.modules-yaml';
import { readModulesManifest } from '@pnpm/installing.modules-yaml';
Copilot AI review requested due to automatic review settings June 1, 2026 12:00

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated 4 comments.

Comment on lines 1 to 4
import semver from 'semver';
import type { LockfilePackageInfo } from '@pnpm/lockfile.types';
import * as dp from '@pnpm/dependency-path';
import * as dp from '@pnpm/deps.path';

Comment on lines 10 to 12
(supportNpmCiRegistryTesting ? describe : describe.skip)(
'package manager rc file is read from the workspace directory when installation is in a capsule',
'workspace .yarnrc.yml is read by Yarn when installation is in a capsule',
function () {
Comment on lines 1 to 4
import semver from 'semver';
import type { LockfilePackageInfo } from '@pnpm/lockfile.types';
import * as dp from '@pnpm/dependency-path';
import * as dp from '@pnpm/deps.path';

Comment on lines 10 to 12
(supportNpmCiRegistryTesting ? describe : describe.skip)(
'package manager rc file is read from the workspace directory when installation is in a capsule',
'workspace .yarnrc.yml is read by Yarn when installation is in a capsule',
function () {
Copilot AI review requested due to automatic review settings June 1, 2026 15:04

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.

Pull request overview

Copilot reviewed 25 out of 26 changed files in this pull request and generated 2 comments.

Comment on lines +25 to +31
// @pnpm/deps.path and @pnpm/lockfile.fs are ESM-only; load them through a .cjs
// shim so the require() chain in the build capsule's mocha runner doesn't trip
// on the transitive ESM import. Call `init()` once before invoking the public
// converters; helpers reach for these module-level slots synchronously.
let dp!: typeof Dp;
let getLockfileImporterId!: typeof GetLockfileImporterId;
let loading: Promise<void> | undefined;
Comment on lines 10 to 12
(supportNpmCiRegistryTesting ? describe : describe.skip)(
'package manager rc file is read from the workspace directory when installation is in a capsule',
'workspace .yarnrc.yml is read by Yarn when installation is in a capsule',
function () {
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Workspace pkgs scrubbed 🐞 Bug ≡ Correctness ⭐ New
Description
convertGraphToLockfile() pre-populates failedWorkspaceComponentPkgs with every workspace
component pkgId, so scrubPkgsFromLockfile() will delete those package/snapshot entries and remove
their references even when they resolved successfully. This can cause the graph-derived lockfile to
omit valid workspace-component dependencies (particularly when there is no existing lockfile to
merge), defeating the goal of avoiding re-resolution and potentially producing a broken/incomplete
lockfile subset.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[R369-376]

  const pkgsToResolve = getPkgsToResolve(lockfile, manifests);
  const failedWorkspaceComponentPkgs = new Set<string>();
+  for (const pkgId of getWorkspaceComponentPkgIds(lockfile, graph, manifests)) {
+    failedWorkspaceComponentPkgs.add(pkgId);
+  }
  await Promise.all(
    pkgsToResolve.map(async (pkgToResolve) => {
      if (lockfile.packages[pkgToResolve.pkgId].resolution == null) {
Evidence
The code adds all workspace-component pkgIds into a set named failedWorkspaceComponentPkgs and
then scrubs every pkgId in that set from the lockfile. getWorkspaceComponentPkgIds() selects
workspace component pkgIds based on manifests/graph membership (not failure), and
scrubPkgsFromLockfile() deletes those pkg entries and removes matching dependencies from
snapshots/importers. This conflicts with the lockfile merge intent to avoid unnecessary
re-resolution.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-443]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[500-516]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[648-682]
scopes/dependencies/pnpm/pnpm.package-manager.ts[573-583]

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

### Issue description
`convertGraphToLockfile()` builds a set named `failedWorkspaceComponentPkgs`, but it is currently pre-filled with *all* workspace component package IDs (via `getWorkspaceComponentPkgIds`). Later, any non-empty set is passed to `scrubPkgsFromLockfile()`, which deletes those entries and removes references from snapshots/importers.

This makes the “failed” scrub path run even when nothing failed, which can yield an incomplete graph-derived lockfile (especially when generating a lockfile in a workspace that doesn’t already have one to merge with).

### Issue Context
- `getWorkspaceComponentPkgIds()` returns workspace component pkgIds present in the generated lockfile (not failed ones).
- `scrubPkgsFromLockfile()` deletes those pkgIds from `packages` and removes corresponding deps from snapshots/importers.
- The dependency-graph lockfile generation is intended to preserve locked versions and avoid re-resolving (see merge commentary in pnpm.package-manager).

### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-442]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[500-516]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[648-682]

### Suggested fix
- Do **not** pre-populate `failedWorkspaceComponentPkgs` with all workspace component pkgIds.
- Keep a separate `workspaceComponentPkgIds` set/list if you need to treat workspace components specially for other logic.
- Only add pkgIds to `failedWorkspaceComponentPkgs` when:
 - `resolve()` throws `ERR_PNPM_NO_MATCHING_VERSION` for a component pkgId, **or**
 - after resolution, the pkg still has no usable `resolution` and it’s a component package.
- Add/adjust a unit test that proves a workspace component with a valid resolution is retained (i.e., not scrubbed) and that only genuinely failing workspace component pkgIds are scrubbed.

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


2. Alias deps pruned 🐞 Bug ≡ Correctness
Description
The new lockfile reachability pruning builds child dep paths as ${name}@${ref}, which fails for
pnpm alias refs where ref already encodes a different depPath (e.g. `uri-js:
[email protected]`). As a result, alias targets can be treated as unreachable and deleted from
packages/snapshots, yielding an incomplete/invalid lockfile for subsequent installs.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[R518-540]

+function dropUnreachableLockfileEntries(lockfile: BitLockfileFile): void {
+  const reachablePackages = new Set<string>();
+  const reachableSnapshots = new Set<string>();
+  const visit = (depPath: string) => {
+    if (reachableSnapshots.has(depPath)) return;
+    reachableSnapshots.add(depPath);
+    reachablePackages.add(dp.removeSuffix(depPath));
+    const snapshot = lockfile.snapshots?.[depPath];
+    if (!snapshot) return;
+    for (const depType of ['dependencies', 'optionalDependencies'] as const) {
+      for (const [name, ref] of Object.entries(snapshot[depType] ?? {})) {
+        if (ref.startsWith('link:') || ref.startsWith('file:')) continue;
+        visit(`${name}@${ref}`);
+      }
+    }
+  };
+  for (const importer of Object.values(lockfile.importers ?? {})) {
+    for (const depType of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {
+      for (const [name, { version }] of Object.entries(importer[depType] ?? {})) {
+        if (version.startsWith('link:') || version.startsWith('file:')) continue;
+        visit(`${name}@${version}`);
+      }
+    }
Evidence
Both pruning walkers traverse snapshots/importers by concatenating ${name}@${ref}. The repo’s own
pnpm-lock.yaml shows alias-style refs (uri-js: [email protected]) while the actual lockfile
key is [email protected], so the constructed key won’t match and the target can be pruned as
“unreachable.”

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[518-540]
scopes/dependencies/pnpm/pnpm.package-manager.ts[643-667]
pnpm-lock.yaml[103702-103708]
pnpm-lock.yaml[46070-46072]

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

## Issue description
Two new lockfile-pruning walkers assume every dependency reference can be traversed by concatenating `${name}@${ref}`. This breaks pnpm alias representation where the value is already a depPath for a *different* package name (e.g. `uri-js: [email protected]`). In that case traversal never reaches `[email protected]`, and it may be deleted from `packages`/`snapshots`.
### Issue Context
In `pnpm-lock.yaml`, alias deps can appear as `uri-js: [email protected]` (not `uri-js: 1.0.1`). The existing lockfile keys for that target are `[email protected]`, not `uri-js@[email protected]`.
### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[518-540]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[643-667]
### Concrete fix approach
- In `lockfile-deps-graph-converter.ts`, use pnpm’s dep-path helper instead of string concatenation:
- Replace `visit(`${name}@${ref}`)` / `visit(`${name}@${version}`)` with `const child = dp.refToRelative(refOrVersion, name); if (child) visit(child);`
- This correctly handles semver refs, peer suffixes, patch hashes, and alias depPaths.
- In `pnpm.package-manager.ts` (no `dp` available synchronously), add a small normalization helper:
- If the ref/version starts with a digit (e.g. `1.2.3(...)`), treat it as a version and visit `${name}@${ref}`.
- Otherwise (e.g. `[email protected]` or `@scope/[email protected]`), treat it as an already-formed depPath and visit `ref` directly.
- Add a regression test (unit-level) with a minimal lockfile containing an alias dependency to ensure pruning retains the alias target package + snapshot.

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


3. Wildcard range overwrite 🐞 Bug ≡ Correctness
Description
DependenciesGraph.merge() treats same-name direct deps as identical when either specifier is '*' /
empty, and may overwrite the existing node id with a higher version without checking it satisfies
the non-wildcard range. This can cause convertGraphToLockfile() to write a lockfile that resolves a
dependency version outside the manifest’s declared semver constraint, leading to incorrect installs.
Code

scopes/scope/objects/models/dependencies-graph.ts[R260-264]

+function isSameDirectDependency(dep1: DependencyNeighbour, dep2: DependencyNeighbour): boolean {
+  if (!dep1.name || !dep2.name) return dep1.id === dep2.id;
+  if (dep1.name !== dep2.name) return false;
+  return dep1.specifier === dep2.specifier || isWildcardSpecifier(dep1.specifier) || isWildcardSpecifier(dep2.specifier);
+}
Evidence
The merge logic can overwrite the selected resolved version (id) while keeping the original
specifier, and lockfile generation later uses that specifier match to choose the id that
becomes the lockfile version ref. This makes it possible to emit a lockfile version that violates
the manifest’s semver range when a wildcard dep is merged with a constrained dep of the same name.

scopes/scope/objects/models/dependencies-graph.ts[78-101]
scopes/scope/objects/models/dependencies-graph.ts[260-268]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[339-363]
components/legacy/scope/scope.ts[763-777]
scopes/component/component-writer/component-writer.main.runtime.ts[121-134]
scopes/dependencies/pnpm/pnpm.package-manager.ts[92-112]

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

## Issue description
`DependenciesGraph.merge()` can merge two direct dependencies of the same name even when only one has a wildcard specifier (`*`/empty). It then may replace the existing dependency `id` with a higher version, without ensuring that higher version satisfies the stricter (non-wildcard) semver range.
This can corrupt downstream lockfile generation: `convertGraphToLockfile()` matches importers by `directDep.specifier === manifest specifier`, so the stricter specifier can remain while the selected `id` points at an incompatible higher version.
### Issue Context
This merged dependencies graph is used during installation/lockfile generation for imported components, so an incorrect merge can affect real installs.
### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[78-101]
- scopes/scope/objects/models/dependencies-graph.ts[260-268]
### Suggested fix approach
1. Tighten `isSameDirectDependency()` so wildcard does **not** automatically unify with a constrained specifier. For example:
- Consider deps the same only when:
- `name` matches AND specifiers are exactly equal, OR
- both specifiers are wildcard/empty.
2. Additionally (or alternatively), before overwriting `existingDirectDep.id` with `directDep.id`, ensure the candidate version satisfies the effective constraint:
- If `existingDirectDep.specifier` is a valid semver range, extract the version from `directDep.id` and validate with `semver.satisfies(version, existingDirectDep.specifier)`.
- Only upgrade when the candidate version is compatible.
3. Add a regression test where one graph has `foo` with `^1.0.0` and another has `foo` with `*` resolving to `2.0.0`, and assert the merged graph does not pick `2.0.0` for the `^1.0.0` specifier.

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


View more (9)
4. Missing pnpm auth merge 🐞 Bug ≡ Correctness
Description
lynx.install() builds authHeaderByUri only from getAuthConfig(registries) and never merges
pnpmConfig.config.authConfig from readConfig(), unlike generateResolverAndFetcher(). Installs
that rely on user/workspace .npmrc credentials can fail against authenticated registries because
nodeApi.install() won’t receive those headers.
Code

scopes/dependencies/pnpm/lynx.ts[R377-385]

+  const installOptions: nodeApi.InstallOptions = {
dir: rootDir,
-    storeController: storeController.ctrl,
-    preferFrozenLockfile: true,
-    pruneLockfileImporters: true,
-    lockfileOnly: options.lockfileOnly ?? false,
-    modulesCacheMaxAge: Infinity, // pnpm should never prune the virtual store. Bit does it on its own.
+    projects,
+    storeDir,
+    cacheDir,
registries: registries.toMap(),
-    resolutionMode: 'highest',
-    rawConfig: authConfig,
-    hooks: { readPackage },
-    externalDependencies,
-    strictPeerDependencies: false,
+    authHeaderByUri: buildAuthHeaderByUri(getAuthConfig(registries) as Record<string, unknown>),
+    proxyConfig: toNodeApiProxyConfig(proxyConfig),
+    networkConfig: toNodeApiNetworkConfig(networkConfig),
Evidence
The resolver path explicitly merges pnpm’s resolved authConfig with Bit registry auth, but the
install path does not, and callers already read pnpm config without passing its authConfig into
lynx.install().

scopes/dependencies/pnpm/lynx.ts[161-188]
scopes/dependencies/pnpm/lynx.ts[377-385]
scopes/dependencies/pnpm/pnpm.package-manager.ts[140-202]

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

## Issue description
`lynx.install()` currently computes `authHeaderByUri` from Bit registries only, ignoring pnpm’s resolved `config.authConfig` (which includes user/workspace `.npmrc` auth). This can break authenticated installs.
### Issue Context
`generateResolverAndFetcher()` already merges pnpm config auth with Bit registry auth, but `install()` does not.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[161-189]
- scopes/dependencies/pnpm/lynx.ts[377-385]
### Suggested change
In `install()`, call `readConfig()` (ideally with the same config root dir used by the package manager) and build headers from a merged auth config, e.g.:
- `const pnpmConfig = await readConfig(rootDir)` (or pass down `packageManagerConfigRootDir`)
- `const mergedAuthConfig = { ...pnpmConfig.config.authConfig, ...getAuthConfig(registries) }`
- `authHeaderByUri: buildAuthHeaderByUri(mergedAuthConfig)`

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


5. Empty resolver dir 🐞 Bug ≡ Correctness
Description
generateResolverAndFetcher() forwards `dir: resolveOpts.projectDir ?? resolveOpts.lockfileDir ??
'' into nodeApi.resolveDependency`, so callers that pass empty strings end up invoking the
resolver with an empty directory. convertGraphToLockfile() currently calls resolve() with
lockfileDir: '' and projectDir: '', so lockfile generation can fail or resolve using config from
an unintended working directory.
Code

scopes/dependencies/pnpm/lynx.ts[R162-174]

+  const mergedAuthConfig = Object.assign({}, pnpmConfig.config.authConfig, authConfig) as Record<string, unknown>;
+  const authHeaderByUri = buildAuthHeaderByUri(mergedAuthConfig);
+  const registriesMap = registries.toMap();
+  const resolve: ResolveFunction = (wantedDep, resolveOpts) =>
+    nodeApi.resolveDependency(wantedDep, {
+      dir: resolveOpts.projectDir ?? resolveOpts.lockfileDir ?? '',
+      cacheDir,
+      registries: registriesMap,
+      authHeaderByUri,
+      proxyConfig: proxyConfig ? toNodeApiProxyConfig(proxyConfig) : undefined,
+      networkConfig: networkConfig ? toNodeApiNetworkConfig(networkConfig) : undefined,
+      fullMetadata,
+    });
Evidence
The resolver wrapper explicitly forwards dir computed with ?? '', and the lockfile graph
converter passes empty-string lockfileDir/projectDir, so dir becomes '' (not nullish) and
reaches the native resolver unchanged.

scopes/dependencies/pnpm/lynx.ts[147-175]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-386]

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

## Issue description
`nodeApi.resolveDependency` is invoked with `dir` derived via nullish coalescing (`??`). Empty strings are not nullish, so `dir` can become `''`, which is not a meaningful base directory for resolution/config discovery.
## Issue Context
At least one internal caller (`convertGraphToLockfile`) passes empty strings for `projectDir`/`lockfileDir`, which now propagate into the resolver due to the new implementation.
## Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[147-175]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-386]
## Concrete fix
1) In `generateResolverAndFetcher`, treat empty string as missing by using `||` (or explicitly checking for a non-empty string), and fall back to a safe default:

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


6. noProxy from authConfig 🐞 Bug ≡ Correctness
Description
getProxyConfig() sets noProxy from config.authConfig.noproxy, which is not the typed
proxy-bypass setting and may not contain the user’s .npmrc no-proxy value. As a result, dependency
downloads can incorrectly go through the proxy even when the user configured domains to bypass it.
Code

scopes/dependencies/pnpm/get-proxy-config.ts[R4-11]

export function getProxyConfig(config: Config): PackageManagerProxyConfig {
const httpProxy = config.httpProxy;
const httpsProxy = config.httpsProxy || httpProxy;
const proxyConfig: PackageManagerProxyConfig = {
httpProxy,
httpsProxy,
-    noProxy: config.rawConfig.noproxy,
+    noProxy: config.authConfig.noproxy,
};
Evidence
The pnpm proxy-config adapter reads noProxy from authConfig, while the dependency-resolver
configuration model and merging logic expect a dedicated noProxy value to be carried through; this
mismatch can drop proxy-bypass settings.

scopes/dependencies/pnpm/get-proxy-config.ts[1-13]
scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts[55-59]
scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[805-809]

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

## Issue description
`getProxyConfig()` sources `noProxy` from `config.authConfig.noproxy`. `authConfig` is used primarily for auth/credential configuration, and using it for proxy-bypass settings risks ignoring `.npmrc` `no-proxy`/`noproxy` configuration.
### Issue Context
Bit’s dependency-resolver supports `noProxy` explicitly and threads it through proxy configuration; if `getProxyConfig()` fails to populate it, proxy bypass won’t work.
### Fix Focus Areas
- Prefer the typed config field for proxy bypass if available (e.g. `config.noProxy`).
- If pnpm’s config reader still exposes raw keys, add a safe fallback chain (e.g. `config.noProxy ?? config.authConfig['no-proxy'] ?? config.authConfig.noproxy`).
- scopes/dependencies/pnpm/get-proxy-config.ts[1-13]
- scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts[55-59]
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[805-809]

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


7. CJS requires ESM module 🐞 Bug ☼ Reliability
Description
TS files are transpiled to CommonJS (require()), but pnpm integration code still statically imports
@pnpm/lockfile.fs even though this PR documents it as ESM-only. This can crash at module-load time
with ERR_REQUIRE_ESM during installs/prune/lockfile operations in CJS contexts (e.g.
mocha/capsules).
Code

scopes/dependencies/pnpm/lynx.ts[R25-28]

import { BitError } from '@teambit/bit-error';
import { BIT_ROOTS_DIR } from '@teambit/legacy.constants';
-import type { MutatedProject, InstallOptions, PeerDependencyIssuesByProjects, ProjectOptions } from '@pnpm/core';
-import { mutateModules } from '@pnpm/core';
-import * as pnpm from '@pnpm/core';
-import type { ClientOptions } from '@pnpm/client';
-import { createClient } from '@pnpm/client';
-import { restartWorkerPool, finishWorkers } from '@pnpm/worker';
-import { createPkgGraph } from '@pnpm/workspace.pkgs-graph';
import { readWantedLockfile, writeWantedLockfile } from '@pnpm/lockfile.fs';
import { type LockfileFile, type LockfileObject } from '@pnpm/lockfile.types';
Evidence
Babel is configured to transform modules to CommonJS, so static TS imports become require(). The PR
itself states @pnpm/lockfile.fs is ESM-only via the new shim, yet multiple runtime modules still
import it at top-level, which is incompatible with require().

babel.config.js[19-26]
scopes/dependencies/pnpm/load-pnpm-esm.cjs[3-10]
scopes/dependencies/pnpm/lynx.ts[20-33]
scopes/dependencies/pnpm/pnpm.package-manager.ts[24-34]
scopes/dependencies/pnpm/pnpm-prune-modules.ts[1-17]

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

## Issue description
`@pnpm/lockfile.fs` is treated as ESM-only in this PR, but several TypeScript modules still import it statically. Since the repo transpiles TS to CommonJS (`@babel/plugin-transform-modules-commonjs`), these imports become `require('@pnpm/lockfile.fs')` and can throw `ERR_REQUIRE_ESM` at runtime.
## Issue Context
The PR already introduces a `.cjs` shim (`load-pnpm-esm.cjs`) specifically because `@pnpm/lockfile.fs` is ESM-only. That mitigation is currently incomplete because other runtime code paths still use static imports.
## Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[24-33]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[24-35]
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[1-17]
- scopes/dependencies/pnpm/load-pnpm-esm.cjs[3-12]
- babel.config.js[19-26]
### Suggested implementation direction
- Remove top-level runtime imports from `@pnpm/lockfile.fs`.
- Replace them with a memoized dynamic loader (e.g. `let lockfileFsPromise; async function loadLockfileFs(){...}`) that uses `import('@pnpm/lockfile.fs')`, or extend the existing `load-pnpm-esm.cjs` shim to export the additional functions you need (`readWantedLockfile`, `writeWantedLockfile`, `readCurrentLockfile`, etc.).
- Update call sites to `const { readWantedLockfile } = await loadLockfileFs()` (or equivalent) before use.

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


8. Auth registry key missing 🐞 Bug ≡ Correctness
Description
getRegistries() now passes config.authConfig into getOriginalAuthConfigByUri(), but that
helper reads config.registry to compute the default registry nerf-dart; if authConfig doesn’t
carry a registry string, the default-auth fallback logic can crash or behave incorrectly.
Code

scopes/dependencies/pnpm/get-registries.ts[R18-22]

+    let credentials = getCredentialsByURI(config.authConfig, uri);
+    let originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, uri);
if (isEmpty(credentials)) {
-      credentials = getCredentialsByURI(config.rawConfig, switchTrailingSlash(uri));
-      originalAuthConfig = getOriginalAuthConfigByUri(config.rawConfig, switchTrailingSlash(uri));
+      credentials = getCredentialsByURI(config.authConfig, switchTrailingSlash(uri));
+      originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, switchTrailingSlash(uri));
Evidence
The new call site passes config.authConfig into getOriginalAuthConfigByUri, while the helper
still dereferences config.registry. This mismatch is introduced by the PR’s switch from
rawConfig to authConfig.

scopes/dependencies/pnpm/get-registries.ts[13-23]
scopes/dependencies/pnpm/get-registries.ts[34-38]

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

## Issue description
`getRegistries()` calls `getOriginalAuthConfigByUri(config.authConfig, uri)`, but `getOriginalAuthConfigByUri()` expects the passed object to contain `registry` (used as the default registry URI). With `@pnpm/config.reader`, `Config.registries` is already the authoritative source of registry URLs, so relying on `authConfig.registry` is brittle and may be `undefined`.
### Issue Context
This impacts building `Registry` objects (default and scoped) used across installs/resolution.
### Fix Focus Areas
- scopes/dependencies/pnpm/get-registries.ts[13-46]
### Suggested fix
Option A (preferred, explicit):
1) Change `getOriginalAuthConfigByUri` signature to accept `defaultRegistryUri: string`.
2) Call it as `getOriginalAuthConfigByUri(config.authConfig, uri, config.registries.default)` (or equivalent default-registry entry).
3) Replace `toNerfDart(config.registry)` with `toNerfDart(defaultRegistryUri)`.
Option B (minimal change):
- Call `getOriginalAuthConfigByUri({ ...config.authConfig, registry: config.registries.default }, uri)` to ensure the expected `registry` key exists.

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


9. Install lock not cleared 🐞 Bug ☼ Reliability
Description
In lynx.install(), installsRunning[rootDir] is only deleted on the success path; if
nodeApi.install() rejects, the rejected promise remains cached and subsequent installs for the same
rootDir will immediately fail at await installsRunning[rootDir]. This prevents retries in the same
process after a single install failure.
Code

scopes/dependencies/pnpm/lynx.ts[R401-418]

await installsRunning[rootDir];
-      await restartWorkerPool();
-      installsRunning[rootDir] = mutateModules(packagesToBuild, opts);
-      const installResult = await installsRunning[rootDir];
-      depsRequiringBuild = installResult.depsRequiringBuild?.sort();
-      if (depsRequiringBuild != null) {
-        await addDepsRequiringBuildToLockfile(rootDir, depsRequiringBuild);
+      installsRunning[rootDir] = nodeApi.install(installOptions, onLog, readPackageHookForDeps);
+      const installResult: nodeApi.InstallResult = await installsRunning[rootDir];
+      resolvedStoreDir = installResult.storeDir;
+      const sortedDepsRequiringBuild = installResult.depsRequiringBuild?.sort();
+      if (sortedDepsRequiringBuild != null) {
+        await addDepsRequiringBuildToLockfile(rootDir, sortedDepsRequiringBuild);
+        depsRequiringBuild = sortedDepsRequiringBuild as unknown as DepPath[];
}
dependenciesChanged =
installResult.stats.added + installResult.stats.removed + installResult.stats.linkedToRoot > 0;
delete installsRunning[rootDir];
} catch (err: any) {
if (logger) {
-        logger.warn('got an error from pnpm mutateModules function', err);
+        logger.warn('got an error from the pnpm install function', err);
}
throw pnpmErrorToBitError(err);
} finally {
Evidence
The lock map is global, awaited before starting a new install, and only deleted on the success path;
on error it is left intact, causing future calls to await the same rejected promise.

scopes/dependencies/pnpm/lynx.ts[42-43]
scopes/dependencies/pnpm/lynx.ts[389-420]

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

## Issue description
`installsRunning[rootDir]` is used to serialize installs, but it is only deleted on the success path. If `nodeApi.install(...)` throws/rejects, the rejected promise remains stored, so the next call will `await installsRunning[rootDir]` and fail immediately without attempting a new install.
### Issue Context
This is a per-process cache/lock. A single transient error (network, registry, etc.) can permanently block subsequent installs for that workspace root until the process restarts.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[389-420]
### Implementation notes
- Capture the current promise in a local variable (`const p = nodeApi.install(...)`), assign it to the map, and in `finally` do `if (installsRunning[rootDir] === p) delete installsRunning[rootDir]`.
- Ensure the entry is cleared on both success and failure, while still preserving serialization semantics.

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


10. Rebuild uses stale storeDir 🐞 Bug ≡ Correctness
Description
lynx.install() updates resolvedStoreDir from installResult.storeDir, but rebuild() calls
nodeApi.rebuild() with the original installOptions object whose storeDir field is never updated.
When storeDir input is undefined or the engine resolves/normalizes it, rebuild can run against the
wrong store location.
Code

scopes/dependencies/pnpm/lynx.ts[R403-440]

+      const installResult: nodeApi.InstallResult = await installsRunning[rootDir];
+      resolvedStoreDir = installResult.storeDir;
+      const sortedDepsRequiringBuild = installResult.depsRequiringBuild?.sort();
+      if (sortedDepsRequiringBuild != null) {
+        await addDepsRequiringBuildToLockfile(rootDir, sortedDepsRequiringBuild);
+        depsRequiringBuild = sortedDepsRequiringBuild as unknown as DepPath[];
}
dependenciesChanged =
installResult.stats.added + installResult.stats.removed + installResult.stats.linkedToRoot > 0;
delete installsRunning[rootDir];
} catch (err: any) {
if (logger) {
-        logger.warn('got an error from pnpm mutateModules function', err);
+        logger.warn('got an error from the pnpm install function', err);
}
throw pnpmErrorToBitError(err);
} finally {
stopReporting?.();
-      await finishWorkers();
}
}
return {
dependenciesChanged,
-    rebuild: async (rebuildOpts) => {
+    // The Rust engine's rebuild rebuilds every build-needing package and does not
+    // support the pending / skipIfHasSideEffectsCache selectors of the old engine.
+    rebuild: async () => {
let stopReporting: Function | undefined;
-      const _opts = {
-        ...opts,
-        ...rebuildOpts,
-        cacheDir,
-      } as any; // eslint-disable-line @typescript-eslint/no-explicit-any
-      if (!_opts.hidePackageManagerOutput) {
+      if (!options.hidePackageManagerOutput) {
stopReporting = initReporter({
appendOnly: true,
hideLifecycleOutput: true,
});
}
try {
-        await rebuild.handler(_opts, []);
+        await nodeApi.rebuild(installOptions, onLog, undefined);
} finally {
stopReporting?.();
}
},
-    storeDir: storeController.dir,
+    storeDir: resolvedStoreDir ?? '',
Evidence
installOptions.storeDir is set once from the incoming storeDir argument; later, resolvedStoreDir is
overwritten from installResult.storeDir and returned, but rebuild still uses the original
installOptions without updating storeDir.

scopes/dependencies/pnpm/lynx.ts[334-343]
scopes/dependencies/pnpm/lynx.ts[401-442]

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

## Issue description
`installResult.storeDir` is captured into `resolvedStoreDir` and returned, but `rebuild()` reuses the precomputed `installOptions` object, whose `storeDir` property remains the original input `storeDir` (which may be `undefined`). This can make rebuild use a different store directory than install used.
### Issue Context
The code already anticipates storeDir potentially being missing/changed (`resolvedStoreDir ?? ''`). Any mismatch can lead to rebuild operating on the wrong store content or failing to locate it.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[334-387]
- scopes/dependencies/pnpm/lynx.ts[401-442]
### Implementation notes
- After a successful install, either:
- mutate `installOptions.storeDir = resolvedStoreDir` (or `installResult.storeDir`) before returning, or
- create a separate options object for rebuild: `{ ...installOptions, storeDir: resolvedStoreDir }`.
- Keep behavior consistent for dryRun (no installResult).

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


11. ESM import in CJS 🐞 Bug ☼ Reliability
Description
DependenciesGraph now statically imports @pnpm/deps.path, which this PR itself documents as
ESM-only; when Babel transpiles this file to CommonJS, it will become a require() and can crash at
runtime with ERR_REQUIRE_ESM. This can break dependency graph operations anywhere
@teambit/objects is loaded in the CJS-transpiled execution path (e.g. mocha via babel-register).
Code

scopes/scope/objects/models/dependencies-graph.ts[3]

+import * as dp from '@pnpm/deps.path';
Evidence
The modified file now imports @pnpm/deps.path statically. The PR-added shim explicitly states
@pnpm/deps.path is ESM-only and must be loaded via Node’s ESM loader (dynamic import()), while
the Babel configuration used by babel-register transforms TS modules to CommonJS, turning the
static import into a require() which is incompatible with ESM-only packages.

scopes/scope/objects/models/dependencies-graph.ts[1-4]
scopes/dependencies/pnpm/load-pnpm-esm.cjs[3-10]
babel.config.js[19-26]
babel-register.js[1-1]

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

## Issue description
`scopes/scope/objects/models/dependencies-graph.ts` now statically imports `@pnpm/deps.path`. The PR also states `@pnpm/deps.path` is ESM-only, while the repo’s Babel setup transpiles TS modules to CommonJS (turning `import` into `require()`), which can throw `ERR_REQUIRE_ESM` at runtime.
### Issue Context
- This repo uses `@babel/plugin-transform-modules-commonjs` (via `babel-register`) in at least some execution paths.
- The PR already introduced a CJS shim + dynamic `import()` loader for ESM-only pnpm modules elsewhere, which suggests the same problem applies here.
### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[1-120]
- scopes/dependencies/pnpm/load-pnpm-esm.cjs[1-12]
- babel.config.js[1-31]
- babel-register.js[1-1]
### Suggested fix directions
Pick one:
1) **Remove the dependency on `@pnpm/deps.path` here** by implementing a small local parser for the *specific* need (extracting `version` from a depPath string) so this code stays synchronous and CJS-safe.
2) **Mirror the shim approach** used in `lockfile-deps-graph-converter.ts`: add a local loader wrapper for `@pnpm/deps.path` and ensure it is initialized before any `DependenciesGraph` code path that calls `dp.parse()`. If you choose this route, add a clear runtime guard/error message when not initialized (instead of an opaque TypeError).

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


12. Core-js deny ignored 🐞 Bug ⛨ Security
Description
In resolveScriptPolicies(), the branch that sets a default deny for "core-js" also returns
dangerouslyAllowAllBuilds: true even though the code comment states pnpm ignores allowBuilds when
dangerouslyAllowAllBuilds is set. This makes the default deny ineffective and can unintentionally
allow core-js build scripts to run when dangerouslyAllowAllScripts is enabled without an explicit
neverBuiltDependencies list.
Code

scopes/dependencies/pnpm/lynx.ts[R428-434]

if (dangerouslyAllowAllScripts) {
-    if (resolvedNeverBuilt == null) {
-      // If neverBuiltDependencies is not explicitly set, use a default list
-      // we tell pnpm to allow all scripts to be executed, except the packages listed below.
-      resolvedNeverBuilt = ['core-js'];
+    // pnpm v11's createAllowBuildFunction ignores allowBuilds when dangerouslyAllowAllBuilds is
+    // set, so emit allowBuilds with just the deny entries whenever a deny list exists.
+    if (!neverBuiltDependencies?.length) {
+      allowBuilds['core-js'] = false;
+      return { dangerouslyAllowAllBuilds: true, allowBuilds };
}
-  } else {
-    onlyBuiltDependencies = [];
-    ignoredBuiltDependencies = [];
-    for (const [packageDescriptor, allowedScript] of Object.entries(allowScripts ?? {})) {
-      switch (allowedScript) {
-        case true:
-          onlyBuiltDependencies.push(packageDescriptor);
-          break;
-        case false:
-          ignoredBuiltDependencies.push(packageDescriptor);
-          break;
-        default:
-          // Ignore any non-boolean values. String values are placeholders that the user
-          // should replace with booleans.
-          // pnpm will print a warning about these during installation.
-          break;
-      }
Evidence
The function comment explicitly states allowBuilds is ignored when dangerouslyAllowAllBuilds is set,
yet the code sets a deny entry in allowBuilds and returns dangerouslyAllowAllBuilds: true in that
same branch; therefore the deny entry will not take effect under the stated behavior.

scopes/dependencies/pnpm/lynx.ts[422-434]

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

## Issue description
`resolveScriptPolicies()` returns `{ dangerouslyAllowAllBuilds: true, allowBuilds }` in the same branch where it sets `allowBuilds['core-js'] = false`, but the adjacent comment states that pnpm ignores `allowBuilds` when `dangerouslyAllowAllBuilds` is set. This makes the default deny entry ineffective.
### Issue Context
The intent (based on existing policy and comments) is to keep a safe default deny list (at least `core-js`) even when `dangerouslyAllowAllScripts` is enabled.
### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[422-439]
### Suggested fix
Adjust the returned options so that the deny entry is actually honored:
- Do **not** set `dangerouslyAllowAllBuilds` in the code path where you need `allowBuilds` to enforce denies (e.g. for `core-js`).
- Alternatively, if pnpm v11 provides a supported way to express “allow all except these denies”, use that API and add/adjust a regression test for the default `core-js` behavior.

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



Remediation recommended

13. Merge ref not detected 🐞 Bug ≡ Correctness
Description
CiMain.getBranchName() can return a synthetic PR ref (e.g. pull//merge) instead of the real source
branch because isPullRequestRef() only matches pull/ and pull//head. When this happens, the
CircleCI PR-URL GitHub API fallback is skipped, which can break lane naming and post-merge cleanup
keyed by branch name.
Code

scopes/git/ci/ci.main.runtime.ts[R202-204]

+  private isPullRequestRef(branchName: string): boolean {
+    return /^pull\/\d+(?:\/head)?$/.test(branchName);
+  }
Evidence
The code returns branch.current immediately when it is not classified as a PR ref, and only
afterwards attempts CircleCI PR URL resolution. Since isPullRequestRef() does not match
pull//merge, that PR checkout form will be treated as a normal branch and bypass the fallback.

scopes/git/ci/ci.main.runtime.ts[180-205]
scopes/git/ci/ci.main.runtime.ts[206-229]

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

## Issue description
`CiMain.getBranchName()` returns early when `branch.current` is not recognized as a PR ref. The current `isPullRequestRef()` regex does **not** match the common GitHub merge ref form (`pull/<n>/merge`, and sometimes normalized/full forms like `refs/pull/<n>/merge`). This prevents the CircleCI PR URL fallback (`getCirclePullRequestBranchName()`) from running and may return an incorrect branch name.
### Issue Context
- The early return happens before CircleCI fallback logic.
- The PR ref detector only allows `pull/<n>` and `pull/<n>/head`.
### How to fix
- Expand `isPullRequestRef()` to recognize PR merge refs as well.
- Suggested regex (covers optional `refs/` prefix): `^(?:refs/)?pull/\d+(?:/(?:head|merge))?$`
- Alternatively: normalize `branchName` by stripping a leading `refs/` before matching.
- Add/adjust a small unit/integration test to ensure `pull/<n>/merge` triggers the CircleCI/GitHub API fallback path.
### Fix Focus Areas
- scopes/git/ci/ci.main.runtime.ts[180-205]

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


14. CI branch fetch no timeout 🐞 Bug ☼ Reliability
Description
CiMain.getBranchName() may call getCirclePullRequestBranchName(), which performs a GitHub API fetch
without any timeout/abort signal. On CircleCI PR jobs (where this fallback path runs), a stalled
network request can hang branch detection and block bit ci pr until the job-level timeout.
Code

scopes/git/ci/ci.main.runtime.ts[R197-216]

+  private async getCirclePullRequestBranchName(): Promise<string | undefined> {
+    const pullRequestUrl = process.env.CIRCLE_PULL_REQUEST || process.env.CIRCLE_PULL_REQUESTS?.split(',')[0];
+    if (!pullRequestUrl) return undefined;
+
+    try {
+      const { pathname } = new URL(pullRequestUrl);
+      const [, owner, repo, pullSegment, pullNumber] = pathname.split('/');
+      if (!owner || !repo || pullSegment !== 'pull' || !pullNumber) return undefined;
+
+      const headers: Record<string, string> = {
+        Accept: 'application/vnd.github+json',
+        'X-GitHub-Api-Version': '2022-11-28',
+      };
+      if (process.env.GITHUB_TOKEN) headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
+
+      const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}`, { headers });
+      if (!response.ok) return undefined;
+
+      const pullRequest = (await response.json()) as { head?: { ref?: string } };
+      return pullRequest.head?.ref;
Evidence
The branch-name resolution is on the execution path of bit ci pr and now includes a GitHub API
request via fetch() with no timeout, so a stalled request can block the command.

scopes/git/ci/ci.main.runtime.ts[180-220]
scopes/git/ci/commands/pr.cmd.ts[60-70]

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

## Issue description
`getCirclePullRequestBranchName()` calls `fetch()` to GitHub’s API without an abort signal / timeout. In the CircleCI PR fallback path (when `CIRCLE_BRANCH` is `pull/*` and `CIRCLE_PULL_REQUEST(S)` is set), this can block `getBranchName()` indefinitely if the request stalls.
### Issue Context
`CiPrCmd.report()` calls `ci.getBranchName()` when `--lane` is not provided; hanging here blocks the command.
### Fix Focus Areas
- scopes/git/ci/ci.main.runtime.ts[180-220]
- scopes/git/ci/commands/pr.cmd.ts[60-70]
### What to change
- Use an abortable timeout for the GitHub API request, e.g. in Node 18+:
- `const signal = AbortSignal.timeout(10_000)` and pass `{ headers, signal }` to `fetch`.
- Treat `AbortError` the same as other failures (return `undefined` so the caller can fall back).
- Optionally add a debug log or warning when the API call fails/times out to improve diagnosability in CI.

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


15. npm alias rejected 🐞 Bug ≡ Correctness
Description
DependencyResolverMain.isValidVersionSpecifier() returns false for npm: aliases that omit an
explicit @ suffix (e.g. npm:uri-js-replace), even though pnpm accepts that alias form. This can
cause dependency-resolver aspect-data validation to reject dependency/policy versions that would
otherwise install correctly.
Code

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[R1476-1485]

+    const trimmedSpec = spec.trim();
+    if (!trimmedSpec) return false;
+    if (semver.valid(trimmedSpec) || semver.validRange(trimmedSpec)) return true;
+    if (/^(?:workspace|file|link|git|git\+https?|ssh):/.test(trimmedSpec)) return true;
+    if (/^https?:\/\/registry\.npmjs\.org\/.+\/-.+\.tgz(?:[#?].*)?$/.test(trimmedSpec)) return true;
+    if (trimmedSpec.startsWith('npm:')) {
+      const versionStart = trimmedSpec.lastIndexOf('@');
+      return versionStart > 'npm:'.length && this.isValidVersionSpecifier(trimmedSpec.slice(versionStart + 1));
+    }
+    return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(trimmedSpec);
Evidence
The validator’s npm: branch hard-requires an @ and returns early, so npm: forms are always
rejected. The repository already uses such a specifier (uri-js: npm:uri-js-replace), demonstrating
this form is expected/valid in practice.

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1432-1486]
workspace.jsonc[681-707]

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

## Issue description
`DependencyResolverMain.isValidVersionSpecifier()` rejects valid pnpm `npm:` alias specifiers when they don’t include an `@<version|tag>` suffix (e.g. `npm:uri-js-replace`). This is because it assumes every `npm:` alias must contain an `@` and only validates the substring after the last `@`.
### Issue Context
The repo itself uses the alias-without-version form in `workspace.jsonc` overrides, demonstrating this is a real, used specifier shape.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1475-1485]
### Suggested fix
Update the `npm:` handling to properly parse the alias package name (including scoped names) and treat a missing alias-version as valid.
One robust approach:
- Parse with something like `^npm:(@[^/]+/[^@]+|[^@]+)(?:@(.+))?$`.
- If the optional version/tag part is missing: return `true` (it resolves to `latest`).
- If present: validate that part using the same semver/tag/url rules.
Add a small unit test (or expand an existing validation test) that asserts:
- `npm:uri-js-replace` is valid
- `npm:@zkochan/[email protected]` is valid
- `npm:pkg@latest` is valid

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


View more (2)
16. Init not enforced 🐞 Bug ☼ Reliability
Description
lockfile-deps-graph-converter.ts now depends on module-level dp/getLockfileImporterId that are
only assigned by async init(), but the exported converters dereference them without any guard. Any
direct caller that forgets to await init() will crash at runtime when dp is first used.
Code

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[R38-52]

+let dp!: typeof Dp;
+let getLockfileImporterId!: typeof GetLockfileImporterId;
+let loading: Promise<void> | undefined;
+
+export function init(): Promise<void> {
+  loading ??= (async () => {
+    const { loadEsm } = require('./load-pnpm-esm.cjs') as {
+      loadEsm: () => Promise<{ dp: typeof Dp; getLockfileImporterId: typeof GetLockfileImporterId }>;
+    };
+    const m = await loadEsm();
+    dp = m.dp;
+    getLockfileImporterId = m.getLockfileImporterId;
+  })();
+  return loading;
+}
Evidence
The module declares dp/getLockfileImporterId as definitely-assigned but only assigns them inside
async init(). Multiple helpers (e.g. importerDepsToNeighbours) immediately call into dp, so a
missing init() call would result in an undefined dereference. The current package-manager caller
explicitly awaits init, showing the dependency is real but not enforced by the converter itself.

scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[24-52]
scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[73-83]
scopes/dependencies/pnpm/pnpm.package-manager.ts[92-113]

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 converter module introduces an async `init()` that populates module-level ESM-only dependencies (`dp`, `getLockfileImporterId`). However, `convertLock...

Comment on lines 428 to 434
if (dangerouslyAllowAllScripts) {
if (resolvedNeverBuilt == null) {
// If neverBuiltDependencies is not explicitly set, use a default list
// we tell pnpm to allow all scripts to be executed, except the packages listed below.
resolvedNeverBuilt = ['core-js'];
// pnpm v11's createAllowBuildFunction ignores allowBuilds when dangerouslyAllowAllBuilds is
// set, so emit allowBuilds with just the deny entries whenever a deny list exists.
if (!neverBuiltDependencies?.length) {
allowBuilds['core-js'] = false;
return { dangerouslyAllowAllBuilds: true, allowBuilds };
}

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. Core-js deny ignored 🐞 Bug ⛨ Security

In resolveScriptPolicies(), the branch that sets a default deny for "core-js" also returns
dangerouslyAllowAllBuilds: true even though the code comment states pnpm ignores allowBuilds when
dangerouslyAllowAllBuilds is set. This makes the default deny ineffective and can unintentionally
allow core-js build scripts to run when dangerouslyAllowAllScripts is enabled without an explicit
neverBuiltDependencies list.
Agent Prompt
### Issue description
`resolveScriptPolicies()` returns `{ dangerouslyAllowAllBuilds: true, allowBuilds }` in the same branch where it sets `allowBuilds['core-js'] = false`, but the adjacent comment states that pnpm ignores `allowBuilds` when `dangerouslyAllowAllBuilds` is set. This makes the default deny entry ineffective.

### Issue Context
The intent (based on existing policy and comments) is to keep a safe default deny list (at least `core-js`) even when `dangerouslyAllowAllScripts` is enabled.

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[422-439]

### Suggested fix
Adjust the returned options so that the deny entry is actually honored:
- Do **not** set `dangerouslyAllowAllBuilds` in the code path where you need `allowBuilds` to enforce denies (e.g. for `core-js`).
- Alternatively, if pnpm v11 provides a supported way to express “allow all except these denies”, use that API and add/adjust a regression test for the default `core-js` behavior.

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

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

qodo-free-for-open-source-projects Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 03d4bc6

import semver from 'semver';
import type { LockfilePackageInfo } from '@pnpm/lockfile.types';
import * as dp from '@pnpm/dependency-path';
import * as dp from '@pnpm/deps.path';

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. Esm import in cjs 🐞 Bug ☼ Reliability

DependenciesGraph now statically imports @pnpm/deps.path, which this PR itself documents as
ESM-only; when Babel transpiles this file to CommonJS, it will become a require() and can crash at
runtime with ERR_REQUIRE_ESM. This can break dependency graph operations anywhere
@teambit/objects is loaded in the CJS-transpiled execution path (e.g. mocha via babel-register).
Agent Prompt
### Issue description
`scopes/scope/objects/models/dependencies-graph.ts` now statically imports `@pnpm/deps.path`. The PR also states `@pnpm/deps.path` is ESM-only, while the repo’s Babel setup transpiles TS modules to CommonJS (turning `import` into `require()`), which can throw `ERR_REQUIRE_ESM` at runtime.

### Issue Context
- This repo uses `@babel/plugin-transform-modules-commonjs` (via `babel-register`) in at least some execution paths.
- The PR already introduced a CJS shim + dynamic `import()` loader for ESM-only pnpm modules elsewhere, which suggests the same problem applies here.

### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[1-120]
- scopes/dependencies/pnpm/load-pnpm-esm.cjs[1-12]
- babel.config.js[1-31]
- babel-register.js[1-1]

### Suggested fix directions
Pick one:
1) **Remove the dependency on `@pnpm/deps.path` here** by implementing a small local parser for the *specific* need (extracting `version` from a depPath string) so this code stays synchronous and CJS-safe.
2) **Mirror the shim approach** used in `lockfile-deps-graph-converter.ts`: add a local loader wrapper for `@pnpm/deps.path` and ensure it is initialized before any `DependenciesGraph` code path that calls `dp.parse()`. If you choose this route, add a clear runtime guard/error message when not initialized (instead of an opaque TypeError).

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

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

qodo-free-for-open-source-projects Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 93dcf91

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again

Grey Divider

Qodo Logo

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

ghost commented Jun 25, 2026

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 637e002

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

ghost commented Jun 25, 2026

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 767e5ae

@zkochan zkochan changed the title deps: migrate pnpm internals to v11 (1100.x) deps: migrate pnpm internals to v12 Jul 7, 2026
Comment on lines 401 to 418
await installsRunning[rootDir];
await restartWorkerPool();
installsRunning[rootDir] = mutateModules(packagesToBuild, opts);
const installResult = await installsRunning[rootDir];
depsRequiringBuild = installResult.depsRequiringBuild?.sort();
if (depsRequiringBuild != null) {
await addDepsRequiringBuildToLockfile(rootDir, depsRequiringBuild);
installsRunning[rootDir] = nodeApi.install(installOptions, onLog, readPackageHookForDeps);
const installResult: nodeApi.InstallResult = await installsRunning[rootDir];
resolvedStoreDir = installResult.storeDir;
const sortedDepsRequiringBuild = installResult.depsRequiringBuild?.sort();
if (sortedDepsRequiringBuild != null) {
await addDepsRequiringBuildToLockfile(rootDir, sortedDepsRequiringBuild);
depsRequiringBuild = sortedDepsRequiringBuild as unknown as DepPath[];
}
dependenciesChanged =
installResult.stats.added + installResult.stats.removed + installResult.stats.linkedToRoot > 0;
delete installsRunning[rootDir];
} catch (err: any) {
if (logger) {
logger.warn('got an error from pnpm mutateModules function', err);
logger.warn('got an error from the pnpm install function', err);
}
throw pnpmErrorToBitError(err);
} finally {

ghost Jul 7, 2026

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. Install lock not cleared 🐞 Bug ☼ Reliability

In lynx.install(), installsRunning[rootDir] is only deleted on the success path; if
nodeApi.install() rejects, the rejected promise remains cached and subsequent installs for the same
rootDir will immediately fail at await installsRunning[rootDir]. This prevents retries in the same
process after a single install failure.
Agent Prompt
### Issue description
`installsRunning[rootDir]` is used to serialize installs, but it is only deleted on the success path. If `nodeApi.install(...)` throws/rejects, the rejected promise remains stored, so the next call will `await installsRunning[rootDir]` and fail immediately without attempting a new install.

### Issue Context
This is a per-process cache/lock. A single transient error (network, registry, etc.) can permanently block subsequent installs for that workspace root until the process restarts.

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[389-420]

### Implementation notes
- Capture the current promise in a local variable (`const p = nodeApi.install(...)`), assign it to the map, and in `finally` do `if (installsRunning[rootDir] === p) delete installsRunning[rootDir]`.
- Ensure the entry is cleared on both success and failure, while still preserving serialization semantics.

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

Comment thread scopes/dependencies/pnpm/lynx.ts Outdated
Comment on lines +403 to +440
const installResult: nodeApi.InstallResult = await installsRunning[rootDir];
resolvedStoreDir = installResult.storeDir;
const sortedDepsRequiringBuild = installResult.depsRequiringBuild?.sort();
if (sortedDepsRequiringBuild != null) {
await addDepsRequiringBuildToLockfile(rootDir, sortedDepsRequiringBuild);
depsRequiringBuild = sortedDepsRequiringBuild as unknown as DepPath[];
}
dependenciesChanged =
installResult.stats.added + installResult.stats.removed + installResult.stats.linkedToRoot > 0;
delete installsRunning[rootDir];
} catch (err: any) {
if (logger) {
logger.warn('got an error from pnpm mutateModules function', err);
logger.warn('got an error from the pnpm install function', err);
}
throw pnpmErrorToBitError(err);
} finally {
stopReporting?.();
await finishWorkers();
}
}
return {
dependenciesChanged,
rebuild: async (rebuildOpts) => {
// The Rust engine's rebuild rebuilds every build-needing package and does not
// support the pending / skipIfHasSideEffectsCache selectors of the old engine.
rebuild: async () => {
let stopReporting: Function | undefined;
const _opts = {
...opts,
...rebuildOpts,
cacheDir,
} as any; // eslint-disable-line @typescript-eslint/no-explicit-any
if (!_opts.hidePackageManagerOutput) {
if (!options.hidePackageManagerOutput) {
stopReporting = initReporter({
appendOnly: true,
hideLifecycleOutput: true,
});
}
try {
await rebuild.handler(_opts, []);
await nodeApi.rebuild(installOptions, onLog, undefined);
} finally {
stopReporting?.();
}
},
storeDir: storeController.dir,
storeDir: resolvedStoreDir ?? '',

ghost Jul 7, 2026

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. Rebuild uses stale storedir 🐞 Bug ≡ Correctness

lynx.install() updates resolvedStoreDir from installResult.storeDir, but rebuild() calls
nodeApi.rebuild() with the original installOptions object whose storeDir field is never updated.
When storeDir input is undefined or the engine resolves/normalizes it, rebuild can run against the
wrong store location.
Agent Prompt
### Issue description
`installResult.storeDir` is captured into `resolvedStoreDir` and returned, but `rebuild()` reuses the precomputed `installOptions` object, whose `storeDir` property remains the original input `storeDir` (which may be `undefined`). This can make rebuild use a different store directory than install used.

### Issue Context
The code already anticipates storeDir potentially being missing/changed (`resolvedStoreDir ?? ''`). Any mismatch can lead to rebuild operating on the wrong store content or failing to locate it.

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[334-387]
- scopes/dependencies/pnpm/lynx.ts[401-442]

### Implementation notes
- After a successful install, either:
  - mutate `installOptions.storeDir = resolvedStoreDir` (or `installResult.storeDir`) before returning, or
  - create a separate options object for rebuild: `{ ...installOptions, storeDir: resolvedStoreDir }`.
- Keep behavior consistent for dryRun (no installResult).

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

Comment thread scopes/pkg/pkg/packer.ts
Comment on lines +136 to 140
const packResult = await nodeApi.pack({ dir: cwd });
const tgzName = path.basename(packResult.tarballPath);
this.logger.debug(`successfully packed tarball at ${cwd}`);
const tgzOriginPath = path.join(cwd, tgzName);
const tgzOriginPath = path.isAbsolute(packResult.tarballPath) ? packResult.tarballPath : path.join(cwd, tgzName);
let tarPath = path.join(outputPath, tgzName);

ghost Jul 7, 2026

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

3. Pack tarballpath mishandled 🐞 Bug ≡ Correctness

pnpmPack() reconstructs the origin tarball path as cwd + basename(tarballPath) when tarballPath is
relative, dropping any relative directory segments. If nodeApi.pack() returns a relative tarball
path that includes subdirectories, fs.move() will look for the wrong source path and fail.
Agent Prompt
### Issue description
When `packResult.tarballPath` is relative, the code computes:
- `tgzName = basename(tarballPath)`
- `tgzOriginPath = join(cwd, tgzName)`
This discards any relative folder components included in `tarballPath`.

### Issue Context
The subsequent `fs.move(tgzOriginPath, tarPath)` relies on `tgzOriginPath` accurately pointing to the tarball created by pnpm.

### Fix Focus Areas
- scopes/pkg/pkg/packer.ts[136-160]

### Implementation notes
- Compute origin path as:
  - `const origin = path.isAbsolute(tarballPath) ? tarballPath : path.join(cwd, tarballPath)`
- Keep `tgzName` for naming, but don’t rebuild the origin path from basename.

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

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

ghost commented Jul 7, 2026

Copy link
Copy Markdown

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

Comment on lines +18 to +22
let credentials = getCredentialsByURI(config.authConfig, uri);
let originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, uri);
if (isEmpty(credentials)) {
credentials = getCredentialsByURI(config.rawConfig, switchTrailingSlash(uri));
originalAuthConfig = getOriginalAuthConfigByUri(config.rawConfig, switchTrailingSlash(uri));
credentials = getCredentialsByURI(config.authConfig, switchTrailingSlash(uri));
originalAuthConfig = getOriginalAuthConfigByUri(config.authConfig, switchTrailingSlash(uri));

ghost Jul 7, 2026

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. Auth registry key missing 🐞 Bug ≡ Correctness

getRegistries() now passes config.authConfig into getOriginalAuthConfigByUri(), but that
helper reads config.registry to compute the default registry nerf-dart; if authConfig doesn’t
carry a registry string, the default-auth fallback logic can crash or behave incorrectly.
Agent Prompt
### Issue description
`getRegistries()` calls `getOriginalAuthConfigByUri(config.authConfig, uri)`, but `getOriginalAuthConfigByUri()` expects the passed object to contain `registry` (used as the default registry URI). With `@pnpm/config.reader`, `Config.registries` is already the authoritative source of registry URLs, so relying on `authConfig.registry` is brittle and may be `undefined`.

### Issue Context
This impacts building `Registry` objects (default and scoped) used across installs/resolution.

### Fix Focus Areas
- scopes/dependencies/pnpm/get-registries.ts[13-46]

### Suggested fix
Option A (preferred, explicit):
1) Change `getOriginalAuthConfigByUri` signature to accept `defaultRegistryUri: string`.
2) Call it as `getOriginalAuthConfigByUri(config.authConfig, uri, config.registries.default)` (or equivalent default-registry entry).
3) Replace `toNerfDart(config.registry)` with `toNerfDart(defaultRegistryUri)`.

Option B (minimal change):
- Call `getOriginalAuthConfigByUri({ ...config.authConfig, registry: config.registries.default }, uri)` to ensure the expected `registry` key exists.

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

Comment on lines +206 to +212
} catch (err: any) {
if (err?.code === 'ERR_PNPM_NAPI_UNIMPLEMENTED') {
// TODO: getPeerDependencyIssues not yet implemented in the Rust engine.
// Returning no issues keeps installs working until the binding lands it.
return {};
}
throw pnpmErrorToBitError(err);

ghost Jul 7, 2026

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

2. Peer issues suppressed silently 🐞 Bug ◔ Observability

lynx.getPeerDependencyIssues() returns {} for ERR_PNPM_NAPI_UNIMPLEMENTED, which makes
dependency-resolver.getMissingPeerDependencies() return undefined and causes the install flow to
report “No missing peer dependencies found” even when peer detection is actually unavailable.
Agent Prompt
### Issue description
When `@pnpm/napi` throws `ERR_PNPM_NAPI_UNIMPLEMENTED`, `getPeerDependencyIssues()` currently returns `{}`. Downstream, Bit interprets this as “no peer issues,” so features like `--add-missing-peers` can silently become a no-op without any indication that peer-issue calculation is unsupported.

### Issue Context
- `dependency-resolver.getMissingPeerDependencies()` reads `peerDependencyIssues['.']?.intersections`.
- The install command uses falsy result to print “No missing peer dependencies found.”

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[177-213]
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[896-922]

### Suggested fix
- In the `ERR_PNPM_NAPI_UNIMPLEMENTED` branch, emit a warning (once per process) indicating peer-dependency detection is currently unavailable with the pnpm napi engine.
- Return a safe, expected shape for the caller to avoid `undefined`, e.g. `{ '.': { intersections: {} } }` (or whatever minimal `PeerDependencyIssuesByProjects` shape the rest of the code expects).
- Alternatively, plumb a flag to allow throwing a clear BitError when `addMissingPeers` is requested, instead of silently returning empty results.

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

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

ghost commented Jul 7, 2026

Copy link
Copy Markdown

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

Comment on lines 25 to 28
import { BitError } from '@teambit/bit-error';
import { BIT_ROOTS_DIR } from '@teambit/legacy.constants';
import type { MutatedProject, InstallOptions, PeerDependencyIssuesByProjects, ProjectOptions } from '@pnpm/core';
import { mutateModules } from '@pnpm/core';
import * as pnpm from '@pnpm/core';
import type { ClientOptions } from '@pnpm/client';
import { createClient } from '@pnpm/client';
import { restartWorkerPool, finishWorkers } from '@pnpm/worker';
import { createPkgGraph } from '@pnpm/workspace.pkgs-graph';
import { readWantedLockfile, writeWantedLockfile } from '@pnpm/lockfile.fs';
import { type LockfileFile, type LockfileObject } from '@pnpm/lockfile.types';

ghost Jul 9, 2026

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. Cjs requires esm module 🐞 Bug ☼ Reliability

TS files are transpiled to CommonJS (require()), but pnpm integration code still statically imports
@pnpm/lockfile.fs even though this PR documents it as ESM-only. This can crash at module-load time
with ERR_REQUIRE_ESM during installs/prune/lockfile operations in CJS contexts (e.g.
mocha/capsules).
Agent Prompt
## Issue description
`@pnpm/lockfile.fs` is treated as ESM-only in this PR, but several TypeScript modules still import it statically. Since the repo transpiles TS to CommonJS (`@babel/plugin-transform-modules-commonjs`), these imports become `require('@pnpm/lockfile.fs')` and can throw `ERR_REQUIRE_ESM` at runtime.

## Issue Context
The PR already introduces a `.cjs` shim (`load-pnpm-esm.cjs`) specifically because `@pnpm/lockfile.fs` is ESM-only. That mitigation is currently incomplete because other runtime code paths still use static imports.

## Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[24-33]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[24-35]
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[1-17]
- scopes/dependencies/pnpm/load-pnpm-esm.cjs[3-12]
- babel.config.js[19-26]

### Suggested implementation direction
- Remove top-level runtime imports from `@pnpm/lockfile.fs`.
- Replace them with a memoized dynamic loader (e.g. `let lockfileFsPromise; async function loadLockfileFs(){...}`) that uses `import('@pnpm/lockfile.fs')`, or extend the existing `load-pnpm-esm.cjs` shim to export the additional functions you need (`readWantedLockfile`, `writeWantedLockfile`, `readCurrentLockfile`, etc.).
- Update call sites to `const { readWantedLockfile } = await loadLockfileFs()` (or equivalent) before use.

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

@zkochan

ghost commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

Status handoff — @pnpm/napi 12.0.0-alpha.10 (2026-07-14)

Bumped pnpm11 to @pnpm/[email protected] (commit 60b1c2f00, pushed).

✅ install --no-optional — FIXED

Released in alpha.10 (pnpm/pnpm#12965). The install.e2e.ts "install --no-optional" test ("should not install optional dependencies") passes end-to-end. The engine fix scopes the transitive-optional exclusion to full installs (is_full_install) so partial add/dlx/global/engine installs keep their optionals (that gate was needed because @pnpm/exe's platform binary is an optionalDependency).

❌ install --update — still fails; root cause not yet nailed

install.e2e.ts "install --update" still fails on alpha.10 (2 failing): @pnpm.e2e/dep-of-pkg-with-1-dep stays at 100.0.0, should update to 100.1.0 within ^100.0.0; same for the subdep pkg-with-1-dep.

What's confirmed (so we don't re-check):

  • Bit plumbing is complete — update: true reaches napi (bit debug.log shows "update": true and updateAll: true). Chain: install.cmd.tsx (--update→updateAll) → install.main.runtime.ts:414 (pmInstallOptions.updateAll) → passed as packageManagerOptions to installer.installComponents → dependency-installer.ts (spreads ...packageManagerOptions) → pnpm.package-manager.ts:221 (updateAll) → lynx.ts:386 (update: options.updateAll).
  • Bit passes the range ^100.0.0 in the manifest (not an exact pin) — confirmed in debug.log — so update should be able to bump.
  • Metadata is not stale — the engine revalidates the packument on every fetch (fetch_full_metadata_cached always sends If-None-Match), so it sees current dist-tags.
  • napi itself doesn't bump — the generated lockfile records version: 100.0.0 (specifier ^100.0.0), so it's not a bit post-step reverting it.

The paradox: an isolated pacquet test (Install struct + UpdateSeedPolicy::DropAll, install/tests.rs::install_with_drop_all_seed_policy_bumps_dependency_within_range) does bump 100.0.0 → 100.1.0. Same engine, same DropAll, but bit's integrated napi install({ update: true }) flow keeps the locked version. Every static layer (napi install.rs: update_requested → DropAll → UpdateReuseScope::None, prefer_frozen: Some(false), optimistic-repeat-install bypassed) says it should re-resolve.

Note: my earlier claim that this was "not an engine bug" is retracted — that rested on a pacquet test whose fixture had latest out of range (101.0.0), masking the behavior.

Recommended next step (needs runtime tracing, not code-reading): build a local instrumented @pnpm/napi .so that logs the resolved update_requested / update_seed_policy / engine mode inside napi install.rs (and in lynx.ts), swap it into bit's node_modules, and re-run the --update e2e in debug mode (keeps the workspace). Leading suspicion: bit reaches napi with an engine mode other than EngineMode::Install (so update_requested never flips true), or a second install pass without update re-pins. Confirm before fixing.

Other clusters still open (from the clean-CI failure set)

  • deps-graph shared-peer merge (deps-graph.e2e.ts "same env" + deps-graph-reimport.e2e.ts "three components"): bit-side, entangled with alpha.9's peer-resolution change; needs a clean-room repro to judge regression vs. test recalibration. DependenciesGraph.merge() only dedupes root direct deps to the highest, not transitive peers.
  • Untriaged: dependency-resolver.e2e.ts @ci/lodash package.json ENOENT (env peer version="*" re-tag scenario) and tsconfig-env-mismatch.e2e.ts bit compile failure.

— Claude Code (Claude Fable 5)

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

ghost commented Jul 14, 2026

Copy link
Copy Markdown

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

Comment on lines +377 to +385
const installOptions: nodeApi.InstallOptions = {
dir: rootDir,
storeController: storeController.ctrl,
preferFrozenLockfile: true,
pruneLockfileImporters: true,
lockfileOnly: options.lockfileOnly ?? false,
modulesCacheMaxAge: Infinity, // pnpm should never prune the virtual store. Bit does it on its own.
projects,
storeDir,
cacheDir,
registries: registries.toMap(),
resolutionMode: 'highest',
rawConfig: authConfig,
hooks: { readPackage },
externalDependencies,
strictPeerDependencies: false,
authHeaderByUri: buildAuthHeaderByUri(getAuthConfig(registries) as Record<string, unknown>),
proxyConfig: toNodeApiProxyConfig(proxyConfig),
networkConfig: toNodeApiNetworkConfig(networkConfig),

ghost Jul 15, 2026

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. Missing pnpm auth merge 🐞 Bug ≡ Correctness

lynx.install() builds authHeaderByUri only from getAuthConfig(registries) and never merges
pnpmConfig.config.authConfig from readConfig(), unlike generateResolverAndFetcher(). Installs
that rely on user/workspace .npmrc credentials can fail against authenticated registries because
nodeApi.install() won’t receive those headers.
Agent Prompt
### Issue description
`lynx.install()` currently computes `authHeaderByUri` from Bit registries only, ignoring pnpm’s resolved `config.authConfig` (which includes user/workspace `.npmrc` auth). This can break authenticated installs.

### Issue Context
`generateResolverAndFetcher()` already merges pnpm config auth with Bit registry auth, but `install()` does not.

### Fix Focus Areas
- scopes/dependencies/pnpm/lynx.ts[161-189]
- scopes/dependencies/pnpm/lynx.ts[377-385]

### Suggested change
In `install()`, call `readConfig()` (ideally with the same config root dir used by the package manager) and build headers from a merged auth config, e.g.:
- `const pnpmConfig = await readConfig(rootDir)` (or pass down `packageManagerConfigRootDir`)
- `const mergedAuthConfig = { ...pnpmConfig.config.authConfig, ...getAuthConfig(registries) }`
- `authHeaderByUri: buildAuthHeaderByUri(mergedAuthConfig)`

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

Comment on lines 192 to 220
@@ -152,30 +199,48 @@ export async function getPeerDependencyIssues(
proxyConfig: PackageManagerProxyConfig;
networkConfig: PackageManagerNetworkConfig;
overrides?: Record<string, string>;
} & Pick<CreateStoreControllerOptions, 'packageImportMethod' | 'pnpmHomeDir'>
packageImportMethod?: 'auto' | 'hardlink' | 'copy' | 'clone';
pnpmHomeDir?: string;
}
): Promise<PeerDependencyIssuesByProjects> {
const projects: ProjectOptions[] = [];
for (const [rootDir, manifest] of Object.entries(manifestsByPaths)) {
projects.push({
buildIndex: 0, // this is not used while searching for peer issues anyway
manifest,
rootDir: rootDir as ProjectRootDir,
const projects: nodeApi.NodeApiProject[] = Object.entries(manifestsByPaths).map(([rootDir, manifest]) => ({
rootDir,
manifest: manifest as nodeApi.PackageManifest,
}));
try {
return await nodeApi.getPeerDependencyIssues({
dir: opts.rootDir,
projects,
storeDir: opts.storeDir,
cacheDir: opts.cacheDir,
overrides: opts.overrides,
peersSuffixMaxLength: 1000,
registries: opts.registries.toMap(),
virtualStoreDirMaxLength: VIRTUAL_STORE_DIR_MAX_LENGTH,
});

ghost Jul 15, 2026

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

2. Peer issues ignore proxy 🐞 Bug ≡ Correctness

lynx.getPeerDependencyIssues() accepts proxyConfig and networkConfig in its opts but doesn’t
forward them to nodeApi.getPeerDependencyIssues(), so caller-provided proxy/TLS settings have no
effect for peer issue calculation.
Agent Prompt
### Issue description
`getPeerDependencyIssues()` is passed `proxyConfig`/`networkConfig` from `PnpmPackageManager`, but the implementation drops them when calling `nodeApi.getPeerDependencyIssues()`. This makes those inputs ineffective and risks incorrect behavior in proxy/TLS-constrained environments.

### Issue Context
`PnpmPackageManager.getPeerDependencyIssues()` collects the configs and forwards them; `lynx.getPeerDependencyIssues()` currently ignores them.

### Fix Focus Areas
- scopes/dependencies/pnpm/pnpm.package-manager.ts[258-279]
- scopes/dependencies/pnpm/lynx.ts[192-220]

### Suggested change
Either:
1) Pass the converted configs if `@pnpm/napi` supports them (e.g. `proxyConfig: toNodeApiProxyConfig(opts.proxyConfig)` and `networkConfig: toNodeApiNetworkConfig(opts.networkConfig)` plus any required auth headers), or
2) Remove these fields from the `opts` shape and stop collecting/passing them to avoid a misleading API.

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 00b5270

Comment on lines +521 to +537
async function removeWantedLockfileForUpdate(
rootDir: string,
updateAll?: boolean
): Promise<(() => Promise<void>) | undefined> {
if (!updateAll) return undefined;
const lockfilePath = join(rootDir, 'pnpm-lock.yaml');
let lockfileContent: Buffer;
try {
lockfileContent = await fs.readFile(lockfilePath);
} catch (err: any) {
if (err?.code === 'ENOENT') return undefined;
throw err;
}
await fs.unlink(lockfilePath);
return async () => {
await fs.writeFile(lockfilePath, lockfileContent);
};

ghost Jul 15, 2026

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. Lockfile deleted on update 🐞 Bug ☼ Reliability

In lynx.install(), update-all runs removeWantedLockfileForUpdate(), which unlinks pnpm-lock.yaml
before calling nodeApi.install(). If the process is abruptly terminated after unlinking
(SIGKILL/OOM/crash) and before pnpm writes a new lockfile, the workspace can be left without
pnpm-lock.yaml.
Agent Prompt
### Issue description
`removeWantedLockfileForUpdate()` deletes `pnpm-lock.yaml` in-place during `updateAll`, and the original is only restored on the normal caught-error path. If the process is interrupted after the delete, the workspace may be left without a wanted lockfile.

### Issue Context
This is triggered only when `updateAll` is true. The current approach relies on JavaScript cleanup, which does not run for hard terminations.

### Fix Focus Areas
- Avoid deleting the only copy of `pnpm-lock.yaml` before the install succeeds (prefer atomic rename to a backup file).
- Ensure that on success the backup is removed, and on failure (or on next startup) the backup can be restored.
- Keep the logic scoped to update-all behavior.

- scopes/dependencies/pnpm/lynx.ts[453-538]

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

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

Comment on lines +1476 to +1485
const trimmedSpec = spec.trim();
if (!trimmedSpec) return false;
if (semver.valid(trimmedSpec) || semver.validRange(trimmedSpec)) return true;
if (/^(?:workspace|file|link|git|git\+https?|ssh):/.test(trimmedSpec)) return true;
if (/^https?:\/\/registry\.npmjs\.org\/.+\/-.+\.tgz(?:[#?].*)?$/.test(trimmedSpec)) return true;
if (trimmedSpec.startsWith('npm:')) {
const versionStart = trimmedSpec.lastIndexOf('@');
return versionStart > 'npm:'.length && this.isValidVersionSpecifier(trimmedSpec.slice(versionStart + 1));
}
return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(trimmedSpec);

ghost Jul 15, 2026

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. Npm alias rejected 🐞 Bug ≡ Correctness

DependencyResolverMain.isValidVersionSpecifier() returns false for npm: aliases that omit an
explicit @<version|tag> suffix (e.g. npm:uri-js-replace), even though pnpm accepts that alias
form. This can cause dependency-resolver aspect-data validation to reject dependency/policy versions
that would otherwise install correctly.
Agent Prompt
### Issue description
`DependencyResolverMain.isValidVersionSpecifier()` rejects valid pnpm `npm:` alias specifiers when they don’t include an `@<version|tag>` suffix (e.g. `npm:uri-js-replace`). This is because it assumes every `npm:` alias must contain an `@` and only validates the substring after the last `@`.

### Issue Context
The repo itself uses the alias-without-version form in `workspace.jsonc` overrides, demonstrating this is a real, used specifier shape.

### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[1475-1485]

### Suggested fix
Update the `npm:` handling to properly parse the alias package name (including scoped names) and treat a missing alias-version as valid.

One robust approach:
- Parse with something like `^npm:(@[^/]+/[^@]+|[^@]+)(?:@(.+))?$`.
- If the optional version/tag part is missing: return `true` (it resolves to `latest`).
- If present: validate that part using the same semver/tag/url rules.

Add a small unit test (or expand an existing validation test) that asserts:
- `npm:uri-js-replace` is valid
- `npm:@zkochan/[email protected]` is valid
- `npm:pkg@latest` is valid

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

Comment on lines +38 to +52
let dp!: typeof Dp;
let getLockfileImporterId!: typeof GetLockfileImporterId;
let loading: Promise<void> | undefined;

export function init(): Promise<void> {
loading ??= (async () => {
const { loadEsm } = require('./load-pnpm-esm.cjs') as {
loadEsm: () => Promise<{ dp: typeof Dp; getLockfileImporterId: typeof GetLockfileImporterId }>;
};
const m = await loadEsm();
dp = m.dp;
getLockfileImporterId = m.getLockfileImporterId;
})();
return loading;
}

ghost Jul 15, 2026

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

2. Init not enforced 🐞 Bug ☼ Reliability

lockfile-deps-graph-converter.ts now depends on module-level dp/getLockfileImporterId that are
only assigned by async init(), but the exported converters dereference them without any guard. Any
direct caller that forgets to await init() will crash at runtime when dp is first used.
Agent Prompt
### Issue description
The converter module introduces an async `init()` that populates module-level ESM-only dependencies (`dp`, `getLockfileImporterId`). However, `convertLockfileToGraph()` / `convertGraphToLockfile()` (and helpers) dereference those variables synchronously with no runtime guard, so forgetting to call `await init()` will lead to a hard crash.

### Issue Context
Current known callers do call `init()`, but the contract is implicit and fragile for future refactors, new call sites, or test isolation.

### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[34-52]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[73-83]

### Suggested fix
Make the initialization contract explicit and safe by doing one of:
1) **Lazy init inside the public API**: change exported converters to `async` and `await init()` at the start (or `await loading`), so callers can’t misuse the module.
2) **Add an initialization guard**: e.g. `function assertInitialized(){ if (!dp || !getLockfileImporterId) throw new Error('lockfile-deps-graph-converter not initialized; call await init() first'); }` and call it at the top of exported functions.

Option (1) is safest if signature changes are acceptable; otherwise (2) at least fails fast with a descriptive error.

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

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

Comment on lines +260 to +264
function isSameDirectDependency(dep1: DependencyNeighbour, dep2: DependencyNeighbour): boolean {
if (!dep1.name || !dep2.name) return dep1.id === dep2.id;
if (dep1.name !== dep2.name) return false;
return dep1.specifier === dep2.specifier || isWildcardSpecifier(dep1.specifier) || isWildcardSpecifier(dep2.specifier);
}

ghost Jul 15, 2026

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. Wildcard range overwrite 🐞 Bug ≡ Correctness

DependenciesGraph.merge() treats same-name direct deps as identical when either specifier is '*' /
empty, and may overwrite the existing node id with a higher version without checking it satisfies
the non-wildcard range. This can cause convertGraphToLockfile() to write a lockfile that resolves a
dependency version outside the manifest’s declared semver constraint, leading to incorrect installs.
Agent Prompt
### Issue description
`DependenciesGraph.merge()` can merge two direct dependencies of the same name even when only one has a wildcard specifier (`*`/empty). It then may replace the existing dependency `id` with a higher version, without ensuring that higher version satisfies the stricter (non-wildcard) semver range.

This can corrupt downstream lockfile generation: `convertGraphToLockfile()` matches importers by `directDep.specifier === manifest specifier`, so the stricter specifier can remain while the selected `id` points at an incompatible higher version.

### Issue Context
This merged dependencies graph is used during installation/lockfile generation for imported components, so an incorrect merge can affect real installs.

### Fix Focus Areas
- scopes/scope/objects/models/dependencies-graph.ts[78-101]
- scopes/scope/objects/models/dependencies-graph.ts[260-268]

### Suggested fix approach
1. Tighten `isSameDirectDependency()` so wildcard does **not** automatically unify with a constrained specifier. For example:
   - Consider deps the same only when:
     - `name` matches AND specifiers are exactly equal, OR
     - both specifiers are wildcard/empty.
2. Additionally (or alternatively), before overwriting `existingDirectDep.id` with `directDep.id`, ensure the candidate version satisfies the effective constraint:
   - If `existingDirectDep.specifier` is a valid semver range, extract the version from `directDep.id` and validate with `semver.satisfies(version, existingDirectDep.specifier)`.
   - Only upgrade when the candidate version is compatible.
3. Add a regression test where one graph has `foo` with `^1.0.0` and another has `foo` with `*` resolving to `2.0.0`, and assert the merged graph does not pick `2.0.0` for the `^1.0.0` specifier.

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

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

Comment on lines +518 to +540
function dropUnreachableLockfileEntries(lockfile: BitLockfileFile): void {
const reachablePackages = new Set<string>();
const reachableSnapshots = new Set<string>();
const visit = (depPath: string) => {
if (reachableSnapshots.has(depPath)) return;
reachableSnapshots.add(depPath);
reachablePackages.add(dp.removeSuffix(depPath));
const snapshot = lockfile.snapshots?.[depPath];
if (!snapshot) return;
for (const depType of ['dependencies', 'optionalDependencies'] as const) {
for (const [name, ref] of Object.entries(snapshot[depType] ?? {})) {
if (ref.startsWith('link:') || ref.startsWith('file:')) continue;
visit(`${name}@${ref}`);
}
}
};
for (const importer of Object.values(lockfile.importers ?? {})) {
for (const depType of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {
for (const [name, { version }] of Object.entries(importer[depType] ?? {})) {
if (version.startsWith('link:') || version.startsWith('file:')) continue;
visit(`${name}@${version}`);
}
}

ghost Jul 15, 2026

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. Alias deps pruned 🐞 Bug ≡ Correctness

The new lockfile reachability pruning builds child dep paths as ${name}@${ref}, which fails for
pnpm alias refs where ref already encodes a different depPath (e.g. `uri-js:
[email protected]`). As a result, alias targets can be treated as unreachable and deleted from
packages/snapshots, yielding an incomplete/invalid lockfile for subsequent installs.
Agent Prompt
### Issue description
Two new lockfile-pruning walkers assume every dependency reference can be traversed by concatenating `${name}@${ref}`. This breaks pnpm alias representation where the value is already a depPath for a *different* package name (e.g. `uri-js: [email protected]`). In that case traversal never reaches `[email protected]`, and it may be deleted from `packages`/`snapshots`.

### Issue Context
In `pnpm-lock.yaml`, alias deps can appear as `uri-js: [email protected]` (not `uri-js: 1.0.1`). The existing lockfile keys for that target are `[email protected]`, not `uri-js@[email protected]`.

### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[518-540]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[643-667]

### Concrete fix approach
- In `lockfile-deps-graph-converter.ts`, use pnpm’s dep-path helper instead of string concatenation:
  - Replace `visit(`${name}@${ref}`)` / `visit(`${name}@${version}`)` with `const child = dp.refToRelative(refOrVersion, name); if (child) visit(child);`
  - This correctly handles semver refs, peer suffixes, patch hashes, and alias depPaths.
- In `pnpm.package-manager.ts` (no `dp` available synchronously), add a small normalization helper:
  - If the ref/version starts with a digit (e.g. `1.2.3(...)`), treat it as a version and visit `${name}@${ref}`.
  - Otherwise (e.g. `[email protected]` or `@scope/[email protected]`), treat it as an already-formed depPath and visit `ref` directly.
- Add a regression test (unit-level) with a minimal lockfile containing an alias dependency to ensure pruning retains the alias target package + snapshot.

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 564afad

Comment on lines +197 to +216
private async getCirclePullRequestBranchName(): Promise<string | undefined> {
const pullRequestUrl = process.env.CIRCLE_PULL_REQUEST || process.env.CIRCLE_PULL_REQUESTS?.split(',')[0];
if (!pullRequestUrl) return undefined;

try {
const { pathname } = new URL(pullRequestUrl);
const [, owner, repo, pullSegment, pullNumber] = pathname.split('/');
if (!owner || !repo || pullSegment !== 'pull' || !pullNumber) return undefined;

const headers: Record<string, string> = {
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
};
if (process.env.GITHUB_TOKEN) headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;

const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}`, { headers });
if (!response.ok) return undefined;

const pullRequest = (await response.json()) as { head?: { ref?: string } };
return pullRequest.head?.ref;

ghost Jul 15, 2026

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. Ci branch fetch no timeout 🐞 Bug ☼ Reliability

CiMain.getBranchName() may call getCirclePullRequestBranchName(), which performs a GitHub API fetch
without any timeout/abort signal. On CircleCI PR jobs (where this fallback path runs), a stalled
network request can hang branch detection and block bit ci pr until the job-level timeout.
Agent Prompt
### Issue description
`getCirclePullRequestBranchName()` calls `fetch()` to GitHub’s API without an abort signal / timeout. In the CircleCI PR fallback path (when `CIRCLE_BRANCH` is `pull/*` and `CIRCLE_PULL_REQUEST(S)` is set), this can block `getBranchName()` indefinitely if the request stalls.

### Issue Context
`CiPrCmd.report()` calls `ci.getBranchName()` when `--lane` is not provided; hanging here blocks the command.

### Fix Focus Areas
- scopes/git/ci/ci.main.runtime.ts[180-220]
- scopes/git/ci/commands/pr.cmd.ts[60-70]

### What to change
- Use an abortable timeout for the GitHub API request, e.g. in Node 18+:
  - `const signal = AbortSignal.timeout(10_000)` and pass `{ headers, signal }` to `fetch`.
  - Treat `AbortError` the same as other failures (return `undefined` so the caller can fall back).
- Optionally add a debug log or warning when the API call fails/times out to improve diagnosability in CI.

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 0ff3250

Comment on lines +202 to +204
private isPullRequestRef(branchName: string): boolean {
return /^pull\/\d+(?:\/head)?$/.test(branchName);
}

ghost Jul 15, 2026

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. Merge ref not detected 🐞 Bug ≡ Correctness

CiMain.getBranchName() can return a synthetic PR ref (e.g. pull/<n>/merge) instead of the real
source branch because isPullRequestRef() only matches pull/<n> and pull/<n>/head. When this
happens, the CircleCI PR-URL GitHub API fallback is skipped, which can break lane naming and
post-merge cleanup keyed by branch name.
Agent Prompt
### Issue description
`CiMain.getBranchName()` returns early when `branch.current` is not recognized as a PR ref. The current `isPullRequestRef()` regex does **not** match the common GitHub merge ref form (`pull/<n>/merge`, and sometimes normalized/full forms like `refs/pull/<n>/merge`). This prevents the CircleCI PR URL fallback (`getCirclePullRequestBranchName()`) from running and may return an incorrect branch name.

### Issue Context
- The early return happens before CircleCI fallback logic.
- The PR ref detector only allows `pull/<n>` and `pull/<n>/head`.

### How to fix
- Expand `isPullRequestRef()` to recognize PR merge refs as well.
  - Suggested regex (covers optional `refs/` prefix): `^(?:refs/)?pull/\d+(?:/(?:head|merge))?$`
  - Alternatively: normalize `branchName` by stripping a leading `refs/` before matching.
- Add/adjust a small unit/integration test to ensure `pull/<n>/merge` triggers the CircleCI/GitHub API fallback path.

### Fix Focus Areas
- scopes/git/ci/ci.main.runtime.ts[180-205]

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

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

ghost commented Jul 15, 2026

Copy link
Copy Markdown

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

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

ghost commented Jul 20, 2026

Copy link
Copy Markdown

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

Comment on lines 369 to 376
const pkgsToResolve = getPkgsToResolve(lockfile, manifests);
const failedWorkspaceComponentPkgs = new Set<string>();
for (const pkgId of getWorkspaceComponentPkgIds(lockfile, graph, manifests)) {
failedWorkspaceComponentPkgs.add(pkgId);
}
await Promise.all(
pkgsToResolve.map(async (pkgToResolve) => {
if (lockfile.packages[pkgToResolve.pkgId].resolution == null) {

ghost Jul 20, 2026

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. Workspace pkgs scrubbed 🐞 Bug ≡ Correctness

convertGraphToLockfile() pre-populates failedWorkspaceComponentPkgs with every workspace
component pkgId, so scrubPkgsFromLockfile() will delete those package/snapshot entries and remove
their references even when they resolved successfully. This can cause the graph-derived lockfile to
omit valid workspace-component dependencies (particularly when there is no existing lockfile to
merge), defeating the goal of avoiding re-resolution and potentially producing a broken/incomplete
lockfile subset.
Agent Prompt
### Issue description
`convertGraphToLockfile()` builds a set named `failedWorkspaceComponentPkgs`, but it is currently pre-filled with *all* workspace component package IDs (via `getWorkspaceComponentPkgIds`). Later, any non-empty set is passed to `scrubPkgsFromLockfile()`, which deletes those entries and removes references from snapshots/importers.

This makes the “failed” scrub path run even when nothing failed, which can yield an incomplete graph-derived lockfile (especially when generating a lockfile in a workspace that doesn’t already have one to merge with).

### Issue Context
- `getWorkspaceComponentPkgIds()` returns workspace component pkgIds present in the generated lockfile (not failed ones).
- `scrubPkgsFromLockfile()` deletes those pkgIds from `packages` and removes corresponding deps from snapshots/importers.
- The dependency-graph lockfile generation is intended to preserve locked versions and avoid re-resolving (see merge commentary in pnpm.package-manager).

### Fix Focus Areas
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[369-442]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[500-516]
- scopes/dependencies/pnpm/lockfile-deps-graph-converter.ts[648-682]

### Suggested fix
- Do **not** pre-populate `failedWorkspaceComponentPkgs` with all workspace component pkgIds.
- Keep a separate `workspaceComponentPkgIds` set/list if you need to treat workspace components specially for other logic.
- Only add pkgIds to `failedWorkspaceComponentPkgs` when:
  - `resolve()` throws `ERR_PNPM_NO_MATCHING_VERSION` for a component pkgId, **or**
  - after resolution, the pkg still has no usable `resolution` and it’s a component package.
- Add/adjust a unit test that proves a workspace component with a valid resolution is retained (i.e., not scrubbed) and that only genuinely failing workspace component pkgIds are scrubbed.

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

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

ghost commented Jul 20, 2026

Copy link
Copy Markdown

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

@zkochan zkochan mentioned this pull request Jul 20, 2026
12 of 14 tasks
@zkochan

ghost commented Jul 20, 2026

Copy link
Copy Markdown
Member Author

Replaced by #10508, created from a fresh branch off latest master with the PR changes squashed into one commit.

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.

2 participants