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

refactor: introduce an agentOrchestrator facade over the seven-module agent lifecycle (#3450)

[._.]/ Adam Eivyfb4913d60512
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 533b13288d..7a395aeba7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changed
+- **The agent lifecycle has a named entry point instead of seven mutually-recursive modules.** The `cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js → agents.js → subAgentSpawner.js → agentLifecycle.js` cluster has no owner, so reasoning about one transition — pause, kill, complete, spawn — means holding all seven files in mind, and several of the back-edges are `await import(...)` calls that exist only to dodge a load-time cycle. `server/services/agentOrchestrator.js` is the facade above that cluster: it imports the transition owners one-directionally, carries the transition-vs-leaf classification in its header so later passes start from it, and renames apart the two different functions both called `terminateAgent` — `requestAgentTermination` only emits the event and returns, while `terminateAgent` keeps the name for the real SIGTERM/SIGKILL sequence. The four agent routes (terminate, pause, kill, stats) now go through it, one hop instead of three. `agentImportCycles.test.js` gains a guard that fails if any of the seven imports the facade back, statically *or* via `await import(...)` — the dynamic form matters because reaching across a blocked layer that way is exactly this cluster's habit. Widening that suite's graph builder to walk subdirectories closed a hole in the pre-existing cycle guard too: it read only top-level `server/services/*.js`, so a cycle routed through one subdirectory hop (`agentTuiSpawning/outputSpooler.js` already imports back up to `../cosAgents.js`) was invisible to it. The remaining call sites and the dynamic-import workarounds follow in later PRs (#3450).
+
- **Every view that used to show a bare "Loading…" text node now uses the shared loading affordances.** ~35 views across Music, MeatSpace, Media, Pipeline, Sprites, Writers Room, Sync, Catalog and a dozen pages rendered unstyled text while fetching, which read as broken content rather than a deliberate loading state. Small inline loads (buttons, side lists, drawer subtitles, popover menus) now render `BrailleSpinner`; full-page and card-grid loads render `PageSkeleton`, which reserves the eventual content's dimensions so the first paint doesn't reflow and announces itself via `role="status"`/`aria-busy`. Several hand-rolled `Loader2 + animate-spin` one-offs collapsed onto the same two components, and the pipeline audio music-library panel lost its duplicate second spinner.
- **Three structural cleanups that each removed a way to get something silently wrong.** `buildReviewWithArgs` took seven positionals, with two same-shaped reviewer-name arrays adjacent to each other and two same-shaped per-reviewer lookup maps adjacent to each other — transposing either pair produced a plausible-looking flag string and no error; everything past the reviewer list is now a named options object. The ecosystem-config branch of `streamDetection` nested eight levels deep to probe each PM2 process's vite config, duplicating that loop byte-for-byte in `parseEcosystemFromPath`; both now call the exported `resolveViteConfigPortForProcess`, which owns the gate and the candidate order and has its own tests (the "stray closing brace" flagged in that block turned out to be mis-indentation, not a structural bug). And `client/src/utils/fileUpload.js` no longer re-exports the four network-calling upload helpers it handed off to `services/apiMedia.js` — the real call sites import them from the services module directly, so the pure-helpers module has no reach into the network layer again (#3452).
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 77e4eaf740..780142e251 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -29,10 +29,6 @@ vi.mock('../services/cos.js', () => ({
getAgentDates: vi.fn(),
getAgentsByDate: vi.fn(),
getAgent: vi.fn(),
- terminateAgent: vi.fn(),
- pauseAgent: vi.fn(),
- killAgent: vi.fn(),
- getAgentProcessStats: vi.fn(),
deleteAgent: vi.fn(),
clearCompletedAgents: vi.fn(),
submitAgentFeedback: vi.fn(),
@@ -53,6 +49,14 @@ vi.mock('../services/cos.js', () => ({
getRecentTasks: vi.fn()
}));
+// Lifecycle transitions moved off `cos.js` onto the agentOrchestrator facade (#3450).
+vi.mock('../services/agentOrchestrator.js', () => ({
+ requestAgentTermination: vi.fn(),
+ pauseAgent: vi.fn(),
+ killAgent: vi.fn(),
+ getAgentProcessStats: vi.fn()
+}));
+
// Mock the taskWatcher service
vi.mock('../services/taskWatcher.js', () => ({
startWatching: vi.fn(),
@@ -109,6 +113,7 @@ vi.mock('../services/codeReview.js', () => ({
// Import mocked modules
import * as cos from '../services/cos.js';
+import * as agentOrchestrator from '../services/agentOrchestrator.js';
import * as taskWatcher from '../services/taskWatcher.js';
import * as appActivity from '../services/appActivity.js';
import * as claudeChangelog from '../services/claudeChangelog.js';
@@ -579,29 +584,29 @@ describe('CoS Routes', () => {
describe('POST /api/cos/agents/:id/terminate', () => {
it('should terminate agent', async () => {
- cos.terminateAgent.mockResolvedValue({ success: true, agentId: 'agent-001' });
+ agentOrchestrator.requestAgentTermination.mockResolvedValue({ success: true, agentId: 'agent-001' });
const response = await request(app).post('/api/cos/agents/agent-001/terminate');
expect(response.status).toBe(200);
- expect(cos.terminateAgent).toHaveBeenCalledWith('agent-001');
+ expect(agentOrchestrator.requestAgentTermination).toHaveBeenCalledWith('agent-001');
});
});
describe('POST /api/cos/agents/:id/pause', () => {
it('should pause agent with reason', async () => {
- cos.pauseAgent.mockResolvedValue({ success: true, agentId: 'agent-001', pausedAt: '2026-05-25T12:00:00.000Z' });
+ agentOrchestrator.pauseAgent.mockResolvedValue({ success: true, agentId: 'agent-001', pausedAt: '2026-05-25T12:00:00.000Z' });
const response = await request(app)
.post('/api/cos/agents/agent-001/pause')
.send({ reason: 'billing window' });
expect(response.status).toBe(200);
- expect(cos.pauseAgent).toHaveBeenCalledWith('agent-001', 'billing window');
+ expect(agentOrchestrator.pauseAgent).toHaveBeenCalledWith('agent-001', 'billing window');
});
it('should return 404 if agent not found', async () => {
- cos.pauseAgent.mockRejectedValue(
+ agentOrchestrator.pauseAgent.mockRejectedValue(
new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' }),
);
@@ -613,16 +618,16 @@ describe('CoS Routes', () => {
describe('POST /api/cos/agents/:id/kill', () => {
it('should force kill agent', async () => {
- cos.killAgent.mockResolvedValue({ success: true, agentId: 'agent-001', signal: 'SIGKILL' });
+ agentOrchestrator.killAgent.mockResolvedValue({ success: true, agentId: 'agent-001', signal: 'SIGKILL' });
const response = await request(app).post('/api/cos/agents/agent-001/kill');
expect(response.status).toBe(200);
- expect(cos.killAgent).toHaveBeenCalledWith('agent-001');
+ expect(agentOrchestrator.killAgent).toHaveBeenCalledWith('agent-001');
});
it('should return 404 if agent not found', async () => {
- cos.killAgent.mockRejectedValue(
+ agentOrchestrator.killAgent.mockRejectedValue(
new ServerError('Agent not found or not running', { status: 404, code: 'NOT_FOUND' }),
);
@@ -634,7 +639,7 @@ describe('CoS Routes', () => {
describe('GET /api/cos/agents/:id/stats', () => {
it('should return agent process stats', async () => {
- cos.getAgentProcessStats.mockResolvedValue({
+ agentOrchestrator.getAgentProcessStats.mockResolvedValue({
active: true,
pid: 12345,
cpu: 5.2,
@@ -648,7 +653,7 @@ describe('CoS Routes', () => {
});
it('should return active:false if no stats available', async () => {
- cos.getAgentProcessStats.mockResolvedValue(null);
+ agentOrchestrator.getAgentProcessStats.mockResolvedValue(null);
const response = await request(app).get('/api/cos/agents/agent-999/stats');
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index a79f2c371e..74b2d0985e 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -5,6 +5,8 @@
import { Router } from 'express';
import { z } from 'zod';
import * as cos from '../services/cos.js';
+// Lifecycle transitions go through the facade (#3450), not the `cos.js` barrel.
+import * as agentOrchestrator from '../services/agentOrchestrator.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
@@ -67,9 +69,11 @@ router.get('/agents/:id/prompt', asyncHandler(async (req, res) => {
res.json(result);
}));
-// POST /api/cos/agents/:id/terminate - Terminate agent (graceful SIGTERM, then SIGKILL)
+// POST /api/cos/agents/:id/terminate - Request termination (graceful SIGTERM, then SIGKILL)
+// This only emits `agent:terminate` and returns immediately; the spawner's
+// handler runs the actual SIGTERM/SIGKILL sequence.
router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {
- const result = await cos.terminateAgent(req.params.id);
+ const result = await agentOrchestrator.requestAgentTermination(req.params.id);
res.json(result);
}));
@@ -78,7 +82,7 @@ router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {
// runner/persist step fails — so no result-shape string-matching here.
router.post('/agents/:id/pause', asyncHandler(async (req, res) => {
const { reason } = validateRequest(pauseBodySchema, req.body ?? {});
- const result = await cos.pauseAgent(req.params.id, reason || null);
+ const result = await agentOrchestrator.pauseAgent(req.params.id, reason || null);
res.json(result);
}));
@@ -86,13 +90,13 @@ router.post('/agents/:id/pause', asyncHandler(async (req, res) => {
// killAgent throws a ServerError — 404 when the agent is missing, 500 when the
// runner termination fails — so no result-shape string-matching here.
router.post('/agents/:id/kill', asyncHandler(async (req, res) => {
- const result = await cos.killAgent(req.params.id);
+ const result = await agentOrchestrator.killAgent(req.params.id);
res.json(result);
}));
// GET /api/cos/agents/:id/stats - Get process stats for agent (CPU, memory)
router.get('/agents/:id/stats', asyncHandler(async (req, res) => {
- const stats = await cos.getAgentProcessStats(req.params.id);
+ const stats = await agentOrchestrator.getAgentProcessStats(req.params.id);
// Return success with active:false instead of 404 - this is expected when process isn't running
res.json(stats || { active: false, pid: null });
}));
diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.js
index 98dbde729c..b2dca91bfc 100644
--- a/server/services/agentImportCycles.test.js
+++ b/server/services/agentImportCycles.test.js
@@ -18,7 +18,7 @@
import { describe, it, expect } from 'vitest';
import { readdirSync, readFileSync } from 'fs';
import { fileURLToPath } from 'url';
-import { dirname, join } from 'path';
+import { dirname, join, relative, resolve } from 'path';
import { staticImportSpecifiers } from '../lib/staticImportGraph.js';
const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));
@@ -39,6 +39,7 @@ const CLUSTER = [
'agentSummaryExtraction.js',
'agentRunnerSync.js',
'agentRunnerOutputBatchers.js',
+ 'agentOrchestrator.js',
];
// The static-import scan itself lives in `server/lib/staticImportGraph.js` so
@@ -47,16 +48,36 @@ const CLUSTER = [
// other). It matches static `import`/`export … from` and bare side-effect
// imports only, never `await import()` (deferred to call time, so it can't
// produce a load-time cycle) and never a specifier inside a comment.
+// Every non-test `.js` under SERVICES_DIR, keyed by its path relative to that
+// directory (`agentLifecycle.js`, `agentTuiSpawning/outputSpooler.js`). The
+// walk recurses: scanning only top-level files left a hole big enough to drive
+// the cycle back through, because a subdirectory module can import back up
+// (`agentTuiSpawning/outputSpooler.js` → `../cosAgents.js` is a live example),
+// so a cycle routed through one subdirectory hop was invisible to this guard.
+function listServiceFiles(dir = SERVICES_DIR, prefix = '') {
+ const out = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...listServiceFiles(join(dir, entry.name), rel));
+ else if (entry.name.endsWith('.js') && !entry.name.includes('.test.')) out.push(rel);
+ }
+ return out;
+}
+
function buildStaticGraph() {
- const files = readdirSync(SERVICES_DIR).filter(f => f.endsWith('.js') && !f.includes('.test.'));
+ const files = listServiceFiles();
const known = new Set(files);
const graph = new Map();
for (const file of files) {
+ const abs = join(SERVICES_DIR, file);
const deps = new Set();
- for (const spec of staticImportSpecifiers(join(SERVICES_DIR, file))) {
- // Same-directory siblings only — this guard is scoped to the services dir.
- const sibling = spec.startsWith('./') ? spec.slice(2) : null;
- if (sibling && known.has(sibling)) deps.add(sibling);
+ for (const spec of staticImportSpecifiers(abs)) {
+ if (!spec.startsWith('.')) continue;
+ // Resolve relative to the importing file, then re-key against SERVICES_DIR
+ // so `./x.js` from a subdirectory and `../x.js` from a sibling land on the
+ // same node. Anything resolving outside the services dir is out of scope.
+ const rel = relative(SERVICES_DIR, resolve(dirname(abs), spec));
+ if (known.has(rel)) deps.add(rel);
}
graph.set(file, [...deps]);
}
@@ -103,6 +124,30 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
}
});
+ it('keeps the agentOrchestrator facade outside the cluster it fronts (#3450)', () => {
+ // The facade only stays a facade while its edges point one way: it imports
+ // the cluster, the cluster never imports it back. Checked against the SEVEN
+ // named modules rather than all of `server/services` on purpose — a service
+ // that is NOT in the cluster can import the facade without closing any loop,
+ // and forbidding that would freeze the remaining call-site migrations.
+ //
+ // Both forms are checked. The graph above is static-only (correct for cycle
+ // detection), but this cluster's established habit is to reach across a
+ // blocked layer with `await import()` — so a dynamic import of the facade
+ // from inside the cluster would violate the layering with the cycle walk
+ // fully green, which is the failure mode this module exists to end.
+ const CLUSTER_SEVEN = [
+ 'cos.js', 'cosAgents.js', 'cosAgentLifecycle.js', 'agentManagement.js',
+ 'agents.js', 'subAgentSpawner.js', 'agentLifecycle.js',
+ ];
+ const offenders = CLUSTER_SEVEN.filter(file => {
+ if ((graph.get(file) || []).includes('agentOrchestrator.js')) return true;
+ return /await import\(\s*['"]\.\/agentOrchestrator\.js['"]\s*\)/
+ .test(readFileSync(join(SERVICES_DIR, file), 'utf-8'));
+ });
+ expect(offenders, `agentOrchestrator.js must not be imported by ${offenders.join(', ')}`).toEqual([]);
+ });
+
it('no longer needs the dynamic-import workaround for handleOrphanedTask', () => {
// The cycle-dodge this issue was filed for: agentLifecycle reached
// agentManagement via `await import()` because agentManagement imported it back.
diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.js
new file mode 100644
index 0000000000..cb7834a304
--- /dev/null
+++ b/server/services/agentOrchestrator.js
@@ -0,0 +1,88 @@
+/**
+ * agentOrchestrator — the one place callers ask for an agent LIFECYCLE TRANSITION.
+ *
+ * ## Why this module exists (#3450)
+ *
+ * Seven modules in the core agent path form one tightly-coupled cluster:
+ *
+ * cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js
+ * → agents.js → subAgentSpawner.js → agentLifecycle.js
+ *
+ * with several edges reaching back up the chain. There is no correctness bug —
+ * the load-bearing back-edges are already broken with `await import(...)` (see
+ * the comment at `cosAgentLifecycle.js#pauseAgent`) and `agentImportCycles.test.js`
+ * derives the live static graph from source and guards it. The cost is
+ * comprehension: no module owns the agent state machine, so reasoning about one
+ * transition means holding all seven files in mind.
+ *
+ * This module sits ABOVE that cluster. It imports the three modules that own
+ * transitions (`agentManagement`, `cosAgentLifecycle`, `agentLifecycle`) and is
+ * imported BY nobody inside the cluster — so its edges stay static and callers
+ * above `server/services/` get one unambiguous entry point.
+ *
+ * `subAgentSpawner.js` calls itself an orchestrator but cannot be this: it is
+ * *inside* the cluster (`agents.js` and `cos.js` both reach it via
+ * `await import(...)`), and it re-exports ~40 symbols as a back-compat barrel.
+ * A facade has to be small, complete, and outside the graph it fronts.
+ *
+ * **Invariant, enforced by `agentImportCycles.test.js`: none of those seven
+ * modules may import this one — statically OR via `await import(...)`.** One
+ * such edge closes the loop and puts every dynamic-import workaround back on the
+ * table, and this cluster's habit is to reach across a blocked layer with
+ * `await import()`, so the guard checks both forms. Anything *outside* the seven
+ * may import the facade freely — routes, socket handlers, and any service the
+ * cluster does not depend on. That is the migration path for the exports below
+ * whose current callers are still inside the cluster: the caller moves out, it
+ * does not import back in.
+ *
+ * ## Transition vs leaf (step 1 of the #3450 sequencing)
+ *
+ * TRANSITIONS move an agent between states. They are exactly the exports below,
+ * annotated there with the state edge each one drives. Two of them are the same
+ * name in two different modules — `cosAgentLifecycle.terminateAgent` only
+ * *requests* termination (emits `agent:terminate`, returns immediately) while
+ * `agentManagement.terminateAgent` runs the real signal sequence. That collision
+ * is the most confusing thing in the cluster, so the facade renames the
+ * request-side one to `requestAgentTermination` and lets the process-side one
+ * keep its name, symmetric with its sibling `killAgent`. CLAUDE.md resolves
+ * same-name collisions with `export * as <namespace>`, but namespacing here
+ * would spell the call `agentOrchestrator.agentManagement.terminateAgent` —
+ * re-exposing the very leaf module the facade exists to hide — so this one
+ * renames instead.
+ *
+ * LEAVES are everything a transition calls on its way through, and they stay
+ * exactly where they are — the facade does not wrap them and never should:
+ * persisted agent state (`cosAgentLifecycle` reads/writes, `cosAgentIndex`,
+ * `cosState`), the in-memory maps (`agentState`), OS process control (`agents.js`,
+ * `bufferedSpawn.killProcessTree`), runner RPC (`cosRunnerClient`), the task store
+ * (`cos.js` task functions), post-run work (`agentWorktreeCleanup`,
+ * `agentFinalization`, `agentRunTracking`, `agentCompletionCleanup`,
+ * `agentSummaryExtraction`), and the pure re-export barrels (`cosAgents.js`,
+ * `subAgentSpawner.js`). If it is not exported below, it is a leaf.
+ *
+ * ## What is still outstanding
+ *
+ * `server/routes/cosAgentRoutes.js` is migrated. Every other call site still
+ * reaches these transitions through `cos.js` or `subAgentSpawner.js`, and the
+ * `await import(...)` forwarders at `cosAgentLifecycle.js#pauseAgent` /
+ * `#killAgent` / `#getAgentProcessStats` still exist to serve them — those are
+ * steps 3 and 4 of the #3450 sequencing. `grep -rn agentOrchestrator server/`
+ * is the live answer to "what has moved so far".
+ */
+
+// Process/runner layer — owns the live agent maps and the OS-level signals.
+export {
+ pauseAgent, // running → paused (process stopped, worktree preserved)
+ killAgent, // running → completed (immediate SIGKILL)
+ terminateAgent, // running → completed (SIGTERM, SIGKILL fallback)
+ getAgentProcessStats, // read, not a transition — but it needs the process layer
+} from './agentManagement.js';
+
+// Persisted-state layer — owns the agent record on disk.
+export {
+ completeAgent, // running|paused → completed
+ terminateAgent as requestAgentTermination, // emits `agent:terminate`, returns
+} from './cosAgentLifecycle.js';
+
+// Spawn layer — turns a task into a running agent.
+export { spawnAgentForTask } from './agentLifecycle.js'; // (none) → running
diff --git a/server/services/agentOrchestrator.test.js b/server/services/agentOrchestrator.test.js
new file mode 100644
index 0000000000..41f5fa9314
--- /dev/null
+++ b/server/services/agentOrchestrator.test.js
@@ -0,0 +1,65 @@
+/**
+ * The facade is a re-export surface (#3450), so argument forwarding cannot fail —
+ * `export { x } from './y.js'` is a binding alias, not a wrapper. What CAN fail
+ * is the wiring: an alias pointed at the wrong leaf. `agentManagement.js` and
+ * `cosAgentLifecycle.js` both export a function called `terminateAgent` and they
+ * do completely different things — one emits `agent:terminate` and returns, the
+ * other runs the real SIGTERM/SIGKILL sequence — so a copy-paste swap between
+ * them is silent and severe. These assertions pin binding identity, which is the
+ * property that actually holds, and pin the surface so the facade cannot quietly
+ * regrow into a second barrel.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('./agentManagement.js', () => ({
+ pauseAgent: () => {},
+ killAgent: () => {},
+ terminateAgent: () => {},
+ getAgentProcessStats: () => {}
+}));
+
+vi.mock('./cosAgentLifecycle.js', () => ({
+ completeAgent: () => {},
+ terminateAgent: () => {}
+}));
+
+vi.mock('./agentLifecycle.js', () => ({
+ spawnAgentForTask: () => {}
+}));
+
+import * as orchestrator from './agentOrchestrator.js';
+import * as agentManagement from './agentManagement.js';
+import * as cosAgentLifecycle from './cosAgentLifecycle.js';
+import * as agentLifecycle from './agentLifecycle.js';
+
+// [facade export, source module, name in that module]
+const WIRING = [
+ ['pauseAgent', agentManagement, 'pauseAgent'],
+ ['killAgent', agentManagement, 'killAgent'],
+ ['terminateAgent', agentManagement, 'terminateAgent'],
+ ['getAgentProcessStats', agentManagement, 'getAgentProcessStats'],
+ ['completeAgent', cosAgentLifecycle, 'completeAgent'],
+ ['requestAgentTermination', cosAgentLifecycle, 'terminateAgent'],
+ ['spawnAgentForTask', agentLifecycle, 'spawnAgentForTask']
+];
+
+describe('agentOrchestrator facade (#3450)', () => {
+ it.each(WIRING)('%s resolves to the intended leaf', (exported, mod, leaf) => {
+ expect(orchestrator[exported]).toBe(mod[leaf]);
+ });
+
+ it('keeps the two same-named terminates distinct', () => {
+ // The whole point of the rename. If these ever converge, one of the two
+ // aliases is pointed at the wrong module and the identity checks above
+ // would both still pass against a single shared binding.
+ expect(orchestrator.terminateAgent).not.toBe(orchestrator.requestAgentTermination);
+ });
+
+ it('exposes exactly the transition surface — new exports are a deliberate decision', () => {
+ // The facade's value is that it is small and complete. A drive-by export
+ // slipped in here is how a facade turns back into a second barrel, so the
+ // set is pinned: growing it means updating this list on purpose.
+ expect(Object.keys(orchestrator).sort()).toEqual(WIRING.map(([name]) => name).sort());
+ });
+});