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
refactor: decompose subAgentSpawner.js god file (3,820 lines) into 9 focused modules
Adam Eivy549e3cc9a78f
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsnew file mode 100644index 0000000000..b4ce2f8e7f--- /dev/null+++ b/server/services/agentCliSpawning.js@@ -0,0 +1,569 @@+/**+ * Agent CLI Spawning+ *+ * Handles building spawn configurations, stream-json parsing, tool input+ * summarization, and Claude settings env injection for agent processes.+ */++import { join } from 'path';+import { readFile, writeFile, rm } from 'fs/promises';+import { existsSync } from 'fs';+import { spawn } from 'child_process';+import { homedir } from 'os';+import { cosEvents, emitLog } from './cosEvents.js';+import { updateAgent, completeAgent, appendAgentOutput } from './cosAgents.js';+import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';+import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';+import { updateTask } from './cos.js';+import { release, completeExecution, errorExecution } from './executionLanes.js';+import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';+import { completeAgentRun } from './agentRunTracking.js';+import { processAgentCompletion } from './agentCompletion.js';+import { activeAgents, userTerminatedAgents } from './agentState.js';+import { PATHS } from '../lib/fileUtils.js';++const AGENTS_DIR = PATHS.cosAgents;++/**+ * Summarize tool input into a concise description for display.+ * Extracts the most relevant parameter from each tool type.+ */+export function summarizeToolInput(toolName, input) {+ if (!input || typeof input !== 'object') return '';+ const shorten = (p) => {+ if (!p || typeof p !== 'string') return '';+ const parts = p.split('/').filter(Boolean);+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : p;+ };+ switch (toolName) {+ case 'Read':+ return shorten(input.file_path);+ case 'Edit':+ return shorten(input.file_path);+ case 'Write':+ return shorten(input.file_path);+ case 'Glob':+ return input.pattern || '';+ case 'Grep':+ return `"${(input.pattern || '').substring(0, 60)}"${input.path ? ` in ${shorten(input.path)}` : ''}`;+ case 'Bash': {+ const cmd = input.command || input.description || '';+ return cmd.substring(0, 80);+ }+ case 'Task':+ return input.description || '';+ case 'WebFetch':+ return shorten(input.url || '');+ case 'WebSearch':+ return `"${(input.query || '').substring(0, 60)}"`;+ case 'TodoWrite':+ return input.todos?.length ? `${input.todos.length} items` : '';+ case 'NotebookEdit':+ return shorten(input.notebook_path);+ default:+ return '';+ }+}++export function safeParse(str) {+ try { return JSON.parse(str); } catch { return null; }+}++/**+ * Create a Claude stream-json parser that extracts human-readable text from JSON stream events.+ * Returns a stateful parser with a `processChunk(data)` method that returns extracted text lines.+ * The parser handles:+ * - content_block_delta: incremental text tokens as they stream+ * - tool_use events: shows tool calls with input details (e.g. "🔧 Read …/services/api.js")+ * - input_json_delta: accumulates tool input JSON for detailed summaries+ * - content_block_stop: emits detailed tool summary when input is complete+ * - result: final result text (used for output file)+ */+export function createStreamJsonParser() {+ let lineBuffer = '';+ let finalResult = '';+ let textBuffer = '';+ // Track text across all conversation turns so multi-step agents (e.g., task + /simplify)+ // preserve all summaries instead of only the final one+ const textSections = [];+ let currentTextSection = '';+ // Track active tool blocks by index for input accumulation+ const activeTools = new Map(); // index -> { name, inputJson }++ // Flush accumulated text into a section boundary (tool call start, result event, or stream end)+ const commitSection = () => {+ const section = currentTextSection.trim();+ if (section) {+ textSections.push(section);+ currentTextSection = '';+ }+ };++ const processChunk = (rawData) => {+ const lines = [];+ lineBuffer += rawData;++ // Split on newlines - each JSON object is on its own line+ const parts = lineBuffer.split('\n');+ // Keep the last incomplete line in the buffer+ lineBuffer = parts.pop() || '';++ for (const part of parts) {+ const trimmed = part.trim();+ if (!trimmed) continue;++ // Skip non-JSON lines (stderr mixed in, etc.)+ if (!trimmed.startsWith('{')) continue;+ const parsed = safeParse(trimmed);+ if (!parsed) continue;++ // Extract text from streaming deltas+ if (parsed.type === 'stream_event') {+ const event = parsed.event;+ if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta') {+ const text = event.delta.text;+ textBuffer += text;+ currentTextSection += text;+ // Emit complete lines for readability, accumulate partial+ const textLines = textBuffer.split('\n');+ textBuffer = textLines.pop() || '';+ for (const tl of textLines) {+ lines.push(tl);+ }+ }+ // Accumulate tool input JSON deltas+ if (event?.type === 'content_block_delta' && event.delta?.type === 'input_json_delta') {+ const idx = event.index;+ const tool = activeTools.get(idx);+ if (tool) {+ tool.inputJson += event.delta.partial_json || '';+ }+ }+ // Track tool use start - record name and begin accumulating input+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {+ const toolName = event.content_block.name || 'unknown';+ const idx = event.index;+ activeTools.set(idx, { name: toolName, inputJson: '' });+ lines.push(`🔧 Using ${toolName}...`);+ commitSection();+ }+ // When tool input is complete, emit a detailed summary line+ if (event?.type === 'content_block_stop') {+ const idx = event.index;+ const tool = activeTools.get(idx);+ if (tool) {+ if (tool.inputJson) {+ const input = safeParse(tool.inputJson);+ if (input) {+ const detail = summarizeToolInput(tool.name, input);+ if (detail) {+ lines.push(` → ${detail}`);+ }+ }+ }+ activeTools.delete(idx);+ }+ }+ }++ // Extract tool results from assistant messages+ if (parsed.type === 'assistant') {+ const content = parsed.message?.content;+ if (Array.isArray(content)) {+ for (const block of content) {+ if (block.type === 'tool_result' && typeof block.content === 'string') {+ const firstLine = block.content.split('\n')[0]?.substring(0, 200);+ if (firstLine) {+ lines.push(` ↳ ${firstLine}`);+ }+ }+ }+ }+ }++ // Capture final result text for output file+ if (parsed.type === 'result') {+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ commitSection();+ finalResult = parsed.result || '';+ }+ }++ return lines;+ };++ const flush = () => {+ const lines = [];+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ commitSection();+ return lines;+ };++ // Multi-section: return all text turns combined (e.g., task summary + simplify summary)+ // Single-section: return the CLI result field (cleaner, no tool call noise)+ const getFinalResult = () => {+ if (textSections.length > 1) {+ return textSections.join('\n\n');+ }+ return finalResult;+ };++ return { processChunk, flush, getFinalResult };+}++/**+ * Build spawn command and arguments for a CLI provider.+ * Returns { command, args, stdinMode } based on provider type.+ */+export function buildCliSpawnConfig(provider, model) {+ const providerId = provider?.id || 'claude-code';++ // Codex CLI uses different invocation pattern+ if (providerId === 'codex') {+ const args = ['exec'];+ if (model) {+ args.push('--model', model);+ }+ return {+ command: provider?.command || 'codex',+ args,+ stdinMode: 'prompt' // codex exec reads prompt from stdin+ };+ }++ // Gemini CLI — uses --yolo for auto-approval, -p for non-interactive stdin mode+ if (providerId === 'gemini-cli') {+ const args = ['--yolo', ...(provider?.args || [])];+ if (model) {+ args.push('--model', model);+ }+ return {+ command: provider?.command || 'gemini',+ args,+ stdinMode: 'prompt'+ };+ }++ // Default: Claude Code CLI+ const args = [+ '--dangerously-skip-permissions', // Unrestricted mode+ '--print', // Print output and exit+ '--output-format', 'stream-json', // Stream JSON events for live output+ '--verbose', // Required for stream-json+ '--include-partial-messages', // Include incremental text deltas+ ...(provider?.args || []), // User-configured provider args+ ];+ if (model) {+ args.push('--model', model);+ }++ return {+ command: provider?.command || process.env.CLAUDE_PATH || 'claude',+ args,+ stdinMode: 'prompt',+ streamFormat: 'stream-json'+ };+}++/**+ * Check if a provider is a Claude CLI provider that needs settings.json env injection.+ */+export const isClaudeCliProvider = (provider) =>+ provider?.type === 'cli' && (provider.id === 'claude-code' || provider.id === 'claude-code-bedrock');++/**+ * Read env vars from ~/.claude/settings.json to inject into Claude CLI spawns.+ * Ensures user's Bedrock/provider config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.)+ * is present in spawned agent environments even if PM2 was started without them.+ */+let _claudeSettingsEnvCache = null;+let _claudeSettingsEnvCacheTime = 0;+const SETTINGS_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes++export async function getClaudeSettingsEnv() {+ if (_claudeSettingsEnvCache !== null && (Date.now() - _claudeSettingsEnvCacheTime) < SETTINGS_CACHE_TTL_MS) return _claudeSettingsEnvCache;+ try {+ const settingsPath = join(homedir(), '.claude', 'settings.json');+ if (existsSync(settingsPath)) {+ const raw = await readFile(settingsPath, 'utf-8');+ const settings = JSON.parse(raw);+ _claudeSettingsEnvCache = settings.env || {};+ } else {+ _claudeSettingsEnvCache = {};+ }+ } catch (err) {+ _claudeSettingsEnvCache = {};+ }+ _claudeSettingsEnvCacheTime = Date.now();+ return _claudeSettingsEnvCache;+}++/**+ * Spawn agent directly (fallback when runner not available).+ * `cleanupWorktreeFn` is passed in to avoid circular imports with agentLifecycle.js.+ * `isTruthyMetaFn` is passed in to avoid circular imports with subAgentSpawner.js.+ */+export async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, agentDir, executionId, laneName, { cleanupWorktreeFn, isTruthyMetaFn }) {+ const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;++ const ROOT_DIR = PATHS.root;+ // Ensure workspacePath is valid+ const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;++ // For Claude CLI providers, inject ~/.claude/settings.json env vars so Bedrock config+ // (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.) is present even if PM2 lacks them+ const claudeSettingsEnv = isClaudeCliProvider(provider)+ ? await getClaudeSettingsEnv()+ : {};++ const claudeProcess = spawn(cliConfig.command, cliConfig.args, {+ cwd,+ shell: false,+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; return e; })()+ });++ registerSpawnedAgent(claudeProcess.pid, {+ fullCommand,+ agentId,+ taskId: task.id,+ model,+ workspacePath,+ prompt: (task.description || '').substring(0, 500)+ });++ claudeProcess.stdin.write(prompt);+ claudeProcess.stdin.end();++ activeAgents.set(agentId, {+ process: claudeProcess,+ taskId: task.id,+ startedAt: Date.now(),+ runId,+ pid: claudeProcess.pid,+ providerId: provider.id,+ executionId,+ laneName+ });++ // Store PID in persisted state for zombie detection+ await updateAgent(agentId, { pid: claudeProcess.pid });++ let outputBuffer = '';+ let rawStreamBuffer = ''; // Raw stdout for stream-json (used for error analysis)+ let hasStartedWorking = false;+ const outputFile = join(agentDir, 'output.txt');+ const isStreamJson = cliConfig.streamFormat === 'stream-json';+ const streamParser = isStreamJson ? createStreamJsonParser() : null;++ // If no output after 3 seconds, transition from initializing to working to show progress+ const initializationTimeout = setTimeout(async () => {+ if (!hasStartedWorking && activeAgents.has(agentId)) {+ hasStartedWorking = true;+ await updateAgent(agentId, { metadata: { phase: 'working' } });+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });+ }+ }, 3000);++ claudeProcess.stdout.on('data', async (data) => {+ const text = data.toString();++ if (!hasStartedWorking) {+ hasStartedWorking = true;+ await updateAgent(agentId, { metadata: { phase: 'working' } });+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });+ }++ if (streamParser) {+ // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)+ rawStreamBuffer += text;+ if (rawStreamBuffer.length > 512 * 1024) {+ rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);+ }+ const lines = streamParser.processChunk(text);+ for (const line of lines) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);+ }+ await writeFile(outputFile, outputBuffer).catch(() => {});+ } else {+ // Non-stream providers: emit raw stdout as before+ outputBuffer += text;+ await writeFile(outputFile, outputBuffer).catch(() => {});+ await appendAgentOutput(agentId, text);+ }+ });++ claudeProcess.stderr.on('data', async (data) => {+ const text = data.toString();+ // Codex stderr: show thinking + tool names, skip config dump and command output+ if (provider.id === 'codex') {+ for (const line of text.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ if (trimmed.startsWith('Reading prompt from stdin')) continue;+ if (trimmed.startsWith('OpenAI Codex v')) continue;+ if (trimmed.startsWith('succeeded in')) continue;+ // Tool calls: show just the command, strip output after "succeeded"+ if (trimmed.startsWith('exec ')) {+ const match = trimmed.match(/^exec\s+\S+\s+-lc\s+(['"])(.*?)\1/);+ const cmd = match ? match[2] : trimmed.split(' in /')[0];+ const display = `🔧 ${cmd}`;+ outputBuffer += display + '\n';+ await appendAgentOutput(agentId, display);+ continue;+ }+ // Skip long lines (command output like file contents, directory listings)+ if (trimmed.length > 300) continue;+ outputBuffer += trimmed + '\n';+ await appendAgentOutput(agentId, trimmed);+ }+ await writeFile(outputFile, outputBuffer).catch(() => {});+ return;+ }+ outputBuffer += `[stderr] ${text}`;+ await writeFile(outputFile, outputBuffer).catch(() => {});+ await appendAgentOutput(agentId, `[stderr] ${text}`);+ });++ claudeProcess.on('error', async (err) => {+ clearTimeout(initializationTimeout);+ console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);++ // Release execution lane+ if (laneName) {+ release(agentId);+ }++ // Complete tool execution tracking with error+ if (executionId) {+ errorExecution(executionId, { message: err.message, category: 'spawn-error' });+ completeExecution(executionId, { success: false });+ }++ cosEvents.emit('agent:error', { agentId, error: err.message });+ await completeAgent(agentId, { success: false, error: err.message });+ await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });+ unregisterSpawnedAgent(claudeProcess.pid);+ activeAgents.delete(agentId);+ });++ claudeProcess.on('close', async (code) => {+ clearTimeout(initializationTimeout);+ const success = code === 0;+ const agentData = activeAgents.get(agentId);+ const duration = Date.now() - (agentData?.startedAt || Date.now());++ // Flush remaining stream parser data+ if (streamParser) {+ const remaining = streamParser.flush();+ for (const line of remaining) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);+ }+ // Use the parsed final result for the output file if available+ const finalResult = streamParser.getFinalResult();+ if (finalResult) {+ outputBuffer = finalResult;+ }+ }++ // Release execution lane+ if (agentData?.laneName) {+ release(agentId);+ }++ // Complete tool execution tracking+ if (agentData?.executionId) {+ if (success) {+ completeExecution(agentData.executionId, { success: true, duration });+ } else {+ errorExecution(agentData.executionId, { message: `Agent exited with code ${code}`, code });+ completeExecution(agentData.executionId, { success: false });+ }+ }++ await writeFile(outputFile, outputBuffer).catch(() => {});++ // Use raw stream buffer for error analysis (contains full JSON with error details)+ const analysisBuffer = rawStreamBuffer || outputBuffer;+ const errorAnalysis = success ? null : analyzeAgentFailure(analysisBuffer, task, model);++ await completeAgent(agentId, {+ success,+ exitCode: code,+ duration,+ outputLength: outputBuffer.length,+ errorAnalysis+ });++ await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis);++ // Update task status with retry tracking+ // Skip if user-terminated — task already blocked by terminateAgent/killAgent+ if (userTerminatedAgents.has(agentId)) {+ userTerminatedAgents.delete(agentId);+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Terminated by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ } else if (success) {+ await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');+ } else {+ const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);+ await updateTask(task.id, failedUpdate, task.taskType || 'user');++ // Handle provider status updates on failure+ if (errorAnalysis) {+ if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {+ const providerId = agentData?.providerId || provider.id;+ if (providerId) {+ await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });+ });+ }+ }+ if (errorAnalysis.category === 'rate-limit') {+ const providerId = agentData?.providerId || provider.id;+ if (providerId) {+ await markProviderRateLimited(providerId).catch(err => {+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });+ });+ }+ }+ }+ }++ // Process memory extraction and app cooldown+ await processAgentCompletion(agentId, task, success, outputBuffer);++ // Clean up ephemeral BTW.md before worktree removal+ if (workspacePath) {+ await rm(join(workspacePath, 'BTW.md')).catch(() => {});+ }++ // Clean up worktree if agent was using one+ await cleanupWorktreeFn(agentId, success, {+ openPR: isTruthyMetaFn(task.metadata?.openPR),+ description: task.description,+ agentOutput: outputBuffer+ });++ unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);+ activeAgents.delete(agentId);+ });++ return agentId;+}diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.jsnew file mode 100644index 0000000000..4c3d3f3dcf--- /dev/null+++ b/server/services/agentCompletion.js@@ -0,0 +1,54 @@+/**+ * Agent Completion Helpers+ *+ * Post-completion tasks shared between runner mode (handleAgentCompletion)+ * and direct mode (spawnDirectly): memory extraction and app cooldown.+ */++import { updateAgent } from './cosAgents.js';+import { getConfig } from './cos.js';+import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';+import { emitLog } from './cosEvents.js';+import { extractAndStoreMemories } from './memoryExtractor.js';++/**+ * Process post-completion tasks: memory extraction and app cooldown.+ * Shared between handleAgentCompletion (runner mode) and spawnDirectly (direct mode).+ */+export async function processAgentCompletion(agentId, task, success, outputBuffer) {+ // Extract memories from successful output+ if (success && outputBuffer.length > 100) {+ const memoryResult = await extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {+ console.log(`⚠️ Memory extraction failed: ${err.message}`);+ return { created: 0, pendingApproval: 0 };+ });+ if (memoryResult.created > 0 || memoryResult.pendingApproval > 0) {+ await updateAgent(agentId, {+ memoryExtraction: {+ created: memoryResult.created,+ pendingApproval: memoryResult.pendingApproval,+ extractedAt: new Date().toISOString()+ }+ });+ }+ }++ // Handle app cooldown+ const appId = task.metadata?.app;+ if (appId) {+ const config = await getConfig();+ const cooldownMs = config.appReviewCooldownMs || 3600000;++ const issuesFound = success ? 1 : 0;+ const issuesFixed = success ? 1 : 0;+ await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {+ emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });+ });++ await startAppCooldown(appId, cooldownMs).catch(err => {+ emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });+ });++ emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });+ }+}diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsnew file mode 100644index 0000000000..25dadb7641--- /dev/null+++ b/server/services/agentErrorAnalysis.js@@ -0,0 +1,568 @@+/**+ * Agent Error Analysis+ *+ * Pattern-based failure analysis, investigation task creation, and+ * failed-task status resolution for CoS agents.+ */++import { emitLog } from './cosEvents.js';+import { addTask, updateTask } from './cos.js';+import { cosEvents } from './cosEvents.js';+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';++// Max retries before blocking a task+export const MAX_TASK_RETRIES = 3;++/**+ * Error patterns that warrant investigation tasks.+ * Patterns are checked in order — first match wins.+ * Categories help the learning system identify failure trends.+ */+export const ERROR_PATTERNS = [+ // ===== API & Authentication Errors =====+ {+ pattern: /API Error: 404.*model:\s*(\S+)/i,+ category: 'model-not-found',+ actionable: true,+ extract: (match, output, task, model) => ({+ message: `Model "${match[1]}" not found`,+ suggestedFix: `Update model configuration - "${match[1]}" doesn't exist. Check provider settings or task metadata.`,+ affectedModel: match[1],+ configuredModel: model+ })+ },+ {+ pattern: /API Error: 401|authentication|unauthorized/i,+ category: 'auth-error',+ actionable: true,+ extract: () => ({+ message: 'Authentication failed',+ suggestedFix: 'Check API keys and provider configuration'+ })+ },+ {+ pattern: /API Error: 429|rate.?limit|too many requests/i,+ category: 'rate-limit',+ actionable: false, // Transient, retry will handle+ extract: () => ({+ message: 'Rate limit exceeded',+ suggestedFix: 'Wait and retry - temporary rate limiting'+ })+ },+ {+ // Catches both "hit your usage limit" and session limits like "hit your limit · resets 6am"+ pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit)/i,+ category: 'usage-limit',+ actionable: true, // Need to switch provider+ extract: (match, output) => {+ const timeMatch = output.match(/(?:try again in|resets?)\s+(.+?)(?:\.|·|\n|$)/im);+ const waitTime = timeMatch ? timeMatch[1].trim() : null;+ return {+ message: `Usage limit exceeded${waitTime ? ` - retry in ${waitTime}` : ''}`,+ suggestedFix: 'Provider usage limit reached. Using fallback provider or wait for limit reset.',+ waitTime,+ requiresFallback: true+ };+ }+ },+ {+ pattern: /API Error: 400|invalid_request_error|bad.?request/i,+ category: 'bad-request',+ actionable: true,+ extract: (match, output) => {+ const msgMatch = output.match(/"message":\s*"([^"]{1,150})"/);+ return {+ message: `Bad request${msgMatch ? `: ${msgMatch[1]}` : ''}`,+ suggestedFix: 'API rejected the request as invalid. Check prompt formatting, tool names, and parameter sizes.'+ };+ }+ },+ {+ pattern: /API Error: 403|forbidden/i,+ category: 'forbidden',+ actionable: true,+ extract: () => ({+ message: 'API access forbidden',+ suggestedFix: 'API key lacks permission for this operation. Check API key permissions and provider configuration.'+ })+ },+ {+ pattern: /API Error: 5\d{2}|server error|internal error/i,+ category: 'server-error',+ actionable: false, // Transient+ extract: () => ({+ message: 'API server error',+ suggestedFix: 'Retry later - temporary server issue'+ })+ },+ {+ pattern: /not_found_error.*model/i,+ category: 'model-not-found',+ actionable: true,+ extract: (match, output, task, model) => ({+ message: `Model not found in API response`,+ suggestedFix: `The model "${model}" specified for this task doesn't exist. Update provider or task configuration.`,+ configuredModel: model+ })+ },++ // ===== Context & Token Errors =====+ {+ pattern: /context.?length|max.?tokens|token.?limit|context.?window/i,+ category: 'context-length',+ actionable: true,+ extract: (match, output) => ({+ message: 'Context length exceeded',+ suggestedFix: 'Task is too large for the context window. Break into smaller subtasks or use a model with larger context.',+ compaction: {+ needed: true,+ reason: 'context-limit',+ outputSize: Buffer.byteLength(output || ''),+ retryHints: [+ 'Summarize intermediate findings concisely instead of reproducing full file contents',+ 'Use targeted reads (offset/limit) instead of reading entire files',+ 'Avoid listing full directory trees — only reference files you modify',+ 'Keep your Task Summary under 30 lines'+ ]+ }+ })+ },+ {+ pattern: /output.?length|max.?output|response.?too.?long/i,+ category: 'output-length',+ actionable: false,+ extract: (match, output) => ({+ message: 'Output length exceeded',+ suggestedFix: 'Agent response exceeded output limit. Task may need to be scoped down.',+ compaction: {+ needed: true,+ reason: 'output-limit',+ outputSize: Buffer.byteLength(output || ''),+ retryHints: [+ 'Limit output to changed files and a brief summary only',+ 'Do not echo file contents back — just reference file paths and line numbers',+ 'Combine related changes into single descriptions'+ ]+ }+ })+ },++ // ===== Tool & MCP Errors =====+ {+ pattern: /tool.?(?:call|use|execution).?(?:failed|error)|failed to (?:call|execute|invoke) tool/i,+ category: 'tool-error',+ actionable: false,+ extract: (match, output) => {+ const toolMatch = output.match(/tool[:\s]+["']?(\w+)["']?/i);+ return {+ message: `Tool execution failed${toolMatch ? `: ${toolMatch[1]}` : ''}`,+ suggestedFix: 'Tool call failed. Check if required dependencies/services are running.'+ };+ }+ },+ {+ pattern: /MCP.?(?:server|connection|error)|mcp.?(?:failed|timeout)/i,+ category: 'mcp-error',+ actionable: false,+ extract: () => ({+ message: 'MCP server error',+ suggestedFix: 'MCP server connection failed. Verify MCP servers are configured and accessible.'+ })+ },+ {+ pattern: /permission.?denied|access.?denied|not.?allowed|insufficient.?permissions/i,+ category: 'permission-denied',+ actionable: true,+ extract: () => ({+ message: 'Permission denied',+ suggestedFix: 'Agent lacks permissions for the requested operation. Check file/directory permissions.'+ })+ },++ // ===== Git & Repository Errors =====+ {+ pattern: /git.?(?:conflict|merge.?conflict)|CONFLICT.*both modified|merge.?failed/i,+ category: 'git-conflict',+ actionable: true,+ extract: () => ({+ message: 'Git merge conflict',+ suggestedFix: 'Merge conflict detected. Resolve conflicts manually before retrying.'+ })+ },+ {+ pattern: /fatal:\s*(?:not a git repository|could not|failed to|unable to)/i,+ category: 'git-error',+ actionable: false,+ extract: (match, output) => {+ const detailMatch = output.match(/fatal:\s*(.+?)(?:\n|$)/i);+ return {+ message: `Git error${detailMatch ? `: ${detailMatch[1].substring(0, 60)}` : ''}`,+ suggestedFix: 'Git operation failed. Verify the repository state and try again.'+ };+ }+ },+ {+ pattern: /nothing.?to.?commit|no.?changes|working.?tree.?clean/i,+ category: 'no-changes',+ actionable: false,+ extract: () => ({+ message: 'No changes to commit',+ suggestedFix: 'Agent completed but made no code changes. Task may already be done or description needs clarification.'+ })+ },++ // ===== Build & Test Errors =====+ {+ pattern: /npm.?ERR!|yarn.?error|pnpm.?(?:ERR|error)/i,+ category: 'npm-error',+ actionable: false,+ extract: (match, output) => {+ const errMatch = output.match(/(?:npm|yarn|pnpm).?(?:ERR!|error)[:\s]*(.+?)(?:\n|$)/i);+ return {+ message: `Package manager error${errMatch ? `: ${errMatch[1].substring(0, 50)}` : ''}`,+ suggestedFix: 'Package installation or script failed. Check package.json and dependencies.'+ };+ }+ },+ {+ pattern: /test.?(?:failed|failure)|(?:failed|failing).?tests?|FAIL\s+\w+\.test/i,+ category: 'test-failure',+ actionable: false,+ extract: () => ({+ message: 'Tests failed',+ suggestedFix: 'One or more tests failed. Review test output and fix failing assertions.'+ })+ },+ {+ pattern: /lint.?(?:error|failed)|eslint.?error|prettier.?error/i,+ category: 'lint-error',+ actionable: false,+ extract: () => ({+ message: 'Linting failed',+ suggestedFix: 'Code style/lint errors detected. Fix formatting issues and retry.'+ })+ },+ {+ pattern: /build.?failed|compilation.?(?:failed|error)|typescript.?error|tsc.+error/i,+ category: 'build-error',+ actionable: false,+ extract: () => ({+ message: 'Build failed',+ suggestedFix: 'Build/compilation failed. Fix syntax or type errors and retry.'+ })+ },++ // ===== Process & System Errors =====+ {+ pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,+ category: 'network-error',+ actionable: false,+ extract: () => ({+ message: 'Network connection failed',+ suggestedFix: 'Check network connectivity and service availability.'+ })+ },+ {+ pattern: /ENOENT|file.?not.?found|no.?such.?file/i,+ category: 'file-not-found',+ actionable: false,+ extract: (match, output) => {+ const pathMatch = output.match(/(?:ENOENT|not.?found)[:\s]*['"]?([^'"}\s]+)['"]?/i);+ return {+ message: `File not found${pathMatch ? `: ${pathMatch[1].substring(0, 40)}` : ''}`,+ suggestedFix: 'Expected file/directory does not exist. Verify paths in the task description.'+ };+ }+ },+ {+ pattern: /ENOMEM|out.?of.?memory|heap.?(?:out|limit)|memory.?(?:limit|exceeded)/i,+ category: 'memory-error',+ actionable: true,+ extract: () => ({+ message: 'Out of memory',+ suggestedFix: 'Process ran out of memory. Task may be too large or there is a memory leak.'+ })+ },+ {+ pattern: /timeout|timed.?out|deadline.?exceeded/i,+ category: 'timeout',+ actionable: false,+ extract: () => ({+ message: 'Operation timed out',+ suggestedFix: 'Task took too long to complete. Consider breaking into smaller subtasks.'+ })+ },+ {+ pattern: /(?:killed|terminated).?(?:by.?signal|SIGTERM|SIGKILL)/i,+ category: 'process-killed',+ actionable: false,+ extract: () => ({+ message: 'Process killed',+ suggestedFix: 'Agent process was terminated. May have exceeded resource limits or was killed externally.'+ })+ },+ {+ pattern: /spawn.?(?:error|failed)|EACCES|command.?not.?found/i,+ category: 'spawn-error',+ actionable: true,+ extract: () => ({+ message: 'Command spawn failed',+ suggestedFix: 'Failed to start subprocess. Check that required CLI tools are installed and accessible.'+ })+ },++ // ===== Playwright & Browser Errors =====+ {+ pattern: /playwright|browser.?(?:crashed|closed|disconnected)/i,+ category: 'browser-error',+ actionable: false,+ extract: () => ({+ message: 'Browser automation failed',+ suggestedFix: 'Playwright browser crashed or disconnected. Check if the dev server is running.'+ })+ },+ {+ pattern: /locator.?(?:timeout|not.?found)|element.?not.?(?:found|visible)/i,+ category: 'locator-error',+ actionable: false,+ extract: () => ({+ message: 'UI element not found',+ suggestedFix: 'Could not find expected element on page. UI may have changed or selector is wrong.'+ })+ },++ // ===== Agent-Specific Errors =====+ {+ pattern: /(?:claude|anthropic).?(?:error|failed)|overloaded_error/i,+ category: 'claude-error',+ actionable: false,+ extract: () => ({+ message: 'Claude API error',+ suggestedFix: 'Claude API returned an error. This is usually transient - retry recommended.'+ })+ },+ {+ pattern: /invalid.?(?:json|syntax)|JSON\.parse|SyntaxError/i,+ category: 'parse-error',+ actionable: false,+ extract: () => ({+ message: 'JSON/Syntax parse error',+ suggestedFix: 'Failed to parse response or file. Check for malformed JSON or syntax errors.'+ })+ },+ {+ pattern: /task.?(?:rejected|declined|refused)|cannot.?(?:complete|perform)/i,+ category: 'task-rejected',+ actionable: true,+ extract: () => ({+ message: 'Agent rejected task',+ suggestedFix: 'Agent could not or would not complete the task. Rephrase or simplify the request.'+ })+ },++ // ===== Limit & Billing Errors =====+ {+ pattern: /(?:maximum|max).*(?:turns?|iterations?|steps?)|turn.?limit|max.?turns|stopped after \d+ turns/i,+ category: 'turn-limit',+ actionable: false,+ extract: () => ({+ message: 'Agent reached turn limit',+ suggestedFix: 'Task exceeded the maximum number of agent turns. Break into smaller subtasks or increase turn limit.'+ })+ },+ {+ pattern: /(?:billing|subscription|payment).?(?:error|issue|required|expired|failed)/i,+ category: 'billing-error',+ actionable: true,+ extract: () => ({+ message: 'Billing/subscription issue',+ suggestedFix: 'Provider billing or subscription problem. Check provider account status.'+ })+ },++ // ===== Safety & Content Errors =====+ {+ pattern: /content.?(?:filter|policy)|safety.?(?:filter|block)|harmful.?content/i,+ category: 'content-filtered',+ actionable: true,+ extract: () => ({+ message: 'Content filtered',+ suggestedFix: 'Request was blocked by content safety filter. Rephrase the task description.'+ })+ }+];++/**+ * Analyze agent failure output and categorize the error.+ */+export function analyzeAgentFailure(output, task, model) {+ // Agent produced no meaningful output — likely failed to start+ if (!output || output.trim().length < 50) {+ return {+ category: 'startup-failure',+ actionable: false,+ message: 'Agent failed to start or produced no output',+ suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.'+ };+ }++ for (const errorDef of ERROR_PATTERNS) {+ const match = output.match(errorDef.pattern);+ if (match) {+ const extracted = errorDef.extract(match, output, task, model);+ return {+ category: errorDef.category,+ actionable: errorDef.actionable,+ ...extracted+ };+ }+ }++ // No pattern matched — extract meaningful context from the output+ const lines = output.split('\n').filter(l => l.trim());+ const lastLines = lines.slice(-20);++ const errorKeywords = /\b(error|fail|exception|fatal|panic|abort|crash|denied|refused|invalid|cannot|could not|unable to)\b/i;+ const errorLines = lastLines.filter(l => errorKeywords.test(l)).slice(0, 5);++ const contextLines = errorLines.length > 0 ? errorLines : lastLines.slice(-5);+ const summary = contextLines[0]?.trim().substring(0, 120) || 'Agent failed with unrecognized error';++ return {+ category: 'unknown',+ actionable: false,+ message: summary,+ details: contextLines.map(l => l.trim()).join('\n'),+ suggestedFix: 'Error did not match known patterns. Review the details or agent output logs.'+ };+}++/**+ * Create an investigation task in COS-TASKS.md for a failed agent.+ */+export async function createInvestigationTask(agentId, originalTask, errorAnalysis) {+ const description = `[Auto] Investigate agent failure: ${errorAnalysis.message}++**Failed Agent**: ${agentId}+**Original Task**: ${originalTask.id} - ${(originalTask.description || '').substring(0, 100)}+**Error Category**: ${errorAnalysis.category}+**Suggested Fix**: ${errorAnalysis.suggestedFix}+${errorAnalysis.configuredModel ? `**Configured Model**: ${errorAnalysis.configuredModel}` : ''}+${errorAnalysis.affectedModel ? `**Affected Model**: ${errorAnalysis.affectedModel}` : ''}++Review the error, fix the configuration or code issue, and retry the original task.`;++ const investigationTask = await addTask({+ description,+ priority: 'HIGH',+ context: `Auto-generated from agent ${agentId} failure`,+ approvalRequired: true // Require human approval before auto-fixing+ }, 'internal');++ emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId}`, {+ agentId,+ taskId: investigationTask.id,+ errorCategory: errorAnalysis.category+ });++ cosEvents.emit('investigation:created', {+ investigationTaskId: investigationTask.id,+ failedAgentId: agentId,+ originalTaskId: originalTask.id,+ errorAnalysis+ });++ return investigationTask;+}++// Error categories where LLM API access is blocked or denied — spawning an+// investigation agent would fail for the same reason, so skip it.+export const API_ACCESS_ERROR_CATEGORIES = new Set([+ 'auth-error',+ 'forbidden',+ 'usage-limit',+]);++export async function maybeCreateInvestigationTask(agentId, task, analysis) {+ if (API_ACCESS_ERROR_CATEGORIES.has(analysis?.category)) {+ emitLog('debug', `⏭️ Skipping investigation task for ${task.id}: API access error (${analysis.category})`, { agentId, taskId: task.id, category: analysis.category });+ return;+ }+ await createInvestigationTask(agentId, task, analysis).catch(err => {+ emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId, taskId: task.id, category: analysis?.category });+ });+}++/**+ * Handle task status update after agent failure.+ * Tracks retry count and blocks the task after MAX_TASK_RETRIES,+ * creating an investigation task instead of retrying endlessly.+ *+ * Returns { status, metadata } to apply to the task.+ */+export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {+ // Actionable errors get blocked immediately (investigation task created unless API access is denied)+ if (errorAnalysis?.actionable) {+ emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {+ taskId: task.id, category: errorAnalysis.category+ });+ await maybeCreateInvestigationTask(agentId, task, errorAnalysis);+ return {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: errorAnalysis.message,+ blockedCategory: errorAnalysis.category,+ blockedAt: new Date().toISOString()+ }+ };+ }++ // Non-actionable errors: track retry count and block after max retries+ const failureCount = (Number(task.metadata?.failureCount) || 0) + 1;+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;+ const lastErrorCategory = errorAnalysis?.category || 'unknown';++ if (totalSpawns >= MAX_TOTAL_SPAWNS || failureCount >= MAX_TASK_RETRIES) {+ emitLog('warn', `🚫 Task ${task.id} blocked after ${failureCount} failures (${lastErrorCategory})`, {+ taskId: task.id, failureCount, category: lastErrorCategory+ });+ const blockedAnalysis = {+ ...(errorAnalysis || {}),+ message: `Task failed ${failureCount} times: ${errorAnalysis?.message || 'unknown error'}`,+ suggestedFix: `Task has failed ${failureCount} consecutive times with ${lastErrorCategory} errors. ${errorAnalysis?.suggestedFix || 'Investigate agent output logs.'}`,+ category: lastErrorCategory+ };+ await maybeCreateInvestigationTask(agentId, task, blockedAnalysis);+ return {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ failureCount,+ lastFailureAt: new Date().toISOString(),+ lastErrorCategory,+ blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,+ blockedCategory: lastErrorCategory,+ blockedAt: new Date().toISOString()+ }+ };+ }++ emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} (${lastErrorCategory})`, {+ taskId: task.id, failureCount, maxRetries: MAX_TASK_RETRIES, category: lastErrorCategory+ });++ // Propagate compaction hints to task metadata for retry prompt injection+ const compaction = errorAnalysis?.compaction || null;++ return {+ status: 'pending',+ metadata: {+ ...task.metadata,+ failureCount,+ lastFailureAt: new Date().toISOString(),+ lastErrorCategory,+ ...(compaction && { compaction })+ }+ };+}diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsnew file mode 100644index 0000000000..c5efcf457b--- /dev/null+++ b/server/services/agentLifecycle.js@@ -0,0 +1,1154 @@+/**+ * Agent Lifecycle+ *+ * Handles agent spawning, runner synchronization, pipeline progression,+ * agent completion, and worktree cleanup.+ */++import { join, relative, resolve, sep } from 'path';+import { readFile, unlink, rm } from 'fs/promises';+import { existsSync } from 'fs';+import { execSync } from 'child_process';+import { cosEvents, emitLog } from './cosEvents.js';+import { registerAgent, updateAgent, completeAgent, appendAgentOutput } from './cosAgents.js';+import { getConfig, updateTask, addTask, getTaskById, checkStagePrecondition } from './cos.js';+import { spawnAgentViaRunner, getActiveAgentsFromRunner, getRunnerHealth } from './cosRunnerClient.js';+import { getActiveProvider, getAllProviders, getProviderById } from './providers.js';+import { isProviderAvailable, markProviderUsageLimit, markProviderRateLimited, getFallbackProvider, getProviderStatus } from './providerStatus.js';+import { PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS } from '../lib/validation.js';+import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { getAppById } from './apps.js';+import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';+import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';+import { detectConflicts } from './taskConflict.js';+import { createWorktree, removeWorktree } from './worktreeManager.js';+import * as jiraService from './jira.js';+import * as git from './git.js';+import { analyzeAgentFailure } from './agentErrorAnalysis.js';+import { resolveFailedTaskUpdate } from './agentErrorAnalysis.js';+import { completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';+import { createAgentRun } from './agentRunTracking.js';+import { buildAgentPrompt, getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';+import { buildCliSpawnConfig, isClaudeCliProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';+import { selectModelForTask } from './agentModelSelection.js';+import { processAgentCompletion } from './agentCompletion.js';+import { activeAgents, runnerAgents, spawningTasks, useRunner } from './agentState.js';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { writeFile } from 'fs/promises';++const ROOT_DIR = PATHS.root;+const AGENTS_DIR = PATHS.cosAgents;++// Metadata booleans may arrive as true/'true' or false/'false' (from JSON vs TASKS.md string round-trip)+const isTruthyMeta = (value) => value === true || value === 'true';+const isFalsyMeta = (value) => value === false || value === 'false';++/**+ * Remove BTW.md from agent workspace after completion.+ * Prevents ephemeral context files from being committed to git.+ */+async function cleanupBtwFile(workspacePath) {+ if (!workspacePath) return;+ const btwPath = join(workspacePath, 'BTW.md');+ await rm(btwPath).catch(() => {});+}++/**+ * Sync running agents from the runner (recovery after server restart).+ * This allows us to receive completion events for agents spawned before restart.+ */+export async function syncRunnerAgents() {+ const agents = await getActiveAgentsFromRunner().catch(err => {+ console.error(`❌ Failed to get active agents from runner: ${err.message}`);+ return [];+ });+ if (agents.length === 0) return 0;++ console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);++ // Get all tasks to find task data for each agent+ const { getAllTasks } = await import('./cos.js');+ const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));++ // Build a task lookup map from all task sources, tagging each with its taskType+ const taskMap = new Map();+ const addTasks = (groupedTasks, taskType) => {+ if (!groupedTasks) return;+ for (const tasks of Object.values(groupedTasks)) {+ if (Array.isArray(tasks)) {+ for (const task of tasks) {+ taskMap.set(task.id, { ...task, taskType });+ }+ }+ }+ };++ addTasks(allTasksData.user?.grouped, 'user');+ addTasks(allTasksData.cos?.grouped, 'internal');++ let syncedCount = 0;+ for (const agent of agents) {+ // Only sync if not already tracked+ if (!runnerAgents.has(agent.id)) {+ const task = taskMap.get(agent.taskId);++ // Infer taskType for fallback: sys- prefix tasks are internal (CoS-generated)+ const inferredType = agent.taskId?.startsWith('sys-') ? 'internal' : 'user';+ runnerAgents.set(agent.id, {+ taskId: agent.taskId,+ task: task || { id: agent.taskId, taskType: inferredType, description: 'Recovered from runner' },+ runId: null, // Run tracking may be lost on restart+ model: null,+ hasStartedWorking: true,+ startedAt: agent.startedAt+ });+ console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);+ syncedCount++;+ }+ }++ return syncedCount;+}++/**+ * Spawn an agent for a task.+ */+export async function spawnAgentForTask(task) {+ if (spawningTasks.has(task.id)) {+ console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);+ return null;+ }++ // Check total spawn count across all retry types to prevent runaway respawning+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;+ if (totalSpawns >= MAX_TOTAL_SPAWNS) {+ console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`,+ blockedCategory: 'max-spawns',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user').catch(() => {});+ return null;+ }++ spawningTasks.add(task.id);++ const agentId = `agent-${uuidv4().slice(0, 8)}`;++ // Determine execution lane and acquire slot+ const laneName = determineLane(task);+ if (!hasCapacity(laneName)) {+ // Wait for lane availability (max 30 seconds)+ const laneResult = await waitForLane(laneName, agentId, { timeoutMs: 30000, metadata: { taskId: task.id } });+ if (!laneResult.success) {+ spawningTasks.delete(task.id);+ emitLog('warn', `Lane ${laneName} unavailable for task ${task.id}, deferring`, { taskId: task.id, lane: laneName });+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'lane-capacity', lane: laneName });+ return null;+ }+ } else {+ const laneResult = acquire(laneName, agentId, { taskId: task.id });+ if (!laneResult.success) {+ spawningTasks.delete(task.id);+ emitLog('warn', `Failed to acquire lane ${laneName}: ${laneResult.error}`, { taskId: task.id });+ return null;+ }+ }++ // Create tool execution for state tracking+ const toolExecution = createToolExecution('agent-spawn', agentId, {+ taskId: task.id,+ lane: laneName,+ priority: task.priority+ });+ startExecution(toolExecution.id);++ // Helper to cleanup on early exit+ const cleanupOnError = (error) => {+ spawningTasks.delete(task.id);+ release(agentId);+ errorExecution(toolExecution.id, { message: error });+ completeExecution(toolExecution.id, { success: false });+ };++ // Get configuration+ const config = await getConfig();+ let provider = await getActiveProvider();++ if (!provider) {+ cleanupOnError('No active AI provider configured');+ cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });+ return null;+ }++ // Check provider availability (usage limits, rate limits, etc.)+ const providerAvailable = isProviderAvailable(provider.id);+ if (!providerAvailable) {+ const status = getProviderStatus(provider.id);+ emitLog('warn', `Provider ${provider.id} unavailable: ${status.message}`, {+ taskId: task.id,+ providerId: provider.id,+ reason: status.reason+ });++ // Try to get a fallback provider (check task-level, then provider-level, then system default)+ const allProviders = await getAllProviders();+ const taskFallbackId = task.metadata?.fallbackProvider;+ const fallbackResult = await getFallbackProvider(provider.id, allProviders, taskFallbackId);++ if (fallbackResult) {+ emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {+ taskId: task.id,+ primaryProvider: provider.id,+ fallbackProvider: fallbackResult.provider.id,+ fallbackSource: fallbackResult.source+ });+ provider = fallbackResult.provider;+ } else {+ const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;+ cleanupOnError(errorMsg);+ cosEvents.emit('agent:error', {+ taskId: task.id,+ error: errorMsg,+ providerId: provider.id,+ providerStatus: status+ });+ return null;+ }+ }++ // Check if user specified a different provider in task metadata+ const userProviderId = task.metadata?.provider;+ if (userProviderId && userProviderId !== provider.id) {+ const userProvider = await getProviderById(userProviderId);+ if (userProvider) {+ emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });+ provider = userProvider;+ } else {+ emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });+ }+ }++ // Select optimal model for this task (async to allow learning-based suggestions)+ const modelSelection = await selectModelForTask(task, provider);+ let selectedModel = modelSelection.model;++ // Validate model is compatible with provider+ if (selectedModel && provider.models && provider.models.length > 0) {+ const modelIsValid = provider.models.includes(selectedModel);+ if (!modelIsValid) {+ emitLog('warn', `Model "${selectedModel}" not valid for provider "${provider.id}", falling back to provider default`, {+ taskId: task.id,+ requestedModel: selectedModel,+ providerId: provider.id,+ validModels: provider.models+ });+ selectedModel = modelSelection.tier === 'heavy' ? provider.heavyModel :+ modelSelection.tier === 'light' ? provider.lightModel :+ modelSelection.tier === 'medium' ? provider.mediumModel :+ provider.defaultModel;+ }+ }++ const logMessage = modelSelection.learningReason+ ? `Model selection: ${selectedModel} (${modelSelection.reason} - ${modelSelection.learningReason})`+ : `Model selection: ${selectedModel} (${modelSelection.reason})`;+ emitLog('info', logMessage, {+ taskId: task.id,+ model: selectedModel,+ tier: modelSelection.tier,+ reason: modelSelection.reason,+ ...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })+ });++ // Determine workspace path and resolve app name+ const isReadOnly = isTruthyMeta(task.metadata?.readOnly);+ let workspacePath = task.metadata?.app+ ? await getAppWorkspace(task.metadata.app)+ : ROOT_DIR;+ const resolvedAppName = task.metadata?.app+ ? (await getAppById(task.metadata.app).catch(() => null))?.name || null+ : null;++ let jiraTicket = null;+ let jiraBranchName = null;+ let worktreeInfo = null;+ const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);+ const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;++ if (!isReadOnly) {+ // Pull latest from git before starting work+ const pullResult = await git.ensureLatest(workspacePath).catch(err => {+ emitLog('warn', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });+ return { success: false, error: err.message };+ });++ if (pullResult.skipped) {+ emitLog('debug', `Pre-task git pull skipped: ${pullResult.skipped}`, { taskId: task.id, workspace: workspacePath });+ } else if (pullResult.conflict) {+ emitLog('warn', `🔀 Git conflict in ${workspacePath} (branch: ${pullResult.branch}): ${pullResult.error}`, {+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch+ });++ const appId = task.metadata?.app || null;+ const conflictDesc = `Resolve git conflict in ${resolvedAppName || workspacePath} on branch ${pullResult.branch}. `+ + `The branch has diverged from origin and automatic rebase failed. `+ + `Error: ${pullResult.error}`;++ await addTask({+ description: conflictDesc,+ priority: 'HIGH',+ app: appId,+ context: `This conflict is blocking task ${task.id}: "${task.description}". `+ + `Resolve the conflict, commit, and push so the blocked task can proceed.`,+ position: 'top'+ }, 'internal').catch(err => {+ emitLog('warn', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });+ });++ await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});+ cleanupOnError(`Git conflict blocks task — conflict resolution task created`);+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'git-conflict', branch: pullResult.branch });+ return null;+ } else if (pullResult.success && !pullResult.upToDate && !pullResult.skipped) {+ emitLog('info', `📥 Pulled latest for ${resolvedAppName || 'workspace'} (branch: ${pullResult.branch})`, {+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch, stashed: pullResult.stashed+ });+ } else if (!pullResult.success) {+ emitLog('warn', `⚠️ Pre-task git pull error: ${pullResult.error}`, { taskId: task.id, workspace: workspacePath });+ }++ // JIRA integration: create ticket + feature branch if app has JIRA enabled and task opted in+ const appData = await getAppDataForTask(task);++ if (appData?.jira?.enabled && task.metadata?.createJiraTicket) {+ jiraTicket = await createJiraTicketForTask(task, appData);++ if (jiraTicket) {+ const slug = (task.description || 'task')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, '')+ .substring(0, 40);+ jiraBranchName = `feature/${jiraTicket.ticketId}-${slug}`;++ if (task.metadata?.app) {+ await git.fetchOrigin(workspacePath).catch(() => {});+ const { baseBranch: defaultBranch } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));+ if (defaultBranch) {+ await git.checkout(workspacePath, defaultBranch).catch(() => {});+ try { execSync(`git merge --ff-only origin/${defaultBranch}`, { cwd: workspacePath, stdio: 'ignore', windowsHide: true }); } catch (err) { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); }+ }+ }++ await git.createBranch(workspacePath, jiraBranchName).catch(err => {+ emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });+ jiraBranchName = null;+ });++ if (jiraBranchName) {+ emitLog('success', `Created feature branch ${jiraBranchName}`, { taskId: task.id, ticketId: jiraTicket.ticketId });+ }++ task.metadata = {+ ...task.metadata,+ jiraTicketId: jiraTicket.ticketId,+ jiraTicketUrl: jiraTicket.ticketUrl,+ jiraBranch: jiraBranchName,+ jiraInstanceId: appData.jira.instanceId,+ jiraCreatePR: appData.jira.createPR !== false+ };+ }+ }++ // Feature agent tasks: use persistent worktree instead of creating a new one+ if (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {+ const { getFeatureAgent } = await import('./featureAgents.js');+ const fa = await getFeatureAgent(task.metadata.featureAgentId).catch(() => null);+ if (fa) {+ const faWorktreePath = join(PATHS.cos, 'feature-agents', fa.id, 'worktree');+ if (existsSync(faWorktreePath)) {+ workspacePath = faWorktreePath;+ worktreeInfo = {+ worktreePath: faWorktreePath,+ branchName: fa.git.branchName,+ baseBranch: fa.git.baseBranch || 'main',+ isPersistentWorktree: true+ };+ const { mergeBaseIntoFeatureWorktree } = await import('./worktreeManager.js');+ if (fa.git.autoMergeBase) {+ await mergeBaseIntoFeatureWorktree(fa.id, fa.git.baseBranch).catch(err => {+ emitLog('warn', `🌳 Feature agent base merge failed: ${err.message}`, { featureAgentId: fa.id });+ });+ }+ emitLog('info', `🌳 Feature agent ${fa.name} using persistent worktree: ${fa.git.branchName}`, {+ featureAgentId: fa.id, worktreePath: faWorktreePath+ });+ }+ }+ }++ if (explicitWorktree && !jiraBranchName) {+ const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));+ emitLog('info', `🌳 Worktree requested for task ${task.id} — creating isolated worktree from ${detectedBase || 'default branch'}`, {+ taskId: task.id, app: task.metadata?.app, baseBranch: detectedBase+ });++ worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {+ baseBranch: detectedBase || undefined+ }).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} (base: ${worktreeInfo.baseBranch})`, {+ agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch+ });+ }+ } else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {+ 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 });+ }+ }+ } // end !isReadOnly++ // Build the agent prompt (includes worktree and JIRA context if applicable)+ const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta);++ // Create agent directory+ const agentDir = join(AGENTS_DIR, agentId);+ if (!existsSync(agentDir)) {+ await ensureDir(agentDir);+ }++ // Save prompt to file+ await writeFile(join(agentDir, 'prompt.txt'), prompt);++ // Create run entry for usage tracking+ const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);++ // Register the agent with model info+ 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,+ isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,+ taskDescription: task.description,+ taskType: task.taskType,+ priority: task.priority,+ providerId: provider.id,+ model: selectedModel,+ modelTier: modelSelection.tier,+ modelReason: modelSelection.reason,+ runId,+ phase: 'initializing',+ useRunner,+ taskAnalysisType: task.metadata?.analysisType || null,+ taskReviewType: task.metadata?.reviewType || null,+ taskApp: task.metadata?.app || null,+ taskAppName: resolvedAppName,+ selfImprovementType: task.metadata?.selfImprovementType || null,+ jobId: task.metadata?.jobId || null,+ missionName: task.metadata?.missionName || null,+ missionId: task.metadata?.missionId || null,+ jiraTicketId: task.metadata?.jiraTicketId || null,+ jiraTicketUrl: task.metadata?.jiraTicketUrl || null,+ jiraBranch: task.metadata?.jiraBranch || null,+ jiraInstanceId: task.metadata?.jiraInstanceId || null,+ jiraCreatePR: task.metadata?.jiraCreatePR ?? null,+ configOpenPR: isTruthyMeta(task.metadata?.openPR),+ configSimplify: isTruthyMeta(task.metadata?.simplify),+ configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),+ configUseWorktree: !!worktreeInfo,+ configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,+ configCodingOnMain: !worktreeInfo && !jiraBranchName+ });++ emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });++ // Mark the task as in_progress and increment total spawn count+ const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;+ const updateResult = await updateTask(task.id, {+ status: 'in_progress',+ metadata: {+ ...task.metadata,+ totalSpawnCount: newSpawnCount,+ lastSpawnedAt: new Date().toISOString()+ }+ }, task.taskType || 'user')+ .catch(err => {+ console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);+ return null;+ });+ spawningTasks.delete(task.id);+ if (!updateResult) {+ cleanupOnError('Failed to update task status');+ return null;+ }++ // Record autonomous job execution now that the task is confirmed spawning+ if (task.metadata?.autonomousJob && task.metadata?.jobId) {+ cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });+ }++ // 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, worktree: !!worktreeInfo });++ // Use CoS Runner if available, otherwise spawn directly+ if (useRunner) {+ return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, toolExecution.id, laneName);+ }++ // Direct spawn mode (fallback)+ return spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName, {+ cleanupWorktreeFn: cleanupAgentWorktree,+ isTruthyMetaFn: isTruthyMeta+ });+}++/**+ * Minimum runner uptime (seconds) before spawning agents.+ * Prevents race condition during rolling restarts where server starts+ * before runner, spawns an agent, then runner restarts and orphans it.+ */+const RUNNER_MIN_UPTIME_SECONDS = 10;++/**+ * Wait for runner to be stable (sufficient uptime) before spawning.+ */+export async function waitForRunnerStability() {+ const maxWaitMs = 15000;+ const checkIntervalMs = 1000;+ const startTime = Date.now();++ while (Date.now() - startTime < maxWaitMs) {+ const health = await getRunnerHealth();+ if (health.available && health.uptime >= RUNNER_MIN_UPTIME_SECONDS) {+ return true;+ }+ if (health.available && health.uptime < RUNNER_MIN_UPTIME_SECONDS) {+ const waitTime = Math.ceil(RUNNER_MIN_UPTIME_SECONDS - health.uptime);+ emitLog('info', `Waiting ${waitTime}s for runner stability (uptime: ${Math.floor(health.uptime)}s)`, { uptime: health.uptime });+ }+ await new Promise(resolve => setTimeout(resolve, checkIntervalMs));+ }++ emitLog('warn', 'Runner stability check timed out, proceeding anyway', {});+ return false;+}++/**+ * Spawn agent via CoS Runner (isolated PM2 process).+ */+export async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, executionId, laneName) {+ // Wait for runner to be stable to prevent orphaned agents during rolling restarts+ await waitForRunnerStability();++ const agentInfo = {+ taskId: task.id,+ task,+ runId,+ model,+ providerId: provider.id,+ hasStartedWorking: false,+ startedAt: Date.now(),+ initializationTimeout: null,+ executionId,+ laneName,+ workspacePath+ };+ runnerAgents.set(agentId, agentInfo);++ // If no output after 3 seconds, transition from initializing to working to show progress+ agentInfo.initializationTimeout = setTimeout(async () => {+ const agent = runnerAgents.get(agentId);+ if (agent && !agent.hasStartedWorking) {+ agent.hasStartedWorking = true;+ await updateAgent(agentId, { metadata: { phase: 'working' } });+ emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });+ }+ }, 3000);++ // For Claude CLI providers, merge ~/.claude/settings.json env vars so Bedrock config is present+ const claudeSettingsEnv = isClaudeCliProvider(provider)+ ? await getClaudeSettingsEnv()+ : {};++ const result = await spawnAgentViaRunner({+ agentId,+ taskId: task.id,+ prompt,+ workspacePath,+ model,+ envVars: { ...claudeSettingsEnv, ...provider.envVars },+ cliCommand: cliConfig.command,+ cliArgs: cliConfig.args+ });++ // Store PID in persisted state for zombie detection+ await updateAgent(agentId, { pid: result.pid });++ emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });+ return agentId;+}++/**+ * Extract the final summary section from agent output.+ * Walks backwards from the end to find the last block of non-tool-call content.+ */+export function extractFinalSummary(outputBuffer) {+ if (!outputBuffer) return null;++ const lines = outputBuffer.split('\n');+ const contentLines = [];+ let foundContent = false;++ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i];+ const isTool = line.startsWith('🔧') || line.startsWith(' →') || line.startsWith(' ↳') || line.startsWith('[stderr]');++ if (!isTool && line.trim()) {+ contentLines.unshift(line);+ foundContent = true;+ } else if (foundContent && isTool) {+ break;+ }+ }++ const summary = contentLines.join('\n').trim();+ return summary || null;+}++/**+ * Extract a concise output summary for pipeline stage agents.+ * For review stages: reads the generated REVIEW.md from the workspace.+ * For implement stages: extracts the final summary from the output.+ */+export async function extractPipelineOutputSummary(task, workspacePath, outputBuffer) {+ const pipeline = task.metadata?.pipeline;+ if (!pipeline?.stages) return null;++ const currentStage = pipeline.currentStage ?? 0;+ const stage = pipeline.stages[currentStage];+ if (!stage) return null;++ const promptKey = stage.promptKey || '';++ // For review stages: read REVIEW.md from workspace (the deliverable)+ if (promptKey.includes('review') && !promptKey.includes('implement') && workspacePath) {+ const reviewPath = join(workspacePath, 'REVIEW.md');+ const content = await readFile(reviewPath, 'utf-8').catch(() => null);+ if (content?.trim()) return content.trim();+ }++ // For implement/triage stages or fallback: extract last content section from output+ return extractFinalSummary(outputBuffer);+}++/**+ * Advance a pipeline to its next stage after the current stage completes.+ * Creates a new task for the next stage or marks the pipeline as complete/failed.+ */+export async function handlePipelineProgression(task, agentId, success) {+ const pipeline = task.metadata?.pipeline;+ if (!pipeline || pipeline.status !== 'running') return;++ const { currentStage, stages } = pipeline;+ const stageResult = {+ stage: currentStage,+ name: stages[currentStage]?.name,+ agentId,+ success,+ completedAt: new Date().toISOString()+ };+ const updatedResults = [...(pipeline.stageResults || []), stageResult];++ if (!success) {+ await updateTask(task.id, {+ metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }+ }, task.taskType);+ emitLog('warn', `⛔ Pipeline ${pipeline.id} failed at stage ${currentStage}: ${stages[currentStage]?.name}`, { pipelineId: pipeline.id });+ return;+ }++ const nextStageIndex = currentStage + 1;+ if (nextStageIndex >= stages.length) {+ await updateTask(task.id, {+ metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'completed', stageResults: updatedResults } }+ }, task.taskType);+ // Clean up pipeline artifacts (e.g., REVIEW.md left by stage 1)+ if (task.metadata.repoPath) {+ const repoRoot = resolve(task.metadata.repoPath);+ for (const stage of stages) {+ const file = stage.precondition?.fileNotExists;+ if (file) {+ const filePath = resolve(repoRoot, file);+ const rel = relative(repoRoot, filePath);+ if (!rel || rel === '..' || rel.startsWith('..' + sep) || resolve(rel) === rel) continue;+ await unlink(filePath).catch(() => {});+ }+ }+ }+ emitLog('info', `✅ Pipeline ${pipeline.id} completed all ${stages.length} stages`, { pipelineId: pipeline.id });+ return;+ }++ const nextStage = stages[nextStageIndex];++ // Check next stage's precondition before advancing+ if (nextStage.precondition && task.metadata.repoPath) {+ const check = checkStagePrecondition(nextStage, task.metadata.repoPath);+ if (!check.passed) {+ await updateTask(task.id, {+ metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }+ }, task.taskType);+ emitLog('warn', `⏭️ Pipeline ${pipeline.id} stage ${nextStageIndex} precondition failed: ${check.reason}`, { pipelineId: pipeline.id });+ return;+ }+ }++ const taskScheduleMod = await import('./taskSchedule.js');+ let prompt = await taskScheduleMod.getStagePrompt(task.metadata.analysisType, nextStageIndex);+ if (task.metadata.appName) prompt = prompt.replace(/\{appName\}/g, task.metadata.appName);+ if (task.metadata.repoPath) prompt = prompt.replace(/\{repoPath\}/g, task.metadata.repoPath);+ if (task.metadata.app) prompt = prompt.replace(/\{appId\}/g, task.metadata.app);++ const nextTask = {+ id: `${task.id || 'sys-pipeline'}-stage${nextStageIndex}-${Date.now().toString(36)}`,+ status: 'pending',+ description: prompt,+ priority: task.priority || 'MEDIUM',+ metadata: {+ ...task.metadata,+ readOnly: nextStage.readOnly ?? false,+ pipeline: {+ ...pipeline,+ currentStage: nextStageIndex,+ stageResults: updatedResults,+ previousStageAgentId: agentId,+ status: 'running'+ }+ },+ autoApproved: true+ };+ if (nextStage.model) nextTask.metadata.model = nextStage.model;+ if (nextStage.providerId) {+ nextTask.metadata.provider = nextStage.providerId;+ nextTask.metadata.providerId = nextStage.providerId;+ }+ // Apply per-stage overrides for agent behavior flags+ const stageReadOnly = nextStage.readOnly ?? false;+ const taskDefaults = pipeline.taskDefaults || {};+ for (const flag of PIPELINE_BEHAVIOR_FLAGS) {+ if (flag in nextStage) {+ nextTask.metadata[flag] = nextStage[flag];+ } else if (stageReadOnly) {+ nextTask.metadata[flag] = false;+ } else if (flag in taskDefaults) {+ nextTask.metadata[flag] = taskDefaults[flag];+ }+ }++ await addTask(nextTask, 'internal', { raw: true });+ emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });+}++/**+ * Handle agent completion (from runner events).+ */+export async function handleAgentCompletion(agentId, exitCode, success, duration) {+ const agent = runnerAgents.get(agentId);+ if (!agent) {+ // Agent not in memory map (server restarted). Check cos state for context.+ const { getAgent: getAgentState } = await import('./cos.js');+ const cosAgent = await getAgentState(agentId).catch(() => null);+ if (!cosAgent) {+ console.log(`⚠️ Received completion for unknown agent: ${agentId} (not in cos state)`);+ return;+ }+ if (cosAgent.status === 'completed') {+ console.log(`✅ Agent ${agentId} already completed (handled by orphan cleanup)`);+ return;+ }+ console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);+ await completeAgent(agentId, {+ success,+ exitCode,+ duration,+ orphaned: true,+ error: success ? undefined : 'Agent completed after server restart'+ });+ if (cosAgent.taskId) {+ const task = await getTaskById(cosAgent.taskId).catch(() => null);+ if (task && task.status !== 'completed') {+ if (success) {+ await updateTask(cosAgent.taskId, { status: 'completed' }, task.taskType || 'user');+ } else {+ // Import handleOrphanedTask dynamically to avoid circular dep with agentManagement+ const { handleOrphanedTask } = await import('./agentManagement.js');+ await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById);+ }+ }+ }+ return;+ }++ const { task, runId, model, executionId, laneName } = agent;++ // Ensure taskType is set — recovered agents may lack it+ if (task && !task.taskType) {+ const id = task.id || '';+ task.taskType = (id.startsWith('sys-') || id.startsWith('app-improve-')) ? 'internal' : 'user';+ }++ // Release execution lane+ if (laneName) {+ release(agentId);+ }++ // Complete tool execution tracking+ if (executionId) {+ if (success) {+ completeExecution(executionId, { success: true, duration });+ } else {+ errorExecution(executionId, { message: `Agent exited with code ${exitCode}`, code: exitCode });+ completeExecution(executionId, { success: false });+ }+ }++ // Read output from agent directory+ const agentDir = join(AGENTS_DIR, agentId);+ const outputFile = join(agentDir, 'output.txt');+ let outputBuffer = '';+ if (existsSync(outputFile)) {+ outputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');+ }++ // Post-execution validation: check for task commit even if exit code is non-zero+ let effectiveSuccess = success;+ if (!effectiveSuccess && task?.id) {+ const workspacePath = agent.workspacePath || ROOT_DIR;+ const commitFound = checkForTaskCommit(task.id, workspacePath);+ if (commitFound) {+ emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });+ effectiveSuccess = true;+ }+ }++ // Analyze failure if applicable+ const errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);++ // Extract pipeline output summary before completion writes metadata to disk+ if (task?.metadata?.pipeline && effectiveSuccess) {+ const workspacePath = agent.workspacePath || ROOT_DIR;+ const summary = await extractPipelineOutputSummary(task, workspacePath, outputBuffer).catch(err => {+ console.log(`⚠️ Failed to extract pipeline summary for ${agentId}: ${err.message}`);+ return null;+ });+ if (summary) {+ await updateAgent(agentId, { metadata: { outputSummary: summary } });+ }+ }++ await completeAgent(agentId, {+ success: effectiveSuccess,+ exitCode,+ duration,+ outputLength: outputBuffer.length,+ errorAnalysis+ });++ // Complete run tracking (skip if no runId - agent was recovered after restart)+ if (runId) {+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);+ }++ // Update task status with retry tracking+ if (effectiveSuccess) {+ const result = await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');+ if (result?.error) {+ emitLog('warn', `⚠️ Failed to mark task ${task.id} completed: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });+ }+ } else {+ const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);+ const result = await updateTask(task.id, failedUpdate, task.taskType || 'user');+ if (result?.error) {+ emitLog('warn', `⚠️ Failed to update failed task ${task.id}: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });+ }++ // Handle provider status updates on failure+ if (errorAnalysis) {+ if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {+ const providerId = agent.providerId || (await getActiveProvider())?.id;+ if (providerId) {+ await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });+ });+ }+ }+ if (errorAnalysis.category === 'rate-limit') {+ const providerId = agent.providerId || (await getActiveProvider())?.id;+ if (providerId) {+ await markProviderRateLimited(providerId).catch(err => {+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });+ });+ }+ }+ }+ }++ // Process memory extraction and app cooldown+ await processAgentCompletion(agentId, task, effectiveSuccess, outputBuffer);++ // Fetch agent state once for JIRA and plan-question blocks+ const { getAgent: getAgentState } = await import('./cos.js');+ const agentState = await getAgentState(agentId).catch(() => null);++ // JIRA integration: push branch, create PR, comment on ticket+ const jiraTicketId = agent.task?.metadata?.jiraTicketId;+ const jiraBranch = agent.task?.metadata?.jiraBranch;+ const jiraInstanceId = agent.task?.metadata?.jiraInstanceId;+ const jiraCreatePR = agent.task?.metadata?.jiraCreatePR;++ if (jiraTicketId && jiraBranch && success) {+ const workspace = agentState?.metadata?.workspacePath || ROOT_DIR;++ let jiraTicketUrl = agent.task?.metadata?.jiraTicketUrl || null;+ if (!jiraTicketUrl && jiraInstanceId) {+ const jiraConfig = await jiraService.getInstances().catch(() => null);+ const baseUrl = jiraConfig?.instances?.[jiraInstanceId]?.baseUrl;+ if (baseUrl) jiraTicketUrl = `${baseUrl}/browse/${jiraTicketId}`;+ }+ const jiraTicketRef = jiraTicketUrl ? `[${jiraTicketId}](${jiraTicketUrl})` : jiraTicketId;++ await git.push(workspace, jiraBranch).catch(err => {+ emitLog('warn', `Failed to push JIRA branch ${jiraBranch}: ${err.message}`, { agentId, ticketId: jiraTicketId });+ });++ let prUrl = null;+ if (jiraCreatePR !== false) {+ const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));+ const targetBranch = devBranch || baseBranch || 'main';++ const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);+ const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;++ const prResult = await git.createPR(workspace, {+ title: `${jiraTicketId}: ${(task.description || 'CoS automated task').substring(0, 100)}`,+ body: jiraPrBodyWithRef,+ base: targetBranch,+ head: jiraBranch+ }).catch(err => {+ emitLog('warn', `Failed to create PR for ${jiraTicketId}: ${err.message}`, { agentId });+ return null;+ });++ if (prResult?.success) {+ prUrl = prResult.url;+ emitLog('success', `Created PR: ${prUrl}`, { agentId, ticketId: jiraTicketId });+ }+ }++ if (jiraInstanceId) {+ const commentLines = [`Agent completed task successfully.`];+ if (prUrl) {+ commentLines.push(`\n*Pull Request:* ${prUrl}`);+ } else if (jiraBranch) {+ commentLines.push(`\n*Branch:* \`${jiraBranch}\``);+ }+ await jiraService.addComment(jiraInstanceId, jiraTicketId, commentLines.join('\n')).catch(err => {+ emitLog('warn', `Failed to comment on JIRA ticket ${jiraTicketId}: ${err.message}`, { agentId });+ });+ }++ const { devBranch: dev, baseBranch: base } = await git.getRepoBranches(workspace).catch(() => ({ devBranch: null, baseBranch: null }));+ const returnBranch = dev || base || 'main';+ await git.checkout(workspace, returnBranch).catch(err => {+ emitLog('warn', `Failed to checkout back to ${returnBranch}: ${err.message}`, { agentId });+ });+ }++ // Check for plan questions marker file (feature-ideas task needing user input)+ if (task?.metadata?.analysisType === 'feature-ideas') {+ const planWorkspace = agentState?.metadata?.workspacePath || task?.metadata?.repoPath || ROOT_DIR;+ const markerPath = join(planWorkspace, '.plan-questions.md');++ const markerContent = await readFile(markerPath, 'utf8').catch(() => null);+ if (markerContent) {+ const titleMatch = markerContent.match(/^#\s+Plan Question:\s*(.+)/m);+ const title = titleMatch?.[1]?.trim() || 'PLAN.md item needs your input';+ const appId = task.metadata?.app;++ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');+ await addNotification({+ type: NOTIFICATION_TYPES.PLAN_QUESTION,+ title,+ message: markerContent,+ priority: PRIORITY_LEVELS.MEDIUM,+ link: appId ? `/apps/${appId}/documents` : undefined,+ metadata: { appId, agentId, taskType: 'feature-ideas' }+ }).catch(err => {+ emitLog('warn', `Failed to create plan_question notification: ${err.message}`, { agentId });+ });++ await rm(markerPath).catch(() => {});+ emitLog('info', `📋 Plan question notification created: ${title}`, { agentId, appId });+ }+ }++ // Advance pipeline to next stage if applicable+ if (task?.metadata?.pipeline) {+ await handlePipelineProgression(task, agentId, effectiveSuccess);+ }++ // Clean up ephemeral BTW.md before worktree removal+ await cleanupBtwFile(agentState?.metadata?.workspacePath);++ // Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)+ if (!jiraBranch) {+ const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);+ const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);+ const cleanupWarnings = await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description, agentOutput: outputBuffer });++ if (cleanupWarnings?.length > 0) {+ const { getAgent: getAgentForResult } = await import('./cos.js');+ const currentAgent = await getAgentForResult(agentId).catch(() => null);+ await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });++ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');+ const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';+ await addNotification({+ type: NOTIFICATION_TYPES.AGENT_WARNING,+ title: `Agent cleanup issue: ${appName}`,+ description: cleanupWarnings.join('\n'),+ priority: PRIORITY_LEVELS.HIGH,+ link: '/cos/agents',+ metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }+ }).catch(err => {+ emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });+ });+ }+ }++ runnerAgents.delete(agentId);+}++/**+ * Clean up a worktree for a completed agent.+ * Reads worktree metadata from the agent's registered state and removes the worktree.+ * When openPR is true, pushes the branch and creates a PR instead of auto-merging.+ * Otherwise, merges the worktree branch back to the source branch on success.+ */+export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null, agentOutput = null } = {}) {+ const { getAgent: getAgentState } = await import('./cos.js');+ const agentState = await getAgentState(agentId).catch(() => null);+ if (!agentState?.metadata?.isWorktree) return [];+ if (agentState?.metadata?.isPersistentWorktree) return [];++ const { sourceWorkspace, worktreeBranch } = agentState.metadata;+ if (!sourceWorkspace || !worktreeBranch) return [];++ const warnings = [];++ // When openPR is set and task succeeded, push branch and create PR instead of auto-merging+ if (openPR && success) {+ emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });++ const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);++ const [pushResult, branchInfo] = await Promise.all([+ git.push(worktreePath, worktreeBranch).then(() => true).catch(err => {+ emitLog('warn', `🌳 Failed to push worktree branch ${worktreeBranch}: ${err.message}`, { agentId });+ return false;+ }),+ git.getRepoBranches(sourceWorkspace).catch(() => ({ baseBranch: null, devBranch: null }))+ ]);++ if (pushResult) {+ const targetBranch = branchInfo.baseBranch || 'main';+ const taskDesc = description || 'CoS automated task';+ const prTitle = taskDesc.replace(/[\r\n]+/g, ' ').trim().substring(0, 100);++ const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput);++ const prResult = await git.createPR(worktreePath, {+ title: prTitle,+ body: prBody,+ base: targetBranch,+ head: worktreeBranch+ }).catch(err => {+ emitLog('warn', `🌳 Failed to create PR for ${worktreeBranch}: ${err.message}`, { agentId });+ return null;+ });++ if (!prResult?.success) {+ const reason = prResult?.error || 'unknown error (createPR returned null or threw)';+ emitLog('error', `🌳 PR creation failed for ${worktreeBranch}: ${reason}`, { agentId, branchName: worktreeBranch });+ warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);+ return warnings;+ }++ emitLog('success', `🌳 Created PR: ${prResult.url}`, { agentId, branchName: worktreeBranch });++ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });+ return { warnings: [`Worktree cleanup failed: ${err.message}`] };+ });+ warnings.push(...(result?.warnings || []));+ return warnings;+ }++ // Push failed — preserve worktree/branch for manual intervention+ warnings.push(`Push failed for branch ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`);+ emitLog('warn', `🌳 Push failed for ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`, { agentId, branchName: worktreeBranch });+ return warnings;+ }++ // Default: auto-merge on success, just cleanup on failure+ emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${success})`, {+ agentId, branchName: worktreeBranch, merge: success+ });++ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });+ return { warnings: [`Worktree cleanup failed: ${err.message}`] };+ });+ warnings.push(...(result?.warnings || []));+ return warnings;+}diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsnew file mode 100644index 0000000000..3f1fcfc8e6--- /dev/null+++ b/server/services/agentManagement.js@@ -0,0 +1,509 @@+/**+ * Agent Management+ *+ * Handles agent termination, process stats, kill-all, orphan cleanup,+ * and orphaned task retry logic.+ */++import { join } from 'path';+import { emitLog } from './cosEvents.js';+import { completeAgent } from './cosAgents.js';+import { updateTask, addTask, getTaskById } from './cos.js';+import { terminateAgentViaRunner, killAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';+import { unregisterSpawnedAgent } from './agents.js';+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';+import { activeAgents, runnerAgents, userTerminatedAgents, useRunner } from './agentState.js';+import { cleanupAgentWorktree, syncRunnerAgents } from './agentLifecycle.js';+import { cleanupOrphanedWorktrees } from './worktreeManager.js';+import { checkForTaskCommit } from './agentRunTracking.js';+import { PATHS } from '../lib/fileUtils.js';++const ROOT_DIR = PATHS.root;++// Max retries before creating investigation task+const MAX_ORPHAN_RETRIES = 3;+// Minimum cooldown between orphan retries (30 minutes)+const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;++/**+ * Terminate an agent (graceful SIGTERM with SIGKILL fallback).+ */+export async function terminateAgent(agentId) {+ // Check if agent is in runner mode+ if (runnerAgents.has(agentId)) {+ const agentInfo = runnerAgents.get(agentId);+ if (agentInfo?.initializationTimeout) {+ clearTimeout(agentInfo.initializationTimeout);+ }+ const result = await terminateAgentViaRunner(agentId).catch(err => ({+ success: false,+ error: err.message+ }));+ if (result.success) {+ await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });+ const task = agentInfo?.task;+ if (task) {+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Terminated by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ }+ runnerAgents.delete(agentId);+ }+ return result;+ }++ // Direct mode+ const agent = activeAgents.get(agentId);++ if (!agent) {+ return { success: false, error: 'Agent not found or not running' };+ }++ // Track as user-terminated so the close handler doesn't re-queue+ userTerminatedAgents.add(agentId);++ // Mark agent as completed immediately with termination status+ await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });++ // Block task immediately (don't defer to close handler — prevents requeue on server restart)+ if (agent.taskId) {+ const task = await getTaskById(agent.taskId).catch(() => null);+ if (task) {+ await updateTask(agent.taskId, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Terminated by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ }+ }++ // Kill the process+ agent.process.kill('SIGTERM');++ // Give it a moment, then force kill if needed+ setTimeout(() => {+ if (activeAgents.has(agentId)) {+ agent.process.kill('SIGKILL');+ unregisterSpawnedAgent(agent.pid);+ activeAgents.delete(agentId);+ }+ }, 5000);++ return { success: true, agentId };+}++/**+ * Get list of active agents.+ */+export function getActiveAgents() {+ const agents = [];++ // Direct mode agents+ for (const [agentId, agent] of activeAgents) {+ agents.push({+ id: agentId,+ taskId: agent.taskId,+ startedAt: agent.startedAt,+ runningTime: Date.now() - agent.startedAt,+ mode: 'direct'+ });+ }++ // Runner mode agents+ for (const [agentId, agent] of runnerAgents) {+ agents.push({+ id: agentId,+ taskId: agent.taskId,+ startedAt: agent.startedAt,+ runningTime: Date.now() - agent.startedAt,+ mode: 'runner'+ });+ }++ return agents;+}++/**+ * Force kill an agent immediately with SIGKILL (no graceful shutdown).+ */+export async function killAgent(agentId) {+ // Check if agent is in runner mode+ if (runnerAgents.has(agentId)) {+ const agentInfo = runnerAgents.get(agentId);+ if (agentInfo?.initializationTimeout) {+ clearTimeout(agentInfo.initializationTimeout);+ }+ const result = await killAgentViaRunner(agentId).catch(err => ({+ success: false,+ error: err.message+ }));+ if (result.success) {+ await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });+ const task = agentInfo?.task;+ if (task) {+ await updateTask(task.id, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Force killed by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ }+ runnerAgents.delete(agentId);+ }+ return result;+ }++ // Direct mode+ const agent = activeAgents.get(agentId);++ if (!agent) {+ return { success: false, error: 'Agent not found or not running' };+ }++ // Track as user-terminated so the close handler doesn't re-queue+ userTerminatedAgents.add(agentId);++ // Mark agent as completed immediately with kill status+ await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });++ // Block task immediately+ if (agent.taskId) {+ const task = await getTaskById(agent.taskId).catch(() => null);+ if (task) {+ await updateTask(agent.taskId, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Force killed by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString()+ }+ }, task.taskType || 'user');+ }+ }++ // Kill the process immediately with SIGKILL+ agent.process.kill('SIGKILL');++ unregisterSpawnedAgent(agent.pid);+ activeAgents.delete(agentId);++ return { success: true, agentId, pid: agent.pid, signal: 'SIGKILL' };+}++/**+ * Get process stats for an agent (CPU, memory usage).+ */+export async function getAgentProcessStats(agentId) {+ // Check if agent is in runner mode - use runner endpoint+ if (runnerAgents.has(agentId) || useRunner) {+ const stats = await getAgentStatsFromRunner(agentId);+ return stats;+ }++ // Direct mode - get stats locally+ const agent = activeAgents.get(agentId);+ if (!agent) {+ return null;+ }++ const { exec } = await import('child_process');+ const { promisify } = await import('util');+ const execAsync = promisify(exec);++ const psCmd = process.platform === 'win32'+ ? `tasklist /FI "PID eq ${agent.pid}" /FO CSV /NH`+ : `ps -p ${agent.pid} -o pid=,pcpu=,rss=,state=`;+ const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));+ const line = result.stdout.trim();++ if (!line) {+ return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };+ }++ const parts = line.split(/\s+/).filter(Boolean);+ if (parts.length >= 3) {+ return {+ active: true,+ agentId,+ pid: parseInt(parts[0], 10),+ cpu: parseFloat(parts[1]) || 0,+ memoryKb: parseInt(parts[2], 10) || 0,+ memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,+ state: parts[3] || 'unknown'+ };+ }++ return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };+}++/**+ * Kill all active agents.+ */+export async function killAllAgents() {+ const directIds = Array.from(activeAgents.keys());+ const runnerIds = Array.from(runnerAgents.keys());++ for (const agentId of directIds) {+ await terminateAgent(agentId);+ }++ for (const agentId of runnerIds) {+ await terminateAgent(agentId);+ }++ return { killed: directIds.length + runnerIds.length };+}++/**+ * Check if a process is running by PID.+ */+export async function isPidAlive(pid) {+ if (!pid) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++/**+ * Clean up orphaned agents on startup.+ * Agents marked as "running" in state but not tracked anywhere are orphaned.+ *+ * Must check:+ * 1. Local activeAgents map (direct-spawned)+ * 2. Local runnerAgents map (recently spawned via runner)+ * 3. CoS Runner service (may have agents from before server restart)+ *+ * After cleanup:+ * - Resets associated tasks to pending for auto-retry+ * - Creates investigation task after max retries exceeded+ * - Triggers evaluation to spawn new agents+ */+export async function cleanupOrphanedAgents() {+ const { getAgents, completeAgent: markComplete, evaluateTasks, getTaskById: getTask } = await import('./cos.js');+ const agents = await getAgents();+ let cleanedCount = 0;+ const orphanedTaskIds = [];++ // Get list of agents actively running in the CoS Runner+ const runnerActiveIds = new Set();+ const runnerAgentsList = await getActiveAgentsFromRunner().catch(() => []);+ for (const agent of runnerAgentsList) {+ runnerActiveIds.add(agent.id);+ }++ // Also sync runner agents to our local map for event handling+ if (runnerAgentsList.length > 0) {+ const synced = await syncRunnerAgents();+ if (synced > 0) {+ console.log(`🔄 Synced ${synced} agents from CoS Runner`);+ }+ }++ for (const agent of agents) {+ if (agent.status === 'running') {+ const inLocalDirect = activeAgents.has(agent.id);+ const inLocalRunner = runnerAgents.has(agent.id);+ const inRemoteRunner = runnerActiveIds.has(agent.id);++ if (!inLocalDirect && !inLocalRunner && !inRemoteRunner) {+ // Before marking as orphaned, check if the process is actually still running+ if (agent.pid) {+ const stillAlive = await isPidAlive(agent.pid);+ if (stillAlive) {+ console.log(`🔄 Agent ${agent.id} (PID ${agent.pid}) still running, re-syncing to runner tracking`);+ const inferredType = agent.taskId?.startsWith('sys-') ? 'internal' : 'user';+ runnerAgents.set(agent.id, {+ id: agent.id, pid: agent.pid, taskId: agent.taskId,+ task: { id: agent.taskId, taskType: inferredType, description: 'Re-synced from PID check' }+ });+ continue;+ }+ }++ console.log(`🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);+ await markComplete(agent.id, {+ success: false,+ error: 'Agent process terminated unexpectedly',+ orphaned: true+ });+ cleanedCount++;++ if (agent.taskId) {+ orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id });+ }+ }+ }+ }++ // 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([...activeAgents.keys(), ...runnerAgents.keys()]);+ 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, getTask);+ }++ // Trigger evaluation to spawn new agents for retried tasks+ if (cleanedCount > 0) {+ emitLog('info', `Cleaned up ${cleanedCount} orphaned agents, triggering evaluation`, { cleanedCount });+ setTimeout(() => {+ evaluateTasks().catch(err => {+ console.error(`❌ Failed to evaluate tasks after orphan cleanup: ${err.message}`);+ });+ }, 1000);+ }++ return cleanedCount;+}++/**+ * Handle an orphaned task - retry or create investigation.+ */+export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn) {+ const task = await getTaskByIdFn(taskId).catch(() => null);+ if (!task) {+ emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });+ return;+ }++ // Never requeue tasks that were explicitly terminated by the user+ if (task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') {+ emitLog('info', `⏭️ Skipping orphaned task ${taskId} — user-terminated`, { taskId, agentId });+ return;+ }++ // Skip tasks already completed+ if (task.status === 'completed') {+ emitLog('debug', `⏭️ Skipping orphaned task ${taskId} — already completed`, { taskId, agentId });+ return;+ }++ // Check if the agent actually committed work before treating as orphaned+ const commitFound = checkForTaskCommit(taskId, ROOT_DIR);+ if (commitFound) {+ emitLog('info', `✅ Orphaned agent ${agentId} actually completed work - commit found for task ${taskId}`, { taskId, agentId });+ await updateTask(taskId, { status: 'completed' }, task.taskType || 'user');+ return;+ }++ // Get current retry count from task metadata+ const retryCount = (Number(task.metadata?.orphanRetryCount) || 0) + 1;+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;+ const taskType = task.taskType || 'user';++ // Block if total spawn count across all retry types is exhausted+ const totalExceeded = totalSpawns >= MAX_TOTAL_SPAWNS;++ // Enforce cooldown between orphan retries+ const lastOrphanedAt = task.metadata?.lastOrphanedAt ? new Date(task.metadata.lastOrphanedAt).getTime() : 0;+ const cooldownRemaining = lastOrphanedAt ? ORPHAN_RETRY_COOLDOWN_MS - (Date.now() - lastOrphanedAt) : 0;+ const inCooldown = cooldownRemaining > 0;++ if (retryCount < MAX_ORPHAN_RETRIES && !totalExceeded && !inCooldown) {+ emitLog('info', `Resetting orphaned task ${taskId} for retry (attempt ${retryCount}/${MAX_ORPHAN_RETRIES}, total spawns ${totalSpawns}/${MAX_TOTAL_SPAWNS})`, {+ taskId,+ retryCount,+ totalSpawns,+ maxRetries: MAX_ORPHAN_RETRIES+ });++ await updateTask(taskId, {+ status: 'pending',+ metadata: {+ ...task.metadata,+ orphanRetryCount: retryCount,+ lastOrphanedAt: new Date().toISOString(),+ lastOrphanedAgentId: agentId+ }+ }, taskType);+ } else if (inCooldown && retryCount < MAX_ORPHAN_RETRIES && !totalExceeded) {+ const cooldownMinutes = Math.ceil(cooldownRemaining / 60000);+ emitLog('info', `⏳ Orphan retry for task ${taskId} in cooldown (${cooldownMinutes}m remaining)`, {+ taskId, cooldownMinutes, retryCount+ });++ await updateTask(taskId, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ orphanRetryCount: retryCount,+ lastOrphanedAt: new Date().toISOString(),+ lastOrphanedAgentId: agentId,+ blockedReason: `Orphan retry cooldown (${cooldownMinutes}m remaining)`,+ blockedCategory: 'orphan-cooldown',+ blockedAt: new Date().toISOString(),+ cooldownUntil: new Date(Date.now() + cooldownRemaining).toISOString()+ }+ }, taskType);+ } else {+ const reason = totalExceeded+ ? `total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`+ : `orphan retries exceeded (${retryCount}/${MAX_ORPHAN_RETRIES})`;+ emitLog('warn', `Task ${taskId} blocked: ${reason}, creating investigation task`, {+ taskId,+ retryCount,+ totalSpawns+ });++ await updateTask(taskId, {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ orphanRetryCount: retryCount,+ blockedReason: reason,+ blockedCategory: 'max-retries',+ blockedAt: new Date().toISOString()+ }+ }, taskType);++ const description = `[Auto-Fix] Investigate repeated agent orphaning for task ${taskId}++**Original Task**: ${(task.description || '').substring(0, 200)}+**Orphan Retries**: ${retryCount}+**Total Spawns**: ${totalSpawns}+**Last Orphaned Agent**: ${agentId}+**Blocked Reason**: ${reason}++This task has been blocked after ${totalSpawns} total agent spawns. Investigate:+1. Check CoS Runner logs for errors+2. Verify process spawning is working correctly+3. Look for resource constraints (memory, CPU)+4. Check for network/connection issues between services++Once the issue is resolved, reset the original task to pending.`;++ await addTask({+ description,+ priority: 'HIGH',+ context: `Auto-generated from repeated orphan failures for task ${taskId}`,+ approvalRequired: false // Auto-approved for orphan issues+ }, 'internal').catch(err => {+ emitLog('error', `Failed to create investigation task: ${err.message}`, { taskId, error: err.message });+ });+ }+}diff --git a/server/services/agentModelSelection.js b/server/services/agentModelSelection.jsnew file mode 100644index 0000000000..d3f0550b16--- /dev/null+++ b/server/services/agentModelSelection.js@@ -0,0 +1,159 @@+/**+ * Agent Model Selection+ *+ * Handles task type key extraction and optimal model selection based on+ * task complexity, thinking levels, and historical performance data.+ */++import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';+import { suggestModelTier } from './taskLearning.js';++/**+ * Extract task type key for learning lookup.+ * Matches the format used in taskLearning.js for consistency.+ */+export function extractTaskTypeKey(task) {+ if (task?.metadata?.analysisType) {+ return `self-improve:${task.metadata.analysisType}`;+ }+ if (task?.metadata?.reviewType === 'idle') {+ return 'idle-review';+ }+ const desc = (task?.description || '').toLowerCase();+ if (desc.includes('[self-improvement]')) {+ const typeMatch = desc.match(/\[self-improvement\]\s*(\w+)/i);+ if (typeMatch) return `self-improve:${typeMatch[1]}`;+ }+ if (task?.taskType === 'user') return 'user-task';+ return 'unknown';+}++/**+ * Select optimal model for a task based on complexity analysis and historical performance.+ * User can override by specifying Model: and/or Provider: in task metadata.+ *+ * Enhanced with:+ * - Thinking levels hierarchy (task → agent → provider)+ * - Learning-based model suggestions from historical success rates+ * - Automatic upgrades when task type has <60% success rate+ */+export async function selectModelForTask(task, provider, agent = {}) {+ const desc = (task.description || '').toLowerCase();+ const context = task.metadata?.context || '';+ const contextLen = context.length;+ const priority = task.priority || 'MEDIUM';++ // Check for user-specified model preference (highest priority)+ const userModel = task.metadata?.model;+ const userProvider = task.metadata?.provider;++ if (userModel) {+ console.log(`👤 User specified model: ${userModel}`);+ return {+ model: userModel,+ tier: 'user-specified',+ reason: 'user-preference',+ userProvider: userProvider || null+ };+ }++ // Check thinking level hierarchy (task → agent → provider)+ const thinkingResult = resolveThinkingLevel(task, agent, provider);+ if (thinkingResult.resolvedFrom !== 'default') {+ const modelFromLevel = getModelForLevel(thinkingResult.level, provider);+ if (modelFromLevel) {+ const isLocal = isLocalPreferred(thinkingResult.level);+ console.log(`🧠 Thinking level: ${thinkingResult.level} → ${modelFromLevel} (from ${thinkingResult.resolvedFrom}${isLocal ? ', local-preferred' : ''})`);+ return {+ model: modelFromLevel,+ tier: thinkingResult.level,+ reason: `thinking-level-${thinkingResult.resolvedFrom}`,+ thinkingLevel: thinkingResult.level,+ localPreferred: isLocal+ };+ }+ }++ // Image/visual analysis → would route to gemini if available+ if (/image|screenshot|visual|photo|picture/.test(desc)) {+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };+ }++ // Critical priority → always use opus/heavy+ if (priority === 'CRITICAL') {+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'critical-priority' };+ }++ // Complex reasoning tasks → opus/heavy+ if (/architect|refactor|design|complex|optimize|security|audit|review.*code|performance/.test(desc)) {+ return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'complex-task' };+ }++ // Long context → needs more capable model+ if (contextLen > 500) {+ return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };+ }++ // Detect coding/development tasks - these should NEVER use light model.+ // Intentionally inclusive: if a task mentions any coding-related term (even in+ // broader context like "bug report template"), we err on the side of using+ // a stronger model since misclassifying a coding task is more costly than+ // over-allocating resources for a documentation task.+ const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);++ // Simple/quick tasks → haiku/light (ONLY for non-coding tasks)+ // Light model is reserved for documentation, text updates, and formatting only+ if (!isCodingTask && /fix typo|update text|update docs|edit readme|update readme|write docs|documentation only|format text/.test(desc)) {+ return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'documentation-task' };+ }++ // Check historical performance for this task type and select optimal model tier+ const taskTypeKey = extractTaskTypeKey(task);+ const learningSuggestion = await suggestModelTier(taskTypeKey).catch(() => null);++ if (learningSuggestion) {+ const { suggested, avoidTiers = [], reason: learningReason } = learningSuggestion;++ // Map tier names to provider model keys+ const tierToModel = {+ heavy: provider.heavyModel,+ medium: provider.mediumModel || provider.defaultModel,+ default: provider.defaultModel,+ light: provider.lightModel+ };++ // If we have a specific tier suggestion, use it+ if (suggested && tierToModel[suggested]) {+ console.log(`📊 Learning-based selection: ${taskTypeKey} → ${suggested} (${learningReason})`);+ return {+ model: tierToModel[suggested],+ tier: suggested,+ reason: 'learning-suggested',+ learningReason,+ avoidedTiers: avoidTiers.length > 0 ? avoidTiers : undefined+ };+ }++ // If no specific suggestion but we have tiers to avoid, pick the best available tier+ if (avoidTiers.length > 0) {+ // Try tiers in order of preference: heavy → medium → default → light+ // Skip any that are in avoidTiers+ const tierPreference = ['heavy', 'medium', 'default', 'light'];+ for (const tier of tierPreference) {+ if (!avoidTiers.includes(tier) && tierToModel[tier]) {+ console.log(`📊 Learning-based avoidance: ${taskTypeKey} → ${tier} (avoiding ${avoidTiers.join(', ')})`);+ return {+ model: tierToModel[tier],+ tier,+ reason: 'learning-avoid-bad-tier',+ learningReason,+ avoidedTiers: avoidTiers+ };+ }+ }+ }+ }++ // Standard tasks → use provider's default model+ return { model: provider.defaultModel, tier: 'default', reason: 'standard-task' };+}diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsnew file mode 100644index 0000000000..21a217d1a9--- /dev/null+++ b/server/services/agentPromptBuilder.js@@ -0,0 +1,489 @@+/**+ * Agent Prompt Builder+ *+ * Builds the full agent prompt including memory context, CLAUDE.md instructions,+ * digital twin, worktree/pipeline/JIRA sections, skill templates, and tools summary.+ * Also handles JIRA ticket creation and app workspace resolution.+ */++import { join } from 'path';+import { readFile, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { homedir } from 'os';+import { getMemorySection } from './memoryRetriever.js';+import { getDigitalTwinForPrompt } from './digital-twin.js';+import { buildPrompt } from './promptService.js';+import { getToolsSummaryForPrompt } from './tools.js';+import { getActiveProvider } from './providers.js';+import { executeApiRun, executeCliRun, createRun } from './runner.js';+import { readJSONFile, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';+import * as jiraService from './jira.js';+import { emitLog } from './cosEvents.js';++const ROOT_DIR = PATHS.root;+const AGENTS_DIR = PATHS.cosAgents;+const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');++/**+ * Skill template keyword matchers.+ * Each entry maps a skill template filename to its trigger keywords.+ * Order matters — first match wins, so more specific patterns come first.+ */+const SKILL_MATCHERS = [+ {+ skill: 'security-audit',+ keywords: ['security', 'audit', 'vulnerability', 'xss', 'injection', 'owasp', 'cve', 'penetration', 'hardening', 'sanitize', 'authorization']+ },+ {+ skill: 'mobile-responsive',+ keywords: ['mobile', 'responsive', 'tablet', 'breakpoint', 'viewport', 'touch', 'swipe', 'small screen', 'media query', 'mobile-friendly', 'adaptive']+ },+ {+ skill: 'bug-fix',+ keywords: ['fix', 'bug', 'broken', 'error', 'crash', 'issue', 'not working', 'fails', 'regression', 'defect']+ },+ {+ skill: 'refactor',+ keywords: ['refactor', 'reorganize', 'restructure', 'clean up', 'simplify', 'extract', 'consolidate', 'decouple', 'modularize']+ },+ {+ skill: 'documentation',+ keywords: ['document', 'documentation', 'docs', 'readme', 'jsdoc', 'api docs', 'guide', 'tutorial', 'changelog']+ },+ {+ skill: 'feature',+ keywords: ['add', 'create', 'implement', 'build', 'new', 'feature', 'support', 'enable', 'integrate', 'endpoint', 'page', 'component']+ }+];++/**+ * Detect the best matching skill template for a task based on description keywords.+ * @param {Object} task - Task object with description+ * @returns {string|null} Skill template name or null if no match+ */+export function detectSkillTemplate(task) {+ const desc = (task?.description || '').toLowerCase();+ for (const matcher of SKILL_MATCHERS) {+ if (matcher.keywords.some(kw => desc.includes(kw))) {+ return matcher.skill;+ }+ }+ return null;+}++/**+ * Load a skill template from disk if it exists.+ * @param {string} skillName - Name of the skill template file (without .md)+ * @returns {Promise<string|null>} Template content or null+ */+export async function loadSkillTemplate(skillName) {+ const templatePath = join(SKILLS_DIR, `${skillName}.md`);+ if (!existsSync(templatePath)) return null;+ const content = await readFile(templatePath, 'utf-8');+ console.log(`🎯 Loaded skill template: ${skillName}`);+ return content;+}++/**+ * Read CLAUDE.md files for agent context.+ * Reads both global (~/.claude/CLAUDE.md) and project-specific (./CLAUDE.md).+ */+export async function getClaudeMdContext(workspaceDir) {+ const contexts = [];++ // Try to read global CLAUDE.md from ~/.claude/CLAUDE.md+ try {+ const globalPath = join(homedir(), '.claude', 'CLAUDE.md');+ if (existsSync(globalPath)) {+ const content = await readFile(globalPath, 'utf-8');+ if (content.trim()) {+ contexts.push({+ type: 'Global Instructions',+ path: globalPath,+ content: content.trim()+ });+ }+ }+ } catch (err) {+ // Silently ignore if global CLAUDE.md doesn't exist or can't be read+ }++ // Try to read project-specific CLAUDE.md from workspace directory+ try {+ const projectPath = join(workspaceDir, 'CLAUDE.md');+ if (existsSync(projectPath)) {+ const content = await readFile(projectPath, 'utf-8');+ if (content.trim()) {+ contexts.push({+ type: 'Project Instructions',+ path: projectPath,+ content: content.trim()+ });+ }+ }+ } catch (err) {+ // Silently ignore if project CLAUDE.md doesn't exist or can't be read+ }++ if (contexts.length === 0) {+ return null;+ }++ let section = '## CLAUDE.md Instructions\n\n';+ section += 'The following instructions must be followed when working on this task:\n\n';++ for (const ctx of contexts) {+ section += `### ${ctx.type}\n`;+ section += `Source: \`${ctx.path}\`\n\n`;+ section += ctx.content + '\n\n';+ }++ return section;+}++/**+ * Build a compaction instruction section for retries after context-limit failures.+ * Provides explicit guidance to the agent on reducing output verbosity.+ */+export function buildCompactionSection(task) {+ const compaction = task.metadata?.compaction;+ if (!compaction?.needed) return '';++ const hints = compaction.retryHints || [];+ const reason = compaction.reason === 'output-limit' ? 'output length limit' : 'context window limit';+ const prevOutputKB = compaction.outputSize ? Math.round(compaction.outputSize / 1024) : 'unknown';++ return `+## Context Compaction Required++**WARNING**: A previous attempt at this task failed because the agent exceeded the ${reason}.+Previous output size: ~${prevOutputKB} KB. You MUST keep your output compact to avoid the same failure.++**Mandatory output constraints**:+${hints.map(h => `- ${h}`).join('\n')}+- Do NOT reproduce entire file contents in your output+- Reference files by path and line number instead of quoting them+- Limit exploratory reads — plan your approach first, then make targeted changes+`;+}++/**+ * Build the full agent prompt.+ * @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+ * @param {Function} isTruthyMetaFn - isTruthyMeta function (passed to avoid circular dep)+ */+export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true') {+ // Get relevant memories for context injection+ const memorySection = await getMemorySection(task, {+ maxTokens: config.memory?.maxContextTokens || 2000+ }).catch(err => {+ console.log(`⚠️ Memory retrieval failed: ${err.message}`);+ return null;+ });++ // Get CLAUDE.md instructions for context injection+ const claudeMdSection = await getClaudeMdContext(workspaceDir).catch(err => {+ console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`);+ return null;+ });++ // Get digital twin context for persona alignment+ const digitalTwinSection = await getDigitalTwinForPrompt({+ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000+ }).catch(err => {+ console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`);+ return null;+ });++ // Build context compaction section if task is retrying after a context-limit failure+ const compactionSection = task.metadata?.compaction?.needed ? buildCompactionSection(task) : '';++ // Build worktree context section if applicable+ const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);+ // When reviewLoop is enabled alongside openPR, the agent opens the PR during its run+ const prHandledByAgent = willReviewLoop && willOpenPR;+ 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}\`+${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}++**Important**: Commit your changes to this branch.${willOpenPR && !prHandledByAgent ? ' Your commits will be submitted as a pull request to the default branch when your task completes.' : ' 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.+` : '';++ // Build pipeline context section if this is a pipeline stage+ const pipelineCtx = task.metadata?.pipeline;+ const pipelineSection = pipelineCtx?.previousStageAgentId ? `+## Pipeline Context+This is stage ${pipelineCtx.currentStage + 1} of ${pipelineCtx.stages.length}: "${pipelineCtx.stages[pipelineCtx.currentStage]?.name}"+Previous stage: "${pipelineCtx.stages[pipelineCtx.currentStage - 1]?.name}"++Read the previous stage's output from:+\`${join(AGENTS_DIR, pipelineCtx.previousStageAgentId, 'output.txt')}\`++Use the findings from the previous stage to inform your work. If the previous stage produced a JSON results block, parse it to determine which items to process.+` : '';++ // Build simplify section if enabled+ const simplifySection = isTruthyMetaFn(task.metadata?.simplify) ? `+## Simplify Step+After completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found before committing.+` : '';++ // Build review loop section if enabled+ const reviewLoopSection = willReviewLoop ? `+## Review Loop+After opening the PR, run \`/do:rpr\` to resolve PR review feedback and complete the merge validation. Continue running the review loop until all checks pass and the PR is approved.+` : '';++ // Build JIRA context section if applicable+ const jiraSection = task.metadata?.jiraTicketId ? `+## JIRA Integration+This task is tracked by JIRA ticket **${task.metadata.jiraTicketId}**.+- **Ticket URL**: ${task.metadata.jiraTicketUrl}+${task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\`` : ''}++Include the ticket ID (${task.metadata.jiraTicketId}) in your commit messages, e.g. \`${task.metadata.jiraTicketId}: description of change\`.+${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch branches.' : ''}+` : '';++ // Detect and load task-type-specific skill template (only when matched)+ const matchedSkill = detectSkillTemplate(task);+ const skillSection = matchedSkill+ ? await loadSkillTemplate(matchedSkill).catch(err => {+ console.log(`⚠️ Skill template load failed for ${matchedSkill}: ${err.message}`);+ return null;+ })+ : null;++ // Build onboard tools section for agent awareness+ const toolsSection = await getToolsSummaryForPrompt().catch(err => {+ console.log(`⚠️ Tools summary retrieval failed: ${err.message}`);+ return '';+ });++ // Build .planning/ context section for GSD-enabled apps+ let planningContextSection = '';+ if (task.metadata?.app) {+ const planningPath = join(workspaceDir, '.planning');+ const hasPlanningDir = await stat(planningPath).then(s => s.isDirectory()).catch(() => false);+ if (hasPlanningDir) {+ const planningParts = [];+ const stateContent = await readFile(join(planningPath, 'STATE.md'), 'utf-8').catch(() => null);+ if (stateContent) planningParts.push(`### Current State\n\`\`\`\n${stateContent.slice(0, 1000)}\n\`\`\``);+ const concernsContent = await readFile(join(planningPath, 'CONCERNS.md'), 'utf-8').catch(() => null);+ if (concernsContent) planningParts.push(`### Known Concerns\n\`\`\`\n${concernsContent.slice(0, 1500)}\n\`\`\``);+ const roadmapContent = await readFile(join(planningPath, 'ROADMAP.md'), 'utf-8').catch(() => null);+ if (roadmapContent) planningParts.push(`### Roadmap\n\`\`\`\n${roadmapContent.slice(0, 1000)}\n\`\`\``);+ if (planningParts.length > 0) {+ planningContextSection = `\n## Project Planning Context (.planning/)\nThis project has GSD planning documents. Use this context to understand priorities and known issues.\n\n${planningParts.join('\n\n')}\n`;+ }+ }+ }++ // Try to use the prompt template system+ const promptData = await buildPrompt('cos-agent-briefing', {+ task,+ config,+ memorySection,+ claudeMdSection,+ digitalTwinSection,+ worktreeSection,+ pipelineSection,+ jiraSection,+ simplifySection,+ reviewLoopSection,+ compactionSection,+ skillSection,+ planningContextSection,+ toolsSection,+ soulSection: digitalTwinSection, // Backwards compatibility for prompt templates+ timestamp: new Date().toISOString()+ }).catch(() => null);++ if (promptData?.prompt) {+ return promptData.prompt;+ }++ // Fallback to built-in template+ return `# Chief of Staff Agent Briefing++${claudeMdSection || ''}++${memorySection || ''}++## Task Assignment+You are an autonomous agent working on behalf of the Chief of Staff.++### Task Details+- **ID**: ${task.id}+- **Priority**: ${task.priority}+- **Description**: ${task.description}+${task.metadata?.context ? `- **Context**: ${task.metadata.context}` : ''}+${task.metadata?.app ? `- **Target App**: ${task.metadata.app}\n- **Target App Directory**: ${workspaceDir}` : ''}+${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `- **Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}+${worktreeSection}+${pipelineSection}+${jiraSection}+${simplifySection}+${reviewLoopSection}+${compactionSection}+${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${toolsSection ? `\n${toolsSection}\n` : ''}${planningContextSection}+## Instructions+1. Analyze the task requirements carefully+2. Make necessary changes to complete the task+3. Test your changes when possible+4. Provide a summary of what was done++## Guidelines+- Focus only on the assigned task+- Make minimal, targeted changes+- Follow existing code patterns and conventions+- Do not make unrelated changes+- If blocked, explain clearly why+- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only+- **BTW Messages**: The user may send you additional context while you work. Check for a \`BTW.md\` file in your working directory root — if it exists, read it for important messages from the user. Incorporate that context into your work. Do not delete or modify BTW.md.+${isTruthyMetaFn(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : task.metadata?.app && worktreeInfo && willOpenPR ? `- Commit code after each feature or bug fix using the git tools or /cam skill. A pull request will be automatically created when your task completes — do NOT open a PR manually.` : task.metadata?.app && worktreeInfo ? `- Commit code after each feature or bug fix using the git tools or /cam skill. Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}++## Git Hygiene (CRITICAL)+- **Before starting work**, run \`git status\` to verify a clean working tree. If there are uncommitted changes from a previous agent or manual work, **stash or discard them** before proceeding — do NOT commit someone else's changes.+- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.+${worktreeInfo ? `- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.` : `- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.`}+- If the working tree is dirty with changes unrelated to your task, run \`git stash\` to set them aside before starting.++## Working Directory+${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.++Begin working on the task now.`;+}++/**+ * Get workspace path for an app.+ */+export async function getAppWorkspace(appName) {+ const appsFile = join(ROOT_DIR, 'data/apps.json');++ const data = await readJSONFile(appsFile, null);+ if (!data) {+ return ROOT_DIR;+ }++ // Handle both object format { apps: { id: {...} } } and array format [...]+ const apps = data.apps || data;++ if (Array.isArray(apps)) {+ const app = apps.find(a => a.name === appName || a.id === appName);+ return app?.repoPath || ROOT_DIR;+ }++ // Object format - keys are app IDs+ const app = apps[appName] || Object.values(apps).find(a => a.name === appName);+ return app?.repoPath || ROOT_DIR;+}++/**+ * Get full app data for a task (including jira config).+ * Returns the app object or null if not found.+ */+export async function getAppDataForTask(task) {+ const appName = task?.metadata?.app;+ if (!appName) return null;++ const appsFile = join(ROOT_DIR, 'data/apps.json');+ const data = await readJSONFile(appsFile, null);+ if (!data) return null;++ const apps = data.apps || data;++ if (Array.isArray(apps)) {+ return apps.find(a => a.name === appName || a.id === appName) || null;+ }++ return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;+}++/**+ * Generate a concise JIRA ticket title from a task description using AI.+ * Falls back to truncated description on failure.+ */+export async function generateJiraTitle(description) {+ const fallback = `[CoS] ${(description || 'Automated task').substring(0, 120)}`;++ const provider = await getActiveProvider().catch(() => null);+ if (!provider) return fallback;++ const model = provider.defaultModel || provider.models?.[0];+ if (!model) return fallback;++ const prompt = `Generate a concise JIRA ticket title (max 80 chars) for this task. Output ONLY the title text, nothing else.\n\nTask: ${description}`;++ const { runId } = await createRun({ providerId: provider.id, model, prompt, source: 'jira-title' }).catch(() => ({}));+ if (!runId) return fallback;++ let title = '';++ await new Promise((resolve) => {+ const onData = (data) => { title += typeof data === 'string' ? data : (data?.text || ''); };+ const onDone = () => resolve();++ if (provider.type === 'cli') {+ executeCliRun(runId, provider, prompt, process.cwd(), onData, onDone, 30000);+ } else {+ executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onDone);+ }+ }).catch(() => {});++ title = title.trim().replace(/^["']|["']$/g, '');+ return title || fallback;+}++/**+ * Create a JIRA ticket for a task if the app has JIRA integration enabled.+ * Non-blocking — returns null on failure.+ * @returns {Promise<{ticketId: string, ticketUrl: string, summary: string}|null>}+ */+export async function createJiraTicketForTask(task, app) {+ const jira = app?.jira;+ if (!jira?.enabled || !jira.instanceId || !jira.projectKey) return null;++ const summary = await generateJiraTitle(task.description);+ const description = [+ `Automated task created by PortOS Chief of Staff.`,+ ``,+ `*Task ID:* ${task.id}`,+ `*Priority:* ${task.priority || 'MEDIUM'}`,+ `*App:* ${app.name || task.metadata?.app || 'unknown'}`,+ ``,+ `{quote}`,+ task.description || '',+ `{quote}`+ ].join('\n');++ const result = await jiraService.createTicket(jira.instanceId, {+ projectKey: jira.projectKey,+ summary,+ description,+ issueType: jira.issueType || 'Task',+ labels: jira.labels || [],+ assignee: jira.assignee,+ epicKey: jira.epicKey+ }).catch(err => {+ emitLog('warn', `Failed to create JIRA ticket: ${err.message}`, { taskId: task.id, app: app.name });+ return null;+ });++ if (!result?.ticketId) return null;++ emitLog('success', `Created JIRA ticket ${result.ticketId}`, {+ taskId: task.id,+ ticketId: result.ticketId,+ ticketUrl: result.url+ });++ return { ticketId: result.ticketId, ticketUrl: result.url, summary };+}diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsnew file mode 100644index 0000000000..fa25b9e5ef--- /dev/null+++ b/server/services/agentRunTracking.js@@ -0,0 +1,203 @@+/**+ * Agent Run Tracking+ *+ * Handles creation, completion, and run-level usage recording for CoS agent runs.+ */++import { join } from 'path';+import { writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { execSync } from 'child_process';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { recordSession, recordMessages } from './usage.js';+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';++const RUNS_DIR = PATHS.runs;++/**+ * Create a run entry for usage tracking.+ */+export async function createAgentRun(agentId, task, model, provider, workspacePath, appName) {+ const runId = uuidv4();+ const runDir = join(RUNS_DIR, runId);++ if (!existsSync(RUNS_DIR)) {+ await ensureDir(RUNS_DIR);+ }+ await mkdir(runDir);++ const metadata = {+ id: runId,+ type: 'ai',+ source: 'cos-agent',+ agentId,+ taskId: task.id,+ providerId: provider.id,+ providerName: provider.name,+ model: model || provider.defaultModel,+ workspacePath,+ workspaceName: appName || 'portos',+ prompt: (task.description || '').substring(0, 500),+ startTime: new Date().toISOString(),+ endTime: null,+ duration: null,+ exitCode: null,+ success: null,+ error: null,+ outputSize: 0+ };++ await writeFile(join(runDir, 'metadata.json'), JSON.stringify(metadata, null, 2));+ await writeFile(join(runDir, 'prompt.txt'), task.description || '');+ await writeFile(join(runDir, 'output.txt'), '');++ // Record usage session for CoS agent+ recordSession(provider.id, provider.name, model || provider.defaultModel).catch(err => {+ console.error(`❌ Failed to record usage session: ${err.message}`);+ });++ return { runId, runDir };+}++/**+ * Check if a commit was made with the task ID.+ * Returns true if a recent commit contains [task-{taskId}].+ * Returns false if git command fails (not a repo, git not available, etc.)+ */+export function checkForTaskCommit(taskId, workspacePath) {+ // Check if it's a git repo first+ const gitDir = join(workspacePath, '.git');+ if (!existsSync(gitDir)) return false;++ try {+ const searchPattern = `[task-${taskId}]`;+ const result = execSync(`git log --all --oneline --grep="${searchPattern}" -1`, {+ cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true+ }).trim();+ return result.length > 0;+ } catch {+ return false;+ }+}++/**+ * Complete a run entry with final results.+ */+export async function completeAgentRun(runId, output, exitCode, duration, errorAnalysis = null) {+ if (!runId) return; // Skip if no runId (e.g., agent recovered after restart)++ const runDir = join(RUNS_DIR, runId);+ const metaPath = join(runDir, 'metadata.json');++ const metadata = await readJSONFile(metaPath, null);+ if (!metadata) return;++ metadata.endTime = new Date().toISOString();+ metadata.duration = duration;+ metadata.exitCode = exitCode;++ // Post-execution validation: check for task commit even if exit code is non-zero+ let success = exitCode === 0;+ if (!success && metadata.taskId && metadata.workspacePath) {+ const commitFound = checkForTaskCommit(metadata.taskId, metadata.workspacePath);+ if (commitFound) {+ console.log(`⚠️ Agent ${metadata.agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${metadata.taskId}`);+ success = true;+ }+ }++ metadata.success = success;+ metadata.outputSize = Buffer.byteLength(output || '');++ // Store error details - extract from output if no analysis provided+ if (exitCode !== 0) {+ const errorInfo = errorAnalysis || extractErrorFromOutput(output, exitCode);+ metadata.error = errorInfo.message || `Process exited with code ${exitCode}`;+ metadata.errorDetails = errorInfo.details || metadata.error;+ metadata.errorCategory = errorInfo.category || 'unknown';+ metadata.suggestedFix = errorInfo.suggestedFix || null;+ if (errorInfo.compaction) {+ metadata.compaction = errorInfo.compaction;+ }+ }++ await writeFile(metaPath, JSON.stringify(metadata, null, 2));+ await writeFile(join(runDir, 'output.txt'), output || '');++ // Record usage for successful CoS agent runs (estimate ~4 chars per token)+ if (exitCode === 0 && metadata.providerId && metadata.model) {+ const estimatedTokens = Math.ceil((output || '').length / 4);+ recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {+ console.error(`❌ Failed to record usage: ${err.message}`);+ });+ }+}++/**+ * Extract error information from output when no pattern matches.+ */+export function extractErrorFromOutput(output, exitCode) {+ if (!output || output.trim().length === 0) {+ // Map common exit codes to readable messages+ const exitCodeMessages = {+ 1: 'General error',+ 2: 'Misuse of shell command',+ 126: 'Command invoked cannot execute (permission or not executable)',+ 127: 'Command not found',+ 128: 'Invalid exit argument',+ 130: 'Script terminated by Ctrl+C',+ 137: 'Process killed (SIGKILL)',+ 143: 'Process terminated (SIGTERM - likely timeout)',+ 255: 'Exit status out of range'+ };+ const codeMsg = exitCodeMessages[exitCode] || `Unknown error`;+ return {+ message: `${codeMsg} (exit code ${exitCode})`,+ details: `Process exited with code ${exitCode}. No output was captured.`,+ category: exitCode === 143 ? 'timeout' : 'unknown'+ };+ }++ const lines = output.split('\n').filter(l => l.trim());+ const lastLines = lines.slice(-20);++ // Look for common error patterns+ const errorPatterns = [+ { pattern: /API Error:\s*(\d+)/i, category: 'api-error' },+ { pattern: /error[:\s]+(.+)/i, category: 'error' },+ { pattern: /failed[:\s]+(.+)/i, category: 'failure' },+ { pattern: /exception[:\s]+(.+)/i, category: 'exception' },+ { pattern: /fatal[:\s]+(.+)/i, category: 'fatal' },+ { pattern: /not found/i, category: 'not-found' },+ { pattern: /permission denied/i, category: 'permission' },+ { pattern: /connection refused/i, category: 'connection' },+ { pattern: /timeout/i, category: 'timeout' },+ { pattern: /rate limit/i, category: 'rate-limit' },+ { pattern: /invalid.*key/i, category: 'auth' },+ { pattern: /unauthorized/i, category: 'auth' },+ { pattern: /authentication failed/i, category: 'auth' }+ ];++ const matchedErrors = [];+ let category = 'unknown';+ for (const line of lastLines) {+ for (const { pattern, category: cat } of errorPatterns) {+ if (pattern.test(line)) {+ matchedErrors.push(line.trim());+ if (category === 'unknown') category = cat;+ break;+ }+ }+ }++ // Use matched errors or fallback to last lines+ const errorLines = matchedErrors.length > 0+ ? matchedErrors.slice(0, 5)+ : lastLines.slice(-5);++ return {+ message: errorLines[0] || `Process exited with code ${exitCode}`,+ details: errorLines.join('\n') || `Process exited with code ${exitCode}`,+ category+ };+}diff --git a/server/services/agentState.js b/server/services/agentState.jsnew file mode 100644index 0000000000..16c5fda628--- /dev/null+++ b/server/services/agentState.js@@ -0,0 +1,20 @@+/**+ * Shared mutable state for agent tracking.+ * Imported by agentLifecycle.js, agentManagement.js, and subAgentSpawner.js.+ */++// activeAgents: direct spawn mode processes (Map<agentId, { process, task, runId, ... }>)+export const activeAgents = new Map();++// runnerAgents: runner-spawned agents (Map<agentId, { taskId, task, runId, model, ... }>)+export const runnerAgents = new Map();++// userTerminatedAgents: agents the user explicitly killed (Set<agentId>)+export const userTerminatedAgents = new Set();++// spawningTasks: tasks currently being spawned (Set<taskId>) — deduplication guard+export const spawningTasks = new Set();++// useRunner: whether CoS Runner mode is active+export let useRunner = false;+export const setUseRunner = (val) => { useRunner = val; };diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 65f95f68df..0d84fa7c9a 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1,144 +1,41 @@/*** Sub-Agent Spawner Service*- * Spawns Claude CLI instances to work on tasks with unrestricted mode- * and MCP server integration. Includes intelligent model selection- * and usage tracking.+ * Orchestrator module: imports from focused sub-modules and re-exports+ * everything for backward compatibility. Keeps module-level initialization+ * (initSpawner, event wiring) and shared state references.*/-import { spawn, execSync } from 'child_process';-import { join, relative, resolve, sep } from 'path';-import { writeFile, mkdir, readFile, readdir, rm, stat, unlink } from 'fs/promises'; // mkdir kept for non-recursive use+import { join } from 'path';+import { readFile, readdir, rm, stat } from 'fs/promises';import { existsSync } from 'fs';-import { homedir } from 'os';-import { v4 as uuidv4 } from '../lib/uuid.js';-import { cosEvents, emitLog } from './cosEvents.js';-import { registerAgent, updateAgent, completeAgent, appendAgentOutput } from './cosAgents.js';-import { getConfig, updateTask, addTask, getTaskById, checkStagePrecondition } from './cos.js';-import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';-import { isRunnerAvailable, spawnAgentViaRunner, terminateAgentViaRunner, killAgentViaRunner, getAgentStatsFromRunner, initCosRunnerConnection, onCosRunnerEvent, getActiveAgentsFromRunner, getRunnerHealth } from './cosRunnerClient.js';-import { getActiveProvider, getProviderById, getAllProviders } from './providers.js';-import { recordSession, recordMessages } from './usage.js';-import { isProviderAvailable, markProviderUsageLimit, markProviderRateLimited, getFallbackProvider, getProviderStatus, initProviderStatus } from './providerStatus.js';-import { buildPrompt } from './promptService.js';-import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';-import { PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS } from '../lib/validation.js';-import { getMemorySection } from './memoryRetriever.js';-import { extractAndStoreMemories } from './memoryExtractor.js';-import { getDigitalTwinForPrompt } from './digital-twin.js';-import { suggestModelTier } from './taskLearning.js';-import { ensureDir, readJSONFile, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';-import { getAppById } from './apps.js';-import { createToolExecution, startExecution, updateExecution, completeExecution, errorExecution, getExecution, getStats as getToolStats } from './toolStateMachine.js';-import { resolveThinkingLevel, getModelForLevel, isLocalPreferred } from './thinkingLevels.js';-import { getToolsSummaryForPrompt } from './tools.js';-import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';-import { detectConflicts } from './taskConflict.js';-import { createWorktree, removeWorktree, cleanupOrphanedWorktrees } from './worktreeManager.js';-import * as jiraService from './jira.js';-import * as git from './git.js';-import { executeApiRun, executeCliRun, createRun } from './runner.js';+import { emitLog, cosEvents } from './cosEvents.js';+import { appendAgentOutput, updateAgent, completeAgent } from './cosAgents.js';+import { initProviderStatus } from './providerStatus.js';+import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';+import { ensureDir, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';++// ─── Shared state (imported from agentState.js) ──────────────────────────────+export { activeAgents, runnerAgents, userTerminatedAgents, spawningTasks, useRunner } from './agentState.js';+import { activeAgents, runnerAgents, setUseRunner } from './agentState.js';++// ─── Sub-module re-exports ────────────────────────────────────────────────────+export { selectModelForTask } from './agentModelSelection.js';+export { createAgentRun, completeAgentRun, checkForTaskCommit, extractErrorFromOutput } from './agentRunTracking.js';+export { ERROR_PATTERNS, analyzeAgentFailure, createInvestigationTask, API_ACCESS_ERROR_CATEGORIES, maybeCreateInvestigationTask, resolveFailedTaskUpdate, MAX_TASK_RETRIES } from './agentErrorAnalysis.js';+export { buildAgentPrompt, getAppWorkspace, getAppDataForTask, generateJiraTitle, createJiraTicketForTask, getClaudeMdContext, buildCompactionSection, detectSkillTemplate, loadSkillTemplate } from './agentPromptBuilder.js';+export { spawnDirectly, createStreamJsonParser, summarizeToolInput, safeParse, buildCliSpawnConfig, isClaudeCliProvider, getClaudeSettingsEnv } from './agentCliSpawning.js';+export { syncRunnerAgents, spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractFinalSummary, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree } from './agentLifecycle.js';+export { terminateAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';+export { processAgentCompletion } from './agentCompletion.js';const ROOT_DIR = PATHS.root;-const AGENTS_DIR = PATHS.cosAgents;const RUNS_DIR = PATHS.runs;// Metadata booleans may arrive as true/'true' or false/'false' (from JSON vs TASKS.md string round-trip)export const isTruthyMeta = (value) => value === true || value === 'true';export const isFalsyMeta = (value) => value === false || value === 'false';-/**- * Extract task type key for learning lookup- * Matches the format used in taskLearning.js for consistency- */-function extractTaskTypeKey(task) {- if (task?.metadata?.analysisType) {- return `self-improve:${task.metadata.analysisType}`;- }- if (task?.metadata?.reviewType === 'idle') {- return 'idle-review';- }- const desc = (task?.description || '').toLowerCase();- if (desc.includes('[self-improvement]')) {- const typeMatch = desc.match(/\[self-improvement\]\s*(\w+)/i);- if (typeMatch) return `self-improve:${typeMatch[1]}`;- }- if (task?.taskType === 'user') return 'user-task';- return 'unknown';-}--/**- * Remove BTW.md from agent workspace after completion.- * Prevents ephemeral context files from being committed to git.- */-async function cleanupBtwFile(workspacePath) {- if (!workspacePath) return;- const btwPath = join(workspacePath, 'BTW.md');- await rm(btwPath).catch(() => {});-}--const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');--/**- * Skill template keyword matchers- * Each entry maps a skill template filename to its trigger keywords.- * Order matters — first match wins, so more specific patterns come first.- */-const SKILL_MATCHERS = [- {- skill: 'security-audit',- keywords: ['security', 'audit', 'vulnerability', 'xss', 'injection', 'owasp', 'cve', 'penetration', 'hardening', 'sanitize', 'authorization']- },- {- skill: 'mobile-responsive',- keywords: ['mobile', 'responsive', 'tablet', 'breakpoint', 'viewport', 'touch', 'swipe', 'small screen', 'media query', 'mobile-friendly', 'adaptive']- },- {- skill: 'bug-fix',- keywords: ['fix', 'bug', 'broken', 'error', 'crash', 'issue', 'not working', 'fails', 'regression', 'defect']- },- {- skill: 'refactor',- keywords: ['refactor', 'reorganize', 'restructure', 'clean up', 'simplify', 'extract', 'consolidate', 'decouple', 'modularize']- },- {- skill: 'documentation',- keywords: ['document', 'documentation', 'docs', 'readme', 'jsdoc', 'api docs', 'guide', 'tutorial', 'changelog']- },- {- skill: 'feature',- keywords: ['add', 'create', 'implement', 'build', 'new', 'feature', 'support', 'enable', 'integrate', 'endpoint', 'page', 'component']- }-];--/**- * Detect the best matching skill template for a task based on description keywords- * @param {Object} task - Task object with description- * @returns {string|null} Skill template name or null if no match- */-function detectSkillTemplate(task) {- const desc = (task?.description || '').toLowerCase();- for (const matcher of SKILL_MATCHERS) {- if (matcher.keywords.some(kw => desc.includes(kw))) {- return matcher.skill;- }- }- return null;-}--/**- * Load a skill template from disk if it exists- * @param {string} skillName - Name of the skill template file (without .md)- * @returns {Promise<string|null>} Template content or null- */-async function loadSkillTemplate(skillName) {- const templatePath = join(SKILLS_DIR, `${skillName}.md`);- if (!existsSync(templatePath)) return null;- const content = await readFile(templatePath, 'utf-8');- console.log(`🎯 Loaded skill template: ${skillName}`);- return content;-}-/*** Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.*/@@ -149,378 +46,8 @@ export async function loadSlashdoCommand(commandName) {}/**- * Select optimal model for a task based on complexity analysis and historical performance- * User can override by specifying Model: and/or Provider: in task metadata- *- * Enhanced with:- * - Thinking levels hierarchy (task → agent → provider)- * - Learning-based model suggestions from historical success rates- * - Automatic upgrades when task type has <60% success rate- */-async function selectModelForTask(task, provider, agent = {}) {- const desc = (task.description || '').toLowerCase();- const context = task.metadata?.context || '';- const contextLen = context.length;- const priority = task.priority || 'MEDIUM';-- // Check for user-specified model preference (highest priority)- const userModel = task.metadata?.model;- const userProvider = task.metadata?.provider;-- if (userModel) {- console.log(`👤 User specified model: ${userModel}`);- return {- model: userModel,- tier: 'user-specified',- reason: 'user-preference',- userProvider: userProvider || null- };- }-- // Check thinking level hierarchy (task → agent → provider)- // This resolves the appropriate thinking level based on configuration hierarchy- const thinkingResult = resolveThinkingLevel(task, agent, provider);- if (thinkingResult.resolvedFrom !== 'default') {- const modelFromLevel = getModelForLevel(thinkingResult.level, provider);- if (modelFromLevel) {- const isLocal = isLocalPreferred(thinkingResult.level);- console.log(`🧠 Thinking level: ${thinkingResult.level} → ${modelFromLevel} (from ${thinkingResult.resolvedFrom}${isLocal ? ', local-preferred' : ''})`);- return {- model: modelFromLevel,- tier: thinkingResult.level,- reason: `thinking-level-${thinkingResult.resolvedFrom}`,- thinkingLevel: thinkingResult.level,- localPreferred: isLocal- };- }- }-- // Image/visual analysis → would route to gemini if available- if (/image|screenshot|visual|photo|picture/.test(desc)) {- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'visual-analysis' };- }-- // Critical priority → always use opus/heavy- if (priority === 'CRITICAL') {- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'critical-priority' };- }-- // Complex reasoning tasks → opus/heavy- if (/architect|refactor|design|complex|optimize|security|audit|review.*code|performance/.test(desc)) {- return { model: provider.heavyModel || provider.defaultModel, tier: 'heavy', reason: 'complex-task' };- }-- // Long context → needs more capable model- if (contextLen > 500) {- return { model: provider.heavyModel || provider.mediumModel || provider.defaultModel, tier: 'heavy', reason: 'long-context' };- }-- // Detect coding/development tasks - these should NEVER use light model- // Intentionally inclusive: if a task mentions any coding-related term (even in- // broader context like "bug report template"), we err on the side of using- // a stronger model since misclassifying a coding task is more costly than- // over-allocating resources for a documentation task.- const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);-- // Simple/quick tasks → haiku/light (ONLY for non-coding tasks)- // Light model is reserved for documentation, text updates, and formatting only- if (!isCodingTask && /fix typo|update text|update docs|edit readme|update readme|write docs|documentation only|format text/.test(desc)) {- return { model: provider.lightModel || provider.defaultModel, tier: 'light', reason: 'documentation-task' };- }-- // Check historical performance for this task type and select optimal model tier- const taskTypeKey = extractTaskTypeKey(task);- const learningSuggestion = await suggestModelTier(taskTypeKey).catch(() => null);-- if (learningSuggestion) {- const { suggested, avoidTiers = [], reason: learningReason } = learningSuggestion;-- // Map tier names to provider model keys- const tierToModel = {- heavy: provider.heavyModel,- medium: provider.mediumModel || provider.defaultModel,- default: provider.defaultModel,- light: provider.lightModel- };-- // If we have a specific tier suggestion, use it- if (suggested && tierToModel[suggested]) {- console.log(`📊 Learning-based selection: ${taskTypeKey} → ${suggested} (${learningReason})`);- return {- model: tierToModel[suggested],- tier: suggested,- reason: 'learning-suggested',- learningReason,- avoidedTiers: avoidTiers.length > 0 ? avoidTiers : undefined- };- }-- // If no specific suggestion but we have tiers to avoid, pick the best available tier- if (avoidTiers.length > 0) {- // Try tiers in order of preference: heavy → medium → default → light- // Skip any that are in avoidTiers- const tierPreference = ['heavy', 'medium', 'default', 'light'];- for (const tier of tierPreference) {- if (!avoidTiers.includes(tier) && tierToModel[tier]) {- console.log(`📊 Learning-based avoidance: ${taskTypeKey} → ${tier} (avoiding ${avoidTiers.join(', ')})`);- return {- model: tierToModel[tier],- tier,- reason: 'learning-avoid-bad-tier',- learningReason,- avoidedTiers: avoidTiers- };- }- }- }- }-- // Standard tasks → use provider's default model- return { model: provider.defaultModel, tier: 'default', reason: 'standard-task' };-}--/**- * Create a run entry for usage tracking- */-async function createAgentRun(agentId, task, model, provider, workspacePath, appName) {- const runId = uuidv4();- const runDir = join(RUNS_DIR, runId);-- if (!existsSync(RUNS_DIR)) {- await ensureDir(RUNS_DIR);- }- await mkdir(runDir);-- const metadata = {- id: runId,- type: 'ai',- source: 'cos-agent',- agentId,- taskId: task.id,- providerId: provider.id,- providerName: provider.name,- model: model || provider.defaultModel,- workspacePath,- workspaceName: appName || 'portos',- prompt: (task.description || '').substring(0, 500),- startTime: new Date().toISOString(),- endTime: null,- duration: null,- exitCode: null,- success: null,- error: null,- outputSize: 0- };-- await writeFile(join(runDir, 'metadata.json'), JSON.stringify(metadata, null, 2));- await writeFile(join(runDir, 'prompt.txt'), task.description || '');- await writeFile(join(runDir, 'output.txt'), '');-- // Record usage session for CoS agent- recordSession(provider.id, provider.name, model || provider.defaultModel).catch(err => {- console.error(`❌ Failed to record usage session: ${err.message}`);- });-- return { runId, runDir };-}--/**- * Check if a commit was made with the task ID- * Returns true if a recent commit contains [task-{taskId}]- * Returns false if git command fails (not a repo, git not available, etc.)- */-function checkForTaskCommit(taskId, workspacePath = ROOT_DIR) {- // Check if it's a git repo first- const gitDir = join(workspacePath, '.git');- if (!existsSync(gitDir)) return false;-- try {- const searchPattern = `[task-${taskId}]`;- const result = execSync(`git log --all --oneline --grep="${searchPattern}" -1`, {- cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true- }).trim();- return result.length > 0;- } catch {- return false;- }-}--/**- * Complete a run entry with final results- */-async function completeAgentRun(runId, output, exitCode, duration, errorAnalysis = null) {- if (!runId) return; // Skip if no runId (e.g., agent recovered after restart)-- const runDir = join(RUNS_DIR, runId);- const metaPath = join(runDir, 'metadata.json');-- const metadata = await readJSONFile(metaPath, null);- if (!metadata) return;-- metadata.endTime = new Date().toISOString();- metadata.duration = duration;- metadata.exitCode = exitCode;-- // Post-execution validation: check for task commit even if exit code is non-zero- let success = exitCode === 0;- if (!success && metadata.taskId && metadata.workspacePath) {- const commitFound = checkForTaskCommit(metadata.taskId, metadata.workspacePath);- if (commitFound) {- console.log(`⚠️ Agent ${metadata.agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${metadata.taskId}`);- success = true;- }- }-- metadata.success = success;- metadata.outputSize = Buffer.byteLength(output || '');-- // Store error details - extract from output if no analysis provided- if (exitCode !== 0) {- const errorInfo = errorAnalysis || extractErrorFromOutput(output, exitCode);- metadata.error = errorInfo.message || `Process exited with code ${exitCode}`;- metadata.errorDetails = errorInfo.details || metadata.error;- metadata.errorCategory = errorInfo.category || 'unknown';- metadata.suggestedFix = errorInfo.suggestedFix || null;- if (errorInfo.compaction) {- metadata.compaction = errorInfo.compaction;- }- }-- await writeFile(metaPath, JSON.stringify(metadata, null, 2));- await writeFile(join(runDir, 'output.txt'), output || '');-- // Record usage for successful CoS agent runs (estimate ~4 chars per token)- if (exitCode === 0 && metadata.providerId && metadata.model) {- const estimatedTokens = Math.ceil((output || '').length / 4);- recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {- console.error(`❌ Failed to record usage: ${err.message}`);- });- }-}--/**- * Extract error information from output when no pattern matches- */-function extractErrorFromOutput(output, exitCode) {- if (!output || output.trim().length === 0) {- // Map common exit codes to readable messages- const exitCodeMessages = {- 1: 'General error',- 2: 'Misuse of shell command',- 126: 'Command invoked cannot execute (permission or not executable)',- 127: 'Command not found',- 128: 'Invalid exit argument',- 130: 'Script terminated by Ctrl+C',- 137: 'Process killed (SIGKILL)',- 143: 'Process terminated (SIGTERM - likely timeout)',- 255: 'Exit status out of range'- };- const codeMsg = exitCodeMessages[exitCode] || `Unknown error`;- return {- message: `${codeMsg} (exit code ${exitCode})`,- details: `Process exited with code ${exitCode}. No output was captured.`,- category: exitCode === 143 ? 'timeout' : 'unknown'- };- }-- const lines = output.split('\n').filter(l => l.trim());- const lastLines = lines.slice(-20);-- // Look for common error patterns- const errorPatterns = [- { pattern: /API Error:\s*(\d+)/i, category: 'api-error' },- { pattern: /error[:\s]+(.+)/i, category: 'error' },- { pattern: /failed[:\s]+(.+)/i, category: 'failure' },- { pattern: /exception[:\s]+(.+)/i, category: 'exception' },- { pattern: /fatal[:\s]+(.+)/i, category: 'fatal' },- { pattern: /not found/i, category: 'not-found' },- { pattern: /permission denied/i, category: 'permission' },- { pattern: /connection refused/i, category: 'connection' },- { pattern: /timeout/i, category: 'timeout' },- { pattern: /rate limit/i, category: 'rate-limit' },- { pattern: /invalid.*key/i, category: 'auth' },- { pattern: /unauthorized/i, category: 'auth' },- { pattern: /authentication failed/i, category: 'auth' }- ];-- const matchedErrors = [];- let category = 'unknown';- for (const line of lastLines) {- for (const { pattern, category: cat } of errorPatterns) {- if (pattern.test(line)) {- matchedErrors.push(line.trim());- if (category === 'unknown') category = cat;- break;- }- }- }-- // Use matched errors or fallback to last lines- const errorLines = matchedErrors.length > 0- ? matchedErrors.slice(0, 5)- : lastLines.slice(-5);-- return {- message: errorLines[0] || `Process exited with code ${exitCode}`,- details: errorLines.join('\n') || `Process exited with code ${exitCode}`,- category- };-}--/**- * Process post-completion tasks: memory extraction and app cooldown- * Shared between handleAgentCompletion (runner mode) and spawnDirectly (direct mode)- */-async function processAgentCompletion(agentId, task, success, outputBuffer) {- // Extract memories from successful output- if (success && outputBuffer.length > 100) {- const memoryResult = await extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {- console.log(`⚠️ Memory extraction failed: ${err.message}`);- return { created: 0, pendingApproval: 0 };- });- if (memoryResult.created > 0 || memoryResult.pendingApproval > 0) {- await updateAgent(agentId, {- memoryExtraction: {- created: memoryResult.created,- pendingApproval: memoryResult.pendingApproval,- extractedAt: new Date().toISOString()- }- });- }- }-- // Handle app cooldown- const appId = task.metadata?.app;- if (appId) {- const config = await getConfig();- const cooldownMs = config.appReviewCooldownMs || 3600000;-- const issuesFound = success ? 1 : 0;- const issuesFixed = success ? 1 : 0;- await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {- emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });- });-- await startAppCooldown(appId, cooldownMs).catch(err => {- emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });- });-- emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });- }-}--// Active agent processes (direct spawn mode)-const activeAgents = new Map();--// Track runner-spawned agents (CoS Runner mode)-const runnerAgents = new Map();--// Track agents terminated by user (to prevent re-queuing)-const userTerminatedAgents = new Set();--/**- * Get list of active agent IDs (for zombie detection)- * Includes both direct mode and runner mode agents+ * Get list of active agent IDs (for zombie detection).+ * Includes both direct mode and runner mode agents.*/export function getActiveAgentIds() {const directIds = Array.from(activeAgents.keys());@@ -529,570 +56,7 @@ export function getActiveAgentIds() {}/**- * Error patterns that warrant investigation tasks.- * Patterns are checked in order - first match wins.- * Categories help the learning system identify failure trends.- */-const ERROR_PATTERNS = [- // ===== API & Authentication Errors =====- {- pattern: /API Error: 404.*model:\s*(\S+)/i,- category: 'model-not-found',- actionable: true,- extract: (match, output, task, model) => ({- message: `Model "${match[1]}" not found`,- suggestedFix: `Update model configuration - "${match[1]}" doesn't exist. Check provider settings or task metadata.`,- affectedModel: match[1],- configuredModel: model- })- },- {- pattern: /API Error: 401|authentication|unauthorized/i,- category: 'auth-error',- actionable: true,- extract: () => ({- message: 'Authentication failed',- suggestedFix: 'Check API keys and provider configuration'- })- },- {- pattern: /API Error: 429|rate.?limit|too many requests/i,- category: 'rate-limit',- actionable: false, // Transient, retry will handle- extract: () => ({- message: 'Rate limit exceeded',- suggestedFix: 'Wait and retry - temporary rate limiting'- })- },- {- // Catches both "hit your usage limit" and session limits like "hit your limit · resets 6am"- pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit)/i,- category: 'usage-limit',- actionable: true, // Need to switch provider- extract: (match, output) => {- // Try to extract the wait time from the message- // e.g., "try again in 1 day 1 hour 33 minutes" or "resets 6am (America/Los_Angeles)"- const timeMatch = output.match(/(?:try again in|resets?)\s+(.+?)(?:\.|·|\n|$)/im);- const waitTime = timeMatch ? timeMatch[1].trim() : null;- return {- message: `Usage limit exceeded${waitTime ? ` - retry in ${waitTime}` : ''}`,- suggestedFix: 'Provider usage limit reached. Using fallback provider or wait for limit reset.',- waitTime,- requiresFallback: true- };- }- },- {- pattern: /API Error: 400|invalid_request_error|bad.?request/i,- category: 'bad-request',- actionable: true,- extract: (match, output) => {- const msgMatch = output.match(/"message":\s*"([^"]{1,150})"/);- return {- message: `Bad request${msgMatch ? `: ${msgMatch[1]}` : ''}`,- suggestedFix: 'API rejected the request as invalid. Check prompt formatting, tool names, and parameter sizes.'- };- }- },- {- pattern: /API Error: 403|forbidden/i,- category: 'forbidden',- actionable: true,- extract: () => ({- message: 'API access forbidden',- suggestedFix: 'API key lacks permission for this operation. Check API key permissions and provider configuration.'- })- },- {- pattern: /API Error: 5\d{2}|server error|internal error/i,- category: 'server-error',- actionable: false, // Transient- extract: () => ({- message: 'API server error',- suggestedFix: 'Retry later - temporary server issue'- })- },- {- pattern: /not_found_error.*model/i,- category: 'model-not-found',- actionable: true,- extract: (match, output, task, model) => ({- message: `Model not found in API response`,- suggestedFix: `The model "${model}" specified for this task doesn't exist. Update provider or task configuration.`,- configuredModel: model- })- },-- // ===== Context & Token Errors =====- {- pattern: /context.?length|max.?tokens|token.?limit|context.?window/i,- category: 'context-length',- actionable: true,- extract: (match, output) => ({- message: 'Context length exceeded',- suggestedFix: 'Task is too large for the context window. Break into smaller subtasks or use a model with larger context.',- compaction: {- needed: true,- reason: 'context-limit',- outputSize: Buffer.byteLength(output || ''),- retryHints: [- 'Summarize intermediate findings concisely instead of reproducing full file contents',- 'Use targeted reads (offset/limit) instead of reading entire files',- 'Avoid listing full directory trees — only reference files you modify',- 'Keep your Task Summary under 30 lines'- ]- }- })- },- {- pattern: /output.?length|max.?output|response.?too.?long/i,- category: 'output-length',- actionable: false,- extract: (match, output) => ({- message: 'Output length exceeded',- suggestedFix: 'Agent response exceeded output limit. Task may need to be scoped down.',- compaction: {- needed: true,- reason: 'output-limit',- outputSize: Buffer.byteLength(output || ''),- retryHints: [- 'Limit output to changed files and a brief summary only',- 'Do not echo file contents back — just reference file paths and line numbers',- 'Combine related changes into single descriptions'- ]- }- })- },-- // ===== Tool & MCP Errors =====- {- pattern: /tool.?(?:call|use|execution).?(?:failed|error)|failed to (?:call|execute|invoke) tool/i,- category: 'tool-error',- actionable: false,- extract: (match, output) => {- const toolMatch = output.match(/tool[:\s]+["']?(\w+)["']?/i);- return {- message: `Tool execution failed${toolMatch ? `: ${toolMatch[1]}` : ''}`,- suggestedFix: 'Tool call failed. Check if required dependencies/services are running.'- };- }- },- {- pattern: /MCP.?(?:server|connection|error)|mcp.?(?:failed|timeout)/i,- category: 'mcp-error',- actionable: false,- extract: () => ({- message: 'MCP server error',- suggestedFix: 'MCP server connection failed. Verify MCP servers are configured and accessible.'- })- },- {- pattern: /permission.?denied|access.?denied|not.?allowed|insufficient.?permissions/i,- category: 'permission-denied',- actionable: true,- extract: () => ({- message: 'Permission denied',- suggestedFix: 'Agent lacks permissions for the requested operation. Check file/directory permissions.'- })- },-- // ===== Git & Repository Errors =====- {- pattern: /git.?(?:conflict|merge.?conflict)|CONFLICT.*both modified|merge.?failed/i,- category: 'git-conflict',- actionable: true,- extract: () => ({- message: 'Git merge conflict',- suggestedFix: 'Merge conflict detected. Resolve conflicts manually before retrying.'- })- },- {- pattern: /fatal:\s*(?:not a git repository|could not|failed to|unable to)/i,- category: 'git-error',- actionable: false,- extract: (match, output) => {- const detailMatch = output.match(/fatal:\s*(.+?)(?:\n|$)/i);- return {- message: `Git error${detailMatch ? `: ${detailMatch[1].substring(0, 60)}` : ''}`,- suggestedFix: 'Git operation failed. Verify the repository state and try again.'- };- }- },- {- pattern: /nothing.?to.?commit|no.?changes|working.?tree.?clean/i,- category: 'no-changes',- actionable: false,- extract: () => ({- message: 'No changes to commit',- suggestedFix: 'Agent completed but made no code changes. Task may already be done or description needs clarification.'- })- },-- // ===== Build & Test Errors =====- {- pattern: /npm.?ERR!|yarn.?error|pnpm.?(?:ERR|error)/i,- category: 'npm-error',- actionable: false,- extract: (match, output) => {- const errMatch = output.match(/(?:npm|yarn|pnpm).?(?:ERR!|error)[:\s]*(.+?)(?:\n|$)/i);- return {- message: `Package manager error${errMatch ? `: ${errMatch[1].substring(0, 50)}` : ''}`,- suggestedFix: 'Package installation or script failed. Check package.json and dependencies.'- };- }- },- {- pattern: /test.?(?:failed|failure)|(?:failed|failing).?tests?|FAIL\s+\w+\.test/i,- category: 'test-failure',- actionable: false,- extract: () => ({- message: 'Tests failed',- suggestedFix: 'One or more tests failed. Review test output and fix failing assertions.'- })- },- {- pattern: /lint.?(?:error|failed)|eslint.?error|prettier.?error/i,- category: 'lint-error',- actionable: false,- extract: () => ({- message: 'Linting failed',- suggestedFix: 'Code style/lint errors detected. Fix formatting issues and retry.'- })- },- {- pattern: /build.?failed|compilation.?(?:failed|error)|typescript.?error|tsc.+error/i,- category: 'build-error',- actionable: false,- extract: () => ({- message: 'Build failed',- suggestedFix: 'Build/compilation failed. Fix syntax or type errors and retry.'- })- },-- // ===== Process & System Errors =====- {- pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,- category: 'network-error',- actionable: false,- extract: () => ({- message: 'Network connection failed',- suggestedFix: 'Check network connectivity and service availability.'- })- },- {- pattern: /ENOENT|file.?not.?found|no.?such.?file/i,- category: 'file-not-found',- actionable: false,- extract: (match, output) => {- const pathMatch = output.match(/(?:ENOENT|not.?found)[:\s]*['"]?([^'"}\s]+)['"]?/i);- return {- message: `File not found${pathMatch ? `: ${pathMatch[1].substring(0, 40)}` : ''}`,- suggestedFix: 'Expected file/directory does not exist. Verify paths in the task description.'- };- }- },- {- pattern: /ENOMEM|out.?of.?memory|heap.?(?:out|limit)|memory.?(?:limit|exceeded)/i,- category: 'memory-error',- actionable: true,- extract: () => ({- message: 'Out of memory',- suggestedFix: 'Process ran out of memory. Task may be too large or there is a memory leak.'- })- },- {- pattern: /timeout|timed.?out|deadline.?exceeded/i,- category: 'timeout',- actionable: false,- extract: () => ({- message: 'Operation timed out',- suggestedFix: 'Task took too long to complete. Consider breaking into smaller subtasks.'- })- },- {- pattern: /(?:killed|terminated).?(?:by.?signal|SIGTERM|SIGKILL)/i,- category: 'process-killed',- actionable: false,- extract: () => ({- message: 'Process killed',- suggestedFix: 'Agent process was terminated. May have exceeded resource limits or was killed externally.'- })- },- {- pattern: /spawn.?(?:error|failed)|EACCES|command.?not.?found/i,- category: 'spawn-error',- actionable: true,- extract: () => ({- message: 'Command spawn failed',- suggestedFix: 'Failed to start subprocess. Check that required CLI tools are installed and accessible.'- })- },-- // ===== Playwright & Browser Errors =====- {- pattern: /playwright|browser.?(?:crashed|closed|disconnected)/i,- category: 'browser-error',- actionable: false,- extract: () => ({- message: 'Browser automation failed',- suggestedFix: 'Playwright browser crashed or disconnected. Check if the dev server is running.'- })- },- {- pattern: /locator.?(?:timeout|not.?found)|element.?not.?(?:found|visible)/i,- category: 'locator-error',- actionable: false,- extract: () => ({- message: 'UI element not found',- suggestedFix: 'Could not find expected element on page. UI may have changed or selector is wrong.'- })- },-- // ===== Agent-Specific Errors =====- {- pattern: /(?:claude|anthropic).?(?:error|failed)|overloaded_error/i,- category: 'claude-error',- actionable: false,- extract: () => ({- message: 'Claude API error',- suggestedFix: 'Claude API returned an error. This is usually transient - retry recommended.'- })- },- {- pattern: /invalid.?(?:json|syntax)|JSON\.parse|SyntaxError/i,- category: 'parse-error',- actionable: false,- extract: () => ({- message: 'JSON/Syntax parse error',- suggestedFix: 'Failed to parse response or file. Check for malformed JSON or syntax errors.'- })- },- {- pattern: /task.?(?:rejected|declined|refused)|cannot.?(?:complete|perform)/i,- category: 'task-rejected',- actionable: true,- extract: () => ({- message: 'Agent rejected task',- suggestedFix: 'Agent could not or would not complete the task. Rephrase or simplify the request.'- })- },-- // ===== Limit & Billing Errors =====- {- pattern: /(?:maximum|max).*(?:turns?|iterations?|steps?)|turn.?limit|max.?turns|stopped after \d+ turns/i,- category: 'turn-limit',- actionable: false,- extract: () => ({- message: 'Agent reached turn limit',- suggestedFix: 'Task exceeded the maximum number of agent turns. Break into smaller subtasks or increase turn limit.'- })- },- {- pattern: /(?:billing|subscription|payment).?(?:error|issue|required|expired|failed)/i,- category: 'billing-error',- actionable: true,- extract: () => ({- message: 'Billing/subscription issue',- suggestedFix: 'Provider billing or subscription problem. Check provider account status.'- })- },-- // ===== Safety & Content Errors =====- {- pattern: /content.?(?:filter|policy)|safety.?(?:filter|block)|harmful.?content/i,- category: 'content-filtered',- actionable: true,- extract: () => ({- message: 'Content filtered',- suggestedFix: 'Request was blocked by content safety filter. Rephrase the task description.'- })- }-];--/**- * Analyze agent failure output and categorize the error- */-function analyzeAgentFailure(output, task, model) {- // Agent produced no meaningful output — likely failed to start- if (!output || output.trim().length < 50) {- return {- category: 'startup-failure',- actionable: false,- message: 'Agent failed to start or produced no output',- suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.'- };- }-- for (const errorDef of ERROR_PATTERNS) {- const match = output.match(errorDef.pattern);- if (match) {- const extracted = errorDef.extract(match, output, task, model);- return {- category: errorDef.category,- actionable: errorDef.actionable,- ...extracted- };- }- }-- // No pattern matched — extract meaningful context from the output- // so the learning system and dashboard show actual error details- // instead of a generic "unknown error" message- const lines = output.split('\n').filter(l => l.trim());- const lastLines = lines.slice(-20);-- // Look for lines that contain error-ish keywords (case-insensitive)- const errorKeywords = /\b(error|fail|exception|fatal|panic|abort|crash|denied|refused|invalid|cannot|could not|unable to)\b/i;- const errorLines = lastLines.filter(l => errorKeywords.test(l)).slice(0, 5);-- // Use matched error lines or fall back to last few lines of output- const contextLines = errorLines.length > 0 ? errorLines : lastLines.slice(-5);- const summary = contextLines[0]?.trim().substring(0, 120) || 'Agent failed with unrecognized error';-- return {- category: 'unknown',- actionable: false,- message: summary,- details: contextLines.map(l => l.trim()).join('\n'),- suggestedFix: 'Error did not match known patterns. Review the details or agent output logs.'- };-}--/**- * Create an investigation task in COS-TASKS.md for failed agent- */-async function createInvestigationTask(agentId, originalTask, errorAnalysis) {- const description = `[Auto] Investigate agent failure: ${errorAnalysis.message}--**Failed Agent**: ${agentId}-**Original Task**: ${originalTask.id} - ${(originalTask.description || '').substring(0, 100)}-**Error Category**: ${errorAnalysis.category}-**Suggested Fix**: ${errorAnalysis.suggestedFix}-${errorAnalysis.configuredModel ? `**Configured Model**: ${errorAnalysis.configuredModel}` : ''}-${errorAnalysis.affectedModel ? `**Affected Model**: ${errorAnalysis.affectedModel}` : ''}--Review the error, fix the configuration or code issue, and retry the original task.`;-- const investigationTask = await addTask({- description,- priority: 'HIGH',- context: `Auto-generated from agent ${agentId} failure`,- approvalRequired: true // Require human approval before auto-fixing- }, 'internal');-- emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId}`, {- agentId,- taskId: investigationTask.id,- errorCategory: errorAnalysis.category- });-- cosEvents.emit('investigation:created', {- investigationTaskId: investigationTask.id,- failedAgentId: agentId,- originalTaskId: originalTask.id,- errorAnalysis- });-- return investigationTask;-}--// Error categories where LLM API access is blocked or denied — spawning an-// investigation agent would fail for the same reason, so skip it.-const API_ACCESS_ERROR_CATEGORIES = new Set([- 'auth-error',- 'forbidden',- 'usage-limit',-]);--async function maybeCreateInvestigationTask(agentId, task, analysis) {- if (API_ACCESS_ERROR_CATEGORIES.has(analysis?.category)) {- emitLog('debug', `⏭️ Skipping investigation task for ${task.id}: API access error (${analysis.category})`, { agentId, taskId: task.id, category: analysis.category });- return;- }- await createInvestigationTask(agentId, task, analysis).catch(err => {- emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId, taskId: task.id, category: analysis?.category });- });-}--/**- * Handle task status update after agent failure.- * Tracks retry count and blocks the task after MAX_TASK_RETRIES,- * creating an investigation task instead of retrying endlessly.- *- * Returns { status, metadata } to apply to the task.- */-async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {- // Actionable errors get blocked immediately (investigation task created unless API access is denied)- if (errorAnalysis?.actionable) {- emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {- taskId: task.id, category: errorAnalysis.category- });- await maybeCreateInvestigationTask(agentId, task, errorAnalysis);- return {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: errorAnalysis.message,- blockedCategory: errorAnalysis.category,- blockedAt: new Date().toISOString()- }- };- }-- // Non-actionable errors: track retry count and block after max retries- const failureCount = (Number(task.metadata?.failureCount) || 0) + 1;- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;- const lastErrorCategory = errorAnalysis?.category || 'unknown';-- if (totalSpawns >= MAX_TOTAL_SPAWNS || failureCount >= MAX_TASK_RETRIES) {- emitLog('warn', `🚫 Task ${task.id} blocked after ${failureCount} failures (${lastErrorCategory})`, {- taskId: task.id, failureCount, category: lastErrorCategory- });- const blockedAnalysis = {- ...(errorAnalysis || {}),- message: `Task failed ${failureCount} times: ${errorAnalysis?.message || 'unknown error'}`,- suggestedFix: `Task has failed ${failureCount} consecutive times with ${lastErrorCategory} errors. ${errorAnalysis?.suggestedFix || 'Investigate agent output logs.'}`,- category: lastErrorCategory- };- await maybeCreateInvestigationTask(agentId, task, blockedAnalysis);- return {- status: 'blocked',- metadata: {- ...task.metadata,- failureCount,- lastFailureAt: new Date().toISOString(),- lastErrorCategory,- blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,- blockedCategory: lastErrorCategory,- blockedAt: new Date().toISOString()- }- };- }-- emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} (${lastErrorCategory})`, {- taskId: task.id, failureCount, maxRetries: MAX_TASK_RETRIES, category: lastErrorCategory- });-- // Propagate compaction hints to task metadata for retry prompt injection- const compaction = errorAnalysis?.compaction || null;-- return {- status: 'pending',- metadata: {- ...task.metadata,- failureCount,- lastFailureAt: new Date().toISOString(),- lastErrorCategory,- ...(compaction && { compaction })- }- };-}--// Track if using runner mode-let useRunner = false;--/**- * Initialize the spawner - listen for task:ready events+ * Initialize the spawner — listen for task:ready events.*/export async function initSpawner() {// Initialize provider status tracking@@ -1118,9 +82,17 @@ export async function initSpawner() {}// Check if CoS Runner is available- useRunner = await isRunnerAvailable();+ const runnerAvailable = await isRunnerAvailable();+ setUseRunner(runnerAvailable);++ // Lazy-import lifecycle functions (avoids circular dep at module init time)+ const { syncRunnerAgents, handleAgentCompletion, cleanupAgentWorktree } = await import('./agentLifecycle.js');+ const { cleanupOrphanedAgents, handleOrphanedTask } = await import('./agentManagement.js');+ const { spawnAgentForTask } = await import('./agentLifecycle.js');+ const { terminateAgent } = await import('./agentManagement.js');+ const { completeAgentRun } = await import('./agentRunTracking.js');- if (useRunner) {+ if (runnerAvailable) {console.log('🤖 Sub-agent spawner initialized (using CoS Runner)');initCosRunnerConnection();@@ -1146,7 +118,6 @@ export async function initSpawner() {await updateAgent(agentId, { metadata: { phase: 'working' } });emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });}-});onCosRunnerEvent('agent:completed', async (data) => {@@ -1196,2625 +167,21 @@ export async function initSpawner() {});}-/**- * Sync running agents from the runner (recovery after server restart)- * This allows us to receive completion events for agents spawned before restart- */-async function syncRunnerAgents() {- const agents = await getActiveAgentsFromRunner().catch(err => {- console.error(`❌ Failed to get active agents from runner: ${err.message}`);- return [];- });- if (agents.length === 0) return 0;-- console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);-- // Get all tasks to find task data for each agent- const { getAllTasks } = await import('./cos.js');- const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));-- // Build a task lookup map from all task sources, tagging each with its taskType- // so handleAgentCompletion updates the correct file after recovery- const taskMap = new Map();- const addTasks = (groupedTasks, taskType) => {- if (!groupedTasks) return;- for (const tasks of Object.values(groupedTasks)) {- if (Array.isArray(tasks)) {- for (const task of tasks) {- taskMap.set(task.id, { ...task, taskType });- }- }- }- };-- addTasks(allTasksData.user?.grouped, 'user');- addTasks(allTasksData.cos?.grouped, 'internal');-- let syncedCount = 0;- for (const agent of agents) {- // Only sync if not already tracked- if (!runnerAgents.has(agent.id)) {- // Try to find the task in our lookup map- const task = taskMap.get(agent.taskId);-- // Infer taskType for fallback: sys- prefix tasks are internal (CoS-generated)- const inferredType = agent.taskId?.startsWith('sys-') ? 'internal' : 'user';- runnerAgents.set(agent.id, {- taskId: agent.taskId,- task: task || { id: agent.taskId, taskType: inferredType, description: 'Recovered from runner' },- runId: null, // Run tracking may be lost on restart- model: null,- hasStartedWorking: true,- startedAt: agent.startedAt- });- console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);- syncedCount++;- }- }-- return syncedCount;-}--// Guard against duplicate spawns for the same task (e.g. immediate spawn + evaluation loop race)-const spawningTasks = new Set();--/**- * Spawn an agent for a task- */-export async function spawnAgentForTask(task) {- if (spawningTasks.has(task.id)) {- console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);- return null;- }-- // Check total spawn count across all retry types to prevent runaway respawning- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;- if (totalSpawns >= MAX_TOTAL_SPAWNS) {- console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`,- blockedCategory: 'max-spawns',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user').catch(() => {});- return null;- }-- spawningTasks.add(task.id);-- const agentId = `agent-${uuidv4().slice(0, 8)}`;-- // Determine execution lane and acquire slot- const laneName = determineLane(task);- if (!hasCapacity(laneName)) {- // Wait for lane availability (max 30 seconds)- const laneResult = await waitForLane(laneName, agentId, { timeoutMs: 30000, metadata: { taskId: task.id } });- if (!laneResult.success) {- spawningTasks.delete(task.id);- emitLog('warn', `Lane ${laneName} unavailable for task ${task.id}, deferring`, { taskId: task.id, lane: laneName });- cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'lane-capacity', lane: laneName });- return null;- }- } else {- const laneResult = acquire(laneName, agentId, { taskId: task.id });- if (!laneResult.success) {- spawningTasks.delete(task.id);- emitLog('warn', `Failed to acquire lane ${laneName}: ${laneResult.error}`, { taskId: task.id });- return null;- }- }-- // Create tool execution for state tracking- const toolExecution = createToolExecution('agent-spawn', agentId, {- taskId: task.id,- lane: laneName,- priority: task.priority- });- startExecution(toolExecution.id);-- // Helper to cleanup on early exit- const cleanupOnError = (error) => {- spawningTasks.delete(task.id);- release(agentId);- errorExecution(toolExecution.id, { message: error });- completeExecution(toolExecution.id, { success: false });- };-- // Get configuration- const config = await getConfig();- let provider = await getActiveProvider();-- if (!provider) {- cleanupOnError('No active AI provider configured');- cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });- return null;- }-- // Check provider availability (usage limits, rate limits, etc.)- const providerAvailable = isProviderAvailable(provider.id);- if (!providerAvailable) {- const status = getProviderStatus(provider.id);- emitLog('warn', `Provider ${provider.id} unavailable: ${status.message}`, {- taskId: task.id,- providerId: provider.id,- reason: status.reason- });-- // Try to get a fallback provider (check task-level, then provider-level, then system default)- const allProviders = await getAllProviders();- const taskFallbackId = task.metadata?.fallbackProvider;- const fallbackResult = await getFallbackProvider(provider.id, allProviders, taskFallbackId);-- if (fallbackResult) {- emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {- taskId: task.id,- primaryProvider: provider.id,- fallbackProvider: fallbackResult.provider.id,- fallbackSource: fallbackResult.source- });- provider = fallbackResult.provider;- } else {- // No fallback available - emit error and defer task- const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;- cleanupOnError(errorMsg);- cosEvents.emit('agent:error', {- taskId: task.id,- error: errorMsg,- providerId: provider.id,- providerStatus: status- });- // Don't spawn - task will retry later when provider recovers- return null;- }- }-- // Check if user specified a different provider in task metadata- const userProviderId = task.metadata?.provider;- if (userProviderId && userProviderId !== provider.id) {- const userProvider = await getProviderById(userProviderId);- if (userProvider) {- emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });- provider = userProvider;- } else {- emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });- }- }-- // Select optimal model for this task (async to allow learning-based suggestions)- const modelSelection = await selectModelForTask(task, provider);- let selectedModel = modelSelection.model;+// Initialize spawner when module loads (async)+initSpawner().catch(err => {+ console.error(`❌ Failed to initialize spawner: ${err.message}`);+});- // Validate model is compatible with provider- if (selectedModel && provider.models && provider.models.length > 0) {- const modelIsValid = provider.models.includes(selectedModel);- if (!modelIsValid) {- emitLog('warn', `Model "${selectedModel}" not valid for provider "${provider.id}", falling back to provider default`, {- taskId: task.id,- requestedModel: selectedModel,- providerId: provider.id,- validModels: provider.models- });- // Fall back to the appropriate tier model for this provider- selectedModel = modelSelection.tier === 'heavy' ? provider.heavyModel :- modelSelection.tier === 'light' ? provider.lightModel :- modelSelection.tier === 'medium' ? provider.mediumModel :- provider.defaultModel;- }- }+// Initialize task learning system+import('./taskLearning.js').then(taskLearning => {+ taskLearning.initTaskLearning();+}).catch(err => {+ console.error(`❌ Failed to initialize task learning: ${err.message}`);+});- const logMessage = modelSelection.learningReason- ? `Model selection: ${selectedModel} (${modelSelection.reason} - ${modelSelection.learningReason})`- : `Model selection: ${selectedModel} (${modelSelection.reason})`;- emitLog('info', logMessage, {- taskId: task.id,- model: selectedModel,- tier: modelSelection.tier,- reason: modelSelection.reason,- ...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })- });-- // Determine workspace path and resolve app name- const isReadOnly = isTruthyMeta(task.metadata?.readOnly);- // App tasks always run in the app workspace, even when read-only (e.g., code review).- // readOnly gates git/worktree operations below, not workspace selection.- let workspacePath = task.metadata?.app- ? await getAppWorkspace(task.metadata.app)- : ROOT_DIR;- const resolvedAppName = task.metadata?.app- ? (await getAppById(task.metadata.app).catch(() => null))?.name || null- : null;-- // Skip git operations, JIRA branch creation, and worktree setup for read-only tasks- let jiraTicket = null;- let jiraBranchName = null;- let worktreeInfo = null;- // Determine worktree usage flags upfront (needed for agent metadata even for read-only tasks)- const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);- const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;-- if (!isReadOnly) {- // Pull latest from git before starting work (scripted — no LLM needed)- const pullResult = await git.ensureLatest(workspacePath).catch(err => {- emitLog('warn', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });- return { success: false, error: err.message };- });-- if (pullResult.skipped) {- emitLog('debug', `Pre-task git pull skipped: ${pullResult.skipped}`, { taskId: task.id, workspace: workspacePath });- } else if (pullResult.conflict) {- // Git conflict detected — create a high-priority task for an agent to resolve it,- // then defer the original task so it retries after the conflict is fixed.- emitLog('warn', `🔀 Git conflict in ${workspacePath} (branch: ${pullResult.branch}): ${pullResult.error}`, {- taskId: task.id, workspace: workspacePath, branch: pullResult.branch- });-- const appId = task.metadata?.app || null;- const conflictDesc = `Resolve git conflict in ${resolvedAppName || workspacePath} on branch ${pullResult.branch}. `- + `The branch has diverged from origin and automatic rebase failed. `- + `Error: ${pullResult.error}`;-- await addTask({- description: conflictDesc,- priority: 'HIGH',- app: appId,- context: `This conflict is blocking task ${task.id}: "${task.description}". `- + `Resolve the conflict, commit, and push so the blocked task can proceed.`,- position: 'top'- }, 'internal').catch(err => {- emitLog('warn', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });- });-- // Return the original task to pending so it retries after the conflict is resolved- await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});- cleanupOnError(`Git conflict blocks task — conflict resolution task created`);- cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'git-conflict', branch: pullResult.branch });- return null;- } else if (pullResult.success && !pullResult.upToDate && !pullResult.skipped) {- emitLog('info', `📥 Pulled latest for ${resolvedAppName || 'workspace'} (branch: ${pullResult.branch})`, {- taskId: task.id, workspace: workspacePath, branch: pullResult.branch, stashed: pullResult.stashed- });- } else if (!pullResult.success) {- // Non-conflict failure (network error, etc.) — log warning but proceed- emitLog('warn', `⚠️ Pre-task git pull error: ${pullResult.error}`, { taskId: task.id, workspace: workspacePath });- }-- // JIRA integration: create ticket + feature branch if app has JIRA enabled and task opted in- const appData = await getAppDataForTask(task);-- if (appData?.jira?.enabled && task.metadata?.createJiraTicket) {- jiraTicket = await createJiraTicketForTask(task, appData);-- if (jiraTicket) {- // Create feature branch: feature/PROJ-123-short-description- const slug = (task.description || 'task')- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-|-$/g, '')- .substring(0, 40);- jiraBranchName = `feature/${jiraTicket.ticketId}-${slug}`;-- // For managed apps, ensure we start from the latest default branch- if (task.metadata?.app) {- await git.fetchOrigin(workspacePath).catch(() => {});- const { baseBranch: defaultBranch } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));- if (defaultBranch) {- await git.checkout(workspacePath, defaultBranch).catch(() => {});- // Fast-forward to latest origin- try { execSync(`git merge --ff-only origin/${defaultBranch}`, { cwd: workspacePath, stdio: 'ignore', windowsHide: true }); } catch (err) { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); }- }- }-- await git.createBranch(workspacePath, jiraBranchName).catch(err => {- emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });- jiraBranchName = null;- });-- if (jiraBranchName) {- emitLog('success', `Created feature branch ${jiraBranchName}`, { taskId: task.id, ticketId: jiraTicket.ticketId });- }-- // Enrich task metadata with JIRA info- task.metadata = {- ...task.metadata,- jiraTicketId: jiraTicket.ticketId,- jiraTicketUrl: jiraTicket.ticketUrl,- jiraBranch: jiraBranchName,- jiraInstanceId: appData.jira.instanceId,- jiraCreatePR: appData.jira.createPR !== false- };- }- }-- // Feature agent tasks: use persistent worktree instead of creating a new one- if (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {- const { getFeatureAgent } = await import('./featureAgents.js');- const fa = await getFeatureAgent(task.metadata.featureAgentId).catch(() => null);- if (fa) {- const faWorktreePath = join(PATHS.cos, 'feature-agents', fa.id, 'worktree');- if (existsSync(faWorktreePath)) {- workspacePath = faWorktreePath;- worktreeInfo = {- worktreePath: faWorktreePath,- branchName: fa.git.branchName,- baseBranch: fa.git.baseBranch || 'main',- isPersistentWorktree: true- };- // Merge base branch into feature worktree before starting- const { mergeBaseIntoFeatureWorktree } = await import('./worktreeManager.js');- if (fa.git.autoMergeBase) {- await mergeBaseIntoFeatureWorktree(fa.id, fa.git.baseBranch).catch(err => {- emitLog('warn', `🌳 Feature agent base merge failed: ${err.message}`, { featureAgentId: fa.id });- });- }- emitLog('info', `🌳 Feature agent ${fa.name} using persistent worktree: ${fa.git.branchName}`, {- featureAgentId: fa.id, worktreePath: faWorktreePath- });- }- }- }-- if (explicitWorktree && !jiraBranchName) {- // User explicitly requested worktree via task creation UI- const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));- emitLog('info', `🌳 Worktree requested for task ${task.id} — creating isolated worktree from ${detectedBase || 'default branch'}`, {- taskId: task.id, app: task.metadata?.app, baseBranch: detectedBase- });-- worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {- baseBranch: detectedBase || undefined- }).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} (base: ${worktreeInfo.baseBranch})`, {- agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch- });- }- } else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {- // No explicit worktree requested and not explicitly disabled: use worktree only when conflict is detected- 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 });- }- }- } // end !isReadOnly-- // Build the agent prompt (includes worktree and JIRA context if applicable)- const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo);-- // Create agent directory- const agentDir = join(AGENTS_DIR, agentId);- if (!existsSync(agentDir)) {- await ensureDir(agentDir);- }-- // Save prompt to file- await writeFile(join(agentDir, 'prompt.txt'), prompt);-- // Create run entry for usage tracking- const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);-- // Register the agent with model info (include worktree metadata + task metadata for learning)- 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,- isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,- taskDescription: task.description,- taskType: task.taskType,- priority: task.priority,- providerId: provider.id,- model: selectedModel,- modelTier: modelSelection.tier,- modelReason: modelSelection.reason,- runId,- phase: 'initializing',- useRunner,- // Forward task metadata fields for learning classification- taskAnalysisType: task.metadata?.analysisType || null,- taskReviewType: task.metadata?.reviewType || null,- taskApp: task.metadata?.app || null,- taskAppName: resolvedAppName,- selfImprovementType: task.metadata?.selfImprovementType || null,- jobId: task.metadata?.jobId || null,- missionName: task.metadata?.missionName || null,- missionId: task.metadata?.missionId || null,- // JIRA integration metadata- jiraTicketId: task.metadata?.jiraTicketId || null,- jiraTicketUrl: task.metadata?.jiraTicketUrl || null,- jiraBranch: task.metadata?.jiraBranch || null,- jiraInstanceId: task.metadata?.jiraInstanceId || null,- jiraCreatePR: task.metadata?.jiraCreatePR ?? null,- // Agent configuration flags (visible in UI)- configOpenPR: isTruthyMeta(task.metadata?.openPR),- configSimplify: isTruthyMeta(task.metadata?.simplify),- configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),- configUseWorktree: !!worktreeInfo,- configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,- configCodingOnMain: !worktreeInfo && !jiraBranchName- });-- emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });-- // Mark the task as in_progress and increment total spawn count- const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;- const updateResult = await updateTask(task.id, {- status: 'in_progress',- metadata: {- ...task.metadata,- totalSpawnCount: newSpawnCount,- lastSpawnedAt: new Date().toISOString()- }- }, task.taskType || 'user')- .catch(err => {- console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);- return null;- });- spawningTasks.delete(task.id);- if (!updateResult) {- cleanupOnError('Failed to update task status');- return null;- }-- // Record autonomous job execution now that the task is confirmed spawning- if (task.metadata?.autonomousJob && task.metadata?.jobId) {- cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });- }-- // 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, worktree: !!worktreeInfo });-- // Use CoS Runner if available, otherwise spawn directly- if (useRunner) {- return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, toolExecution.id, laneName);- }-- // Direct spawn mode (fallback)- return spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName);-}--/**- * Minimum runner uptime (seconds) before spawning agents.- * Prevents race condition during rolling restarts where server starts- * before runner, spawns an agent, then runner restarts and orphans it.- */-const RUNNER_MIN_UPTIME_SECONDS = 10;--/**- * Wait for runner to be stable (sufficient uptime) before spawning- */-async function waitForRunnerStability() {- const maxWaitMs = 15000;- const checkIntervalMs = 1000;- const startTime = Date.now();-- while (Date.now() - startTime < maxWaitMs) {- const health = await getRunnerHealth();- if (health.available && health.uptime >= RUNNER_MIN_UPTIME_SECONDS) {- return true;- }- if (health.available && health.uptime < RUNNER_MIN_UPTIME_SECONDS) {- const waitTime = Math.ceil(RUNNER_MIN_UPTIME_SECONDS - health.uptime);- emitLog('info', `Waiting ${waitTime}s for runner stability (uptime: ${Math.floor(health.uptime)}s)`, { uptime: health.uptime });- }- await new Promise(resolve => setTimeout(resolve, checkIntervalMs));- }-- emitLog('warn', 'Runner stability check timed out, proceeding anyway', {});- return false;-}--/**- * Spawn agent via CoS Runner (isolated PM2 process)- */-async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, executionId, laneName) {- // Wait for runner to be stable to prevent orphaned agents during rolling restarts- await waitForRunnerStability();-- // Store tracking info for runner-spawned agents- const agentInfo = {- taskId: task.id,- task,- runId,- model,- providerId: provider.id,- hasStartedWorking: false,- startedAt: Date.now(),- initializationTimeout: null,- executionId,- laneName,- workspacePath- };- runnerAgents.set(agentId, agentInfo);-- // If no output after 3 seconds, transition from initializing to working to show progress- agentInfo.initializationTimeout = setTimeout(async () => {- const agent = runnerAgents.get(agentId);- if (agent && !agent.hasStartedWorking) {- agent.hasStartedWorking = true;- await updateAgent(agentId, { metadata: { phase: 'working' } });- emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });- }- }, 3000);-- // For Claude CLI providers, merge ~/.claude/settings.json env vars so Bedrock config- // (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.) is present in the runner spawn env- const claudeSettingsEnv = isClaudeCliProvider(provider)- ? await getClaudeSettingsEnv()- : {};-- const result = await spawnAgentViaRunner({- agentId,- taskId: task.id,- prompt,- workspacePath,- model,- envVars: { ...claudeSettingsEnv, ...provider.envVars },- cliCommand: cliConfig.command,- cliArgs: cliConfig.args- });-- // Store PID in persisted state for zombie detection- await updateAgent(agentId, { pid: result.pid });-- emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });- return agentId;-}--/**- * Extract the final summary section from agent output.- * Walks backwards from the end to find the last block of non-tool-call content.- */-function extractFinalSummary(outputBuffer) {- if (!outputBuffer) return null;-- const lines = outputBuffer.split('\n');- const contentLines = [];- let foundContent = false;-- for (let i = lines.length - 1; i >= 0; i--) {- const line = lines[i];- const isTool = line.startsWith('🔧') || line.startsWith(' →') || line.startsWith(' ↳') || line.startsWith('[stderr]');-- if (!isTool && line.trim()) {- contentLines.unshift(line);- foundContent = true;- } else if (foundContent && isTool) {- break;- }- }-- const summary = contentLines.join('\n').trim();- return summary || null;-}--/**- * Extract a concise output summary for pipeline stage agents.- * For review stages: reads the generated REVIEW.md from the workspace.- * For implement stages: extracts the final summary from the output.- */-async function extractPipelineOutputSummary(task, workspacePath, outputBuffer) {- const pipeline = task.metadata?.pipeline;- if (!pipeline?.stages) return null;-- const currentStage = pipeline.currentStage ?? 0;- const stage = pipeline.stages[currentStage];- if (!stage) return null;-- const promptKey = stage.promptKey || '';-- // For review stages: read REVIEW.md from workspace (the deliverable)- if (promptKey.includes('review') && !promptKey.includes('implement') && workspacePath) {- const reviewPath = join(workspacePath, 'REVIEW.md');- const content = await readFile(reviewPath, 'utf-8').catch(() => null);- if (content?.trim()) return content.trim();- }-- // For implement/triage stages or fallback: extract last content section from output- return extractFinalSummary(outputBuffer);-}--/**- * Advance a pipeline to its next stage after the current stage completes.- * Creates a new task for the next stage or marks the pipeline as complete/failed.- */-async function handlePipelineProgression(task, agentId, success) {- const pipeline = task.metadata?.pipeline;- if (!pipeline || pipeline.status !== 'running') return;-- const { currentStage, stages } = pipeline;- const stageResult = {- stage: currentStage,- name: stages[currentStage]?.name,- agentId,- success,- completedAt: new Date().toISOString()- };- const updatedResults = [...(pipeline.stageResults || []), stageResult];-- if (!success) {- await updateTask(task.id, {- metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }- }, task.taskType);- emitLog('warn', `⛔ Pipeline ${pipeline.id} failed at stage ${currentStage}: ${stages[currentStage]?.name}`, { pipelineId: pipeline.id });- return;- }-- const nextStageIndex = currentStage + 1;- if (nextStageIndex >= stages.length) {- await updateTask(task.id, {- metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'completed', stageResults: updatedResults } }- }, task.taskType);- // Clean up pipeline artifacts (e.g., REVIEW.md left by stage 1)- if (task.metadata.repoPath) {- const repoRoot = resolve(task.metadata.repoPath);- for (const stage of stages) {- const file = stage.precondition?.fileNotExists;- if (file) {- const filePath = resolve(repoRoot, file);- // Only delete files within the repo directory (prevent path traversal)- const rel = relative(repoRoot, filePath);- if (!rel || rel === '..' || rel.startsWith('..' + sep) || resolve(rel) === rel) continue;- await unlink(filePath).catch(() => {});- }- }- }- emitLog('info', `✅ Pipeline ${pipeline.id} completed all ${stages.length} stages`, { pipelineId: pipeline.id });- return;- }-- const nextStage = stages[nextStageIndex];-- // Check next stage's precondition before advancing- if (nextStage.precondition && task.metadata.repoPath) {- const check = checkStagePrecondition(nextStage, task.metadata.repoPath);- if (!check.passed) {- await updateTask(task.id, {- metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }- }, task.taskType);- emitLog('warn', `⏭️ Pipeline ${pipeline.id} stage ${nextStageIndex} precondition failed: ${check.reason}`, { pipelineId: pipeline.id });- return;- }- }-- const taskScheduleMod = await import('./taskSchedule.js');- let prompt = await taskScheduleMod.getStagePrompt(task.metadata.analysisType, nextStageIndex);- if (task.metadata.appName) prompt = prompt.replace(/\{appName\}/g, task.metadata.appName);- if (task.metadata.repoPath) prompt = prompt.replace(/\{repoPath\}/g, task.metadata.repoPath);- if (task.metadata.app) prompt = prompt.replace(/\{appId\}/g, task.metadata.app);-- const nextTask = {- id: `${task.id || 'sys-pipeline'}-stage${nextStageIndex}-${Date.now().toString(36)}`,- status: 'pending',- description: prompt,- priority: task.priority || 'MEDIUM',- metadata: {- ...task.metadata,- readOnly: nextStage.readOnly ?? false,- pipeline: {- ...pipeline,- currentStage: nextStageIndex,- stageResults: updatedResults,- previousStageAgentId: agentId,- status: 'running'- }- },- autoApproved: true- };- if (nextStage.model) nextTask.metadata.model = nextStage.model;- if (nextStage.providerId) {- nextTask.metadata.provider = nextStage.providerId;- nextTask.metadata.providerId = nextStage.providerId;- }- // Apply per-stage overrides for agent behavior flags- // Read-only stages default to false; write stages restore task-level defaults- const stageReadOnly = nextStage.readOnly ?? false;- const taskDefaults = pipeline.taskDefaults || {};- for (const flag of PIPELINE_BEHAVIOR_FLAGS) {- if (flag in nextStage) {- nextTask.metadata[flag] = nextStage[flag];- } else if (stageReadOnly) {- nextTask.metadata[flag] = false;- } else if (flag in taskDefaults) {- nextTask.metadata[flag] = taskDefaults[flag];- }- }-- await addTask(nextTask, 'internal', { raw: true });- emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });-}--/**- * Handle agent completion (from runner events)- */-async function handleAgentCompletion(agentId, exitCode, success, duration) {- const agent = runnerAgents.get(agentId);- if (!agent) {- // Agent not in memory map (server restarted). Check cos state for context.- const { getAgent: getAgentState } = await import('./cos.js');- const cosAgent = await getAgentState(agentId).catch(() => null);- if (!cosAgent) {- console.log(`⚠️ Received completion for unknown agent: ${agentId} (not in cos state)`);- return;- }- if (cosAgent.status === 'completed') {- console.log(`✅ Agent ${agentId} already completed (handled by orphan cleanup)`);- return;- }- // Agent still running in cos state but not in memory - handle completion with cos data- console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);- await completeAgent(agentId, {- success,- exitCode,- duration,- orphaned: true,- error: success ? undefined : 'Agent completed after server restart'- });- if (cosAgent.taskId) {- const task = await getTaskById(cosAgent.taskId).catch(() => null);- if (task && task.status !== 'completed') {- if (success) {- await updateTask(cosAgent.taskId, { status: 'completed' }, task.taskType || 'user');- } else {- // Route through handleOrphanedTask for consistent retry counting, cooldown, and limits- await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById);- }- }- }- return;- }-- const { task, runId, model, executionId, laneName } = agent;-- // Ensure taskType is set — recovered agents may lack it, causing updateTask to search the wrong file- if (task && !task.taskType) {- const id = task.id || '';- task.taskType = (id.startsWith('sys-') || id.startsWith('app-improve-')) ? 'internal' : 'user';- }-- // Release execution lane- if (laneName) {- release(agentId);- }-- // Complete tool execution tracking- if (executionId) {- if (success) {- completeExecution(executionId, { success: true, duration });- } else {- errorExecution(executionId, { message: `Agent exited with code ${exitCode}`, code: exitCode });- completeExecution(executionId, { success: false });- }- }-- // Read output from agent directory- const agentDir = join(AGENTS_DIR, agentId);- const outputFile = join(agentDir, 'output.txt');- let outputBuffer = '';- if (existsSync(outputFile)) {- outputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');- }-- // Post-execution validation: check for task commit even if exit code is non-zero- // This catches cases where the agent was killed/crashed after committing work- let effectiveSuccess = success;- if (!effectiveSuccess && task?.id) {- const workspacePath = agent.workspacePath || ROOT_DIR;- const commitFound = checkForTaskCommit(task.id, workspacePath);- if (commitFound) {- emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });- effectiveSuccess = true;- }- }-- // Analyze failure if applicable- const errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);-- // Extract pipeline output summary before completion writes metadata to disk- if (task?.metadata?.pipeline && effectiveSuccess) {- const workspacePath = agent.workspacePath || ROOT_DIR;- const summary = await extractPipelineOutputSummary(task, workspacePath, outputBuffer).catch(err => {- console.log(`⚠️ Failed to extract pipeline summary for ${agentId}: ${err.message}`);- return null;- });- if (summary) {- await updateAgent(agentId, { metadata: { outputSummary: summary } });- }- }-- await completeAgent(agentId, {- success: effectiveSuccess,- exitCode,- duration,- outputLength: outputBuffer.length,- errorAnalysis- });-- // Complete run tracking (skip if no runId - agent was recovered after restart)- if (runId) {- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);- }-- // Update task status with retry tracking- if (effectiveSuccess) {- const result = await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');- if (result?.error) {- emitLog('warn', `⚠️ Failed to mark task ${task.id} completed: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });- }- } else {- const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);- const result = await updateTask(task.id, failedUpdate, task.taskType || 'user');- if (result?.error) {- emitLog('warn', `⚠️ Failed to update failed task ${task.id}: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });- }-- // Handle provider status updates on failure- if (errorAnalysis) {- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {- const providerId = agent.providerId || (await getActiveProvider())?.id;- if (providerId) {- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });- });- }- }- if (errorAnalysis.category === 'rate-limit') {- const providerId = agent.providerId || (await getActiveProvider())?.id;- if (providerId) {- await markProviderRateLimited(providerId).catch(err => {- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });- });- }- }- }- }-- // Process memory extraction and app cooldown- await processAgentCompletion(agentId, task, effectiveSuccess, outputBuffer);-- // Fetch agent state once for JIRA and plan-question blocks- const { getAgent: getAgentState } = await import('./cos.js');- const agentState = await getAgentState(agentId).catch(() => null);-- // JIRA integration: push branch, create PR, comment on ticket- const jiraTicketId = agent.task?.metadata?.jiraTicketId;- const jiraBranch = agent.task?.metadata?.jiraBranch;- const jiraInstanceId = agent.task?.metadata?.jiraInstanceId;- const jiraCreatePR = agent.task?.metadata?.jiraCreatePR;-- if (jiraTicketId && jiraBranch && success) {- const workspace = agentState?.metadata?.workspacePath || ROOT_DIR;-- // Resolve JIRA ticket URL for linking in PR description- let jiraTicketUrl = agent.task?.metadata?.jiraTicketUrl || null;- if (!jiraTicketUrl && jiraInstanceId) {- const jiraConfig = await jiraService.getInstances().catch(() => null);- const baseUrl = jiraConfig?.instances?.[jiraInstanceId]?.baseUrl;- if (baseUrl) jiraTicketUrl = `${baseUrl}/browse/${jiraTicketId}`;- }- const jiraTicketRef = jiraTicketUrl ? `[${jiraTicketId}](${jiraTicketUrl})` : jiraTicketId;-- // Push the feature branch- await git.push(workspace, jiraBranch).catch(err => {- emitLog('warn', `Failed to push JIRA branch ${jiraBranch}: ${err.message}`, { agentId, ticketId: jiraTicketId });- });-- // Create PR if configured (default true when JIRA is enabled)- let prUrl = null;- if (jiraCreatePR !== false) {- const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));- const targetBranch = devBranch || baseBranch || 'main';-- const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);- const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;-- const prResult = await git.createPR(workspace, {- title: `${jiraTicketId}: ${(task.description || 'CoS automated task').substring(0, 100)}`,- body: jiraPrBodyWithRef,- base: targetBranch,- head: jiraBranch- }).catch(err => {- emitLog('warn', `Failed to create PR for ${jiraTicketId}: ${err.message}`, { agentId });- return null;- });-- if (prResult?.success) {- prUrl = prResult.url;- emitLog('success', `Created PR: ${prUrl}`, { agentId, ticketId: jiraTicketId });- }- }-- // Comment on JIRA ticket with results- if (jiraInstanceId) {- const commentLines = [`Agent completed task successfully.`];- if (prUrl) {- commentLines.push(`\n*Pull Request:* ${prUrl}`);- } else if (jiraBranch) {- commentLines.push(`\n*Branch:* \`${jiraBranch}\``);- }- await jiraService.addComment(jiraInstanceId, jiraTicketId, commentLines.join('\n')).catch(err => {- emitLog('warn', `Failed to comment on JIRA ticket ${jiraTicketId}: ${err.message}`, { agentId });- });- }-- // Checkout back to original branch- const { devBranch: dev, baseBranch: base } = await git.getRepoBranches(workspace).catch(() => ({ devBranch: null, baseBranch: null }));- const returnBranch = dev || base || 'main';- await git.checkout(workspace, returnBranch).catch(err => {- emitLog('warn', `Failed to checkout back to ${returnBranch}: ${err.message}`, { agentId });- });- }-- // Check for plan questions marker file (feature-ideas task needing user input)- if (task?.metadata?.analysisType === 'feature-ideas') {- const planWorkspace = agentState?.metadata?.workspacePath || task?.metadata?.repoPath || ROOT_DIR;- const markerPath = join(planWorkspace, '.plan-questions.md');-- const markerContent = await readFile(markerPath, 'utf8').catch(() => null);- if (markerContent) {- const titleMatch = markerContent.match(/^#\s+Plan Question:\s*(.+)/m);- const title = titleMatch?.[1]?.trim() || 'PLAN.md item needs your input';- const appId = task.metadata?.app;-- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');- await addNotification({- type: NOTIFICATION_TYPES.PLAN_QUESTION,- title,- message: markerContent,- priority: PRIORITY_LEVELS.MEDIUM,- link: appId ? `/apps/${appId}/documents` : undefined,- metadata: { appId, agentId, taskType: 'feature-ideas' }- }).catch(err => {- emitLog('warn', `Failed to create plan_question notification: ${err.message}`, { agentId });- });-- await rm(markerPath).catch(() => {});- emitLog('info', `📋 Plan question notification created: ${title}`, { agentId, appId });- }- }-- // Advance pipeline to next stage if applicable- if (task?.metadata?.pipeline) {- await handlePipelineProgression(task, agentId, effectiveSuccess);- }-- // Clean up ephemeral BTW.md before worktree removal- await cleanupBtwFile(agentState?.metadata?.workspacePath);-- // Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)- if (!jiraBranch) {- const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);- const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);- const cleanupWarnings = await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description, agentOutput: outputBuffer });-- if (cleanupWarnings?.length > 0) {- // Merge warnings into existing result (updateAgent shallow-merges, so spread existing result to preserve fields)- const { getAgent: getAgentForResult } = await import('./cos.js');- const currentAgent = await getAgentForResult(agentId).catch(() => null);- await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });-- // Create a notification for significant cleanup issues- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');- const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';- await addNotification({- type: NOTIFICATION_TYPES.AGENT_WARNING,- title: `Agent cleanup issue: ${appName}`,- description: cleanupWarnings.join('\n'),- priority: PRIORITY_LEVELS.HIGH,- link: '/cos/agents',- metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }- }).catch(err => {- emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });- });- }- }-- runnerAgents.delete(agentId);-}--/**- * Clean up a worktree for a completed agent.- * Reads worktree metadata from the agent's registered state and removes the worktree.- * When openPR is true, pushes the branch and creates a PR instead of auto-merging.- * Otherwise, merges the worktree branch back to the source branch on success.- */-export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null, agentOutput = null } = {}) {- const { getAgent: getAgentState } = await import('./cos.js');- const agentState = await getAgentState(agentId).catch(() => null);- if (!agentState?.metadata?.isWorktree) return [];- if (agentState?.metadata?.isPersistentWorktree) return [];-- const { sourceWorkspace, worktreeBranch } = agentState.metadata;- if (!sourceWorkspace || !worktreeBranch) return [];-- const warnings = [];-- // When openPR is set and task succeeded, push branch and create PR instead of auto-merging- if (openPR && success) {- emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });-- const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);-- const [pushResult, branchInfo] = await Promise.all([- git.push(worktreePath, worktreeBranch).then(() => true).catch(err => {- emitLog('warn', `🌳 Failed to push worktree branch ${worktreeBranch}: ${err.message}`, { agentId });- return false;- }),- git.getRepoBranches(sourceWorkspace).catch(() => ({ baseBranch: null, devBranch: null }))- ]);-- if (pushResult) {- const targetBranch = branchInfo.baseBranch || 'main';- const taskDesc = description || 'CoS automated task';- const prTitle = taskDesc.replace(/[\r\n]+/g, ' ').trim().substring(0, 100);-- const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput);-- const prResult = await git.createPR(worktreePath, {- title: prTitle,- body: prBody,- base: targetBranch,- head: worktreeBranch- }).catch(err => {- emitLog('warn', `🌳 Failed to create PR for ${worktreeBranch}: ${err.message}`, { agentId });- return null;- });-- if (!prResult?.success) {- const reason = prResult?.error || 'unknown error (createPR returned null or threw)';- emitLog('error', `🌳 PR creation failed for ${worktreeBranch}: ${reason}`, { agentId, branchName: worktreeBranch });- warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);- return warnings;- }-- emitLog('success', `🌳 Created PR: ${prResult.url}`, { agentId, branchName: worktreeBranch });-- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {- emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });- return { warnings: [`Worktree cleanup failed: ${err.message}`] };- });- warnings.push(...(result?.warnings || []));- return warnings;- }-- // Push failed — preserve worktree/branch for manual intervention- warnings.push(`Push failed for branch ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`);- emitLog('warn', `🌳 Push failed for ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`, { agentId, branchName: worktreeBranch });- return warnings;- }-- // Default: auto-merge on success, just cleanup on failure- emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${success})`, {- agentId, branchName: worktreeBranch, merge: success- });-- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {- emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });- return { warnings: [`Worktree cleanup failed: ${err.message}`] };- });- warnings.push(...(result?.warnings || []));- return warnings;-}--/**- * Spawn agent directly (fallback when runner not available)- */-async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, agentDir, executionId, laneName) {- const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;-- // Ensure workspacePath is valid- const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;-- // For Claude CLI providers, inject ~/.claude/settings.json env vars so Bedrock config- // (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.) is present even if PM2 lacks them- const claudeSettingsEnv = isClaudeCliProvider(provider)- ? await getClaudeSettingsEnv()- : {};-- const claudeProcess = spawn(cliConfig.command, cliConfig.args, {- cwd,- shell: false,- stdio: ['pipe', 'pipe', 'pipe'],- windowsHide: true,- env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; return e; })()- });-- registerSpawnedAgent(claudeProcess.pid, {- fullCommand,- agentId,- taskId: task.id,- model,- workspacePath,- prompt: (task.description || '').substring(0, 500)- });-- claudeProcess.stdin.write(prompt);- claudeProcess.stdin.end();-- activeAgents.set(agentId, {- process: claudeProcess,- taskId: task.id,- startedAt: Date.now(),- runId,- pid: claudeProcess.pid,- providerId: provider.id,- executionId,- laneName- });-- // Store PID in persisted state for zombie detection- await updateAgent(agentId, { pid: claudeProcess.pid });-- let outputBuffer = '';- let rawStreamBuffer = ''; // Raw stdout for stream-json (used for error analysis)- let hasStartedWorking = false;- const outputFile = join(agentDir, 'output.txt');- const isStreamJson = cliConfig.streamFormat === 'stream-json';- const streamParser = isStreamJson ? createStreamJsonParser() : null;-- // If no output after 3 seconds, transition from initializing to working to show progress- const initializationTimeout = setTimeout(async () => {- if (!hasStartedWorking && activeAgents.has(agentId)) {- hasStartedWorking = true;- await updateAgent(agentId, { metadata: { phase: 'working' } });- emitLog('info', `Agent ${agentId} working (after initialization delay)...`, { agentId, phase: 'working' });- }- }, 3000);-- claudeProcess.stdout.on('data', async (data) => {- const text = data.toString();-- if (!hasStartedWorking) {- hasStartedWorking = true;- await updateAgent(agentId, { metadata: { phase: 'working' } });- emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });- }-- if (streamParser) {- // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)- rawStreamBuffer += text;- if (rawStreamBuffer.length > 512 * 1024) {- rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);- }- const lines = streamParser.processChunk(text);- for (const line of lines) {- outputBuffer += line + '\n';- await appendAgentOutput(agentId, line);- }- await writeFile(outputFile, outputBuffer).catch(() => {});- } else {- // Non-stream providers: emit raw stdout as before- outputBuffer += text;- await writeFile(outputFile, outputBuffer).catch(() => {});- await appendAgentOutput(agentId, text);- }- });-- claudeProcess.stderr.on('data', async (data) => {- const text = data.toString();- // Codex stderr: show thinking + tool names, skip config dump and command output- if (provider.id === 'codex') {- for (const line of text.split('\n')) {- const trimmed = line.trim();- if (!trimmed) continue;- if (trimmed.startsWith('Reading prompt from stdin')) continue;- if (trimmed.startsWith('OpenAI Codex v')) continue;- if (trimmed.startsWith('succeeded in')) continue;- // Tool calls: show just the command, strip output after "succeeded"- if (trimmed.startsWith('exec ')) {- const match = trimmed.match(/^exec\s+\S+\s+-lc\s+(['"])(.*?)\1/);- const cmd = match ? match[2] : trimmed.split(' in /')[0];- const display = `🔧 ${cmd}`;- outputBuffer += display + '\n';- await appendAgentOutput(agentId, display);- continue;- }- // Skip long lines (command output like file contents, directory listings)- if (trimmed.length > 300) continue;- outputBuffer += trimmed + '\n';- await appendAgentOutput(agentId, trimmed);- }- await writeFile(outputFile, outputBuffer).catch(() => {});- return;- }- outputBuffer += `[stderr] ${text}`;- await writeFile(outputFile, outputBuffer).catch(() => {});- await appendAgentOutput(agentId, `[stderr] ${text}`);- });-- claudeProcess.on('error', async (err) => {- clearTimeout(initializationTimeout);- console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);-- // Release execution lane- if (laneName) {- release(agentId);- }-- // Complete tool execution tracking with error- if (executionId) {- errorExecution(executionId, { message: err.message, category: 'spawn-error' });- completeExecution(executionId, { success: false });- }-- cosEvents.emit('agent:error', { agentId, error: err.message });- await completeAgent(agentId, { success: false, error: err.message });- await completeAgentRun(runId, outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });- unregisterSpawnedAgent(claudeProcess.pid);- activeAgents.delete(agentId);- });-- claudeProcess.on('close', async (code) => {- clearTimeout(initializationTimeout);- const success = code === 0;- const agentData = activeAgents.get(agentId);- const duration = Date.now() - (agentData?.startedAt || Date.now());-- // Flush remaining stream parser data- if (streamParser) {- const remaining = streamParser.flush();- for (const line of remaining) {- outputBuffer += line + '\n';- await appendAgentOutput(agentId, line);- }- // Use the parsed final result for the output file if available- const finalResult = streamParser.getFinalResult();- if (finalResult) {- outputBuffer = finalResult;- }- }-- // Release execution lane- if (agentData?.laneName) {- release(agentId);- }-- // Complete tool execution tracking- if (agentData?.executionId) {- if (success) {- completeExecution(agentData.executionId, { success: true, duration });- } else {- errorExecution(agentData.executionId, { message: `Agent exited with code ${code}`, code });- completeExecution(agentData.executionId, { success: false });- }- }-- await writeFile(outputFile, outputBuffer).catch(() => {});-- // Use raw stream buffer for error analysis (contains full JSON with error details)- const analysisBuffer = rawStreamBuffer || outputBuffer;- const errorAnalysis = success ? null : analyzeAgentFailure(analysisBuffer, task, model);-- await completeAgent(agentId, {- success,- exitCode: code,- duration,- outputLength: outputBuffer.length,- errorAnalysis- });-- await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis);-- // Update task status with retry tracking- // Skip if user-terminated — task already blocked by terminateAgent/killAgent- if (userTerminatedAgents.has(agentId)) {- userTerminatedAgents.delete(agentId);- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Terminated by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');- } else if (success) {- await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');- } else {- const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);- await updateTask(task.id, failedUpdate, task.taskType || 'user');-- // Handle provider status updates on failure- if (errorAnalysis) {- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {- const providerId = agentData?.providerId || provider.id;- if (providerId) {- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });- });- }- }- if (errorAnalysis.category === 'rate-limit') {- const providerId = agentData?.providerId || provider.id;- if (providerId) {- await markProviderRateLimited(providerId).catch(err => {- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });- });- }- }- }- }-- // Process memory extraction and app cooldown- await processAgentCompletion(agentId, task, success, outputBuffer);-- // Clean up ephemeral BTW.md before worktree removal- await cleanupBtwFile(workspacePath);-- // Clean up worktree if agent was using one- await cleanupAgentWorktree(agentId, success, {- openPR: isTruthyMeta(task.metadata?.openPR),- description: task.description,- agentOutput: outputBuffer- });-- unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);- activeAgents.delete(agentId);- });-- return agentId;-}--/**- * Summarize tool input into a concise description for display.- * Extracts the most relevant parameter from each tool type.- */-function summarizeToolInput(toolName, input) {- if (!input || typeof input !== 'object') return '';- const shorten = (p) => {- if (!p || typeof p !== 'string') return '';- // Strip long absolute paths to just filename or last 2 segments- const parts = p.split('/').filter(Boolean);- return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : p;- };- switch (toolName) {- case 'Read':- return shorten(input.file_path);- case 'Edit':- return shorten(input.file_path);- case 'Write':- return shorten(input.file_path);- case 'Glob':- return input.pattern || '';- case 'Grep':- return `"${(input.pattern || '').substring(0, 60)}"${input.path ? ` in ${shorten(input.path)}` : ''}`;- case 'Bash': {- const cmd = input.command || input.description || '';- return cmd.substring(0, 80);- }- case 'Task':- return input.description || '';- case 'WebFetch':- return shorten(input.url || '');- case 'WebSearch':- return `"${(input.query || '').substring(0, 60)}"`;- case 'TodoWrite':- return input.todos?.length ? `${input.todos.length} items` : '';- case 'NotebookEdit':- return shorten(input.notebook_path);- default:- return '';- }-}--function safeParse(str) {- try { return JSON.parse(str); } catch { return null; }-}--/**- * Create a Claude stream-json parser that extracts human-readable text from JSON stream events.- * Returns a stateful parser with a `processChunk(data)` method that returns extracted text lines.- * The parser handles:- * - content_block_delta: incremental text tokens as they stream- * - tool_use events: shows tool calls with input details (e.g. "🔧 Read …/services/api.js")- * - input_json_delta: accumulates tool input JSON for detailed summaries- * - content_block_stop: emits detailed tool summary when input is complete- * - result: final result text (used for output file)- */-function createStreamJsonParser() {- let lineBuffer = '';- let finalResult = '';- let textBuffer = '';- // Track text across all conversation turns so multi-step agents (e.g., task + /simplify)- // preserve all summaries instead of only the final one- const textSections = [];- let currentTextSection = '';- // Track active tool blocks by index for input accumulation- const activeTools = new Map(); // index -> { name, inputJson }-- // Flush accumulated text into a section boundary (tool call start, result event, or stream end)- const commitSection = () => {- const section = currentTextSection.trim();- if (section) {- textSections.push(section);- currentTextSection = '';- }- };-- const processChunk = (rawData) => {- const lines = [];- lineBuffer += rawData;-- // Split on newlines - each JSON object is on its own line- const parts = lineBuffer.split('\n');- // Keep the last incomplete line in the buffer- lineBuffer = parts.pop() || '';-- for (const part of parts) {- const trimmed = part.trim();- if (!trimmed) continue;-- let parsed;- // Skip non-JSON lines (stderr mixed in, etc.)- if (!trimmed.startsWith('{')) continue;- parsed = safeParse(trimmed);- if (!parsed) continue;-- // Extract text from streaming deltas- if (parsed.type === 'stream_event') {- const event = parsed.event;- if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta') {- const text = event.delta.text;- textBuffer += text;- currentTextSection += text;- // Emit complete lines for readability, accumulate partial- const textLines = textBuffer.split('\n');- textBuffer = textLines.pop() || '';- for (const tl of textLines) {- lines.push(tl);- }- }- // Accumulate tool input JSON deltas- if (event?.type === 'content_block_delta' && event.delta?.type === 'input_json_delta') {- const idx = event.index;- const tool = activeTools.get(idx);- if (tool) {- tool.inputJson += event.delta.partial_json || '';- }- }- // Track tool use start - record name and begin accumulating input- if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {- const toolName = event.content_block.name || 'unknown';- const idx = event.index;- activeTools.set(idx, { name: toolName, inputJson: '' });- lines.push(`🔧 Using ${toolName}...`);- commitSection();- }- // When tool input is complete, emit a detailed summary line- if (event?.type === 'content_block_stop') {- const idx = event.index;- const tool = activeTools.get(idx);- if (tool) {- if (tool.inputJson) {- const input = safeParse(tool.inputJson);- if (input) {- const detail = summarizeToolInput(tool.name, input);- if (detail) {- lines.push(` → ${detail}`);- }- }- }- activeTools.delete(idx);- }- }- }-- // Extract tool results from assistant messages- if (parsed.type === 'assistant') {- const content = parsed.message?.content;- if (Array.isArray(content)) {- for (const block of content) {- if (block.type === 'tool_result' && typeof block.content === 'string') {- const firstLine = block.content.split('\n')[0]?.substring(0, 200);- if (firstLine) {- lines.push(` ↳ ${firstLine}`);- }- }- }- }- }-- // Capture final result text for output file- if (parsed.type === 'result') {- if (textBuffer) {- lines.push(textBuffer);- textBuffer = '';- }- commitSection();- finalResult = parsed.result || '';- }- }-- return lines;- };-- const flush = () => {- const lines = [];- if (textBuffer) {- lines.push(textBuffer);- textBuffer = '';- }- commitSection();- return lines;- };-- // Multi-section: return all text turns combined (e.g., task summary + simplify summary)- // Single-section: return the CLI result field (cleaner, no tool call noise)- const getFinalResult = () => {- if (textSections.length > 1) {- return textSections.join('\n\n');- }- return finalResult;- };-- return { processChunk, flush, getFinalResult };-}--/**- * Build spawn command and arguments for a CLI provider- * Returns { command, args, stdinMode } based on provider type- */-function buildCliSpawnConfig(provider, model) {- const providerId = provider?.id || 'claude-code';-- // Codex CLI uses different invocation pattern- if (providerId === 'codex') {- const args = ['exec'];- if (model) {- args.push('--model', model);- }- return {- command: provider?.command || 'codex',- args,- stdinMode: 'prompt' // codex exec reads prompt from stdin- };- }-- // Gemini CLI — uses --yolo for auto-approval, -p for non-interactive stdin mode- if (providerId === 'gemini-cli') {- const args = ['--yolo', ...(provider?.args || [])];- if (model) {- args.push('--model', model);- }- return {- command: provider?.command || 'gemini',- args,- stdinMode: 'prompt'- };- }-- // Default: Claude Code CLI- // Use provider's configured command (respects user's Claude setup, e.g. Bedrock)- const args = [- '--dangerously-skip-permissions', // Unrestricted mode- '--print', // Print output and exit- '--output-format', 'stream-json', // Stream JSON events for live output- '--verbose', // Required for stream-json- '--include-partial-messages', // Include incremental text deltas- ...(provider?.args || []), // User-configured provider args- ];- if (model) {- args.push('--model', model);- }-- return {- command: provider?.command || process.env.CLAUDE_PATH || 'claude',- args,- stdinMode: 'prompt',- streamFormat: 'stream-json'- };-}--/**- * Build spawn arguments for Claude CLI- * @deprecated Use buildCliSpawnConfig instead- */-function buildSpawnArgs(config, model) {- // Note: MCP server config via --mcp-config requires a file path, not inline JSON- // For now, we skip MCP config and rely on the user's default settings- // Prompt will be passed via stdin to avoid shell escaping issues- const args = [- '--dangerously-skip-permissions', // Unrestricted mode- '--print', // Print output and exit- '--output-format', 'stream-json', // Stream JSON events for live output- '--verbose', // Required for stream-json- '--include-partial-messages', // Include incremental text deltas- ];-- // Add model selection if specified- if (model) {- args.push('--model', model);- }-- return args;-}--/**- * Check if a provider is a Claude CLI provider that needs settings.json env injection- */-const isClaudeCliProvider = (provider) =>- provider?.type === 'cli' && (provider.id === 'claude-code' || provider.id === 'claude-code-bedrock');--/**- * Read env vars from ~/.claude/settings.json to inject into Claude CLI spawns- * Ensures user's Bedrock/provider config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.)- * is present in spawned agent environments even if PM2 was started without them- */-let _claudeSettingsEnvCache = null;-let _claudeSettingsEnvCacheTime = 0;-const SETTINGS_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes-async function getClaudeSettingsEnv() {- if (_claudeSettingsEnvCache !== null && (Date.now() - _claudeSettingsEnvCacheTime) < SETTINGS_CACHE_TTL_MS) return _claudeSettingsEnvCache;- try {- const settingsPath = join(homedir(), '.claude', 'settings.json');- if (existsSync(settingsPath)) {- const raw = await readFile(settingsPath, 'utf-8');- const settings = JSON.parse(raw);- _claudeSettingsEnvCache = settings.env || {};- } else {- _claudeSettingsEnvCache = {};- }- } catch (err) {- _claudeSettingsEnvCache = {};- }- _claudeSettingsEnvCacheTime = Date.now();- return _claudeSettingsEnvCache;-}--/**- * Read CLAUDE.md files for agent context- * Reads both global (~/.claude/CLAUDE.md) and project-specific (./CLAUDE.md)- */-async function getClaudeMdContext(workspaceDir) {- const contexts = [];-- // Try to read global CLAUDE.md from ~/.claude/CLAUDE.md- try {- const globalPath = join(homedir(), '.claude', 'CLAUDE.md');- if (existsSync(globalPath)) {- const content = await readFile(globalPath, 'utf-8');- if (content.trim()) {- contexts.push({- type: 'Global Instructions',- path: globalPath,- content: content.trim()- });- }- }- } catch (err) {- // Silently ignore if global CLAUDE.md doesn't exist or can't be read- }-- // Try to read project-specific CLAUDE.md from workspace directory- try {- const projectPath = join(workspaceDir, 'CLAUDE.md');- if (existsSync(projectPath)) {- const content = await readFile(projectPath, 'utf-8');- if (content.trim()) {- contexts.push({- type: 'Project Instructions',- path: projectPath,- content: content.trim()- });- }- }- } catch (err) {- // Silently ignore if project CLAUDE.md doesn't exist or can't be read- }-- // Format as markdown section- if (contexts.length === 0) {- return null;- }-- let section = '## CLAUDE.md Instructions\n\n';- section += 'The following instructions must be followed when working on this task:\n\n';-- for (const ctx of contexts) {- section += `### ${ctx.type}\n`;- section += `Source: \`${ctx.path}\`\n\n`;- section += ctx.content + '\n\n';- }-- return section;-}--/**- * 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 })- */-/**- * Build a compaction instruction section for retries after context-limit failures.- * Provides explicit guidance to the agent on reducing output verbosity.- */-function buildCompactionSection(task) {- const compaction = task.metadata?.compaction;- if (!compaction?.needed) return '';-- const hints = compaction.retryHints || [];- const reason = compaction.reason === 'output-limit' ? 'output length limit' : 'context window limit';- const prevOutputKB = compaction.outputSize ? Math.round(compaction.outputSize / 1024) : 'unknown';-- return `-## Context Compaction Required--**WARNING**: A previous attempt at this task failed because the agent exceeded the ${reason}.-Previous output size: ~${prevOutputKB} KB. You MUST keep your output compact to avoid the same failure.--**Mandatory output constraints**:-${hints.map(h => `- ${h}`).join('\n')}-- Do NOT reproduce entire file contents in your output-- Reference files by path and line number instead of quoting them-- Limit exploratory reads — plan your approach first, then make targeted changes-`;-}--async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null) {- // Get relevant memories for context injection- const memorySection = await getMemorySection(task, {- maxTokens: config.memory?.maxContextTokens || 2000- }).catch(err => {- console.log(`⚠️ Memory retrieval failed: ${err.message}`);- return null;- });-- // Get CLAUDE.md instructions for context injection- const claudeMdSection = await getClaudeMdContext(workspaceDir).catch(err => {- console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`);- return null;- });-- // Get digital twin context for persona alignment- const digitalTwinSection = await getDigitalTwinForPrompt({- maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000- }).catch(err => {- console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`);- return null;- });-- // Build context compaction section if task is retrying after a context-limit failure- const compactionSection = task.metadata?.compaction?.needed ? buildCompactionSection(task) : '';-- // Build worktree context section if applicable- const willOpenPR = isTruthyMeta(task.metadata?.openPR);- const willReviewLoop = isTruthyMeta(task.metadata?.reviewLoop);- // When reviewLoop is enabled alongside openPR, the agent opens the PR during its run (reviewLoop takes precedence over post-exit PR creation)- const prHandledByAgent = willReviewLoop && willOpenPR;- 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}\`-${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}--**Important**: Commit your changes to this branch.${willOpenPR && !prHandledByAgent ? ' Your commits will be submitted as a pull request to the default branch when your task completes.' : ' 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.-` : '';-- // Build pipeline context section if this is a pipeline stage- const pipelineCtx = task.metadata?.pipeline;- const pipelineSection = pipelineCtx?.previousStageAgentId ? `-## Pipeline Context-This is stage ${pipelineCtx.currentStage + 1} of ${pipelineCtx.stages.length}: "${pipelineCtx.stages[pipelineCtx.currentStage]?.name}"-Previous stage: "${pipelineCtx.stages[pipelineCtx.currentStage - 1]?.name}"--Read the previous stage's output from:-\`${join(AGENTS_DIR, pipelineCtx.previousStageAgentId, 'output.txt')}\`--Use the findings from the previous stage to inform your work. If the previous stage produced a JSON results block, parse it to determine which items to process.-` : '';-- // Build simplify section if enabled- const simplifySection = isTruthyMeta(task.metadata?.simplify) ? `-## Simplify Step-After completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found before committing.-` : '';-- // Build review loop section if enabled- const reviewLoopSection = willReviewLoop ? `-## Review Loop-After opening the PR, run \`/do:rpr\` to resolve PR review feedback and complete the merge validation. Continue running the review loop until all checks pass and the PR is approved.-` : '';-- // Build JIRA context section if applicable- const jiraSection = task.metadata?.jiraTicketId ? `-## JIRA Integration-This task is tracked by JIRA ticket **${task.metadata.jiraTicketId}**.-- **Ticket URL**: ${task.metadata.jiraTicketUrl}-${task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\`` : ''}--Include the ticket ID (${task.metadata.jiraTicketId}) in your commit messages, e.g. \`${task.metadata.jiraTicketId}: description of change\`.-${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch branches.' : ''}-` : '';-- // Detect and load task-type-specific skill template (only when matched)- const matchedSkill = detectSkillTemplate(task);- const skillSection = matchedSkill- ? await loadSkillTemplate(matchedSkill).catch(err => {- console.log(`⚠️ Skill template load failed for ${matchedSkill}: ${err.message}`);- return null;- })- : null;-- // Build onboard tools section for agent awareness- const toolsSection = await getToolsSummaryForPrompt().catch(err => {- console.log(`⚠️ Tools summary retrieval failed: ${err.message}`);- return '';- });-- // Build .planning/ context section for GSD-enabled apps- let planningContextSection = '';- if (task.metadata?.app) {- const planningPath = join(workspaceDir, '.planning');- const hasPlanningDir = await stat(planningPath).then(s => s.isDirectory()).catch(() => false);- if (hasPlanningDir) {- const planningParts = [];- const stateContent = await readFile(join(planningPath, 'STATE.md'), 'utf-8').catch(() => null);- if (stateContent) planningParts.push(`### Current State\n\`\`\`\n${stateContent.slice(0, 1000)}\n\`\`\``);- const concernsContent = await readFile(join(planningPath, 'CONCERNS.md'), 'utf-8').catch(() => null);- if (concernsContent) planningParts.push(`### Known Concerns\n\`\`\`\n${concernsContent.slice(0, 1500)}\n\`\`\``);- const roadmapContent = await readFile(join(planningPath, 'ROADMAP.md'), 'utf-8').catch(() => null);- if (roadmapContent) planningParts.push(`### Roadmap\n\`\`\`\n${roadmapContent.slice(0, 1000)}\n\`\`\``);- if (planningParts.length > 0) {- planningContextSection = `\n## Project Planning Context (.planning/)\nThis project has GSD planning documents. Use this context to understand priorities and known issues.\n\n${planningParts.join('\n\n')}\n`;- }- }- }-- // Try to use the prompt template system- const promptData = await buildPrompt('cos-agent-briefing', {- task,- config,- memorySection,- claudeMdSection,- digitalTwinSection,- worktreeSection,- pipelineSection,- jiraSection,- simplifySection,- reviewLoopSection,- compactionSection,- skillSection,- planningContextSection,- toolsSection,- soulSection: digitalTwinSection, // Backwards compatibility for prompt templates- timestamp: new Date().toISOString()- }).catch(() => null);-- if (promptData?.prompt) {- return promptData.prompt;- }-- // Fallback to built-in template- return `# Chief of Staff Agent Briefing--${claudeMdSection || ''}--${memorySection || ''}--## Task Assignment-You are an autonomous agent working on behalf of the Chief of Staff.--### Task Details-- **ID**: ${task.id}-- **Priority**: ${task.priority}-- **Description**: ${task.description}-${task.metadata?.context ? `- **Context**: ${task.metadata.context}` : ''}-${task.metadata?.app ? `- **Target App**: ${task.metadata.app}\n- **Target App Directory**: ${workspaceDir}` : ''}-${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `- **Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}-${worktreeSection}-${pipelineSection}-${jiraSection}-${simplifySection}-${reviewLoopSection}-${compactionSection}-${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${toolsSection ? `\n${toolsSection}\n` : ''}${planningContextSection}-## Instructions-1. Analyze the task requirements carefully-2. Make necessary changes to complete the task-3. Test your changes when possible-4. Provide a summary of what was done--## Guidelines-- Focus only on the assigned task-- Make minimal, targeted changes-- Follow existing code patterns and conventions-- Do not make unrelated changes-- If blocked, explain clearly why-- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only-- **BTW Messages**: The user may send you additional context while you work. Check for a \`BTW.md\` file in your working directory root — if it exists, read it for important messages from the user. Incorporate that context into your work. Do not delete or modify BTW.md.-${isTruthyMeta(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : task.metadata?.app && worktreeInfo && willOpenPR ? `- Commit code after each feature or bug fix using the git tools or /cam skill. A pull request will be automatically created when your task completes — do NOT open a PR manually.` : task.metadata?.app && worktreeInfo ? `- Commit code after each feature or bug fix using the git tools or /cam skill. Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}--## Git Hygiene (CRITICAL)-- **Before starting work**, run \`git status\` to verify a clean working tree. If there are uncommitted changes from a previous agent or manual work, **stash or discard them** before proceeding — do NOT commit someone else's changes.-- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.-${worktreeInfo ? `- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.` : `- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.`}-- If the working tree is dirty with changes unrelated to your task, run \`git stash\` to set them aside before starting.--## Working Directory-${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.--Begin working on the task now.`;-}--/**- * Get workspace path for an app- */-async function getAppWorkspace(appName) {- const appsFile = join(ROOT_DIR, 'data/apps.json');-- const data = await readJSONFile(appsFile, null);- if (!data) {- return ROOT_DIR;- }-- // Handle both object format { apps: { id: {...} } } and array format [...]- const apps = data.apps || data;-- if (Array.isArray(apps)) {- const app = apps.find(a => a.name === appName || a.id === appName);- return app?.repoPath || ROOT_DIR;- }-- // Object format - keys are app IDs- const app = apps[appName] || Object.values(apps).find(a => a.name === appName);- return app?.repoPath || ROOT_DIR;-}--/**- * Get full app data for a task (including jira config).- * Returns the app object or null if not found.- */-async function getAppDataForTask(task) {- const appName = task?.metadata?.app;- if (!appName) return null;-- const appsFile = join(ROOT_DIR, 'data/apps.json');- const data = await readJSONFile(appsFile, null);- if (!data) return null;-- const apps = data.apps || data;-- if (Array.isArray(apps)) {- return apps.find(a => a.name === appName || a.id === appName) || null;- }-- return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;-}--/**- * Generate a concise JIRA ticket title from a task description using AI.- * Falls back to truncated description on failure.- */-async function generateJiraTitle(description) {- const fallback = `[CoS] ${(description || 'Automated task').substring(0, 120)}`;-- const provider = await getActiveProvider().catch(() => null);- if (!provider) return fallback;-- const model = provider.defaultModel || provider.models?.[0];- if (!model) return fallback;-- const prompt = `Generate a concise JIRA ticket title (max 80 chars) for this task. Output ONLY the title text, nothing else.\n\nTask: ${description}`;-- const { runId } = await createRun({ providerId: provider.id, model, prompt, source: 'jira-title' }).catch(() => ({}));- if (!runId) return fallback;-- let title = '';-- await new Promise((resolve) => {- const onData = (data) => { title += typeof data === 'string' ? data : (data?.text || ''); };- const onDone = () => resolve();-- if (provider.type === 'cli') {- executeCliRun(runId, provider, prompt, process.cwd(), onData, onDone, 30000);- } else {- executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onDone);- }- }).catch(() => {});-- title = title.trim().replace(/^["']|["']$/g, '');- return title || fallback;-}--/**- * Create a JIRA ticket for a task if the app has JIRA integration enabled.- * Non-blocking — returns null on failure.- * @returns {Promise<{ticketId: string, ticketUrl: string, summary: string}|null>}- */-async function createJiraTicketForTask(task, app) {- const jira = app?.jira;- if (!jira?.enabled || !jira.instanceId || !jira.projectKey) return null;-- const summary = await generateJiraTitle(task.description);- const description = [- `Automated task created by PortOS Chief of Staff.`,- ``,- `*Task ID:* ${task.id}`,- `*Priority:* ${task.priority || 'MEDIUM'}`,- `*App:* ${app.name || task.metadata?.app || 'unknown'}`,- ``,- `{quote}`,- task.description || '',- `{quote}`- ].join('\n');-- const result = await jiraService.createTicket(jira.instanceId, {- projectKey: jira.projectKey,- summary,- description,- issueType: jira.issueType || 'Task',- labels: jira.labels || [],- assignee: jira.assignee,- epicKey: jira.epicKey- }).catch(err => {- emitLog('warn', `Failed to create JIRA ticket: ${err.message}`, { taskId: task.id, app: app.name });- return null;- });-- if (!result?.ticketId) return null;-- emitLog('success', `Created JIRA ticket ${result.ticketId}`, {- taskId: task.id,- ticketId: result.ticketId,- ticketUrl: result.url- });-- return { ticketId: result.ticketId, ticketUrl: result.url, summary };-}--/**- * Terminate an agent- */-export async function terminateAgent(agentId) {- // Check if agent is in runner mode- if (runnerAgents.has(agentId)) {- const agentInfo = runnerAgents.get(agentId);- if (agentInfo?.initializationTimeout) {- clearTimeout(agentInfo.initializationTimeout);- }- const result = await terminateAgentViaRunner(agentId).catch(err => ({- success: false,- error: err.message- }));- if (result.success) {- // Mark agent as completed with termination status- await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });- // Block task instead of re-queuing — user intentionally stopped this- const task = agentInfo?.task;- if (task) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Terminated by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');- }- runnerAgents.delete(agentId);- }- return result;- }-- // Direct mode- const agent = activeAgents.get(agentId);-- if (!agent) {- return { success: false, error: 'Agent not found or not running' };- }-- // Track as user-terminated so the close handler doesn't re-queue- userTerminatedAgents.add(agentId);-- // Mark agent as completed immediately with termination status- await completeAgent(agentId, { success: false, error: 'Agent terminated by user' });-- // Block task immediately (don't defer to close handler — prevents requeue on server restart)- if (agent.taskId) {- const task = await getTaskById(agent.taskId).catch(() => null);- if (task) {- await updateTask(agent.taskId, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Terminated by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');- }- }-- // Kill the process- agent.process.kill('SIGTERM');-- // Give it a moment, then force kill if needed- setTimeout(() => {- if (activeAgents.has(agentId)) {- agent.process.kill('SIGKILL');- unregisterSpawnedAgent(agent.pid);- activeAgents.delete(agentId);- }- }, 5000);-- return { success: true, agentId };-}--/**- * Get list of active agents- */-export function getActiveAgents() {- const agents = [];-- // Direct mode agents- for (const [agentId, agent] of activeAgents) {- agents.push({- id: agentId,- taskId: agent.taskId,- startedAt: agent.startedAt,- runningTime: Date.now() - agent.startedAt,- mode: 'direct'- });- }-- // Runner mode agents- for (const [agentId, agent] of runnerAgents) {- agents.push({- id: agentId,- taskId: agent.taskId,- startedAt: agent.startedAt,- runningTime: Date.now() - agent.startedAt,- mode: 'runner'- });- }-- return agents;-}--/**- * Force kill an agent immediately with SIGKILL (no graceful shutdown)- */-export async function killAgent(agentId) {- // Check if agent is in runner mode- if (runnerAgents.has(agentId)) {- const agentInfo = runnerAgents.get(agentId);- if (agentInfo?.initializationTimeout) {- clearTimeout(agentInfo.initializationTimeout);- }- const result = await killAgentViaRunner(agentId).catch(err => ({- success: false,- error: err.message- }));- if (result.success) {- // Mark agent as completed with kill status- await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });- // Block task instead of re-queuing — user intentionally killed this- const task = agentInfo?.task;- if (task) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Force killed by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');- }- runnerAgents.delete(agentId);- }- return result;- }-- // Direct mode- const agent = activeAgents.get(agentId);-- if (!agent) {- return { success: false, error: 'Agent not found or not running' };- }-- // Track as user-terminated so the close handler doesn't re-queue- userTerminatedAgents.add(agentId);-- // Mark agent as completed immediately with kill status- await completeAgent(agentId, { success: false, error: 'Agent force killed by user (SIGKILL)' });-- // Block task immediately (don't defer to close handler — prevents requeue on server restart)- if (agent.taskId) {- const task = await getTaskById(agent.taskId).catch(() => null);- if (task) {- await updateTask(agent.taskId, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Force killed by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user');- }- }-- // Kill the process immediately with SIGKILL- agent.process.kill('SIGKILL');-- unregisterSpawnedAgent(agent.pid);- activeAgents.delete(agentId);-- return { success: true, agentId, pid: agent.pid, signal: 'SIGKILL' };-}--/**- * Get process stats for an agent (CPU, memory usage)- */-export async function getAgentProcessStats(agentId) {- // Check if agent is in runner mode - use runner endpoint- if (runnerAgents.has(agentId) || useRunner) {- const stats = await getAgentStatsFromRunner(agentId);- return stats;- }-- // Direct mode - get stats locally- const agent = activeAgents.get(agentId);- if (!agent) {- return null;- }-- // Get process stats- const { exec } = await import('child_process');- const { promisify } = await import('util');- const execAsync = promisify(exec);-- const psCmd = process.platform === 'win32'- ? `tasklist /FI "PID eq ${agent.pid}" /FO CSV /NH`- : `ps -p ${agent.pid} -o pid=,pcpu=,rss=,state=`;- const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));- const line = result.stdout.trim();-- if (!line) {- return { active: false, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'dead' };- }-- const parts = line.split(/\s+/).filter(Boolean);- if (parts.length >= 3) {- return {- active: true,- agentId,- pid: parseInt(parts[0], 10),- cpu: parseFloat(parts[1]) || 0,- memoryKb: parseInt(parts[2], 10) || 0,- memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,- state: parts[3] || 'unknown'- };- }-- return { active: true, agentId, pid: agent.pid, cpu: 0, memoryKb: 0, memoryMb: 0, state: 'unknown' };-}--/**- * Kill all active agents- */-export async function killAllAgents() {- const directIds = Array.from(activeAgents.keys());- const runnerIds = Array.from(runnerAgents.keys());-- for (const agentId of directIds) {- await terminateAgent(agentId);- }-- for (const agentId of runnerIds) {- await terminateAgent(agentId);- }-- return { killed: directIds.length + runnerIds.length };-}--// Max retries before creating investigation task-const MAX_ORPHAN_RETRIES = 3;-const MAX_TASK_RETRIES = 3;-// Minimum cooldown between orphan retries (30 minutes)-const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;--/**- * Check if a process is running by PID- */-async function isPidAlive(pid) {- if (!pid) return false;- try {- process.kill(pid, 0);- return true;- } catch {- return false;- }-}--/**- * Clean up orphaned agents on startup- * Agents marked as "running" in state but not tracked anywhere are orphaned- *- * Must check:- * 1. Local activeAgents map (direct-spawned)- * 2. Local runnerAgents map (recently spawned via runner)- * 3. CoS Runner service (may have agents from before server restart)- *- * After cleanup:- * - Resets associated tasks to pending for auto-retry- * - Creates investigation task after max retries exceeded- * - Triggers evaluation to spawn new agents- */-export async function cleanupOrphanedAgents() {- const { getAgents, completeAgent: markComplete, evaluateTasks, getTaskById } = await import('./cos.js');- const agents = await getAgents();- let cleanedCount = 0;- const orphanedTaskIds = [];-- // Get list of agents actively running in the CoS Runner- const runnerActiveIds = new Set();- const runnerAgentsList = await getActiveAgentsFromRunner().catch(() => []);- for (const agent of runnerAgentsList) {- runnerActiveIds.add(agent.id);- }-- // Also sync runner agents to our local map for event handling- if (runnerAgentsList.length > 0) {- const synced = await syncRunnerAgents();- if (synced > 0) {- console.log(`🔄 Synced ${synced} agents from CoS Runner`);- }- }-- for (const agent of agents) {- if (agent.status === 'running') {- // Check if agent is tracked locally or in the runner- const inLocalDirect = activeAgents.has(agent.id);- const inLocalRunner = runnerAgents.has(agent.id);- const inRemoteRunner = runnerActiveIds.has(agent.id);-- if (!inLocalDirect && !inLocalRunner && !inRemoteRunner) {- // Before marking as orphaned, check if the process is actually still running- // This prevents false positives when servers restart but agent process survives- if (agent.pid) {- const stillAlive = await isPidAlive(agent.pid);- if (stillAlive) {- console.log(`🔄 Agent ${agent.id} (PID ${agent.pid}) still running, re-syncing to runner tracking`);- const inferredType = agent.taskId?.startsWith('sys-') ? 'internal' : 'user';- runnerAgents.set(agent.id, {- id: agent.id, pid: agent.pid, taskId: agent.taskId,- task: { id: agent.taskId, taskType: inferredType, description: 'Re-synced from PID check' }- });- continue;- }- }-- console.log(`🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);- await markComplete(agent.id, {- success: false,- error: 'Agent process terminated unexpectedly',- orphaned: true- });- cleanedCount++;-- // Track the task for retry- if (agent.taskId) {- orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id });- }- }- }- }-- // 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);- }-- // Trigger evaluation to spawn new agents for retried tasks- if (cleanedCount > 0) {- emitLog('info', `Cleaned up ${cleanedCount} orphaned agents, triggering evaluation`, { cleanedCount });- // Small delay to let state settle before evaluation- setTimeout(() => {- evaluateTasks().catch(err => {- console.error(`❌ Failed to evaluate tasks after orphan cleanup: ${err.message}`);- });- }, 1000);- }-- return cleanedCount;-}--/**- * Handle an orphaned task - retry or create investigation- */-export async function handleOrphanedTask(taskId, agentId, getTaskById) {- const task = await getTaskById(taskId).catch(() => null);- if (!task) {- emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });- return;- }-- // Never requeue tasks that were explicitly terminated by the user- if (task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') {- emitLog('info', `⏭️ Skipping orphaned task ${taskId} — user-terminated`, { taskId, agentId });- return;- }-- // Skip tasks already completed — prevents race where completeAgent() finishes- // before updateTask() and a health check calls handleOrphanedTask in between- if (task.status === 'completed') {- emitLog('debug', `⏭️ Skipping orphaned task ${taskId} — already completed`, { taskId, agentId });- return;- }-- // Check if the agent actually committed work before treating as orphaned- const commitFound = checkForTaskCommit(taskId);- if (commitFound) {- emitLog('info', `✅ Orphaned agent ${agentId} actually completed work - commit found for task ${taskId}`, { taskId, agentId });- await updateTask(taskId, { status: 'completed' }, task.taskType || 'user');- return;- }-- // Get current retry count from task metadata- const retryCount = (Number(task.metadata?.orphanRetryCount) || 0) + 1;- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;- const taskType = task.taskType || 'user';-- // Block if total spawn count across all retry types is exhausted- const totalExceeded = totalSpawns >= MAX_TOTAL_SPAWNS;-- // Enforce cooldown between orphan retries- const lastOrphanedAt = task.metadata?.lastOrphanedAt ? new Date(task.metadata.lastOrphanedAt).getTime() : 0;- const cooldownRemaining = lastOrphanedAt ? ORPHAN_RETRY_COOLDOWN_MS - (Date.now() - lastOrphanedAt) : 0;- const inCooldown = cooldownRemaining > 0;-- if (retryCount < MAX_ORPHAN_RETRIES && !totalExceeded && !inCooldown) {- // Reset task to pending for automatic retry- emitLog('info', `Resetting orphaned task ${taskId} for retry (attempt ${retryCount}/${MAX_ORPHAN_RETRIES}, total spawns ${totalSpawns}/${MAX_TOTAL_SPAWNS})`, {- taskId,- retryCount,- totalSpawns,- maxRetries: MAX_ORPHAN_RETRIES- });-- await updateTask(taskId, {- status: 'pending',- metadata: {- ...task.metadata,- orphanRetryCount: retryCount,- lastOrphanedAt: new Date().toISOString(),- lastOrphanedAgentId: agentId- }- }, taskType);- } else if (inCooldown && retryCount < MAX_ORPHAN_RETRIES && !totalExceeded) {- // Within cooldown — block temporarily with info about when retry is eligible- const cooldownMinutes = Math.ceil(cooldownRemaining / 60000);- emitLog('info', `⏳ Orphan retry for task ${taskId} in cooldown (${cooldownMinutes}m remaining)`, {- taskId, cooldownMinutes, retryCount- });-- await updateTask(taskId, {- status: 'blocked',- metadata: {- ...task.metadata,- orphanRetryCount: retryCount,- lastOrphanedAt: new Date().toISOString(),- lastOrphanedAgentId: agentId,- blockedReason: `Orphan retry cooldown (${cooldownMinutes}m remaining)`,- blockedCategory: 'orphan-cooldown',- blockedAt: new Date().toISOString(),- cooldownUntil: new Date(Date.now() + cooldownRemaining).toISOString()- }- }, taskType);- } else {- // Max retries or total spawns exceeded - create auto-approved investigation task- const reason = totalExceeded- ? `total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`- : `orphan retries exceeded (${retryCount}/${MAX_ORPHAN_RETRIES})`;- emitLog('warn', `Task ${taskId} blocked: ${reason}, creating investigation task`, {- taskId,- retryCount,- totalSpawns- });-- // Mark task as blocked- await updateTask(taskId, {- status: 'blocked',- metadata: {- ...task.metadata,- orphanRetryCount: retryCount,- blockedReason: reason,- blockedCategory: 'max-retries',- blockedAt: new Date().toISOString()- }- }, taskType);-- // Create auto-approved investigation task (no approval required for orphan issues)- const description = `[Auto-Fix] Investigate repeated agent orphaning for task ${taskId}--**Original Task**: ${(task.description || '').substring(0, 200)}-**Orphan Retries**: ${retryCount}-**Total Spawns**: ${totalSpawns}-**Last Orphaned Agent**: ${agentId}-**Blocked Reason**: ${reason}--This task has been blocked after ${totalSpawns} total agent spawns. Investigate:-1. Check CoS Runner logs for errors-2. Verify process spawning is working correctly-3. Look for resource constraints (memory, CPU)-4. Check for network/connection issues between services--Once the issue is resolved, reset the original task to pending.`;-- await addTask({- description,- priority: 'HIGH',- context: `Auto-generated from repeated orphan failures for task ${taskId}`,- approvalRequired: false // Auto-approved for orphan issues- }, 'internal').catch(err => {- emitLog('error', `Failed to create investigation task: ${err.message}`, { taskId, error: err.message });- });- }-}--// Initialize spawner when module loads (async)-initSpawner().catch(err => {- console.error(`❌ Failed to initialize spawner: ${err.message}`);-});--// Initialize task learning system-import('./taskLearning.js').then(taskLearning => {- taskLearning.initTaskLearning();+// Clean up orphaned agents after a short delay (let other services init first)+import('./agentManagement.js').then(({ cleanupOrphanedAgents }) => {+ setTimeout(cleanupOrphanedAgents, 2000);}).catch(err => {- console.error(`❌ Failed to initialize task learning: ${err.message}`);+ console.error(`❌ Failed to schedule orphan cleanup: ${err.message}`);});--// Clean up orphaned agents after a short delay (let other services init first)-setTimeout(cleanupOrphanedAgents, 2000);