Skip to content

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

fix: isolate dependency update worktree installs

[._.]/ Adam Eivy42f7c5326716
diff --git a/AGENTS.md b/AGENTS.md
index 657dcd4f57..d5a64a9180 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -94,7 +94,7 @@ The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on
**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, local curl/scripts hit the loopback-only HTTP mirror on `:5553` to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (re-exported at `server/lib/ports.js`). Guide and diagram: `docs/PORTS.md`.
-**Never run `npm ci` or `npm install` from inside a CoS worktree (`data/cos/worktrees/*`).** Worktrees get the primary checkout's `node_modules` (root, `client/`, `server/`) by symlink; npm follows the symlink and empties the PRIMARY checkout's real `node_modules`, which takes every agent spawn down with `posix_spawn failed: No such file or directory` until someone reinstalls. If a worktree is missing dependencies, symlink them from the primary checkout and call the workspace binaries directly (`server/node_modules/.bin/vitest run <files>`) — never install. Recovery and mechanism: `docs/TROUBLESHOOTING.md` ("Every Agent Spawn Fails…"); the runner names the fault in `server/lib/ptySpawnDiagnostics.js`.
+**Never run `npm ci` or `npm install` from inside an ordinary CoS worktree (`data/cos/worktrees/*`).** Ordinary worktrees get the primary checkout's `node_modules` (root, `client/`, `server/`) by symlink; npm follows the symlink and empties the PRIMARY checkout's real `node_modules`, which takes every agent spawn down with `posix_spawn failed: No such file or directory` until someone reinstalls. If an ordinary worktree is missing dependencies, use the linked workspace binaries directly (`server/node_modules/.bin/vitest run <files>`) — never install. **The `dependency-updates` scheduled task is the exception:** its CoS-managed worktree receives no dependency symlinks, so package-manager installs and updates stay inside that worktree. Do not use the source checkout's dependency paths for that task. Recovery and mechanism: `docs/TROUBLESHOOTING.md` ("Every Agent Spawn Fails…"); the runner names this fault in `server/lib/ptySpawnDiagnostics.js`.
**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug. See `docs/BACKUP.md` for the `overridable` tiers and `computeEffectiveExcludes()`.
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 7d96794401..ed8c31facb 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -262,9 +262,11 @@ npm install --prefix client
pm2 restart portos-cos
```
-**Prevention**: if a worktree is missing dependencies, symlink them from the
-primary checkout and call the workspace binaries directly
-(`server/node_modules/.bin/vitest run <files>`) — never install.
+**Prevention**: ordinary CoS worktrees share dependencies through symlinks, so
+use the workspace binaries from the primary checkout
+(`server/node_modules/.bin/vitest run <files>`) and never install there. The
+`dependency-updates` scheduled task is the exception: its managed worktree gets
+no dependency symlinks, and any package-manager install stays in that worktree.
### Tasks Not Being Picked Up
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index e3ff6c2fe6..b40c179099 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -35,7 +35,7 @@ import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import * as git from './git.js';
import { detectConflicts } from './taskConflict.js';
-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, releaseIdleSiblingNextHolder } from './worktreeManager.js';
+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';
import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
@@ -43,7 +43,7 @@ import { resolveTaskForkHead } from '../lib/forkHead.js';
import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';
import { createJiraTicketForTask } from './promptSections/appContext.js';
import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';
-import { isNonCommittingCoordinatorTask } from './taskTypeHooks.js';
+import { isNonCommittingCoordinatorTask, resolveTaskHookType } from './taskTypeHooks.js';
import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
const ROOT_DIR = PATHS.root;
@@ -159,6 +159,7 @@ async function prepareRequestedWorktree({
forkHead,
allowSharedWorkspaceFallback,
}) {
+ const isolateDependencies = resolveTaskHookType(task) === 'dependency-updates';
// Detecting the base branch and resolving the branch holder are independent
// reads (a git-branches lookup vs. an agent-liveness + worktree-list check) —
// kick both off before awaiting either so their I/O overlaps instead of
@@ -218,7 +219,8 @@ async function prepareRequestedWorktree({
// `origin/<branch>` to attach to (#6064). Null for every other task, which
// is the behavior that predates it.
forkHead: forkHead || undefined,
- planId: task.metadata?.planId || undefined
+ planId: task.metadata?.planId || undefined,
+ linkDependencies: !isolateDependencies,
}).catch(err => {
worktreeError = err;
emitLog('warn', `🌳 Worktree creation failed for task ${task.id}: ${err.message}`, { taskId: task.id });
@@ -227,6 +229,11 @@ async function prepareRequestedWorktree({
if (worktreeInfo) {
const nextWorkspacePath = worktreeInfo.worktreePath;
+ // An adopted tree may predate the dependency-update opt-out. Detach only
+ // the source-checkout links; preserve a real install already in the tree.
+ if (isolateDependencies && takeover?.worktreeInfo) {
+ await unlinkWorktreeDependencies(workspacePath, nextWorkspacePath);
+ }
const origin = worktreeInfo.adopted
? `adopted from ${takeover?.adoptedFrom || task.metadata?.resumedFromAgentId || 'the interrupted run'}`
: `base: ${worktreeInfo.baseBranch}`;
@@ -575,7 +582,8 @@ export async function prepareAgentWorkspace({ agentId, task }) {
});
worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {
- planId: task.metadata?.planId || undefined
+ planId: task.metadata?.planId || undefined,
+ linkDependencies: resolveTaskHookType(task) !== 'dependency-updates',
}).catch(err => {
emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
return null;
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index c4944225f1..bd58668347 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -44,6 +44,7 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({
...(await importOriginal()),
createWorktree: vi.fn(),
adoptWorktree: vi.fn(),
+ unlinkWorktreeDependencies: vi.fn().mockResolvedValue(undefined),
findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),
releaseIdleSiblingNextHolder: vi.fn().mockResolvedValue(null),
mergeBaseIntoFeatureWorktree: vi.fn(),
@@ -70,7 +71,7 @@ import { ensureLatest } from './git.js';
import { execGit } from '../lib/execGit.js';
import { detectConflicts } from './taskConflict.js';
import { getAppWorkspace } from './agentAppWorkspace.js';
-import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, releaseIdleSiblingNextHolder } from './worktreeManager.js';
+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
@@ -176,6 +177,25 @@ describe('prepareAgentWorkspace', () => {
expect(detectConflicts).not.toHaveBeenCalled();
});
+ it('does not link source dependencies into dependency-update worktrees', async () => {
+ createWorktree.mockResolvedValue({
+ worktreePath: '/mock/worktrees/agent-deps',
+ branchName: 'cos/t-deps/agent-deps',
+ baseBranch: 'main',
+ });
+ const task = {
+ id: 't-deps', taskType: 'internal',
+ metadata: { analysisType: 'dependency-updates', useWorktree: true },
+ };
+
+ const r = await prepareAgentWorkspace({ agentId: 'agent-deps', task });
+
+ expect(r.outcome).toBe('ready');
+ expect(createWorktree).toHaveBeenCalledWith('agent-deps', expect.any(String), 't-deps', expect.objectContaining({
+ linkDependencies: false,
+ }));
+ });
+
it('blocks a read-only task when its required worktree cannot be created', async () => {
createWorktree.mockResolvedValue(null);
const task = {
@@ -343,9 +363,12 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {
baseBranch: null, existingBranch: true, adopted: true
});
- const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: resumeTask() });
+ const r = await prepareAgentWorkspace({
+ agentId: 'agent-new', task: resumeTask({ analysisType: 'dependency-updates' }),
+ });
expect(adoptWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), DEAD_TREE, 'cos/t-resume/agent-dead');
+ expect(unlinkWorktreeDependencies).toHaveBeenCalledWith(expect.any(String), '/mock/worktrees/agent-new');
expect(createWorktree).not.toHaveBeenCalled();
expect(r.outcome).toBe('ready');
expect(r.worktreeInfo.adopted).toBe(true);
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 6c14b211ec..5b61da296f 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -385,6 +385,13 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(PROMPT_VERSIONS['dependency-updates']).toBeGreaterThanOrEqual(5);
});
+ it('keeps dependency installs inside scheduled worktrees', () => {
+ const current = DEFAULT_TASK_PROMPTS['dependency-updates'];
+ expect(current).toContain('intentionally private to that worktree');
+ expect(current).toContain('isolated from the source checkout');
+ expect(PROMPT_VERSIONS['dependency-updates']).toBeGreaterThanOrEqual(7);
+ });
+
// NOTE: PROMPT_VERSIONS keys are SCHEDULE keys, not always prompt keys —
// code-reviewer-a/b version a pipeline whose stages use the
// code-reviewer-review / code-reviewer-implement prompt bodies — so there is
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index a381b521a0..fac4dc5750 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -21,7 +21,7 @@
"cost-efficiency": "239bad18c51b50c80599d30b2fb0ad15",
"data-integrity": "5fcc4f5044101e89da5bbf4890c11a1c",
"data-safety": "eb97988dfc16d4c655f1834acc91d665",
- "dependency-updates": "44de787b45e037fbce281efc87706873",
+ "dependency-updates": "2d94021c979a86a349e125f5c15665d8",
"do-replan": "35660eb7b43e4259a6a9253ed288a1db",
"documentation": "a30e3bfba8cd13369ccaf806a3534a79",
"error-handling": "137b371f38398042c0a2c7e2279c92ce",
@@ -80,7 +80,7 @@
"cost-efficiency": 1,
"data-integrity": 1,
"data-safety": 2,
- "dependency-updates": 6,
+ "dependency-updates": 7,
"do-replan": 2,
"documentation": 7,
"error-handling": 3,
@@ -249,7 +249,8 @@
"3f461b1c111ba45b7fa5016883cfa54d",
"7ed05444e2602f4895bdd1e5e0edcaa8",
"1d59f04bea630a85a3085829db8599e7",
- "f34cfa7e495d2bd6d3ac3c80b44447e8"
+ "f34cfa7e495d2bd6d3ac3c80b44447e8",
+ "44de787b45e037fbce281efc87706873"
],
"do-replan": [
"59a57f1bb445138c30ab4fa23630c6f8"
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 922478f668..4da965c80d 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -487,6 +487,11 @@ Check {appName} dependencies for updates and security vulnerabilities:
Repository: {repoPath}
+When this task runs in a CoS-managed worktree, its \`node_modules\` directories are
+intentionally private to that worktree. If validation needs installed packages,
+use the repository's documented package manager from the worktree so installs
+and lockfile regeneration stay isolated from the source checkout.
+
Inventory security alerts first, then resolve open automated dependency PRs before
making your own bumps. A Dependabot/Renovate PR is a bump already
proposed and already isolated to one package — redoing it yourself conflicts with the bot
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 142b556379..ee73016bff 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -41,7 +41,7 @@ export const PROMPT_VERSIONS = {
'console-errors': 4, // v4: refer to framework-neutral UI lifecycle audit. v3: carries {modeInstructions}, collects real emitted output before diagnosing, groups duplicates by cause, and forbids "fixing" an error by suppressing it. Previously v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)
'error-handling': 3, // v3: carries {modeInstructions} and covers resilience (timeouts, retry ceilings, degraded-dependency fallback, cleanup on the error path, actionable user-facing text) while handing swallowed errors and log context to observability. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
'typing': 3, // v3: carries {modeInstructions}, exits cleanly on an untyped project, and targets boundary escape hatches and validator/type disagreement instead of a mechanical annotation sweep. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)
- 'dependency-updates': 6, // v6: the throwaway bot-PR worktree is `dep-{appSlug}-pr-<n>` — the app NAME alone did not isolate two managed apps sharing a name, and {appSlug} is rendered server-side rather than slugified by the agent (`appWorktreeSlug`, server/lib/worktreeOwnership.js). v5: inventory all Dependabot alerts and ecosystems, verify actual upstream fixes, and track unpatched mitigations separately from alert closure. v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")
+ 'dependency-updates': 7, // v7: dependency-update worktrees keep package-manager writes out of the source checkout's shared node_modules. v6: the throwaway bot-PR worktree is `dep-{appSlug}-pr-<n>` — the app NAME alone did not isolate two managed apps sharing a name, and {appSlug} is rendered server-side rather than slugified by the agent (`appWorktreeSlug`, server/lib/worktreeOwnership.js). v5: inventory all Dependabot alerts and ecosystems, verify actual upstream fixes, and track unpatched mitigations separately from alert closure. v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")
'documentation': 7, // v7: carries {modeInstructions} and ranks wrong documentation above missing documentation, verifying instructions against the code rather than trusting the prose. Previously v6: the changelog step names `AGENTS.md` (or `CLAUDE.md`) as the file carrying the repo's documented convention — #4852 made AGENTS.md the canonical cross-vendor agent-instructions filename, and a managed app that adopted it would otherwise be told to read a file it no longer has. v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)
'ui-bugs': 3, // v3: carries {modeInstructions}, exits cleanly when the interface is unreachable instead of filing from imagination, and cedes layout/a11y/UX/copy to their owners. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
'mobile-responsive': 3, // v3: carries {modeInstructions} and requires the viewport width plus what a user cannot do there, rather than flagging any layout that merely looks different. Previously v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 02b1554560..fa88a5b3fe 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -10,8 +10,8 @@
*/
import { existsSync, realpathSync } from 'fs';
-import { lstat, readdir, rm, stat, symlink } from 'fs/promises';
-import { join } from 'path';
+import { lstat, readlink, readdir, rm, stat, symlink, unlink } from 'fs/promises';
+import { dirname, isAbsolute, join, resolve } from 'path';
import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';
import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';
@@ -42,10 +42,9 @@ const AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.y
// hundreds of files. Enough to identify the work, short enough to read.
const DIRT_PATHS_IN_WARNING = 5;
-// Dependencies are intentionally linked from the source checkout rather than
-// installed in each ephemeral worktree. npm follows these links and can erase
-// the primary checkout if an agent runs npm install, so agents must use the
-// already-installed workspace binaries instead.
+// Dependencies are linked from the source checkout for ordinary ephemeral
+// worktrees. Dependency-update tasks opt out so package managers cannot mutate
+// the source checkout's installed tree through these links.
const WORKTREE_DEPENDENCY_PATHS = ['node_modules', 'client/node_modules', 'server/node_modules'];
/**
@@ -66,6 +65,26 @@ export async function linkWorktreeDependencies(sourceWorkspace, worktreePath) {
}));
}
+/**
+ * Remove only dependency symlinks that point back into the source checkout.
+ * Real dependency directories and links managed by another tool stay intact.
+ */
+export async function unlinkWorktreeDependencies(sourceWorkspace, worktreePath) {
+ await Promise.all(WORKTREE_DEPENDENCY_PATHS.map(async (relativePath) => {
+ const sourcePath = join(sourceWorkspace, relativePath);
+ const targetPath = join(worktreePath, relativePath);
+ const targetStat = await lstat(targetPath).catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (!targetStat?.isSymbolicLink()) return;
+
+ const linkTarget = await readlink(targetPath);
+ const linkedPath = isAbsolute(linkTarget) ? linkTarget : resolve(dirname(targetPath), linkTarget);
+ if (pathsEqual(linkedPath, sourcePath)) await unlink(targetPath);
+ }));
+}
+
// `git worktree add` lock-contention retry (#2193). Git guards a repo's
// worktree bookkeeping (`.git/worktrees`, `.git/index.lock`) with a per-repo
// lock, so two adds fired in the same evaluation tick race — the loser fails
@@ -477,6 +496,7 @@ async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
* @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)
* @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives when it is a FORK PR's head, which has no `origin/<branch>`. Consulted only after the local and origin lookups both miss; omitting it preserves today's exact behavior, error message included.
* @param {string} options.planId - PLAN.md item slug ID — when provided, spliced into the branch name as `cos/<taskId>/<planId>/<agentId>` so other agents can detect this item is in flight by scanning branches/PRs
+ * @param {boolean} options.linkDependencies - Link source dependencies unless explicitly false
* @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree
*/
export async function createWorktree(agentId, sourceWorkspace, taskId, options = {}) {
@@ -554,7 +574,11 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
// both pass untouched — which is required: dropping the fork upstream would
// aim a config-derived push back at origin.
await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: false });
- await linkWorktreeDependencies(sourceWorkspace, worktreePath);
+ if (options.linkDependencies === false) {
+ await unlinkWorktreeDependencies(sourceWorkspace, worktreePath);
+ } else {
+ await linkWorktreeDependencies(sourceWorkspace, worktreePath);
+ }
console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);
return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };
}
@@ -599,7 +623,11 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
// Backstop the flag above — an older git, or a repo-level `branch.autoSetupMerge`
// setting, must not be able to hand an agent a branch aimed at the default branch.
await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: true });
- await linkWorktreeDependencies(sourceWorkspace, worktreePath);
+ if (options.linkDependencies === false) {
+ await unlinkWorktreeDependencies(sourceWorkspace, worktreePath);
+ } else {
+ await linkWorktreeDependencies(sourceWorkspace, worktreePath);
+ }
console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 6fd7beb070..f956388988 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -19,7 +19,9 @@ vi.mock('fs/promises', () => ({
readdir: vi.fn().mockResolvedValue([]),
rm: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),
+ readlink: vi.fn().mockResolvedValue(''),
symlink: vi.fn().mockResolvedValue(undefined),
+ unlink: vi.fn().mockResolvedValue(undefined),
// adoptWorktree ensures the worktrees root exists before moving a tree into it.
mkdir: vi.fn().mockResolvedValue(undefined),
}));
@@ -50,6 +52,7 @@ const {
createWorktree,
createPersistentWorktree,
linkWorktreeDependencies,
+ unlinkWorktreeDependencies,
listWorktrees,
WORKTREE_ADD_TIMEOUT_MS,
} = await import('./worktreeManager.js');
@@ -57,7 +60,7 @@ const { isPathInsideDir } = await import('../lib/fileUtils.js');
const { worktreeOwnershipReason } = await import('../lib/worktreeOwnership.js');
const { win32 } = await import('path');
const { existsSync } = await import('fs');
-const { lstat, symlink } = await import('fs/promises');
+const { lstat, readlink, symlink, unlink } = await import('fs/promises');
const { PATHS } = await import('../lib/fileUtils.js');
/**
@@ -117,7 +120,9 @@ describe('Worktree Path Construction', () => {
describe('Worktree dependency preparation', () => {
beforeEach(() => {
lstat.mockReset();
+ readlink.mockReset();
symlink.mockClear();
+ unlink.mockClear();
});
it('links installed root, client, and server dependencies when targets are absent', async () => {
@@ -154,6 +159,21 @@ describe('Worktree dependency preparation', () => {
await expect(linkWorktreeDependencies('/generic-repo', '/generic-worktree')).resolves.toBeUndefined();
expect(symlink).not.toHaveBeenCalled();
});
+
+ it('removes only symlinks that point to the source checkout', async () => {
+ lstat.mockImplementation((path) => {
+ const normalized = path.replaceAll('\\', '/');
+ if (normalized === '/worktree/node_modules') return Promise.resolve({ isSymbolicLink: () => true });
+ if (normalized === '/worktree/client/node_modules') return Promise.resolve({ isSymbolicLink: () => false });
+ return Promise.reject(Object.assign(new Error('missing'), { code: 'ENOENT' }));
+ });
+ readlink.mockResolvedValue('/repo/node_modules');
+
+ await unlinkWorktreeDependencies('/repo', '/worktree');
+
+ expect(unlink).toHaveBeenCalledTimes(1);
+ expect(unlink).toHaveBeenCalledWith('/worktree/node_modules');
+ });
});
describe('Worktree Porcelain Parsing', () => {
@@ -1286,6 +1306,17 @@ describe('createWorktree upstream safety (#4172)', () => {
expect(add.indexOf('--no-track')).toBeLessThan(add.indexOf('-b'));
});
+ it('keeps dependency-update worktrees detached from source dependencies', async () => {
+ const missing = Object.assign(new Error('missing'), { code: 'ENOENT' });
+ lstat.mockReset();
+ lstat.mockRejectedValue(missing);
+ symlink.mockClear();
+
+ await createWorktree('agent-deps', '/repo', 'task-deps', { linkDependencies: false });
+
+ expect(symlink).not.toHaveBeenCalled();
+ });
+
it('drops an upstream that still points at the default branch', async () => {
// An older git, or a repo whose config re-tracks despite the flag: the first
// read finds `main`, the guard unsets, the re-read confirms.