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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: retire the cosAgents.js barrel so each agent function has one address (#3450)
[._.]/ Adam Eivy6b5db17824f6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9f9fc7fcc9..3fb6bda968 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **The `cosAgents.js` barrel is gone, so an agent function no longer arrives from a specifier that says nothing about which layer it lives in.** The #2530 decomposition split a ~1090-line module into four focused siblings — `cosAgentIndex.js` (date-bucket index + on-disk archive layout), `cosAgentLifecycle.js` (register / update / complete / output / terminate), `cosAgentFeedback.js` (capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — then put an `export *` wall back in front of all four so no import path had to change. Three years of imports later, `updateAgent` and `getAgentsByDate` came from the same specifier despite sitting in different layers, and the wall is what made `cos.js` a *two*-hop forwarder of a lifecycle transition, which is the shape #3450's guard exists to delete. All ~20 production importers and ~14 `vi.mock` targets now name the module that declares what they asked for — several of which turn out to want only the index (`cosReports.js`, the peer cos-history merge) or only the lifecycle layer (the runner sync, the TUI output spooler, the completion cleanup), so the graph gets narrower as well as flatter. The four leaf modules are unchanged; the two test files that only ever exercised one of them are renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`). The forwarder guard in `agentImportCycles.test.js` — which walks re-export edges rather than naming barrels, so a new one is covered the day it is written — now asserts `cos.js` is the *only* module forwarding a transition, and was bypass-probed both ways: planting a fresh `export *` barrel turns it red, and so does routing a production import of `completeAgent` back through `cos.js`. Its two module-loading assertions also take an explicit timeout: they transform `cos.js`'s whole service graph, which lands at 5–10s and straddles Vitest's 10s default, so the guard was one busy machine away from failing for a reason that had nothing to do with the invariant (#3450).+- **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).diff --git a/client/public/flows.json b/client/public/flows.jsonindex 459aa00015..0bd3495053 100644--- a/client/public/flows.json+++ b/client/public/flows.json@@ -58,7 +58,7 @@{ "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": "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.cosAgentLifecycle", "label": "cosAgentLifecycle", "group": "server-services", "file": "server/services/cosAgentLifecycle.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." },{ "id": "svc.shell", "label": "shell", "group": "server-services", "file": "server/services/shell.js", "desc": "PTY session manager: spawn, single-subscriber attach, safe env allowlist." },{ "id": "svc.backup", "label": "backup", "group": "server-services", "file": "server/services/backup.js", "desc": "rsync snapshots + pg_dump + manifest; effective-exclude computation." },@@ -157,9 +157,9 @@{ "from": "svc.cosRunnerClient", "to": "ext.cosRunner", "transport": "socket", "label": "spawn request", "payload": "Socket.IO + HTTP to portos-cos on PORTS.COS" },{ "from": "ext.cosRunner", "to": "ext.aiCli", "transport": "spawn", "label": "run agent CLI", "payload": "claude/codex spawned in the task's worktree with the prompt" },{ "from": "ext.cosRunner", "to": "svc.cosRunnerClient", "transport": "socket", "label": "output stream", "payload": "parsed agent output lines + completion status" },- { "from": "svc.cosRunnerClient", "to": "svc.cosAgents", "transport": "call", "label": "record output", "payload": "batched output lines + lifecycle updates" },- { "from": "svc.cosAgents", "to": "store.jsonFiles", "transport": "storage", "label": "persist agent index", "payload": "date-bucketed agent state JSON" },- { "from": "svc.cosAgents", "to": "page.chiefOfStaff", "transport": "socket", "label": "agent:output / agent:completed", "payload": "live output lines and final summary rendered in the UI" }+ { "from": "svc.cosRunnerClient", "to": "svc.cosAgentLifecycle", "transport": "call", "label": "record output", "payload": "batched output lines + lifecycle updates" },+ { "from": "svc.cosAgentLifecycle", "to": "store.jsonFiles", "transport": "storage", "label": "persist agent index", "payload": "date-bucketed agent state JSON" },+ { "from": "svc.cosAgentLifecycle", "to": "page.chiefOfStaff", "transport": "socket", "label": "agent:output / agent:completed", "payload": "live output lines and final summary rendered in the UI" }]},{diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex 860554855e..1c5ce3ada0 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -9,7 +9,7 @@ These apply to Express/service/model code. Universal constraints (no try/catch o## Write serialization and throughput- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.-- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.+- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgentLifecycle.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.## Tests and peer fan-outdiff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex ddd276157d..d98cb43b8c 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -327,7 +327,7 @@ export const COS_ARCHIVE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;// agentIds are `agent-<id>` — alphanumerics, `_` and `-` only. NO dots, so a// `..` traversal can't form, and NO slash. Capped well above any real id.export const COS_AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;-// The exact set of files an archive holds (cosAgents.js). A fixed enum is the+// The exact set of files an archive holds (cosAgentIndex.js). A fixed enum is the// tightest possible filename allowlist.export const COS_ARCHIVE_FILES = Object.freeze(['metadata.json', 'output.txt', 'prompt.txt']);const peerCosHistoryManifestEntrySchema = z.object({diff --git a/server/routes/git.js b/server/routes/git.jsindex 8f3140e3cb..2dba715104 100644--- a/server/routes/git.js+++ b/server/routes/git.js@@ -3,7 +3,7 @@ import { existsSync, statSync, realpathSync } from 'fs';import { resolve } from 'path';import * as git from '../services/git.js';import * as appsService from '../services/apps.js';-import { getAgents } from '../services/cosAgents.js';+import { getAgents } from '../services/cosAgentLifecycle.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';diff --git a/server/routes/git.test.js b/server/routes/git.test.jsindex e942b39774..259916dd97 100644--- a/server/routes/git.test.js+++ b/server/routes/git.test.js@@ -36,7 +36,7 @@ vi.mock('../services/apps.js', () => ({getAppById: vi.fn()}));-vi.mock('../services/cosAgents.js', () => ({+vi.mock('../services/cosAgentLifecycle.js', () => ({getAgents: vi.fn().mockResolvedValue([])}));@@ -59,7 +59,7 @@ vi.mock('fs', async (importOriginal) => {import { existsSync, statSync, realpathSync } from 'fs';import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';-import * as cosAgentsService from '../services/cosAgents.js';+import * as cosAgentLifecycleService from '../services/cosAgentLifecycle.js';import * as gitService from '../services/git.js';function makeApp() {@@ -167,7 +167,7 @@ describe('git routes — active agent branch exclusion', () => {describe('POST /api/git/cleanup-merged — active agent branches are passed to service', () => {it('passes the active agent worktreeBranch as an excludeBranches Set to deleteMergedBranches', async () => {- cosAgentsService.getAgents.mockResolvedValue([+ cosAgentLifecycleService.getAgents.mockResolvedValue([{ status: 'running', metadata: { worktreeBranch: 'feature/agent-work' } },{ status: 'stopped', metadata: { worktreeBranch: 'feature/done-work' } },]);@@ -193,7 +193,7 @@ describe('git routes — active agent branch exclusion', () => {});it('passes an empty Set when no agents are running', async () => {- cosAgentsService.getAgents.mockResolvedValue([]);+ cosAgentLifecycleService.getAgents.mockResolvedValue([]);gitService.deleteMergedBranches.mockResolvedValue({ deleted: [] });const app = makeApp();@@ -206,7 +206,7 @@ describe('git routes — active agent branch exclusion', () => {});it('still passes an empty Set when getAgents rejects (catch guard)', async () => {- cosAgentsService.getAgents.mockRejectedValue(new Error('service down'));+ cosAgentLifecycleService.getAgents.mockRejectedValue(new Error('service down'));gitService.deleteMergedBranches.mockResolvedValue({ deleted: [] });const app = makeApp();@@ -223,7 +223,7 @@ describe('git routes — active agent branch exclusion', () => {describe('POST /api/git/delete-branch — active agent branches are excluded', () => {it('passes the active agent branches as excludeBranches to deleteBranch', async () => {- cosAgentsService.getAgents.mockResolvedValue([+ cosAgentLifecycleService.getAgents.mockResolvedValue([{ status: 'running', metadata: { worktreeBranch: 'feature/agent-active' } },]);gitService.deleteBranch.mockResolvedValue({ branch: 'feature/other', results: { local: 'deleted' } });@@ -268,7 +268,7 @@ describe('git routes — active agent branch exclusion', () => {});it('service error propagates as 500', async () => {- cosAgentsService.getAgents.mockResolvedValue([]);+ cosAgentLifecycleService.getAgents.mockResolvedValue([]);gitService.deleteBranch.mockRejectedValue(Object.assign(new Error('Cannot delete branch in active use by an agent: feature/agent-active'), { status: 500 }));diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex f016bf9173..4016c6b11b 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -11,7 +11,7 @@ import { existsSync } from 'fs';import { spawn } from 'child_process';import { homedir } from 'os';import { cosEvents, emitLog } from './cosEvents.js';-// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// The DEFINING module, not a barrel (#3450) — see the note in// `agentManagement.js`. This module is a LEAF that `agentLifecycle.js` imports,// which puts it inside the facade's closure, so the facade is out of reach here.import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgentLifecycle.js';diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex cbda12e97d..fb7d8c4138 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -9,7 +9,7 @@ vi.mock('./cosAgentLifecycle.js', () => {// Faithful stand-in for the real debounced batcher: accumulates pushed lines// and, on flush(), routes them through the mocked appendAgentOutputLines while// swallowing+logging failures (mirrors the real createAgentOutputBatcher in- // cosAgentLifecycle.js — whose error handling is unit-tested in cosAgents.test.js).+ // cosAgentLifecycle.js — whose error handling is unit-tested in cosAgentLifecycle.test.js).const createAgentOutputBatcher = vi.fn((agentId) => {let pending = [];return {diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.jsindex d87fbf6416..1160acc1b0 100644--- a/server/services/agentCompletion.js+++ b/server/services/agentCompletion.js@@ -5,7 +5,7 @@* and direct mode (spawnDirectly): memory extraction and app cooldown.*/-import { updateAgent } from './cosAgents.js';+import { updateAgent } from './cosAgentLifecycle.js';import { getConfig } from './cos.js';import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';import { emitLog } from './cosEvents.js';diff --git a/server/services/agentCompletion.test.js b/server/services/agentCompletion.test.jsindex 0496f026e6..e12c14c220 100644--- a/server/services/agentCompletion.test.js+++ b/server/services/agentCompletion.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';// Mock dependencies before importing the module under test-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({updateAgent: vi.fn().mockResolvedValue(undefined)}));vi.mock('./cos.js', () => ({diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 2d399fe9f4..31a1dc8d40 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -19,7 +19,7 @@import { join, relative, resolve, sep } from 'path';import { unlink, rm } from 'fs/promises';import { emitLog } from './cosEvents.js';-import { updateAgent } from './cosAgents.js';+import { updateAgent } from './cosAgentLifecycle.js';import { updateTask, addTask, reviveBlockedTask, checkStagePrecondition } from './cos.js';import { PIPELINE_BEHAVIOR_FLAGS, normalizeReviewers } from '../lib/validation.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 40e6aac084..937cd6971e 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -11,7 +11,7 @@import { describe, it, expect, beforeEach, vi } from 'vitest';vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));-vi.mock('./cosAgents.js', () => ({ updateAgent: vi.fn() }));+vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn() }));vi.mock('./cos.js', () => ({updateTask: vi.fn().mockResolvedValue({}),addTask: vi.fn().mockResolvedValue({}),diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex c9eb3bca7e..29cf13b0e5 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -20,7 +20,7 @@import { join } from 'path';import { execGit } from '../lib/execGit.js';import { emitLog } from './cosEvents.js';-// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// The DEFINING module, not a barrel (#3450) — see the note in// `agentManagement.js`. This module is a LEAF that both transition modules// import, which puts it inside the facade's closure, so the facade is out of// reach here.diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex e8051cd84a..f1e7f90b93 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -2,7 +2,7 @@* Regression guard for the agent-lifecycle circular-dependency cluster (#2837).** The cluster — agentLifecycle / agentCliSpawning / agentTuiSpawning /- * agentManagement / subAgentSpawner / cosAgents — used to contain two real+ * agentManagement / subAgentSpawner / cosAgentLifecycle — used to contain two real* STATIC cycles plus three `await import(...)` workarounds whose only job was to* dodge the load-time cycle. Both were fixed by extracting the shared pieces* (finalize, summary extraction, runner sync, runner output batchers) into leaf@@ -33,7 +33,6 @@ const CLUSTER = ['agentTuiSpawning.js','agentManagement.js','subAgentSpawner.js',- 'cosAgents.js','cosAgentLifecycle.js','agentFinalization.js','agentSummaryExtraction.js',@@ -52,7 +51,7 @@ const CLUSTER = [// 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),+// (`agentTuiSpawning/outputSpooler.js` → `../cosAgentLifecycle.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 = [];@@ -144,6 +143,13 @@ const MODULE_LOADERS = {};const exportedNames = async (mod) => Object.keys(await MODULE_LOADERS[mod]());+// Whichever assertion loads first pays for transforming `cos.js`'s whole service+// graph — measured at 5–10s here depending on machine load, i.e. straddling the+// 10s default, which turns a green guard into an intermittent red one that says+// nothing about the invariant. Every `it()` below that calls `exportedNames`+// carries this, not just the one that happens to run first today.+const MODULE_LOAD_TIMEOUT_MS = 60_000;+function findCycles(graph) {const cycles = new Set();const stack = [];@@ -262,7 +268,7 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {.not.toContain(name);}}- });+ }, MODULE_LOAD_TIMEOUT_MS);it('keeps the cluster orchestrators from re-growing a re-export barrel (#3450)', async () => {// `subAgentSpawner.js` re-exported ~40 symbols from nine siblings, and@@ -291,7 +297,7 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {`${mod} must declare what it exports — ${forwarded.join(', ')} is forwarded from another module; import it from the one that defines it`).toEqual([]);}- });+ }, MODULE_LOAD_TIMEOUT_MS);it('makes every transition caller name the facade or the defining module, never a barrel (#3450)', () => {// Step 3 of the #3450 sequencing, for the callers the "move the caller out"@@ -332,12 +338,13 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {.toContain('requestAgentTermination');// A FORWARDER is any module that re-exports its way to a declaring module, at- // any depth: `cosAgents.js` is one hop (`export * from './cosAgentLifecycle.js'`),- // `cos.js` is two (`export { … } from './cosAgents.js'`). Walking the- // re-export edges instead of listing the barrels means a NEW barrel is- // covered the day it is written, and the two this issue has yet to collapse- // need no naming here. Asserted rather than merely computed, so collapsing- // one has to come here and say so.+ // any depth: `cos.js` is one hop (`export { … } from './cosAgentLifecycle.js'`).+ // It used to be two, through the `cosAgents.js` barrel that sat between them;+ // that barrel is retired (#3450), leaving `cos.js`'s agent re-export block as+ // the last forwarder. Walking the re-export edges instead of listing the+ // barrels means a NEW barrel is covered the day it is written. Asserted+ // rather than merely computed, so collapsing this last one has to come here+ // and say so.const reexportEdges = (file) => [...readFileSync(join(SERVICES_DIR, file), 'utf-8').matchAll(/export\s*(?:\*|\{[^}]*\})\s*(?:as\s+\w+\s*)?from\s*['"]([^'"]+)['"]/g)@@ -358,7 +365,7 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {}}expect([...forwarders].sort(), 'the set of barrels still forwarding a transition changed — intended?')- .toEqual(['cos.js', 'cosAgents.js']);+ .toEqual(['cos.js']);// Production sources only. A test mirrors whatever its subject imports (a// mock pointed at a module the subject no longer imports silently stopsdiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex fbe6a664b9..821f0c2b4a 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -29,7 +29,7 @@ import { join } from 'path';import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { cosEvents, emitLog } from './cosEvents.js';-// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// The DEFINING module, not a barrel (#3450) — see the note in// `agentManagement.js`. This module owns the `spawnAgentForTask` transition the// facade re-exports, so it is permanently inside the facade's closure and must// name `completeAgent`'s home directly.diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 9a8a468a04..9fd4ee8cd5 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -8,7 +8,7 @@import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';import { emitLog } from './cosEvents.js';-// The DEFINING module, not the `cosAgents.js` barrel (#3450). This module is one+// The DEFINING module, not a barrel (#3450). This module is one// of the three `agentOrchestrator.js` imports, so it can never reach a transition// through the facade — an import back from here closes the loop the facade exists// to open. Inside the closure the single address for a transition is the modulediff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 624c778799..4f1220b250 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -59,7 +59,7 @@ vi.mock('./agentRunTracking.js', () => ({}));// Stub other transitive imports we don't exercise in handleOrphanedTask.-// The DEFINING module, not the `cosAgents.js` barrel — mirrors the production+// The DEFINING module, not the `cosAgentLifecycle.js` module — mirrors the production// import (#3450). Mocking the barrel here would silently stop applying and let// the real state layer load.vi.mock('./cosAgentLifecycle.js', () => ({diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.jsindex 10ee609f50..b922105b72 100644--- a/server/services/agentOrchestrator.js+++ b/server/services/agentOrchestrator.js@@ -9,6 +9,9 @@* cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js* → agents.js → subAgentSpawner.js → agentLifecycle.js*+ * (`cosAgents.js` no longer exists — it was the back-compat barrel between+ * `cos.js` and the four modules the #2530 split produced, and #3450 retired it.)+ ** with several edges reaching back up the chain. There is no correctness bug —* the load-bearing back-edges were broken with `await import(...)` before this* module existed, and `agentImportCycles.test.js` derives the live static graph@@ -65,8 +68,7 @@* `bufferedSpawn.killProcessTree`), runner RPC (`cosRunnerClient`), the task store* (`cos.js` task functions), post-run work (`agentWorktreeCleanup`,* `agentFinalization`, `agentRunTracking`, `agentCompletionCleanup`,- * `agentSummaryExtraction`), and the one remaining re-export barrel- * (`cosAgents.js`). If it is not exported below, it is a leaf.+ * `agentSummaryExtraction`). If it is not exported below, it is a leaf.** ## Moving a caller out (the shape every migration takes)*@@ -113,9 +115,18 @@* and `getAgents` through the `cos.js` re-export block for no cycle-breaking* benefit, since that module is a static import here — is gone with it.*- * Remaining: the two barrels that still expose a partial view of the cluster —- * `cosAgents.js` and `cos.js`'s agent re-export block. Both are wide surfaces- * (30+ importers, many `vi.mock`ed) and each wants its own PR.+ * The `cosAgents.js` barrel is retired too. It re-exported all four modules the+ * #2530 split produced (`cosAgentIndex`, `cosAgentLifecycle`, `cosAgentFeedback`,+ * `cosAgentArchive`) behind one `export *` wall, so `updateAgent` and+ * `getAgentsByDate` arrived from the same specifier despite living in different+ * layers — and the barrel is what made `cos.js` a TWO-hop forwarder of a+ * transition. Every importer now names the declaring module; the four leaves are+ * unchanged, and the two test files that only ever exercised one of them are+ * renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`).+ *+ * Remaining: `cos.js`'s agent re-export block (`export { … } from` the four+ * modules above, ~20 names) is the last partial view of the cluster. It is a+ * wide surface with many `vi.mock`ed importers and wants its own PR.*/// Process/runner layer — owns the live agent maps and the OS-level signals.diff --git a/server/services/agentRunnerOutputBatchers.js b/server/services/agentRunnerOutputBatchers.jsindex 6f5dbe7da5..ddda1ff64b 100644--- a/server/services/agentRunnerOutputBatchers.js+++ b/server/services/agentRunnerOutputBatchers.js@@ -10,10 +10,10 @@* import `flushRunnerOutputBatcher` statically. It previously reached for it via* `await import('./subAgentSpawner.js')` purely to dodge a cycle — the spawner* barrel re-exports agentManagement. Leaf module: only depends on the state- * layer (`cosAgents.js`).+ * layer (`cosAgentLifecycle.js`).*/-import { createAgentOutputBatcher } from './cosAgents.js';+import { createAgentOutputBatcher } from './cosAgentLifecycle.js';const runnerOutputBatchers = new Map();diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex 1ce42c44e5..6311998e1a 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -14,7 +14,7 @@import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isAgentOwnedLocally, runnerAgents } from './agentState.js';-import { getAgent } from './cosAgents.js';+import { getAgent } from './cosAgentLifecycle.js';import * as shellService from './shell.js';/**diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.jsindex f9cf35788c..d7f2697dc9 100644--- a/server/services/agentRunnerSync.test.js+++ b/server/services/agentRunnerSync.test.js@@ -30,13 +30,13 @@ vi.mock('./cos.js', () => ({}),}));-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgent: vi.fn(),}));import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';-import { getAgent } from './cosAgents.js';+import { getAgent } from './cosAgentLifecycle.js';import { activeAgents, runnerAgents } from './agentState.js';import { syncRunnerAgents } from './agentRunnerSync.js';diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 50a239126c..084907f0ec 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -11,7 +11,7 @@ import { existsSync } from 'fs';import { readFile, rm } from 'fs/promises';import * as shellService from './shell.js';import { emitLog } from './cosEvents.js';-import { updateAgent } from './cosAgents.js';+import { updateAgent } from './cosAgentLifecycle.js';import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';import { captureWorktreeDiff, worktreeHasChanges, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 0cac1068b3..c2952c1db7 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -22,7 +22,7 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn()}));-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({appendAgentOutputLines: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined)@@ -194,7 +194,7 @@ import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentFinalization.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';-import * as cosAgents from './cosAgents.js';+import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';import { activeAgents, userTerminatedAgents } from './agentState.js';import { MAX_RUNTIME_WRAP_UP_GRACE_MS } from '../lib/tuiHandshake.js';@@ -1819,7 +1819,7 @@ describe('spawnTuiAgent runtime', () => {);expect(inMemTruncWarns).toHaveLength(0);- const inMemTruncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(+ const inMemTruncMetaCalls = vi.mocked(cosAgentLifecycle.updateAgent).mock.calls.filter(([_id, payload]) => payload?.metadata?.rawBufferTruncated === true);expect(inMemTruncMetaCalls).toHaveLength(0);@@ -1846,7 +1846,7 @@ describe('spawnTuiAgent runtime', () => {);expect(truncWarns).toHaveLength(1);- const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(+ const truncMetaCalls = vi.mocked(cosAgentLifecycle.updateAgent).mock.calls.filter(([_id, payload]) => payload?.metadata?.outputBufferTruncated === true);expect(truncMetaCalls).toHaveLength(1);@@ -1931,7 +1931,7 @@ describe('spawnTuiAgent runtime', () => {);expect(truncWarns).toHaveLength(1);- const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(+ const truncMetaCalls = vi.mocked(cosAgentLifecycle.updateAgent).mock.calls.filter(([_id, payload]) => payload?.metadata?.rawSpoolTruncated === true);expect(truncMetaCalls).toHaveLength(1);@@ -2016,7 +2016,7 @@ describe('spawnTuiAgent runtime', () => {// in-state output stream (live view / fallback). Both must carry the// sentinel resolution — assert on the persistence paths, not outputBuffer,// since the test mocks OUTPUT_BUFFER_CAP down to 1 byte.- const flushedLines = vi.mocked(cosAgents.appendAgentOutputLines).mock.calls+ const flushedLines = vi.mocked(cosAgentLifecycle.appendAgentOutputLines).mock.calls.flatMap(([, lines]) => lines);expect(flushedLines).toContain('✅ Agent signaled completion');expect(flushedLines.some(l => l.includes('Implemented the fix.'))).toBe(true);@@ -2056,7 +2056,7 @@ describe('spawnTuiAgent runtime', () => {expect(cleanupWorktreeFn).not.toHaveBeenCalled();// The record stays `running`; only the phase label is refined, so boot// recovery still sees it as an agent to reconcile from the marker.- expect(vi.mocked(cosAgents.updateAgent).mock.calls.some(+ expect(vi.mocked(cosAgentLifecycle.updateAgent).mock.calls.some(([, patch]) => patch?.metadata?.phase === 'interrupted' && patch?.metadata?.interruptedBy === 'host-shutdown')).toBe(true);});diff --git a/server/services/agentTuiSpawning/outputSpooler.js b/server/services/agentTuiSpawning/outputSpooler.jsindex 6186588cc9..db965a571f 100644--- a/server/services/agentTuiSpawning/outputSpooler.js+++ b/server/services/agentTuiSpawning/outputSpooler.js@@ -17,7 +17,7 @@*/import { appendFile, writeFile } from 'fs/promises';-import { appendAgentOutputLines, updateAgent } from '../cosAgents.js';+import { appendAgentOutputLines, updateAgent } from '../cosAgentLifecycle.js';import { OUTPUT_BUFFER_CAP, OUTPUT_BUFFER_HEADROOM, RAW_SPOOL_MAX_BYTES } from '../../lib/tuiHandshake.js';// Debounce window for batching parsed output AND raw chunks to disk + state.diff --git a/server/services/agentTuiSpawning/outputSpooler.test.js b/server/services/agentTuiSpawning/outputSpooler.test.jsindex 9b5332c4df..6f289b0b9e 100644--- a/server/services/agentTuiSpawning/outputSpooler.test.js+++ b/server/services/agentTuiSpawning/outputSpooler.test.js@@ -8,7 +8,7 @@ vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(undefined),}));-vi.mock('../cosAgents.js', () => ({+vi.mock('../cosAgentLifecycle.js', () => ({appendAgentOutputLines: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),}));@@ -20,7 +20,7 @@ vi.mock('../../lib/tuiHandshake.js', () => ({}));import { appendFile, writeFile } from 'fs/promises';-import { appendAgentOutputLines, updateAgent } from '../cosAgents.js';+import { appendAgentOutputLines, updateAgent } from '../cosAgentLifecycle.js';import { createOutputSpooler } from './outputSpooler.js';const OUTPUT_FILE = '/tmp/agent/output.txt';diff --git a/server/services/citysnapshots.js b/server/services/citysnapshots.jsindex da92be3965..7d312b0471 100644--- a/server/services/citysnapshots.js+++ b/server/services/citysnapshots.js@@ -29,7 +29,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { getSettings } from './settings.js';import * as apps from './apps.js';import * as cos from './cos.js';-import { getAgents } from './cosAgents.js';+import { getAgents } from './cosAgentLifecycle.js';import { getCosTasks } from './cosTaskStore.js';import { getPendingCounts } from './review.js';import { getSelf, getPeers } from './instances.js';diff --git a/server/services/citysnapshots.test.js b/server/services/citysnapshots.test.jsindex 9da7f4a22f..36fb527a2f 100644--- a/server/services/citysnapshots.test.js+++ b/server/services/citysnapshots.test.js@@ -21,7 +21,7 @@ describe('citysnapshots service', () => {vi.doUnmock('./settings.js');vi.doUnmock('./apps.js');vi.doUnmock('./cos.js');- vi.doUnmock('./cosAgents.js');+ vi.doUnmock('./cosAgentLifecycle.js');vi.doUnmock('./cosTaskStore.js');vi.doUnmock('./review.js');vi.doUnmock('./instances.js');@@ -61,7 +61,7 @@ describe('citysnapshots service', () => {stats: { tasksCompleted: 7 },})),}));- vi.doMock('./cosAgents.js', () => ({+ vi.doMock('./cosAgentLifecycle.js', () => ({getAgents: mock('agents', src('agents', [{ id: 'agent-1', status: 'running', workspacePath: '/repos/a1/sub' },{ id: 'agent-2', status: 'completed', workspacePath: '/repos/a2' },diff --git a/server/services/cos.js b/server/services/cos.jsindex 39b19b32c5..50e94ad83d 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -6,7 +6,10 @@** Decomposed modules:* - cosState.js — shared state management (loadState, saveState, config, mutex)- * - cosAgents.js — agent lifecycle (register, complete, archive, feedback)+ * - cosAgentLifecycle.js — agent lifecycle (register, update, complete, terminate)+ * - cosAgentIndex.js — date-bucket index + on-disk archive layout+ * - cosAgentFeedback.js — per-agent feedback capture + task-type classifier+ * - cosAgentArchive.js — state-eviction sweeps* - cosReports.js — reports, briefings, and activity tracking* - cosEvents.js — event emitter and logging* - cosHealthMonitor.js — daemon health checks (PM2/memory, auto-restart)@@ -41,11 +44,19 @@ export { cosEvents, emitLog };// Agent lifecycle (re-export for backward compat with `import * as cos`).//+// Sourced from the four modules that DECLARE these, not from a barrel: the+// `cosAgents.js` barrel these used to come through is retired (#3450), so this+// block is the last remaining second address for an agent function and the next+// one to collapse.+//// `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';+export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, sendBtwToAgent, cleanupZombieAgents, deleteAgent } from './cosAgentLifecycle.js';+export { getAgentDates, getAgentsByDate, pruneOldAgentArchives } from './cosAgentIndex.js';+export { submitAgentFeedback, getFeedbackStats, extractTaskType } from './cosAgentFeedback.js';+export { archiveStaleAgents, clearCompletedAgents } from './cosAgentArchive.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';@@ -78,7 +89,8 @@ const POST_STARTUP_QUEUE_DELAY_MS = 30_000;const RECENT_COMPLETION_GRACE_MS = 60_000;// Internal imports for functions used in this module-import { pruneOldAgentArchives, archiveStaleAgents as _archiveStaleAgents, loadAgentIndex } from './cosAgents.js';+import { pruneOldAgentArchives, loadAgentIndex } from './cosAgentIndex.js';+import { archiveStaleAgents as _archiveStaleAgents } from './cosAgentArchive.js';import { resolveAgentProviderAndModel } from './agentProviderResolution.js';// Task generation + evaluation engine (extracted to cosTaskGenerator.js).@@ -703,7 +715,7 @@ export async function getScript(name) {return { name, content, metadata };}-// Agent and report functions are now in cosAgents.js and cosReports.js+// Agent and report functions are now in the cosAgent* modules and cosReports.js// Re-exported above for backward compat with `import * as cos from './cos.js'`/**diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.jsindex f5e0b1dc10..304f7c7dc9 100644--- a/server/services/cosAgentArchive.js+++ b/server/services/cosAgentArchive.js@@ -5,7 +5,8 @@* stay on date-bucketed disk) and the destructive clear-completed sweep.* Extracted from the former monolithic cosAgents.js (issue #2530).*- * The public barrel `cosAgents.js` re-exports everything here.+ * The `cosAgents.js` barrel that used to re-export this module is retired+ * (#3450) — callers import from here directly.*/import { writeFile, rename, readdir, rm } from 'fs/promises';diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.jsindex ebc4101a99..098920ac02 100644--- a/server/services/cosAgentFeedback.js+++ b/server/services/cosAgentFeedback.js@@ -4,7 +4,8 @@* Per-agent feedback capture + aggregation and the task-type classifier.* Extracted from the former monolithic cosAgents.js (issue #2530).*- * The public barrel `cosAgents.js` re-exports everything here.+ * The `cosAgents.js` barrel that used to re-export this module is retired+ * (#3450) — callers import from here directly.*/import { existsSync } from 'fs';diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.jsindex 6f7bf3946a..6aed4300c0 100644--- a/server/services/cosAgentIndex.js+++ b/server/services/cosAgentIndex.js@@ -6,7 +6,8 @@* concerns live in one focused module. Owns the lazy `agentIndex` singleton and* the directory-resolution helper the lifecycle/feedback/archive modules share.*- * The public barrel `cosAgents.js` re-exports everything here.+ * The `cosAgents.js` barrel that used to re-export this module is retired+ * (#3450) — callers import from here directly.*/import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';diff --git a/server/services/cosAgents.indexMerge.test.js b/server/services/cosAgentIndex.merge.test.jssimilarity index 96%rename from server/services/cosAgents.indexMerge.test.jsrename to server/services/cosAgentIndex.merge.test.jsindex a9dc5b6ab2..50177b592f 100644--- a/server/services/cosAgents.indexMerge.test.js+++ b/server/services/cosAgentIndex.merge.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdir, rm, writeFile, readFile } from 'fs/promises';import { join } from 'path';-// Isolated file so cosAgents' lazy agentIndex singleton starts clean (a shared+// Isolated file so cosAgentIndex's lazy agentIndex singleton starts clean (a shared// file would carry the cache across describes). cosState is mocked to point// AGENTS_DIR at a tmpdir so addAgentArchivesToIndex (#1650 receiver hook) never// touches the real data/cos/agents index.@@ -18,7 +18,7 @@ vi.mock('./cosState.js', () => ({}));vi.mock('./domainUsage.js', () => ({ recordDomainUsage: vi.fn(async () => {}) }));-import { addAgentArchivesToIndex, loadAgentIndex } from './cosAgents.js';+import { addAgentArchivesToIndex, loadAgentIndex } from './cosAgentIndex.js';const INDEX_FILE = join(mockCosState.agentsDir, 'index.json');diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 7a48f111a6..af5dc50500 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -6,7 +6,8 @@* (issue #2530); the date-bucket index + archive layout lives in cosAgentIndex.js* and is shared via loadAgentIndex/saveAgentIndex/getAgentDir.*- * The public barrel `cosAgents.js` re-exports everything here.+ * The `cosAgents.js` barrel that used to re-export this module is retired+ * (#3450) — callers import from here directly.*/import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';diff --git a/server/services/cosAgents.test.js b/server/services/cosAgentLifecycle.test.jssimilarity index 99%rename from server/services/cosAgents.test.jsrename to server/services/cosAgentLifecycle.test.jsindex b3d968b5c0..a6ebec35fe 100644--- a/server/services/cosAgents.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -46,12 +46,12 @@ vi.mock('fs/promises', async (importOriginal) => {};});-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent } from './cosAgents.js';+import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent } from './cosAgentLifecycle.js';import { saveState } from './cosState.js';import { recordDomainUsage } from './domainUsage.js';import { cosEvents } from './cosEvents.js';-describe('cosAgents', () => {+describe('cosAgentLifecycle', () => {beforeEach(async () => {await rm(mockCosState.agentsDir, { recursive: true, force: true });await mkdir(mockCosState.agentsDir, { recursive: true });diff --git a/server/services/cosAgents.js b/server/services/cosAgents.jsdeleted file mode 100644index 3e7708f877..0000000000--- a/server/services/cosAgents.js+++ /dev/null@@ -1,18 +0,0 @@-/**- * CoS Agents Module (barrel)- *- * Agent lifecycle management, previously a single ~1090-line file. Decomposed- * (issue #2530) into focused sibling modules; this file stays as a thin barrel- * so every existing `from './cosAgents.js'` import path keeps working:- *- * - cosAgentIndex.js — date-bucket index, migration, prune, archive layout- * - cosAgentLifecycle.js — register / update / complete / output / terminate /- * pause / kill / BTW / zombie cleanup / single reads- * - cosAgentFeedback.js — per-agent feedback capture + aggregation + classifier- * - cosAgentArchive.js — state-eviction sweeps (archive stale, clear completed)- */--export * from './cosAgentIndex.js';-export * from './cosAgentLifecycle.js';-export * from './cosAgentFeedback.js';-export * from './cosAgentArchive.js';diff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex 40434d577b..0c5ed872c5 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -9,7 +9,7 @@ import { readFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js';-import { getAgentsByDate } from './cosAgents.js';+import { getAgentsByDate } from './cosAgentIndex.js';import { formatDuration, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';// A completed agent's work duration in ms: prefer the recorded `result.duration`,diff --git a/server/services/cosReports.test.js b/server/services/cosReports.test.jsindex 39a42b29c3..888ee1d892 100644--- a/server/services/cosReports.test.js+++ b/server/services/cosReports.test.js@@ -14,7 +14,7 @@ vi.mock('./cosState.js', () => ({isDaemonRunning: () => mock.daemonRunning}));-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentIndex.js', () => ({getAgentsByDate: vi.fn(async (date) => mock.agentsByDate[date] || [])}));diff --git a/server/services/malwareScanReports.js b/server/services/malwareScanReports.jsindex d0347852ae..3f3759c514 100644--- a/server/services/malwareScanReports.js+++ b/server/services/malwareScanReports.js@@ -46,7 +46,7 @@ export async function finalizeMalwareScan({ agentId, task, success }) {// graphs into the completion hot path.const [brain, agents, review] = await Promise.all([import('./brain.js'),- import('./cosAgents.js'),+ import('./cosAgentLifecycle.js'),import('./review.js')]);diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 3c5c29cd46..6ca4227165 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -7,7 +7,7 @@import { join } from 'path';import { cosEvents } from './cosEvents.js';-import { getAgents } from './cosAgents.js';+import { getAgents } from './cosAgentLifecycle.js';import { ensureDir, getDateString, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { getWeekId, isConsecutiveWeek } from '../lib/isoWeek.js';diff --git a/server/services/productivity.test.js b/server/services/productivity.test.jsindex 0ceb59c975..95ce6d3cb3 100644--- a/server/services/productivity.test.js+++ b/server/services/productivity.test.js@@ -4,7 +4,7 @@* Before this suite the module existed only as a `vi.mock()` target in* `routes/cosInsightRoutes.test.js` — referenced by a test, executed by none.* Here the real module runs: only the file-I/O boundary is redirected- * (`PATHS.cos` → a temp dir) and the agent history source (`cosAgents.js`) is+ * (`PATHS.cos` → a temp dir) and the agent history source (`cosAgentLifecycle.js` / `cosAgentIndex.js`) is* stubbed, so the streak arithmetic, the day/week boundary handling, and the* insight derivation are all exercised for real.*@@ -35,7 +35,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) =>const mock = vi.hoisted(() => ({ agents: [] }));-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgents: vi.fn(async () => mock.agents),}));diff --git a/server/services/sharing/cosHistorySync.test.js b/server/services/sharing/cosHistorySync.test.jsindex 7e0a1e0b87..488c8a15ac 100644--- a/server/services/sharing/cosHistorySync.test.js+++ b/server/services/sharing/cosHistorySync.test.js@@ -7,7 +7,7 @@ import { createHash } from 'crypto';// Completed-agent CoS history federation (#1650). We exercise peerSync.js's// cos-history functions against a tmpdir-redirected PATHS.cos, stubbing the-// network (peerFetch) and the peer registry (instances). cosAgents.js is mocked+// network (peerFetch) and the peer registry (instances). cosAgentIndex.js is mocked// so the receiver's index merge is a spy — it must NEVER touch the real// data/cos/agents index. The heavy record-graph modules are mocked exactly as// peerSync.test.js does, purely so importing peerSync.js stays cheap + offline.@@ -32,9 +32,9 @@ vi.mock('../mediaCollections.js', async () => ({}));vi.mock('../mediaAssetIndex/index.js', () => ({ reconcileMediaAssets: vi.fn().mockResolvedValue(undefined) }));vi.mock('../../lib/peerHttpClient.js', async () => ({ peerFetch: vi.fn() }));-// cosAgents is dynamic-imported by the receiver to merge the agentId→date index.+// cosAgentIndex is dynamic-imported by the receiver to merge the agentId→date index.// Spy it so the merge is observable AND can't write the real data/cos index.-vi.mock('../cosAgents.js', () => ({ addAgentArchivesToIndex: vi.fn().mockResolvedValue(0) }));+vi.mock('../cosAgentIndex.js', () => ({ addAgentArchivesToIndex: vi.fn().mockResolvedValue(0) }));import {buildCosHistoryManifest,@@ -43,7 +43,7 @@ import {} from './peerSync.js';import { getPeers } from '../instances.js';import { peerFetch } from '../../lib/peerHttpClient.js';-import { addAgentArchivesToIndex } from '../cosAgents.js';+import { addAgentArchivesToIndex } from '../cosAgentIndex.js';const sha = (s) => createHash('sha256').update(s).digest('hex');diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.jsindex 2ccb935159..c81b7e96c2 100644--- a/server/services/sharing/peerCosSync.js+++ b/server/services/sharing/peerCosSync.js@@ -202,7 +202,7 @@ async function pullOneCosArchiveFile(peer, base, entry) {* index so the CoS history UI lists them. Called ONLY when the manifest's files* are confirmed present on disk (the diff returned empty), so every referenced* agent — including its metadata.json — exists; a half-pulled agent is never- * indexed. Dynamic import keeps cosAgents out of peerSync's static graph (mirrors+ * indexed. Dynamic import keeps cosAgentIndex out of peerSync's static graph (mirrors* reconcileMediaLibraryIndex). addAgentArchivesToIndex unions and never* overwrites a locally-owned id.*/@@ -217,7 +217,7 @@ async function reconcileCosHistoryIndex(entries) {seen.add(key);pairs.push({ date: e.date, agentId: e.agentId });}- const mod = await import('../cosAgents.js').catch(() => null);+ const mod = await import('../cosAgentIndex.js').catch(() => null);if (!mod?.addAgentArchivesToIndex) return;await mod.addAgentArchivesToIndex(pairs).catch((err) => {console.log(`⚠️ peerSync: cos-history index merge failed: ${err.message}`);diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex d4d6c0ec2b..1d1c967791 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -10,13 +10,14 @@** 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`.+ * over the `cosAgents.js` barrel (since retired too) 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@@ -31,7 +32,7 @@ import { join } from 'path';import { readdir, rm, stat } from 'fs/promises';import { existsSync } from 'fs';import { emitLog, cosEvents } from './cosEvents.js';-import { updateAgent } from './cosAgents.js';+import { updateAgent } from './cosAgentLifecycle.js';import { initProviderStatus } from './providerStatus.js';import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';import { PATHS } from '../lib/fileUtils.js';diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.jsindex 54ba4c18f3..3f621f6cab 100644--- a/server/services/weeklyDigest.js+++ b/server/services/weeklyDigest.js@@ -10,7 +10,8 @@ import { readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { cosEvents, emitLog } from './cosEvents.js';-import { getAgents, getAgentDates, getAgentsByDate } from './cosAgents.js';+import { getAgents } from './cosAgentLifecycle.js';+import { getAgentDates, getAgentsByDate } from './cosAgentIndex.js';import { atomicWrite, ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';import { getWeekId } from '../lib/isoWeek.js';diff --git a/server/services/weeklyDigest.test.js b/server/services/weeklyDigest.test.jsindex dafc09142b..e1fccf2491 100644--- a/server/services/weeklyDigest.test.js+++ b/server/services/weeklyDigest.test.js@@ -5,7 +5,7 @@* `routes/cosLearningRoutes.test.js`, so none of the aggregation, the* week-over-week math, or the insight copy was ever executed. Here the real* module runs against a temp digests dir (the only file-I/O boundary) with the- * agent history source (`cosAgents.js`) stubbed.+ * agent history source (`cosAgentLifecycle.js` / `cosAgentIndex.js`) stubbed.** Fixture timestamps are built from LOCAL date components so every expectation* holds regardless of the runner's timezone — the service reads local getters.@@ -34,8 +34,11 @@ const mock = vi.hoisted(() => ({agentsByDate: {}, // getAgentsByDate(date)}));-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgents: vi.fn(async () => mock.agents),+}));++vi.mock('./cosAgentIndex.js', () => ({getAgentDates: vi.fn(async () => Object.keys(mock.agentsByDate).map(date => ({ date }))),getAgentsByDate: vi.fn(async (date) => mock.agentsByDate[date] || []),}));@@ -448,7 +451,7 @@ describe('generateWeeklyDigest — insights', () => {describe('getWeeklyDigest', () => {it('returns a stored digest for a past week without recomputing', async () => {writeDigest('2026-W05', storedDigest('2026-W05', { totalTasks: 99, successRate: 42, totalWorkTimeMs: 5000 }));- const { getAgents } = await import('./cosAgents.js');+ const { getAgents } = await import('./cosAgentLifecycle.js');const digest = await digestService.getWeeklyDigest('2026-W05');