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(cos): export init() and call explicitly from server/index.js (#288)

[._.]/ Adam Eivyabdf2db8697c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f86aaa1316..6d427ed0a4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,6 +19,7 @@
## Refactors
+- **CoS — explicit `init()` instead of module-level auto-init.** `server/services/cos.js` previously called `init()` at the bottom of the module, gated by `NODE_ENV !== 'test' && VITEST !== 'true'` so unit tests didn't spin up listeners/timers. The guard was a "test hack in the prod boot path" — `init` is now exported and called explicitly from `server/index.js` alongside `automationScheduler.init()` / `agentActionExecutor.init()` / etc. Test imports of `cos.js` no longer have side effects, and the prod boot path no longer branches on test-env vars.
- **`LoraPicker` extracted** (`client/src/components/imageGen/LoraPicker.jsx`). The LoRA multi-select previously inlined in `ImageGen.jsx` is now a shared component used by both the standalone Image Gen page and the Universe Builder batch-render form.
- **`ImageGenSettingsForm` extended** with `showLoras` + `showStylePreset` props (mounts `LoraPicker` / `StylePresetPicker`) and the previously-hidden CFG / quantize / model-defaults reset.
- **`getStylePresetById` helper** added to `server/lib/writersRoomStylePresets.js` — Map-backed O(1) lookup that replaces the hand-rolled `STYLE_PRESETS.find(...)` pattern.
diff --git a/DONE.md b/DONE.md
index 050434adbd..cb79103bb1 100644
--- a/DONE.md
+++ b/DONE.md
@@ -8,6 +8,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
## 2026-05
+- **CoS — explicit `init()` instead of module-level auto-init.** Dropped the `NODE_ENV !== 'test' && VITEST !== 'true'` guard from `server/services/cos.js`; `init` is now exported and called from `server/index.js` alongside the other startup `*.init()` calls. Test imports no longer spin up event listeners / timers as a side effect, and the prod boot path no longer branches on test-env vars.
- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."
- **Importer — section follow-ups landed.** Auto-detect content type stage (`importer-classify`, light-tier head pass that pre-selects the radio); in-place `proseExcerpt` edit affordance per issue card so users can trim/correct boundaries without re-running Analyze (3 heavy-tier calls); `replaceMode` flag wipes existing issues + overwrites arc/seasons on re-import (destructive opt-in for existing series); partial-commit retry now drops arc/seasons/canon from the retry payload via `arcAlreadyPersisted` context so a parallel-tab edit isn't overwritten; React.memo on per-issue and per-season cards (with stable patcher + memoized seasonOptions) so unedited cards skip render on keystroke; `ARC_SHAPE_IDS` exposed via `/importer/config` and `IMPORTER_ARC_ROLES_FALLBACK` retired from the client (server is now the sole source of arc roles + shape ids); screenplay-prompt split logic gates on `isUserRequestedCount` rather than conflating it with the per-type default; "(first season)" UI label replaced with the actual lowest-numbered season + title.
- **Sharing — auto-unsubscribe on local record delete.** `recordEvents.js` now hooks `deleteSeries` / `deleteUniverse` so orphaned `data/sharing/subscriptions.json` entries clean up automatically instead of logging errors on the next re-export attempt.
diff --git a/PLAN.md b/PLAN.md
index 751e13edc7..ad4ebc30c9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -139,7 +139,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Better-audit residue
-- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).
+- [x] ~~**[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).~~ **Shipped 2026-05-17** — `init()` is now exported and called explicitly from `server/index.js` (alongside the other `*.init()` calls); module-level auto-init removed entirely so the test guard is no longer needed.
- [ ] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.
- [ ] **[HIGH][TESTS]** Add coverage for `server/services/shell.js` and `server/services/feeds.js` — both have exported functions but no sibling test. Shell drives all terminal sessions; feeds manages subscriptions. (New — surfaced 2026-05-16 replan.)
- [ ] **[MEDIUM][CLIENT]** 4 components still redefine `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally: `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, `MortalLoomTab.jsx`, `ImportTab.jsx`.
diff --git a/server/index.js b/server/index.js
index 4ff826a1d8..2fac518013 100644
--- a/server/index.js
+++ b/server/index.js
@@ -119,6 +119,7 @@ import { errorEvents } from './lib/errorHandler.js';
import './services/subAgentSpawner.js'; // Initialize CoS agent spawner
import * as automationScheduler from './services/automationScheduler.js';
import * as agentActionExecutor from './services/agentActionExecutor.js';
+import * as cos from './services/cos.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import * as telegram from './services/telegram.js';
import * as telegramBridge from './services/telegramBridge.js';
@@ -409,6 +410,10 @@ app.use('/api/ask', askRoutes);
// data/ exists and the worker loop is running before /api/video-gen or
// /api/image-gen can enqueue (otherwise persist() can race with ensureDir).
+// Explicit call (not a module-level side effect) so test imports of cos.js
+// don't spin up its event listeners and timers.
+cos.init().catch(err => console.error(`❌ CoS init failed: ${err.message}`));
+
// Initialize agent automation scheduler and action executor
automationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));
// agentActionExecutor.init() is synchronous — guard with try/catch so a thrown
@@ -583,8 +588,8 @@ ensureSelf()
// orchestrator so projects don't sit frozen waiting for listeners that
// no longer exist. Doesn't block startup.
// recoverInFlightProjects resolves cdRecoveryDone on success. On any
- // failure path here, explicitly resolve it so cos.init's gate doesn't
- // hit the 5s timeout fallback for nothing.
+ // failure path here, explicitly resolve it so cos.start's gate doesn't
+ // hit the 60s timeout fallback for nothing.
recoverInFlightProjects().catch(async (e) => {
console.log(`⚠️ CD boot recovery failed: ${e.message}`);
const { markRecoveryDone } = await import('./services/creativeDirector/recovery.js');
diff --git a/server/services/cos.js b/server/services/cos.js
index 716aaaef35..72d770a8da 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -3031,9 +3031,10 @@ async function scheduleNextImprovementCheck() {
}
/**
- * Initialize on module load
+ * Wire event listeners, load state, and auto-start the daemon when configured.
+ * Called once from `server/index.js` during boot.
*/
-async function init() {
+export async function init() {
await ensureDirectories();
// When an agent completes, immediately try to dequeue the next pending task
@@ -3137,9 +3138,3 @@ async function init() {
}
}
-// Initialize asynchronously — vitest sets NODE_ENV=test by default, so this
-// skips eager init (and its listeners/timers) in unit tests and avoids
-// circular-import side effects.
-if (process.env.NODE_ENV !== 'test' && process.env.VITEST !== 'true') {
- init();
-}
diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.js
index e2df830a36..fa19dbb300 100644
--- a/server/services/creativeDirector/recovery.js
+++ b/server/services/creativeDirector/recovery.js
@@ -29,14 +29,15 @@ import { listProjects, updateScene, updateRun, updateProject } from './local.js'
import { listJobs, cancelJob } from '../mediaJobQueue/index.js';
import { updateTask } from '../cos.js';
-// Boot-time coordination: cos.js eagerly calls resetOrphanedTasks() during
-// module import, which would respawn stale CD treatment/evaluate tasks
-// BEFORE recoverInFlightProjects() has had a chance to retire them via
-// updateTask. Two concurrent agents would then race on the same project.
-// Expose a promise that cos.init() awaits before its first
-// resetOrphanedTasks call, so the order is always:
+// Boot-time coordination: cos.start() (entered from cos.init() when
+// alwaysOn/autoStart is configured) calls resetOrphanedTasks(), which
+// would respawn stale CD treatment/evaluate tasks BEFORE
+// recoverInFlightProjects() has had a chance to retire them via updateTask.
+// Two concurrent agents would then race on the same project. Expose a
+// promise that cos.start() awaits before its resetOrphanedTasks call,
+// so the order is always:
// 1. recoverInFlightProjects retires stale CD tasks (status='completed').
-// 2. cos.resetOrphanedTasks runs and finds nothing CD-related to respawn.
+// 2. resetOrphanedTasks runs and finds nothing CD-related to respawn.
let resolveRecoveryDone;
export const cdRecoveryDone = new Promise((resolve) => {
resolveRecoveryDone = resolve;
@@ -66,8 +67,8 @@ export async function recoverInFlightProjects() {
(p) => RECOVERABLE_STATUSES.has(p.status) || CLEANUP_ONLY_STATUSES.has(p.status),
);
if (!needsCleanup.length) {
- // Must resolve the gate even on the no-op path or cos.init's
- // resetOrphanedTasks await would sit on its 5s timeout for nothing
+ // Must resolve the gate even on the no-op path or cos.start's
+ // resetOrphanedTasks await would sit on its 60s timeout for nothing
// every daemon start/auto-start.
resolveRecoveryDone();
return { resumed: 0 };