Skip to content

feat: opt-in support for pnpm's global virtual store - #10582

Merged
zkochan merged 34 commits into
teambit:masterfrom
zkochan:gvs2
Aug 8, 2026
Merged

zkochan merged 34 commits into
teambit:masterfrom
zkochan:gvs2

Conversation

@zkochan

@zkochan zkochan commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Opt-in support for pnpm's global virtual store: dependency directories are created once in a store shared by every workspace on the machine, instead of being re-created inside each node_modules/.pnpm. Capsules deliberately keep the project-local layout — see below.

Every engine dependency is in a published @pnpm/napi: the settings surface (pnpm/pnpm#13648) and the link: slot fix (pnpm/pnpm#13658) in 12.0.0-rc.0, and the slot-materialization dedup (pnpm/pnpm#13669) in 12.0.0-rc.1, which this branch pins. The local-engine bootstrap script is gone.

Effect

After a fresh install the project-local virtual store holds nothing but lock.yaml and the hoisted node_modules — every dependency directory, including injected workspace components, lives in the shared store:

workspace node_modules/.pnpm entries, no GVS with GVS
a Bit Cloud workspace 20832 0
the bit repo itself 6441 0
bitdev-envs 4017 0

Bit uses pnpm's own <storeDir>/links, so slots are reused across bit versions and shared with every other pnpm project on the machine, upgrades stay incremental, and pnpm store prune accounts for them.

Migration note: switching an existing workspace over does not remove what the previous project-local store already contains — pnpm does not prune it once the effective virtual store points elsewhere — so the old directories linger until node_modules/.pnpm is deleted. New workspaces never see them.

Turning it on

Off by default. Per workspace under teambit.dependencies/dependency-resolver, machine-wide with bit config set enable_global_virtual_store true, or per run with BIT_ENABLE_GLOBAL_VIRTUAL_STORE=true. It has no effect when nodeLinker is hoisted, which uses no virtual store at all.

What it took to behave identically

A shared store breaks one assumption that runs through Bit: that a package can walk up out of node_modules/.pnpm into the workspace. Consequences:

  • Core aspects (CJS). Bit deliberately does not declare @teambit/* core aspects as dependencies of the envs and aspects that use them — they have to be the single copy from the running installation, and declaring them would install duplicates. Project-locally they resolved by walking up into the workspace root; nothing in a shared store can. This branch uses pnpm's documented mechanism for hoisted dependencies in this layout: the privately hoisted directory stays project-local at node_modules/.pnpm/node_modules even under the global virtual store, the core aspects are linked there, and bootstrap puts that directory on NODE_PATH before any aspect loads. Nothing is written inside the store itself, which is what allows the shared <storeDir>/links to be used at all.
  • Core aspects (ESM). Node ignores NODE_PATH for ESM, and bit supports ESM components, so the same hoisted-directory fallback is provided to the ESM resolver via a module.register() loader (adapted from pnpm's @pnpm/plugin-esm-node-path, MIT), installed at bootstrap and propagated to child processes through NODE_OPTIONS.
  • Phantom tsconfig extends in published envs. TypeScript resolves extends with its own resolver — neither NODE_PATH nor the ESM loader applies — and several published envs extend a package they never declare (@teambit/react/typescript/tsconfig.json from the node mocha envs, base-react-env, rspack.envs.react-env and react-env 1.x; rspack.envs.react-env/config/tsconfig.json from cloud-react). Project-locally the walk up out of .pnpm passed the privately hoisted directory and caught these by accident. Fixed with pnpm's documented remedy: built-in packageExtensions declaring the missing dependency for the known envs, merged under the workspace's own packageExtensions so users can cover third-party envs the same way. Extensions only add what a manifest lacks, an unmatched entry is not an error (react-env's is scoped to @1 — 2.x inlined the config), and none of these envs import their extends-target at runtime, so the added copy cannot shadow the host-provided singletons. (fix(dependency-resolver): patch react-env's tsconfig extends for the global virtual store #10572 explored a patchedDependencies-based variant for react-env 1.x and is closed — the extensions cover it.)
  • The bit repo itself. A workspace that authors the core aspects bridges them into the hoisted store only until they compile, then removes the bridge. Right project-locally, fatal from a shared store. The bridge now persists, repointed at the compiled workspace copy.
  • Injected dirs. getInjectedDirs reports an injected copy absolute when it cannot be made relative to the lockfile dir — under a shared store, always. compiler.task.ts joined it onto the capsule root regardless, hard-linking build artifacts into a path that does not exist. (node-modules-linker and workspace-compiler already guarded this; only that one site did not.)
  • bit deps diagnose. Its duplicate-copy counts came from scanning node_modules/.pnpm. The shared store holds every workspace's packages, so it cannot answer that question for one workspace; the counts now come from the current lockfile pnpm writes next to the hoisted directory, whose dep paths map one-to-one onto the project-local directory names.
  • Capsules stay project-local. A capsule is a self-contained build sandbox and TypeScript's declaration emit depends on that: it names an inferred type through the package that declares it, which it can only do while that package sits inside the capsule. Moving env/aspect packages out made bit build of any custom env fail with TS2742. Workspace installs — the ones users wait on repeatedly — still get the shared store.

Also here: patchedDependencies

The branch adds pnpm's patchedDependencies as a dependency-resolver setting (it began as the vehicle for the react-env tsconfig fix above, and is useful on its own):

{
  "teambit.dependencies/dependency-resolver": {
    "patchedDependencies": { "[email protected]": "patches/is-positive.patch" }
  }
}

Paths are relative to the workspace root. pnpm resolves a relative patch path from the directory it is installing in, so capsule installs — which run in the capsules directory — get the paths resolved against the workspace root first; workspace installs keep the configured spelling, which pnpm records in pnpm-lock.yaml and which must stay machine-independent there.

Self-hosting: a workspace whose node_modules provides the running bit

Both layouts are safe in steady state: repeat installs preserve the top-level package directories the running process resolves from (verified by sampling them through live installs), and the end-of-install compile refreshes the per-variant copies. A layout switch is different — it relocates every injected component package, rebuilding the top-level directories from source, so their compiled dist disappears mid-install and a bit running from them dies before reaching the compile that would restore it, leaving node_modules unusable. The installer now detects the combination (current layout read off .modules.yaml, self-hosting by realpath of the running module) and refuses up front with instructions to run the one-time transition from an external bit installation.

With that and the engine fix, the bit repo itself runs under the global virtual store: full install + compile of all 332 components, repeat self-hosted installs in ~50s, npm run lint green. The repo's own tsc needed the type-layer counterpart of the runtime bridges — tsconfig.json paths routing react typings and @teambit/* through the workspace's node_modules, since a published package's .d.ts cannot reach undeclared @types/core aspects from a store slot either.

Phantom dependencies, generally

A shared store makes an under-declared package fail loudly: it lives outside the project, so nothing the project hoisted is on its resolution path any more. That is a real constraint, not a bug to work around, and it applies to pnpm generally rather than to Bit. Every failure this branch hit was a genuine phantom dependency — an env's undeclared tsconfig base, a fixture env with detection switched off (@bit-no-check removed so the dependency gets declared), @teambit/webpack.webpack-bundler requiring events/ without declaring it (covered by packageExtensions, documented in the aspect docs), and the repo's own undeclared @types/graceful-fs (now declared).

One CI change

bit_pr now runs on a temp lane (dropped --keep-lane). A reused PR lane serves components unchanged since an earlier export with artifacts from older commits, so capsules mix generations of @teambit packages and cross-copy instanceof checks start failing — deterministic red that looks exactly like branch breakage and defeats bisection (on this branch: run 1 green on a fresh lane, every later push red, across 11 runs and 2 lanes). Filed as #10583; the temp-lane flow is self-consistent per run.

Testing

  • New e2e: global-virtual-store.e2e.ts (nothing materialized in the workspace, dependencies linked from the shared store, component loads and compiles, patched dependencies under the store) and patched-dependencies.e2e.ts (a workspace-relative patch applies both in the workspace and in the capsule — verified to fail before the capsule-path fix).
  • The bit repo (332 components): full global-virtual-store install, repeat self-hosted installs, transition guard verified in both directions (clean refusal, workspace intact), lint green. Runs on the released rc.1 engine.
  • A Bit Cloud workspace, 105 components: wiped-node_modules install + compile, slot reuse verified (a repeat install creates 0 of 30766 slots), core-aspect resolution through NODE_PATH verified positively and negatively, bit start working.
  • bitdev-envs (609 components, 20 apps): bit app list byte-identical to the non-GVS baseline, apps running — against an earlier revision of the core-aspect mechanism.
  • The full e2e suite under BIT_ENABLE_GLOBAL_VIRTUAL_STORE=true was run locally against an earlier revision: no GVS-specific failures (the validate command failures reproduce with the store off). CI runs the suite in its default store-off configuration, where this branch has been green including the 40-shard e2e.

The first commit (fix(doctor)) is unrelated to the rest and can be split out — it surfaced because the e2e temp dir contains a dot, which is why doctor-infra.e2e.ts fails locally but passes on CI.

zkochan and others added 14 commits August 7, 2026 23:45
`_calculateFinalFileName` stripped the extension from the whole path, so
any dot in a parent directory was treated as the extension:
`bit doctor --archive /tmp/my.dir/report` wrote `/tmp/my.tar` instead of
`/tmp/my.dir/report.tar`.

Strip the extension from the last path segment only. Unrelated to the
rest of this branch - it surfaced because the e2e temp dir contains a
dot, which is why `doctor-infra.e2e.ts` fails locally but passes on CI.
…tore

With `enableGlobalVirtualStore` on, dependency directories are created
once in a store shared by every workspace and capsule on the machine
instead of being re-created inside each `node_modules/.pnpm`. On real
workspaces that collapses the project-local virtual store from 20832 to
529 entries (and 4017 to 258), leaving only the injected components.

Off by default. Enable per workspace under
`teambit.dependencies/dependency-resolver`, machine-wide with
`bit config set enable_global_virtual_store true`, or per run with
`BIT_ENABLE_GLOBAL_VIRTUAL_STORE` (which is how the e2e suite runs the
whole matrix under it).

Making it behave identically to the project-local layout needed four
fixes:

- The core aspects are phantom dependencies of every published env and
  aspect. Project-locally a package in `node_modules/.pnpm` resolves
  them by walking up into the workspace's root `node_modules`; nothing
  in a shared store can walk up into a workspace, so every env failed to
  load. Mirror the installation's core-aspect links at the root of the
  store, which every slot in it can reach, and key that store per bit
  installation so two of them cannot shadow each other's aspects.
- A workspace that authors the core aspects (the bit repo) bridges them
  into the hoisted store only until they compile, then removes the
  bridge. That is right project-locally and fatal from a shared store,
  so under it the bridge stays, repointed at the compiled workspace copy.
- `getInjectedDirs` reports an injected copy absolute when it cannot be
  made relative to the lockfile dir - which under a shared store is
  always. `compiler.task.ts` joined it onto the capsule root regardless,
  hard-linking build artifacts into a path that does not exist.
- Capsules stay on the project-local store. A capsule is a self-contained
  build sandbox and TypeScript's declaration emit depends on that: it
  names an inferred type through the package that declares it, which it
  can only do while that package is inside the capsule. Moving env and
  aspect packages out made `bit build` of any custom env fail with
  TS2742.

Also adds `patchedDependencies` and `packageExtensions` passthrough.
`packageExtensions` is not optional under a shared store: it is the only
way to satisfy a phantom dependency of a published package, since the
package now lives outside the project and can no longer reach whatever
the project hoisted.

`bit deps diagnose` and the prune step read the current lockfile instead
of assuming `node_modules/.pnpm` holds the packages, and the global store
is skipped for `nodeLinker: hoisted`, which uses no virtual store.
Three suites hand-wrote paths that only exist in the project-local
virtual store, so they broke under the global one even though the
behaviour they check was fine:

- `install.e2e` and `node-linker.e2e` asserted on `node_modules/.pnpm`
  directly. New `helper.fs.getVirtualStoreDirNames()` reads the current
  lockfile when the directory holds no package dirs, which yields the
  same names either way.
- `dependency-resolver.e2e` verified dependency overrides by reading
  `node_modules/.pnpm/<depPath>/node_modules/<dep>/package.json`. New
  `helper.fs.readPackageJsonOfChain(['rimraf','glob','inflight','once'])`
  walks the chain the way Node resolves it, so it is correct under the
  project-local, global and hoisted layouts alike.

Adds `global-virtual-store.e2e.ts` covering the store itself: deps are
not created in the workspace, they resolve out of the shared store, the
current lockfile still records them, the component loads and compiles,
and a patched dependency is applied to the shared copy.
Documents `enableGlobalVirtualStore`, `globalVirtualStoreDir` and
`patchedDependencies`, and adds the script that installs a locally built
pnpm engine over the published `@pnpm/napi` - needed until a release
carries the options this branch passes (pnpm/pnpm#13648).
`my-react-env.bit-env.ts` opened with `// @bit-no-check`, which turns off
Bit's dependency detection for the file. Its imports - notably
`@teambit/react.react-env` - therefore never reached the component's
generated manifest, so the env only resolved them by reaching packages
the workspace had hoisted.

That is a phantom dependency, and it stops working the moment the
package is not inside the project any more: under the global virtual
store the env fails to load with `Cannot find module
'@teambit/react.react-env'`. Nothing in this fixture needs dependency
detection off - `@ts-nocheck`, which is what the tsconfig scenario
actually relies on, stays.

None of the real env components in the workspaces this was checked
against carry `@bit-no-check`, and they resolve correctly either way.
… global virtual store

The core aspects are phantom dependencies of every published env: required
without being declared, provided by the running bit installation. Under the
project-local virtual store an env resolves them by walking up out of
node_modules/.pnpm into the workspace root. Under the global virtual store the
env lives in the shared store with no workspace above it, so that fails.

Bit worked around this by mirroring the core aspects at the root of the virtual
store, which forced a <storeDir>/bit-links/<installationId> root private to one
bit installation: no slot reuse across bit versions or with other pnpm
projects, a full re-materialization of ~275k directories on every bit upgrade,
and nothing to prune stale roots.

Use pnpm's documented mechanism for hoisted dependencies in this layout
instead. The privately hoisted directory stays project-local at
node_modules/.pnpm/node_modules even under the global virtual store, and is
reached from a store slot via NODE_PATH. Link the core aspects there and put it
on NODE_PATH during bootstrap - pnpm does that for the shims it writes, but bit
runs from bvm and loads aspects in its own process.

Nothing is written inside the store, so pnpm's shared <storeDir>/links can be
used: slots are reused across bit versions and with every other pnpm project,
upgrades stay incremental, and pnpm store prune accounts for them.

Node ignores NODE_PATH for ESM. Core aspects and published env dists are
CommonJS today; @pnpm/plugin-esm-node-path is the escape hatch if that changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… in ESM too

NODE_PATH covers only CommonJS - Node ignores it for ESM entirely. Bit supports
ESM components, so an ESM package in the shared store could not reach the
hoisted directory at all, leaving the workaround covering only half the problem.

Register an ESM loader whose resolve hook retries a failed bare specifier
against the NODE_PATH entries. Registered in bit's own process via
module.register, and exported through NODE_OPTIONS so the processes bit spawns -
env build steps, app servers, test workers - inherit it, since they resolve
their own dependencies and hit the same wall.

The loader and the --import registration are adapted from pnpm's
@pnpm/plugin-esm-node-path (MIT), inlined as a data URL so there is no file to
ship and no install step to depend on. Skipped when module.register is missing
(Node < 20.6); the CommonJS half still applies there.

Also generalize the surrounding comments: this is about phantom dependencies as
a class, not core aspects specifically. The core aspects are the case that
motivated it, but any under-declared package resolves the same way, which is why
the whole hoisted directory goes on the path rather than a hand-picked list.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The global virtual store work needs two engine changes that are now in a
released build: the napi surface for `enableGlobalVirtualStore`,
`globalVirtualStoreDir`, `packageExtensions` and `patchedDependencies`
(pnpm/pnpm#13648), and the fix for `link:` dependencies vanishing from
virtual-store slots (pnpm/pnpm#13658).

Verified on the released engine: a global-virtual-store install of the
opus-5 workspace reuses all 30,766 existing slots (creates none), leaves
the project-local `node_modules/.pnpm` empty, and still applies the
react-env tsconfig patch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…f-hosted workspaces

Two failures surfaced running bit's own repo (a workspace whose node_modules
provides the running bit) under the global virtual store; both are general.

Built-in packageExtensions. Several published envs' tsconfigs `extends` a
package they never declare (`@teambit/react/typescript/tsconfig.json` from the
node mocha envs, base-react-env, rspack react-env and react-env 1.x;
`@teambit/rspack.envs.react-env/config/tsconfig.json` from cloud-react).
TypeScript resolves `extends` with its own resolver from the tsconfig's real
location: project-locally the walk up out of node_modules/.pnpm passes the
privately hoisted directory, which catches any phantom, so these envs worked by
accident; a global-store slot walks up into the store and finds nothing, and
`bit status`/`bit compile` fail with "File '@teambit/react/typescript/
tsconfig.json' not found." Ship pnpm's documented remedy for exactly this -
packageExtensions declaring the missing dependency - for the known envs, merged
under the workspace's own entries so users can cover third-party envs the same
way. Extensions only add what a manifest lacks, an unmatched entry is not an
error (which is why react-env's can be scoped to @1 - 2.x inlined the config),
and none of these envs import their extends-target at runtime, so the added
registry copy cannot shadow the host-provided core-aspect singletons.

Transition guard. Switching a workspace between the project-local and global
layouts relocates every injected component package, rebuilding the top-level
directories from source - their compiled dist disappears until the
end-of-install compile restores it. Steady-state installs in either layout
preserve the top-level directories (verified by sampling them through live
installs), so a bit running from this workspace's node_modules survives every
install except the layout switch itself, where it loses its own code
mid-install and leaves node_modules unusable. Detect the combination up front -
current layout read off .modules.yaml's virtualStoreDir, self-hosting detected
by realpath of the running module - and refuse with instructions to run the
one-time transition from an external bit installation. The guard sits in
installComponents, not install(): workspace installs enter there directly.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tual store

The repo's own tsc gate broke once node_modules moved to the global virtual
store, all through one mechanism: a published package's .d.ts can no longer
reach undeclared packages by walking up from its store slot, where the walk out
of node_modules/.pnpm used to catch them.

- tsconfig paths: route react/react-dom to the workspace's hoisted @types (the
  published UI packages peer on react but never declare @types/react, so their
  props types silently collapsed - 58 of 68 errors), and route @teambit/* through
  the workspace's node_modules (published .d.ts reference core aspects they never
  declare; this is the type-layer counterpart of the runtime NODE_PATH bridge).
- declare @types/graceful-fs, which run-bit.ts relied on as a phantom.
- drop two @ts-expect-error suppressions whose local-vs-published skew the now
  consistent resolution eliminated, annotate the component-compare query
  response whose published type lags the GraphQL response (`tests`), and work
  around the published Tab/ContentTab pair whose members intersect `content`
  into the unusable `ReactNode & string`.

The lockfile carries the built-in packageExtensions (@teambit/react in the
phantom-extends envs' slots) and @types/graceful-fs.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ript

rc.1 carries the slot-materialization dedup (pnpm/pnpm#13669), the last
engine change the global virtual store needed from a checkout, so the
script that installed a locally built engine over the released one goes
away as promised. It also adds `allowUnusedPatches`, which unblocks the
version-scoped patch approach parked in teambit#10572 if it is ever wanted over
the packageExtensions built-ins.

Verified on the released engine: two consecutive self-hosted
global-virtual-store installs of this repo (the workload whose peer
variants previously raced the link pass on every install), zero race
errors, lint green.

Co-Authored-By: Claude Fable 5 <[email protected]>


The two @ts-expect-error suppressions removed in 83e380c were only
unused in the workspace type-check, where the repo tsconfig's paths
collapse @teambit/* to a single copy. The capsule build resolves two
semantic-schema versions (the member's 0.0.92 without diff(), the
renderer's 0.0.113 with it), so the skew error is real there and
bit_pr failed on it. @ts-ignore expresses exactly this
context-dependence: it suppresses where the error occurs and is not
itself an error where it doesn't.

Co-Authored-By: Claude Fable 5 <[email protected]>
…or CI bisect

The global-virtual-store e2e still asserted the obsolete bit-links
private store root; the shared-store design links from pnpm's own
<storeDir>/links, which is what the failing assertion actually showed.

TEMP DO NOT MERGE: the transition guard and built-in packageExtensions
are switched off behind BIT_TEMP_CI_BISECT to split two hypotheses for
the deterministic bit_pr capsule MochaTest failures (this commit's
dependency-installer logic vs the lockfile re-resolution drift). Will
be reverted once the culprit is identified.

Co-Authored-By: Claude Fable 5 <[email protected]>
…mal against master

Re-enables the transition guard and the built-in packageExtensions that
6f6a6a6 had temporarily switched off for a CI bisect - the bisect
exonerated them. What deterministically broke bit_pr's capsule
MochaTest (snapping/checkout/lanes specs) was the committed lockfile: a
full re-resolution consolidates dozens of stale duplicate third-party
versions, which re-pairs peer-suffix variants of @teambit runtime
packages, changes which duplicated copies land in the build capsules,
and breaks cross-copy `instanceof` in the spec flows - the diagnostic
run showed a freshly tagged component reporting `{deleted: true}`
because a thrown ComponentNotFoundInPath from one copy was not an
instance of the class the status loader caught from another.

The lockfile here is master's with exactly two semantic changes - the
@pnpm/napi family bumped to 12.0.0-rc.1 and @types/graceful-fs added -
hand-applied and then normalized by bit 2.0.70's own writer on its
frozen path ("Lockfile is up to date", zero version-set differences).
The snapping/checkout/lanes specs pass against this tree locally.

Known follow-up: an install that re-locks (any manifest change, or a
global-virtual-store install adding the gated extension entries) will
re-trigger the consolidation; the underlying cross-copy identity
fragility deserves its own fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
@zkochan
zkochan marked this pull request as ready for review August 7, 2026 21:47
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add opt-in support for pnpm global virtual store (with safe resolution bridges)

✨ Enhancement 🐞 Bug fix 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add opt-in pnpm global virtual store for workspace installs; keep capsules project-local.
• Bridge phantom/core-aspect resolution via hoisted store, NODE_PATH, and an ESM loader.
• Add transition safety guard, packageExtensions/patchedDependencies support, docs, and e2e
 coverage.
Diagram

graph TD
  A["Workspace config & env"] --> B["DependencyResolverMain"] --> C["DependencyInstaller"] --> D["PnpmPackageManager/Lynx"] --> E["pnpm global virtual store"]
  B --> F["DependencyLinker"] --> G["Hoisted resolution bridge"]
  H["e2e tests"] --> B
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use @pnpm/plugin-esm-node-path as a dependency
  • ➕ Avoids inlining/maintaining a custom ESM loader string
  • ➕ Keeps behavior closer to pnpm’s upstream implementation
  • ➖ Adds a runtime dependency and requires it to be present/installed everywhere Bit runs
  • ➖ Harder to guarantee early bootstrap ordering before any aspect/env loads
2. Keep Bit-private global virtual store root (bit-links/)
  • ➕ Avoids any chance of cross-installation collisions without extra resolution bridges
  • ➖ Loses the main benefit of pnpm’s shared /links (cross-project/bit-version slot reuse)
  • ➖ More custom store semantics; less compatible with pnpm tooling like store prune
3. Eliminate phantom core-aspect deps by declaring them everywhere
  • ➕ Removes the need for NODE_PATH/ESM-loader bridging and special linker behavior
  • ➖ Conflicts with the singleton requirement for @teambit/* core aspects (duplicates likely)
  • ➖ Large ecosystem-wide change with high compatibility risk

Recommendation: Keep the PR’s approach: use pnpm’s shared /links for maximum reuse, but restore Bit’s historical “walk-up” behavior via a project-local hoisted dir + NODE_PATH and an ESM loader fallback. The added transition guard is the right safety net for self-hosted workspaces, and built-in packageExtensions is a pragmatic fix for known tsconfig phantom-deps while still allowing user overrides.

Files changed (29) +6548 / -748

Enhancement (9) +459 / -6
dependency-installer.tsAdd GVS install plumbing, capsule exception, packageExtensions, and transition guard +124/-2

Add GVS install plumbing, capsule exception, packageExtensions, and transition guard

• Threads enableGlobalVirtualStore/globalVirtualStoreDir/patchedDependencies/packageExtensions into package-manager installs, while forcing capsules to remain project-local. Adds built-in packageExtensions for known tsconfig phantom-deps and introduces a guard that blocks unsafe layout switches for self-hosted workspaces.

scopes/dependencies/dependency-resolver/dependency-installer.ts

dependency-linker.tsLink core aspects into privately-hoisted store for GVS resolution +68/-3

Link core aspects into privately-hoisted store for GVS resolution

• Adds linking of core-aspect packages into the project-local hoisted directory so store slots can resolve phantom core dependencies via NODE_PATH. Adjusts authored-core-aspect bootstrap bridging to persist (and repoint) under the global virtual store once compiled.

scopes/dependencies/dependency-resolver/dependency-linker.ts

dependency-resolver.main.runtime.tsImplement GVS enablement precedence and compute global store directory +61/-0

Implement GVS enablement precedence and compute global store directory

• Adds env/workspace/global-config precedence for enableGlobalVirtualStore and computes globalVirtualStoreDir via the package manager. Introduces a stable installation identifier (version + realpath hash) for scoping behavior and threads new config fields into DependencyInstaller construction.

scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts

index.tsExport SelfHostedVirtualStoreTransition exception +1/-0

Export SelfHostedVirtualStoreTransition exception

• Adds the new exception to the dependency-resolver exceptions barrel export so callers can reference it consistently.

scopes/dependencies/dependency-resolver/exceptions/index.ts

index.tsExport PackageExtension type from dependency-resolver public API +1/-0

Export PackageExtension type from dependency-resolver public API

• Exposes the PackageExtension type alongside other package-manager types so workspace config and pnpm adapter code can share it without duplication.

scopes/dependencies/dependency-resolver/index.ts

package-manager.tsAdd packageExtensions type and GVS/patch options to package-manager API +41/-0

Add packageExtensions type and GVS/patch options to package-manager API

• Defines PackageExtension and extends PackageManagerInstallOptions with enableGlobalVirtualStore, globalVirtualStoreDir, patchedDependencies, and packageExtensions. Extends the PackageManager interface with getGlobalVirtualStoreDir capability.

scopes/dependencies/dependency-resolver/package-manager.ts

lynx.tsPass GVS and pnpm extension options through to pnpm engine install +11/-0

Pass GVS and pnpm extension options through to pnpm engine install

• Adds enableGlobalVirtualStore/globalVirtualStoreDir/patchedDependencies/packageExtensions options to the pnpm engine call path. Ensures the hoisted nodeLinker disables GVS since it does not use a virtual store.

scopes/dependencies/pnpm/lynx.ts

pnpm.package-manager.tsImplement globalVirtualStoreDir resolution using pnpm storeDir/links +25/-0

Implement globalVirtualStoreDir resolution using pnpm storeDir/links

• Threads new install options to the pnpm engine adapter. Implements getGlobalVirtualStoreDir returning pnpm’s shared <storeDir>/links (or configured override) now that Bit no longer mirrors core aspects into the store root.

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

bootstrap.tsAdd hoisted dependency resolution via NODE_PATH and ESM loader registration +127/-1

Add hoisted dependency resolution via NODE_PATH and ESM loader registration

• Detects a workspace and prepends its privately hoisted node_modules/.pnpm/node_modules to NODE_PATH, reinitializing Node’s global lookup paths. Registers an ESM resolve-hook loader via module.register and propagates it via NODE_OPTIONS so child processes inherit the fallback behavior.

scopes/harmony/bit/bootstrap.ts

Bug fix (8) +100 / -10
grouped-schema-nodes-overview-summary.tsxAvoid unused ts-expect-error under capsule-only version skew +5/-2

Avoid unused ts-expect-error under capsule-only version skew

• Replaces @ts-expect-error with @ts-ignore and clarifies that the issue appears only in capsule builds where two semantic-schema versions coexist. Prevents workspace type-check from failing due to an "unused expect-error".

components/overview/renderers/grouped-schema-nodes-overview-summary/grouped-schema-nodes-overview-summary.tsx

component-compare.tsxType-narrow GraphQL response to tolerate published type lag +6/-1

Type-narrow GraphQL response to tolerate published type lag

• Renames the raw query result and casts it to include an optional tests field that exists at runtime but is missing from the published types. Documents the version-skew rationale.

components/ui/component-compare/component-compare/component-compare.tsx

component-overview.tsxWork around ContentTab type intersection skew from published types +12/-2

Work around ContentTab type intersection skew from published types

• Defines a local fixed ContentTab shape and casts only at the ContentTabs boundary. Prevents impossible ReactNode & string intersection requirements caused by a published type mismatch.

components/ui/component-meta/component-overview.tsx

compiler.task.tsFix injected-dir hardlinking when injected paths are absolute +8/-1

Fix injected-dir hardlinking when injected paths are absolute

• Guards path-joining logic so absolute injected dirs are not incorrectly joined under the capsule root. Fixes artifact linking when the global virtual store causes injected dirs to be reported as absolute paths.

scopes/compilation/compiler/compiler.task.ts

dependencies.main.runtime.tsDiagnose virtual-store entries via lock.yaml when .pnpm is empty under GVS +24/-2

Diagnose virtual-store entries via lock.yaml when .pnpm is empty under GVS

• Adds logic to compute per-workspace virtual store directory names from node_modules/.pnpm/lock.yaml when package dirs are absent. Updates diagnose flows to use the new reader for consistent behavior under GVS.

scopes/dependencies/dependencies/dependencies.main.runtime.ts

self-hosted-virtual-store-transition.tsAdd explicit error for unsafe self-hosted layout transitions +26/-0

Add explicit error for unsafe self-hosted layout transitions

• Introduces a BitError thrown before installs that would switch virtual store layouts while Bit is running from the workspace’s own node_modules. Provides actionable instructions to perform the one-time transition from an external Bit installation.

scopes/dependencies/dependency-resolver/exceptions/self-hosted-virtual-store-transition.ts

pnpm-prune-modules.tsHandle empty/missing project-local virtual store under GVS and lockfile-only installs +13/-1

Handle empty/missing project-local virtual store under GVS and lockfile-only installs

• Makes pruning resilient when node_modules/.pnpm has no package directories (GVS) or is absent (lockfileOnly), treating both as “nothing to prune”. Prevents ENOENT errors during cleanup.

scopes/dependencies/pnpm/pnpm-prune-modules.ts

doctor.main.runtime.tsFix doctor --archive path handling when parent directories contain dots +6/-1

Fix doctor --archive path handling when parent directories contain dots

• Corrects archive filename generation to strip extensions from the basename only, preserving dots in parent directory names. Prevents truncating paths like /tmp/my.dir/report into /tmp/my.tar.

scopes/harmony/doctor/doctor.main.runtime.ts

Tests (5) +93 / -15
my-react-env.bit-env.tsRemove @bit-no-check marker from tsconfig-issue fixture env +0/-1

Remove @bit-no-check marker from tsconfig-issue fixture env

• Drops the custom no-check directive so the fixture participates in type/dependency validation. Helps surface and validate phantom-dependency behavior under stricter resolution.

components/legacy/e2e-helper/excluded-fixtures/workspace-with-tsconfig-issue/my-scope/envs/my-react-env/my-react-env.bit-env.ts

dependency-resolver.e2e.tsMake dependency override assertions layout-agnostic +4/-12

Make dependency override assertions layout-agnostic

• Replaces hard-coded node_modules/.pnpm paths with resolution-chain helpers. Keeps tests valid across project-local virtual store, global virtual store, and hoisted nodeLinker behaviors.

e2e/harmony/dependency-resolver.e2e.ts

global-virtual-store.e2e.tsAdd e2e coverage for global virtual store and patchedDependencies +85/-0

Add e2e coverage for global virtual store and patchedDependencies

• Adds a new suite that verifies .pnpm contains no package dirs under GVS, deps link from the shared store, lock.yaml still records installed deps, and patchedDependencies applies to the shared-store copy.

e2e/harmony/global-virtual-store.e2e.ts

install.e2e.tsUse virtual-store entry helper when asserting optional deps behavior +1/-1

Use virtual-store entry helper when asserting optional deps behavior

• Switches optional-deps assertions to use getVirtualStoreDirNames so they remain correct under both project-local and global virtual store layouts.

e2e/harmony/install.e2e.ts

node-linker.e2e.tsRelax isolated-linker realpath expectation to support GVS bit-links path +3/-1

Relax isolated-linker realpath expectation to support GVS bit-links path

• Updates the expectation to match either project-local .pnpm or global-store bit-links path patterns. Documents why the realpath differs when GVS is enabled.

e2e/harmony/node-linker.e2e.ts

Documentation (1) +37 / -0
dependency-resolver.mdxDocument global virtual store, patchedDependencies, and config knobs +37/-0

Document global virtual store, patchedDependencies, and config knobs

• Adds docs for enableGlobalVirtualStore, globalVirtualStoreDir, and their tradeoffs/behavior with nodeLinker. Documents patchedDependencies usage in Bit’s dependency-resolver config surface.

scopes/dependencies/aspect-docs/dependency-resolver/dependency-resolver.mdx

Other (6) +5859 / -717
constants.tsAdd global config key for enabling the global virtual store +6/-0

Add global config key for enabling the global virtual store

• Introduces CFG_ENABLE_GLOBAL_VIRTUAL_STORE to allow machine-wide opt-in via Bit config. Documents precedence versus per-workspace dependency-resolver settings.

components/legacy/constants/constants.ts

e2e-fs-helper.tsAdd resolution-robust helpers for pnpm layouts (local/GVS/hoisted) +46/-0

Add resolution-robust helpers for pnpm layouts (local/GVS/hoisted)

• Adds helper methods to resolve package directories via Node-style resolution instead of hard-coded .pnpm paths. Adds logic to derive virtual store entries from lock.yaml when the project-local .pnpm directory contains no package dirs under the global virtual store.

components/legacy/e2e-helper/e2e-fs-helper.ts

pnpm-lock.yamlUpdate lockfile for pnpm engine and dependency graph changes +5759/-714

Update lockfile for pnpm engine and dependency graph changes

• Refreshes the repository lockfile to reflect updated pnpm engine version and related dependency resolution changes required for global virtual store support.

pnpm-lock.yaml

dependency-resolver-workspace-config.tsExpose GVS and pnpm extension config in workspace schema +31/-1

Expose GVS and pnpm extension config in workspace schema

• Adds enableGlobalVirtualStore, globalVirtualStoreDir, patchedDependencies, and packageExtensions to the dependency-resolver workspace config interface. Documents why these matter more under a shared store (phantom dependencies become visible).

scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts

tsconfig.jsonAdd tsconfig path mappings to keep types resolvable under GVS +15/-1

Add tsconfig path mappings to keep types resolvable under GVS

• Pins react/react-dom typings and @teambit/* specifiers to workspace node_modules so published .d.ts resolution matches the runtime hoisted-resolution bridge. Prevents type collapse when store slots cannot walk up to hoisted @types/core aspects.

tsconfig.json

workspace.jsoncBump pnpm engine and add missing @types dependency +2/-1

Bump pnpm engine and add missing @types dependency

• Pins @pnpm/napi to 12.0.0-rc.1 and adds @types/graceful-fs to satisfy newly surfaced type requirements under stricter resolution.

workspace.jsonc

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Capsule patch paths wrong ✓ Resolved 🐞 Bug ≡ Correctness
Description
DependencyInstaller forwards patchedDependencies to the package manager unchanged, but capsule
installs run with rootDir=capsulesDir, so any relative patch path (documented as
workspace-root-relative) will be resolved against the capsule root and can fail the capsule install
with missing patch files.
Code

scopes/dependencies/dependency-resolver/dependency-installer.ts[R349-352]

+      patchedDependencies: this.patchedDependencies,
+      packageExtensions: this.withBuiltInPackageExtensions(
+        this.packageExtensions,
+        !this.installingContext?.inCapsule && this.dependencyResolver.enableGlobalVirtualStore()
Evidence
Docs explicitly state relative patch paths resolve against the workspace root, but capsule installs
use capsulesDir as the install root, and the installer forwards patchedDependencies unchanged to
the package manager, so relative paths will resolve against the wrong directory during capsule
installs.

scopes/dependencies/aspect-docs/dependency-resolver/dependency-resolver.mdx[116-121]
scopes/component/isolator/isolator.main.runtime.ts[1094-1100]
scopes/component/isolator/isolator.main.runtime.ts[1132-1138]
scopes/dependencies/dependency-resolver/dependency-installer.ts[330-377]
scopes/dependencies/dependency-resolver/package-manager.ts[71-75]

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

## Issue description
`patchedDependencies` patch file paths are documented as resolving relative to the workspace root, but capsule installs use a different installation root (`capsulesDir`). `DependencyInstaller` currently passes `patchedDependencies` through unchanged, so relative patch paths will be interpreted relative to the capsule root and the patch file will not be found.
### Issue Context
- Capsules create/install under `capsulesDir`, not the workspace root.
- `patchedDependencies` is a new surface and should behave consistently between workspace installs and capsule installs.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-installer.ts[331-377]
### Suggested fix
1. Before passing `patchedDependencies` to the package manager, normalize values:
- If a patch path is already absolute, keep it.
- If it is relative, resolve it against the *workspace root* (prefer `options.packageManagerConfigRootDir` when present; otherwise use the real workspace root if available).
2. Pass the normalized (absolute) map to the package manager for both workspace installs and capsule installs.
3. (Optional) Add an e2e that configures `patchedDependencies` with a relative path and performs a capsule-based operation (e.g. build/isolate) to ensure it works.

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


2. Test rejects /links paths ✓ Resolved 🐞 Bug ≡ Correctness
Description
e2e/harmony/node-linker.e2e.ts only accepts resolved paths containing ".pnpm" or "bit-links", but
this PR’s pnpm integration uses pnpm’s shared "<storeDir>/links" for the global virtual store, so
the assertion can fail when GVS is enabled.
Code

e2e/harmony/node-linker.e2e.ts[R35-38]

+        // the isolated linker symlinks into a virtual store: `node_modules/.pnpm` project-locally,
+        // or `<storeDir>/bit-links/<installation>` when the global virtual store is enabled.
+        expect(fs.realpathSync(depPath)).to.match(/[\\/](\.pnpm|bit-links)[\\/]/);
});
Evidence
The node-linker test’s regex does not match pnpm’s GVS directory used by this PR. The pnpm package
manager returns /links, and the new global-virtual-store e2e test also expects resolved dependency
paths to contain /links/.

e2e/harmony/node-linker.e2e.ts[33-38]
scopes/dependencies/pnpm/pnpm.package-manager.ts[426-445]
e2e/harmony/global-virtual-store.e2e.ts[33-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
The nodeLinker="isolated" e2e test asserts the resolved dependency path matches `/(\.pnpm|bit-links)/`, but under the global virtual store the real path resolves under `<storeDir>/links`, which this PR explicitly adopts.
### Issue Context
- This will break CI runs that enable the global virtual store (e.g. via `BIT_ENABLE_GLOBAL_VIRTUAL_STORE=true`).
- The PR’s pnpm package-manager now returns `<storeDir>/links` as the global virtual store dir.
### Fix Focus Areas
- e2e/harmony/node-linker.e2e.ts[35-38]
- scopes/dependencies/pnpm/pnpm.package-manager.ts[426-445]
### Suggested fix
- Update the regex to accept `links` (and optionally keep `bit-links` for backward compatibility), e.g. `expect(...).to.match(/[\\/](\.pnpm|links|bit-links)[\\/]/);`
- Update the comment above the assertion to mention `<storeDir>/links` (matching the new implementation and the new GVS e2e test).

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


3. Link errors swallowed ✓ Resolved 🐞 Bug ☼ Reliability
Description
DependencyLinker.linkCoreAspectsToHoistedStore() catches createLinks() failures and only logs a
warning, allowing the link/install flow to proceed even though global-virtual-store slots rely on
those hoisted-store links to resolve phantom core aspects. This can convert a deterministic link
failure into later, harder-to-debug runtime/module-resolution failures.
Code

scopes/dependencies/dependency-resolver/dependency-linker.ts[R231-236]

+    try {
+      await createLinks(hoistedStoreDir, links, { skipIfSymlinkValid: true });
+    } catch (err: any) {
+      this.logger.warn(
+        `failed linking the core aspects into the hoisted store at ${hoistedStoreDir}. ${err.message}`
+      );
Evidence
The new hoisted-store linking path catches and ignores link creation failures, but the resolution
bridge depends on that hoisted directory being on NODE_PATH; without the links, store-slot packages
cannot resolve core aspects from the workspace.

scopes/dependencies/dependency-resolver/dependency-linker.ts[190-237]
scopes/dependencies/fs/linked-dependencies/linked-dependencies.ts[10-22]
scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[162-173]

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

## Issue description
`linkCoreAspectsToHoistedStore()` currently swallows failures from `createLinks()` and proceeds, which can leave required core-aspect links missing while the install/link flow reports success.
### Issue Context
The global-virtual-store resolution bridge relies on the workspace’s privately hoisted directory (`<root>/node_modules/.pnpm/node_modules`) being populated with the core-aspect links. If these links cannot be created, the workspace is effectively broken for packages resolving from global-store slots.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-linker.ts[231-237]
### Implementation notes
- Replace the warn-and-continue behavior with a thrown error (preferably a domain-specific Bit error) so the install/link step fails immediately.
- If there are truly recoverable error modes, explicitly detect and handle only those cases, and validate that the expected links exist before proceeding.

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


View more (6)
4. Self-install root misdetected 🐞 Bug ≡ Correctness
Description
ensureSelfInstallationBridge() derives the installation root by taking the parent of the last
"node_modules" segment of __dirname, which resolves to a pnpm store slot directory under the global
virtual store. isGlobalVirtualStoreLayout() then looks for /node_modules/.modules.yaml and can
incorrectly skip the bridge, breaking phantom-dependency resolution when running Bit outside a
workspace.
Code

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[R115-119]

+function selfInstallationRoot(): string | undefined {
+  const segments = __dirname.split(path.sep);
+  const idx = segments.lastIndexOf('node_modules');
+  if (idx <= 0) return undefined;
+  return segments.slice(0, idx).join(path.sep) || path.sep;
Evidence
The bridge’s "self installation" path is computed from __dirname by trimming to the last
node_modules segment, and then isGlobalVirtualStoreLayout() expects node_modules/.modules.yaml
to exist under that computed root. The PR itself documents that global virtual store packages live
under /links/.../node_modules/..., which means __dirname can point into a store slot where that
.modules.yaml is not located, making the layout check a false negative and skipping the bridge.

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[77-107]
scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[109-135]
scopes/dependencies/dependency-resolver/dependency-linker.ts[196-203]

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

## Issue description
`selfInstallationRoot()` assumes the directory before the last `node_modules` in `__dirname` is the installation root. Under pnpm's global virtual store, Bit packages can be loaded from store-slot paths that contain nested `node_modules` segments, so this heuristic returns the slot root rather than the actual installation root that owns `node_modules/.modules.yaml`. This can cause `ensureSelfInstallationBridge()` to skip installing the hoisted-resolution bridge.
### Issue Context
- `ensureSelfInstallationBridge()` uses `selfInstallationRoot()` and then calls `isGlobalVirtualStoreLayout(root)` which reads `root/node_modules/.modules.yaml`.
- Under GVS, packages can live under paths like `<storeDir>/links/.../node_modules/...` (store slot layout), so `__dirname` can be inside such a slot and the "last node_modules" is not the install boundary.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[109-135]

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


5. Capsule GVS override possible ✓ Resolved 🐞 Bug ≡ Correctness
Description
In DependencyInstaller.installComponents(), capsule-safe values for
enableGlobalVirtualStore/globalVirtualStoreDir are set but can be overridden by the later spread of
packageManagerOptions, allowing a capsule install to accidentally use the global virtual store. This
breaks the PR’s stated capsule invariant and can surface the TS2742-style failures the comment warns
about.
Code

scopes/dependencies/dependency-resolver/dependency-installer.ts[R341-345]

+      enableGlobalVirtualStore:
+        !this.installingContext?.inCapsule && this.dependencyResolver.enableGlobalVirtualStore(),
+      globalVirtualStoreDir: this.installingContext?.inCapsule
+        ? undefined
+        : await this.dependencyResolver.getGlobalVirtualStoreDir(finalRootDir),
Evidence
The code sets capsule-safe enableGlobalVirtualStore and globalVirtualStoreDir, but the final
...packageManagerOptions spread can overwrite them, re-enabling GVS inside capsules.

scopes/dependencies/dependency-resolver/dependency-installer.ts[327-367]

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

## Issue description
`calculatedPmOpts` sets capsule-safe values (`enableGlobalVirtualStore: false` and `globalVirtualStoreDir: undefined` when `installingContext.inCapsule`), but then spreads `...packageManagerOptions` afterwards, which can override those capsule-enforced values.
### Issue Context
The comment explicitly states capsules must remain on the project-local virtual store because declaration emit depends on it. Allowing caller-provided options to override this defeats that invariant.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-installer.ts[327-367]
### Implementation guidance
- Move `...packageManagerOptions` earlier in the object literal (before the capsule-enforced fields), and then re-assert the capsule-enforced values after it.
- Alternatively, explicitly strip `enableGlobalVirtualStore`/`globalVirtualStoreDir`/`packageExtensions`/`patchedDependencies` from `packageManagerOptions` when `installingContext.inCapsule` to prevent future call sites from bypassing the capsule constraint.

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


6. GVS transition misses NODE_PATH ✓ Resolved 🐞 Bug ☼ Reliability
Description
enableHoistedDependencyResolution() only enables the hoisted-resolution bridge when the
*pre-install* node_modules/.modules.yaml already reflects the global virtual store, so a
project-local→GVS switch can complete but then reload envs/compile in the same process without the
bridge, breaking phantom-dep resolution from store slots. The self-hosted transition guard only
blocks transitions when the running bit is inside the workspace; externally hosted bit installs can
still perform the transition and hit this gap.
Code

scopes/harmony/bit/bootstrap.ts[R154-156]

+  if (!isGlobalVirtualStoreLayout(workspaceRoot)) return;
+  const existing = process.env.NODE_PATH;
+  if (!existing?.split(NODE_PATH_SEPARATOR).includes(hoistedDir)) {
Evidence
The bootstrap bridge is gated on the existing .modules.yaml layout (pre-install) and only runs
once at startup, while bit install continues in-process after installComponents() to reload envs
and compile; layout transitions are allowed for externally hosted bit runs because the guard throws
only when bit is self-hosted inside the workspace.

scopes/harmony/bit/bootstrap.ts[70-163]
scopes/harmony/bit/bootstrap.ts[209-239]
scopes/workspace/install/install.main.runtime.ts[437-486]
scopes/dependencies/dependency-resolver/dependency-installer.ts[199-226]
scopes/dependencies/dependency-resolver/dependency-resolver.main.runtime.ts[264-308]

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

## Issue description
When a workspace switches from the project-local virtual store to pnpm’s global virtual store during a single `bit install` run, `bootstrap()` has already executed and `enableHoistedDependencyResolution()` will have decided *not* to set `NODE_PATH` / register the ESM loader because the **old** `.modules.yaml` still indicated the project-local layout. After the install, Bit continues in the same process (env reload + compile), but the bridge isn’t re-applied, so packages now resolving from global-store slots can fail to resolve phantom deps.
### Issue Context
- The transition is allowed for non-self-hosted Bit installs (bvm/global), so this is a real user path.
- The fix needs to ensure:
1) CommonJS global paths are refreshed after `.modules.yaml` changes (via `_initPaths()`), and
2) the ESM loader is registered in the current process (updating `NODE_OPTIONS` alone won’t affect the already-running process).
### Fix Focus Areas
- scopes/harmony/bit/bootstrap.ts[141-207]
- scopes/workspace/install/install.main.runtime.ts[437-486]
- scopes/dependencies/dependency-resolver/dependency-installer.ts[199-226]
### Suggested implementation direction
- Refactor the hoisted bridge logic into an exported, idempotent function (e.g. `ensureHoistedDependencyResolution(workspaceRoot: string)`), so it can be called:
- at process startup (current behavior), and
- **after** `installer.installComponents()` completes, but **before** `reloadMovedEnvs()` / compilation.
- In `InstallMain._installModules` flow, after `await installer.installComponents(...)`, if the workspace is now in GVS layout (or if `dependencyResolver.enableGlobalVirtualStore()` is true), call the exported bridge function to refresh `NODE_PATH` + register the ESM loader for the current process before env reload/compile.

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


7. Hoisted resolution always enabled ✓ Resolved 🐞 Bug ≡ Correctness
Description
enableHoistedDependencyResolution() activates whenever node_modules/.pnpm/node_modules exists, which
Bit’s pnpm integration treats as the default hoisting target; this means Bit will mutate NODE_PATH
and propagate an ESM loader via NODE_OPTIONS even when the global virtual store is not enabled. This
can change module resolution behavior (especially for undeclared/phantom deps) in regular pnpm
workspaces, not just in GVS mode.
Code

scopes/harmony/bit/bootstrap.ts[R136-140]

+function enableHoistedDependencyResolution() {
+  const workspaceRoot = findWorkspaceRoot(process.cwd());
+  if (!workspaceRoot) return;
+  const hoistedDir = path.join(workspaceRoot, 'node_modules', '.pnpm', 'node_modules');
+  if (!fs.existsSync(hoistedDir)) return;
Evidence
Bootstrap currently enables the workaround whenever the hoisted dir exists, and Bit’s pnpm
config/docs indicate hoisting to node_modules/.pnpm/node_modules is a standard/default behavior, so
the condition is likely true even without GVS enabled.

scopes/harmony/bit/bootstrap.ts[70-73]
scopes/harmony/bit/bootstrap.ts[136-149]
scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts[237-248]
scopes/dependencies/pnpm/pnpm.package-manager.ts[585-595]

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

## Issue description
`enableHoistedDependencyResolution()` is intended to support pnpm’s **global virtual store** layout, but it currently triggers solely based on the existence of `<workspace>/node_modules/.pnpm/node_modules`. Bit’s pnpm integration/documentation indicates this hoisted directory is a normal/default pnpm setup (hoisting target), so the bootstrap path can run even when GVS is not enabled, mutating `NODE_PATH`/`NODE_OPTIONS` for the Bit process and child processes.
### Issue Context
The function is invoked at the top of `bootstrap()`, before aspects load, so the gating must rely on filesystem state (e.g. pnpm metadata), not on DependencyResolver runtime state.
### Fix Focus Areas
- scopes/harmony/bit/bootstrap.ts[70-73]
- scopes/harmony/bit/bootstrap.ts[136-149]
### Suggested fix
1. Replace the current heuristic ("hoistedDir exists") with a check for the *active virtual store layout*.
2. Read and parse `<workspaceRoot>/node_modules/.modules.yaml` (YAML) and inspect `virtualStoreDir`:
- If `virtualStoreDir` resolves **inside** the workspace (project-local `.pnpm`), skip the workaround.
- If it resolves **outside** the workspace (global virtual store), enable the workaround.
3. Keep the existing `fs.existsSync(hoistedDir)` as a secondary guard, but only after confirming the layout is global.
This aligns the workaround with the PR’s intent and avoids altering module resolution in non-GVS pnpm workspaces.

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


8. ESM NODE_PATH fallback broken ⊘ Outdated 🐞 Bug ≡ Correctness
Description
The inlined ESM loader retries resolution by calling createRequire() with each NODE_PATH entry as
the base, but NODE_PATH entries are node_modules directories, so Node will look under
"<basePath>/node_modules/<pkg>" and miss packages located directly in the hoisted dir. This can make
ESM resolution still fail under the global virtual store even though NODE_PATH is set.
Code

scopes/harmony/bit/bootstrap.ts[R125-129]

+    for (const basePath of extraNodePaths) {
+      try {
+        const require = createRequire(pathToFileURL(basePath + '/').href)
+        return { url: pathToFileURL(require.resolve(specifier)).href, shortCircuit: true }
+      } catch {}
Evidence
The bootstrap code sets NODE_PATH to a node_modules directory under .pnpm, but the ESM loader uses
that directory as the base for createRequire(), which changes Node’s search to /node_modules/...
instead of searching directly within the NODE_PATH entry; this defeats the intended fallback.

scopes/harmony/bit/bootstrap.ts[136-149]
scopes/harmony/bit/bootstrap.ts[110-134]

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 ESM loader in `ESM_NODE_PATH_LOADER` is intended to resolve bare specifiers from `NODE_PATH`, but it uses `createRequire(pathToFileURL(basePath + '/'))` where `basePath` is itself a `node_modules` directory (e.g. `<workspace>/node_modules/.pnpm/node_modules`). That makes `require.resolve(specifier)` search `<basePath>/node_modules/<specifier>`, which likely doesn’t exist, so the fallback won’t actually find hoisted packages.
### Issue Context
- `enableHoistedDependencyResolution()` prepends `<workspace>/node_modules/.pnpm/node_modules` to `NODE_PATH`.
- The ESM loader then iterates those `NODE_PATH` entries and tries to resolve from them.
### Fix
Change the loader fallback to resolve *as if* the `NODE_PATH` entry is a module search path.
Two workable approaches:
1) Use `createRequire(import.meta.url)` once, then `require.resolve(specifier, { paths: [basePath] })`.
2) Or, when using `createRequire()`, pass a URL whose directory’s `node_modules` is the `basePath` (e.g. createRequire(pathToFileURL(path.join(basePath, '..', 'noop.js')).href)).
### Fix Focus Areas
- scopes/harmony/bit/bootstrap.ts[110-134]

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


9. ESM loader not propagated ✓ Resolved 🐞 Bug ≡ Correctness
Description
registerEsmNodePathLoader() skips adding its --import flag whenever NODE_OPTIONS contains the
substring "register" (e.g. "--require ts-node/register"), so child processes won't inherit the ESM
fallback loader and ESM resolution via hoisted NODE_PATH can fail under the global virtual store.
Code

scopes/harmony/bit/bootstrap.ts[R185-188]

+  const registration = `import{register}from'node:module';register(${JSON.stringify(loaderUrl)},${JSON.stringify(parentUrl)});`;
+  const importFlag = `--import=data:text/javascript,${encodeURIComponent(registration)}`;
+  if (process.env.NODE_OPTIONS?.includes('register')) return;
+  process.env.NODE_OPTIONS = process.env.NODE_OPTIONS
Evidence
The code builds an --import flag but returns early for any NODE_OPTIONS containing the substring
register, which includes common options unrelated to this loader; this prevents propagating the
loader to child processes.

scopes/harmony/bit/bootstrap.ts[171-191]

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

## Issue description
`registerEsmNodePathLoader()` currently checks `process.env.NODE_OPTIONS?.includes('register')` and returns early. This wrongly treats common existing values like `--require ts-node/register` as if the new loader was already installed, preventing propagation of the loader to spawned Node processes.
### Issue Context
- The current process already calls `module.register(...)` before the `NODE_OPTIONS` check, so the bug mostly impacts child processes.
- The guard should only skip when *this specific* loader (or this specific `--import` flag) is already present.
### Fix Focus Areas
- scopes/harmony/bit/bootstrap.ts[171-191]
### Expected fix
- Replace the broad substring guard with a precise check, e.g.:
- Check for the exact `--import=data:text/javascript,` flag you add (or for `loaderUrl`/a stable marker within it).
- Alternatively, add an explicit environment marker (e.g. `BIT_ESM_NODE_PATH_LOADER=1`) and check that instead.
- Ensure the function appends `importFlag` when `NODE_OPTIONS` contains unrelated `register` occurrences.

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



Remediation recommended

10. Regex .modules.yaml parsing ✓ Resolved 🐞 Bug ☼ Reliability
Description
Global-virtual-store detection reads node_modules/.modules.yaml and extracts virtualStoreDir
with a regex; any valid YAML form the regex doesn’t fully handle (e.g., trailing comments/whitespace
variations) will make Bit treat the layout as project-local and skip the hoisted-resolution bridge
and/or transition guard. This can reintroduce hard-to-debug module resolution failures under the
global virtual store, or reduce the safety of self-hosted transition detection.
Code

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[116]

+  const virtualStoreDir = modulesYaml.match(/^\s*"?virtualStoreDir"?:\s*"?([^"\n]+?)"?,?\s*$/m)?.[1];
Evidence
Both layout-detection call sites use a regex over YAML text to extract virtualStoreDir, while
other new PR code already parses YAML structurally for the lockfile fallback; using the YAML parser
would avoid misclassification due to YAML formatting differences.

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[109-132]
scopes/dependencies/dependency-resolver/dependency-installer.ts[203-220]
scopes/dependencies/dependencies/dependencies.main.runtime.ts[613-621]

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

## Issue description
`virtualStoreDir` is extracted from `node_modules/.modules.yaml` via a regex, which is brittle for a YAML file. When parsing fails or captures extra text, the code falls back to treating the layout as project-local, skipping the hoisted-resolution bridge / transition guard.
## Issue Context
The repo already uses a YAML parser (`yaml`) for similar lockfile-based fallbacks. Reusing it here makes layout detection robust and avoids duplicating ad-hoc parsing in multiple call sites.
## Fix Focus Areas
- scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[109-132]
- scopes/dependencies/dependency-resolver/dependency-installer.ts[203-220]

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


11. Non-directory .pnpm entries ✓ Resolved 🐞 Bug ≡ Correctness
Description
DependenciesMain.readVirtualStoreEntries() treats any non-hidden entry in node_modules/.pnpm
(except node_modules/lock.yaml) as a materialized package copy, even if it’s a file. This can
inflate/garble bit deps diagnose copy counts and can also suppress the lockfile fallback because a
single unexpected file makes entries.length non-zero.
Code

scopes/dependencies/dependencies/dependencies.main.runtime.ts[R613-616]

+  private async readVirtualStoreEntries(virtualStoreDir: string): Promise<string[]> {
+    const entries = (await fs.readdir(virtualStoreDir)).filter(
+      (entry) => !entry.startsWith('.') && entry !== 'node_modules' && entry !== 'lock.yaml'
+    );
Evidence
The production diagnose code filters readdir() results by string name only, while the PR’s updated
e2e helper explicitly uses withFileTypes and isDirectory() to ensure only dependency directories
are counted.

scopes/dependencies/dependencies/dependencies.main.runtime.ts[613-621]
components/legacy/e2e-helper/e2e-fs-helper.ts[62-72]

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

## Issue description
`readVirtualStoreEntries()` uses `fs.readdir()` and filters by name only, so non-directory entries can be treated as package directories and prevent the lockfile fallback from running.
## Issue Context
The new e2e helper (`FsHelper.getVirtualStoreDirNames`) already demonstrates the safer approach: `readdir(..., { withFileTypes: true })` and `entry.isDirectory()`.
## Fix Focus Areas
- scopes/dependencies/dependencies/dependencies.main.runtime.ts[613-621]
- components/legacy/e2e-helper/e2e-fs-helper.ts[62-76]

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


12. Docs contradict capsule behavior ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
Docs and config comments state enableGlobalVirtualStore shares dependency directories across
“every workspace and capsule” and imply a Bit-private default store, but DependencyInstaller
explicitly forces the global virtual store off for capsule installs and pnpm defaults to /links.
This mismatch can mislead users and future maintainers when diagnosing install/perf/disk behavior.
Code

scopes/dependencies/aspect-docs/dependency-resolver/dependency-resolver.mdx[R96-99]

+By default every workspace builds its own copy of the dependency directories under
+`node_modules/.pnpm`. Setting `enableGlobalVirtualStore` moves them into a directory shared by every
+workspace and capsule on the machine, so a dependency subgraph that was already installed once is
+linked rather than re-created. Installs become significantly faster, at the cost of a virtual store
Evidence
The docs/comments claim capsule participation, while the installer enforces
enableGlobalVirtualStore off in capsules; additionally, the pnpm adapter’s default global store
dir is /links, contradicting comments that describe a Bit-private default.

scopes/dependencies/aspect-docs/dependency-resolver/dependency-resolver.mdx[94-113]
components/legacy/constants/constants.ts[363-367]
scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts[143-156]
scopes/dependencies/dependency-resolver/dependency-installer.ts[334-375]
scopes/dependencies/pnpm/pnpm.package-manager.ts[426-445]

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

## Issue description
Documentation and config comments claim the global virtual store is shared across “workspaces and capsules” (and that the default is Bit-private), but the implementation keeps capsules project-local and pnpm defaults to `<storeDir>/links`.
### Issue Context
- Capsule installs are explicitly forced off of the global virtual store.
- pnpm’s `getGlobalVirtualStoreDir()` returns `<storeDir>/links` when not overridden.
### Fix Focus Areas
- scopes/dependencies/aspect-docs/dependency-resolver/dependency-resolver.mdx[94-113]
- components/legacy/constants/constants.ts[363-367]
- scopes/dependencies/dependency-resolver/dependency-resolver-workspace-config.ts[143-156]
- scopes/dependencies/dependency-resolver/package-manager.ts[57-68]
### Expected change
- Update wording to clarify: global virtual store applies to **workspace installs**; **capsules remain project-local** (by design).
- Correct the “default directory” description to match the pnpm implementation (`<storeDir>/links`) or explicitly document the actual default selection logic.

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


View more (5)
13. LockfileOnly writes .pnpm ✓ Resolved 🐞 Bug ≡ Correctness
Description
When enableGlobalVirtualStore is enabled, syncCoreAspectLinksForEnvs() no longer requires
node_modules/.pnpm to exist, so a lockfileOnly install (which can leave node_modules/.pnpm
missing) can still create node_modules/.pnpm/node_modules and write symlinks. This violates
lockfile-only expectations and can accidentally activate the hoisted-resolution bridge by
fabricating the hoisted dir.
Code

scopes/dependencies/dependency-resolver/dependency-linker.ts[R684-687]

+    const underGlobalVirtualStore = Boolean(await this.dependencyResolver.getGlobalVirtualStoreDir(rootDir));
// the hoisted store only exists in a pnpm-managed workspace. anywhere else this directory is on
// no resolution path, so there is nothing to bridge - and it must not be fabricated here.
-    if (!fs.pathExistsSync(hoistedStoreDir)) return;
+    if (!underGlobalVirtualStore && !fs.pathExistsSync(hoistedStoreDir)) return;
Evidence
syncCoreAspectLinksForEnvs() now continues under GVS even if .pnpm is missing, and then calls
createLinks(). createLinkOrSymlink() ensures parent directories exist, so this will create
.pnpm/node_modules. This conflicts with the documented behavior that lockfileOnly installs can
leave .pnpm absent.

scopes/dependencies/dependency-resolver/dependency-linker.ts[670-715]
scopes/dependencies/pnpm/pnpm-prune-modules.ts[35-49]
scopes/toolbox/fs/link-or-symlink/create-link-or-symlink.ts[24-35]
scopes/workspace/install/install.main.runtime.ts[397-468]

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

## Issue description
`syncCoreAspectLinksForEnvs()` can now create `node_modules/.pnpm/node_modules` (and symlinks) even when pnpm did not materialize the project-local virtual store (notably during `lockfileOnly` installs). This breaks the expectation that `lockfileOnly` does not mutate `node_modules` layout.
### Issue Context
- `pnpmPruneModules` explicitly documents that `lockfileOnly` may leave `node_modules/.pnpm` missing.
- `createLinkOrSymlink()` creates destination parent directories, so calling `createLinks()` will fabricate the `.pnpm/node_modules` tree.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-linker.ts[670-721]
- scopes/dependencies/pnpm/pnpm-prune-modules.ts[35-49]
- scopes/toolbox/fs/link-or-symlink/create-link-or-symlink.ts[24-35]
### Suggested fix
- Restore an unconditional existence guard before writing links into the hoisted store:
- If `node_modules/.pnpm` (or at least `node_modules/.pnpm/node_modules`) does not exist, return early even under global virtual store.
- Optionally, add an explicit `lockfileOnly`/"no node_modules materialized" signal into the linking context so any hoisted-store bridging/linking is skipped in that mode.

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


14. Containment equality misclassified ✓ Resolved 🐞 Bug ≡ Correctness
Description
isPathInside() returns false when child === parent, but it’s used to classify whether
virtualStoreDir is inside the workspace. If pnpm’s recorded virtualStoreDir ever resolves
exactly to the workspace root, Bit will misclassify the layout as global and may enable the
bridge/transition guard incorrectly.
Code

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[R101-104]

+export function isPathInside(child: string, parent: string): boolean {
+  const rel = path.relative(parent, child);
+  return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
+}
Evidence
The helper explicitly excludes equality (rel !== ''), while both the layout detection and
transition guard interpret “not inside” as “global/outside workspace”. That makes equality a
misclassification case.

scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[101-129]
scopes/dependencies/dependency-resolver/dependency-installer.ts[203-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
`isPathInside()` currently treats `child === parent` as **not inside** (`rel !== ''`). Callers use it as a containment predicate to decide whether a virtual store path is inside/outside the workspace, so equality should be considered “inside” for those classifications.
### Issue Context
This affects layout classification (`isGlobalVirtualStoreLayout`) and the self-hosted transition guard (`assertSafeVirtualStoreTransition`).
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[101-104]
- scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[106-129]
- scopes/dependencies/dependency-resolver/dependency-installer.ts[203-229]
### Implementation notes
- Either:
- change `isPathInside()` to return true when `rel === ''`, OR
- keep `isPathInside()` strict and introduce a second helper (e.g. `isPathInsideOrEqual`) and use that at the layout/transition call sites.

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


15. Brittle .pnpm directory scan ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new GVS e2e check treats any node_modules/.pnpm entry other than lock.yaml and
node_modules as a “dependency directory”, without excluding dotfiles or verifying entries are
directories. If pnpm ever adds additional non-package entries under .pnpm, the test (and similar
helper logic) can fail even though no dependency directories were created in the workspace.
Code

e2e/harmony/global-virtual-store.e2e.ts[R29-31]

+      const virtualStoreDir = path.join(helper.scopes.localPath, 'node_modules/.pnpm');
+      const dirs = fs.readdirSync(virtualStoreDir).filter((dir) => dir !== 'lock.yaml' && dir !== 'node_modules');
+      expect(dirs).to.deep.eq([]);
Evidence
Both the new GVS e2e test and the new FsHelper helper classify .pnpm contents using a name-only
filter; neither filters dotfiles nor checks directory-ness, so any additional entry under .pnpm
can cause false failures and also suppress FsHelper’s lockfile fallback.

e2e/harmony/global-virtual-store.e2e.ts[28-32]
components/legacy/e2e-helper/e2e-fs-helper.ts[62-72]

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

## Issue description
The new GVS test asserts `.pnpm` contains no dependency directories by listing entries and filtering only by name (`lock.yaml`, `node_modules`). This is brittle: any extra metadata entry (including dotfiles or files) will be misclassified as a dependency directory.
### Issue Context
There is similar logic in `FsHelper.getVirtualStoreDirNames()` which also returns early when *any* other entry exists, preventing its lockfile-based fallback.
### Fix Focus Areas
- e2e/harmony/global-virtual-store.e2e.ts[28-32]
- components/legacy/e2e-helper/e2e-fs-helper.ts[62-72]
### Suggested fix
- Use `readdirSync(dir, { withFileTypes: true })` and:
- ignore dotfiles (`name.startsWith('.')`)
- ignore `lock.yaml` and `node_modules`
- only consider `Dirent.isDirectory()` entries as candidate dependency dirs.
- Consider updating the e2e test to reuse a hardened `helper.fs.getVirtualStoreDirNames()` so the “no dependency dirs” assertion is consistent across layouts.

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


16. Capsule hoisted links written ✓ Resolved 🐞 Bug ☼ Reliability
Description
DependencyLinker.calculateLinkedDeps() now writes core-aspect links into
/node_modules/.pnpm/node_modules based on global-virtual-store config, and this runs for capsule
roots too. This bypasses the capsule invariant (capsules force enableGlobalVirtualStore=false
during install) and can mutate capsule .pnpm layout / resolution unexpectedly.
Code

scopes/dependencies/dependency-resolver/dependency-linker.ts[183]

+    await this.linkCoreAspectsToHoistedStore(rootDir, linkResults);
Evidence
The linker performs hoisted-store linking during calculateLinkedDeps(), and capsule code paths
call calculateLinkedDeps() with inCapsule: true even though capsule installs force
enableGlobalVirtualStore=false, so the new linker behavior can still execute in capsules whenever
the workspace config enables GVS.

scopes/dependencies/dependency-resolver/dependency-linker.ts[147-244]
scopes/component/isolator/isolator.main.runtime.ts[718-732]
scopes/dependencies/dependency-resolver/dependency-installer.ts[334-375]

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

## Issue description
`DependencyLinker.calculateLinkedDeps()` now calls `linkCoreAspectsToHoistedStore()` (a filesystem-writing operation) unconditionally. The decision to run is based on `DependencyResolverMain.getGlobalVirtualStoreDir()`, which is config-driven and does **not** account for capsule context.
This means capsule flows (which deliberately install with `enableGlobalVirtualStore=false`) can still end up getting extra symlinks written into `capsulesDir/node_modules/.pnpm/node_modules`, which is both surprising for a `calculate*` method and risks altering capsule isolation / resolution.
### Issue Context
- Capsules explicitly force `enableGlobalVirtualStore=false` in the installer.
- Capsule setup still calls `calculateLinkedDeps()` with `linkingContext: { inCapsule: true }`.
### Fix Focus Areas
- Guard `linkCoreAspectsToHoistedStore()` so it does not run when `this.linkingContext?.inCapsule` is true (or otherwise key off the *effective* install mode rather than workspace/global config).
- Keep `calculateLinkedDeps()` free of side effects when possible; alternatively, relocate this linking to a post-install step in the workspace install flow where the context is explicit.
- scopes/dependencies/dependency-resolver/dependency-linker.ts[147-244]
- scopes/component/isolator/isolator.main.runtime.ts[718-732]
- scopes/dependencies/dependency-resolver/dependency-installer.ts[334-375]

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


17. Windows layout check misclassifies ✓ Resolved 🐞 Bug ☼ Reliability
Description
assertSafeVirtualStoreTransition() classifies project-local vs global virtual store using a
case-sensitive path prefix check, which can mis-detect on Windows (e.g. drive-letter casing
differences) and incorrectly throw SelfHostedVirtualStoreTransition. The same case-sensitive prefix
logic is also used by isGlobalVirtualStoreLayout(), potentially enabling/disabling the
hoisted-resolution bridge incorrectly on Windows.
Code

scopes/dependencies/dependency-resolver/dependency-installer.ts[R215-218]

+    const workspaceRealpath = await fs.realpath(finalRootDir).catch(() => finalRootDir);
+    const resolvedStoreDir = path.resolve(workspaceRealpath, 'node_modules', virtualStoreDir);
+    const storeRealpath = await fs.realpath(resolvedStoreDir).catch(() => resolvedStoreDir);
+    const currentIsGlobal = !storeRealpath.startsWith(workspaceRealpath + path.sep);
Evidence
The transition guard’s layout classification is implemented via a case-sensitive startsWith()
prefix test; Windows-specific link handling in the repo indicates Windows support and makes this
misclassification impactful. The same prefix-based classification is duplicated in the
hoisted-resolution bridge’s layout detection.

scopes/dependencies/dependency-resolver/dependency-installer.ts[202-229]
scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[89-112]
scopes/toolbox/fs/link-or-symlink/create-link-or-symlink.ts[31-35]

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

## Issue description
`assertSafeVirtualStoreTransition()` (and the related `isGlobalVirtualStoreLayout()`) determine whether a path is inside the workspace using `startsWith(workspaceRealpath + path.sep)`. This comparison is case-sensitive, which can misclassify on Windows and incorrectly block installs (or incorrectly enable the hoisted bridge).
### Issue Context
Windows paths are typically case-insensitive; different casings of the same real path (e.g. `C:\...` vs `c:\...`) can cause `startsWith()` to fail.
### Fix Focus Areas
- scopes/dependencies/dependency-resolver/dependency-installer.ts[210-229]
- scopes/dependencies/dependency-resolver/hoisted-resolution-bridge.ts[89-112]
### Suggested fix
- Replace the `startsWith()` containment check with a platform-safe containment test, e.g.:
- Compute `const rel = path.relative(workspaceRealpath, storeRealpath)` and treat it as “inside” when `rel` is neither absolute nor starts with `..` (and not equal to `''` unless you want to treat equality as inside).
- Or, on win32 only, compare normalized forms (e.g. `toLowerCase()` on both sides) before `startsWith()`.
- Keep the existing `path.sep` boundary guard (or the `path.relative` approach) to avoid prefix collisions (`C:\ws` vs `C:\ws2`).

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


To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment thread scopes/harmony/bit/bootstrap.ts Resolved
…and hoisted linker

- The ESM loader's idempotence check matched any 'register' substring in
  NODE_OPTIONS, so a user's `--require ts-node/register` silently
  suppressed propagating the loader to child processes. Check for the
  exact import flag instead.
- The transition guard resolved the recorded virtualStoreDir against the
  as-given workspace spelling while comparing to the workspace's
  realpath, misreading a project-local store as global for a workspace
  reached through a symlink - and then refusing a legitimate install.
  Both sides now compare as real paths.
- enableGlobalVirtualStore() now reports false under nodeLinker:
  hoisted, matching the engine option the pnpm adapter already forces
  off: the hoisted linker has no virtual store to replace, and the
  store-gated behaviors (core-aspect links, NODE_PATH bootstrap, the
  transition guard) must not run against a store the engine won't use.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread scopes/harmony/bit/bootstrap.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 76dfbc7

With --keep-lane, snapAndExportReusingLane serves every component
unchanged since an earlier export from the lane, carrying artifacts
built from older commits of the branch. The build capsules then mix
generations of @teambit runtime packages, and cross-copy `instanceof`
breaks inside capsule-run specs: a freshly tagged component reports
`{deleted: true}` because ComponentNotFoundInPath thrown by one copy is
not an instance of the class another copy's status loader catches.

On a PR that snaps core components - the only kind whose specs run in
bit_pr at all - this fails deterministically from the second push
onward: the first run on a fresh lane is green, every later run mixes
with it. Verified across eleven runs on two lanes: fresh-lane runs
green, every reused-lane run red with the same three spec failures,
identical content either way.

The temp-lane flow (the default elsewhere) rebuilds each run from one
commit. What it trades away is the lane's persistent history and UI
edits on Bit Cloud between PR commits.

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

Copy link
Copy Markdown

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

…h specifiers in the ESM loader

The layout checks (transition guard, isGlobalVirtualStoreLayout, the
self-hosted detection) compared paths with a case-sensitive startsWith
prefix, which misclassifies on Windows where realpath results and
given spellings can differ in drive-letter casing. Containment now
goes through path.relative - case-insensitive on win32, case-sensitive
on posix, and immune to prefix collisions (C:\ws vs C:\ws2) - via a
shared isPathInside helper.

The ESM loader's bare-specifier gate treated Windows drive-letter and
UNC paths as bare, sending genuine path specifiers into the NODE_PATH
fallback. The gate now recognizes both; verified against the emitted
loader source (including the double-escaping through the template
literal, which the first attempt got one level wrong - caught by
decoding and executing the generated module).

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

Copy link
Copy Markdown

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

…t of capsules

linkCoreAspectsToHoistedStore gated on the global-virtual-store config
alone, so capsule link flows in a store-enabled workspace wrote the
bridge links into capsule hoist directories - capsules deliberately
stay project-local (the installer re-asserts that invariant) and reach
the core aspects by walking up to the capsule root. Gate on the
linking context like the installer does.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread e2e/harmony/node-linker.e2e.ts Resolved
Comment thread e2e/harmony/global-virtual-store.e2e.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 29e1573

…ks root

The isolated-nodeLinker assertion still named bit-links, the private
root Bit carved out before adopting pnpm's shared <storeDir>/links -
under the global virtual store the resolved path matches neither
alternative. And the .pnpm scans (the GVS test and the e2e fs helper)
classified any unrecognized entry as a dependency directory, so a
future pnpm metadata file would fail the test and suppress the
helper's lockfile fallback. Filter to real non-dot directories.

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1019a6d

… a stale jsdoc

isPathInside answered 'does this path escape that root' at every call
site, yet returned false for a path equal to the root - the degenerate
store-dir-equals-workspace case would have read as the global layout.
Renamed to isPathInsideOrEqual with equality included. Also rewrote
the getGlobalVirtualStoreDir jsdoc, which still described the
abandoned private-store-root design and a method that no longer
exists.

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

Copy link
Copy Markdown

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

…t-aware traversal check

The hoisted-store writers skipped the .pnpm existence guard under the
global virtual store, so a lockfile-only install - which leaves the
directory missing on purpose - could fabricate .pnpm/node_modules just
to hold the core-aspect links. Both writers now bridge only a store
pnpm actually materialized; every real install materializes it under
both layouts before the linking runs. Also: isPathInsideOrEqual read a
child named ..foo as traversal (component-aware check now, with a
spec), and linkCoreAspectsToHoistedStore's jsdoc still referenced a
renamed method and a NODE_PATH-only caveat the ESM loader has since
resolved.

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

Copy link
Copy Markdown

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

…tore root is pnpm's links

The user-facing docs and config comments still described the earlier
design: a store shared by 'workspaces and capsules' (capsule installs
force the project-local layout) and a default root private to the bit
installation (it is pnpm's shared <storeDir>/links now).

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5b90d4c

… directories as copies

Current pnpm writes the modules manifest as JSON, so the recorded
virtualStoreDir is now read with JSON.parse and the line match is kept
only for the block-YAML older versions wrote. The reader is shared
with the transition guard, which had its own copy of the pattern - the
guard and the bootstrap-time bridge can no longer disagree about the
current layout.

Separately, 'bit deps diagnose' counted any non-hidden .pnpm entry as
a materialized copy, so a stray file would garble the counts and
suppress the lockfile fallback the global virtual store relies on.

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 188422c

patchedDependencies paths are configured relative to the workspace
root, but pnpm resolves a relative one from the directory it installs
in - the capsules root for a capsule install. Any workspace using a
patch therefore installed fine and failed to build: 'Failed to read
patch file <capsulesDir>/patches/....patch'. Capsule installs now get
paths resolved against the workspace root the caller already passes as
the package manager config root; workspace installs keep the
configured spelling, which pnpm records in the lockfile and which must
stay machine-independent there.

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

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 13c3061

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants