Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

simplify: clean up agent modules post-decomposition

Adam Eivy62990802af6f
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index b4ce2f8e7f..cfe5d89c5b 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -20,7 +20,7 @@ import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalys
import { completeAgentRun } from './agentRunTracking.js';
import { processAgentCompletion } from './agentCompletion.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -65,9 +65,7 @@ export function summarizeToolInput(toolName, input) {
}
}
-export function safeParse(str) {
- try { return JSON.parse(str); } catch { return null; }
-}
+export const safeParse = (str) => safeJSONParse(str, null);
/**
* Create a Claude stream-json parser that extracts human-readable text from JSON stream events.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index c5efcf457b..7bb7cddde3 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -24,24 +24,19 @@ 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 { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
+import { createAgentRun, completeAgentRun, checkForTaskCommit } 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 { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } 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.
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 3f1fcfc8e6..b122150aa0 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -25,37 +25,40 @@ const MAX_ORPHAN_RETRIES = 3;
// Minimum cooldown between orphan retries (30 minutes)
const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;
+/**
+ * Shared runner-mode termination path for terminateAgent and killAgent.
+ * Calls runnerFn, marks the task blocked, and cleans up.
+ */
+async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReason) {
+ const agentInfo = runnerAgents.get(agentId);
+ if (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);
+ const result = await runnerFn(agentId).catch(err => ({ success: false, error: err.message }));
+ if (result.success) {
+ await completeAgent(agentId, { success: false, error: errorMessage });
+ const task = agentInfo?.task;
+ if (task) {
+ await updateTask(task.id, {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ blockedReason,
+ blockedCategory: 'user-terminated',
+ blockedAt: new Date().toISOString()
+ }
+ }, task.taskType || 'user');
+ }
+ runnerAgents.delete(agentId);
+ }
+ return result;
+}
+
/**
* 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;
+ return terminateRunnerAgent(agentId, terminateAgentViaRunner, 'Agent terminated by user', 'Terminated by user');
}
// Direct mode
@@ -139,31 +142,7 @@ export function getActiveAgents() {
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;
+ return terminateRunnerAgent(agentId, killAgentViaRunner, 'Agent force killed by user (SIGKILL)', 'Force killed by user');
}
// Direct mode
@@ -257,14 +236,7 @@ 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);
- }
-
+ await Promise.all([...directIds, ...runnerIds].map(agentId => terminateAgent(agentId)));
return { killed: directIds.length + runnerIds.length };
}
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 21a217d1a9..c97dd3015f 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -8,7 +8,6 @@
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';
@@ -77,10 +76,8 @@ export function detectSkillTemplate(task) {
* @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}`);
+ const content = await readFile(join(SKILLS_DIR, `${skillName}.md`), 'utf-8').catch(() => null);
+ if (content) console.log(`🎯 Loaded skill template: ${skillName}`);
return content;
}
@@ -92,37 +89,17 @@ 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
+ const globalPath = join(homedir(), '.claude', 'CLAUDE.md');
+ const globalContent = await readFile(globalPath, 'utf-8').catch(() => null);
+ if (globalContent?.trim()) {
+ contexts.push({ type: 'Global Instructions', path: globalPath, content: globalContent.trim() });
}
// 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
+ const projectPath = join(workspaceDir, 'CLAUDE.md');
+ const projectContent = await readFile(projectPath, 'utf-8').catch(() => null);
+ if (projectContent?.trim()) {
+ contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent.trim() });
}
if (contexts.length === 0) {
@@ -176,27 +153,15 @@ ${hints.map(h => `- ${h}`).join('\n')}
* @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;
- });
+ // Fetch independent context sections in parallel
+ const [memorySection, claudeMdSection, digitalTwinSection] = await Promise.all([
+ getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })
+ .catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),
+ getClaudeMdContext(workspaceDir)
+ .catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),
+ 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) : '';
@@ -274,11 +239,13 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
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);
+ const [stateContent, concernsContent, roadmapContent] = await Promise.all([
+ readFile(join(planningPath, 'STATE.md'), 'utf-8').catch(() => null),
+ readFile(join(planningPath, 'CONCERNS.md'), 'utf-8').catch(() => null),
+ readFile(join(planningPath, 'ROADMAP.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`;
diff --git a/server/services/agentState.js b/server/services/agentState.js
index 16c5fda628..bc2a5751fb 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -18,3 +18,7 @@ export const spawningTasks = new Set();
// useRunner: whether CoS Runner mode is active
export let useRunner = false;
export const setUseRunner = (val) => { useRunner = val; };
+
+// Metadata booleans may arrive as true/'true' or false/'false' (JSON vs TASKS.md string round-trip)
+export const isTruthyMeta = (value) => value === true || value === 'true';
+export const isFalsyMeta = (value) => value === false || value === 'false';
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 0d84fa7c9a..afde3baa2b 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -16,7 +16,7 @@ import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './
import { ensureDir, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';
// ─── Shared state (imported from agentState.js) ──────────────────────────────
-export { activeAgents, runnerAgents, userTerminatedAgents, spawningTasks, useRunner } from './agentState.js';
+export { activeAgents, runnerAgents, userTerminatedAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';
import { activeAgents, runnerAgents, setUseRunner } from './agentState.js';
// ─── Sub-module re-exports ────────────────────────────────────────────────────
@@ -32,9 +32,6 @@ export { processAgentCompletion } from './agentCompletion.js';
const ROOT_DIR = PATHS.root;
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';
/**
* Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.