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: retire the agent state-layer's deferred imports into the process layer (#3450)

[._.]/ Adam Eivybc6f8253c820
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index eb5100e736..26cc718c03 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **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 anything reachable from the facade imports it back, statically *or* via `import(...)` — the dynamic form matters because reaching across a blocked layer that way is exactly this cluster's habit, and the forbidden set is derived from the graph rather than listed so it can't fall behind. 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).
+- **The agent-lifecycle cluster lost the deferred imports it used to reach across its own layering.** `cosAgentLifecycle.js` carried three `await import('./agentManagement.js')` forwarders — `pauseAgent`, `killAgent`, `getAgentProcessStats` — that existed purely so a caller holding a `cos.js` handle could reach the process layer from the agent *state* layer, which cannot import it statically without inverting the layering. Their only consumer was `cos.js`'s own re-export block, so both are gone: those three transitions come from `agentOrchestrator.js` now. `agents.js` moved onto the facade too, which needed an actual structural fix rather than an import swap — it was stuck reaching `killAgent` through `await import('./subAgentSpawner.js')` because `agentManagement.js` imported `unregisterSpawnedAgent` back out of it, and that same back-edge put `agents.js` inside the facade's closure where importing the facade was forbidden. Pushing the pid map both sides wanted down into `agentState.js` — the import-free leaf they already shared other agent state through — deleted the edge; `agents.js` fell out of the closure and took a plain static import. `subAgentSpawner.js`'s event wiring (`task:ready` → spawn, `agent:terminate` → terminate, runner-error → complete) now asks the facade for those transitions instead of three separate leaves. `agentImportCycles.test.js` gains a guard for each half, each verified to fail on a planted violation: no new deferred import from the state layer into the process layer, no process-layer transition back in `cos.js`'s re-export block (derived from the facade's own export blocks rather than a hand-listed set, minus the one genuine name collision), `agentState.js` stays import-free, and `agents.js` reaches the facade statically. The facade header now describes that extract-a-leaf move as the shape every remaining migration takes, rather than carrying a call-site inventory that would go stale (#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/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index e746424388..738af197a0 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -12,13 +12,12 @@ import { spawn } from 'child_process';
import { homedir } from 'os';
import { cosEvents, emitLog } from './cosEvents.js';
import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgents.js';
-import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
-import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { normalizeReviewers } from '../lib/validation.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 9d10aeb65f..6fc70c0c1d 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -34,10 +34,6 @@ vi.mock('./cosAgents.js', () => {
createAgentOutputBatcher,
};
});
-vi.mock('./agents.js', () => ({
- registerSpawnedAgent: vi.fn(),
- unregisterSpawnedAgent: vi.fn(),
-}));
vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));
vi.mock('./toolStateMachine.js', () => ({
completeExecution: vi.fn(),
@@ -57,6 +53,8 @@ vi.mock('./agentState.js', () => ({
activeAgents: new Map(),
userTerminatedAgents: new Set(),
pausedAgents: new Map(),
+ registerSpawnedAgent: vi.fn(),
+ unregisterSpawnedAgent: vi.fn(),
metaStringOr: (value, fallback) => (typeof value === 'string' && value) ? value : fallback,
}));
vi.mock('../lib/fileUtils.js', () => ({
diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.js
index a1dca93255..cec4084b22 100644
--- a/server/services/agentImportCycles.test.js
+++ b/server/services/agentImportCycles.test.js
@@ -84,6 +84,25 @@ function buildStaticGraph() {
return graph;
}
+// Does `file` reach `mod` with a DEFERRED import? The static graph deliberately
+// ignores `import()` — correct for cycle detection, since a deferred import
+// cannot produce a load-time cycle — but reaching across a blocked layer that
+// way is exactly this cluster's habit, so several guards below need to see it.
+// One implementation, because two copies of a structural matcher is how a guard
+// rots: a fix to one silently under-reports in the other (the same reason the
+// static scan lives once in `server/lib/staticImportGraph.js`).
+//
+// The match is deliberately loose — anything between `import(` and the closing
+// paren that names the module — so quotes, template literals, an interleaved
+// comment and any path depth all count. `await` is NOT required, so a
+// `return import(...).then(...)` back-edge is caught too. A mention inside a
+// comment trips it as well; that fails CLOSED, which is the correct bias for a
+// structural guard (the alternative is a green suite over a live back-edge).
+function importsDynamically(file, mod) {
+ const src = readFileSync(join(SERVICES_DIR, file), 'utf-8');
+ return new RegExp(String.raw`\bimport\(\s*[^)]*\b${mod.replace(/\./g, '\\.')}[^)]*\)`).test(src);
+}
+
function findCycles(graph) {
const cycles = new Set();
const stack = [];
@@ -146,31 +165,90 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
walk('agentOrchestrator.js');
expect(reachable.size, 'facade closure looks empty — did the module move?').toBeGreaterThan(3);
- // Dynamic imports are matched too, and WITHOUT requiring `await`: the static
- // graph deliberately ignores `import()` (correct for cycle detection), but
- // reaching across a blocked layer with a deferred import is exactly this
- // cluster's habit, so a `return import(...).then(...)` back-edge would
- // violate the layering with the cycle walk fully green.
- //
- // The match is deliberately loose — anything between `import(` and the
- // closing paren that names the facade — so quotes, template literals and an
- // interleaved comment all count, at any path depth. A mention inside a
- // comment would also trip it; that fails CLOSED, which is the correct bias
- // for a structural guard (the alternative is a green suite over a live
- // back-edge).
- const DYNAMIC_FACADE_IMPORT = /\bimport\(\s*[^)]*\bagentOrchestrator\.js[^)]*\)/;
+ // Deferred imports count as back-edges here too — see `importsDynamically`.
const offenders = [...reachable].filter(file =>
(graph.get(file) || []).includes('agentOrchestrator.js') ||
- DYNAMIC_FACADE_IMPORT.test(readFileSync(join(SERVICES_DIR, file), 'utf-8'))
+ importsDynamically(file, 'agentOrchestrator.js')
).sort();
expect(offenders, `agentOrchestrator.js must not be imported by ${offenders.join(', ')}`).toEqual([]);
});
+ it('no longer needs the state-layer forwarders into the process layer (#3450)', () => {
+ // Step 4 of the #3450 sequencing. `cosAgentLifecycle.js` — the agent STATE
+ // layer — used to forward pause/kill/stats into the PROCESS layer with
+ // `await import()`, purely so a caller holding a `cos.js` handle could reach
+ // across a boundary the state layer cannot import across statically. Those
+ // callers go through the facade now.
+ //
+ // Guard the mechanism, not the three names: ANY deferred import of
+ // `agentManagement.js` from here is a new forwarder. A *static* one needs no
+ // assertion — it closes a cycle the walk above already fails on.
+ expect(importsDynamically('cosAgentLifecycle.js', 'agentManagement.js'),
+ 'cosAgentLifecycle.js must not defer-import the process layer — ask the facade').toBe(false);
+
+ // The other half: `cos.js` re-exporting those transitions is what gave the
+ // forwarders callers in the first place. Derive which names are off-limits
+ // from the facade itself — everything it takes from the process layer —
+ // rather than listing them, so the rule tracks the facade as it grows.
+ //
+ // Minus the names the facade ALSO serves from the state layer. That set is
+ // `terminateAgent`, the one genuine collision in this cluster: `cos.js`
+ // legitimately re-exports the state-layer function of that name, and it is
+ // only unambiguous inside the facade because the facade renames it to
+ // `requestAgentTermination`. Subtracting is what keeps this derivation from
+ // failing on a name `cos.js` is right to export.
+ const facade = readFileSync(join(SERVICES_DIR, 'agentOrchestrator.js'), 'utf-8');
+ const reexportedFrom = (source) => {
+ const block = facade.match(new RegExp(String.raw`export\s*\{([^}]*)\}\s*from\s*'\./${source}'`));
+ expect(block, `facade no longer re-exports from ${source} — did the layering change?`).toBeTruthy();
+ return block[1]
+ .replace(/\/\/[^\n]*/g, '') // strip the per-export state-edge comments
+ .split(',')
+ .map(entry => entry.split(/\s+as\s+/)[0].trim())
+ .filter(Boolean);
+ };
+ const stateLayer = new Set(reexportedFrom('cosAgentLifecycle.js'));
+ const forbidden = reexportedFrom('agentManagement.js').filter(name => !stateLayer.has(name));
+ expect(forbidden.length, 'derived nothing to forbid — check the facade export blocks').toBeGreaterThan(0);
+
+ // Scope to the re-export statements, not the whole file: `completeAgent` and
+ // friends legitimately appear elsewhere in cos.js. ALL of them, via matchAll
+ // — the realistic way one of these comes back is a second
+ // `export { pauseAgent } from './cosAgents.js';` statement, which a
+ // first-match-only scan would never see, staying green over the regression.
+ const cosReexports = [...readFileSync(join(SERVICES_DIR, 'cos.js'), 'utf-8')
+ .matchAll(/export\s*\{[^}]*\}\s*from\s*'\.\/cosAgents\.js'/g)].map(m => m[0]).join('\n');
+ expect(cosReexports, 'cos.js agent re-export block not found — did it move?').toBeTruthy();
+ for (const name of forbidden) {
+ expect(cosReexports, `cos.js must not re-export ${name} — it is a process-layer transition, ask the facade`)
+ .not.toMatch(new RegExp(String.raw`\b${name}\b`));
+ }
+
+ // Scoped to `cos.js` on purpose: `subAgentSpawner.js` still re-exports these
+ // same three from `agentManagement.js`. That barrel is the cluster's declared
+ // back-compat surface and retiring it is its own slice of #3450, so widening
+ // this to "no module may re-export a facade transition" would fail today. The
+ // narrower rule holds the line where the forwarders actually had callers.
+ });
+
+ it('keeps agentState.js an import-free leaf, so agents.js can use the facade (#3450)', () => {
+ // `agentState.js` is what lets modules that cannot import each other share
+ // state — the pid map moved here so `agentManagement.js` no longer had to
+ // import it out of `agents.js`. One import of a cluster module here would
+ // close a cycle for every such pair at once, so it must stay import-free.
+ expect(graph.get('agentState.js')).toEqual([]);
+
+ // The payoff: with that back-edge gone, agents.js is outside the facade's
+ // closure and reaches the kill transition through a plain static import.
+ expect(importsDynamically('agents.js', 'subAgentSpawner.js'),
+ 'agents.js must not defer-import the spawner barrel — the facade is a static import now').toBe(false);
+ expect(graph.get('agents.js')).toContain('agentOrchestrator.js');
+ });
+
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.
- const src = readFileSync(join(SERVICES_DIR, 'agentLifecycle.js'), 'utf-8');
- expect(src).not.toMatch(/await import\(\s*['"]\.\/agentManagement\.js['"]\s*\)/);
- expect(src).toMatch(/import \{ handleOrphanedTask \} from '\.\/agentManagement\.js';/);
+ expect(importsDynamically('agentLifecycle.js', 'agentManagement.js')).toBe(false);
+ expect(graph.get('agentLifecycle.js')).toContain('agentManagement.js');
});
});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 8018ebb2ab..5099efe207 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -11,10 +11,9 @@ import { emitLog } from './cosEvents.js';
import { completeAgent, updateAgent } from './cosAgents.js';
import { updateTask, addTask, getTaskById } from './cos.js';
import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
-import { unregisterSpawnedAgent } from './agents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, isAgentOwnedLocally } from './agentState.js';
+import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, isAgentOwnedLocally, unregisterSpawnedAgent } from './agentState.js';
// Both were extracted out of agentLifecycle.js (issue #2837) so this module no
// longer depends on the lifecycle orchestrator — which depends on THIS module
// for handleOrphanedTask. Importing them from their own leaf modules is what
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 79035e77fd..0ec6351879 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -70,7 +70,6 @@ vi.mock('./cosRunnerClient.js', () => ({
getAgentStatsFromRunner: vi.fn(),
getActiveAgentsFromRunner: vi.fn().mockResolvedValue([])
}));
-vi.mock('./agents.js', () => ({ unregisterSpawnedAgent: vi.fn() }));
vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));
vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));
vi.mock('./shell.js', () => ({ writeToSession: vi.fn(), killSession: vi.fn() }));
diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.js
index 8b82a54af6..bfdb938328 100644
--- a/server/services/agentOrchestrator.js
+++ b/server/services/agentOrchestrator.js
@@ -9,11 +9,12 @@
* → 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.
+ * the load-bearing back-edges were broken with `await import(...)` before this
+ * module existed, 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. (`cos.js#handleOrphanedTask` is what a surviving deferred back-edge
+ * looks like; the ones this facade replaced are described further down.)
*
* This module sits ABOVE that cluster. It imports the three modules that own
* transitions (`agentManagement`, `cosAgentLifecycle`, `agentLifecycle`) and is
@@ -21,9 +22,10 @@
* 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.
+ * *inside* the cluster — `cos.js` still reaches it via `await import(...)` — and
+ * it re-exports ~40 symbols as a back-compat barrel, including three transitions
+ * this facade also owns. A facade has to be small, complete, and outside the
+ * graph it fronts; retiring that barrel is its own slice of #3450.
*
* **Invariant, enforced by `agentImportCycles.test.js`: no module reachable
* FROM this one may import it back — statically OR via `import(...)`.** One such
@@ -61,14 +63,27 @@
* `agentSummaryExtraction`), and the pure re-export barrels (`cosAgents.js`,
* `subAgentSpawner.js`). If it is not exported below, it is a leaf.
*
+ * ## Moving a caller out (the shape every migration takes)
+ *
+ * A caller is stuck inside the closure because something in the closure imports
+ * IT. Find that edge, push what the importer actually wanted down into a leaf,
+ * and the caller migrates itself. Use `agentState.js` for shared mutable state —
+ * it is import-free precisely so modules that cannot import each other can still
+ * share; do not add a second leaf beside it. Do NOT reach back in with a deferred
+ * import: the guard rejects it, and it is how this cluster got here in the first
+ * place. `agentState.js#spawnedAgentCommands` documents the worked example.
+ *
* ## 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".
+ * `server/routes/cosAgentRoutes.js`, `agents.js` and `subAgentSpawner.js`'s event
+ * wiring are migrated, and the deferred forwarders that used to sit in
+ * `cosAgentLifecycle.js` are gone along with the `cos.js` re-exports that were
+ * their only consumers — steps 3 and 4 of the #3450 sequencing. Remaining:
+ * the transitions below that still have callers INSIDE the closure, and the
+ * three overlapping barrels (`cosAgents.js`, `subAgentSpawner.js`, and `cos.js`'s
+ * agent re-export block), which each expose a partial view of the cluster.
+ * `grep -rn agentOrchestrator server/` is the live answer to what has moved —
+ * do not keep a hand-written call-site inventory here; it only goes stale.
*/
// Process/runner layer — owns the live agent maps and the OS-level signals.
diff --git a/server/services/agentState.js b/server/services/agentState.js
index a2a60a5718..a7c3f3dfbb 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -1,6 +1,10 @@
/**
* Shared mutable state for agent tracking.
* Imported by agentLifecycle.js, agentManagement.js, and subAgentSpawner.js.
+ *
+ * **This module must stay import-free.** It is what lets modules that cannot
+ * import each other share state, so one import of a cluster module here closes
+ * a cycle for every one of them at once. `agentImportCycles.test.js` enforces it.
*/
// activeAgents: direct spawn mode processes (Map<agentId, { process, task, runId, ... }>)
@@ -19,6 +23,39 @@ export const pausedAgents = new Map();
// spawningTasks: tasks currently being spawned (Set<taskId>) — deduplication guard
export const spawningTasks = new Set();
+// spawnedAgentCommands: OS pid → spawn metadata for agents this server started
+// (Map<pid, { fullCommand, agentId, taskId, model, workspacePath, prompt, registeredAt }>).
+//
+// Lived in `agents.js` until #3450. It had to move because it was the last edge
+// from the agent cluster into `agents.js`: `agentManagement.js` imported
+// `unregisterSpawnedAgent` from there, so `agents.js` could not import the
+// `killAgent` transition back without a cycle — it reached it through
+// `await import('./subAgentSpawner.js')` instead, and that same back-edge put
+// `agents.js` inside the `agentOrchestrator` facade's closure, where importing
+// the facade was forbidden too. With the map here (a module both sides already
+// import, and which imports nothing itself) the edge is gone and `agents.js`
+// takes a plain static `import … from './agentOrchestrator.js'`.
+const spawnedAgentCommands = new Map();
+
+// Register a spawned agent's full command (call when spawning).
+export const registerSpawnedAgent = (pid, data) => {
+ spawnedAgentCommands.set(pid, {
+ fullCommand: data.fullCommand,
+ agentId: data.agentId,
+ taskId: data.taskId,
+ model: data.model,
+ workspacePath: data.workspacePath,
+ prompt: data.prompt,
+ registeredAt: Date.now()
+ });
+};
+
+// Unregister a spawned agent (call when its process exits).
+export const unregisterSpawnedAgent = (pid) => { spawnedAgentCommands.delete(pid); };
+
+// Spawn metadata for a pid, or undefined when the pid is not one of ours.
+export const getSpawnedAgent = (pid) => spawnedAgentCommands.get(pid);
+
// useRunner: whether CoS Runner mode is active
export let useRunner = false;
export const setUseRunner = (val) => { useRunner = val; };
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 957e4811b9..50a239126c 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -12,11 +12,10 @@ import { readFile, rm } from 'fs/promises';
import * as shellService from './shell.js';
import { emitLog } from './cosEvents.js';
import { updateAgent } from './cosAgents.js';
-import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';
import { captureWorktreeDiff, worktreeHasChanges, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
-import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';
import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 7c9a5af1fa..0cac1068b3 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -28,10 +28,6 @@ vi.mock('./cosAgents.js', () => ({
completeAgent: vi.fn().mockResolvedValue(undefined)
}));
-vi.mock('./agents.js', () => ({
- registerSpawnedAgent: vi.fn(),
- unregisterSpawnedAgent: vi.fn()
-}));
vi.mock('./providerStatus.js', () => ({
markProviderUsageLimit: vi.fn().mockResolvedValue(undefined),
@@ -86,6 +82,8 @@ vi.mock('./agentState.js', () => ({
activeAgents: new Map(),
userTerminatedAgents: new Set(),
pausedAgents: new Map(),
+ registerSpawnedAgent: vi.fn(),
+ unregisterSpawnedAgent: vi.fn(),
// Mirrors the real predicate (covers the TASKS.md string round-trip) — the
// worktreeChangesExpected opt-out reads through it.
isFalsyMeta: (value) => value === false || value === 'false',
diff --git a/server/services/agents.js b/server/services/agents.js
index daf196f713..6683a90ad6 100644
--- a/server/services/agents.js
+++ b/server/services/agents.js
@@ -1,5 +1,7 @@
import { exec } from 'child_process';
import { promisify } from 'util';
+import { getSpawnedAgent } from './agentState.js';
+import { killAgent } from './agentOrchestrator.js';
const execAsync = promisify(exec);
@@ -14,9 +16,6 @@ const AGENT_PATTERNS = [
{ name: 'Copilot', pattern: 'copilot', command: 'copilot' }
];
-// Track spawned agents with their full commands (by PID)
-const spawnedAgentCommands = new Map();
-
/**
* Decide whether a matched process line is a real AI-agent CLI or an OS/UI
* helper that only happens to share a substring with an agent name.
@@ -41,28 +40,6 @@ export function isAgentProcessCommand(command) {
return true;
}
-/**
- * Register a spawned agent's full command (call when spawning)
- */
-export function registerSpawnedAgent(pid, data) {
- spawnedAgentCommands.set(pid, {
- fullCommand: data.fullCommand,
- agentId: data.agentId,
- taskId: data.taskId,
- model: data.model,
- workspacePath: data.workspacePath,
- prompt: data.prompt,
- registeredAt: Date.now()
- });
-}
-
-/**
- * Unregister a spawned agent (call when process exits)
- */
-export function unregisterSpawnedAgent(pid) {
- spawnedAgentCommands.delete(pid);
-}
-
/**
* Get list of running agent processes
*/
@@ -73,7 +50,7 @@ export async function getRunningAgents() {
const procs = await findProcesses(agent.pattern);
procs.forEach(proc => {
// Enrich with spawned command data if available
- const spawnedData = spawnedAgentCommands.get(proc.pid);
+ const spawnedData = getSpawnedAgent(proc.pid);
agents.push({
...proc,
@@ -295,7 +272,8 @@ function formatRuntime(ms) {
/**
* Kill a process by PID.
* If the process is a CoS-spawned agent, delegates to the CoS killAgent
- * to ensure the task is properly blocked instead of requeued.
+ * transition (via the `agentOrchestrator` facade) so the task is properly
+ * blocked instead of requeued.
*/
export async function killProcess(pid) {
// Security: Ensure PID is a valid integer to prevent command injection
@@ -305,10 +283,9 @@ export async function killProcess(pid) {
}
// Check if this PID belongs to a CoS-spawned agent
- const spawnedData = spawnedAgentCommands.get(safePid);
+ const spawnedData = getSpawnedAgent(safePid);
if (spawnedData?.agentId) {
console.log(`🔪 PID ${safePid} is CoS agent ${spawnedData.agentId}, delegating to CoS killAgent`);
- const { killAgent } = await import('./subAgentSpawner.js');
// killAgent throws a ServerError when the agent is missing or the kill
// fails; treat that as "already gone" and fall through to the raw kill
// below rather than surfacing it — this path is a best-effort cleanup.
diff --git a/server/services/agents.test.js b/server/services/agents.test.js
index 780ab4a469..4bd1fb6fc7 100644
--- a/server/services/agents.test.js
+++ b/server/services/agents.test.js
@@ -23,15 +23,16 @@ vi.mock('util', async (importOriginal) => {
};
});
-// Mock subAgentSpawner so killProcess CoS delegation doesn't import real code
-vi.mock('./subAgentSpawner.js', () => ({
+// Mock the orchestrator facade so killProcess's CoS delegation doesn't import
+// the real agent cluster (#3450 — agents.js reaches killAgent through the facade
+// now, not through the subAgentSpawner barrel).
+vi.mock('./agentOrchestrator.js', () => ({
killAgent: vi.fn().mockResolvedValue({ success: true })
}));
import { exec } from 'child_process';
+import { registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import {
- registerSpawnedAgent,
- unregisterSpawnedAgent,
getRunningAgents,
killProcess,
getProcessInfo,
@@ -129,7 +130,7 @@ describe('agents.js', () => {
// Verify the CoS killAgent mock was invoked with the registered agentId —
// this proves the registry entry is live and used by killProcess.
- const { killAgent } = await import('./subAgentSpawner.js');
+ const { killAgent } = await import('./agentOrchestrator.js');
expect(killAgent).toHaveBeenCalledWith('agent-ts');
});
@@ -137,7 +138,7 @@ describe('agents.js', () => {
// killAgent now throws a ServerError when the agent is already gone
// (issue #2534). killProcess must catch that and fall through to a raw
// kill rather than surfacing the throw.
- const { killAgent } = await import('./subAgentSpawner.js');
+ const { killAgent } = await import('./agentOrchestrator.js');
killAgent.mockRejectedValueOnce(
Object.assign(new Error('Agent not found or not running'), { status: 404, code: 'NOT_FOUND' }),
);
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 6f1812507e..606a5dfce3 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -84,10 +84,6 @@ vi.mock('./promptService.js', () => ({
buildPrompt: vi.fn()
}));
-vi.mock('./agents.js', () => ({
- registerSpawnedAgent: vi.fn(),
- unregisterSpawnedAgent: vi.fn()
-}));
vi.mock('./memoryRetriever.js', () => ({
getMemorySection: vi.fn()
diff --git a/server/services/cos.js b/server/services/cos.js
index 052c89affb..87792d185b 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -39,8 +39,13 @@ import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEn
import { cosEvents, emitLog } from './cosEvents.js';
export { cosEvents, emitLog };
-// Agent lifecycle (re-export for backward compat with `import * as cos`)
-export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, pauseAgent, killAgent, sendBtwToAgent, getAgentProcessStats, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
+// Agent lifecycle (re-export for backward compat with `import * as cos`).
+//
+// `pauseAgent` / `killAgent` / `getAgentProcessStats` are deliberately NOT here:
+// they are process-layer transitions, and re-exporting them from the task store
+// is what forced the `await import()` forwarders in `cosAgentLifecycle.js`.
+// Callers ask `agentOrchestrator.js` for those (#3450).
+export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, sendBtwToAgent, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
// Reports and activity (re-export for backward compat with `import * as cos`)
export { generateReport, getReport, getTodayReport, listReports, listBriefings, getBriefing, getLatestBriefing, getTodayActivity, getWhileAwayActivity, getRecentTasks, formatRelativeTime } from './cosReports.js';
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 14d539330f..7a48f111a6 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -446,24 +446,12 @@ export async function terminateAgent(agentId) {
return { success: true, agentId };
}
-// Pause an agent without completing its task or cleaning up its worktree.
-//
-// The three delegations below stay DYNAMIC on purpose (#2837): this module is
-// the agent STATE layer that `agentManagement.js` builds on (via the
-// `cosAgents.js` barrel), so a static import here would invert the layering and
-// reintroduce a cycle. They now target `agentManagement.js` directly rather than
-// the `subAgentSpawner.js` barrel, so the deferred load pulls in one module
-// instead of the entire spawner graph.
-export async function pauseAgent(agentId, reason = null) {
- const { pauseAgent: pauseAgentFromSpawner } = await import('./agentManagement.js');
- return pauseAgentFromSpawner(agentId, reason);
-}
-
-// Force kill an agent with SIGKILL (immediate, no graceful shutdown)
-export async function killAgent(agentId) {
- const { killAgent: killAgentFromSpawner } = await import('./agentManagement.js');
- return killAgentFromSpawner(agentId);
-}
+// `pauseAgent` / `killAgent` / `getAgentProcessStats` moved to
+// `agentOrchestrator.js` (#3450). They lived here as deferred-import forwarders
+// into the process layer, which this STATE layer cannot import statically
+// without inverting the layering — so do not re-add one. Ask the facade for a
+// transition; `agentImportCycles.test.js` fails on any new deferred import of
+// `agentManagement.js` from this file.
// Send a BTW (additional context) message to a running agent.
//
@@ -521,12 +509,6 @@ export async function sendBtwToAgent(agentId, message) {
return { success: true, delivered: 'tui-paste', tuiSessionId: agentInfo.tuiSessionId };
}
-// Get process stats for an agent (CPU, memory)
-export async function getAgentProcessStats(agentId) {
- const { getAgentProcessStats: getStatsFromSpawner } = await import('./agentManagement.js');
- return getStatsFromSpawner(agentId);
-}
-
// Check if a PID is still running
async function isPidAlive(pid) {
if (!pid) return false;
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 51efa2aff5..20c06f56a9 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -14,16 +14,22 @@ import { join } from 'path';
import { readdir, rm, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { emitLog, cosEvents } from './cosEvents.js';
-import { updateAgent, completeAgent } from './cosAgents.js';
+import { updateAgent } from './cosAgents.js';
import { initProviderStatus } from './providerStatus.js';
import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';
import { PATHS } from '../lib/fileUtils.js';
import { loadSlashdoFile } from '../lib/slashdoLoader.js';
import { getRunnerOutputBatcher, flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
-import { handleAgentCompletion, spawnAgentForTask } from './agentLifecycle.js';
-import { cleanupOrphanedAgents, terminateAgent } from './agentManagement.js';
+import { handleAgentCompletion } from './agentLifecycle.js';
+import { cleanupOrphanedAgents } from './agentManagement.js';
import { completeAgentRun } from './agentRunTracking.js';
+// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
+// them from the facade rather than from the three separate leaves that happen to
+// implement them (#3450). It can: nothing the facade imports imports this barrel
+// back, so the edge stays one-directional. The `export { … }` blocks below still
+// name the leaves directly — those are the back-compat barrel surface, not calls.
+import { completeAgent, spawnAgentForTask, terminateAgent } from './agentOrchestrator.js';
// ─── Shared state (imported from agentState.js) ──────────────────────────────
export { activeAgents, runnerAgents, userTerminatedAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta, getActiveAgentIds } from './agentState.js';