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
feat: link dependencies into agent worktrees
[._.]/ Adam Eivy2dae8ec7561e
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex d973e942ca..b4bf8cdd86 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -10,7 +10,7 @@*/import { existsSync, realpathSync } from 'fs';-import { readdir, rm, stat } from 'fs/promises';+import { lstat, readdir, rm, stat, symlink } from 'fs/promises';import { join } from 'path';import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';@@ -42,6 +42,30 @@ 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.+const WORKTREE_DEPENDENCY_PATHS = ['node_modules', 'client/node_modules', 'server/node_modules'];++/**+ * Make installed dependencies available to a fresh worktree without copying+ * 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.+ */+export async function linkWorktreeDependencies(sourceWorkspace, worktreePath) {+ await Promise.all(WORKTREE_DEPENDENCY_PATHS.map(async (relativePath) => {+ const sourcePath = join(sourceWorkspace, relativePath);+ const targetPath = join(worktreePath, relativePath);+ const sourceExists = await lstat(sourcePath).then(() => true).catch(() => false);+ if (!sourceExists) return;+ const targetExists = await lstat(targetPath).then(() => true).catch(() => false);+ if (targetExists) return;+ await symlink(sourcePath, targetPath, 'dir');+ }));+}+// `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@@ -530,6 +554,7 @@ 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);console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };}@@ -574,6 +599,7 @@ 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);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.jsindex c3c332e9c0..6bf536de36 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -15,9 +15,11 @@ vi.mock('fs', () => ({realpathSync: vi.fn((p) => p),}));vi.mock('fs/promises', () => ({+ lstat: vi.fn().mockResolvedValue({}),readdir: vi.fn().mockResolvedValue([]),rm: vi.fn().mockResolvedValue(undefined),stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),+ symlink: vi.fn().mockResolvedValue(undefined),// adoptWorktree ensures the worktrees root exists before moving a tree into it.mkdir: vi.fn().mockResolvedValue(undefined),}));@@ -47,6 +49,7 @@ const {findAdoptableWorktreeForBranch,createWorktree,createPersistentWorktree,+ linkWorktreeDependencies,listWorktrees,WORKTREE_ADD_TIMEOUT_MS,} = await import('./worktreeManager.js');@@ -54,6 +57,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 { PATHS } = await import('../lib/fileUtils.js');/**@@ -110,6 +114,36 @@ describe('Worktree Path Construction', () => {});});+describe('Worktree dependency preparation', () => {+ beforeEach(() => {+ lstat.mockReset();+ symlink.mockClear();+ });++ it('links installed root, client, and server dependencies when targets are absent', async () => {+ lstat.mockImplementation((path) => path.startsWith('/repo/')+ ? Promise.resolve({})+ : Promise.reject(new Error('missing')));++ await linkWorktreeDependencies('/repo', '/worktree');++ expect(symlink).toHaveBeenCalledTimes(3);+ expect(symlink).toHaveBeenCalledWith('/repo/node_modules', '/worktree/node_modules', 'dir');+ expect(symlink).toHaveBeenCalledWith('/repo/client/node_modules', '/worktree/client/node_modules', 'dir');+ expect(symlink).toHaveBeenCalledWith('/repo/server/node_modules', '/worktree/server/node_modules', 'dir');+ });++ it('skips missing sources and preserves existing targets', async () => {+ lstat.mockImplementation((path) => path === '/repo/node_modules' || path === '/worktree/node_modules'+ ? Promise.resolve({})+ : Promise.reject(new Error('missing')));++ await linkWorktreeDependencies('/repo', '/worktree');++ expect(symlink).not.toHaveBeenCalled();+ });+});+describe('Worktree Porcelain Parsing', () => {function parseWorktreeList(stdout) {const worktrees = [];