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 subAgentSpawner re-export barrel so a transition has one address (#3450)

[._.]/ Adam Eivy4b80f3767c5e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6831129757..7b43a63541 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
- **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).
+- **The agent cluster's back-compat re-export barrel is retired, so a lifecycle transition has one address instead of three.** `subAgentSpawner.js` re-exported ~40 symbols from nine sibling modules "for backward compatibility" — a second, partial view of the cluster layered over `cosAgents.js` and `cos.js`'s agent block, including the same three process-layer transitions (`pauseAgent` / `killAgent` / `getAgentProcessStats`) that `agentOrchestrator.js` owns. That overlap is why the previous PR's "no module may re-export a facade transition" guard had to be narrowed to `cos.js`: stating the rule generally would have failed on the barrel. The barrel had almost no consumers left — `telegram.js` reaching `getActiveAgents`, two `await import('./subAgentSpawner.js')` calls in `cos.js` for `cleanupOrphanedAgents` / `handleOrphanedTask`, and three test files — and all of them now name the module that actually defines what they want, which also deletes the last two `cos.js → subAgentSpawner.js` edges from the seven-module chain. `agentLifecycle.js`'s pass-through re-exports of the leaves extracted out of it (`finalizeAgent`, `extractFinalSummary`, `syncRunnerAgents`, the worktree-cleanup cluster) went with it: the barrel was their last consumer, and an orchestrator re-exporting the leaves beneath it is what made "where does `finalizeAgent` live" a three-answer question. What remains in `subAgentSpawner.js` is what it actually does — `initSpawner()`'s runner connection and event wiring. Two guards in `agentImportCycles.test.js` hold the line, both bypass-probed: the transition re-export rule now runs over `cos.js` *and* `subAgentSpawner.js`, and a new one asserts each cluster orchestrator declares everything it exports, comparing the module's live key list against its own declarations so `export *`, `export { x } from …`, and `import` + a bare `export { x }` all fail identically rather than each needing its own regex (#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/client/public/flows.json b/client/public/flows.json
index 2e219c9074..459aa00015 100644
--- a/client/public/flows.json
+++ b/client/public/flows.json
@@ -56,7 +56,7 @@
{ "id": "svc.voicePipeline", "label": "voice pipeline", "group": "server-services", "file": "server/services/voice/pipeline.js", "desc": "Voice turn orchestration: STT → LLM tool loop → TTS streaming." },
{ "id": "svc.voiceTools", "label": "voice tools", "group": "server-services", "file": "server/services/voice/tools.js", "desc": "Voice agent tool schemas + dispatch: navigation, UI actions, timers, calendar." },
{ "id": "svc.cos", "label": "cos", "group": "server-services", "file": "server/services/cos.js", "desc": "CoS task lifecycle: create/approve/queue; emits task:ready." },
- { "id": "svc.subAgentSpawner", "label": "subAgentSpawner", "group": "server-services", "file": "server/services/subAgentSpawner.js", "desc": "Turns a ready task into a running agent: prompt build, model selection, worktree prep." },
+ { "id": "svc.subAgentSpawner", "label": "subAgentSpawner", "group": "server-services", "file": "server/services/subAgentSpawner.js", "desc": "Wires task:ready and the CoS Runner events to the spawn path; agentLifecycle.js does the prompt build, model selection and worktree prep." },
{ "id": "svc.cosRunnerClient", "label": "cosRunnerClient", "group": "server-services", "file": "server/services/cosRunnerClient.js", "desc": "Client for the standalone CoS Runner process (Socket.IO + HTTP health)." },
{ "id": "svc.cosAgents", "label": "cosAgents", "group": "server-services", "file": "server/services/cosAgents.js", "desc": "Agent state index (date-bucketed JSON) + agent:* event fan-out to the UI." },
{ "id": "svc.pm2", "label": "pm2 service", "group": "server-services", "file": "server/services/pm2.js", "desc": "PM2 wrapper: CLI spawn + programmatic connect, strict jlist status." },
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 102b923ca4..6a605ebe37 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -215,10 +215,11 @@ Server Event → Socket.IO → socket.js → React Component State Update
- Self-improvement task generation
### Sub-Agent Spawner (`server/services/subAgentSpawner.js`)
-- Claude CLI process spawning
-- Model selection based on task complexity
-- MCP server integration
-- Usage tracking
+- `initSpawner()`: CoS Runner connection + runner event handlers, the `task:ready` → spawn and `agent:terminate` → terminate listeners, run-directory pruning, orphan sweep
+- The work itself lives in focused siblings: `agentLifecycle.js` (spawn/completion), `agentCliSpawning.js` / `agentTuiSpawning.js` (process spawning), `agentModelSelection.js`, `agentPromptBuilder.js`, `agentRunTracking.js`
+
+### Agent Orchestrator (`server/services/agentOrchestrator.js`)
+- The one entry point for an agent LIFECYCLE TRANSITION (pause / kill / terminate / complete / spawn) — read its header before touching the agent cluster
### Memory Service (`server/services/memoryBackend.js`)
- Backend switcher: PostgreSQL + pgvector (`memoryDB.js`) for real installs; the file backend (`memory.js`) is a test-only escape hatch
diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.js
index f8727282e7..443bd486a4 100644
--- a/server/services/agentImportCycles.test.js
+++ b/server/services/agentImportCycles.test.js
@@ -105,6 +105,19 @@ function importsDynamically(file, mod) {
return new RegExp(String.raw`\bimport\s*\(\s*[^)]*\b${mod.replace(/\./g, '\\.')}[^)]*\)`).test(src);
}
+// Loaders for the modules whose REAL export surface the guards below assert on.
+// Spelled out one literal specifier each rather than `import(`./${name}`)` —
+// the bundler cannot analyze a fully-variable specifier and warns, and the point
+// of reading the live key list is that it is ground truth, so it should not
+// depend on runtime path assembly. Every module here is side-effect-free to
+// import (their side effects live behind `init()`/`start()`/`initSpawner()`).
+const MODULE_LOADERS = {
+ 'cos.js': () => import('./cos.js'),
+ 'subAgentSpawner.js': () => import('./subAgentSpawner.js'),
+ 'agentLifecycle.js': () => import('./agentLifecycle.js'),
+};
+const exportedNames = async (mod) => Object.keys(await MODULE_LOADERS[mod]());
+
function findCycles(graph) {
const cycles = new Set();
const stack = [];
@@ -216,25 +229,53 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {
const forbidden = reexportedFrom('agentManagement.js').filter(name => !stateLayer.has(name));
expect(forbidden.length, 'derived nothing to forbid — check the facade export blocks').toBeGreaterThan(0);
- // Then assert against cos.js's REAL export surface, not its source text.
- // Every regex for this was bypassable by a form it did not anticipate — a
- // second re-export statement, a different source module, double quotes,
+ // Then assert against each barrel's REAL export surface, not its source
+ // text. Every regex for this was bypassable by a form it did not anticipate
+ // — a second re-export statement, a different source module, double quotes,
// `export *`, `import` + a bare `export { … }` with no `from` at all. The
- // module's own key list is ground truth and has no syntax to outrun. cos.js
- // imports clean and side-effect-free here (its side effects live behind
- // `init()`/`start()`), which is what makes this affordable.
- const cosExports = Object.keys(await import('./cos.js'));
- expect(cosExports, 'cos.js exports nothing — did the import fail?').not.toEqual([]);
- for (const name of forbidden) {
- expect(cosExports, `cos.js must not re-export ${name} — it is a process-layer transition, ask the facade`)
- .not.toContain(name);
+ // module's own key list is ground truth and has no syntax to outrun.
+ //
+ // `subAgentSpawner.js` joined this loop in #3450. It used to be excluded on
+ // purpose — it re-exported the same three transitions as its back-compat
+ // barrel, so the rule could only be stated for `cos.js`. With that barrel
+ // retired the rule generalizes, which is the point of having retired it.
+ for (const barrel of ['cos.js', 'subAgentSpawner.js']) {
+ const barrelExports = await exportedNames(barrel);
+ expect(barrelExports, `${barrel} exports nothing — did the import fail?`).not.toEqual([]);
+ for (const name of forbidden) {
+ expect(barrelExports, `${barrel} must not re-export ${name} — it is a process-layer transition, ask the facade`)
+ .not.toContain(name);
+ }
}
+ });
- // 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 the cluster orchestrators from re-growing a re-export barrel (#3450)', async () => {
+ // `subAgentSpawner.js` re-exported ~40 symbols from nine siblings, and
+ // `agentLifecycle.js` re-exported the leaves that had been extracted out of
+ // it for that barrel to forward. So "where does finalizeAgent live" had
+ // three answers, and a caller could reach a transition through a module that
+ // merely forwards it. Both surfaces are gone; this keeps them gone.
+ //
+ // Stated as "every export is DECLARED here", which is the only form that
+ // survives contact with the syntax: `export *`, `export { x } from …`, and
+ // `import` + a bare `export { x }` all fail it identically, and so does a
+ // re-export from a module this test has never heard of. The real key list is
+ // ground truth for what is exported; the source scan only answers what is
+ // declared, and if that scan ever misses a legitimate local declaration the
+ // test fails LOUD rather than going green over a live re-export.
+ for (const mod of ['subAgentSpawner.js', 'agentLifecycle.js']) {
+ const src = readFileSync(join(SERVICES_DIR, mod), 'utf-8');
+ const declared = new Set(
+ [...src.matchAll(/^export\s+(?:async\s+)?(?:function\s*\*?|const|let|var|class)\s+([A-Za-z0-9_$]+)/gm)]
+ .map(m => m[1])
+ );
+ const actual = await exportedNames(mod);
+ expect(actual, `${mod} exports nothing — did the import fail?`).not.toEqual([]);
+ const forwarded = actual.filter(name => !declared.has(name)).sort();
+ expect(forwarded,
+ `${mod} must declare what it exports — ${forwarded.join(', ')} is forwarded from another module; import it from the one that defines it`
+ ).toEqual([]);
+ }
});
it('keeps agentState.js an import-free leaf, so agents.js can use the facade (#3450)', () => {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 3f88bc41c5..424746040c 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -16,10 +16,13 @@
* - `agentRunnerSync.js` — syncRunnerAgents (agentManagement, subAgentSpawner)
* - `agentState.js` — the shared in-memory agent maps
*
- * All of them are re-exported below so existing `from './agentLifecycle.js'`
- * imports keep resolving. Do NOT move a function back in here if a spawner or
- * agentManagement calls it — that re-creates the cycle, and
- * `agentImportCycles.test.js` will fail.
+ * This module used to re-export all of them so `from './agentLifecycle.js'`
+ * kept resolving for callers written before the extraction. Those pass-throughs
+ * are gone (#3450): their last consumer was `subAgentSpawner.js`'s back-compat
+ * barrel, and re-exporting a leaf from the orchestrator above it is what made
+ * "where does finalizeAgent live" a three-answer question. Import a leaf from
+ * the leaf. Do NOT move a function back in here if a spawner or agentManagement
+ * calls it — that re-creates the cycle, and `agentImportCycles.test.js` will fail.
*/
import { join } from 'path';
@@ -60,9 +63,8 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
// Extracted helpers — these carve the two giant orchestrators
// (spawnAgentForTask / handleAgentCompletion) into focused, testable modules.
-// The worktree-cleanup cluster and handlePipelineProgression are re-exported
-// below so existing consumers (subAgentSpawner, agentManagement) that import
-// them from agentLifecycle.js keep working.
+// Imported for use here only; the pass-through re-exports that used to sit
+// below them were retired with the `subAgentSpawner.js` barrel (#3450).
import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';
@@ -71,21 +73,6 @@ import { dispatchRecoveredTaskOutputHook, finalizeAgent, stampLiExecutionVerdict
import { extractFinalSummary } from './agentSummaryExtraction.js';
import { handleOrphanedTask } from './agentManagement.js';
-// Re-export the moved functions so existing consumers (subAgentSpawner,
-// agentManagement) keep importing them from agentLifecycle.js. cleanupAgentWorktree
-// is also used internally (passed as cleanupWorktreeFn to the spawn helpers), so it
-// stays imported above; the rest are pure pass-throughs.
-export { cleanupAgentWorktree };
-export { spawnReviewLoopFollowUp, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
-export { handlePipelineProgression } from './agentCompletionCleanup.js';
-// The finalize/summary/runner-sync clusters moved OUT to their own modules to
-// break the static import cycle with the two spawners (issue #2837). Re-exported
-// here so long-standing consumers (subAgentSpawner's barrel, agentManagement,
-// existing tests) keep resolving them from agentLifecycle.js.
-export { dispatchRecoveredTaskOutputHook, dispatchTaskOutputHookOnce, finalizeAgent, releaseAgentLane, evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout, persistSimplifySummaries } from './agentFinalization.js';
-export { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';
-export { syncRunnerAgents } from './agentRunnerSync.js';
-
const ROOT_DIR = PATHS.root;
const AGENTS_DIR = PATHS.cosAgents;
diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.js
index bfdb938328..653d650b60 100644
--- a/server/services/agentOrchestrator.js
+++ b/server/services/agentOrchestrator.js
@@ -3,7 +3,8 @@
*
* ## Why this module exists (#3450)
*
- * Seven modules in the core agent path form one tightly-coupled cluster:
+ * Seven modules in the core agent path formed one tightly-coupled cluster when
+ * this was filed:
*
* cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js
* → agents.js → subAgentSpawner.js → agentLifecycle.js
@@ -14,18 +15,22 @@
* 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.)
+ * looks like; the ones this facade replaced are described further down. The
+ * `agents.js` and `subAgentSpawner.js` hops in that chain are gone — read it as
+ * the shape of the problem, not as today's graph.)
*
* 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 — `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.
+ * `subAgentSpawner.js` calls itself an orchestrator but is not this one: it is
+ * the cluster's EVENT WIRING (runner handlers, `task:ready`, `agent:terminate`),
+ * and it used to re-export ~40 symbols as a back-compat barrel — including three
+ * transitions this facade also owns. That barrel is retired (#3450), along with
+ * the pass-through re-exports `agentLifecycle.js` kept for it, so the two modules
+ * no longer answer the same question two ways. What is left there consumes the
+ * facade rather than duplicating it.
*
* **Invariant, enforced by `agentImportCycles.test.js`: no module reachable
* FROM this one may import it back — statically OR via `import(...)`.** One such
@@ -60,8 +65,8 @@
* `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.
+ * `agentSummaryExtraction`), and the one remaining re-export barrel
+ * (`cosAgents.js`). If it is not exported below, it is a leaf.
*
* ## Moving a caller out (the shape every migration takes)
*
@@ -76,14 +81,21 @@
* ## What is still outstanding
*
* `server/routes/cosAgentRoutes.js`, `agents.js` and `subAgentSpawner.js`'s event
- * wiring are migrated, and the deferred forwarders that used to sit in
+ * wiring are migrated, 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.
+ * their only consumers, and the `subAgentSpawner.js` barrel (plus the
+ * `agentLifecycle.js` pass-throughs whose last consumer it was) is retired.
* `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.
+ *
+ * Remaining: the transitions below that still have callers INSIDE the closure
+ * (all four are `completeAgent`, reached through `cosAgents.js`), and the two
+ * barrels that still expose a partial view of the cluster — `cosAgents.js` and
+ * `cos.js`'s agent re-export block. Note that `agentFinalization.js` and
+ * `agentCliSpawning.js` are LEAVES that call a transition, so "move the caller
+ * out" does not apply to them as written: the closure edge to break is the one
+ * `agentLifecycle.js`/`agentManagement.js` hold INTO them, not an import of
+ * theirs.
*/
// Process/runner layer — owns the live agent maps and the OS-level signals.
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 606a5dfce3..7e6685e71c 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-// --- Mock every dependency subAgentSpawner.js imports ---
+// --- Mock every dependency agentWorktreeCleanup.js pulls in transitively ---
vi.mock('child_process', () => ({
spawn: vi.fn(),
@@ -208,8 +208,10 @@ vi.mock('./runner.js', () => ({
import { join } from 'path';
import { existsSync as existsSyncMock } from 'fs';
-import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';
-import { resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';
+// All five come from `agentWorktreeCleanup.js`, the module that defines them.
+// They used to be pulled through the `subAgentSpawner.js` barrel, which was
+// retired in #3450.
+import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp, resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';
import { getAgent, getAgentRecord, getTaskById, addTask, updateTask } from './cos.js';
import { removeWorktree } from './worktreeManager.js';
import { PATHS } from '../lib/fileUtils.js';
diff --git a/server/services/cos.js b/server/services/cos.js
index 87792d185b..39b19b32c5 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -85,8 +85,8 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
// `evaluateTasks` and the generators emit `task:ready`; the spawn-side
// scheduler (dequeueNextTask / tryImmediateSpawn) below reacts to that. Most of
// these are imported for internal use by the scheduler; checkStagePrecondition
-// and applyAppWorktreeDefault are re-exported for agentLifecycle.js and
-// subAgentSpawner, and evaluateTasks for the cos route + `import * as cos`.
+// is re-exported for agentCompletionCleanup.js, applyAppWorktreeDefault for the
+// suite, and evaluateTasks for the cos route + `import * as cos`.
import {
evaluateTasks,
generateIdleReviewTask,
@@ -219,7 +219,7 @@ export async function start() {
setDaemonRunning(true);
// First clean up orphaned agents (agents marked running but no live process)
- const { cleanupOrphanedAgents } = await import('./subAgentSpawner.js');
+ const { cleanupOrphanedAgents } = await import('./agentManagement.js');
const cleanedAgents = await cleanupOrphanedAgents();
if (cleanedAgents > 0) {
emitLog('info', `Cleaned up ${cleanedAgents} orphaned agent(s)`);
@@ -576,7 +576,7 @@ async function resetOrphanedTasks({ bootRecovery = false } = {}) {
// Route orphaned tasks through handleOrphanedTask for consistent retry counting,
// cooldown enforcement, and max-spawn limits (prevents runaway respawning)
- const { handleOrphanedTask } = await import('./subAgentSpawner.js');
+ const { handleOrphanedTask } = await import('./agentManagement.js');
const processOrphanedTasks = async (tasks) => {
for (const task of tasks) {
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 20c06f56a9..d4d6c0ec2b 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -1,9 +1,26 @@
/**
- * Sub-Agent Spawner Service
+ * Sub-Agent Spawner Service — the agent cluster's EVENT WIRING.
*
- * Orchestrator module: imports from focused sub-modules and re-exports
- * everything for backward compatibility. Owns the explicit `initSpawner()`
- * entry point (event wiring + orphan cleanup) and shared state references.
+ * Owns `initSpawner()`: the CoS Runner connection, the runner event handlers
+ * (`agent:output` / `agent:completed` / `agents:orphaned` / `agent:error`), the
+ * `task:ready` → spawn and `agent:terminate` → terminate listeners, run-directory
+ * pruning, and the delayed orphan sweep. Nothing else.
+ *
+ * ## It is no longer a barrel (#3450)
+ *
+ * Until #3450 this file also re-exported ~40 symbols from nine sibling modules
+ * "for backward compatibility" — a second, partial view of the cluster layered
+ * over `cosAgents.js` and `cos.js`'s agent block, including three process-layer
+ * transitions `agentOrchestrator.js` also owns. Two barrels naming the same
+ * transition is how a caller ends up importing the wrong one and the layering
+ * stops meaning anything. The re-exports are gone; the surviving consumers of
+ * this module import `initSpawner` (`bootstrap.js`) and `loadSlashdoCommand`
+ * (CoS agent prompts), and everything else now imports the module that actually
+ * defines it — or, for a lifecycle transition, `agentOrchestrator.js`.
+ *
+ * That is also why this module can take a static `agentOrchestrator.js` import
+ * while the modules it wires cannot: with the barrel retired, nothing in the
+ * facade's closure imports this file at all.
*
* NOTE: importing this module is side-effect-free — `initSpawner()` must be
* called explicitly (see `server/index.js`). This keeps test imports from
@@ -24,38 +41,15 @@ import { syncRunnerAgents } from './agentRunnerSync.js';
import { handleAgentCompletion } from './agentLifecycle.js';
import { cleanupOrphanedAgents } from './agentManagement.js';
import { completeAgentRun } from './agentRunTracking.js';
+import { runnerAgents, setUseRunner } from './agentState.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.
+// implement them (#3450). It can: nothing the facade imports imports this module
+// back, so the edge stays one-directional.
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';
-import { 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, isTuiProvider, getClaudeSettingsEnv } from './agentCliSpawning.js';
-export { spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './agentLifecycle.js';
-export { syncRunnerAgents } from './agentRunnerSync.js';
-export { extractFinalSummary } from './agentSummaryExtraction.js';
-export { terminateAgent, pauseAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';
-export { processAgentCompletion } from './agentCompletion.js';
-
const RUNS_DIR = PATHS.runs;
-// The runner output batchers moved to their own leaf module (issue #2837) so
-// agentManagement.js can import `flushRunnerOutputBatcher` statically instead of
-// dynamically reaching back through this barrel. Re-exported for consumers that
-// still import it from here.
-export { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
-
-
/**
* Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.
*/
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
index a702f1fcde..e8eeadd054 100644
--- a/server/services/subAgentSpawner.test.js
+++ b/server/services/subAgentSpawner.test.js
@@ -24,11 +24,17 @@ vi.mock('./thinkingLevels.js', async (importOriginal) => {
});
import { describe, it, expect, vi } from 'vitest';
-import { isTruthyMeta, isFalsyMeta, selectModelForTask } from './subAgentSpawner.js';
+import { isTruthyMeta, isFalsyMeta } from './agentState.js';
+import { selectModelForTask } from './agentModelSelection.js';
import { applyAppWorktreeDefault } from './cos.js';
/**
- * Tests for the subAgentSpawner service
+ * Pure decision helpers from the sub-agent spawn path.
+ *
+ * Kept under this name because it is where these cases were written; each import
+ * now names the module that DEFINES the helper. They used to come through
+ * `subAgentSpawner.js`'s back-compat barrel, retired in #3450 — a test reaching
+ * for a re-export is exactly the kind of consumer that kept that barrel alive.
*
* Note: We test the pure functions directly by importing them from production.
* For functions with complex dependencies (process spawning, file system, etc.)
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 9a51d29e87..958d0ed686 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -14,7 +14,7 @@ import { getDomainAutonomyMode } from './cosState.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { approveMemory, rejectMemory, peekMemory } from './memoryBackend.js';
import { ensureDir, PATHS, readJSONFile, formatDuration, atomicWrite } from '../lib/fileUtils.js';
-import { getActiveAgents } from './subAgentSpawner.js';
+import { getActiveAgents } from './agentManagement.js';
import { getGoals } from './identity.js';
const HEALTH_CHECK_INTERVAL_MS = 30_000;
diff --git a/server/services/telegram.test.js b/server/services/telegram.test.js
index b890cb8d3c..e963120030 100644
--- a/server/services/telegram.test.js
+++ b/server/services/telegram.test.js
@@ -104,7 +104,7 @@ vi.mock('../lib/fileUtils.js', () => ({
atomicWrite: vi.fn(async () => {}),
}));
-vi.mock('./subAgentSpawner.js', () => ({ getActiveAgents: vi.fn(() => []) }));
+vi.mock('./agentManagement.js', () => ({ getActiveAgents: vi.fn(() => []) }));
vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => ({ goals: [] })) }));
vi.mock('../lib/uuid.js', () => ({ v4: vi.fn(() => 'test-uuid') }));