Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: provision worktree node_modules so workspace links resolve inside the worktree (#12633)
[._.]/ Adam Eivy5691889f11c9
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 119548d168..ece107bcef 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -351,6 +351,32 @@ use the workspace binaries from the primary checkout`dependency-updates` scheduled task is the exception: its managed worktree getsno dependency symlinks, and any package-manager install stays in that worktree.+### Worktree Tests Fail on a Clean Tree in a Workspace-Link Repo (Stale Workspace Packages)++**Symptom**: In a managed repo that uses npm workspaces (`node_modules/@scope/pkg+-> ../../packages/pkg`), a fresh CoS or claim worktree fails tests that import a+workspace package — a `TypeError` on a field the branch just added, or a path+assertion naming the primary checkout — even though the branch is untouched.++**Cause**: a plain `worktree/node_modules -> primary/node_modules` symlink+resolves the workspace links against the PRIMARY checkout. When the primary's+checked-out branch is behind the worktree's base, `require('@scope/pkg')` loads+the primary's stale `packages/pkg`. The branch is fine; the environment is not.++**Fix**: `scripts/link-worktree-deps.js` (and `worktreeManager`'s dependency+linking) now detects workspace links in the source's `node_modules` and builds a+REAL `node_modules` directory in the worktree. Every entry is symlinked to the+primary except the workspace links, which are recreated with the same relative+targets so they resolve inside the worktree. Provisioning refuses a link that+would resolve outside the worktree (`server/lib/worktreeNodeModules.js`). The+directory carries a `.portos-worktree-links` marker so cleanup removes only what+it created.++**Existing worktrees** keep whatever they were given (provisioning never replaces+an existing path). To repair one, delete the `node_modules` symlink in the+worktree and rerun `node scripts/link-worktree-deps.js <primary> <worktree>`.+Still never run `npm install` in a worktree.+### Tasks Not Being Picked Up**Symptom**: Added tasks to TASKS.md but CoS ignores them.diff --git a/scripts/link-worktree-deps.test.js b/scripts/link-worktree-deps.test.jsindex bc32187e91..98a06466f3 100644--- a/scripts/link-worktree-deps.test.js+++ b/scripts/link-worktree-deps.test.js@@ -1,6 +1,6 @@import { describe, it, expect, afterEach } from 'vitest';import { spawnSync } from 'child_process';-import { lstatSync, mkdirSync, mkdtempSync, readlinkSync, rmSync, writeFileSync } from 'fs';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { dirname, join } from 'path';import { fileURLToPath } from 'url';@@ -39,6 +39,41 @@ describe('link-worktree-deps script', () => {expect(lstatSync(join(source, 'node_modules')).isSymbolicLink()).toBe(false);});+ it('resolves workspace links inside the worktree, not the source checkout (#12633)', () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'portos-link-worktree-deps-')));+ const source = join(root, 'source');+ const worktree = join(root, 'worktree');+ // Source install: a registry package, a workspace scope next to a registry scope entry, a bin shim.+ const modules = join(source, 'node_modules');+ mkdirSync(join(modules, 'left-pad'), { recursive: true });+ mkdirSync(join(modules, '@acme'), { recursive: true });+ mkdirSync(join(modules, '@types', 'node'), { recursive: true });+ mkdirSync(join(modules, '.bin'), { recursive: true });+ mkdirSync(join(source, 'packages', 'core'), { recursive: true });+ mkdirSync(join(worktree, 'packages', 'core'), { recursive: true });+ writeFileSync(join(source, 'packages', 'core', 'marker.txt'), 'stale');+ writeFileSync(join(worktree, 'packages', 'core', 'marker.txt'), 'fresh');+ symlinkSync('../../packages/core', join(modules, '@acme', 'core'), 'dir');+ symlinkSync('../left-pad', join(modules, '.bin', 'left-pad'), 'dir');++ const result = runScript(source, worktree);++ expect(result.status).toBe(0);+ const linked = join(worktree, 'node_modules');+ expect(lstatSync(linked).isSymbolicLink()).toBe(false);+ expect(readlinkSync(join(linked, '@acme', 'core'))).toBe('../../packages/core');+ expect(readFileSync(join(linked, '@acme', 'core', 'marker.txt'), 'utf8')).toBe('fresh');+ expect(realpathSync(join(linked, '@acme', 'core')).startsWith(worktree)).toBe(true);+ // Everything that is not a workspace link still shares the source's install.+ expect(realpathSync(join(linked, 'left-pad'))).toBe(join(modules, 'left-pad'));+ expect(realpathSync(join(linked, '@types'))).toBe(join(modules, '@types'));+ expect(existsSync(join(linked, '.bin', 'left-pad'))).toBe(true);++ // Already provisioned: a rerun leaves the directory exactly as it was.+ expect(runScript(source, worktree).status).toBe(0);+ expect(readFileSync(join(linked, '@acme', 'core', 'marker.txt'), 'utf8')).toBe('fresh');+ });+it('exits non-zero without both paths', () => {const result = runScript('/only-one-path');expect(result.status).toBe(1);diff --git a/server/lib/README.md b/server/lib/README.mdindex 26895adff7..053e306c8a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -559,6 +559,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `taskTargetScope.js` | Target scope for a scheduled task type: `INSTALL_WIDE_TASK_TYPES`, `MANAGED_APP_TARGET_TASK_TYPES`, `PROGRAMMATIC_SCHEDULED_TASK_TYPES`, `isProgrammaticScheduledTaskType`, `requiresManagedAppTarget`, `requiresInstallWideTarget`. Declared here (not in `services/taskScheduleRegistry.js`, which re-exports it) so `quotaBurnValidation.js` can reject a burn reference with the wrong target scope without importing upward into services. || `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. || `appPromptPlaceholders.js` | `applyAppPlaceholders(text, app)` — expand `{appName}` / `{repoPath}` / `{appId}` / `{appSlug}` in a CoS prompt template. The ONE owner of that chain: four renderers (`cosTaskGenerator.js`'s claim-work router and JIRA per-ticket builder, `cosTaskPreStepBlocks.js`'s scheduled builder, `referenceRepos.js`) each used to spell it themselves and drifted. Function-form replacers throughout, since a name/path/id is free text a `$` can appear in. Callers expand their own injected blocks (`{trackerInstructions}`, `{modeInstructions}`) FIRST — those blocks carry app placeholders of their own. Pure. |+| `worktreeNodeModules.js` | Workspace-aware `node_modules` provisioning for a worktree (#12633). `provisionWorkspaceNodeModules(sourceRoot, worktreeRoot)` builds a real `node_modules` directory when the source's holds workspace links (`@scope/pkg -> ../../packages/pkg`): every entry is symlinked back to the source except those links, which are recreated so they resolve INSIDE the worktree (a plain directory symlink resolves them against the source checkout, so a worktree ahead of the source's branch silently tests stale workspace code). Returns `false` and creates nothing when there are no workspace links. `assertLinkWithinWorktree` is the containment guard run on every recreated link; `removeProvisionedNodeModules` undoes the farm and only touches a directory carrying `WORKTREE_NODE_MODULES_MARKER`, so a real `npm install` is never mistaken for it. Consumed by `services/worktreeManager.js#linkWorktreeDependencies`. || `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies root, agent-id, lock, active-agent, liveness and claim policies IN THAT ORDER, so an unconditional hold always outranks a claim and callers never re-derive the precedence from the slug; the claim hold has two opt-outs (`allowStaleClaim` for reapers, `allowLiveClaim` for the dispatch side). `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit; `worktreeHoldExpiresAt()` names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. `appWorktreeSlug(app)` is the per-app segment (`<name-slug>-<8 id chars>`) that claim prompts render INSIDE the `claim-` prefix — `data/cos/worktrees/` is one directory shared by every managed app, so a work-item-only name collides whenever two apps carry the same issue number or PLAN slug. || `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |diff --git a/server/lib/index.js b/server/lib/index.jsindex a94efec2cf..037a6a44df 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -505,6 +505,7 @@ export * from './scheduleRunOrder.js';export * from './taskReadinessReasons.js';export * from './taskTargetScope.js';export * from './taxonomyTally.js';+export * from './worktreeNodeModules.js';export * from './worktreeOwnership.js';export * from './xmlEntities.js';diff --git a/server/lib/worktreeNodeModules.js b/server/lib/worktreeNodeModules.jsnew file mode 100644index 0000000000..09bf957918--- /dev/null+++ b/server/lib/worktreeNodeModules.js@@ -0,0 +1,159 @@+/**+ * Workspace-aware `node_modules` provisioning for a worktree (#12633).+ *+ * A plain `worktree/node_modules -> source/node_modules` symlink resolves the+ * install's workspace links (`@scope/pkg -> ../../packages/pkg`) against the+ * SOURCE checkout, so a worktree whose base is ahead of the source's checked-out+ * branch silently runs the source's stale workspace packages. When the source+ * has such links, the worktree gets a real `node_modules` directory instead:+ * every entry is symlinked back to the source except the workspace links, which+ * are recreated with the same targets so they resolve inside the worktree.+ */++import { mkdir, readdir, readlink, rm, rmdir, symlink, unlink, writeFile } from 'fs/promises';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'path';++// Marks a directory this module built, so cleanup never mistakes a real+// `npm install` (whose workspace links look identical) for provisioned links.+export const WORKTREE_NODE_MODULES_MARKER = '.portos-worktree-links';++const isInside = (parent, child) => {+ const rel = relative(parent, child);+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));+};++// `@scope` directories and `.bin` hold links one level down; other package+// directories are opaque (their own contents are never inspected).+const isLinkContainer = (entry) => entry.isDirectory() && (entry.name.startsWith('@') || entry.name === '.bin');++const resolveLink = async (linkPath) => resolve(dirname(linkPath), await readlink(linkPath));++// A workspace link points into the source checkout but outside its node_modules.+async function readWorkspaceLink(sourceRoot, sourceModules, linkPath) {+ const target = await readlink(linkPath);+ const resolved = resolve(dirname(linkPath), target);+ if (!isInside(sourceRoot, resolved) || isInside(sourceModules, resolved)) return null;+ return { target, resolved };+}++async function planChild(sourceRoot, sourceModules, directory, entry) {+ const workspace = entry.isSymbolicLink()+ ? await readWorkspaceLink(sourceRoot, sourceModules, join(directory, entry.name))+ : null;+ return { name: entry.name, workspace, type: entry.isDirectory() ? 'dir' : 'file' };+}++async function planEntry(sourceRoot, sourceModules, entry) {+ const path = join(sourceModules, entry.name);+ if (entry.isSymbolicLink()) return planChild(sourceRoot, sourceModules, sourceModules, entry);+ if (!isLinkContainer(entry)) return { name: entry.name, workspace: null, type: entry.isDirectory() ? 'dir' : 'file' };+ const children = await readdir(path, { withFileTypes: true });+ return {+ name: entry.name,+ workspace: null,+ type: 'dir',+ children: await Promise.all(children.map(child => planChild(sourceRoot, sourceModules, path, child))),+ };+}++const hasWorkspaceLink = (planned) => !!planned.workspace || !!planned.children?.some(child => child.workspace);++// Recreate a workspace link under the worktree: a relative target is kept+// verbatim (it already resolves from the new location), an absolute one inside+// the source checkout is rebased onto the worktree.+function workspaceLinkTarget(sourceRoot, worktreeRoot, { target, resolved }) {+ return isAbsolute(target) ? join(worktreeRoot, relative(sourceRoot, resolved)) : target;+}++/**+ * Fail when a provisioned link would land outside the worktree. Resolves+ * lexically (no realpath) so a workspace package the branch deleted still+ * passes while a link escaping to the source checkout does not.+ */+export async function assertLinkWithinWorktree(worktreeRoot, linkPath) {+ const resolved = await resolveLink(linkPath);+ if (!isInside(worktreeRoot, resolved)) {+ throw new Error(`Workspace link ${linkPath} resolves outside the worktree (${resolved})`);+ }+}++async function createLinks(sourceRoot, worktreeRoot, sourceModules, destModules, plan) {+ const workspaceLinks = [];+ const linkEntry = async (directoryInSource, directoryInDest, planned) => {+ const destPath = join(directoryInDest, planned.name);+ if (planned.workspace) {+ await symlink(workspaceLinkTarget(sourceRoot, worktreeRoot, planned.workspace), destPath, planned.type);+ workspaceLinks.push(destPath);+ return;+ }+ await symlink(join(directoryInSource, planned.name), destPath, planned.type);+ };++ await mkdir(destModules, { recursive: true });+ await writeFile(join(destModules, WORKTREE_NODE_MODULES_MARKER), '');+ await Promise.all(plan.map(async (planned) => {+ if (!planned.children || !hasWorkspaceLink(planned)) return linkEntry(sourceModules, destModules, planned);+ const sourceDirectory = join(sourceModules, planned.name);+ const destDirectory = join(destModules, planned.name);+ await mkdir(destDirectory);+ await Promise.all(planned.children.map(child => linkEntry(sourceDirectory, destDirectory, child)));+ }));+ await Promise.all(workspaceLinks.map(linkPath => assertLinkWithinWorktree(worktreeRoot, linkPath)));+}++/**+ * Provision `<worktree>/node_modules` as a real directory whose workspace links+ * resolve inside the worktree. Returns false, creating nothing, when the source+ * has no workspace links — the caller then uses the plain directory symlink.+ */+export async function provisionWorkspaceNodeModules(sourceRoot, worktreeRoot) {+ const sourceModules = join(sourceRoot, 'node_modules');+ const destModules = join(worktreeRoot, 'node_modules');+ const entries = await readdir(sourceModules, { withFileTypes: true }).catch(() => []);+ const plan = await Promise.all(entries.map(entry => planEntry(sourceRoot, sourceModules, entry)));+ if (!plan.some(hasWorkspaceLink)) return false;++ await createLinks(sourceRoot, worktreeRoot, sourceModules, destModules, plan).catch(async (err) => {+ // A half-built directory would read as "already provisioned" to the next run.+ await rm(destModules, { recursive: true, force: true });+ throw err;+ });+ return true;+}++const ignoreCodes = (...codes) => (err) => {+ if (codes.includes(err.code)) return null;+ throw err;+};++/**+ * Undo `provisionWorkspaceNodeModules`: drop the links it created (into the+ * source's node_modules, or workspace links within the worktree) and the+ * directory itself once empty. A directory without the marker, and any real+ * package inside one, is left alone.+ */+export async function removeProvisionedNodeModules(sourceRoot, worktreeRoot) {+ const sourceModules = join(sourceRoot, 'node_modules');+ const destModules = join(worktreeRoot, 'node_modules');+ const entries = await readdir(destModules, { withFileTypes: true }).catch(ignoreCodes('ENOENT', 'ENOTDIR'));+ if (!entries?.some(entry => entry.name === WORKTREE_NODE_MODULES_MARKER)) return;++ const owned = async (linkPath) => {+ const resolved = await resolveLink(linkPath);+ return isInside(sourceModules, resolved) || (isInside(worktreeRoot, resolved) && !isInside(destModules, resolved));+ };+ const removeOwnedLink = async (path) => {+ if (await owned(path)) await unlink(path);+ };++ await Promise.all(entries.map(async (entry) => {+ const path = join(destModules, entry.name);+ if (entry.isSymbolicLink()) return removeOwnedLink(path);+ if (!isLinkContainer(entry)) return;+ const children = await readdir(path, { withFileTypes: true });+ await Promise.all(children.filter(child => child.isSymbolicLink()).map(child => removeOwnedLink(join(path, child.name))));+ await rmdir(path).catch(ignoreCodes('ENOTEMPTY', 'EEXIST'));+ }));+ await unlink(join(destModules, WORKTREE_NODE_MODULES_MARKER));+ await rmdir(destModules).catch(ignoreCodes('ENOTEMPTY', 'EEXIST'));+}diff --git a/server/lib/worktreeNodeModules.test.js b/server/lib/worktreeNodeModules.test.jsnew file mode 100644index 0000000000..6b26ec3071--- /dev/null+++ b/server/lib/worktreeNodeModules.test.js@@ -0,0 +1,68 @@+import { afterEach, describe, expect, it } from 'vitest';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import {+ assertLinkWithinWorktree,+ provisionWorkspaceNodeModules,+ removeProvisionedNodeModules,+} from './worktreeNodeModules.js';++let root;+afterEach(() => {+ if (root) rmSync(root, { recursive: true, force: true });+ root = undefined;+});++function fixture() {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'portos-worktree-nm-')));+ const source = join(root, 'source');+ const worktree = join(root, 'worktree');+ mkdirSync(join(source, 'node_modules', 'left-pad'), { recursive: true });+ mkdirSync(join(source, 'node_modules', '@acme'), { recursive: true });+ mkdirSync(join(source, 'packages', 'core'), { recursive: true });+ mkdirSync(join(worktree, 'packages', 'core'), { recursive: true });+ symlinkSync('../../packages/core', join(source, 'node_modules', '@acme', 'core'), 'dir');+ return { source, worktree };+}++describe('worktree node_modules provisioning', () => {+ it('creates nothing when the source has no workspace links', async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'portos-worktree-nm-')));+ mkdirSync(join(root, 'source', 'node_modules', 'left-pad'), { recursive: true });+ mkdirSync(join(root, 'worktree'));+ expect(await provisionWorkspaceNodeModules(join(root, 'source'), join(root, 'worktree'))).toBe(false);+ expect(existsSync(join(root, 'worktree', 'node_modules'))).toBe(false);+ });++ it('rejects a link that resolves outside the worktree', async () => {+ const { source, worktree } = fixture();+ mkdirSync(join(worktree, 'node_modules'));+ symlinkSync(join(source, 'packages', 'core'), join(worktree, 'node_modules', 'escaped'), 'dir');+ await expect(assertLinkWithinWorktree(worktree, join(worktree, 'node_modules', 'escaped'))).rejects.toThrow('outside the worktree');+ });++ it('removes only a provisioned directory, leaving a real install untouched', async () => {+ const { source, worktree } = fixture();+ expect(await provisionWorkspaceNodeModules(source, worktree)).toBe(true);+ await removeProvisionedNodeModules(source, worktree);+ expect(existsSync(join(worktree, 'node_modules'))).toBe(false);+ expect(existsSync(join(source, 'node_modules', '@acme', 'core'))).toBe(true);++ // An npm-installed tree has the same workspace links but no marker.+ mkdirSync(join(worktree, 'node_modules', '@acme'), { recursive: true });+ symlinkSync('../../packages/core', join(worktree, 'node_modules', '@acme', 'core'), 'dir');+ await removeProvisionedNodeModules(source, worktree);+ expect(lstatSync(join(worktree, 'node_modules', '@acme', 'core')).isSymbolicLink()).toBe(true);+ });++ it('keeps real packages added to a provisioned directory when it is removed', async () => {+ const { source, worktree } = fixture();+ await provisionWorkspaceNodeModules(source, worktree);+ rmSync(join(worktree, 'node_modules', 'left-pad'));+ mkdirSync(join(worktree, 'node_modules', 'left-pad'));+ writeFileSync(join(worktree, 'node_modules', 'left-pad', 'index.js'), '');+ await removeProvisionedNodeModules(source, worktree);+ expect(readdirSync(join(worktree, 'node_modules'))).toEqual(['left-pad']);+ });+});diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 4bf90fb6a9..240de62cd8 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -25,6 +25,7 @@ import { forkRemoteName, normalizeForkHead, forkLocalBranch } from '../lib/forkHimport { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';import { ensureInstanceId } from './instanceIdentity.js';import { preserveBranchRetirement } from '../lib/branchRetirementArchive.js';+import { provisionWorkspaceNodeModules, removeProvisionedNodeModules } from '../lib/worktreeNodeModules.js';export { isHumanClaimWorktree } from '../lib/worktreeOwnership.js';@@ -70,6 +71,8 @@ async function worktreeDependencyPaths(sourceWorkspace, worktreePath, { cleanup* or reinstalling them. Missing source directories are skipped so this also* works for managed repositories that do not use PortOS's client/server* layout. Existing paths are preserved, including real directories and links.+ * A root node_modules holding workspace links is rebuilt as a real directory+ * so those links resolve inside the worktree, not the source (#12633).*/export async function linkWorktreeDependencies(sourceWorkspace, worktreePath) {const dependencyPaths = await worktreeDependencyPaths(sourceWorkspace, worktreePath);@@ -80,13 +83,15 @@ export async function linkWorktreeDependencies(sourceWorkspace, worktreePath) {if (!sourceExists) return;const targetExists = await lstat(targetPath).then(() => true).catch(() => false);if (targetExists) return;+ if (relativePath === 'node_modules' && await provisionWorkspaceNodeModules(sourceWorkspace, worktreePath)) return;await symlink(sourcePath, targetPath, 'dir');}));}/**- * Remove only dependency symlinks that point back into the source checkout.- * Real dependency directories and links managed by another tool stay intact.+ * Remove only dependency symlinks that point back into the source checkout,+ * plus a root node_modules this module provisioned as a link farm. Real+ * dependency directories and links managed by another tool stay intact.*/export async function unlinkWorktreeDependencies(sourceWorkspace, worktreePath) {const dependencyPaths = await worktreeDependencyPaths(sourceWorkspace, worktreePath, { cleanup: true });@@ -97,7 +102,11 @@ export async function unlinkWorktreeDependencies(sourceWorkspace, worktreePath)if (err.code === 'ENOENT') return null;throw err;});- if (!targetStat?.isSymbolicLink()) return;+ if (!targetStat) return;+ if (!targetStat.isSymbolicLink()) {+ if (relativePath === 'node_modules') await removeProvisionedNodeModules(sourceWorkspace, worktreePath);+ return;+ }const linkTarget = await readlink(targetPath);const linkedPath = isAbsolute(linkTarget) ? linkTarget : resolve(dirname(targetPath), linkTarget);diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 6d5e10ea9f..f2ad8447f3 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -31,6 +31,9 @@ vi.mock('fs/promises', () => ({readlink: vi.fn().mockResolvedValue(''),symlink: vi.fn().mockResolvedValue(undefined),unlink: vi.fn().mockResolvedValue(undefined),+ // lib/worktreeNodeModules.js (workspace-link farm); its behavior has a real-filesystem suite.+ rmdir: vi.fn().mockResolvedValue(undefined),+ writeFile: vi.fn().mockResolvedValue(undefined),// adoptWorktree ensures the worktrees root exists before moving a tree into it.mkdir: vi.fn().mockResolvedValue(undefined),}));@@ -149,7 +152,8 @@ describe('Worktree dependency preparation', () => {symlink.mockClear();unlink.mockClear();existsSync.mockImplementation(path => normalize(path) === '/repo/nested/.git');- readdir.mockResolvedValue([+ // The source's node_modules holds no workspace links, so the plain directory symlink applies.+ readdir.mockImplementation(async path => normalize(path).endsWith('/repo/node_modules') ? [] : [...directories.map(name => ({ name, isDirectory: () => true })),{ name: 'linked-package', isDirectory: () => false },]);