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: decompose cos.js dequeueNextTask and split cosAgents modules (#2530)

Adam Eivyb5dee5db1989
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9d6e1abbb5..447172a35e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,10 @@
- **First-run tutorial for POST cognitive drills.** The timed, stimulus-driven cognitive drills (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) start flashing a stimulus the instant they mount, which is disorienting the first time you meet one. Each drill type now shows a one-time how-to card — a plain-language goal, numbered steps, and the controls — the first time it's encountered, and holds the drill (and its timers) until you tap **Start drill**. The card is config-aware (it names the n-back lag, the digit-span direction, and the reaction-time mode), then never shows again for that type (tracked per type in `localStorage`). Non-timed drills (math/memory, LLM/verbal) are self-explanatory and are not gated.
- **Voice fast-resolution cascade (lower CoS latency, opt-in).** The voice Chief of Staff can now triage each spoken/typed turn through fast client-side tiers before the (slow) server LLM: **tier 1 triggers** resolve navigation commands ("go to tasks", "open the daily log") instantly in the browser with no LLM; **tier 2** runs Chrome's on-device **Gemini Nano** (Prompt API — `window.LanguageModel` / legacy `self.ai.languageModel`) for simple/conversational turns, entirely local and private; **tier 3** is the existing server pipeline (recommend Ollama), which still handles every tool/action turn, personal-data retrieval, dictation, and confirmations. Off by default (existing installs keep all-server behavior); enable under **Settings → Voice → Fast resolution**, which also shows a live on-device-model availability pill with the `chrome://flags` hint. Applies to Web-Speech STT and typed input (whisper/hands-free audio turns stay server-driven); trigger/Nano replies are spoken through the configured TTS and keep barge-in + echo-suppression working. New `llm.fastPath` config (`enabled`/`triggers`/`browserLlm`/`browser.{temperature,topK}`); new client modules `browserLlm.js` (Nano client) and `voiceFastPath.js` (routing decision). Nothing runs a model the user hasn't triggered (no cold-bootstrap).
+## Changed
+
+- **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.
+
## Documentation
- **[issue-2546] Document missing `.env` vars and the boot `CREATE INDEX` lock window.** `.env.example` now carries commented entries with purpose notes for four vars the server actually reads but never documented: `PUBLIC_HOST` (public hostname baked into Google/Spotify OAuth redirect URIs), `SPOTIFY_REDIRECT_URI` (verbatim Spotify redirect override), `CODEX_HOME` (Codex CLI home scanned for provider-usage stats), and `HUGGINGFACE_TOKEN` (the fourth HF-token alias read by the Hugging Face catalog client). Separately, `ensureSchema()` in `server/lib/db.js` creates every index (incl. the HNSW vector index) non-`CONCURRENTLY`, so the first apply on a large pre-existing table takes a write-blocking lock at boot; a comment there and a new **Boot schema upgrades & the CREATE INDEX lock window** section in `docs/STORAGE.md` explain when this bites (existing-install upgrades, not fresh installs) and why the fix for a future large-table index is a `CONCURRENTLY` db-migration rather than changing `ensureSchema()`. Docs-only — no runtime behavior change.
diff --git a/server/services/cos.js b/server/services/cos.js
index 38a132e465..5ab9fcd5d2 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -111,6 +111,13 @@ import {
clearSpawningJob
} from './cosJobScheduler.js';
+// Pure priority/capacity helpers for dequeueNextTask (extracted to cosDequeue.js,
+// issue #2530). The per-cycle capacity tracker + mission/idle tier-eligibility
+// predicates are shared with the scheduler unit tests so they exercise the real
+// guards instead of a local replica. The async tiers stay here as
+// `spawnDequeuePriorityN(ctx)` helpers.
+import { createDequeueCapacity, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';
+
/**
* Get current CoS status
*/
@@ -686,67 +693,35 @@ async function tryImmediateSpawn(task) {
cosEvents.emit('task:ready', { ...task, taskType: 'user' });
}
+// ─── dequeueNextTask priority tiers ────────────────────────────────────────
+//
+// dequeueNextTask (below) is a thin orchestrator that threads a shared `ctx`
+// through the five priority tiers in order. Each tier is a focused async helper
+// that reads/mutates the per-cycle spawn capacity via `ctx.capacity` (the pure
+// tracker from cosDequeue.js) and emits `task:ready` for admitted tasks. This
+// mirrors the established `spawnPriorityN(ctx)` decomposition in
+// cosTaskGenerator.js's evaluateTasks (issue #2530).
+
/**
- * Event-driven task dequeue — the primary way tasks get spawned.
- *
- * Triggered by: agent:completed, tasks:user:added, tasks:cos:added, status:resumed
- * Fills all available slots using the same priority order as evaluateTasks:
- * 0. On-demand requests
- * 1. User tasks
- * 2. Auto-approved system tasks
- * 3. Mission-driven proactive tasks (if proactiveMode)
- * 4. Idle review task (if idleReviewEnabled)
- * Returns silently when idle — no log noise.
+ * Priority 0 — on-demand task requests (explicit user "Run"). Runs even while
+ * paused. Loads the task schedule onto `ctx` (reused by Priority 2) and drains
+ * the on-demand request queue, generating + persisting a task per request.
*/
-async function dequeueNextTask() {
- if (!isDaemonRunning()) return;
+async function spawnDequeuePriority0OnDemand(ctx) {
+ const { state, capacity } = ctx;
- // A global pause stops scheduled/autonomous spawning, but NOT explicit user
- // triggers: on-demand requests (Priority 0) are processed even while paused so
- // a manual "Run" from an app's automation page still fires. The autonomous
- // tiers (Priority 1+) are skipped below when paused.
- const paused = await isPaused();
-
- const state = await loadState();
- const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
- const availableSlots = state.config.maxConcurrentAgents - runningAgents;
-
- if (availableSlots <= 0) return;
-
- // This instance's federation id, resolved once per cycle so the priority
- // tiers below can skip tasks a peer holds a live lease on (#1650). Warm path
- // is the cheap cached read; only the cold boot creates the identity.
- const instanceId = await ensureInstanceId();
-
- const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
- const agentsByProject = countRunningAgentsByProject(state.agents);
- const spawnProjectCounts = { ...agentsByProject };
- let spawned = 0;
-
- // `ceiling` defaults to the global slot count; autonomous sections pass the
- // lower `autonomousSpawnCeiling` so the CoS daily action budget (#711) caps them.
- const canSpawn = (task, ceiling = availableSlots) => {
- if (spawned >= ceiling) return false;
- const project = task.metadata?.app || '_self';
- return (spawnProjectCounts[project] || 0) < perProjectLimit;
- };
-
- const trackSpawn = (task) => {
- const project = task.metadata?.app || '_self';
- spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
- spawned++;
- };
-
- // Priority 0: On-demand task requests
const taskScheduleMod = await import('./taskSchedule.js');
const taskSchedule = await taskScheduleMod.loadSchedule();
const onDemandRequests = await taskScheduleMod.getOnDemandRequests();
+ // Stash for Priority 2's disabled-analysis-type gate (avoids a second load).
+ ctx.taskScheduleMod = taskScheduleMod;
+ ctx.taskSchedule = taskSchedule;
// Track apps already marked review-started this cycle so multiple on-demand
// requests for the same app don't each rewrite its activity record.
const reviewStartedApps = new Set();
for (const request of onDemandRequests) {
- if (spawned >= availableSlots) break;
+ if (capacity.spawned >= capacity.availableSlots) break;
if (!isImprovementEnabled(state)) {
emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
@@ -809,11 +784,11 @@ async function dequeueNextTask() {
task = await generateSelfImprovementTaskForType(request.taskType, state);
}
- if (task && canSpawn(task)) {
+ if (task && capacity.canSpawn(task)) {
const persisted = await addTask(task, 'internal', { raw: true });
if (!persisted?.duplicate) {
cosEvents.emit('task:ready', task);
- trackSpawn(task);
+ capacity.trackSpawn(task);
}
} else if (!task) {
// Explicit user "Run" produced no task — surface WHY (parked / transient /
@@ -824,17 +799,22 @@ async function dequeueNextTask() {
await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: taskSchedule.tasks[request.taskType] });
}
}
+}
- // Global pause stops every autonomous/scheduled/user tier below; only the
- // on-demand queue above (explicit user "Run") bypasses it.
- if (paused) return;
+/**
+ * Priority 1 — pending user tasks. Records `pendingUserTasks` /
+ * `hasPendingUserTasks` on `ctx` for the mission/idle tiers below.
+ */
+async function spawnDequeuePriority1UserTasks(ctx) {
+ const { state, instanceId, capacity } = ctx;
- // Priority 1: User tasks
const userTaskData = await getUserTasks();
const pendingUserTasks = userTaskData.grouped?.pending || [];
+ ctx.pendingUserTasks = pendingUserTasks;
+ ctx.hasPendingUserTasks = pendingUserTasks.length > 0;
for (const task of pendingUserTasks) {
- if (spawned >= availableSlots) break;
+ if (capacity.spawned >= capacity.availableSlots) break;
// A federated peer holds a live lease on this task (#1650) — it's being
// worked on the other machine. Skip it during candidate selection so it
// doesn't consume this cycle's spawn slot (the spawn guard would return
@@ -845,14 +825,21 @@ async function dequeueNextTask() {
}
if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
const userTask = { ...task, taskType: 'user' };
- if (!canSpawn(userTask)) continue;
+ if (!capacity.canSpawn(userTask)) continue;
cosEvents.emit('task:ready', userTask);
- trackSpawn(userTask);
+ capacity.trackSpawn(userTask);
}
+}
+
+/**
+ * Priority 2 — auto-approved system tasks, gated by the CoS auto-run domain.
+ * Resolves `ctx.cosAutonomyMode` and `ctx.autonomousSpawnCeiling` (used by the
+ * mission/idle tiers) from the daily CoS budget (#711). `off`/`dry-run` withhold
+ * the unattended spawn; `dry-run` logs what execute mode would have run.
+ */
+async function spawnDequeuePriority2AutoApproved(ctx) {
+ const { state, instanceId, capacity } = ctx;
- // Priority 2: Auto-approved system tasks — gated by the CoS auto-run domain.
- // `off`/`dry-run` both stop the unattended spawn; `dry-run` logs what would
- // have run so the user can see the plan without it executing.
const cosTaskData = await getCosTasks();
const autoApproved = cosTaskData.autoApproved || [];
let cosAutonomyMode = getDomainMode(state.config, 'cos');
@@ -881,13 +868,15 @@ async function dequeueNextTask() {
}
}
}
- const autonomousSpawnCeiling = Math.min(availableSlots, spawned + autonomousActionsRemaining);
+ const autonomousSpawnCeiling = Math.min(capacity.availableSlots, capacity.spawned + autonomousActionsRemaining);
+ ctx.cosAutonomyMode = cosAutonomyMode;
+ ctx.autonomousSpawnCeiling = autonomousSpawnCeiling;
// Engine-specific gate shared by execute and dry-run: improvement tasks whose
// task type was disabled after queuing are skipped.
const isDisabledAnalysisType = (task) => {
const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;
- return Boolean(analysisType) && !taskSchedule.tasks[analysisType]?.enabled;
+ return Boolean(analysisType) && !ctx.taskSchedule.tasks[analysisType]?.enabled;
};
if (cosAutonomyMode !== 'execute') {
@@ -898,9 +887,9 @@ async function dequeueNextTask() {
if (cosAutonomyMode === 'dry-run') {
const wouldSpawn = await selectDryRunAutoApproved(autoApproved, {
availableSlots: autonomousSpawnCeiling,
- alreadySpawned: spawned,
- perProjectLimit,
- spawnProjectCounts,
+ alreadySpawned: capacity.spawned,
+ perProjectLimit: capacity.perProjectLimit,
+ spawnProjectCounts: capacity.spawnProjectCounts,
isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
cooldownExempt: isCooldownExemptTask,
extraSkip: isDisabledAnalysisType,
@@ -912,7 +901,7 @@ async function dequeueNextTask() {
}
} else {
for (const task of autoApproved) {
- if (spawned >= autonomousSpawnCeiling) break;
+ if (capacity.spawned >= autonomousSpawnCeiling) break;
// A federated peer holds a live lease on this task (#1650) — skip it
// during candidate selection so it doesn't consume an autonomous slot
// the spawn guard would just reject.
@@ -937,60 +926,149 @@ async function dequeueNextTask() {
if (onCooldown) continue;
}
const sysTask = { ...task, taskType: 'internal' };
- if (!canSpawn(sysTask, autonomousSpawnCeiling)) continue;
+ if (!capacity.canSpawn(sysTask, autonomousSpawnCeiling)) continue;
cosEvents.emit('task:ready', sysTask);
- trackSpawn(sysTask);
+ capacity.trackSpawn(sysTask);
}
}
+}
- const hasPendingUserTasks = pendingUserTasks.length > 0;
+/**
+ * Priority 3 — mission-driven proactive tasks. Speculative autonomous spawns,
+ * only generated when the shared `isMissionTierEligible` predicate passes (auto-
+ * run in execute, no pending user tasks, proactive mode on, headroom left).
+ */
+async function spawnDequeuePriority3Missions(ctx) {
+ const { state, capacity } = ctx;
+
+ if (!isMissionTierEligible({
+ spawned: capacity.spawned,
+ ceiling: ctx.autonomousSpawnCeiling,
+ hasPendingUserTasks: ctx.hasPendingUserTasks,
+ proactiveMode: state.config.proactiveMode,
+ autonomyMode: ctx.cosAutonomyMode
+ })) return;
+
+ const missionTasks = await generateMissionTasks({ maxTasks: ctx.autonomousSpawnCeiling - capacity.spawned }).catch(err => {
+ emitLog('debug', `Mission task generation failed: ${err.message}`);
+ return [];
+ });
- // Priority 3: Mission-driven proactive tasks. These are speculative autonomous
- // spawns — when CoS auto-run isn't `execute`, skip generating them entirely
- // (off and dry-run both withhold autonomous spawns; only the concrete already-
- // queued auto-approved tasks above are surfaced for dry-run).
- if (spawned < autonomousSpawnCeiling && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {
- const missionTasks = await generateMissionTasks({ maxTasks: autonomousSpawnCeiling - spawned }).catch(err => {
- emitLog('debug', `Mission task generation failed: ${err.message}`);
- return [];
+ for (const missionTask of missionTasks) {
+ if (capacity.spawned >= ctx.autonomousSpawnCeiling) break;
+ const cosTask = {
+ id: missionTask.id,
+ description: missionTask.description,
+ priority: missionTask.priority?.toUpperCase() || 'MEDIUM',
+ status: 'pending',
+ metadata: missionTask.metadata,
+ taskType: 'internal',
+ approvalRequired: !missionTask.autoApprove
+ };
+ if (!capacity.canSpawn(cosTask, ctx.autonomousSpawnCeiling)) continue;
+ cosEvents.emit('task:ready', cosTask);
+ capacity.trackSpawn(cosTask);
+ emitLog('info', `Generated mission task: ${missionTask.id}`, {
+ missionId: missionTask.metadata?.missionId
});
-
- for (const missionTask of missionTasks) {
- if (spawned >= autonomousSpawnCeiling) break;
- const cosTask = {
- id: missionTask.id,
- description: missionTask.description,
- priority: missionTask.priority?.toUpperCase() || 'MEDIUM',
- status: 'pending',
- metadata: missionTask.metadata,
- taskType: 'internal',
- approvalRequired: !missionTask.autoApprove
- };
- if (!canSpawn(cosTask, autonomousSpawnCeiling)) continue;
- cosEvents.emit('task:ready', cosTask);
- trackSpawn(cosTask);
- emitLog('info', `Generated mission task: ${missionTask.id}`, {
- missionId: missionTask.metadata?.missionId
- });
- }
}
+}
- // Priority 4: Idle review task (only when completely idle) — also an autonomous
- // spawn, so gated by the CoS auto-run domain.
- if (spawned === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks && cosAutonomyMode === 'execute') {
- const freshCosTasks = await getCosTasks();
- const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
- if (pendingSystemTasks === 0) {
- const idleTask = await generateIdleReviewTask(state);
- if (idleTask && canSpawn(idleTask, autonomousSpawnCeiling)) {
- cosEvents.emit('task:ready', idleTask);
- trackSpawn(idleTask);
- }
+/**
+ * Priority 4 — idle review task, only when the daemon is completely idle this
+ * cycle (shared `isIdleTierEligible` predicate: nothing spawned, no pending user
+ * tasks, idle review on, auto-run in execute).
+ */
+async function spawnDequeuePriority4IdleReview(ctx) {
+ const { state, capacity } = ctx;
+
+ if (!isIdleTierEligible({
+ spawned: capacity.spawned,
+ hasPendingUserTasks: ctx.hasPendingUserTasks,
+ idleReviewEnabled: state.config.idleReviewEnabled,
+ autonomyMode: ctx.cosAutonomyMode
+ })) return;
+
+ const freshCosTasks = await getCosTasks();
+ const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
+ if (pendingSystemTasks === 0) {
+ const idleTask = await generateIdleReviewTask(state);
+ if (idleTask && capacity.canSpawn(idleTask, ctx.autonomousSpawnCeiling)) {
+ cosEvents.emit('task:ready', idleTask);
+ capacity.trackSpawn(idleTask);
}
}
+}
+
+/**
+ * Event-driven task dequeue — the primary way tasks get spawned.
+ *
+ * Triggered by: agent:completed, tasks:user:added, tasks:cos:added, status:resumed
+ * Thin orchestrator: computes per-cycle capacity, then threads a shared `ctx`
+ * through the five priority tiers in order (same order as evaluateTasks):
+ * 0. On-demand requests (bypasses pause)
+ * 1. User tasks
+ * 2. Auto-approved system tasks
+ * 3. Mission-driven proactive tasks (if proactiveMode)
+ * 4. Idle review task (if idleReviewEnabled)
+ * Returns silently when idle — no log noise.
+ */
+async function dequeueNextTask() {
+ if (!isDaemonRunning()) return;
+
+ // A global pause stops scheduled/autonomous spawning, but NOT explicit user
+ // triggers: on-demand requests (Priority 0) are processed even while paused so
+ // a manual "Run" from an app's automation page still fires. The autonomous
+ // tiers (Priority 1+) are skipped below when paused.
+ const paused = await isPaused();
+
+ const state = await loadState();
+ const capacity = createDequeueCapacity(state, { agentsByProject: countRunningAgentsByProject(state.agents) });
+ const availableSlots = capacity.availableSlots;
+
+ if (availableSlots <= 0) return;
+
+ // This instance's federation id, resolved once per cycle so the priority
+ // tiers below can skip tasks a peer holds a live lease on (#1650). Warm path
+ // is the cheap cached read; only the cold boot creates the identity.
+ const instanceId = await ensureInstanceId();
+
+ // Shared spawn context threaded through each priority tier. The tiers mutate
+ // the running spawn total + per-project counts through `capacity` (whose
+ // `canSpawn`/`trackSpawn` close over that state), and stash cross-tier values
+ // (taskSchedule, pendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling) on
+ // `ctx` as they resolve them.
+ const ctx = {
+ state,
+ instanceId,
+ capacity,
+ pendingUserTasks: [],
+ hasPendingUserTasks: false,
+ taskScheduleMod: null,
+ taskSchedule: null,
+ cosAutonomyMode: null,
+ autonomousSpawnCeiling: availableSlots
+ };
+
+ // Priority 0 (on-demand) runs even when paused — an explicit user "Run"
+ // bypasses the global pause.
+ await spawnDequeuePriority0OnDemand(ctx);
+
+ // Global pause stops every autonomous/scheduled/user tier below; only the
+ // on-demand queue above (explicit user "Run") bypasses it.
+ if (paused) return;
+
+ // Priority 1 spends against the global slot cap.
+ await spawnDequeuePriority1UserTasks(ctx);
+
+ // Priorities 2, 3, 4 spend against the lower autonomous ceiling that
+ // Priority 2 resolves onto `ctx.autonomousSpawnCeiling` from the daily budget.
+ await spawnDequeuePriority2AutoApproved(ctx);
+ await spawnDequeuePriority3Missions(ctx);
+ await spawnDequeuePriority4IdleReview(ctx);
- if (spawned > 0) {
- emitLog('info', `⚡ Dequeued ${spawned} task(s)`, { spawned, availableSlots });
+ if (capacity.spawned > 0) {
+ emitLog('info', `⚡ Dequeued ${capacity.spawned} task(s)`, { spawned: capacity.spawned, availableSlots });
}
}
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 3127f3f251..28012e7a42 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -17,10 +17,12 @@
* `evaluateTasks` and `dequeueNextTask` are 250+ LOC each and pull in 40+
* imported helpers (loadState, getAllTasks, addTask, getActiveApps, mission
* generation, taskSchedule, etc.). Mocking the full graph would be a brittle
- * test of mocks rather than logic, so we follow the established
- * inline-function-copy pattern from `subAgentSpawner.test.js` and
- * `agentLifecycle.test.js`: lift the priority/capacity slice into a pure
- * function that mirrors the production loop and exercise it with test data.
+ * test of mocks rather than logic, so we exercise the *real* capacity/gate
+ * exports the scheduler uses — `createDequeueCapacity`, `isMissionTierEligible`,
+ * `isIdleTierEligible` from cosDequeue.js (issue #2530) — through a thin drain
+ * harness. Only the tier-ordering loop glue is local; every capacity and
+ * eligibility decision routes through the same helpers `dequeueNextTask` calls,
+ * so a guard-logic regression fails here instead of only in production.
*
* A source-level regression check at the bottom asserts the priority order
* and the capacity-guard early return are still in place in `cos.js`, so a
@@ -34,6 +36,7 @@ import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { firstLine, isPerpetualRefillCandidate } from './cos.js';
import { canQueueImprovementTasks } from './cosState.js';
+import { createDequeueCapacity, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
@@ -44,84 +47,81 @@ const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
// whichever module now owns it.
const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');
const SCHED_SRC = readFileSync(join(__dirname, 'cosJobScheduler.js'), 'utf-8');
+// The pure capacity tracker + mission/idle tier-eligibility predicates that
+// dequeueNextTask (and these tests) call live in cosDequeue.js (issue #2530).
+const DEQ_SRC = readFileSync(join(__dirname, 'cosDequeue.js'), 'utf-8');
-// ─── Inline replicas of the cos.js priority + capacity slice ───────────────
+// ─── Real capacity/gate exports driven by a thin harness ───────────────────
/**
- * Replica of the capacity-tracking closure used in `evaluateTasks` (lines
- * 633–666) and `dequeueNextTask` (lines 2329–2349). These are the exact
- * guards that decide whether a task can spawn now or must wait.
+ * Build the REAL per-cycle capacity tracker (`createDequeueCapacity` from
+ * cosDequeue.js) from a fixture state — the same tracker `dequeueNextTask`
+ * constructs. Exposes `availableSlots`, `perProjectLimit`, `spawnProjectCounts`,
+ * and the `canSpawn`/`trackSpawn` closure the scheduler enforces. `spawned` is a
+ * live numeric getter (not an array), so the drain harness below keeps its own
+ * `admitted` list of the task objects it let through.
*/
function makeCapacityTracker(state, agentsByProject = {}) {
- const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
- const availableSlots = state.config.maxConcurrentAgents - runningAgents;
- const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
-
- const spawnProjectCounts = { ...agentsByProject };
- const spawned = [];
-
- const canSpawn = (task) => {
- if (spawned.length >= availableSlots) return false;
- const project = task.metadata?.app || '_self';
- return (spawnProjectCounts[project] || 0) < perProjectLimit;
- };
-
- const trackSpawn = (task) => {
- const project = task.metadata?.app || '_self';
- spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
- spawned.push(task);
- };
-
- return { availableSlots, perProjectLimit, canSpawn, trackSpawn, spawned, spawnProjectCounts };
+ return createDequeueCapacity(state, { agentsByProject });
}
/**
- * Replica of the priority-bucket loop in `evaluateTasks` / `dequeueNextTask`.
- * The production code merges five buckets in this exact order:
+ * Thin drain harness modelling the priority-bucket loop in `dequeueNextTask`.
+ * The five buckets are drained in this exact order:
*
- * 0. onDemand — explicit user requests (highest)
+ * 0. onDemand — explicit user requests (highest, bypasses pause)
* 1. user — user-authored pending tasks
* 2. autoSystem — auto-approved system / improvement tasks
- * 3. mission — proactive mission tasks (only when no pending user)
- * 4. idle — generated idle-review task (only when nothing else
- * has been queued/spawned in this cycle)
+ * 3. mission — proactive mission tasks (only when eligible)
+ * 4. idle — generated idle-review task (only when eligible)
*
- * Within a bucket the iteration order is whatever the source array provides
- * (file order for parsed TASKS.md; arrival order for the on-demand request
- * queue). The dequeue loop does NOT re-sort by priorityValue at this layer
- * — it relies on the upstream parser/writer to keep CRITICAL/HIGH tasks
- * positioned earlier in the file. This is the contract these tests pin.
+ * Only the ordering/glue is local: every capacity decision routes through the
+ * real `capacity.canSpawn`/`trackSpawn`, and the mission/idle fences use the
+ * real `isMissionTierEligible` / `isIdleTierEligible` predicates the scheduler
+ * calls. Within a bucket, iteration order is the source array order (file order
+ * for parsed TASKS.md; arrival order for the on-demand queue) — the loop does
+ * NOT re-sort by priorityValue.
*
- * Idle gating: production is stricter than just `!hasPendingUserTasks`. In
- * `dequeueNextTask` the idle generator is fenced by `if (spawned === 0 &&
- * state.config.idleReviewEnabled && !hasPendingUserTasks)` (cos.js:2480) —
- * i.e. NOTHING else (autoSystem, mission) may have spawned this cycle.
- * `evaluateTasks` mirrors this at cos.js:862 with `tasksToSpawn.length === 0`.
- * The replica enforces the same `spawned === 0` precondition.
+ * Idle gating is stricter than mission's: `isIdleTierEligible` requires
+ * `spawned === 0`, so ANY earlier spawn (autoSystem or mission) suppresses idle
+ * on the same cycle. Tests run with auto-run in `execute` and proactive/idle
+ * enabled so the tier predicates reduce to the pending-user + spawned gates.
*/
function priorityDequeue(buckets, capacity, { paused = false } = {}) {
- const order = ['onDemand', 'user', 'autoSystem', 'mission', 'idle'];
-
- // Mission / idle only run when no pending user tasks exist, mirroring the
- // production `hasPendingUserTasks` gate at lines 795 / 2450.
+ const admitted = [];
const hasPendingUserTasks = (buckets.user || []).length > 0;
+ // No daily budget in these fixtures, so the autonomous ceiling equals the
+ // global slot count.
+ const ceiling = capacity.availableSlots;
- for (const bucketName of order) {
- // Global pause: on-demand (explicit user "Run") still drains, but every
- // autonomous/scheduled/user tier below is skipped — mirrors the
- // `if (paused) return;` gate in dequeueNextTask after Priority 0.
- if (paused && bucketName !== 'onDemand') break;
- if ((bucketName === 'mission' || bucketName === 'idle') && hasPendingUserTasks) continue;
- // Idle is stricter: only fires when no other bucket has spawned yet.
- if (bucketName === 'idle' && capacity.spawned.length > 0) continue;
- const bucket = buckets[bucketName] || [];
- for (const task of bucket) {
- if (capacity.spawned.length >= capacity.availableSlots) return capacity.spawned;
+ const drain = (bucketName) => {
+ for (const task of buckets[bucketName] || []) {
+ if (capacity.spawned >= capacity.availableSlots) return;
if (!capacity.canSpawn(task)) continue;
- capacity.trackSpawn({ ...task, _bucket: bucketName });
+ capacity.trackSpawn(task);
+ admitted.push({ ...task, _bucket: bucketName });
}
- }
- return capacity.spawned;
+ };
+
+ // Priority 0 (on-demand) drains even when paused.
+ drain('onDemand');
+ // Global pause stops every autonomous/scheduled/user tier below.
+ if (paused) return admitted;
+
+ drain('user');
+ drain('autoSystem');
+
+ if (isMissionTierEligible({
+ spawned: capacity.spawned, ceiling, hasPendingUserTasks,
+ proactiveMode: true, autonomyMode: 'execute'
+ })) drain('mission');
+
+ if (isIdleTierEligible({
+ spawned: capacity.spawned, hasPendingUserTasks,
+ idleReviewEnabled: true, autonomyMode: 'execute'
+ })) drain('idle');
+
+ return admitted;
}
// ─── Fixture helpers ───────────────────────────────────────────────────────
@@ -646,31 +646,30 @@ describe('cos.js source — priority + capacity invariants', () => {
expect(fnBody).toMatch(/if\s*\(\s*availableSlots\s*<=\s*0\s*\)/);
});
- it('priority order in dequeueNextTask: onDemand → user → autoSystem → mission → idle', () => {
- const fnStart = COS_SRC.indexOf('async function dequeueNextTask');
- const fnBody = extractFnBody(COS_SRC, fnStart);
-
- // Anchor on the actual code markers (declarations / generator calls)
- // for each priority bucket — NOT the `// Priority N` comments. A comment
- // rename or rewording shouldn't fail this test; only an actual reorder
- // of the dequeue logic should.
+ it('dequeueNextTask orchestrates the spawnDequeuePriority* tiers in priority order', () => {
+ // dequeueNextTask (cos.js) decomposes each priority tier into a named
+ // `spawnDequeuePriorityN(ctx)` helper (issue #2530), mirroring evaluateTasks.
+ // This pins that the orchestrator actually INVOKES each tier helper, in order
+ // — an actual reorder of the dequeue logic is the only thing that fails it.
//
- // Priority 0 (onDemand) — `onDemandRequests` declaration + loop
- // Priority 1 (user) — `pendingUserTasks` declaration + loop
- // Priority 2 (autoSystem) — `autoApproved` declaration + loop
- // Priority 3 (mission) — `generateMissionTasks(` call
- // Priority 4 (idle) — `generateIdleReviewTask(` call
- const onDemandIdx = fnBody.indexOf('onDemandRequests');
- const userIdx = fnBody.indexOf('pendingUserTasks');
- const autoSysIdx = fnBody.indexOf('autoApproved');
- const missionIdx = fnBody.indexOf('generateMissionTasks(');
- const idleIdx = fnBody.indexOf('generateIdleReviewTask(');
-
- expect(onDemandIdx, 'onDemandRequests must appear').toBeGreaterThan(-1);
- expect(userIdx, 'pendingUserTasks must appear after onDemand').toBeGreaterThan(onDemandIdx);
- expect(autoSysIdx, 'autoApproved must appear after pendingUserTasks').toBeGreaterThan(userIdx);
- expect(missionIdx, 'generateMissionTasks must appear after autoApproved').toBeGreaterThan(autoSysIdx);
- expect(idleIdx, 'generateIdleReviewTask must appear after generateMissionTasks').toBeGreaterThan(missionIdx);
+ // Priority 0 (onDemand) — spawnDequeuePriority0OnDemand(ctx)
+ // Priority 1 (user) — spawnDequeuePriority1UserTasks(ctx)
+ // Priority 2 (autoSystem) — spawnDequeuePriority2AutoApproved(ctx)
+ // Priority 3 (mission) — spawnDequeuePriority3Missions(ctx)
+ // Priority 4 (idle) — spawnDequeuePriority4IdleReview(ctx)
+ const fnBody = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
+
+ const onDemandIdx = fnBody.indexOf('spawnDequeuePriority0OnDemand(ctx)');
+ const userIdx = fnBody.indexOf('spawnDequeuePriority1UserTasks(ctx)');
+ const autoSysIdx = fnBody.indexOf('spawnDequeuePriority2AutoApproved(ctx)');
+ const missionIdx = fnBody.indexOf('spawnDequeuePriority3Missions(ctx)');
+ const idleIdx = fnBody.indexOf('spawnDequeuePriority4IdleReview(ctx)');
+
+ expect(onDemandIdx, 'spawnDequeuePriority0OnDemand must be invoked').toBeGreaterThan(-1);
+ expect(userIdx, 'spawnDequeuePriority1UserTasks must run after on-demand').toBeGreaterThan(onDemandIdx);
+ expect(autoSysIdx, 'spawnDequeuePriority2AutoApproved must run after user tasks').toBeGreaterThan(userIdx);
+ expect(missionIdx, 'spawnDequeuePriority3Missions must run after auto-approved').toBeGreaterThan(autoSysIdx);
+ expect(idleIdx, 'spawnDequeuePriority4IdleReview must run after missions').toBeGreaterThan(missionIdx);
});
it('evaluateTasks orchestrates the spawnPriority* tiers in priority order', () => {
@@ -707,12 +706,13 @@ describe('cos.js source — priority + capacity invariants', () => {
const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));
// dequeueNextTask: the `if (paused) return` gate appears AFTER the on-demand
- // loop (`onDemandRequests`), and `paused` is NOT returned-on before it.
- const dqOnDemandIdx = dequeueFn.indexOf('onDemandRequests');
+ // tier (`spawnDequeuePriority0OnDemand`), and `paused` is NOT returned-on
+ // before it.
+ const dqOnDemandIdx = dequeueFn.indexOf('spawnDequeuePriority0OnDemand(ctx)');
const dqPauseGateIdx = dequeueFn.search(/if\s*\(\s*paused\s*\)\s*return/);
- expect(dqOnDemandIdx, 'dequeueNextTask must process onDemandRequests').toBeGreaterThan(-1);
+ expect(dqOnDemandIdx, 'dequeueNextTask must invoke spawnDequeuePriority0OnDemand').toBeGreaterThan(-1);
expect(dqPauseGateIdx, 'dequeueNextTask must keep an `if (paused) return` gate').toBeGreaterThan(-1);
- expect(dqPauseGateIdx, 'pause gate must come AFTER the on-demand loop').toBeGreaterThan(dqOnDemandIdx);
+ expect(dqPauseGateIdx, 'pause gate must come AFTER the on-demand tier').toBeGreaterThan(dqOnDemandIdx);
// evaluateTasks: Priority 0 runs unconditionally; Priorities 1+ are wrapped in
// an `if (!paused)` block that begins after spawnPriority0OnDemand.
@@ -727,8 +727,10 @@ describe('cos.js source — priority + capacity invariants', () => {
it('per-project cap defaults to global cap when unset', () => {
// The fallback `state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents`
// is the safety net for older state.json files that pre-date the
- // per-project cap. Both dequeueNextTask and evaluateTasks must keep it.
- const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
+ // per-project cap. dequeueNextTask's capacity tracker was extracted to
+ // `createDequeueCapacity` in cosDequeue.js (issue #2530), so the dequeue-side
+ // fallback lives there now; evaluateTasks keeps its own inline copy.
+ const dequeueFn = extractFnBody(DEQ_SRC, DEQ_SRC.indexOf('export function createDequeueCapacity'));
const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));
const pattern = /maxConcurrentAgentsPerProject\s*\|\|\s*state\.config\.maxConcurrentAgents/;
@@ -737,17 +739,21 @@ describe('cos.js source — priority + capacity invariants', () => {
});
it('idle generator is fenced by spawned===0 / tasksToSpawn.length===0', () => {
- // Pin the strict-idle gate that the replica enforces. If a refactor
- // drops either fence, idle could spawn alongside autoSystem/mission and
- // double-load the agent pool.
- const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
- // The generator engine's tiers are now decomposed into named spawnPriority*
- // helpers (issue #1082), so this gate lives in `spawnPriority4IdleReview`
- // rather than the `evaluateTasks` orchestrator body — scope to the whole
- // cosTaskGenerator module (the engine) instead of the single function.
+ // Pin the strict-idle gate. If a refactor drops either fence, idle could
+ // spawn alongside autoSystem/mission and double-load the agent pool.
+ // dequeueNextTask's idle tier (spawnDequeuePriority4IdleReview) now routes
+ // through the shared `isIdleTierEligible` predicate in cosDequeue.js
+ // (issue #2530), whose body carries the `spawned === 0` fence.
+ const idleTier = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority4IdleReview'));
+ const idlePred = extractFnBody(DEQ_SRC, DEQ_SRC.indexOf('export function isIdleTierEligible'));
+ // The generator engine's tiers are decomposed into named spawnPriority*
+ // helpers (issue #1082), so its gate lives in `spawnPriority4IdleReview`
+ // — scope to the whole cosTaskGenerator module (the engine).
const evalFn = GEN_SRC;
- expect(dequeueFn).toMatch(/spawned\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
+ expect(idleTier, 'idle tier must call the shared isIdleTierEligible predicate').toMatch(/isIdleTierEligible\(/);
+ expect(idleTier, 'idle tier must pass state.config.idleReviewEnabled into the predicate').toMatch(/idleReviewEnabled:\s*state\.config\.idleReviewEnabled/);
+ expect(idlePred, 'isIdleTierEligible must fence on spawned === 0 && idleReviewEnabled').toMatch(/spawned\s*===\s*0\s*&&\s*!!idleReviewEnabled/);
expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
});
@@ -757,17 +763,27 @@ describe('cos.js source — priority + capacity invariants', () => {
// (dequeueNextTask in cos.js, evaluateTasks in cosTaskGenerator.js) must read
// the cos mode and fence their mission / idle / auto-approved blocks on it,
// or "off"/"dry-run" leaks autonomous agents through the un-gated engine.
- const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
+ // dequeueNextTask resolves the cos mode in spawnDequeuePriority2AutoApproved
+ // and fences its mission/idle tiers through the shared eligibility predicates
+ // (issue #2530) — both still live in the cos.js module, so scope to it.
+ const dequeueSrc = COS_SRC;
// evaluateTasks resolves the mode in `resolveAutonomyBudget` and fences each
// autonomous tier inside its spawnPriority* helper (issue #1082) — both still
// live in the cosTaskGenerator module, so scope to the whole engine source.
const evalFn = GEN_SRC;
- for (const [name, fnBody] of [['dequeueNextTask', dequeueFn], ['evaluateTasks (cosTaskGenerator)', evalFn]]) {
+ for (const [name, fnBody] of [['dequeueNextTask (cos.js)', dequeueSrc], ['evaluateTasks (cosTaskGenerator)', evalFn]]) {
expect(fnBody, `${name} must resolve the cos autonomy mode`).toMatch(/getDomainMode\(\s*state\.config\s*,\s*['"]cos['"]\s*\)/);
- // The mission/idle blocks must be fenced on execute so off/dry-run skip them.
- expect(fnBody, `${name} must fence autonomous spawns on cosAutonomyMode === 'execute'`).toMatch(/cosAutonomyMode\s*===\s*['"]execute['"]/);
}
+ // evaluateTasks fences autonomous spawns inline on `cosAutonomyMode === 'execute'`.
+ expect(evalFn, `evaluateTasks must fence autonomous spawns on cosAutonomyMode === 'execute'`).toMatch(/cosAutonomyMode\s*===\s*['"]execute['"]/);
+ // dequeueNextTask's autonomous tiers gate through the shared predicates, which
+ // enforce `autonomyMode === 'execute'` in cosDequeue.js; the auto-approved tier
+ // withholds spawns unless the mode is execute (`cosAutonomyMode !== 'execute'`).
+ expect(dequeueSrc, `dequeueNextTask must gate mission/idle via the eligibility predicates`).toMatch(/isMissionTierEligible\(/);
+ expect(dequeueSrc, `dequeueNextTask must gate the idle tier via the eligibility predicate`).toMatch(/isIdleTierEligible\(/);
+ expect(dequeueSrc, `dequeueNextTask auto-approved tier must withhold spawns unless mode is execute`).toMatch(/cosAutonomyMode\s*!==\s*['"]execute['"]/);
+ expect(DEQ_SRC, `cosDequeue predicates must enforce autonomyMode === 'execute'`).toMatch(/autonomyMode\s*===\s*['"]execute['"]/);
});
it('CoS auto-run domain gate (#711) covers the scheduled-job + improvement-check timers', () => {
@@ -801,12 +817,12 @@ describe('cos.js source — priority + capacity invariants', () => {
// startup/manual `evaluateTasks` loop AND the event-driven `dequeueNextTask`
// loop (the common "Run Now" path). Pin (a) the set is declared and (b) the
// cooldown stamp is gated on it in each.
- // evaluateTasks now lives in cosTaskGenerator.js, and its Priority-0 on-demand
- // loop is the extracted `spawnPriority0OnDemand` helper (issue #1082);
- // dequeueNextTask stays monolithic in cos.js.
+ // Both engines' Priority-0 on-demand loops are now extracted helpers:
+ // `spawnPriority0OnDemand` in cosTaskGenerator.js (issue #1082) and
+ // `spawnDequeuePriority0OnDemand` in cos.js (issue #2530).
for (const { fnName, src } of [
{ fnName: 'async function spawnPriority0OnDemand', src: GEN_SRC },
- { fnName: 'async function dequeueNextTask', src: COS_SRC },
+ { fnName: 'async function spawnDequeuePriority0OnDemand', src: COS_SRC },
]) {
const fnBody = extractFnBody(src, src.indexOf(fnName));
expect(
@@ -828,7 +844,7 @@ describe('cos.js source — priority + capacity invariants', () => {
// active agent inside an `if (task)` guard after generation.
for (const { fnName, src } of [
{ fnName: 'async function spawnPriority0OnDemand', src: GEN_SRC },
- { fnName: 'async function dequeueNextTask', src: COS_SRC },
+ { fnName: 'async function spawnDequeuePriority0OnDemand', src: COS_SRC },
]) {
const fnBody = extractFnBody(src, src.indexOf(fnName));
expect(
diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.js
new file mode 100644
index 0000000000..3dbf0fef14
--- /dev/null
+++ b/server/services/cosAgentArchive.js
@@ -0,0 +1,118 @@
+/**
+ * CoS Agent Archive Module
+ *
+ * State-eviction paths: archive stale completed agents out of state.json (they
+ * 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.
+ */
+
+import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { cosEvents } from './cosEvents.js';
+import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
+import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
+import { loadAgentIndex, saveAgentIndex } from './cosAgentIndex.js';
+
+// Archive stale completed agents from state.json.
+// Completed agents are already persisted to per-agent metadata files on disk
+// (metadata.json) by completeAgent(), so removing them from state.json only
+// reduces the size of the in-memory state and the state.json file.
+export async function archiveStaleAgents() {
+ return withStateLock(async () => {
+ const state = await loadState();
+ const retentionMs = state.config.completedAgentRetentionMs ?? 86400000;
+ const cutoff = Date.now() - retentionMs;
+
+ const staleIds = Object.keys(state.agents).filter(id => {
+ const agent = state.agents[id];
+ if (agent.status !== 'completed') return false;
+ const completedAt = agent.completedAt ? new Date(agent.completedAt).getTime() : 0;
+ return completedAt > 0 && completedAt < cutoff;
+ });
+
+ if (staleIds.length === 0) return { archived: 0 };
+
+ const idx = await loadAgentIndex();
+
+ for (const id of staleIds) {
+ // Ensure agent is persisted to date-bucketed disk before removing from state
+ if (!idx.has(id)) {
+ const agent = state.agents[id];
+ const dateStr = agent.completedAt?.slice(0, 10);
+ if (!dateStr) continue;
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await ensureDir(bucketDir);
+
+ const { output, ...agentWithoutOutput } = agent;
+ const flatDir = join(AGENTS_DIR, id);
+ const targetDir = join(bucketDir, id);
+
+ if (existsSync(flatDir) && !existsSync(targetDir)) {
+ // Write metadata then move (with cross-filesystem fallback)
+ await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
+ await rename(flatDir, targetDir).catch(async () => {
+ await ensureDir(targetDir);
+ const files = await readdir(flatDir).catch(() => []);
+ for (const file of files) {
+ const content = await tryReadFile(join(flatDir, file), null);
+ if (content !== null) await writeFile(join(targetDir, file), content);
+ }
+ await rm(flatDir, { recursive: true }).catch(() => {});
+ });
+ if (!existsSync(targetDir)) continue; // Skip index update if move failed
+ } else if (!existsSync(targetDir)) {
+ await ensureDir(targetDir);
+ await atomicWrite(join(targetDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
+ }
+
+ idx.set(id, dateStr);
+ }
+
+ delete state.agents[id];
+ }
+
+ await saveState(state);
+ await saveAgentIndex();
+ console.log(`📦 Archived ${staleIds.length} stale agents from state.json (retained on disk)`);
+ cosEvents.emit('agents:changed', { action: 'auto-archive', archived: staleIds.length });
+ return { archived: staleIds.length };
+ });
+}
+
+// Clear completed agents from state, cache, and disk
+export async function clearCompletedAgents() {
+ return withStateLock(async () => {
+ const state = await loadState();
+ const idx = await loadAgentIndex();
+
+ // Remove completed agents from state
+ const stateCompleted = Object.keys(state.agents).filter(
+ id => state.agents[id].status === 'completed'
+ );
+ for (const id of stateCompleted) {
+ delete state.agents[id];
+ }
+ await saveState(state);
+
+ // Collect all unique dates from index, then remove date bucket dirs
+ const dates = new Set(idx.values());
+ const totalCleared = idx.size + stateCompleted.filter(id => !idx.has(id)).length;
+
+ const removals = [...dates].map(date => {
+ const dateDir = join(AGENTS_DIR, date);
+ return existsSync(dateDir)
+ ? rm(dateDir, { recursive: true }).catch(() => {})
+ : Promise.resolve();
+ });
+ await Promise.all(removals);
+
+ // Clear index
+ idx.clear();
+ await saveAgentIndex();
+
+ return { cleared: totalCleared };
+ });
+}
diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.js
new file mode 100644
index 0000000000..d37831121f
--- /dev/null
+++ b/server/services/cosAgentFeedback.js
@@ -0,0 +1,145 @@
+/**
+ * CoS Agent Feedback Module
+ *
+ * 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.
+ */
+
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { cosEvents, emitLog } from './cosEvents.js';
+import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
+import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';
+
+// Submit feedback for a completed agent
+export async function submitAgentFeedback(agentId, feedback) {
+ return withStateLock(async () => {
+ const state = await loadState();
+ const feedbackData = {
+ rating: feedback.rating,
+ comment: feedback.comment || null,
+ submittedAt: new Date().toISOString()
+ };
+
+ // Try state first (recently completed agents still in state)
+ if (state.agents[agentId]) {
+ const agent = state.agents[agentId];
+ if (agent.status !== 'completed') {
+ return { error: 'Can only submit feedback for completed agents' };
+ }
+ state.agents[agentId].feedback = feedbackData;
+ await saveState(state);
+
+ // Also update on-disk metadata (derive date bucket from completedAt if archived)
+ const dateBucket = agent.completedAt ? agent.completedAt.slice(0, 10) : null;
+ const agentDir = getAgentDir(agentId, dateBucket);
+ const metaPath = join(agentDir, 'metadata.json');
+ if (existsSync(metaPath)) {
+ const content = await tryReadFile(metaPath);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw) {
+ raw.feedback = feedbackData;
+ await atomicWrite(metaPath, raw).catch(() => {});
+ }
+ }
+ }
+
+ emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
+ cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
+ return { success: true, agent: state.agents[agentId] };
+ }
+
+ // Agent not in state — look up from disk via index
+ const idx = await loadAgentIndex();
+ const dateStr = idx.get(agentId);
+ if (!dateStr) return { error: 'Agent not found' };
+
+ const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
+ const content = await tryReadFile(metaPath);
+ if (!content) return { error: 'Agent not found' };
+
+ const raw = safeJSONParse(content, null);
+ if (!raw) return { error: 'Agent not found' };
+
+ raw.feedback = feedbackData;
+ await atomicWrite(metaPath, raw);
+
+ emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
+ cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
+ return { success: true, agent: { ...raw, id: agentId } };
+ });
+}
+
+// Get aggregated feedback statistics
+export async function getFeedbackStats() {
+ const state = await loadState();
+ const agents = Object.values(state.agents);
+
+ const withFeedback = agents.filter(a => a.feedback);
+ const positive = withFeedback.filter(a => a.feedback.rating === 'positive').length;
+ const negative = withFeedback.filter(a => a.feedback.rating === 'negative').length;
+ const neutral = withFeedback.filter(a => a.feedback.rating === 'neutral').length;
+
+ // Group by task type
+ const byTaskType = {};
+ withFeedback.forEach(a => {
+ const taskType = extractTaskType(a.metadata?.taskDescription);
+ if (!byTaskType[taskType]) {
+ byTaskType[taskType] = { positive: 0, negative: 0, neutral: 0, total: 0 };
+ }
+ byTaskType[taskType][a.feedback.rating]++;
+ byTaskType[taskType].total++;
+ });
+
+ // Recent feedback (last 10 with comments)
+ const recentWithComments = withFeedback
+ .filter(a => a.feedback.comment)
+ .sort((a, b) => new Date(b.feedback.submittedAt) - new Date(a.feedback.submittedAt))
+ .slice(0, 10)
+ .map(a => ({
+ agentId: a.id,
+ taskDescription: a.metadata?.taskDescription,
+ rating: a.feedback.rating,
+ comment: a.feedback.comment,
+ submittedAt: a.feedback.submittedAt
+ }));
+
+ const satisfactionRate = withFeedback.length > 0
+ ? Math.round((positive / withFeedback.length) * 100)
+ : null;
+
+ return {
+ total: withFeedback.length,
+ positive,
+ negative,
+ neutral,
+ satisfactionRate,
+ byTaskType,
+ recentWithComments
+ };
+}
+
+// Helper to extract task type from description (mirrors client-side logic)
+export function extractTaskType(description) {
+ if (!description) return 'general';
+ const d = description.toLowerCase();
+ if (d.includes('fix') || d.includes('bug') || d.includes('error') || d.includes('issue')) return 'bug-fix';
+ if (d.includes('refactor') || d.includes('clean up') || d.includes('improve') || d.includes('optimize')) return 'refactor';
+ if (d.includes('test')) return 'testing';
+ if (d.includes('document') || d.includes('readme') || d.includes('docs')) return 'documentation';
+ if (d.includes('review') || d.includes('audit')) return 'code-review';
+ if (d.includes('mobile') || d.includes('responsive')) return 'mobile-responsive';
+ if (d.includes('security') || d.includes('vulnerability')) return 'security';
+ if (d.includes('performance') || d.includes('speed')) return 'performance';
+ if (d.includes('ui') || d.includes('ux') || d.includes('design') || d.includes('style')) return 'ui-ux';
+ if (d.includes('api') || d.includes('endpoint') || d.includes('route')) return 'api';
+ if (d.includes('database') || d.includes('migration')) return 'database';
+ if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';
+ if (d.includes('investigate') || d.includes('debug')) return 'investigation';
+ if (d.includes('self-improvement') || d.includes('feature idea')) return 'self-improvement';
+ return 'feature';
+}
diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.js
new file mode 100644
index 0000000000..6f7bf3946a
--- /dev/null
+++ b/server/services/cosAgentIndex.js
@@ -0,0 +1,301 @@
+/**
+ * CoS Agent Index Module
+ *
+ * The date-bucket index + on-disk archive layout for CoS agents. Extracted from
+ * the former monolithic cosAgents.js (issue #2530) so the index/migration/archive
+ * 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.
+ */
+
+import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { AGENTS_DIR } from './cosState.js';
+import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { repairCodexTaskSummary } from './codexSummaryRepair.js';
+
+const INDEX_FILE = join(AGENTS_DIR, 'index.json');
+
+// Lightweight index mapping agentId → YYYY-MM-DD date bucket (~50KB vs 16MB full cache)
+// Lazy-loaded from data/cos/agents/index.json on first access
+let agentIndex = null;
+let agentIndexPromise = null;
+
+// Load agent index from disk (lazy init, singleton promise prevents concurrent migrations)
+export async function loadAgentIndex() {
+ if (agentIndex) return agentIndex;
+ if (agentIndexPromise) return agentIndexPromise;
+
+ agentIndexPromise = (async () => {
+ if (!existsSync(AGENTS_DIR)) {
+ await ensureDir(AGENTS_DIR);
+ }
+
+ if (existsSync(INDEX_FILE)) {
+ const content = await tryReadFile(INDEX_FILE);
+ const parsed = safeJSONParse(content ?? '{}', {});
+ agentIndex = new Map(Object.entries(parsed));
+ console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
+ } else {
+ // No index yet — run migration from flat dirs to date buckets
+ agentIndex = await migrateAgentsToDateBuckets();
+ }
+
+ return agentIndex;
+ })().catch(err => {
+ agentIndexPromise = null;
+ throw err;
+ });
+
+ return agentIndexPromise;
+}
+
+// Persist agent index to disk via the shared atomicWrite helper (temp file + rename,
+// with Windows backup-swap fallback). Without atomic semantics a mid-write crash
+// truncates index.json and on next boot the date-bucket migration would silently
+// re-run (or worse, drop already-archived agents from the lookup).
+export async function saveAgentIndex() {
+ if (!agentIndex) return;
+ const obj = Object.fromEntries(agentIndex);
+ await atomicWrite(INDEX_FILE, obj).catch(err => {
+ console.error(`❌ Failed to save agent index: ${err.message}`);
+ });
+}
+
+/**
+ * Merge a batch of {agentId, date} pairs into the agent index. Used by the
+ * peer-sync CoS-history receiver (#1650): after pulling a peer's completed-agent
+ * archives onto local disk, the date-bucket index must learn the new agentIds so
+ * the history UI lists them. Idempotent union — only valid YYYY-MM-DD-bucketed
+ * pairs are accepted. Returns the number of NEW entries added.
+ *
+ * A pre-existing agentId is treated as already-owned and is NEVER overwritten,
+ * even when the incoming `date` differs: agent ids are generated independently
+ * per instance, so an id collision (or a restored local archive) must not be able
+ * to repoint a local agent's bucket at a peer's date — that would make
+ * `getAgent()` read the wrong (or non-existent) directory and hide the local
+ * agent's own history. First write wins; the local entry is authoritative.
+ */
+export async function addAgentArchivesToIndex(pairs) {
+ if (!Array.isArray(pairs) || pairs.length === 0) return 0;
+ const idx = await loadAgentIndex();
+ let added = 0;
+ for (const pair of pairs) {
+ const agentId = pair?.agentId;
+ const date = pair?.date;
+ if (typeof agentId !== 'string' || !agentId) continue;
+ if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
+ if (idx.has(agentId)) continue; // already owned — never overwrite (id is authoritative)
+ idx.set(agentId, date);
+ added += 1;
+ }
+ if (added > 0) await saveAgentIndex();
+ return added;
+}
+
+// Resolve the correct directory for an agent (running = flat, completed = date bucket)
+export function getAgentDir(agentId, dateString) {
+ if (dateString) return join(AGENTS_DIR, dateString, agentId);
+ // Check index for date bucket
+ const date = agentIndex?.get(agentId);
+ if (date) return join(AGENTS_DIR, date, agentId);
+ // Fallback to flat dir (running agents or pre-migration)
+ return join(AGENTS_DIR, agentId);
+}
+
+// Migrate flat agent-* directories into YYYY-MM-DD date buckets
+// Runs once when index.json doesn't exist. Idempotent — no-op if already migrated.
+async function migrateAgentsToDateBuckets() {
+ const index = new Map();
+
+ if (!existsSync(AGENTS_DIR)) {
+ await ensureDir(AGENTS_DIR);
+ await atomicWrite(INDEX_FILE, {});
+ console.log('📂 Created empty agent index (no agents to migrate)');
+ return index;
+ }
+
+ const entries = await readdir(AGENTS_DIR, { withFileTypes: true });
+
+ // Also scan existing date-bucket dirs to include them in the index
+ const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !dateDirPattern.test(entry.name)) continue;
+ const dateStr = entry.name;
+ const dateDir = join(AGENTS_DIR, dateStr);
+ const agentDirs = await readdir(dateDir, { withFileTypes: true }).catch(() => []);
+ for (const agentEntry of agentDirs) {
+ if (agentEntry.isDirectory() && agentEntry.name.startsWith('agent-')) {
+ index.set(agentEntry.name, dateStr);
+ }
+ }
+ }
+
+ // Find flat agent-* dirs that need migration
+ const flatAgentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
+
+ if (flatAgentDirs.length === 0) {
+ await atomicWrite(INDEX_FILE, Object.fromEntries(index));
+ console.log(`📂 Agent index built: ${index.size} entries (no flat dirs to migrate)`);
+ return index;
+ }
+
+ console.log(`📦 Migrating ${flatAgentDirs.length} agents into date buckets...`);
+ let migrated = 0;
+ let skipped = 0;
+
+ for (const entry of flatAgentDirs) {
+ const agentId = entry.name;
+ const agentDir = join(AGENTS_DIR, agentId);
+ const metaPath = join(agentDir, 'metadata.json');
+
+ let dateStr = null;
+
+ // Try to get date from metadata
+ if (existsSync(metaPath)) {
+ const content = await tryReadFile(metaPath);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw?.completedAt) {
+ dateStr = raw.completedAt.slice(0, 10); // YYYY-MM-DD
+ }
+ }
+ }
+
+ // Fallback: directory mtime
+ if (!dateStr) {
+ const dirStat = await stat(agentDir).catch(() => null);
+ if (dirStat?.mtime) {
+ dateStr = dirStat.mtime.toISOString().slice(0, 10);
+ }
+ }
+
+ if (!dateStr) {
+ console.log(`⚠️ Cannot determine date for ${agentId}, skipping`);
+ skipped++;
+ continue;
+ }
+
+ // Move into date bucket
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await ensureDir(bucketDir);
+ const targetDir = join(bucketDir, agentId);
+
+ // If target already exists (partial previous migration), skip
+ if (existsSync(targetDir)) {
+ index.set(agentId, dateStr);
+ migrated++;
+ continue;
+ }
+
+ await rename(agentDir, targetDir).catch(async (renameErr) => {
+ // rename can fail across filesystems — fall back to copy+delete
+ console.log(`⚠️ Rename failed for ${agentId}, using copy: ${renameErr.message}`);
+ try {
+ await ensureDir(targetDir);
+ const files = await readdir(agentDir);
+ for (const file of files) {
+ const content = await readFile(join(agentDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(agentDir, { recursive: true });
+ } catch (copyErr) {
+ console.error(`❌ Copy fallback failed for ${agentId}: ${copyErr.message}`);
+ // Clean up partially-created target to avoid skipping on next startup
+ await rm(targetDir, { recursive: true, force: true }).catch(() => {});
+ throw copyErr;
+ }
+ });
+
+ index.set(agentId, dateStr);
+ migrated++;
+ }
+
+ // Persist index
+ await atomicWrite(INDEX_FILE, Object.fromEntries(index));
+ const uniqueDates = new Set(index.values()).size;
+ const parts = [`📦 Migrated ${migrated} agents into date buckets (${uniqueDates} unique dates)`];
+ if (skipped > 0) parts.push(`skipped ${skipped} undatable`);
+ console.log(parts.join(', '));
+
+ return index;
+}
+
+// Prune agent archive date buckets older than retentionDays (default 90).
+// Removes directories + their index entries. Runs after migration on startup.
+export async function pruneOldAgentArchives(retentionDays = 90) {
+ const idx = await loadAgentIndex();
+ if (!idx || idx.size === 0) return;
+
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - retentionDays);
+ const cutoffStr = cutoff.toISOString().slice(0, 10);
+
+ const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
+ const entries = await readdir(AGENTS_DIR, { withFileTypes: true }).catch(() => []);
+ const oldDates = entries
+ .filter(e => e.isDirectory() && dateDirPattern.test(e.name) && e.name < cutoffStr)
+ .map(e => e.name);
+
+ if (oldDates.length === 0) return;
+
+ for (const dateStr of oldDates) {
+ await rm(join(AGENTS_DIR, dateStr), { recursive: true }).catch(() => {});
+ }
+
+ // Remove index entries for all old dates in a single pass
+ const oldDateSet = new Set(oldDates);
+ let pruned = 0;
+ for (const [agentId, date] of idx.entries()) {
+ if (oldDateSet.has(date)) { idx.delete(agentId); pruned++; }
+ }
+
+ await saveAgentIndex();
+ console.log(`🗑️ Pruned ${pruned} archived agents older than ${retentionDays} days (${oldDates.length} date buckets)`);
+}
+
+// Get available agent date buckets with counts, sorted descending
+export async function getAgentDates() {
+ const idx = await loadAgentIndex();
+ const dateCounts = {};
+ for (const date of idx.values()) {
+ dateCounts[date] = (dateCounts[date] || 0) + 1;
+ }
+ return Object.entries(dateCounts)
+ .map(([date, count]) => ({ date, count }))
+ .sort((a, b) => b.date.localeCompare(a.date));
+}
+
+// Get completed agents for a specific date bucket
+export async function getAgentsByDate(date) {
+ const dateDir = join(AGENTS_DIR, date);
+ if (!existsSync(dateDir)) return [];
+
+ const entries = await readdir(dateDir, { withFileTypes: true });
+ const agentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
+ const agents = [];
+
+ // Batch reads in chunks of 50 to avoid fd exhaustion on large date buckets
+ const BATCH_SIZE = 50;
+ for (let i = 0; i < agentDirs.length; i += BATCH_SIZE) {
+ const batch = agentDirs.slice(i, i + BATCH_SIZE);
+ const reads = batch.map(async (entry) => {
+ const metaPath = join(dateDir, entry.name, 'metadata.json');
+ const content = await tryReadFile(metaPath);
+ if (!content) return;
+ const raw = safeJSONParse(content, null);
+ if (!raw) return;
+ const id = raw.id || raw.agentId || entry.name;
+ const { output, ...rest } = raw;
+ const agent = { ...rest, id, status: raw.status || 'completed' };
+ const repaired = await repairCodexTaskSummary(join(dateDir, entry.name), agent);
+ if (repaired) agent.metadata = { ...agent.metadata, taskSummary: repaired };
+ agents.push(agent);
+ });
+ await Promise.allSettled(reads);
+ }
+
+ return agents.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
+}
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
new file mode 100644
index 0000000000..939763c0bc
--- /dev/null
+++ b/server/services/cosAgentLifecycle.js
@@ -0,0 +1,582 @@
+/**
+ * CoS Agent Lifecycle Module
+ *
+ * Agent register/update/complete/output/terminate/pause/kill/BTW/zombie-cleanup
+ * and single-agent reads. Extracted from the former monolithic cosAgents.js
+ * (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.
+ */
+
+import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { cosEvents } from './cosEvents.js';
+import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
+import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { recordDomainUsage } from './domainUsage.js';
+import { repairCodexTaskSummary } from './codexSummaryRepair.js';
+import { loadAgentIndex, saveAgentIndex, getAgentDir } from './cosAgentIndex.js';
+
+export async function registerAgent(agentId, taskId, metadata = {}) {
+ return withStateLock(async () => {
+ const state = await loadState();
+
+ state.agents[agentId] = {
+ id: agentId,
+ taskId,
+ status: 'running',
+ startedAt: new Date().toISOString(),
+ metadata,
+ output: []
+ };
+
+ state.stats.agentsSpawned++;
+ await saveState(state);
+
+ cosEvents.emit('agent:spawned', state.agents[agentId]);
+ return state.agents[agentId];
+ });
+}
+
+export async function updateAgent(agentId, updates) {
+ return withStateLock(async () => {
+ const state = await loadState();
+
+ if (!state.agents[agentId]) {
+ return null;
+ }
+
+ // Merge metadata if present in updates
+ if (updates.metadata) {
+ state.agents[agentId] = {
+ ...state.agents[agentId],
+ ...updates,
+ metadata: { ...state.agents[agentId].metadata, ...updates.metadata }
+ };
+ } else {
+ state.agents[agentId] = { ...state.agents[agentId], ...updates };
+ }
+ await saveState(state);
+
+ cosEvents.emit('agent:updated', state.agents[agentId]);
+ return state.agents[agentId];
+ });
+}
+
+export async function completeAgent(agentId, result = {}) {
+ const completed = await withStateLock(async () => {
+ const state = await loadState();
+
+ if (!state.agents[agentId]) {
+ return null;
+ }
+
+ state.agents[agentId] = {
+ ...state.agents[agentId],
+ status: 'completed',
+ completedAt: new Date().toISOString(),
+ // Success-criteria validation verdict (issue #2344): normalize to an
+ // explicit null sentinel when a completion path didn't declare/evaluate a
+ // machine-checkable criterion, so persisted telemetry never conflates
+ // "not declared" with "declared and failed" (false). Distinct from
+ // result.success (the runner's exit-code verdict).
+ result: { validationPassed: null, ...result },
+ };
+
+ if (result.success) {
+ state.stats.tasksCompleted++;
+ } else {
+ state.stats.errors = (state.stats.errors || 0) + 1;
+ }
+
+ await saveState(state);
+ // `agent:completed` is intentionally emitted later, after the domain-usage
+ // ledger is updated (see the recordDomainUsage block below, #1683). Do NOT
+ // move it back here. `agent:updated` carries no scheduling side effect, so it
+ // stays inside the lock.
+ cosEvents.emit('agent:updated', state.agents[agentId]);
+
+ // Determine date bucket from completedAt
+ const dateStr = state.agents[agentId].completedAt.slice(0, 10);
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await ensureDir(bucketDir);
+
+ // Write metadata to flat dir first (may already have output.txt/prompt.txt there)
+ const flatDir = join(AGENTS_DIR, agentId);
+ if (!existsSync(flatDir)) {
+ await ensureDir(flatDir);
+ }
+ const { output: _output, ...agentWithoutOutput } = state.agents[agentId];
+ await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput);
+
+ // Move entire agent dir into date bucket (atomic on same filesystem)
+ const targetDir = join(bucketDir, agentId);
+ if (!existsSync(targetDir)) {
+ await rename(flatDir, targetDir).catch(async () => {
+ // Fallback for cross-filesystem: copy files then remove
+ await ensureDir(targetDir);
+ const files = await readdir(flatDir);
+ for (const file of files) {
+ const content = await readFile(join(flatDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(flatDir, { recursive: true });
+ });
+ }
+
+ // Update index
+ const idx = await loadAgentIndex();
+ idx.set(agentId, dateStr);
+ await saveAgentIndex();
+
+ return state.agents[agentId];
+ });
+
+ // Daily CoS budget accounting (#711): count only AUTONOMOUS runs (non-user
+ // tasks) — the same set the CoS auto-run gate withholds when over budget —
+ // toward the domain's actions/minutes ledger. Recorded outside the state lock
+ // (separate ledger file + write tail) so it never serializes against state.json.
+ //
+ // This MUST land before the `agent:completed` emit below: that event's handler
+ // schedules `dequeueNextTask()`, whose daily action-budget gate reads this
+ // ledger. Recording first ensures the gate counts the just-finished action, so
+ // a perpetual drain can't admit one spawn past `maxActionsPerDay` at the
+ // boundary (#1683).
+ if (completed?.metadata?.taskType && completed.metadata.taskType !== 'user') {
+ await recordDomainUsage('cos', { actions: 1, ms: Number(result.duration) || 0 })
+ .catch(err => console.error(`❌ Failed to record CoS budget usage for ${agentId}: ${err.message}`));
+ }
+
+ // Emit now that the ledger reflects this action (#1683). Fires for every
+ // completed agent, matching prior behavior — only the timing moved.
+ if (completed) {
+ cosEvents.emit('agent:completed', completed);
+ }
+
+ return completed;
+}
+
+export async function appendAgentOutput(agentId, line) {
+ const result = await withStateLock(async () => {
+ const state = await loadState();
+
+ if (!state.agents[agentId]) {
+ return null;
+ }
+
+ state.agents[agentId].output.push({
+ timestamp: new Date().toISOString(),
+ line
+ });
+
+ // Trim to last 1000 lines in state
+ if (state.agents[agentId].output.length > 1000) {
+ state.agents[agentId].output = state.agents[agentId].output.slice(-1000);
+ }
+
+ await saveState(state);
+ return state.agents[agentId];
+ });
+
+ if (result) {
+ cosEvents.emit('agent:output', { agentId, line });
+ }
+
+ return result;
+}
+
+// Batched variant — single state load+save for many lines. Used by the TUI
+// spawner to avoid write-amplification on chatty TUIs that emit hundreds of
+// lines per second; per-line appendAgentOutput would re-load and re-save the
+// entire state JSON for every line.
+export async function appendAgentOutputLines(agentId, lines) {
+ if (!Array.isArray(lines) || lines.length === 0) return null;
+ const result = await withStateLock(async () => {
+ const state = await loadState();
+ if (!state.agents[agentId]) return null;
+ const timestamp = new Date().toISOString();
+ for (const line of lines) {
+ state.agents[agentId].output.push({ timestamp, line });
+ }
+ if (state.agents[agentId].output.length > 1000) {
+ state.agents[agentId].output = state.agents[agentId].output.slice(-1000);
+ }
+ await saveState(state);
+ return state.agents[agentId];
+ });
+
+ if (result) {
+ for (const line of lines) {
+ cosEvents.emit('agent:output', { agentId, line });
+ }
+ }
+
+ return result;
+}
+
+// Debounce window for batching streamed agent output to state. A chatty
+// producer (CoS Runner stream events, non-stream CLI stdout) can emit dozens
+// of lines/sec; without batching, each line round-trips a full state
+// load+save (see appendAgentOutput). 250ms is invisible to the live tail but
+// cuts state I/O by 1-2 orders of magnitude. Matches OUTPUT_FLUSH_INTERVAL_MS
+// in agentTuiSpawning.js.
+const OUTPUT_FLUSH_INTERVAL_MS = 250;
+
+// Debounced per-agent output batcher. Wraps appendAgentOutputLines with a
+// ~250ms flush window so a hot streaming producer triggers one state load+save
+// per window instead of per line — the write-amplification guard documented in
+// CLAUDE.md ("High-frequency state writes must batch"). The TUI spawner rolls
+// its own equivalent inline because it co-flushes an output.txt appendFile in
+// the same batch; producers that only need the state write should use this.
+//
+// Callers MUST `await flush()` in their finish/cleanup path before the
+// completion event so the final lines land before the agent is marked done.
+export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_INTERVAL_MS } = {}) {
+ let pending = [];
+ let timer = null;
+ let flushing = null;
+
+ const drain = async () => {
+ if (timer) { clearTimeout(timer); timer = null; }
+ if (pending.length === 0) return;
+ const batch = pending;
+ pending = [];
+ // Swallow+log state-write failures so neither the debounced timer nor a
+ // caller's `await flush()` ever rejects — this runs in child-process /
+ // timer callbacks where an uncaught throw would crash Node (CLAUDE.md "No
+ // try/catch" exception). The authoritative transcript lives in output.txt;
+ // a dropped live-tail batch is non-fatal. Mirrors the TUI spawner's
+ // `.catch(() => {})` on its own batched append.
+ await appendAgentOutputLines(agentId, batch).catch((err) => {
+ console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`);
+ });
+ };
+
+ const schedule = () => {
+ if (timer || flushing) return;
+ timer = setTimeout(() => {
+ timer = null;
+ flushing = drain().finally(() => {
+ flushing = null;
+ // Catch lines that arrived during the in-flight drain — without this a
+ // producer that goes quiet right after the timer fires strands its last
+ // batch in `pending` until flush().
+ if (pending.length > 0) schedule();
+ });
+ }, intervalMs);
+ };
+
+ return {
+ push(lineOrLines) {
+ if (Array.isArray(lineOrLines)) {
+ if (lineOrLines.length === 0) return;
+ pending.push(...lineOrLines);
+ } else {
+ pending.push(lineOrLines);
+ }
+ schedule();
+ },
+ // Wait for any in-flight drain, then fully empty `pending`. A push can race
+ // in during an awaited drain, so loop until nothing is left rather than
+ // draining a fixed number of times (which could strand a late line to the
+ // debounce timer). flush() is only called once the producer has stopped, so
+ // the loop terminates promptly.
+ async flush() {
+ if (flushing) await flushing;
+ while (pending.length > 0) await drain();
+ },
+ };
+}
+
+// Get all agents from in-memory state (includes running and recently completed; archived agents loaded via getAgentsByDate)
+export async function getAgents() {
+ const state = await loadState();
+ return Object.values(state.agents);
+}
+
+// Get agent by ID with full output from file
+export async function getAgent(agentId) {
+ const state = await loadState();
+ let agent = state.agents[agentId];
+
+ // Fall back to disk metadata via index if not in state
+ if (!agent) {
+ const idx = await loadAgentIndex();
+ const dateStr = idx.get(agentId);
+ if (dateStr) {
+ const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
+ const content = await tryReadFile(metaPath);
+ if (content) {
+ const raw = safeJSONParse(content, null);
+ if (raw) {
+ const { output, ...rest } = raw;
+ agent = { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
+ }
+ }
+ }
+ }
+ if (!agent) return null;
+
+ // Completed agents live in date buckets; paused agents remain in the flat
+ // agent dir but should still expose their preserved full transcript.
+ if (agent.status === 'completed' || agent.status === 'paused') {
+ const dateStr = agent.status === 'completed' ? agent.completedAt?.slice(0, 10) : null;
+ const agentDir = dateStr ? getAgentDir(agentId, dateStr) : getAgentDir(agentId);
+ const repaired = await repairCodexTaskSummary(agentDir, agent);
+ if (repaired) agent = { ...agent, metadata: { ...agent.metadata, taskSummary: repaired } };
+ const outputFile = join(agentDir, 'output.txt');
+ if (existsSync(outputFile)) {
+ const fullOutput = await readFile(outputFile, 'utf-8');
+ const lines = fullOutput.split('\n').filter(line => line.trim());
+ const timestamp = agent.completedAt || agent.pausedAt;
+ return {
+ ...agent,
+ output: lines.map(line => ({ line, timestamp }))
+ };
+ }
+ }
+
+ return agent;
+}
+
+// Read the prompt that was sent to an agent at spawn time.
+// Used by the AgentCard UI to let the user inspect what was pasted into the
+// TUI / sent to the CLI so the prompt can be iterated on.
+export async function getAgentPrompt(agentId) {
+ const state = await loadState();
+ const agent = state.agents[agentId];
+ if (!agent) return { error: 'Agent not found' };
+ const agentDir = getAgentDir(agentId, agent.archiveDate);
+ const promptPath = join(agentDir, 'prompt.txt');
+ if (!existsSync(promptPath)) return { error: 'Prompt file not found' };
+ const prompt = await readFile(promptPath, 'utf8');
+ return { prompt, bytes: prompt.length };
+}
+
+// Terminate an agent (will be handled by spawner)
+export async function terminateAgent(agentId) {
+ // Emit event to kill the process FIRST
+ cosEvents.emit('agent:terminate', agentId);
+ // The spawner will handle marking the agent as completed after termination
+ return { success: true, agentId };
+}
+
+// Pause an agent without completing its task or cleaning up its worktree.
+export async function pauseAgent(agentId, reason = null) {
+ const { pauseAgent: pauseAgentFromSpawner } = await import('./subAgentSpawner.js');
+ return pauseAgentFromSpawner(agentId, reason);
+}
+
+// Force kill an agent with SIGKILL (immediate, no graceful shutdown)
+export async function killAgent(agentId) {
+ const { killAgent: killAgentFromSpawner } = await import('./subAgentSpawner.js');
+ return killAgentFromSpawner(agentId);
+}
+
+// Send a BTW (additional context) message to a running agent.
+//
+// BTW is only supported for Claude Code TUI agents — the message gets
+// bracket-pasted directly into the live PTY session as if the user typed it
+// themselves. The legacy BTW.md path is gone: it required headless agents to
+// poll a file mid-run, which most CLIs (codex / antigravity / LM Studio) don't do
+// reliably anyway, and the indirection had to be reflected in the prompt with
+// a brittle "check this file" instruction. Other TUI kinds (codex, antigravity)
+// don't honor bracketed-paste in the same way, so they're not eligible
+// either.
+export async function sendBtwToAgent(agentId, message) {
+ const agentInfo = await withStateLock(async () => {
+ const state = await loadState();
+ const agent = state.agents[agentId];
+ if (!agent) return { error: 'Agent not found' };
+ if (agent.status !== 'running') return { error: 'Agent is not running' };
+ if (agent.metadata?.executionMode !== 'tui') {
+ return { error: 'BTW is only supported for Claude Code TUI agents.' };
+ }
+ if (agent.metadata?.tuiKind !== 'claude') {
+ return { error: `BTW is only supported for Claude Code TUI agents (this agent runs ${agent.metadata.tuiKind || 'an unknown TUI'}).` };
+ }
+ if (!agent.metadata?.tuiSessionId) {
+ return { error: 'Agent has no attached TUI session' };
+ }
+ return { tuiSessionId: agent.metadata.tuiSessionId };
+ });
+
+ if (agentInfo.error) return agentInfo;
+
+ const shellService = await import('./shell.js');
+ if (!shellService.getSession(agentInfo.tuiSessionId)) {
+ return { error: 'TUI session is no longer alive' };
+ }
+ // Bracketed-paste + delayed Enter, mirroring the initial prompt paste in
+ // agentTuiSpawning.js: Claude Code commits the paste buffer before the
+ // submit arrives, so multi-line messages land as a single paste event.
+ shellService.writeToSession(agentInfo.tuiSessionId, `\x1b[200~${message}\x1b[201~`);
+ setTimeout(() => {
+ try {
+ // Re-check session liveness: the TUI session may have died in the 400ms window.
+ if (shellService.getSession(agentInfo.tuiSessionId)) {
+ shellService.writeToSession(agentInfo.tuiSessionId, '\r');
+ }
+ } catch (err) {
+ console.error(`❌ [cosAgents] BTW delayed Enter failed for session ${agentInfo.tuiSessionId}: ${err.message}`);
+ }
+ }, 400);
+
+ // Track in agent state (cap at 50 messages)
+ const timestamp = new Date().toISOString();
+ await withStateLock(async () => {
+ const state = await loadState();
+ if (!state.agents[agentId]) return;
+ if (!state.agents[agentId].btwMessages) {
+ state.agents[agentId].btwMessages = [];
+ }
+ state.agents[agentId].btwMessages.push({ message, timestamp });
+ if (state.agents[agentId].btwMessages.length > 50) {
+ state.agents[agentId].btwMessages = state.agents[agentId].btwMessages.slice(-50);
+ }
+ await saveState(state);
+ });
+
+ cosEvents.emit('agent:btw', { agentId, message, timestamp });
+ return { success: true, delivered: 'tui-paste', tuiSessionId: agentInfo.tuiSessionId };
+}
+
+// Get process stats for an agent (CPU, memory)
+export async function getAgentProcessStats(agentId) {
+ const { getAgentProcessStats: getStatsFromSpawner } = await import('./subAgentSpawner.js');
+ return getStatsFromSpawner(agentId);
+}
+
+// Check if a PID is still running
+async function isPidAlive(pid) {
+ if (!pid) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Cleanup zombie agents - agents marked as running but whose process is dead
+export async function cleanupZombieAgents() {
+ // Check local tracking maps (read from the side-effect-free state module, not
+ // subAgentSpawner — avoids pulling in the heavier orchestrator just to read the maps).
+ const { getActiveAgentIds } = await import('./agentState.js');
+ const activeIds = getActiveAgentIds();
+
+ // Also check with the CoS runner for agents it's actively tracking
+ const { getActiveAgentsFromRunner } = await import('./cosRunnerClient.js');
+ const runnerAgents = await getActiveAgentsFromRunner().catch(() => []);
+ const runnerAgentIds = new Set(runnerAgents.map(a => a.id));
+
+ return withStateLock(async () => {
+ const state = await loadState();
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');
+ const cleaned = [];
+
+ for (const agent of runningAgents) {
+ // Skip if tracked in local maps or runner
+ if (activeIds.includes(agent.id) || runnerAgentIds.has(agent.id)) {
+ continue;
+ }
+
+ // If agent has a PID, verify the process is actually dead
+ if (agent.pid) {
+ const alive = await isPidAlive(agent.pid);
+ if (alive) continue;
+ } else {
+ // No PID yet - agent might still be initializing
+ // Give it a 30 second grace period before marking as zombie
+ const startedAt = agent.startedAt ? new Date(agent.startedAt).getTime() : 0;
+ const ageMs = Date.now() - startedAt;
+ if (ageMs < 30000) continue;
+ }
+
+ // Agent is not tracked anywhere and process is dead — it's a zombie
+ console.log(`🧟 Zombie agent detected: ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
+ state.agents[agent.id] = {
+ ...agent,
+ status: 'completed',
+ completedAt: new Date().toISOString(),
+ result: { success: false, error: 'Agent process terminated unexpectedly' }
+ };
+ cleaned.push(agent.id);
+ }
+
+ if (cleaned.length > 0) {
+ await saveState(state);
+
+ // Persist zombie-cleaned agents to date-bucketed dirs and update index
+ const idx = await loadAgentIndex();
+ for (const agentId of cleaned) {
+ const agent = state.agents[agentId];
+ const dateStr = agent.completedAt?.slice(0, 10);
+ if (!dateStr) continue;
+ const bucketDir = join(AGENTS_DIR, dateStr);
+ await ensureDir(bucketDir);
+
+ const flatDir = join(AGENTS_DIR, agentId);
+ const { output, ...agentWithoutOutput } = agent;
+
+ // Ensure metadata is written before move
+ if (!existsSync(flatDir)) await ensureDir(flatDir);
+ await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
+
+ // Move to date bucket
+ const targetDir = join(bucketDir, agentId);
+ if (!existsSync(targetDir)) {
+ await rename(flatDir, targetDir).catch(async () => {
+ await ensureDir(targetDir);
+ const files = await readdir(flatDir);
+ for (const file of files) {
+ const content = await readFile(join(flatDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(flatDir, { recursive: true });
+ });
+ }
+
+ idx.set(agentId, dateStr);
+ }
+ await saveAgentIndex();
+
+ console.log(`🧹 Cleaned up ${cleaned.length} zombie agents: ${cleaned.join(', ')}`);
+ cosEvents.emit('agents:changed', { action: 'zombie-cleanup', cleaned });
+ }
+
+ return { cleaned, count: cleaned.length };
+ });
+}
+
+// Delete a single agent from state and disk
+export async function deleteAgent(agentId) {
+ return withStateLock(async () => {
+ const state = await loadState();
+ const idx = await loadAgentIndex();
+
+ const inState = !!state.agents[agentId];
+ const inIndex = idx.has(agentId);
+ if (!inState && !inIndex) {
+ return { error: 'Agent not found' };
+ }
+
+ delete state.agents[agentId];
+ await saveState(state);
+
+ // Remove from disk (date-bucketed or flat)
+ const agentDir = getAgentDir(agentId);
+ if (existsSync(agentDir)) {
+ await rm(agentDir, { recursive: true }).catch(() => {});
+ }
+
+ // Remove from index
+ idx.delete(agentId);
+ await saveAgentIndex();
+
+ cosEvents.emit('agents:changed', { action: 'deleted', agentId });
+ return { success: true, agentId };
+ });
+}
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 1c7c4b4ea0..3e7708f877 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -1,1093 +1,18 @@
/**
- * CoS Agents Module
+ * CoS Agents Module (barrel)
*
- * Agent lifecycle management extracted from cos.js.
- * Handles agent registration, state tracking, output capture,
- * date-bucketed archival, zombie cleanup, feedback, and index management.
- */
-
-import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';
-import { existsSync } from 'fs';
-import { join } from 'path';
-import { cosEvents, emitLog } from './cosEvents.js';
-import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
-import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
-import { recordDomainUsage } from './domainUsage.js';
-import { repairCodexTaskSummary } from './codexSummaryRepair.js';
-
-const INDEX_FILE = join(AGENTS_DIR, 'index.json');
-
-// Lightweight index mapping agentId → YYYY-MM-DD date bucket (~50KB vs 16MB full cache)
-// Lazy-loaded from data/cos/agents/index.json on first access
-let agentIndex = null;
-let agentIndexPromise = null;
-
-// Load agent index from disk (lazy init, singleton promise prevents concurrent migrations)
-export async function loadAgentIndex() {
- if (agentIndex) return agentIndex;
- if (agentIndexPromise) return agentIndexPromise;
-
- agentIndexPromise = (async () => {
- if (!existsSync(AGENTS_DIR)) {
- await ensureDir(AGENTS_DIR);
- }
-
- if (existsSync(INDEX_FILE)) {
- const content = await tryReadFile(INDEX_FILE);
- const parsed = safeJSONParse(content ?? '{}', {});
- agentIndex = new Map(Object.entries(parsed));
- console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
- } else {
- // No index yet — run migration from flat dirs to date buckets
- agentIndex = await migrateAgentsToDateBuckets();
- }
-
- return agentIndex;
- })().catch(err => {
- agentIndexPromise = null;
- throw err;
- });
-
- return agentIndexPromise;
-}
-
-// Persist agent index to disk via the shared atomicWrite helper (temp file + rename,
-// with Windows backup-swap fallback). Without atomic semantics a mid-write crash
-// truncates index.json and on next boot the date-bucket migration would silently
-// re-run (or worse, drop already-archived agents from the lookup).
-async function saveAgentIndex() {
- if (!agentIndex) return;
- const obj = Object.fromEntries(agentIndex);
- await atomicWrite(INDEX_FILE, obj).catch(err => {
- console.error(`❌ Failed to save agent index: ${err.message}`);
- });
-}
-
-/**
- * Merge a batch of {agentId, date} pairs into the agent index. Used by the
- * peer-sync CoS-history receiver (#1650): after pulling a peer's completed-agent
- * archives onto local disk, the date-bucket index must learn the new agentIds so
- * the history UI lists them. Idempotent union — only valid YYYY-MM-DD-bucketed
- * pairs are accepted. Returns the number of NEW entries added.
+ * 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:
*
- * A pre-existing agentId is treated as already-owned and is NEVER overwritten,
- * even when the incoming `date` differs: agent ids are generated independently
- * per instance, so an id collision (or a restored local archive) must not be able
- * to repoint a local agent's bucket at a peer's date — that would make
- * `getAgent()` read the wrong (or non-existent) directory and hide the local
- * agent's own history. First write wins; the local entry is authoritative.
+ * - 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 async function addAgentArchivesToIndex(pairs) {
- if (!Array.isArray(pairs) || pairs.length === 0) return 0;
- const idx = await loadAgentIndex();
- let added = 0;
- for (const pair of pairs) {
- const agentId = pair?.agentId;
- const date = pair?.date;
- if (typeof agentId !== 'string' || !agentId) continue;
- if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
- if (idx.has(agentId)) continue; // already owned — never overwrite (id is authoritative)
- idx.set(agentId, date);
- added += 1;
- }
- if (added > 0) await saveAgentIndex();
- return added;
-}
-
-// Resolve the correct directory for an agent (running = flat, completed = date bucket)
-function getAgentDir(agentId, dateString) {
- if (dateString) return join(AGENTS_DIR, dateString, agentId);
- // Check index for date bucket
- const date = agentIndex?.get(agentId);
- if (date) return join(AGENTS_DIR, date, agentId);
- // Fallback to flat dir (running agents or pre-migration)
- return join(AGENTS_DIR, agentId);
-}
-
-// Migrate flat agent-* directories into YYYY-MM-DD date buckets
-// Runs once when index.json doesn't exist. Idempotent — no-op if already migrated.
-async function migrateAgentsToDateBuckets() {
- const index = new Map();
-
- if (!existsSync(AGENTS_DIR)) {
- await ensureDir(AGENTS_DIR);
- await atomicWrite(INDEX_FILE, {});
- console.log('📂 Created empty agent index (no agents to migrate)');
- return index;
- }
-
- const entries = await readdir(AGENTS_DIR, { withFileTypes: true });
-
- // Also scan existing date-bucket dirs to include them in the index
- const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
- for (const entry of entries) {
- if (!entry.isDirectory() || !dateDirPattern.test(entry.name)) continue;
- const dateStr = entry.name;
- const dateDir = join(AGENTS_DIR, dateStr);
- const agentDirs = await readdir(dateDir, { withFileTypes: true }).catch(() => []);
- for (const agentEntry of agentDirs) {
- if (agentEntry.isDirectory() && agentEntry.name.startsWith('agent-')) {
- index.set(agentEntry.name, dateStr);
- }
- }
- }
-
- // Find flat agent-* dirs that need migration
- const flatAgentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
-
- if (flatAgentDirs.length === 0) {
- await atomicWrite(INDEX_FILE, Object.fromEntries(index));
- console.log(`📂 Agent index built: ${index.size} entries (no flat dirs to migrate)`);
- return index;
- }
-
- console.log(`📦 Migrating ${flatAgentDirs.length} agents into date buckets...`);
- let migrated = 0;
- let skipped = 0;
-
- for (const entry of flatAgentDirs) {
- const agentId = entry.name;
- const agentDir = join(AGENTS_DIR, agentId);
- const metaPath = join(agentDir, 'metadata.json');
-
- let dateStr = null;
-
- // Try to get date from metadata
- if (existsSync(metaPath)) {
- const content = await tryReadFile(metaPath);
- if (content) {
- const raw = safeJSONParse(content, null);
- if (raw?.completedAt) {
- dateStr = raw.completedAt.slice(0, 10); // YYYY-MM-DD
- }
- }
- }
-
- // Fallback: directory mtime
- if (!dateStr) {
- const dirStat = await stat(agentDir).catch(() => null);
- if (dirStat?.mtime) {
- dateStr = dirStat.mtime.toISOString().slice(0, 10);
- }
- }
-
- if (!dateStr) {
- console.log(`⚠️ Cannot determine date for ${agentId}, skipping`);
- skipped++;
- continue;
- }
-
- // Move into date bucket
- const bucketDir = join(AGENTS_DIR, dateStr);
- await ensureDir(bucketDir);
- const targetDir = join(bucketDir, agentId);
-
- // If target already exists (partial previous migration), skip
- if (existsSync(targetDir)) {
- index.set(agentId, dateStr);
- migrated++;
- continue;
- }
-
- await rename(agentDir, targetDir).catch(async (renameErr) => {
- // rename can fail across filesystems — fall back to copy+delete
- console.log(`⚠️ Rename failed for ${agentId}, using copy: ${renameErr.message}`);
- try {
- await ensureDir(targetDir);
- const files = await readdir(agentDir);
- for (const file of files) {
- const content = await readFile(join(agentDir, file));
- await writeFile(join(targetDir, file), content);
- }
- await rm(agentDir, { recursive: true });
- } catch (copyErr) {
- console.error(`❌ Copy fallback failed for ${agentId}: ${copyErr.message}`);
- // Clean up partially-created target to avoid skipping on next startup
- await rm(targetDir, { recursive: true, force: true }).catch(() => {});
- throw copyErr;
- }
- });
-
- index.set(agentId, dateStr);
- migrated++;
- }
-
- // Persist index
- await atomicWrite(INDEX_FILE, Object.fromEntries(index));
- const uniqueDates = new Set(index.values()).size;
- const parts = [`📦 Migrated ${migrated} agents into date buckets (${uniqueDates} unique dates)`];
- if (skipped > 0) parts.push(`skipped ${skipped} undatable`);
- console.log(parts.join(', '));
-
- return index;
-}
-
-// Prune agent archive date buckets older than retentionDays (default 90).
-// Removes directories + their index entries. Runs after migration on startup.
-export async function pruneOldAgentArchives(retentionDays = 90) {
- const idx = await loadAgentIndex();
- if (!idx || idx.size === 0) return;
-
- const cutoff = new Date();
- cutoff.setDate(cutoff.getDate() - retentionDays);
- const cutoffStr = cutoff.toISOString().slice(0, 10);
-
- const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;
- const entries = await readdir(AGENTS_DIR, { withFileTypes: true }).catch(() => []);
- const oldDates = entries
- .filter(e => e.isDirectory() && dateDirPattern.test(e.name) && e.name < cutoffStr)
- .map(e => e.name);
-
- if (oldDates.length === 0) return;
-
- for (const dateStr of oldDates) {
- await rm(join(AGENTS_DIR, dateStr), { recursive: true }).catch(() => {});
- }
-
- // Remove index entries for all old dates in a single pass
- const oldDateSet = new Set(oldDates);
- let pruned = 0;
- for (const [agentId, date] of idx.entries()) {
- if (oldDateSet.has(date)) { idx.delete(agentId); pruned++; }
- }
-
- await saveAgentIndex();
- console.log(`🗑️ Pruned ${pruned} archived agents older than ${retentionDays} days (${oldDates.length} date buckets)`);
-}
-
-export async function registerAgent(agentId, taskId, metadata = {}) {
- return withStateLock(async () => {
- const state = await loadState();
-
- state.agents[agentId] = {
- id: agentId,
- taskId,
- status: 'running',
- startedAt: new Date().toISOString(),
- metadata,
- output: []
- };
-
- state.stats.agentsSpawned++;
- await saveState(state);
-
- cosEvents.emit('agent:spawned', state.agents[agentId]);
- return state.agents[agentId];
- });
-}
-
-export async function updateAgent(agentId, updates) {
- return withStateLock(async () => {
- const state = await loadState();
-
- if (!state.agents[agentId]) {
- return null;
- }
-
- // Merge metadata if present in updates
- if (updates.metadata) {
- state.agents[agentId] = {
- ...state.agents[agentId],
- ...updates,
- metadata: { ...state.agents[agentId].metadata, ...updates.metadata }
- };
- } else {
- state.agents[agentId] = { ...state.agents[agentId], ...updates };
- }
- await saveState(state);
-
- cosEvents.emit('agent:updated', state.agents[agentId]);
- return state.agents[agentId];
- });
-}
-
-export async function completeAgent(agentId, result = {}) {
- const completed = await withStateLock(async () => {
- const state = await loadState();
-
- if (!state.agents[agentId]) {
- return null;
- }
-
- state.agents[agentId] = {
- ...state.agents[agentId],
- status: 'completed',
- completedAt: new Date().toISOString(),
- // Success-criteria validation verdict (issue #2344): normalize to an
- // explicit null sentinel when a completion path didn't declare/evaluate a
- // machine-checkable criterion, so persisted telemetry never conflates
- // "not declared" with "declared and failed" (false). Distinct from
- // result.success (the runner's exit-code verdict).
- result: { validationPassed: null, ...result },
- };
-
- if (result.success) {
- state.stats.tasksCompleted++;
- } else {
- state.stats.errors = (state.stats.errors || 0) + 1;
- }
-
- await saveState(state);
- // `agent:completed` is intentionally emitted later, after the domain-usage
- // ledger is updated (see the recordDomainUsage block below, #1683). Do NOT
- // move it back here. `agent:updated` carries no scheduling side effect, so it
- // stays inside the lock.
- cosEvents.emit('agent:updated', state.agents[agentId]);
-
- // Determine date bucket from completedAt
- const dateStr = state.agents[agentId].completedAt.slice(0, 10);
- const bucketDir = join(AGENTS_DIR, dateStr);
- await ensureDir(bucketDir);
-
- // Write metadata to flat dir first (may already have output.txt/prompt.txt there)
- const flatDir = join(AGENTS_DIR, agentId);
- if (!existsSync(flatDir)) {
- await ensureDir(flatDir);
- }
- const { output: _output, ...agentWithoutOutput } = state.agents[agentId];
- await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput);
-
- // Move entire agent dir into date bucket (atomic on same filesystem)
- const targetDir = join(bucketDir, agentId);
- if (!existsSync(targetDir)) {
- await rename(flatDir, targetDir).catch(async () => {
- // Fallback for cross-filesystem: copy files then remove
- await ensureDir(targetDir);
- const files = await readdir(flatDir);
- for (const file of files) {
- const content = await readFile(join(flatDir, file));
- await writeFile(join(targetDir, file), content);
- }
- await rm(flatDir, { recursive: true });
- });
- }
-
- // Update index
- const idx = await loadAgentIndex();
- idx.set(agentId, dateStr);
- await saveAgentIndex();
-
- return state.agents[agentId];
- });
-
- // Daily CoS budget accounting (#711): count only AUTONOMOUS runs (non-user
- // tasks) — the same set the CoS auto-run gate withholds when over budget —
- // toward the domain's actions/minutes ledger. Recorded outside the state lock
- // (separate ledger file + write tail) so it never serializes against state.json.
- //
- // This MUST land before the `agent:completed` emit below: that event's handler
- // schedules `dequeueNextTask()`, whose daily action-budget gate reads this
- // ledger. Recording first ensures the gate counts the just-finished action, so
- // a perpetual drain can't admit one spawn past `maxActionsPerDay` at the
- // boundary (#1683).
- if (completed?.metadata?.taskType && completed.metadata.taskType !== 'user') {
- await recordDomainUsage('cos', { actions: 1, ms: Number(result.duration) || 0 })
- .catch(err => console.error(`❌ Failed to record CoS budget usage for ${agentId}: ${err.message}`));
- }
-
- // Emit now that the ledger reflects this action (#1683). Fires for every
- // completed agent, matching prior behavior — only the timing moved.
- if (completed) {
- cosEvents.emit('agent:completed', completed);
- }
-
- return completed;
-}
-
-export async function appendAgentOutput(agentId, line) {
- const result = await withStateLock(async () => {
- const state = await loadState();
-
- if (!state.agents[agentId]) {
- return null;
- }
-
- state.agents[agentId].output.push({
- timestamp: new Date().toISOString(),
- line
- });
-
- // Trim to last 1000 lines in state
- if (state.agents[agentId].output.length > 1000) {
- state.agents[agentId].output = state.agents[agentId].output.slice(-1000);
- }
-
- await saveState(state);
- return state.agents[agentId];
- });
-
- if (result) {
- cosEvents.emit('agent:output', { agentId, line });
- }
-
- return result;
-}
-
-// Batched variant — single state load+save for many lines. Used by the TUI
-// spawner to avoid write-amplification on chatty TUIs that emit hundreds of
-// lines per second; per-line appendAgentOutput would re-load and re-save the
-// entire state JSON for every line.
-export async function appendAgentOutputLines(agentId, lines) {
- if (!Array.isArray(lines) || lines.length === 0) return null;
- const result = await withStateLock(async () => {
- const state = await loadState();
- if (!state.agents[agentId]) return null;
- const timestamp = new Date().toISOString();
- for (const line of lines) {
- state.agents[agentId].output.push({ timestamp, line });
- }
- if (state.agents[agentId].output.length > 1000) {
- state.agents[agentId].output = state.agents[agentId].output.slice(-1000);
- }
- await saveState(state);
- return state.agents[agentId];
- });
-
- if (result) {
- for (const line of lines) {
- cosEvents.emit('agent:output', { agentId, line });
- }
- }
-
- return result;
-}
-
-// Debounce window for batching streamed agent output to state. A chatty
-// producer (CoS Runner stream events, non-stream CLI stdout) can emit dozens
-// of lines/sec; without batching, each line round-trips a full state
-// load+save (see appendAgentOutput). 250ms is invisible to the live tail but
-// cuts state I/O by 1-2 orders of magnitude. Matches OUTPUT_FLUSH_INTERVAL_MS
-// in agentTuiSpawning.js.
-const OUTPUT_FLUSH_INTERVAL_MS = 250;
-
-// Debounced per-agent output batcher. Wraps appendAgentOutputLines with a
-// ~250ms flush window so a hot streaming producer triggers one state load+save
-// per window instead of per line — the write-amplification guard documented in
-// CLAUDE.md ("High-frequency state writes must batch"). The TUI spawner rolls
-// its own equivalent inline because it co-flushes an output.txt appendFile in
-// the same batch; producers that only need the state write should use this.
-//
-// Callers MUST `await flush()` in their finish/cleanup path before the
-// completion event so the final lines land before the agent is marked done.
-export function createAgentOutputBatcher(agentId, { intervalMs = OUTPUT_FLUSH_INTERVAL_MS } = {}) {
- let pending = [];
- let timer = null;
- let flushing = null;
-
- const drain = async () => {
- if (timer) { clearTimeout(timer); timer = null; }
- if (pending.length === 0) return;
- const batch = pending;
- pending = [];
- // Swallow+log state-write failures so neither the debounced timer nor a
- // caller's `await flush()` ever rejects — this runs in child-process /
- // timer callbacks where an uncaught throw would crash Node (CLAUDE.md "No
- // try/catch" exception). The authoritative transcript lives in output.txt;
- // a dropped live-tail batch is non-fatal. Mirrors the TUI spawner's
- // `.catch(() => {})` on its own batched append.
- await appendAgentOutputLines(agentId, batch).catch((err) => {
- console.error(`❌ agent ${agentId} output batch flush failed: ${err.message}`);
- });
- };
-
- const schedule = () => {
- if (timer || flushing) return;
- timer = setTimeout(() => {
- timer = null;
- flushing = drain().finally(() => {
- flushing = null;
- // Catch lines that arrived during the in-flight drain — without this a
- // producer that goes quiet right after the timer fires strands its last
- // batch in `pending` until flush().
- if (pending.length > 0) schedule();
- });
- }, intervalMs);
- };
-
- return {
- push(lineOrLines) {
- if (Array.isArray(lineOrLines)) {
- if (lineOrLines.length === 0) return;
- pending.push(...lineOrLines);
- } else {
- pending.push(lineOrLines);
- }
- schedule();
- },
- // Wait for any in-flight drain, then fully empty `pending`. A push can race
- // in during an awaited drain, so loop until nothing is left rather than
- // draining a fixed number of times (which could strand a late line to the
- // debounce timer). flush() is only called once the producer has stopped, so
- // the loop terminates promptly.
- async flush() {
- if (flushing) await flushing;
- while (pending.length > 0) await drain();
- },
- };
-}
-
-// Get all agents from in-memory state (includes running and recently completed; archived agents loaded via getAgentsByDate)
-export async function getAgents() {
- const state = await loadState();
- return Object.values(state.agents);
-}
-
-// Get available agent date buckets with counts, sorted descending
-export async function getAgentDates() {
- const idx = await loadAgentIndex();
- const dateCounts = {};
- for (const date of idx.values()) {
- dateCounts[date] = (dateCounts[date] || 0) + 1;
- }
- return Object.entries(dateCounts)
- .map(([date, count]) => ({ date, count }))
- .sort((a, b) => b.date.localeCompare(a.date));
-}
-
-// Get completed agents for a specific date bucket
-export async function getAgentsByDate(date) {
- const dateDir = join(AGENTS_DIR, date);
- if (!existsSync(dateDir)) return [];
-
- const entries = await readdir(dateDir, { withFileTypes: true });
- const agentDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('agent-'));
- const agents = [];
-
- // Batch reads in chunks of 50 to avoid fd exhaustion on large date buckets
- const BATCH_SIZE = 50;
- for (let i = 0; i < agentDirs.length; i += BATCH_SIZE) {
- const batch = agentDirs.slice(i, i + BATCH_SIZE);
- const reads = batch.map(async (entry) => {
- const metaPath = join(dateDir, entry.name, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (!content) return;
- const raw = safeJSONParse(content, null);
- if (!raw) return;
- const id = raw.id || raw.agentId || entry.name;
- const { output, ...rest } = raw;
- const agent = { ...rest, id, status: raw.status || 'completed' };
- const repaired = await repairCodexTaskSummary(join(dateDir, entry.name), agent);
- if (repaired) agent.metadata = { ...agent.metadata, taskSummary: repaired };
- agents.push(agent);
- });
- await Promise.allSettled(reads);
- }
-
- return agents.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
-}
-
-// Get agent by ID with full output from file
-export async function getAgent(agentId) {
- const state = await loadState();
- let agent = state.agents[agentId];
-
- // Fall back to disk metadata via index if not in state
- if (!agent) {
- const idx = await loadAgentIndex();
- const dateStr = idx.get(agentId);
- if (dateStr) {
- const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (content) {
- const raw = safeJSONParse(content, null);
- if (raw) {
- const { output, ...rest } = raw;
- agent = { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
- }
- }
- }
- }
- if (!agent) return null;
-
- // Completed agents live in date buckets; paused agents remain in the flat
- // agent dir but should still expose their preserved full transcript.
- if (agent.status === 'completed' || agent.status === 'paused') {
- const dateStr = agent.status === 'completed' ? agent.completedAt?.slice(0, 10) : null;
- const agentDir = dateStr ? getAgentDir(agentId, dateStr) : getAgentDir(agentId);
- const repaired = await repairCodexTaskSummary(agentDir, agent);
- if (repaired) agent = { ...agent, metadata: { ...agent.metadata, taskSummary: repaired } };
- const outputFile = join(agentDir, 'output.txt');
- if (existsSync(outputFile)) {
- const fullOutput = await readFile(outputFile, 'utf-8');
- const lines = fullOutput.split('\n').filter(line => line.trim());
- const timestamp = agent.completedAt || agent.pausedAt;
- return {
- ...agent,
- output: lines.map(line => ({ line, timestamp }))
- };
- }
- }
-
- return agent;
-}
-
-// Read the prompt that was sent to an agent at spawn time.
-// Used by the AgentCard UI to let the user inspect what was pasted into the
-// TUI / sent to the CLI so the prompt can be iterated on.
-export async function getAgentPrompt(agentId) {
- const state = await loadState();
- const agent = state.agents[agentId];
- if (!agent) return { error: 'Agent not found' };
- const agentDir = getAgentDir(agentId, agent.archiveDate);
- const promptPath = join(agentDir, 'prompt.txt');
- if (!existsSync(promptPath)) return { error: 'Prompt file not found' };
- const prompt = await readFile(promptPath, 'utf8');
- return { prompt, bytes: prompt.length };
-}
-
-// Terminate an agent (will be handled by spawner)
-export async function terminateAgent(agentId) {
- // Emit event to kill the process FIRST
- cosEvents.emit('agent:terminate', agentId);
- // The spawner will handle marking the agent as completed after termination
- return { success: true, agentId };
-}
-
-// Pause an agent without completing its task or cleaning up its worktree.
-export async function pauseAgent(agentId, reason = null) {
- const { pauseAgent: pauseAgentFromSpawner } = await import('./subAgentSpawner.js');
- return pauseAgentFromSpawner(agentId, reason);
-}
-
-// Force kill an agent with SIGKILL (immediate, no graceful shutdown)
-export async function killAgent(agentId) {
- const { killAgent: killAgentFromSpawner } = await import('./subAgentSpawner.js');
- return killAgentFromSpawner(agentId);
-}
-
-// Send a BTW (additional context) message to a running agent.
-//
-// BTW is only supported for Claude Code TUI agents — the message gets
-// bracket-pasted directly into the live PTY session as if the user typed it
-// themselves. The legacy BTW.md path is gone: it required headless agents to
-// poll a file mid-run, which most CLIs (codex / antigravity / LM Studio) don't do
-// reliably anyway, and the indirection had to be reflected in the prompt with
-// a brittle "check this file" instruction. Other TUI kinds (codex, antigravity)
-// don't honor bracketed-paste in the same way, so they're not eligible
-// either.
-export async function sendBtwToAgent(agentId, message) {
- const agentInfo = await withStateLock(async () => {
- const state = await loadState();
- const agent = state.agents[agentId];
- if (!agent) return { error: 'Agent not found' };
- if (agent.status !== 'running') return { error: 'Agent is not running' };
- if (agent.metadata?.executionMode !== 'tui') {
- return { error: 'BTW is only supported for Claude Code TUI agents.' };
- }
- if (agent.metadata?.tuiKind !== 'claude') {
- return { error: `BTW is only supported for Claude Code TUI agents (this agent runs ${agent.metadata.tuiKind || 'an unknown TUI'}).` };
- }
- if (!agent.metadata?.tuiSessionId) {
- return { error: 'Agent has no attached TUI session' };
- }
- return { tuiSessionId: agent.metadata.tuiSessionId };
- });
-
- if (agentInfo.error) return agentInfo;
-
- const shellService = await import('./shell.js');
- if (!shellService.getSession(agentInfo.tuiSessionId)) {
- return { error: 'TUI session is no longer alive' };
- }
- // Bracketed-paste + delayed Enter, mirroring the initial prompt paste in
- // agentTuiSpawning.js: Claude Code commits the paste buffer before the
- // submit arrives, so multi-line messages land as a single paste event.
- shellService.writeToSession(agentInfo.tuiSessionId, `\x1b[200~${message}\x1b[201~`);
- setTimeout(() => {
- try {
- // Re-check session liveness: the TUI session may have died in the 400ms window.
- if (shellService.getSession(agentInfo.tuiSessionId)) {
- shellService.writeToSession(agentInfo.tuiSessionId, '\r');
- }
- } catch (err) {
- console.error(`❌ [cosAgents] BTW delayed Enter failed for session ${agentInfo.tuiSessionId}: ${err.message}`);
- }
- }, 400);
-
- // Track in agent state (cap at 50 messages)
- const timestamp = new Date().toISOString();
- await withStateLock(async () => {
- const state = await loadState();
- if (!state.agents[agentId]) return;
- if (!state.agents[agentId].btwMessages) {
- state.agents[agentId].btwMessages = [];
- }
- state.agents[agentId].btwMessages.push({ message, timestamp });
- if (state.agents[agentId].btwMessages.length > 50) {
- state.agents[agentId].btwMessages = state.agents[agentId].btwMessages.slice(-50);
- }
- await saveState(state);
- });
-
- cosEvents.emit('agent:btw', { agentId, message, timestamp });
- return { success: true, delivered: 'tui-paste', tuiSessionId: agentInfo.tuiSessionId };
-}
-
-// Get process stats for an agent (CPU, memory)
-export async function getAgentProcessStats(agentId) {
- const { getAgentProcessStats: getStatsFromSpawner } = await import('./subAgentSpawner.js');
- return getStatsFromSpawner(agentId);
-}
-
-// Check if a PID is still running
-async function isPidAlive(pid) {
- if (!pid) return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
-}
-
-// Cleanup zombie agents - agents marked as running but whose process is dead
-export async function cleanupZombieAgents() {
- // Check local tracking maps (read from the side-effect-free state module, not
- // subAgentSpawner — avoids pulling in the heavier orchestrator just to read the maps).
- const { getActiveAgentIds } = await import('./agentState.js');
- const activeIds = getActiveAgentIds();
-
- // Also check with the CoS runner for agents it's actively tracking
- const { getActiveAgentsFromRunner } = await import('./cosRunnerClient.js');
- const runnerAgents = await getActiveAgentsFromRunner().catch(() => []);
- const runnerAgentIds = new Set(runnerAgents.map(a => a.id));
-
- return withStateLock(async () => {
- const state = await loadState();
- const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');
- const cleaned = [];
-
- for (const agent of runningAgents) {
- // Skip if tracked in local maps or runner
- if (activeIds.includes(agent.id) || runnerAgentIds.has(agent.id)) {
- continue;
- }
-
- // If agent has a PID, verify the process is actually dead
- if (agent.pid) {
- const alive = await isPidAlive(agent.pid);
- if (alive) continue;
- } else {
- // No PID yet - agent might still be initializing
- // Give it a 30 second grace period before marking as zombie
- const startedAt = agent.startedAt ? new Date(agent.startedAt).getTime() : 0;
- const ageMs = Date.now() - startedAt;
- if (ageMs < 30000) continue;
- }
-
- // Agent is not tracked anywhere and process is dead — it's a zombie
- console.log(`🧟 Zombie agent detected: ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
- state.agents[agent.id] = {
- ...agent,
- status: 'completed',
- completedAt: new Date().toISOString(),
- result: { success: false, error: 'Agent process terminated unexpectedly' }
- };
- cleaned.push(agent.id);
- }
-
- if (cleaned.length > 0) {
- await saveState(state);
-
- // Persist zombie-cleaned agents to date-bucketed dirs and update index
- const idx = await loadAgentIndex();
- for (const agentId of cleaned) {
- const agent = state.agents[agentId];
- const dateStr = agent.completedAt?.slice(0, 10);
- if (!dateStr) continue;
- const bucketDir = join(AGENTS_DIR, dateStr);
- await ensureDir(bucketDir);
-
- const flatDir = join(AGENTS_DIR, agentId);
- const { output, ...agentWithoutOutput } = agent;
-
- // Ensure metadata is written before move
- if (!existsSync(flatDir)) await ensureDir(flatDir);
- await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
-
- // Move to date bucket
- const targetDir = join(bucketDir, agentId);
- if (!existsSync(targetDir)) {
- await rename(flatDir, targetDir).catch(async () => {
- await ensureDir(targetDir);
- const files = await readdir(flatDir);
- for (const file of files) {
- const content = await readFile(join(flatDir, file));
- await writeFile(join(targetDir, file), content);
- }
- await rm(flatDir, { recursive: true });
- });
- }
-
- idx.set(agentId, dateStr);
- }
- await saveAgentIndex();
-
- console.log(`🧹 Cleaned up ${cleaned.length} zombie agents: ${cleaned.join(', ')}`);
- cosEvents.emit('agents:changed', { action: 'zombie-cleanup', cleaned });
- }
-
- return { cleaned, count: cleaned.length };
- });
-}
-
-// Delete a single agent from state and disk
-export async function deleteAgent(agentId) {
- return withStateLock(async () => {
- const state = await loadState();
- const idx = await loadAgentIndex();
-
- const inState = !!state.agents[agentId];
- const inIndex = idx.has(agentId);
- if (!inState && !inIndex) {
- return { error: 'Agent not found' };
- }
-
- delete state.agents[agentId];
- await saveState(state);
-
- // Remove from disk (date-bucketed or flat)
- const agentDir = getAgentDir(agentId);
- if (existsSync(agentDir)) {
- await rm(agentDir, { recursive: true }).catch(() => {});
- }
-
- // Remove from index
- idx.delete(agentId);
- await saveAgentIndex();
-
- cosEvents.emit('agents:changed', { action: 'deleted', agentId });
- return { success: true, agentId };
- });
-}
-
-// Submit feedback for a completed agent
-export async function submitAgentFeedback(agentId, feedback) {
- return withStateLock(async () => {
- const state = await loadState();
- const feedbackData = {
- rating: feedback.rating,
- comment: feedback.comment || null,
- submittedAt: new Date().toISOString()
- };
-
- // Try state first (recently completed agents still in state)
- if (state.agents[agentId]) {
- const agent = state.agents[agentId];
- if (agent.status !== 'completed') {
- return { error: 'Can only submit feedback for completed agents' };
- }
- state.agents[agentId].feedback = feedbackData;
- await saveState(state);
-
- // Also update on-disk metadata (derive date bucket from completedAt if archived)
- const dateBucket = agent.completedAt ? agent.completedAt.slice(0, 10) : null;
- const agentDir = getAgentDir(agentId, dateBucket);
- const metaPath = join(agentDir, 'metadata.json');
- if (existsSync(metaPath)) {
- const content = await tryReadFile(metaPath);
- if (content) {
- const raw = safeJSONParse(content, null);
- if (raw) {
- raw.feedback = feedbackData;
- await atomicWrite(metaPath, raw).catch(() => {});
- }
- }
- }
-
- emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
- cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
- return { success: true, agent: state.agents[agentId] };
- }
-
- // Agent not in state — look up from disk via index
- const idx = await loadAgentIndex();
- const dateStr = idx.get(agentId);
- if (!dateStr) return { error: 'Agent not found' };
-
- const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (!content) return { error: 'Agent not found' };
-
- const raw = safeJSONParse(content, null);
- if (!raw) return { error: 'Agent not found' };
-
- raw.feedback = feedbackData;
- await atomicWrite(metaPath, raw);
-
- emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
- cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
- return { success: true, agent: { ...raw, id: agentId } };
- });
-}
-
-// Get aggregated feedback statistics
-export async function getFeedbackStats() {
- const state = await loadState();
- const agents = Object.values(state.agents);
-
- const withFeedback = agents.filter(a => a.feedback);
- const positive = withFeedback.filter(a => a.feedback.rating === 'positive').length;
- const negative = withFeedback.filter(a => a.feedback.rating === 'negative').length;
- const neutral = withFeedback.filter(a => a.feedback.rating === 'neutral').length;
-
- // Group by task type
- const byTaskType = {};
- withFeedback.forEach(a => {
- const taskType = extractTaskType(a.metadata?.taskDescription);
- if (!byTaskType[taskType]) {
- byTaskType[taskType] = { positive: 0, negative: 0, neutral: 0, total: 0 };
- }
- byTaskType[taskType][a.feedback.rating]++;
- byTaskType[taskType].total++;
- });
-
- // Recent feedback (last 10 with comments)
- const recentWithComments = withFeedback
- .filter(a => a.feedback.comment)
- .sort((a, b) => new Date(b.feedback.submittedAt) - new Date(a.feedback.submittedAt))
- .slice(0, 10)
- .map(a => ({
- agentId: a.id,
- taskDescription: a.metadata?.taskDescription,
- rating: a.feedback.rating,
- comment: a.feedback.comment,
- submittedAt: a.feedback.submittedAt
- }));
-
- const satisfactionRate = withFeedback.length > 0
- ? Math.round((positive / withFeedback.length) * 100)
- : null;
-
- return {
- total: withFeedback.length,
- positive,
- negative,
- neutral,
- satisfactionRate,
- byTaskType,
- recentWithComments
- };
-}
-
-// Helper to extract task type from description (mirrors client-side logic)
-export function extractTaskType(description) {
- if (!description) return 'general';
- const d = description.toLowerCase();
- if (d.includes('fix') || d.includes('bug') || d.includes('error') || d.includes('issue')) return 'bug-fix';
- if (d.includes('refactor') || d.includes('clean up') || d.includes('improve') || d.includes('optimize')) return 'refactor';
- if (d.includes('test')) return 'testing';
- if (d.includes('document') || d.includes('readme') || d.includes('docs')) return 'documentation';
- if (d.includes('review') || d.includes('audit')) return 'code-review';
- if (d.includes('mobile') || d.includes('responsive')) return 'mobile-responsive';
- if (d.includes('security') || d.includes('vulnerability')) return 'security';
- if (d.includes('performance') || d.includes('speed')) return 'performance';
- if (d.includes('ui') || d.includes('ux') || d.includes('design') || d.includes('style')) return 'ui-ux';
- if (d.includes('api') || d.includes('endpoint') || d.includes('route')) return 'api';
- if (d.includes('database') || d.includes('migration')) return 'database';
- if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';
- if (d.includes('investigate') || d.includes('debug')) return 'investigation';
- if (d.includes('self-improvement') || d.includes('feature idea')) return 'self-improvement';
- return 'feature';
-}
-
-// Archive stale completed agents from state.json.
-// Completed agents are already persisted to per-agent metadata files on disk
-// (metadata.json) by completeAgent(), so removing them from state.json only
-// reduces the size of the in-memory state and the state.json file.
-export async function archiveStaleAgents() {
- return withStateLock(async () => {
- const state = await loadState();
- const retentionMs = state.config.completedAgentRetentionMs ?? 86400000;
- const cutoff = Date.now() - retentionMs;
-
- const staleIds = Object.keys(state.agents).filter(id => {
- const agent = state.agents[id];
- if (agent.status !== 'completed') return false;
- const completedAt = agent.completedAt ? new Date(agent.completedAt).getTime() : 0;
- return completedAt > 0 && completedAt < cutoff;
- });
-
- if (staleIds.length === 0) return { archived: 0 };
-
- const idx = await loadAgentIndex();
-
- for (const id of staleIds) {
- // Ensure agent is persisted to date-bucketed disk before removing from state
- if (!idx.has(id)) {
- const agent = state.agents[id];
- const dateStr = agent.completedAt?.slice(0, 10);
- if (!dateStr) continue;
- const bucketDir = join(AGENTS_DIR, dateStr);
- await ensureDir(bucketDir);
-
- const { output, ...agentWithoutOutput } = agent;
- const flatDir = join(AGENTS_DIR, id);
- const targetDir = join(bucketDir, id);
-
- if (existsSync(flatDir) && !existsSync(targetDir)) {
- // Write metadata then move (with cross-filesystem fallback)
- await atomicWrite(join(flatDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
- await rename(flatDir, targetDir).catch(async () => {
- await ensureDir(targetDir);
- const files = await readdir(flatDir).catch(() => []);
- for (const file of files) {
- const content = await tryReadFile(join(flatDir, file), null);
- if (content !== null) await writeFile(join(targetDir, file), content);
- }
- await rm(flatDir, { recursive: true }).catch(() => {});
- });
- if (!existsSync(targetDir)) continue; // Skip index update if move failed
- } else if (!existsSync(targetDir)) {
- await ensureDir(targetDir);
- await atomicWrite(join(targetDir, 'metadata.json'), agentWithoutOutput).catch(() => {});
- }
-
- idx.set(id, dateStr);
- }
-
- delete state.agents[id];
- }
-
- await saveState(state);
- await saveAgentIndex();
- console.log(`📦 Archived ${staleIds.length} stale agents from state.json (retained on disk)`);
- cosEvents.emit('agents:changed', { action: 'auto-archive', archived: staleIds.length });
- return { archived: staleIds.length };
- });
-}
-
-// Clear completed agents from state, cache, and disk
-export async function clearCompletedAgents() {
- return withStateLock(async () => {
- const state = await loadState();
- const idx = await loadAgentIndex();
-
- // Remove completed agents from state
- const stateCompleted = Object.keys(state.agents).filter(
- id => state.agents[id].status === 'completed'
- );
- for (const id of stateCompleted) {
- delete state.agents[id];
- }
- await saveState(state);
-
- // Collect all unique dates from index, then remove date bucket dirs
- const dates = new Set(idx.values());
- const totalCleared = idx.size + stateCompleted.filter(id => !idx.has(id)).length;
-
- const removals = [...dates].map(date => {
- const dateDir = join(AGENTS_DIR, date);
- return existsSync(dateDir)
- ? rm(dateDir, { recursive: true }).catch(() => {})
- : Promise.resolve();
- });
- await Promise.all(removals);
-
- // Clear index
- idx.clear();
- await saveAgentIndex();
- return { cleared: totalCleared };
- });
-}
+export * from './cosAgentIndex.js';
+export * from './cosAgentLifecycle.js';
+export * from './cosAgentFeedback.js';
+export * from './cosAgentArchive.js';
diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.js
new file mode 100644
index 0000000000..d965d405be
--- /dev/null
+++ b/server/services/cosDequeue.js
@@ -0,0 +1,103 @@
+/**
+ * CoS Dequeue — pure priority/capacity helpers (issue #2530)
+ *
+ * The spawn-side scheduler `dequeueNextTask` (in cos.js) fills open agent slots
+ * by draining five priority tiers in order. This module holds the *pure*,
+ * side-effect-free pieces of that decision — the per-cycle capacity tracker and
+ * the mission/idle tier-eligibility predicates — so the scheduler and its unit
+ * tests share ONE implementation instead of the tests re-deriving a local
+ * replica of the guards.
+ *
+ * The async tiers themselves (which load schedules, generate tasks, emit
+ * `task:ready`, advance cooldowns) stay in cos.js as `spawnDequeuePriorityN(ctx)`
+ * helpers — they're integration-level and pinned by source-order regression
+ * tests — but every capacity/gate decision they make routes through here.
+ */
+
+// Canonical priority-tier order for the dequeue scheduler. `dequeueNextTask`
+// invokes its `spawnDequeuePriorityN` helpers in exactly this sequence; the
+// source-order regression test in cos.test.js pins the invocation order against
+// this list so a reshuffle fails loudly.
+export const DEQUEUE_PRIORITY_ORDER = Object.freeze([
+ 'onDemand', // Priority 0 — explicit user "Run" requests (bypasses pause)
+ 'user', // Priority 1 — user-authored pending tasks
+ 'autoSystem', // Priority 2 — auto-approved system / improvement tasks
+ 'mission', // Priority 3 — proactive mission-driven tasks
+ 'idle', // Priority 4 — generated idle-review task
+]);
+
+/**
+ * Per-cycle spawn-capacity tracker. Owns the running `spawned` count and the
+ * per-project tally, and exposes the exact `canSpawn` / `trackSpawn` closure the
+ * scheduler uses to enforce the global slot cap AND the per-project cap.
+ *
+ * `availableSlots` = global cap minus currently-running agents (may be 0 or
+ * negative if a config change shrank the cap below live load — callers still
+ * guard with `availableSlots <= 0`). `perProjectLimit` falls back to the global
+ * cap when `maxConcurrentAgentsPerProject` is unset/0, matching the scheduler's
+ * historical behavior.
+ *
+ * `canSpawn(task, ceiling = availableSlots)` — autonomous tiers pass a lower
+ * `ceiling` (the daily CoS action budget) so a task admitted there counts
+ * against both the global slots and the budget. A task with no `metadata.app`
+ * buckets into the `_self` project key (PortOS-on-itself work) so app-less tasks
+ * can't bypass the per-project cap.
+ */
+export function createDequeueCapacity(state, { agentsByProject = {} } = {}) {
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
+ const availableSlots = state.config.maxConcurrentAgents - runningAgents;
+ const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
+
+ const spawnProjectCounts = { ...agentsByProject };
+ let spawned = 0;
+
+ const canSpawn = (task, ceiling = availableSlots) => {
+ if (spawned >= ceiling) return false;
+ const project = task.metadata?.app || '_self';
+ return (spawnProjectCounts[project] || 0) < perProjectLimit;
+ };
+
+ const trackSpawn = (task) => {
+ const project = task.metadata?.app || '_self';
+ spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
+ spawned++;
+ };
+
+ return {
+ availableSlots,
+ perProjectLimit,
+ spawnProjectCounts,
+ canSpawn,
+ trackSpawn,
+ // Live read of the running spawn count — a getter so callers always see the
+ // current total after trackSpawn mutations rather than a stale snapshot.
+ get spawned() { return spawned; },
+ };
+}
+
+/**
+ * Priority 3 (mission) tier eligibility. Mission tasks are speculative
+ * autonomous spawns: they only run when there's autonomous headroom left this
+ * cycle, no pending user tasks are waiting, proactive mode is on, AND the CoS
+ * auto-run domain is in `execute` (off/dry-run withhold autonomous spawns).
+ */
+export function isMissionTierEligible({ spawned, ceiling, hasPendingUserTasks, proactiveMode, autonomyMode }) {
+ return spawned < ceiling
+ && !hasPendingUserTasks
+ && !!proactiveMode
+ && autonomyMode === 'execute';
+}
+
+/**
+ * Priority 4 (idle-review) tier eligibility. The idle task only fires when the
+ * daemon is COMPLETELY idle this cycle — nothing else spawned (`spawned === 0`),
+ * no pending user tasks, idle review enabled, and CoS auto-run in `execute`.
+ * The `spawned === 0` fence is stricter than mission's `< ceiling`: even a single
+ * autonomous spawn suppresses idle on the same cycle.
+ */
+export function isIdleTierEligible({ spawned, hasPendingUserTasks, idleReviewEnabled, autonomyMode }) {
+ return spawned === 0
+ && !!idleReviewEnabled
+ && !hasPendingUserTasks
+ && autonomyMode === 'execute';
+}