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

feat(cos): add task conflict detection and git worktree isolation

Adam Eivy7a18cb8a3fb9
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index 32795efa3d..fab95083d7 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -249,6 +249,14 @@ This release introduces a structured changelog documentation system for creating
- **API Endpoints**: Full REST API at `/api/browser` with status, config, launch, stop, restart, health, process, pages, version, and logs endpoints
- **Navigation**: Added to sidebar with Globe icon between Dev Tools and Media
+### Chief of Staff - Task Conflict Detection & Git Worktrees
+- **Conflict Detection**: When the CoS kicks off a new agent, it now analyzes whether the work conflicts with existing active agents in the same workspace
+- **Automatic Worktree Isolation**: If conflicts are detected (uncommitted changes, same-app targeting, keyword overlap in descriptions), the agent is spawned in an isolated git worktree instead of the shared workspace
+- **Auto-Merge on Success**: When an agent completes successfully in a worktree, its branch is automatically merged back to the source branch
+- **Orphaned Worktree Cleanup**: Worktrees from crashed or terminated agents are automatically cleaned up during orphan detection
+- **Agent Prompt Context**: Agents working in worktrees receive instructions about their isolation context and branch
+- **Three-Level Detection**: Detects conflicts via uncommitted changes (strongest signal), same-app targeting (medium), and keyword overlap analysis (heuristic)
+
### AI Provider Model Updates
- **Claude Opus 4.6**: Added `claude-opus-4-6` model to Claude Code CLI provider as the new default and heavy tier model
- **GPT-5.2**: Codex CLI provider uses `gpt-5.2` as default and heavy tier model (5.3 was not yet available)
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 3b915b6030..82bb95bd95 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -29,6 +29,8 @@ import { readJSONFile } from '../lib/fileUtils.js';
import { createToolExecution, startExecution, updateExecution, completeExecution, errorExecution, getExecution, getStats as getToolStats } from './toolStateMachine.js';
import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';
import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';
+import { detectConflicts } from './taskConflict.js';
+import { createWorktree, removeWorktree, cleanupOrphanedWorktrees } from './worktreeManager.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -815,12 +817,45 @@ export async function spawnAgentForTask(task) {
});
// Determine workspace path
- const workspacePath = task.metadata?.app
+ let workspacePath = task.metadata?.app
? await getAppWorkspace(task.metadata.app)
: ROOT_DIR;
- // Build the agent prompt
- const prompt = await buildAgentPrompt(task, config, workspacePath);
+ // Check for conflicts with active agents and decide on worktree usage
+ let worktreeInfo = null;
+ const { getAgents } = await import('./cos.js');
+ const allAgents = await getAgents();
+ const runningAgents = allAgents.filter(a => a.status === 'running');
+
+ const conflictResult = await detectConflicts(task, workspacePath, runningAgents).catch(err => {
+ emitLog('warn', `Conflict detection failed: ${err.message}`, { taskId: task.id });
+ return { hasConflict: false, recommendation: 'proceed' };
+ });
+
+ if (conflictResult.recommendation === 'worktree') {
+ emitLog('info', `🌳 Conflict detected for task ${task.id}: ${conflictResult.reason} — creating worktree`, {
+ taskId: task.id,
+ conflictingAgents: conflictResult.conflictingAgents,
+ reason: conflictResult.reason
+ });
+
+ worktreeInfo = await createWorktree(agentId, workspacePath, task.id).catch(err => {
+ emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
+ return null;
+ });
+
+ if (worktreeInfo) {
+ workspacePath = worktreeInfo.worktreePath;
+ emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName}`, {
+ agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName
+ });
+ }
+ } else if (conflictResult.recommendation === 'proceed') {
+ emitLog('debug', `No conflicts for task ${task.id}, using shared workspace`, { taskId: task.id });
+ }
+
+ // Build the agent prompt (includes worktree context if applicable)
+ const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo);
// Create agent directory
const agentDir = join(AGENTS_DIR, agentId);
@@ -834,9 +869,12 @@ export async function spawnAgentForTask(task) {
// Create run entry for usage tracking
const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath);
- // Register the agent with model info
+ // Register the agent with model info (include worktree metadata)
await registerAgent(agentId, task.id, {
workspacePath,
+ sourceWorkspace: worktreeInfo ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR) : null,
+ worktreeBranch: worktreeInfo?.branchName || null,
+ isWorktree: !!worktreeInfo,
taskDescription: task.description,
taskType: task.taskType,
priority: task.priority,
@@ -848,7 +886,7 @@ export async function spawnAgentForTask(task) {
useRunner
});
- emitLog('info', `Agent ${agentId} initializing...`, { agentId, taskId: task.id });
+ emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}`, { agentId, taskId: task.id });
// Mark the task as in_progress to prevent re-spawning
await updateTask(task.id, { status: 'in_progress' }, task.taskType || 'user');
@@ -856,7 +894,7 @@ export async function spawnAgentForTask(task) {
// Build CLI-specific spawn configuration
const cliConfig = buildCliSpawnConfig(provider, selectedModel);
- emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct', cli: cliConfig.command, lane: laneName });
+ emitLog('success', `Spawning agent for task ${task.id}`, { agentId, model: selectedModel, mode: useRunner ? 'runner' : 'direct', cli: cliConfig.command, lane: laneName, worktree: !!worktreeInfo });
// Use CoS Runner if available, otherwise spawn directly
if (useRunner) {
@@ -1049,9 +1087,34 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
// Process memory extraction and app cooldown
await processAgentCompletion(agentId, task, success, outputBuffer);
+ // Clean up worktree if agent was using one
+ await cleanupAgentWorktree(agentId, success);
+
runnerAgents.delete(agentId);
}
+/**
+ * Clean up a worktree for a completed agent.
+ * Reads worktree metadata from the agent's registered state and removes the worktree.
+ * On success, merges the worktree branch back to the source branch.
+ */
+async function cleanupAgentWorktree(agentId, success) {
+ const { getAgent: getAgentState } = await import('./cos.js');
+ const agentState = await getAgentState(agentId).catch(() => null);
+ if (!agentState?.metadata?.isWorktree) return;
+
+ const { sourceWorkspace, worktreeBranch } = agentState.metadata;
+ if (!sourceWorkspace || !worktreeBranch) return;
+
+ emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${success})`, {
+ agentId, branchName: worktreeBranch, merge: success
+ });
+
+ await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {
+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
+ });
+}
+
/**
* Spawn agent directly (fallback when runner not available)
*/
@@ -1238,6 +1301,9 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, provid
// Process memory extraction and app cooldown
await processAgentCompletion(agentId, task, success, outputBuffer);
+ // Clean up worktree if agent was using one
+ await cleanupAgentWorktree(agentId, success);
+
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
activeAgents.delete(agentId);
});
@@ -1362,8 +1428,12 @@ async function getClaudeMdContext(workspaceDir) {
/**
* Build the prompt for an agent
+ * @param {Object} task - Task object
+ * @param {Object} config - CoS configuration
+ * @param {string} workspaceDir - Working directory (may be a worktree)
+ * @param {Object|null} worktreeInfo - Worktree details if using a worktree ({ worktreePath, branchName })
*/
-async function buildAgentPrompt(task, config, workspaceDir) {
+async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null) {
// Get relevant memories for context injection
const memorySection = await getMemorySection(task, {
maxTokens: config.memory?.maxContextTokens || 2000
@@ -1386,6 +1456,16 @@ async function buildAgentPrompt(task, config, workspaceDir) {
return null;
});
+ // Build worktree context section if applicable
+ const worktreeSection = worktreeInfo ? `
+## Git Worktree Context
+You are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.
+- **Branch**: \`${worktreeInfo.branchName}\`
+- **Worktree Path**: \`${worktreeInfo.worktreePath}\`
+
+**Important**: Commit your changes to this branch. Your commits will be automatically merged back to the main development branch when your task completes. Do NOT manually switch branches or modify the worktree configuration.
+` : '';
+
// Try to use the prompt template system
const promptData = await buildPrompt('cos-agent-briefing', {
task,
@@ -1393,6 +1473,7 @@ async function buildAgentPrompt(task, config, workspaceDir) {
memorySection,
claudeMdSection,
digitalTwinSection,
+ worktreeSection,
soulSection: digitalTwinSection, // Backwards compatibility for prompt templates
timestamp: new Date().toISOString()
}).catch(() => null);
@@ -1418,7 +1499,7 @@ You are an autonomous agent working on behalf of the Chief of Staff.
${task.metadata?.context ? `- **Context**: ${task.metadata.context}` : ''}
${task.metadata?.app ? `- **Target App**: ${task.metadata.app}` : ''}
${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `- **Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}
-
+${worktreeSection}
## Instructions
1. Analyze the task requirements carefully
2. Make necessary changes to complete the task
@@ -1738,6 +1819,17 @@ export async function cleanupOrphanedAgents() {
}
}
+ // Clean up worktrees for orphaned agents
+ for (const { agentId } of orphanedTaskIds) {
+ await cleanupAgentWorktree(agentId, false);
+ }
+
+ // Also clean up any orphaned worktrees not tracked by any agent
+ const activeIds = new Set(getActiveAgentIds());
+ await cleanupOrphanedWorktrees(ROOT_DIR, activeIds).catch(err => {
+ console.log(`⚠️ Orphaned worktree cleanup failed: ${err.message}`);
+ });
+
// Handle orphaned tasks - reset for retry or create investigation task
for (const { taskId, agentId } of orphanedTaskIds) {
await handleOrphanedTask(taskId, agentId, getTaskById);
diff --git a/server/services/taskConflict.js b/server/services/taskConflict.js
new file mode 100644
index 0000000000..b0a08bab33
--- /dev/null
+++ b/server/services/taskConflict.js
@@ -0,0 +1,165 @@
+/**
+ * Task Conflict Detection Service
+ *
+ * Analyzes whether a new task conflicts with active agents working in
+ * the same workspace. When conflicts are detected, the spawner should
+ * use a git worktree for isolation.
+ */
+
+import { spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { join } from 'path';
+
+/**
+ * Execute a git command and return stdout
+ */
+function execGit(args, cwd) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('git', args, { cwd, shell: false });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', d => { stdout += d.toString(); });
+ child.stderr.on('data', d => { stderr += d.toString(); });
+ child.on('close', code => {
+ if (code !== 0) {
+ reject(new Error(stderr || `git exited with code ${code}`));
+ } else {
+ resolve(stdout);
+ }
+ });
+ child.on('error', reject);
+ });
+}
+
+/**
+ * Get list of files modified in the working tree (unstaged + staged + untracked)
+ */
+async function getModifiedFiles(workspacePath) {
+ const stdout = await execGit(['status', '--porcelain'], workspacePath);
+ return stdout.trim().split('\n')
+ .filter(Boolean)
+ .map(line => line.substring(3).trim());
+}
+
+/**
+ * Check whether a workspace path is inside a git repository
+ */
+async function isGitRepo(workspacePath) {
+ if (!existsSync(join(workspacePath, '.git'))) return false;
+ const stdout = await execGit(
+ ['rev-parse', '--is-inside-work-tree'],
+ workspacePath
+ ).catch(() => 'false');
+ return stdout.trim() === 'true';
+}
+
+/**
+ * Detect conflicts between a new task and currently active agents.
+ *
+ * Returns:
+ * { hasConflict, reason, conflictingAgents, recommendation }
+ *
+ * recommendation is one of:
+ * 'worktree' – use a git worktree for the new task
+ * 'proceed' – no conflict, run in the normal workspace
+ * 'skip' – task targets a non-git workspace, worktrees not possible
+ */
+export async function detectConflicts(task, workspacePath, activeAgentsList) {
+ // If the workspace isn't a git repo, worktrees aren't an option
+ const gitRepo = await isGitRepo(workspacePath).catch(() => false);
+ if (!gitRepo) {
+ return {
+ hasConflict: false,
+ reason: 'not-a-git-repo',
+ conflictingAgents: [],
+ recommendation: 'skip'
+ };
+ }
+
+ // Find agents currently working in the same workspace
+ const sameWorkspaceAgents = activeAgentsList.filter(agent => {
+ const agentWorkspace = agent.metadata?.workspacePath || agent.workspacePath;
+ return agentWorkspace === workspacePath;
+ });
+
+ if (sameWorkspaceAgents.length === 0) {
+ return {
+ hasConflict: false,
+ reason: 'no-active-agents-in-workspace',
+ conflictingAgents: [],
+ recommendation: 'proceed'
+ };
+ }
+
+ // There are active agents in the same workspace – check for file-level overlap
+ const modifiedFiles = await getModifiedFiles(workspacePath).catch(() => []);
+
+ // If the workspace already has uncommitted changes (from another agent), conflict
+ if (modifiedFiles.length > 0) {
+ return {
+ hasConflict: true,
+ reason: 'workspace-has-uncommitted-changes',
+ conflictingAgents: sameWorkspaceAgents.map(a => a.id),
+ modifiedFiles,
+ recommendation: 'worktree'
+ };
+ }
+
+ // Even without uncommitted changes, concurrent agents in the same workspace
+ // can step on each other. Use description heuristics for overlap.
+ const taskDesc = (task.description || '').toLowerCase();
+ const taskApp = task.metadata?.app;
+
+ const overlappingAgents = sameWorkspaceAgents.filter(agent => {
+ const agentDesc = (agent.metadata?.taskDescription || agent.taskDescription || '').toLowerCase();
+ const agentApp = agent.metadata?.app || agent.app;
+
+ // Same target app is a strong conflict signal
+ if (taskApp && agentApp && taskApp === agentApp) return true;
+
+ // Check for keyword overlap in descriptions (files, components, features)
+ const taskKeywords = extractKeywords(taskDesc);
+ const agentKeywords = extractKeywords(agentDesc);
+ const overlap = taskKeywords.filter(k => agentKeywords.includes(k));
+ return overlap.length >= 2;
+ });
+
+ if (overlappingAgents.length > 0) {
+ return {
+ hasConflict: true,
+ reason: 'concurrent-agents-likely-overlap',
+ conflictingAgents: overlappingAgents.map(a => a.id),
+ recommendation: 'worktree'
+ };
+ }
+
+ // Agents in same workspace but no obvious overlap – still use worktree
+ // to be safe, since concurrent file edits are unpredictable
+ return {
+ hasConflict: true,
+ reason: 'concurrent-agents-in-same-workspace',
+ conflictingAgents: sameWorkspaceAgents.map(a => a.id),
+ recommendation: 'worktree'
+ };
+}
+
+/**
+ * Extract meaningful keywords from a task description for overlap detection.
+ * Filters out common stop words and short tokens.
+ */
+function extractKeywords(text) {
+ const stopWords = new Set([
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
+ 'of', 'with', 'by', 'from', 'is', 'it', 'this', 'that', 'be', 'as',
+ 'are', 'was', 'were', 'been', 'has', 'have', 'had', 'do', 'does',
+ 'not', 'no', 'can', 'will', 'should', 'may', 'task', 'fix', 'add',
+ 'update', 'change', 'make', 'use', 'new', 'all', 'any', 'each'
+ ]);
+
+ return text
+ .replace(/[^a-z0-9\s-_/.]/g, ' ')
+ .split(/\s+/)
+ .filter(w => w.length > 2 && !stopWords.has(w));
+}
+
+export { extractKeywords, getModifiedFiles, isGitRepo };
diff --git a/server/services/taskConflict.test.js b/server/services/taskConflict.test.js
new file mode 100644
index 0000000000..658869666c
--- /dev/null
+++ b/server/services/taskConflict.test.js
@@ -0,0 +1,210 @@
+import { describe, it, expect } from 'vitest';
+
+/**
+ * Tests for the task conflict detection service.
+ * We test the pure logic inline to avoid complex mocking of child_process/fs.
+ */
+
+// Inline extractKeywords logic for unit testing
+function extractKeywords(text) {
+ const stopWords = new Set([
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
+ 'of', 'with', 'by', 'from', 'is', 'it', 'this', 'that', 'be', 'as',
+ 'are', 'was', 'were', 'been', 'has', 'have', 'had', 'do', 'does',
+ 'not', 'no', 'can', 'will', 'should', 'may', 'task', 'fix', 'add',
+ 'update', 'change', 'make', 'use', 'new', 'all', 'any', 'each'
+ ]);
+
+ return text
+ .replace(/[^a-z0-9\s-_/.]/g, ' ')
+ .split(/\s+/)
+ .filter(w => w.length > 2 && !stopWords.has(w));
+}
+
+// Inline conflict analysis logic for testing without git/fs dependencies
+function analyzeConflict(task, workspacePath, activeAgents, options = {}) {
+ const { isGitRepo = true, modifiedFiles = [] } = options;
+
+ if (!isGitRepo) {
+ return { hasConflict: false, reason: 'not-a-git-repo', conflictingAgents: [], recommendation: 'skip' };
+ }
+
+ const sameWorkspaceAgents = activeAgents.filter(agent => {
+ const agentWorkspace = agent.metadata?.workspacePath || agent.workspacePath;
+ return agentWorkspace === workspacePath;
+ });
+
+ if (sameWorkspaceAgents.length === 0) {
+ return { hasConflict: false, reason: 'no-active-agents-in-workspace', conflictingAgents: [], recommendation: 'proceed' };
+ }
+
+ if (modifiedFiles.length > 0) {
+ return {
+ hasConflict: true,
+ reason: 'workspace-has-uncommitted-changes',
+ conflictingAgents: sameWorkspaceAgents.map(a => a.id),
+ modifiedFiles,
+ recommendation: 'worktree'
+ };
+ }
+
+ const taskDesc = (task.description || '').toLowerCase();
+ const taskApp = task.metadata?.app;
+
+ const overlappingAgents = sameWorkspaceAgents.filter(agent => {
+ const agentDesc = (agent.metadata?.taskDescription || agent.taskDescription || '').toLowerCase();
+ const agentApp = agent.metadata?.app || agent.app;
+
+ if (taskApp && agentApp && taskApp === agentApp) return true;
+
+ const taskKeywords = extractKeywords(taskDesc);
+ const agentKeywords = extractKeywords(agentDesc);
+ const overlap = taskKeywords.filter(k => agentKeywords.includes(k));
+ return overlap.length >= 2;
+ });
+
+ if (overlappingAgents.length > 0) {
+ return {
+ hasConflict: true,
+ reason: 'concurrent-agents-likely-overlap',
+ conflictingAgents: overlappingAgents.map(a => a.id),
+ recommendation: 'worktree'
+ };
+ }
+
+ return {
+ hasConflict: true,
+ reason: 'concurrent-agents-in-same-workspace',
+ conflictingAgents: sameWorkspaceAgents.map(a => a.id),
+ recommendation: 'worktree'
+ };
+}
+
+describe('extractKeywords', () => {
+ it('should extract meaningful words and filter stop words', () => {
+ const keywords = extractKeywords('fix the authentication bug in login component');
+ expect(keywords).not.toContain('the');
+ expect(keywords).toContain('authentication');
+ expect(keywords).toContain('bug');
+ expect(keywords).toContain('login');
+ expect(keywords).toContain('component');
+ });
+
+ it('should filter short words (<=2 chars)', () => {
+ const keywords = extractKeywords('a go to do it');
+ expect(keywords).toHaveLength(0);
+ });
+
+ it('should handle file paths', () => {
+ const keywords = extractKeywords('update server/services/cos.js');
+ expect(keywords).toContain('server/services/cos.js');
+ });
+
+ it('should return empty for empty string', () => {
+ expect(extractKeywords('')).toHaveLength(0);
+ });
+});
+
+describe('Conflict Detection Logic', () => {
+ const workspace = '/home/user/portos';
+
+ describe('No conflict scenarios', () => {
+ it('should return proceed when no agents are active in workspace', () => {
+ const task = { description: 'Fix login button', metadata: {} };
+ const result = analyzeConflict(task, workspace, []);
+
+ expect(result.hasConflict).toBe(false);
+ expect(result.recommendation).toBe('proceed');
+ });
+
+ it('should return proceed when agents are in different workspaces', () => {
+ const task = { description: 'Fix login', metadata: {} };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: '/other/workspace', taskDescription: 'Fix login' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents);
+
+ expect(result.hasConflict).toBe(false);
+ expect(result.recommendation).toBe('proceed');
+ });
+
+ it('should skip conflict detection for non-git repos', () => {
+ const task = { description: 'Run something', metadata: {} };
+ const result = analyzeConflict(task, workspace, [], { isGitRepo: false });
+
+ expect(result.hasConflict).toBe(false);
+ expect(result.recommendation).toBe('skip');
+ });
+ });
+
+ describe('Conflict scenarios', () => {
+ it('should detect conflict when workspace has uncommitted changes', () => {
+ const task = { description: 'Add feature', metadata: {} };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: workspace, taskDescription: 'Working on stuff' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents, {
+ modifiedFiles: ['server/index.js', 'client/App.jsx']
+ });
+
+ expect(result.hasConflict).toBe(true);
+ expect(result.reason).toBe('workspace-has-uncommitted-changes');
+ expect(result.recommendation).toBe('worktree');
+ expect(result.conflictingAgents).toContain('agent-1');
+ });
+
+ it('should detect overlap when tasks target the same app', () => {
+ const task = { description: 'Improve dashboard', metadata: { app: 'my-app' } };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: workspace, taskDescription: 'Review my-app', app: 'my-app' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents);
+
+ expect(result.hasConflict).toBe(true);
+ expect(result.reason).toBe('concurrent-agents-likely-overlap');
+ expect(result.recommendation).toBe('worktree');
+ });
+
+ it('should detect overlap when descriptions share keywords', () => {
+ const task = { description: 'refactor authentication middleware logic', metadata: {} };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: workspace, taskDescription: 'improve authentication middleware performance' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents);
+
+ expect(result.hasConflict).toBe(true);
+ expect(result.reason).toBe('concurrent-agents-likely-overlap');
+ expect(result.recommendation).toBe('worktree');
+ });
+
+ it('should still flag conflict for agents in same workspace with no keyword overlap', () => {
+ const task = { description: 'update readme file', metadata: {} };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: workspace, taskDescription: 'deploy kubernetes cluster' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents);
+
+ expect(result.hasConflict).toBe(true);
+ expect(result.reason).toBe('concurrent-agents-in-same-workspace');
+ expect(result.recommendation).toBe('worktree');
+ });
+ });
+
+ describe('Multiple agents', () => {
+ it('should identify all conflicting agents', () => {
+ const task = { description: 'work on auth', metadata: {} };
+ const agents = [
+ { id: 'agent-1', metadata: { workspacePath: workspace, taskDescription: 'fix auth module' } },
+ { id: 'agent-2', metadata: { workspacePath: workspace, taskDescription: 'test auth flows' } },
+ { id: 'agent-3', metadata: { workspacePath: '/other', taskDescription: 'something else' } }
+ ];
+ const result = analyzeConflict(task, workspace, agents);
+
+ expect(result.hasConflict).toBe(true);
+ expect(result.conflictingAgents).toHaveLength(2);
+ expect(result.conflictingAgents).toContain('agent-1');
+ expect(result.conflictingAgents).toContain('agent-2');
+ expect(result.conflictingAgents).not.toContain('agent-3');
+ });
+ });
+});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
new file mode 100644
index 0000000000..d770029847
--- /dev/null
+++ b/server/services/worktreeManager.js
@@ -0,0 +1,199 @@
+/**
+ * Git Worktree Manager
+ *
+ * Creates and cleans up git worktrees for CoS agents that need isolated
+ * workspaces to avoid file conflicts with concurrent agents.
+ *
+ * Worktrees are created under data/cos/worktrees/<agentId>/ with a
+ * unique branch name. On agent completion, the worktree is removed
+ * and the branch cleaned up.
+ */
+
+import { spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { mkdir, rm } from 'fs/promises';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const WORKTREES_DIR = join(__dirname, '../../data/cos/worktrees');
+
+/**
+ * Execute a git command and return stdout
+ */
+function execGit(args, cwd) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('git', args, { cwd, shell: false });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', d => { stdout += d.toString(); });
+ child.stderr.on('data', d => { stderr += d.toString(); });
+ child.on('close', code => {
+ if (code !== 0) {
+ reject(new Error(stderr || `git exited with code ${code}`));
+ } else {
+ resolve(stdout);
+ }
+ });
+ child.on('error', reject);
+ });
+}
+
+/**
+ * Create a git worktree for an agent.
+ *
+ * Creates a new branch and worktree directory that the agent can work in
+ * without disturbing the main workspace.
+ *
+ * @param {string} agentId - The agent identifier (used for branch/directory naming)
+ * @param {string} sourceWorkspace - The original git repository path
+ * @param {string} taskId - Task identifier (included in branch name for traceability)
+ * @returns {{ worktreePath: string, branchName: string }} paths for the new worktree
+ */
+export async function createWorktree(agentId, sourceWorkspace, taskId) {
+ if (!existsSync(WORKTREES_DIR)) {
+ await mkdir(WORKTREES_DIR, { recursive: true });
+ }
+
+ const branchName = `cos/${taskId}/${agentId}`;
+ const worktreePath = join(WORKTREES_DIR, agentId);
+
+ // Get the current branch to base the worktree on
+ const currentBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace)).trim();
+
+ // Create worktree with a new branch based on current HEAD
+ await execGit(
+ ['worktree', 'add', '-b', branchName, worktreePath, currentBranch],
+ sourceWorkspace
+ );
+
+ console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName})`);
+
+ return { worktreePath, branchName };
+}
+
+/**
+ * Remove a git worktree and its associated branch.
+ *
+ * Called during agent cleanup. Merges the worktree branch back
+ * to the source branch if the agent made commits, then prunes.
+ *
+ * @param {string} agentId - The agent identifier
+ * @param {string} sourceWorkspace - The original git repository path
+ * @param {string} branchName - The worktree branch to clean up
+ * @param {object} options - { merge: boolean } whether to attempt merge back
+ */
+export async function removeWorktree(agentId, sourceWorkspace, branchName, options = {}) {
+ const worktreePath = join(WORKTREES_DIR, agentId);
+
+ if (!existsSync(worktreePath)) {
+ console.log(`🌳 Worktree already removed for ${agentId}`);
+ return { merged: false, removed: true };
+ }
+
+ let merged = false;
+
+ // If merge requested, check if there are commits to merge
+ if (options.merge) {
+ const currentBranch = (await execGit(
+ ['rev-parse', '--abbrev-ref', 'HEAD'],
+ sourceWorkspace
+ )).trim();
+
+ // Check if worktree branch has commits ahead of the source branch
+ const aheadCount = (await execGit(
+ ['rev-list', '--count', `${currentBranch}..${branchName}`],
+ sourceWorkspace
+ ).catch(() => '0')).trim();
+
+ if (parseInt(aheadCount, 10) > 0) {
+ // Merge worktree branch back to the source branch
+ await execGit(['merge', branchName, '--no-edit'], sourceWorkspace)
+ .then(() => { merged = true; })
+ .catch(err => {
+ console.log(`⚠️ Could not auto-merge ${branchName}: ${err.message}`);
+ });
+ }
+ }
+
+ // Remove the worktree
+ await execGit(['worktree', 'remove', worktreePath, '--force'], sourceWorkspace)
+ .catch(async () => {
+ // Fallback: manually remove the directory and prune
+ await rm(worktreePath, { recursive: true, force: true });
+ await execGit(['worktree', 'prune'], sourceWorkspace).catch(() => {});
+ });
+
+ // Delete the branch if we merged or if it was never used
+ await execGit(['branch', '-D', branchName], sourceWorkspace)
+ .catch(() => {
+ // Branch may already be deleted or never created
+ });
+
+ console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
+
+ return { merged, removed: true };
+}
+
+/**
+ * List all active worktrees for the repository
+ */
+export async function listWorktrees(sourceWorkspace) {
+ const stdout = await execGit(['worktree', 'list', '--porcelain'], sourceWorkspace);
+ const worktrees = [];
+ let current = {};
+
+ for (const line of stdout.split('\n')) {
+ if (line.startsWith('worktree ')) {
+ if (current.path) worktrees.push(current);
+ current = { path: line.slice(9) };
+ } else if (line.startsWith('HEAD ')) {
+ current.head = line.slice(5);
+ } else if (line.startsWith('branch ')) {
+ current.branch = line.slice(7);
+ } else if (line === 'bare') {
+ current.bare = true;
+ } else if (line === 'detached') {
+ current.detached = true;
+ }
+ }
+ if (current.path) worktrees.push(current);
+
+ return worktrees;
+}
+
+/**
+ * Clean up any orphaned worktrees (worktrees whose agent no longer exists)
+ *
+ * @param {string} sourceWorkspace - The original git repository path
+ * @param {Set<string>} activeAgentIds - Set of currently active agent IDs
+ */
+export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds) {
+ if (!existsSync(WORKTREES_DIR)) return 0;
+
+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
+ let cleaned = 0;
+
+ for (const wt of worktrees) {
+ // Only clean up worktrees under our managed directory
+ if (!wt.path.startsWith(WORKTREES_DIR)) continue;
+
+ // Extract agent ID from the worktree path
+ const agentId = wt.path.split('/').pop();
+ if (!activeAgentIds.has(agentId)) {
+ const branchName = wt.branch?.replace('refs/heads/', '') || '';
+ await removeWorktree(agentId, sourceWorkspace, branchName, { merge: false })
+ .catch(err => {
+ console.log(`⚠️ Failed to clean orphaned worktree ${agentId}: ${err.message}`);
+ });
+ cleaned++;
+ }
+ }
+
+ if (cleaned > 0) {
+ console.log(`🌳 Cleaned ${cleaned} orphaned worktree(s)`);
+ }
+
+ return cleaned;
+}
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
new file mode 100644
index 0000000000..6c0ba7cf37
--- /dev/null
+++ b/server/services/worktreeManager.test.js
@@ -0,0 +1,155 @@
+import { describe, it, expect } from 'vitest';
+
+/**
+ * Tests for the worktree manager service.
+ * Tests the pure logic (branch naming, path construction) without actual git operations.
+ */
+
+describe('Worktree Branch Naming', () => {
+ function buildBranchName(taskId, agentId) {
+ return `cos/${taskId}/${agentId}`;
+ }
+
+ it('should include task ID and agent ID', () => {
+ const branch = buildBranchName('task-abc123', 'agent-12345678');
+ expect(branch).toBe('cos/task-abc123/agent-12345678');
+ });
+
+ it('should use cos/ prefix for namespacing', () => {
+ const branch = buildBranchName('task-xyz', 'agent-abcd');
+ expect(branch.startsWith('cos/')).toBe(true);
+ });
+
+ it('should handle system task IDs', () => {
+ const branch = buildBranchName('sys-001', 'agent-00000001');
+ expect(branch).toBe('cos/sys-001/agent-00000001');
+ });
+});
+
+describe('Worktree Path Construction', () => {
+ function buildWorktreePath(baseDir, agentId) {
+ return `${baseDir}/${agentId}`;
+ }
+
+ it('should create path under worktrees directory', () => {
+ const path = buildWorktreePath('/data/cos/worktrees', 'agent-12345678');
+ expect(path).toBe('/data/cos/worktrees/agent-12345678');
+ });
+
+ it('should use agent ID as directory name', () => {
+ const path = buildWorktreePath('/data/cos/worktrees', 'agent-abcdef12');
+ expect(path.endsWith('agent-abcdef12')).toBe(true);
+ });
+});
+
+describe('Worktree Porcelain Parsing', () => {
+ function parseWorktreeList(stdout) {
+ const worktrees = [];
+ let current = {};
+
+ for (const line of stdout.split('\n')) {
+ if (line.startsWith('worktree ')) {
+ if (current.path) worktrees.push(current);
+ current = { path: line.slice(9) };
+ } else if (line.startsWith('HEAD ')) {
+ current.head = line.slice(5);
+ } else if (line.startsWith('branch ')) {
+ current.branch = line.slice(7);
+ } else if (line === 'bare') {
+ current.bare = true;
+ } else if (line === 'detached') {
+ current.detached = true;
+ }
+ }
+ if (current.path) worktrees.push(current);
+
+ return worktrees;
+ }
+
+ it('should parse single worktree', () => {
+ const output = `worktree /Users/user/project
+HEAD abc1234567890
+branch refs/heads/main
+`;
+ const result = parseWorktreeList(output);
+ expect(result).toHaveLength(1);
+ expect(result[0].path).toBe('/Users/user/project');
+ expect(result[0].head).toBe('abc1234567890');
+ expect(result[0].branch).toBe('refs/heads/main');
+ });
+
+ it('should parse multiple worktrees', () => {
+ const output = `worktree /Users/user/project
+HEAD abc1234567890
+branch refs/heads/main
+
+worktree /data/cos/worktrees/agent-12345678
+HEAD def9876543210
+branch refs/heads/cos/task-abc/agent-12345678
+`;
+ const result = parseWorktreeList(output);
+ expect(result).toHaveLength(2);
+ expect(result[0].path).toBe('/Users/user/project');
+ expect(result[1].path).toBe('/data/cos/worktrees/agent-12345678');
+ expect(result[1].branch).toBe('refs/heads/cos/task-abc/agent-12345678');
+ });
+
+ it('should handle detached HEAD', () => {
+ const output = `worktree /Users/user/project
+HEAD abc1234567890
+detached
+`;
+ const result = parseWorktreeList(output);
+ expect(result).toHaveLength(1);
+ expect(result[0].detached).toBe(true);
+ });
+
+ it('should handle empty output', () => {
+ const result = parseWorktreeList('');
+ expect(result).toHaveLength(0);
+ });
+});
+
+describe('Orphaned Worktree Detection', () => {
+ function findOrphanedWorktrees(worktrees, worktreesDir, activeAgentIds) {
+ return worktrees.filter(wt => {
+ if (!wt.path.startsWith(worktreesDir)) return false;
+ const agentId = wt.path.split('/').pop();
+ return !activeAgentIds.has(agentId);
+ });
+ }
+
+ it('should identify worktrees without active agents', () => {
+ const worktrees = [
+ { path: '/project', branch: 'refs/heads/main' },
+ { path: '/data/cos/worktrees/agent-aaa', branch: 'refs/heads/cos/task-1/agent-aaa' },
+ { path: '/data/cos/worktrees/agent-bbb', branch: 'refs/heads/cos/task-2/agent-bbb' }
+ ];
+ const activeIds = new Set(['agent-aaa']);
+ const orphans = findOrphanedWorktrees(worktrees, '/data/cos/worktrees', activeIds);
+
+ expect(orphans).toHaveLength(1);
+ expect(orphans[0].path).toContain('agent-bbb');
+ });
+
+ it('should not include the main worktree', () => {
+ const worktrees = [
+ { path: '/project', branch: 'refs/heads/main' },
+ { path: '/data/cos/worktrees/agent-aaa', branch: 'refs/heads/cos/task-1/agent-aaa' }
+ ];
+ const orphans = findOrphanedWorktrees(worktrees, '/data/cos/worktrees', new Set());
+
+ expect(orphans).toHaveLength(1);
+ expect(orphans[0].path).not.toBe('/project');
+ });
+
+ it('should return empty when all worktrees have active agents', () => {
+ const worktrees = [
+ { path: '/data/cos/worktrees/agent-aaa', branch: 'refs/heads/cos/task-1/agent-aaa' }
+ ];
+ const activeIds = new Set(['agent-aaa']);
+ const orphans = findOrphanedWorktrees(worktrees, '/data/cos/worktrees', activeIds);
+
+ expect(orphans).toHaveLength(0);
+ });
+});