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([subagent-spawner-top-level-side-effects]): init spawner explicitly instead of on module load

[._.]/ Adam Eivy5abc119f31ef
diff --git a/server/index.js b/server/index.js
index 6fa760f1d1..3edce6bb6d 100644
--- a/server/index.js
+++ b/server/index.js
@@ -130,7 +130,7 @@ import { setHttpsEnabledAtBoot } from './lib/httpsState.js';
import { initTaskLearning } from './services/taskLearning.js';
import { recordSession, recordMessages } from './services/usage.js';
import { errorEvents } from './lib/errorHandler.js';
-import './services/subAgentSpawner.js'; // Initialize CoS agent spawner
+import { initSpawner } from './services/subAgentSpawner.js';
import * as automationScheduler from './services/automationScheduler.js';
import * as agentActionExecutor from './services/agentActionExecutor.js';
import * as cos from './services/cos.js';
@@ -347,6 +347,13 @@ initAutoFixer();
// Initialize task learning system to track agent completions
initTaskLearning();
+// Initialize the CoS agent spawner (event wiring + orphan cleanup) explicitly,
+// now that the runner patch + task learning are ready. Fire-and-forget: the
+// spawner sets up its own listeners and recovers in-flight agents in the background.
+initSpawner().catch(err => {
+ console.error(`❌ Failed to initialize spawner: ${err.message}`);
+});
+
// Middleware - allow any origin for Tailscale access
app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', req.headers.origin || '*');
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 6b979def9a..41ec8b5b44 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -2,8 +2,12 @@
* Sub-Agent Spawner Service
*
* Orchestrator module: imports from focused sub-modules and re-exports
- * everything for backward compatibility. Keeps module-level initialization
- * (initSpawner, event wiring) and shared state references.
+ * everything for backward compatibility. Owns the explicit `initSpawner()`
+ * entry point (event wiring + orphan cleanup) and shared state references.
+ *
+ * NOTE: importing this module is side-effect-free — `initSpawner()` must be
+ * called explicitly (see `server/index.js`). This keeps test imports from
+ * re-arming the event listeners and timers on every suite.
*/
import { join } from 'path';
@@ -100,10 +104,8 @@ export async function initSpawner() {
setUseRunner(runnerAvailable);
// Lazy-import lifecycle functions (avoids circular dep at module init time)
- const { syncRunnerAgents, handleAgentCompletion, cleanupAgentWorktree } = await import('./agentLifecycle.js');
- const { cleanupOrphanedAgents, handleOrphanedTask } = await import('./agentManagement.js');
- const { spawnAgentForTask } = await import('./agentLifecycle.js');
- const { terminateAgent } = await import('./agentManagement.js');
+ const { syncRunnerAgents, handleAgentCompletion, spawnAgentForTask } = await import('./agentLifecycle.js');
+ const { cleanupOrphanedAgents, terminateAgent } = await import('./agentManagement.js');
const { completeAgentRun } = await import('./agentRunTracking.js');
if (runnerAvailable) {
@@ -198,23 +200,12 @@ export async function initSpawner() {
cosEvents.on('agent:terminate', async (agentId) => {
await terminateAgent(agentId);
});
-}
-// Initialize spawner when module loads (async)
-initSpawner().catch(err => {
- console.error(`❌ Failed to initialize spawner: ${err.message}`);
-});
-
-// Initialize task learning system
-import('./taskLearning.js').then(taskLearning => {
- taskLearning.initTaskLearning();
-}).catch(err => {
- console.error(`❌ Failed to initialize task learning: ${err.message}`);
-});
-
-// Clean up orphaned agents after a short delay (let other services init first)
-import('./agentManagement.js').then(({ cleanupOrphanedAgents }) => {
- setTimeout(cleanupOrphanedAgents, 2000);
-}).catch(err => {
- console.error(`❌ Failed to schedule orphan cleanup: ${err.message}`);
-});
+ // Clean up orphaned agents after a short delay (let other services finish init).
+ // setTimeout runs outside the request lifecycle, so guard the async callback.
+ setTimeout(() => {
+ cleanupOrphanedAgents().catch(err => {
+ console.error(`❌ Failed to clean up orphaned agents: ${err.message}`);
+ });
+ }, 2000);
+}