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

test(cos,agentLifecycle): coverage for evaluateTasks, dequeueNextTask, spawn/completion error recovery (#218)

[._.]/ Adam Eivye86e1d3897bb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3de6cf0ef8..f0def46d1f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Tests
+
+- **God-file test coverage for `cos.js` + `agentLifecycle.js`.** Added `server/services/cos.test.js` (18 tests) pinning `evaluateTasks` priority ordering (Priority 0 onDemand → 1 user → 2 autoSystem → 3 mission → 4 idle, with mission/idle gated by `hasPendingUserTasks` and idle further fenced behind `spawned === 0` / `tasksToSpawn.length === 0`) and `dequeueNextTask` capacity guards (global `maxConcurrentAgents` early-return when saturated or over-saturated, per-project `maxConcurrentAgentsPerProject` cap counting both pre-existing runners and in-batch spawns, `_self` sentinel for app-less PortOS tasks, fallback to global cap when per-project is unset). Extended `server/services/agentLifecycle.test.js` (+15 tests: 11 active + 4 skipped) covering `spawnAgentForTask` cleanupOnError paths (no-provider, no-fallback, git-conflict, updateTask-null) and `handleAgentCompletion` error-recovery regression pins (throws from `completeAgent`, `updateTask`, `completeAgentRun`, `processAgentCompletion` all leak the `runnerAgents` Map entry because none of those steps are wrapped in try/catch and the terminal `runnerAgents.delete(agentId)` is unconditional at the function tail). Tests follow the inline-function-copy pattern from `subAgentSpawner.test.js` — pure logic replicas exercised with test fixtures, plus source-level regression guards that pin priority order, the `availableSlots <= 0` short-circuit, and the runner-cleanup tail placement. 4 skipped tests are TODO markers for the PLAN.md backlog item "Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`" — they flip green once that fix lands.
+
## Added
- **Favorite + note any generated image or video.** Every MediaCard now has a star toggle in the corner; clicking the tile opens the lightbox where a single editable note (max 2000 chars, 500ms debounced save) lives next to the prompt. Favorites and notes are surfaced across all four gallery surfaces — Media History, Image Gen, Video Gen, and Media Collection Detail — and a "Favorites" filter chip on each scopes the grid to starred items only. Press `s` while a lightbox is open to toggle favorite. Annotations persist to a new sidecar `data/media-annotations.json` keyed by `<kind>:<ref>` (same scheme as collections) so they survive when the underlying job records get pruned. Empty annotations (`!starred && !note`) get removed from disk on write to keep the file lean. Backed by `server/services/mediaAnnotations.js` + `server/routes/mediaAnnotations.js` (GET / PATCH with prune-on-empty + 2000-char note cap), the shared `useMediaAnnotations()` hook with optimistic-update + revert, and `MediaCard` / `MediaLightbox` prop extensions (`starred`, `hasNote`, `onToggleStar`, `annotation`, `onAnnotationChange`).
diff --git a/PLAN.md b/PLAN.md
index 2f72701551..b1b98bebca 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -7,7 +7,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
1. **Voice agent next power-ups** — `ui_read` (extract visible page text so "what does this say?" works without hand-navigation), destructive-action confirmation gate (pause and require spoken "confirm" when `ui_click` matches `/delete|remove|discard|reset|clear/i`), proactive CoS speech (server-pushed voice with quiet-hours policy + barge-in contract).
-2. **God-file test coverage** — `cos.js` (3115 lines) and `agentLifecycle.js` (1446 lines) still have no test sibling. Add tests for `evaluateTasks` priority ordering + `dequeueNextTask` capacity guards (cos), and `spawnAgentForTask` + `handleAgentCompletion` error recovery (agentLifecycle). Both files are still growing — `agentLifecycle.js` is +11 LOC since last replan; add coverage before further surgery.
## Backlog
@@ -76,6 +75,7 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test-specific hack in prod boot path).
- [ ] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.
+- [ ] **[HIGH][CODE]** Wrap `handleAgentCompletion` body in try/finally so the terminal `runnerAgents.delete(agentId)` (`server/services/agentLifecycle.js:1146`) always runs. Today a throw from `completeAgent` (line 939), `completeAgentRun` (line 949), `updateTask` (lines 954 / 960), or `processAgentCompletion` (line 987) aborts the function and leaks the runner-agents Map entry forever, blocking any retry. Tests added 2026-05-12 in `agentLifecycle.test.js` ("regression-pin" block) document the gap — once the wrap lands, those tests' `runnerAgents.has(...)` assertions flip and need updating. Sister fix to the open Backlog item "Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`" above.
- [ ] **[MEDIUM][CLIENT]** 4 components still redefine `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally instead of importing from `client/src/utils/formatters.js`: `pages/VideoTimelineEditor.jsx`, `pages/VideoTimeline.jsx`, `components/settings/MortalLoomTab.jsx`, `components/brain/tabs/ImportTab.jsx`. (Down from 8.)
- [ ] **[MEDIUM][PERF]** `server/services/feeds.js#getItems` (lines 303–319) — full-sort-then-paginate on every request. Pre-sort once at write time or maintain a per-feed index.
- [ ] **[MEDIUM][CODE]** Magic numbers in `cos.js:166,357`, `lmStudioManager.js:66`; brittle `err.message.startsWith('unknown piper voice:')` in `routes/voice.js:160` and `err.message.includes('not initialized')` in `services/visionTest.js:124`.
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 14be91544c..a64a0bf75e 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -1,32 +1,53 @@
/**
- * Tests for agentLifecycle — focused on the `spawningTasks` dedup-guard race
- * that allowed a SECOND agent to be spawned for the SAME task id after the
- * first spawn already passed the dedup add but before the runner queued the
- * agent.
+ * Tests for agentLifecycle — three concerns:
*
- * The production race (pre-fix, agentLifecycle.js line 511):
+ * 1. The `spawningTasks` dedup-guard race that allowed a SECOND agent to be
+ * spawned for the SAME task id after the first spawn already passed the
+ * dedup add but before the runner queued the agent (`spawningTasks dedup`
+ * blocks below).
*
- * await updateTask(task.id, { status: 'in_progress', ... });
- * spawningTasks.delete(task.id); // ← released too early
- * ...
- * return spawnViaRunner(...); // ← actual runner enqueue
+ * The production race (pre-fix, agentLifecycle.js line 511):
*
- * A concurrent `spawnAgentForTask(sameTask)` call landing between the delete
- * and the runner-enqueue saw an empty set, fell through the dedup check
- * (which does NOT re-check task.status), and proceeded to spawn a SECOND
- * agent for the same task id. The fix wraps the spawn call in try/finally
- * and releases the guard only after the runner accepted the agent.
+ * await updateTask(task.id, { status: 'in_progress', ... });
+ * spawningTasks.delete(task.id); // ← released too early
+ * ...
+ * return spawnViaRunner(...); // ← actual runner enqueue
*
- * These tests use inline copies of the dedup slice (matching the convention
- * in subAgentSpawner.test.js — pure logic copies instead of mocking the
- * full async-heavy production function).
+ * A concurrent `spawnAgentForTask(sameTask)` call landing between the
+ * delete and the runner-enqueue saw an empty set, fell through the dedup
+ * check (which does NOT re-check task.status), and proceeded to spawn a
+ * SECOND agent for the same task id. The fix wraps the spawn call in
+ * try/finally and releases the guard only after the runner accepted the
+ * agent.
+ *
+ * 2. `spawnAgentForTask` error recovery (`spawnAgentForTask — cleanupOnError`
+ * block). Documents which detected-error paths release the guard via
+ * `cleanupOnError`, plus a SKIPPED test that pins the partial-coverage
+ * gap: a throw between `spawningTasks.add(task.id)` (line 134) and the
+ * try/finally (line 536) leaks the guard forever. PLAN.md → Backlog has
+ * a separate item to widen the try/finally; the skip flips green once
+ * that fix lands.
+ *
+ * 3. `handleAgentCompletion` error recovery (`handleAgentCompletion error
+ * recovery` block). The completion function has NO try/catch wrapping
+ * its core steps, so a throw from `completeAgent`, `updateTask`, or
+ * `processAgentCompletion` aborts the function before
+ * `runnerAgents.delete(agentId)` runs at line 1146 — leaking the agent's
+ * entry in the in-memory `runnerAgents` map. Observable impact: memory
+ * grows unboundedly across runs, and a stale entry can re-trigger or
+ * misroute completion handling if the runner re-emits the event or the
+ * handler is retried for the same agentId.
+ *
+ * These tests use inline copies of the relevant slices (matching the
+ * convention in subAgentSpawner.test.js — pure logic copies instead of
+ * mocking the full async-heavy production function).
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
-import { spawningTasks } from './agentState.js';
+import { spawningTasks, runnerAgents } from './agentState.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');
@@ -318,3 +339,377 @@ describe('agentLifecycle source — spawningTasks delete placement', () => {
expect(fnBody).toMatch(finallyPattern);
});
});
+
+// ─── spawnAgentForTask — cleanupOnError ────────────────────────────────────
+//
+// `spawnAgentForTask` has ~400 LOC of async work between
+// `spawningTasks.add(task.id)` (line 134) and the try/finally (line 536).
+// Most detected-error paths inside that span call `cleanupOnError`, which
+// releases the dedup guard, the execution lane, and the tool-execution
+// state. The inline replica below mirrors that helper so we can pin the
+// invariants: every `cleanupOnError(...)` call MUST drop the guard. A
+// future refactor that inlines part of `cleanupOnError` is the kind of
+// drift this guard catches.
+
+function makeCleanupHarness(taskId, agentId) {
+ const released = [];
+ const completed = [];
+ const errored = [];
+
+ const cleanupOnError = (error) => {
+ spawningTasks.delete(taskId);
+ released.push({ agentId, reason: 'release' });
+ errored.push({ executionId: `exec-${agentId}`, message: error });
+ completed.push({ executionId: `exec-${agentId}`, success: false });
+ };
+
+ return { cleanupOnError, released, completed, errored };
+}
+
+describe('spawnAgentForTask — cleanupOnError error recovery', () => {
+ beforeEach(() => {
+ spawningTasks.clear();
+ });
+
+ it('releases the dedup guard when no AI provider is configured', () => {
+ // Production line 169: `cleanupOnError('No active AI provider configured')`
+ // when getActiveProvider() returns null.
+ const task = { id: 'task-no-provider' };
+ spawningTasks.add(task.id);
+ const harness = makeCleanupHarness(task.id, 'agent-1');
+
+ harness.cleanupOnError('No active AI provider configured');
+
+ expect(spawningTasks.has(task.id)).toBe(false);
+ expect(harness.released).toHaveLength(1);
+ expect(harness.errored[0].message).toBe('No active AI provider configured');
+ expect(harness.completed[0].success).toBe(false);
+ });
+
+ it('releases the dedup guard when provider is unavailable and no fallback exists', () => {
+ // Production line 199: cleanupOnError fires on the no-fallback path.
+ const task = { id: 'task-unavailable-provider' };
+ spawningTasks.add(task.id);
+ const harness = makeCleanupHarness(task.id, 'agent-2');
+
+ harness.cleanupOnError('Provider anthropic unavailable (usage-limit) and no fallback available');
+
+ expect(spawningTasks.has(task.id)).toBe(false);
+ expect(harness.completed[0].success).toBe(false);
+ });
+
+ it('releases the dedup guard when a git conflict defers the task', () => {
+ // Production line 300: cleanupOnError fires after creating the conflict
+ // resolution task and re-queueing the original.
+ const task = { id: 'task-git-conflict' };
+ spawningTasks.add(task.id);
+ const harness = makeCleanupHarness(task.id, 'agent-3');
+
+ harness.cleanupOnError('Git conflict blocks task — conflict resolution task created');
+
+ expect(spawningTasks.has(task.id)).toBe(false);
+ });
+
+ it('releases the dedup guard when updateTask fails to flip status to in_progress', () => {
+ // Production line 512: `cleanupOnError('Failed to update task status')`
+ // when `updateTask` returns null (parse error, file missing, etc.).
+ const task = { id: 'task-update-failed' };
+ spawningTasks.add(task.id);
+ const harness = makeCleanupHarness(task.id, 'agent-4');
+
+ harness.cleanupOnError('Failed to update task status');
+
+ expect(spawningTasks.has(task.id)).toBe(false);
+ });
+
+ // ─── Deferred-fix coverage ──────────────────────────────────────────────
+ //
+ // PLAN.md → Backlog has a separate item: "Widen `spawningTasks`
+ // try/finally in `agentLifecycle.js#spawnAgentForTask`". Today's
+ // try/finally only wraps the `spawnViaRunner` / `spawnDirectly` calls
+ // (lines 536–547). The ~400 LOC above (buildAgentPrompt, writeFile,
+ // createAgentRun, registerAgent, etc.) is NOT inside any try/catch. A
+ // throw on any of those paths leaves `spawningTasks` registered FOREVER,
+ // permanently blocking future spawns of that task id.
+ //
+ // The detected-error paths above use `cleanupOnError` and are safe. The
+ // SKIPPED tests below pin the gap: an uncaught throw from one of those
+ // mid-spawn async steps leaks the guard. They flip green when the
+ // backlog widen-try-finally fix lands.
+
+ it.skip('TODO(plan.md backlog): a throw from buildAgentPrompt leaves the guard set forever', async () => {
+ // PRE-FIX: throws from lines ~165–525 are NOT in a try/finally, so the
+ // guard leaks. Once the fix widens the try/finally up to the
+ // `spawningTasks.add(task.id)` line, this becomes pass-by-construction.
+ // Production reference: agentLifecycle.js:443 `buildAgentPrompt` call.
+ const task = { id: 'task-prompt-throw' };
+ async function simulateProductionPreFix() {
+ spawningTasks.add(task.id);
+ // The actual production code does not wrap this in a try/catch.
+ // We simulate a throw HERE — outside any guard.
+ throw new Error('prompt build failed (ENOSPC)');
+ }
+ await expect(simulateProductionPreFix()).rejects.toThrow('prompt build failed');
+ // BUG (today): guard leaks. After the backlog fix this becomes false.
+ expect(spawningTasks.has(task.id)).toBe(true);
+ });
+
+ it.skip('TODO(plan.md backlog): a throw from writeFile(prompt) leaves the guard set forever', async () => {
+ // Production reference: agentLifecycle.js:452 `writeFile(join(agentDir, 'prompt.txt'), prompt)`.
+ // Same shape as the buildAgentPrompt skip — separate test so the
+ // failure surface is easier to read after the fix lands.
+ const task = { id: 'task-writefile-throw' };
+ async function simulateProductionPreFix() {
+ spawningTasks.add(task.id);
+ throw new Error('writeFile failed (EACCES)');
+ }
+ await expect(simulateProductionPreFix()).rejects.toThrow();
+ expect(spawningTasks.has(task.id)).toBe(true);
+ });
+
+ it.skip('TODO(plan.md backlog): a throw from createAgentRun leaves the guard set forever', async () => {
+ // Production reference: agentLifecycle.js:455 `createAgentRun(agentId, ...)`.
+ const task = { id: 'task-runs-throw' };
+ async function simulateProductionPreFix() {
+ spawningTasks.add(task.id);
+ throw new Error('createAgentRun failed (DB write)');
+ }
+ await expect(simulateProductionPreFix()).rejects.toThrow();
+ expect(spawningTasks.has(task.id)).toBe(true);
+ });
+
+ it.skip('TODO(plan.md backlog): a throw from registerAgent leaves the guard set forever', async () => {
+ // Production reference: agentLifecycle.js:458 `registerAgent(agentId, task.id, {...})`.
+ const task = { id: 'task-register-throw' };
+ async function simulateProductionPreFix() {
+ spawningTasks.add(task.id);
+ throw new Error('registerAgent failed (state mutex lost)');
+ }
+ await expect(simulateProductionPreFix()).rejects.toThrow();
+ expect(spawningTasks.has(task.id)).toBe(true);
+ });
+});
+
+// ─── handleAgentCompletion error recovery ──────────────────────────────────
+//
+// `handleAgentCompletion` (agentLifecycle.js:841) does:
+// ... read agent ...
+// completeAgent(agentId, {...}) // line 939
+// updateTask(task.id, {...}) // line 954 / 960
+// processAgentCompletion(...) // line 987
+// ... JIRA / plan-question / pipeline ...
+// runnerAgents.delete(agentId) // line 1146 — runner cleanup
+//
+// None of the inner steps are wrapped in try/catch. A throw from any of
+// them aborts the function, leaving the runnerAgents Map entry and the
+// task status in whatever transitional state the failed step left them.
+// The inline copies below model that flow so we can pin the documented
+// gap.
+
+function makeCompletionHarness({ taskId, agentId, throws = {}, taskType = 'user', runId = null }) {
+ const calls = [];
+ return {
+ agentId,
+ taskId,
+ completeAgent: async (id, info) => {
+ calls.push({ step: 'completeAgent', id, info });
+ if (throws.completeAgent) throw new Error('completeAgent failed: state save error');
+ },
+ completeAgentRun: async (rid, output, code, dur, err) => {
+ calls.push({ step: 'completeAgentRun', rid });
+ if (throws.completeAgentRun) throw new Error('completeAgentRun failed');
+ },
+ updateTask: async (id, updates, ttype) => {
+ calls.push({ step: 'updateTask', id, status: updates.status, ttype });
+ if (throws.updateTask) throw new Error('updateTask failed');
+ return { id, status: updates.status };
+ },
+ processAgentCompletion: async (id, t, ok, out) => {
+ calls.push({ step: 'processAgentCompletion', id, ok });
+ if (throws.processAgentCompletion) throw new Error('processAgentCompletion failed: hook crash');
+ },
+ /** Mirrors the final `runnerAgents.delete(agentId)` at line 1146. */
+ deleteRunner: () => {
+ calls.push({ step: 'deleteRunner', agentId });
+ runnerAgents.delete(agentId);
+ },
+ calls,
+ taskType,
+ runId,
+ };
+}
+
+/**
+ * Inline replica of the completion flow up to and including the cleanup
+ * delete. Mirrors agentLifecycle.js lines 935–987 + 1146, with branching
+ * on `effectiveSuccess` as in production.
+ */
+async function runCompletion(harness, effectiveSuccess) {
+ await harness.completeAgent(harness.agentId, { success: effectiveSuccess });
+ if (harness.runId) {
+ await harness.completeAgentRun(harness.runId);
+ }
+ if (effectiveSuccess) {
+ await harness.updateTask(harness.taskId, { status: 'completed' }, harness.taskType);
+ } else {
+ await harness.updateTask(harness.taskId, { status: 'pending' }, harness.taskType);
+ }
+ await harness.processAgentCompletion(harness.agentId, { id: harness.taskId }, effectiveSuccess, '');
+ harness.deleteRunner();
+}
+
+describe('handleAgentCompletion — happy path', () => {
+ beforeEach(() => {
+ runnerAgents.clear();
+ });
+
+ it('marks task completed, processes hooks, and removes the runner record on success', async () => {
+ runnerAgents.set('agent-A', { taskId: 'task-A' });
+ const h = makeCompletionHarness({ taskId: 'task-A', agentId: 'agent-A' });
+
+ await runCompletion(h, true);
+
+ expect(h.calls.map(c => c.step)).toEqual([
+ 'completeAgent',
+ 'updateTask',
+ 'processAgentCompletion',
+ 'deleteRunner',
+ ]);
+ expect(h.calls.find(c => c.step === 'updateTask').status).toBe('completed');
+ expect(runnerAgents.has('agent-A')).toBe(false);
+ });
+
+ it('failure path: task stays pending, runner record still deleted', async () => {
+ runnerAgents.set('agent-B', { taskId: 'task-B' });
+ const h = makeCompletionHarness({ taskId: 'task-B', agentId: 'agent-B' });
+
+ await runCompletion(h, false);
+
+ expect(h.calls.find(c => c.step === 'updateTask').status).toBe('pending');
+ expect(runnerAgents.has('agent-B')).toBe(false);
+ });
+});
+
+describe('handleAgentCompletion — error recovery (uncovered today)', () => {
+ beforeEach(() => {
+ runnerAgents.clear();
+ });
+
+ it('regression-pin: a throw from completeAgent (state save) prevents runner cleanup', async () => {
+ // Production reference: agentLifecycle.js:939 — `await completeAgent(...)`
+ // is NOT wrapped in try/catch. A throw bubbles to the caller, but more
+ // importantly skips lines 940–1146, including the final
+ // `runnerAgents.delete(agentId)`. The runner record is leaked.
+ runnerAgents.set('agent-C', { taskId: 'task-C' });
+ const h = makeCompletionHarness({
+ taskId: 'task-C',
+ agentId: 'agent-C',
+ throws: { completeAgent: true },
+ });
+
+ await expect(runCompletion(h, true)).rejects.toThrow('completeAgent failed');
+
+ // BUG (documented): the runner-agents Map still has agent-C. A
+ // follow-up completion event for the same agentId would re-enter
+ // handleAgentCompletion and re-trigger the failing step. PLAN.md
+ // backlog should track wrapping these steps in try/catch with a final
+ // `runnerAgents.delete` in a finally block.
+ expect(runnerAgents.has('agent-C')).toBe(true);
+
+ // Downstream steps (updateTask, processAgentCompletion) never ran.
+ expect(h.calls.map(c => c.step)).toEqual(['completeAgent']);
+ });
+
+ it('regression-pin: a throw from updateTask leaves runner record + skips post-completion hooks', async () => {
+ // Production reference: agentLifecycle.js:954 (success branch) / 960
+ // (failure branch). The function only inspects `result?.error` for
+ // soft-fail values — an actual thrown error bubbles up and skips
+ // processAgentCompletion + the final cleanup.
+ runnerAgents.set('agent-D', { taskId: 'task-D' });
+ const h = makeCompletionHarness({
+ taskId: 'task-D',
+ agentId: 'agent-D',
+ throws: { updateTask: true },
+ });
+
+ await expect(runCompletion(h, true)).rejects.toThrow('updateTask failed');
+
+ expect(runnerAgents.has('agent-D')).toBe(true);
+ // processAgentCompletion never invoked — memory extraction skipped.
+ expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'updateTask']);
+ });
+
+ it('regression-pin: a throw from processAgentCompletion (hook dispatch) leaks the runner record', async () => {
+ // Production reference: agentLifecycle.js:987 — the memory-extraction /
+ // app-cooldown hook is called as `await processAgentCompletion(...)`
+ // with no try/catch. A crash inside the hook (memory store down,
+ // extraction throw) abandons the rest of the cleanup.
+ runnerAgents.set('agent-E', { taskId: 'task-E' });
+ const h = makeCompletionHarness({
+ taskId: 'task-E',
+ agentId: 'agent-E',
+ throws: { processAgentCompletion: true },
+ });
+
+ await expect(runCompletion(h, true)).rejects.toThrow('processAgentCompletion failed');
+
+ expect(runnerAgents.has('agent-E')).toBe(true);
+ // completeAgent + updateTask DID run — the task is marked completed in
+ // state, but the runner record is still cached in memory. A subsequent
+ // event for the same agentId hits the `if (!agent)` branch incorrectly
+ // because the agent IS still cached, leading to re-attempted hook
+ // dispatch that throws again.
+ expect(h.calls.find(c => c.step === 'completeAgent')).toBeDefined();
+ expect(h.calls.find(c => c.step === 'updateTask')).toBeDefined();
+ expect(h.calls.find(c => c.step === 'deleteRunner')).toBeUndefined();
+ });
+
+ it('regression-pin: a throw from completeAgentRun (run-tracking) leaves the runner record', async () => {
+ // Production reference: agentLifecycle.js:949 — only invoked when
+ // runId exists. completeAgentRun writes usage stats; a write failure
+ // shouldn't strand the runner-agent map.
+ runnerAgents.set('agent-F', { taskId: 'task-F' });
+ const h = makeCompletionHarness({
+ taskId: 'task-F',
+ agentId: 'agent-F',
+ runId: 'run-123',
+ throws: { completeAgentRun: true },
+ });
+
+ await expect(runCompletion(h, true)).rejects.toThrow('completeAgentRun failed');
+
+ expect(runnerAgents.has('agent-F')).toBe(true);
+ });
+});
+
+// Source-level regression: a future refactor MUST keep the runner cleanup
+// at the very tail of `handleAgentCompletion`. If someone moves the delete
+// into a guard branch (e.g. only on success), this catches it.
+
+describe('agentLifecycle source — runner cleanup placement', () => {
+ it('handleAgentCompletion ends with runnerAgents.delete(agentId)', () => {
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
+ expect(fnStart, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
+
+ // Find the closing brace of the top-level function body.
+ const bodyStart = AGENT_LIFECYCLE_SRC.indexOf('{', fnStart);
+ let depth = 0;
+ let bodyEnd = bodyStart;
+ for (let i = bodyStart; i < AGENT_LIFECYCLE_SRC.length; i++) {
+ const c = AGENT_LIFECYCLE_SRC[i];
+ if (c === '{') depth++;
+ else if (c === '}') {
+ depth--;
+ if (depth === 0) { bodyEnd = i; break; }
+ }
+ }
+
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(bodyStart, bodyEnd);
+
+ // The terminal cleanup line lives near the very bottom of the function.
+ // Check it appears in the last 200 chars of the body so a refactor that
+ // moves it into a conditional branch shows up red here.
+ const tail = fnBody.slice(-200);
+ expect(tail).toMatch(/runnerAgents\.delete\(agentId\)/);
+ });
+});
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
new file mode 100644
index 0000000000..de6b312a00
--- /dev/null
+++ b/server/services/cos.test.js
@@ -0,0 +1,650 @@
+/**
+ * Tests for cos.js — focused on the two hot-spot internals that gate every
+ * agent spawn but have no full-function test sibling:
+ *
+ * 1. `evaluateTasks` priority ordering — Priority 0 (on-demand) > Priority 1
+ * (user) > Priority 2 (auto-approved system) > Priority 3 (mission /
+ * feature agent) > Priority 4 (idle review). Within a priority bucket
+ * tasks are taken in the order they appear in TASKS.md (the parser sorts
+ * nothing for the pending slice — file order is the tie-breaker).
+ *
+ * 2. `dequeueNextTask` capacity guards — global `maxConcurrentAgents` cap
+ * and per-project `maxConcurrentAgentsPerProject` cap. The function must
+ * short-circuit when no slots are available and must skip tasks whose
+ * project bucket is already saturated even if the global slot count
+ * permits one more spawn.
+ *
+ * `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.
+ *
+ * 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
+ * future refactor that reorders priorities or removes the
+ * `availableSlots <= 0` short-circuit flips a clear red flag.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
+
+// ─── Inline replicas of the cos.js priority + capacity slice ───────────────
+
+/**
+ * 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.
+ */
+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 };
+}
+
+/**
+ * Replica of the priority-bucket loop in `evaluateTasks` / `dequeueNextTask`.
+ * The production code merges five buckets in this exact order:
+ *
+ * 0. onDemand — explicit user requests (highest)
+ * 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)
+ *
+ * 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.
+ *
+ * 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.
+ */
+function priorityDequeue(buckets, capacity) {
+ 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 hasPendingUserTasks = (buckets.user || []).length > 0;
+
+ for (const bucketName of order) {
+ 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;
+ if (!capacity.canSpawn(task)) continue;
+ capacity.trackSpawn({ ...task, _bucket: bucketName });
+ }
+ }
+ return capacity.spawned;
+}
+
+// ─── Fixture helpers ───────────────────────────────────────────────────────
+
+function makeState({ maxConcurrentAgents = 3, maxConcurrentAgentsPerProject = null, runningAgents = [] } = {}) {
+ return {
+ config: { maxConcurrentAgents, maxConcurrentAgentsPerProject },
+ agents: Object.fromEntries(runningAgents.map((a, i) => [`agent-${i}`, a])),
+ };
+}
+
+function makeRunningAgent(app = '_self') {
+ return { status: 'running', metadata: { taskApp: app, app } };
+}
+
+const task = (id, priority = 'MEDIUM', { app } = {}) => ({
+ id,
+ priority,
+ status: 'pending',
+ metadata: app !== undefined ? { app } : {},
+});
+
+// ─── evaluateTasks: priority ordering ──────────────────────────────────────
+
+describe('evaluateTasks — priority ordering', () => {
+ it('drains buckets in order: onDemand > user > autoSystem > mission > idle', () => {
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [task('task-onDemand-1')],
+ user: [task('task-user-1')],
+ autoSystem: [task('sys-auto-1')],
+ // Mission/idle should be SKIPPED here because user bucket is non-empty
+ // (matches production line 795 `hasPendingUserTasks` gate).
+ mission: [task('sys-mission-1')],
+ idle: [task('sys-idle-1')],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+
+ // Order is: onDemand, user, autoSystem (mission/idle blocked by user-pending gate)
+ expect(spawned.map(t => t.id)).toEqual([
+ 'task-onDemand-1',
+ 'task-user-1',
+ 'sys-auto-1',
+ ]);
+ expect(spawned.map(t => t._bucket)).toEqual(['onDemand', 'user', 'autoSystem']);
+ });
+
+ it('mission + idle fire only when there are NO pending user tasks', () => {
+ // Idle is fenced behind `spawned === 0` in production (cos.js:2480), so
+ // when autoSystem and mission are both non-empty, idle does NOT fire.
+ // This test pins the user-pending gate; the next test pins the idle
+ // `spawned === 0` gate.
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [], // ← critical: no pending user tasks
+ autoSystem: [task('sys-auto-1')],
+ mission: [task('sys-mission-1')],
+ idle: [task('sys-idle-1')],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ // autoSystem + mission spawn; idle is SUPPRESSED because earlier buckets
+ // already produced spawns (mirrors cos.js:2480 `spawned === 0` guard).
+ expect(spawned.map(t => t._bucket)).toEqual(['autoSystem', 'mission']);
+ });
+
+ it('idle fires only when nothing else has spawned (spawned === 0 gate, cos.js:2480)', () => {
+ // When autoSystem and mission are both empty AND no user-pending, idle
+ // gets to run. This is the only path through which the idle bucket
+ // actually drains in production.
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [],
+ autoSystem: [],
+ mission: [],
+ idle: [task('sys-idle-1')],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t._bucket)).toEqual(['idle']);
+ });
+
+ it('idle suppressed when only autoSystem spawned (no user, no mission)', () => {
+ // Pin the asymmetry: even a SINGLE autoSystem spawn is enough to suppress
+ // idle on the same cycle. This is the production behavior at cos.js:862
+ // (`tasksToSpawn.length === 0`) and cos.js:2480 (`spawned === 0`).
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [],
+ autoSystem: [task('sys-auto-1')],
+ mission: [],
+ idle: [task('sys-idle-1')],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t._bucket)).toEqual(['autoSystem']);
+ });
+
+ it('within a single bucket, file/arrival order wins (no in-bucket priority re-sort)', () => {
+ // The dequeue loop does NOT sort by priorityValue at this layer. The
+ // parsed-tasks slice preserves file order, so a HIGH task placed AFTER
+ // a LOW task in TASKS.md is taken AFTER the LOW task. This is the
+ // documented contract: callers using `addTask({ position: 'top' })` are
+ // expected to control ordering at write time.
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [
+ task('task-low-first', 'LOW'),
+ task('task-high-second', 'HIGH'),
+ task('task-critical-third', 'CRITICAL'),
+ ],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t.id)).toEqual([
+ 'task-low-first',
+ 'task-high-second',
+ 'task-critical-third',
+ ]);
+ });
+
+ it('stops issuing spawns once availableSlots is exhausted (cross-bucket)', () => {
+ // Only 2 free slots — onDemand fills slot 1, user fills slot 2, the rest
+ // of the queues are left untouched.
+ const state = makeState({ maxConcurrentAgents: 2 });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [task('task-onDemand-1')],
+ user: [task('task-user-1'), task('task-user-2')],
+ autoSystem: [task('sys-auto-1')],
+ mission: [],
+ idle: [],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned).toHaveLength(2);
+ expect(spawned.map(t => t.id)).toEqual(['task-onDemand-1', 'task-user-1']);
+ });
+
+ it('returns no spawns when buckets are empty (idle queue)', () => {
+ const state = makeState({ maxConcurrentAgents: 5 });
+ const capacity = makeCapacityTracker(state);
+ const buckets = { onDemand: [], user: [], autoSystem: [], mission: [], idle: [] };
+ expect(priorityDequeue(buckets, capacity)).toEqual([]);
+ });
+});
+
+// ─── dequeueNextTask: capacity guards ──────────────────────────────────────
+
+describe('dequeueNextTask — capacity guards', () => {
+ it('returns zero spawns when running agents already saturate the global cap', () => {
+ // 3-slot cap, 3 already running — no headroom.
+ const state = makeState({
+ maxConcurrentAgents: 3,
+ runningAgents: [makeRunningAgent(), makeRunningAgent(), makeRunningAgent()],
+ });
+ const capacity = makeCapacityTracker(state);
+ expect(capacity.availableSlots).toBe(0);
+
+ const buckets = {
+ onDemand: [task('task-onDemand-1')],
+ user: [task('task-user-1')],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned).toEqual([]);
+ });
+
+ it('returns zero spawns when running agents OVER-saturate the cap (>= guard, not ==)', () => {
+ // Defensive: if some path registered more agents than the cap (e.g. a
+ // config change shrunk the cap below current load), availableSlots goes
+ // negative — the guard must still block, not let `< 0` slip through as
+ // "infinite slots".
+ const state = makeState({
+ maxConcurrentAgents: 2,
+ runningAgents: [makeRunningAgent(), makeRunningAgent(), makeRunningAgent()],
+ });
+ const capacity = makeCapacityTracker(state);
+ expect(capacity.availableSlots).toBeLessThan(0);
+
+ const buckets = { onDemand: [], user: [task('task-user-1')], autoSystem: [], mission: [], idle: [] };
+ expect(priorityDequeue(buckets, capacity)).toEqual([]);
+ });
+
+ it('respects per-project cap: project saturated → task skipped, other-project task still fills', () => {
+ // Global cap 5, but per-project cap 1. App "alpha" already has 1
+ // running agent, so its pending user task must be skipped. The pending
+ // task for app "beta" should still spawn (different bucket of the
+ // per-project counter).
+ const state = makeState({
+ maxConcurrentAgents: 5,
+ maxConcurrentAgentsPerProject: 1,
+ runningAgents: [makeRunningAgent('alpha')],
+ });
+ const agentsByProject = { alpha: 1 };
+ const capacity = makeCapacityTracker(state, agentsByProject);
+
+ const buckets = {
+ onDemand: [],
+ user: [
+ task('task-alpha-1', 'HIGH', { app: 'alpha' }),
+ task('task-beta-1', 'MEDIUM', { app: 'beta' }),
+ ],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t.id)).toEqual(['task-beta-1']);
+ });
+
+ it('per-project cap counts in-batch spawns too (not just pre-existing runners)', () => {
+ // Per-project cap 2, none running. Three user tasks all on app "alpha".
+ // First two must spawn, third must be skipped (in-batch spawn count
+ // pushed alpha to the per-project cap).
+ const state = makeState({
+ maxConcurrentAgents: 10,
+ maxConcurrentAgentsPerProject: 2,
+ });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [
+ task('task-alpha-1', 'HIGH', { app: 'alpha' }),
+ task('task-alpha-2', 'HIGH', { app: 'alpha' }),
+ task('task-alpha-3', 'HIGH', { app: 'alpha' }),
+ ],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t.id)).toEqual(['task-alpha-1', 'task-alpha-2']);
+ expect(capacity.spawnProjectCounts.alpha).toBe(2);
+ });
+
+ it('per-project cap defaults to global cap when null/0', () => {
+ // When maxConcurrentAgentsPerProject is null, production lines 638 +
+ // 2334 fall through to the global cap, so the per-project guard is
+ // effectively disabled.
+ const state = makeState({
+ maxConcurrentAgents: 3,
+ maxConcurrentAgentsPerProject: null,
+ });
+ const capacity = makeCapacityTracker(state);
+ expect(capacity.perProjectLimit).toBe(3);
+
+ const buckets = {
+ onDemand: [],
+ user: [
+ task('task-alpha-1', 'HIGH', { app: 'alpha' }),
+ task('task-alpha-2', 'HIGH', { app: 'alpha' }),
+ task('task-alpha-3', 'HIGH', { app: 'alpha' }),
+ ],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+
+ expect(priorityDequeue(buckets, capacity)).toHaveLength(3);
+ });
+
+ it('null app metadata buckets into the `_self` project key (PortOS work)', () => {
+ // PortOS-on-itself tasks have no app metadata. The `_self` bucket is a
+ // sentinel that prevents app-less tasks from bypassing the per-project
+ // cap (which is a real production guarantee — see line 659).
+ const state = makeState({
+ maxConcurrentAgents: 5,
+ maxConcurrentAgentsPerProject: 1,
+ });
+ const capacity = makeCapacityTracker(state);
+
+ const buckets = {
+ onDemand: [],
+ user: [
+ task('task-self-1', 'HIGH'),
+ task('task-self-2', 'HIGH'),
+ ],
+ autoSystem: [],
+ mission: [],
+ idle: [],
+ };
+
+ const spawned = priorityDequeue(buckets, capacity);
+ expect(spawned.map(t => t.id)).toEqual(['task-self-1']);
+ expect(capacity.spawnProjectCounts._self).toBe(1);
+ });
+});
+
+// ─── Source-level regression guards ────────────────────────────────────────
+//
+// These pin two structural invariants of the production code that the
+// inline-copy tests can't catch on their own. If a future refactor moves
+// the early-return out of `dequeueNextTask` or shuffles the priority order,
+// these assertions flip red.
+
+/**
+ * Extract a function body from `src` starting at signature offset `fnStart`
+ * by scanning braces (depth-tracked) until the matching closing `}`. This is
+ * more robust than a fixed-length slice — large functions like
+ * `dequeueNextTask` (~250 LOC) can grow past any chosen window and silently
+ * drop priority markers, making ordering assertions pass on empty matches.
+ *
+ * Skips brace characters inside string literals (single/double quote AND
+ * template literals, including nested `${...}` interpolations), regex
+ * literals, and line/block comments so stray `{`/`}` characters don't
+ * unbalance the scanner. `evaluateTasks` and `dequeueNextTask` both contain
+ * template literals like `emitLog(`...${task.id}...`)` whose `${...}` braces
+ * would otherwise be counted as structural braces.
+ *
+ * Regex disambiguation uses a "previous significant token" heuristic — a `/`
+ * is a regex literal when the preceding non-whitespace token is not an
+ * identifier/number/closing-bracket. This handles the patterns used in cos.js
+ * (assignment, return, function-arg position) but isn't a full JS tokenizer;
+ * if a future refactor introduces edge cases the source-level assertions
+ * will fail loudly rather than silently miss matches.
+ */
+function extractFnBody(src, fnStart) {
+ const openIdx = src.indexOf('{', fnStart);
+ if (openIdx === -1) return '';
+ let depth = 0;
+ let i = openIdx;
+ // Stack tracks nested template-literal `${...}` interpolation depth so the
+ // scanner returns to template-string mode after a `}` closes an expression.
+ const tplStack = [];
+ // Last significant (non-whitespace, non-comment) character — used to decide
+ // whether `/` starts a regex literal or is the division operator.
+ let lastSig = '';
+ const setLastSig = (c) => { if (!/\s/.test(c)) lastSig = c; };
+
+ while (i < src.length) {
+ const ch = src[i];
+ const next = src[i + 1];
+ // Line comment — skip to newline
+ if (ch === '/' && next === '/') {
+ const nl = src.indexOf('\n', i + 2);
+ i = nl === -1 ? src.length : nl + 1;
+ continue;
+ }
+ // Block comment — skip to closing */
+ if (ch === '/' && next === '*') {
+ const end = src.indexOf('*/', i + 2);
+ i = end === -1 ? src.length : end + 2;
+ continue;
+ }
+ // Regex literal — `/` is a regex start when not preceded by an
+ // identifier/number/closing-paren/closing-bracket (i.e. when it can't be
+ // the division operator). Skip to matching unescaped `/` (and flags).
+ if (ch === '/' && !/[\w)\]]/.test(lastSig)) {
+ let j = i + 1;
+ let inClass = false;
+ while (j < src.length) {
+ const c = src[j];
+ if (c === '\\') { j += 2; continue; }
+ if (c === '[') inClass = true;
+ else if (c === ']') inClass = false;
+ else if (c === '/' && !inClass) break;
+ else if (c === '\n') break; // unterminated regex — bail
+ j++;
+ }
+ // Skip trailing flags (g/i/m/s/u/y)
+ j++;
+ while (j < src.length && /[gimsuy]/.test(src[j])) j++;
+ i = j;
+ lastSig = '/';
+ continue;
+ }
+ // Single/double-quoted string — skip to matching unescaped quote
+ if (ch === '"' || ch === "'") {
+ let j = i + 1;
+ while (j < src.length) {
+ if (src[j] === '\\') { j += 2; continue; }
+ if (src[j] === ch) break;
+ if (src[j] === '\n') break; // unterminated — bail
+ j++;
+ }
+ i = j + 1;
+ lastSig = ch;
+ continue;
+ }
+ // Template literal — scan until backtick or `${`. On `${` push depth and
+ // resume normal scanning until matching `}` (tracked via tplStack).
+ if (ch === '`') {
+ let j = i + 1;
+ while (j < src.length) {
+ if (src[j] === '\\') { j += 2; continue; }
+ if (src[j] === '`') { j++; break; }
+ if (src[j] === '$' && src[j + 1] === '{') {
+ // Enter interpolation; resume outer loop, push template marker.
+ tplStack.push(depth);
+ i = j + 2;
+ depth++; // the `{` of ${
+ lastSig = '{';
+ break;
+ }
+ j++;
+ }
+ if (j >= i) { // either closed the template or entered interpolation
+ if (src[i] === undefined) break;
+ if (tplStack.length === 0 || tplStack[tplStack.length - 1] !== depth - 1) {
+ // We closed the template entirely (didn't enter interpolation).
+ i = j;
+ lastSig = '`';
+ }
+ }
+ continue;
+ }
+ if (ch === '{') { depth++; setLastSig(ch); i++; continue; }
+ if (ch === '}') {
+ depth--;
+ // If we just closed a template interpolation, resume template scan.
+ if (tplStack.length > 0 && tplStack[tplStack.length - 1] === depth) {
+ tplStack.pop();
+ // Resume template literal scan from i+1
+ let j = i + 1;
+ while (j < src.length) {
+ if (src[j] === '\\') { j += 2; continue; }
+ if (src[j] === '`') { j++; break; }
+ if (src[j] === '$' && src[j + 1] === '{') {
+ tplStack.push(depth);
+ j += 2;
+ depth++;
+ break;
+ }
+ j++;
+ }
+ i = j;
+ lastSig = '`';
+ continue;
+ }
+ if (depth === 0) return src.slice(fnStart, i + 1);
+ setLastSig(ch);
+ i++;
+ continue;
+ }
+ setLastSig(ch);
+ i++;
+ }
+ return src.slice(fnStart); // unbalanced — return rest of file
+}
+
+describe('cos.js source — priority + capacity invariants', () => {
+ it('dequeueNextTask early-returns when availableSlots <= 0', () => {
+ const fnStart = COS_SRC.indexOf('async function dequeueNextTask');
+ expect(fnStart, 'dequeueNextTask must exist').toBeGreaterThan(-1);
+ const fnBody = extractFnBody(COS_SRC, fnStart);
+
+ // `if (availableSlots <= 0) return;` (line 2332) is the cheap guard
+ // that prevents spawning when the global cap is at or beyond capacity.
+ // Regex tolerates optional braces, optional semicolon, and optional
+ // single-line block (`{ return; }`) so a formatting refactor doesn't
+ // trip this behavioral check.
+ expect(fnBody).toMatch(
+ /if\s*\(\s*availableSlots\s*<=\s*0\s*\)\s*(?:\{\s*)?return\s*;?\s*(?:\})?/
+ );
+ });
+
+ it('evaluateTasks short-circuits when availableSlots <= 0', () => {
+ const fnStart = COS_SRC.indexOf('export async function evaluateTasks');
+ expect(fnStart, 'evaluateTasks must exist').toBeGreaterThan(-1);
+ const fnBody = extractFnBody(COS_SRC, fnStart);
+
+ 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.
+ //
+ // 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);
+ });
+
+ 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'));
+ const evalFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function evaluateTasks'));
+
+ const pattern = /maxConcurrentAgentsPerProject\s*\|\|\s*state\.config\.maxConcurrentAgents/;
+ expect(dequeueFn).toMatch(pattern);
+ expect(evalFn).toMatch(pattern);
+ });
+
+ 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'));
+ const evalFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function evaluateTasks'));
+
+ expect(dequeueFn).toMatch(/spawned\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
+ expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
+ });
+});