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: replace agentLifecycle/cos replica tests with real-helper imports (#2548)

[._.]/ Adam Eivyd9a43f8df79b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3a6560b48f..d8bd39529b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -67,3 +67,4 @@
- **[issue-2532] Extract the Shell page's socket/session/terminal lifecycle into a `useShellSession` hook.** `pages/Shell.jsx` inlined ~750 lines of xterm setup, the Socket.IO `shell:*` protocol, and the single-subscriber PTY attach/detach contract (the `pendingAttachRef {target,generation}` guards, `claim`-vs-user-intent handling, `userIdleRef` passive-idle gating, `mountedRef` deferred-work guards, and URL sync). That cohesive concern now lives in `client/src/hooks/useShellSession.js` — which documents the full attach/detach contract at the top of the file — and the route drops to a thin presentational shell (header, quick-commands, terminal container) plus two extracted panels, `components/shell/TerminalHotKeys.jsx` and `components/shell/ShellSessionTabs.jsx`. Pure structural refactor toward the WritersRoom pattern — behavior identical, generation guards preserved byte-for-byte, no route-contract change; lint, the hooks barrel test, and the client build stay green.
- **[issue-2580] Await the canvas draw assertions in `MidiVisualization.test.jsx` to fix a CI flake.** The "paints the roll" test `await`ed the footer text (`findByText(/3 notes · /)`) then *synchronously* asserted `expect(ctx.fill).toHaveBeenCalled()`, but the roll paints in the `<MidiPianoRoll>` child a tick after the footer text commits — so CI intermittently landed the paint one tick late and the assertion failed. That draw assertion (and the zoom-controls `ctx.clearRect` assertion, which followed the fit/zoom button clicks) are now wrapped in `waitFor(...)` so they wait for the draw deterministically. Audited the sibling songs canvas tests (`PianoRoll`, `MidiPianoRoll`, `Metronome`, `RoundStack`, `PitchTuner`, `SingToScore`, `SongTraining`, `ReferenceAnalysis`, `SongRecordings`): only `MidiVisualization` gates its paint behind async data loading, so it was the only racy one — `PianoRoll`/`MidiPianoRoll` assert after a synchronous `render()`/`pump()` (no text-`findBy` gap), and the rest have no canvas assertions. Test-only; each test keeps its own explicit `getContext` mock.
- **[issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak `activeRuns`.** `runner.js#executeApiRun` attached an `AbortController` but armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller in `activeRuns` — and thus the run slot — indefinitely; the CLI path (`executeCliRun`) already had an internal timeout, and the Runs-router path invoked the API runner with no outer guard. `executeApiRun` now accepts an optional `timeout` (falling back to `provider.timeout` then a 300s default, mirroring `aiProvider`/`askService`) and arms it before the fetch. A single-settlement gate (`markSettled()`) guarantees exactly one of {timer, response paths} finalizes the run: on timeout the timer aborts the fetch/reader AND independently finalizes the run as an `ERROR_CATEGORIES.TIMEOUT` failure — so a stalled fetch/stream, a provider that never responds, and even a `ensureProviderReady` hook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError's `UNKNOWN`/HTTP 0. Both the Runs router and `promptRunner` now thread their `effectiveTimeout` into the API call (parity with the CLI/TUI branches), so a per-call override — e.g. the importer's long stage timeout — governs the ceiling instead of being cut short by the provider/default fallback; `promptRunner`'s own timer is demoted to a delayed backstop so the runner's timeout wins classification. The non-2xx error-body read now runs with the abort timer still armed (a provider that sends error headers then stalls the body is cancelled, not hung), and the success-path finalization-failure fallback rebuilds metadata from the stored record so run identity survives a write error. New unit tests prove both a hung stream and a hung readiness hook flip `isRunActive` back to false and complete with `errorCategory: 'timeout'`.
+- **[issue-2548] Replace the vacuous agentLifecycle spawn/completion replica tests with imports of real guard helpers.** `agentLifecycle.test.js` re-implemented production logic — local `unfixedSpawn`/`fixedSpawn` copies of the `spawningTasks` dedup flow and a `runCompletion`/`makeCompletionHarness` copy of the completion try/finally — and never imported `spawnAgentForTask`/`handleAgentCompletion`, so they stayed green when production regressed. The two concurrency contracts those replicas modelled are now extracted into `server/services/agentGuards.js`: `withSpawnDedupGuard(spawningTasks, taskId, fn)` (acquire-before-first-await, hold across the whole spawn body incl. the runner-enqueue handoff, release in `finally`, `SPAWN_DEDUP_SKIP` on a concurrent duplicate) and `withMapEntryCleanup(map, key, fn)` (delete the `runnerAgents` entry in `finally` even when a completion step throws). `spawnAgentForTask` now wraps `runAgentSpawn` in the former (dropping six inline `spawningTasks.delete` sites), and `handleAgentCompletion` wraps its body in the latter — so the tests drive the exact code production runs. The late-delete race that spawned a second agent for the same task id is now a behavioral test against the real guard, not a hand-copied one; the remaining source-scan tests were trimmed to non-negotiable orderings (the handedOff pre-spawn/post-handoff split, the #1563 claim/register ordering, the #989 marker release, the #2243 runner env merge) plus two wiring guards that pin the delegation. `cos.test.js` already drove the real `createDequeueCapacity`/`isMissionTierEligible`/`isIdleTierEligible` exports after #2530, so it was left as-is. New `agentGuards.test.js` unit-tests both helpers in isolation.
diff --git a/server/services/agentGuards.js b/server/services/agentGuards.js
new file mode 100644
index 0000000000..7398ee2cee
--- /dev/null
+++ b/server/services/agentGuards.js
@@ -0,0 +1,72 @@
+/**
+ * Agent lifecycle guard primitives.
+ *
+ * Two tiny, dependency-injected control-flow helpers carved out of the
+ * ~470-LOC `spawnAgentForTask` and `handleAgentCompletion` orchestrators
+ * (agentLifecycle.js) so the concurrency contracts they enforce are unit-
+ * testable against the REAL code path instead of a hand-copied replica
+ * (issue #2548). Both operate purely on a Set/Map passed in — no module
+ * state, no I/O — so a test can drive them with a throwaway collection.
+ */
+
+/**
+ * Sentinel returned by `withSpawnDedupGuard` when the guard was already held
+ * for `taskId` — i.e. a concurrent spawn is already in flight and this call
+ * must not proceed. A Symbol (not `null`) so the caller can distinguish
+ * "deduped, do nothing" from a legitimate `null` result of the wrapped work.
+ */
+export const SPAWN_DEDUP_SKIP = Symbol('spawn-dedup-skip');
+
+/**
+ * Run `fn` under a per-task spawn dedup guard.
+ *
+ * Contract (the race closed by issue #1563 / the spawningTasks fix):
+ * 1. If `spawningTasks` already holds `taskId`, return `SPAWN_DEDUP_SKIP`
+ * without touching the set — a duplicate `task:ready` re-emit is rejected.
+ * 2. Otherwise acquire the guard SYNCHRONOUSLY (before the first `await`
+ * inside `fn`), so a second call landing while `fn` is suspended at any
+ * await sees the guard held and dedups at step 1 rather than spawning a
+ * second agent for the same task id.
+ * 3. Release the guard in a `finally` so it outlives the entire wrapped
+ * body — every early `return`, and any throw, still releases it. Holding
+ * the guard until `fn` settles (not merely until the task is flipped to
+ * in_progress) is what prevents the late-delete race where a racer slips
+ * in between the release and the runner actually accepting the agent.
+ *
+ * @param {Set<string>} spawningTasks - the in-process dedup set
+ * @param {string} taskId
+ * @param {() => Promise<any>} fn - the guarded spawn work
+ * @returns {Promise<any|typeof SPAWN_DEDUP_SKIP>}
+ */
+export async function withSpawnDedupGuard(spawningTasks, taskId, fn) {
+ if (spawningTasks.has(taskId)) return SPAWN_DEDUP_SKIP;
+ spawningTasks.add(taskId);
+ try {
+ return await fn();
+ } finally {
+ spawningTasks.delete(taskId);
+ }
+}
+
+/**
+ * Run `fn`, then unconditionally delete `key` from `map` in a `finally`.
+ *
+ * The completion-side counterpart to `withSpawnDedupGuard`: a throw from any
+ * inner step of `handleAgentCompletion` (completeAgent, updateTask,
+ * processAgentCompletion, finalizeAgent…) must never strand the agent's entry
+ * in the in-memory `runnerAgents` map — a stale entry grows memory unboundedly
+ * and can re-trigger/misroute completion if the runner re-emits the event.
+ * The error still propagates to the caller; the finally only guards the map.
+ *
+ * @param {Map<string, any>} map
+ * @param {string} key
+ * @param {() => Promise<any>} fn
+ * @returns {Promise<any>}
+ */
+export async function withMapEntryCleanup(map, key, fn) {
+ try {
+ return await fn();
+ } finally {
+ map.delete(key);
+ }
+}
diff --git a/server/services/agentGuards.test.js b/server/services/agentGuards.test.js
new file mode 100644
index 0000000000..455ccf0541
--- /dev/null
+++ b/server/services/agentGuards.test.js
@@ -0,0 +1,83 @@
+/**
+ * Focused unit tests for the agentGuards primitives in isolation (issue #2548).
+ *
+ * agentLifecycle.test.js drives these same helpers through the spawn/completion
+ * lenses; here we pin their bare contract against throwaway collections so a
+ * regression in the helper is unambiguous and doesn't require the lifecycle
+ * module's imports to load.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
+
+describe('withSpawnDedupGuard', () => {
+ it('acquires, runs, and releases on success', async () => {
+ const set = new Set();
+ const seen = [];
+ const result = await withSpawnDedupGuard(set, 'a', async () => {
+ seen.push(set.has('a')); // held during fn
+ return 42;
+ });
+ expect(seen).toEqual([true]);
+ expect(result).toBe(42);
+ expect(set.has('a')).toBe(false);
+ });
+
+ it('releases on throw and re-raises', async () => {
+ const set = new Set();
+ await expect(
+ withSpawnDedupGuard(set, 'a', async () => { throw new Error('boom'); })
+ ).rejects.toThrow('boom');
+ expect(set.has('a')).toBe(false);
+ });
+
+ it('short-circuits with SPAWN_DEDUP_SKIP when the key is already held', async () => {
+ const set = new Set(['a']);
+ let ran = false;
+ const result = await withSpawnDedupGuard(set, 'a', async () => { ran = true; });
+ expect(result).toBe(SPAWN_DEDUP_SKIP);
+ expect(ran).toBe(false);
+ expect(set.has('a')).toBe(true); // does not delete a guard it didn't acquire
+ });
+
+ it('SPAWN_DEDUP_SKIP is a distinct sentinel (not null/undefined)', () => {
+ expect(typeof SPAWN_DEDUP_SKIP).toBe('symbol');
+ expect(SPAWN_DEDUP_SKIP).not.toBeNull();
+ expect(SPAWN_DEDUP_SKIP).not.toBeUndefined();
+ });
+
+ it('adds the guard synchronously before fn yields', async () => {
+ const set = new Set();
+ let releaseGate;
+ const gate = new Promise((r) => { releaseGate = r; });
+ const inflight = withSpawnDedupGuard(set, 'a', async () => { await gate; return 'done'; });
+ // No await between the call and this assertion — the guard must already hold.
+ expect(set.has('a')).toBe(true);
+ releaseGate();
+ await inflight;
+ expect(set.has('a')).toBe(false);
+ });
+});
+
+describe('withMapEntryCleanup', () => {
+ it('runs fn, returns its value, and deletes the entry', async () => {
+ const map = new Map([['k', { v: 1 }]]);
+ const result = await withMapEntryCleanup(map, 'k', async () => 'ok');
+ expect(result).toBe('ok');
+ expect(map.has('k')).toBe(false);
+ });
+
+ it('deletes the entry even when fn throws, then re-raises', async () => {
+ const map = new Map([['k', { v: 1 }]]);
+ await expect(
+ withMapEntryCleanup(map, 'k', async () => { throw new Error('fail'); })
+ ).rejects.toThrow('fail');
+ expect(map.has('k')).toBe(false);
+ });
+
+ it('is a no-op when the key is absent', async () => {
+ const map = new Map();
+ await withMapEntryCleanup(map, 'missing', async () => {});
+ expect(map.has('missing')).toBe(false);
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 3d54d1d7b5..7123474f40 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -34,6 +34,7 @@ import { ensureInstanceId } from './instances.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner } from './cosTaskClaim.js';
import { resolveForgeTokenEnv } from './git.js';
import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
+import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
// Extracted helpers — these carve the two giant orchestrators
@@ -116,21 +117,31 @@ export async function syncRunnerAgents() {
/**
* Spawn an agent for a task.
+ *
+ * The entire spawn body runs under `withSpawnDedupGuard` (agentGuards.js),
+ * which owns the whole `spawningTasks` dedup lifecycle: it rejects a
+ * concurrent duplicate (the `has()` check → `SPAWN_DEDUP_SKIP`), acquires the
+ * guard SYNCHRONOUSLY before the first `await` in `runAgentSpawn`, and releases
+ * it in a `finally` so no early `return null` or throw can strand the task id
+ * in the set. Extracting the guard makes the late-delete race it closes
+ * unit-testable against the real helper (issue #2548) instead of a replica.
*/
export async function spawnAgentForTask(task) {
- if (spawningTasks.has(task.id)) {
+ const outcome = await withSpawnDedupGuard(spawningTasks, task.id, () => runAgentSpawn(task));
+ if (outcome === SPAWN_DEDUP_SKIP) {
console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);
return null;
}
+ return outcome;
+}
- // Acquire the in-process dedup guard SYNCHRONOUSLY — before any `await` below.
- // A `task:ready` re-emit for the same task id can land while this call is
- // suspended at an await (e.g. `ensureInstanceId()` / `getTaskById()`), and
- // EventEmitter does not serialize async listeners, so a guard taken after an
- // await would let a second call slip past the `has()` check above and spawn a
- // duplicate agent (codex review). Every early `return null` below releases it.
- spawningTasks.add(task.id);
-
+/**
+ * The guarded spawn body. Runs only inside `withSpawnDedupGuard` above, which
+ * holds the `spawningTasks` guard across this whole function and releases it in
+ * a finally — so this body never needs to touch the dedup set itself; every
+ * early `return null` and any throw is covered by the wrapper's release.
+ */
+async function runAgentSpawn(task) {
// Cross-instance claim guard (issue #1563, acceptance criterion 2). When this
// task list is shared with a federated peer (full-sync mode, #1561), the peer
// may already be working this task. Refuse to spawn while another instance
@@ -140,21 +151,17 @@ export async function spawnAgentForTask(task) {
// task; the authoritative acquire-with-fresh-reread happens below, before any
// spawn setup. No-op for a non-federated install (no claim metadata) and for
// re-claiming our own task on retry/resume.
- // Resolve identity defensively: this runs after `spawningTasks.add` but before
- // the main try/finally, so an uncaught rejection (e.g. cold-start identity
- // creation failing to write data/instances.json) would exit with the task id
- // stranded in `spawningTasks`, blocking every future spawn of it until restart
- // (codex review). Release the guard on failure.
+ // Resolve identity defensively: a cold-start identity failure (e.g. writing
+ // data/instances.json fails) returns null here; the wrapper's finally still
+ // releases the dedup guard, so the task id is never stranded in spawningTasks.
let instanceId;
try {
instanceId = await ensureInstanceId();
} catch (err) {
- spawningTasks.delete(task.id);
emitLog('error', `Failed to resolve instance identity for task ${task.id}: ${err?.message || err}`, { taskId: task.id });
return null;
}
if (!isClaimableBy(task.metadata, instanceId)) {
- spawningTasks.delete(task.id);
console.log(`🔒 Task ${task.id} is claimed by instance ${getClaimOwner(task.metadata)} (live lease) — skipping spawn on ${instanceId}`);
return null;
}
@@ -162,7 +169,6 @@ export async function spawnAgentForTask(task) {
// Check total spawn count across all retry types to prevent runaway respawning
const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
if (totalSpawns >= MAX_TOTAL_SPAWNS) {
- spawningTasks.delete(task.id);
console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);
await updateTask(task.id, {
status: 'blocked',
@@ -187,7 +193,6 @@ export async function spawnAgentForTask(task) {
const laneName = determineLane(task);
const laneResult = acquire(laneName, agentId, { taskId: task.id });
if (!laneResult.success) {
- spawningTasks.delete(task.id);
emitLog('warn', `Failed to tag lane ${laneName}: ${laneResult.error}`, { taskId: task.id });
await releaseAppReviewMarker(task.metadata?.app).catch(() => {});
return null;
@@ -214,7 +219,9 @@ export async function spawnAgentForTask(task) {
// no-op when the task carries no `metadata.app` or the marker is a real
// `agent-*` id from a different live agent.
const cleanupOnError = async (error) => {
- spawningTasks.delete(task.id);
+ // The spawn-dedup guard is released by withSpawnDedupGuard's finally around
+ // this whole body (see spawnAgentForTask) — cleanupOnError only owns the
+ // lane, tool-execution, claim, and app-review marker releases.
release(agentId);
errorExecution(toolExecution.id, { message: error });
completeExecution(toolExecution.id, { success: false });
@@ -270,10 +277,9 @@ export async function spawnAgentForTask(task) {
//
// - `handedOff === false` (pre-spawn): any uncaught throw from
// buildAgentPrompt / writeFile / createAgentRun / registerAgent /
- // worktree + JIRA provisioning. Release the dedup guard, the
- // execution lane, and the tool-execution state; without this, a
- // throw mid-setup leaks `spawningTasks` and permanently blocks
- // re-spawns of that task id until process restart. Also re-emit
+ // worktree + JIRA provisioning. cleanupOnError releases the execution
+ // lane and the tool-execution state (the dedup guard itself is released
+ // by withSpawnDedupGuard's finally around this whole body). Also re-emit
// `job:spawn-failed` for autonomous-job tasks so cos.js can clear
// its job-level guard immediately instead of waiting 5 minutes.
//
@@ -517,17 +523,16 @@ export async function spawnAgentForTask(task) {
worktree: !!worktreeInfo
});
- // Dedup-window fix: keep the `spawningTasks` guard active across the
- // actual spawn call, not just up to the in_progress flip. Releasing
- // between `updateTask` and `spawnViaRunner` / `spawnDirectly` opened a
- // window where a concurrent `spawnAgentForTask(task)` call (e.g. a
- // re-fired `task:ready` from a follow-up scheduler tick) saw an empty
- // set and a task whose registered agent hadn't yet been queued to the
- // runner, and proceeded to spawn a second agent for the same task id.
- // The outer finally below releases the guard whether the spawn returns
- // normally or rejects. release() must NOT run here on the success
- // path; the lane is released by the agent-completion handler when the
- // work finishes.
+ // Dedup-window fix: the `spawningTasks` guard stays held across the actual
+ // spawn call, not just up to the in_progress flip — withSpawnDedupGuard
+ // (around this whole body) only releases it once runAgentSpawn settles.
+ // Releasing between `updateTask` and `spawnViaRunner` / `spawnDirectly`
+ // opened a window where a concurrent `spawnAgentForTask(task)` call (e.g. a
+ // re-fired `task:ready` from a follow-up scheduler tick) saw an empty set
+ // and a task whose registered agent hadn't yet been queued to the runner,
+ // and proceeded to spawn a second agent for the same task id. release()
+ // must NOT run here on the success path; the lane is released by the
+ // agent-completion handler when the work finishes.
handedOff = true;
if (isTui) {
return await spawnTuiAgent({
@@ -585,9 +590,9 @@ export async function spawnAgentForTask(task) {
cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });
}
return null;
- } finally {
- spawningTasks.delete(task.id);
}
+ // No finally here: withSpawnDedupGuard (around runAgentSpawn) owns the
+ // spawningTasks release, so it fires whether this body returns or throws.
}
/**
@@ -1067,10 +1072,11 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
const { task, runId, model, executionId, laneName } = agent;
- // try/finally so a throw from any inner step still drops the runnerAgents
- // entry — otherwise a memory-extraction crash etc. would strand it forever
- // and no future spawn could reclaim the slot.
- try {
+ // withMapEntryCleanup drops the runnerAgents entry in a finally even if any
+ // inner completion step throws — otherwise a memory-extraction crash etc.
+ // would strand it forever and no future spawn could reclaim the slot. The
+ // error still propagates to the caller (agentGuards.js, issue #2548).
+ return withMapEntryCleanup(runnerAgents, agentId, async () => {
// Normalize the agent's task shape — recovered agents (post-restart,
// via syncRunnerAgents) may lack taskType AND metadata, both of which
// downstream paths spread / read without a guard.
@@ -1175,7 +1181,5 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// cleanup completed — without this the runner harness would never see
// the failure and couldn't requeue or alert.
if (finalizeError) throw finalizeError;
- } finally {
- runnerAgents.delete(agentId);
- }
+ });
}
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 07446a98b0..cb7796a321 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -1,48 +1,28 @@
/**
- * Tests for agentLifecycle — three concerns:
+ * Tests for the agent-lifecycle concurrency guards.
*
- * 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).
+ * The two guard primitives that gate every spawn + completion were extracted
+ * into agentGuards.js (issue #2548) precisely so these tests drive the REAL
+ * code path instead of a hand-copied replica of spawnAgentForTask /
+ * handleAgentCompletion:
*
- * The production race (pre-fix, agentLifecycle.js line 511):
+ * - withSpawnDedupGuard — the `spawningTasks` dedup guard that
+ * `spawnAgentForTask` wraps `runAgentSpawn` in. Acquires the guard
+ * synchronously before the first await, holds it across the ENTIRE spawn
+ * body (including the runner-enqueue handoff), and releases it in a
+ * finally. That is what closes the late-delete race where a concurrent
+ * `task:ready` re-emit spawned a SECOND agent for the same task id.
+ * - withMapEntryCleanup — the `runnerAgents` cleanup that
+ * `handleAgentCompletion` wraps its body in, so a throw from any
+ * completion step (completeAgent / updateTask / processAgentCompletion /
+ * finalizeAgent) can't strand the in-memory agent record.
*
- * await updateTask(task.id, { status: 'in_progress', ... });
- * spawningTasks.delete(task.id); // ← released too early
- * ...
- * return spawnViaRunner(...); // ← actual runner enqueue
- *
- * 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 set of post-fix tests that simulate uncaught
- * throws from buildAgentPrompt / writeFile / createAgentRun /
- * registerAgent and assert the widened try/catch/finally releases the
- * guard regardless. The earlier partial-coverage gap (throws between
- * `spawningTasks.add` and the narrow spawn-only try/finally leaking the
- * guard forever) is closed by the outer try wrapping the whole spawn
- * path.
- *
- * 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).
+ * A thin set of source-level assertions at the bottom pins the remaining
+ * non-negotiable orderings that live inside the ~470-LOC orchestrators and
+ * have no behavioral seam — the handedOff pre-spawn/post-handoff split, the
+ * federation claim/register ordering (#1563), the #989 app-review marker
+ * release, the runner env merge (#2243) — plus the wiring invariant that the
+ * orchestrators actually delegate to the extracted guards.
*/
import { describe, it, expect, beforeEach } from 'vitest';
@@ -50,295 +30,252 @@ import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { spawningTasks, runnerAgents } from './agentState.js';
+import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');
-// ─── Inline replicas of the dedup slice ──────────────────────────────────────
-
-/**
- * Pre-fix spawn: delete BEFORE the runner-enqueue async work.
- * Mirrors agentLifecycle.js pre-fix flow (lines 499 → 511 → 528–536).
- */
-async function unfixedSpawn(task, hooks) {
- // line 113 — dedup check
- if (spawningTasks.has(task.id)) {
- hooks.onDuplicate?.(task.id);
- return null;
- }
-
- // line 134 — guard add (sync)
- spawningTasks.add(task.id);
-
- // simulate all the async work between line 134 and line 499 (config load,
- // provider resolve, prompt build, registerAgent, etc.)
- await hooks.preUpdateWork();
-
- // line 499 — task status flipped to in_progress
- await hooks.updateTaskStatus(task.id, 'in_progress');
-
- // line 511 — guard released BEFORE the runner enqueue (the bug)
- spawningTasks.delete(task.id);
-
- // simulate any sync between 511 and the spawn call
- hooks.postDeletePreSpawn?.();
-
- // line 528–536 — actually queue the runner; this is the work that should
- // have been inside the guard window.
- const agentId = await hooks.runnerEnqueue(task.id);
- hooks.onSpawn?.(agentId, task.id);
- return agentId;
-}
-
-/**
- * Post-fix spawn: guard wraps the runner-enqueue via try/finally.
- * Mirrors agentLifecycle.js post-fix flow.
- */
-async function fixedSpawn(task, hooks) {
- if (spawningTasks.has(task.id)) {
- hooks.onDuplicate?.(task.id);
- return null;
- }
-
- spawningTasks.add(task.id);
-
- await hooks.preUpdateWork();
- await hooks.updateTaskStatus(task.id, 'in_progress');
-
- // Hook into the same "post-update / pre-spawn" boundary as the unfixed
- // variant, but inside the guard window. This is the exact spot where the
- // pre-fix code dropped the guard.
- hooks.postDeletePreSpawn?.();
-
- try {
- const agentId = await hooks.runnerEnqueue(task.id);
- hooks.onSpawn?.(agentId, task.id);
- return agentId;
- } finally {
- spawningTasks.delete(task.id);
- }
-}
-
-// ─── Test harness ────────────────────────────────────────────────────────────
-
function deferred() {
let resolve;
const promise = new Promise((r) => { resolve = r; });
return { promise, resolve };
}
-/**
- * Build a hooks object whose `runnerEnqueue` blocks on an external gate, so a
- * second `spawnAgentForTask` call can be injected between the dedup-delete
- * (pre-fix) and the runner-enqueue completing. The gate is read at call time
- * (not captured) so callers can mutate `hooks.gate` to release the block.
- */
-function makeHooks(opts = {}) {
- const hooks = {
- gate: opts.gate ?? null,
- onDuplicate: opts.onDuplicate,
- onSpawn: opts.onSpawn,
- onRunnerEnqueueEntered: opts.onRunnerEnqueueEntered,
- postDeletePreSpawn: opts.postDeletePreSpawn,
- preUpdateWork: async () => {},
- updateTaskStatus: async () => {},
- runnerEnqueue: async (taskId) => {
- hooks.onRunnerEnqueueEntered?.(taskId);
- if (hooks.gate) await hooks.gate;
- return `agent-${taskId.slice(-6)}-${Math.random().toString(36).slice(2, 6)}`;
- },
- };
- return hooks;
-}
-
beforeEach(() => {
spawningTasks.clear();
+ runnerAgents.clear();
});
-// ─── Sanity checks (both implementations should agree) ───────────────────────
+// ─── withSpawnDedupGuard — the real spawn dedup guard ───────────────────────
-describe('spawningTasks dedup — sanity', () => {
- it('blocks a synchronous second call (unfixed)', async () => {
- const task = { id: 'task-sync-1' };
- const dupes = [];
- const spawned = [];
- const hooks = makeHooks({
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
+describe('withSpawnDedupGuard — spawn dedup guard', () => {
+ it('holds the guard for the duration of fn and releases it on success', async () => {
+ const task = { id: 'task-ok' };
+ let heldDuringFn = false;
+ const result = await withSpawnDedupGuard(spawningTasks, task.id, async () => {
+ heldDuringFn = spawningTasks.has(task.id);
+ return 'agent-1';
});
+ expect(heldDuringFn).toBe(true);
+ expect(result).toBe('agent-1');
+ expect(spawningTasks.has(task.id)).toBe(false);
+ });
- // First call: starts, adds to guard, awaits preUpdateWork.
- const first = unfixedSpawn(task, hooks);
- // Second call BEFORE first's first await yields any further than initial
- // microtask: dedup must reject.
- const second = unfixedSpawn(task, hooks);
- await Promise.all([first, second]);
+ it('releases the guard even when fn throws (no leak on setup failure)', async () => {
+ // The pre-widening bug: a throw from buildAgentPrompt / writeFile /
+ // createAgentRun / registerAgent leaked spawningTasks forever, permanently
+ // blocking every future spawn of that task id.
+ await expect(
+ withSpawnDedupGuard(spawningTasks, 'task-throw', async () => {
+ throw new Error('buildAgentPrompt failed (ENOSPC)');
+ })
+ ).rejects.toThrow('buildAgentPrompt failed');
+ expect(spawningTasks.has('task-throw')).toBe(false);
+ });
- expect(dupes).toEqual(['task-sync-1']);
- expect(spawned).toHaveLength(1);
+ it('releases the guard on an early return null (detected-error path)', async () => {
+ // Every detected-error early return inside runAgentSpawn (no provider,
+ // claim yielded, max-spawns, lane-acquire, updateTask failure) returns null;
+ // the guard must be released for each of them.
+ const result = await withSpawnDedupGuard(spawningTasks, 'task-null', async () => null);
+ expect(result).toBeNull();
+ expect(spawningTasks.has('task-null')).toBe(false);
});
- it('blocks a synchronous second call (fixed)', async () => {
- const task = { id: 'task-sync-2' };
- const dupes = [];
- const spawned = [];
- const hooks = makeHooks({
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
+ it('returns SPAWN_DEDUP_SKIP and does not touch the set when already held', async () => {
+ spawningTasks.add('task-inflight'); // an earlier spawn is mid-flight
+ let fnRan = false;
+ const result = await withSpawnDedupGuard(spawningTasks, 'task-inflight', async () => {
+ fnRan = true;
+ return 'agent-2';
});
-
- const first = fixedSpawn(task, hooks);
- const second = fixedSpawn(task, hooks);
- await Promise.all([first, second]);
-
- expect(dupes).toEqual(['task-sync-2']);
- expect(spawned).toHaveLength(1);
+ expect(result).toBe(SPAWN_DEDUP_SKIP);
+ expect(fnRan).toBe(false); // the guarded body never ran
+ expect(spawningTasks.has('task-inflight')).toBe(true); // pre-existing guard untouched
+ });
+
+ it('acquires the guard synchronously before the first await inside fn', async () => {
+ // A `task:ready` re-emit can land while the first spawn is suspended at an
+ // await (ensureInstanceId / getTaskById). The guard must be taken
+ // synchronously — before fn yields — or the racer slips past the has()
+ // check. Prove it: a second call issued with NO await between the two must
+ // already see the guard held.
+ const gate = deferred();
+ const first = withSpawnDedupGuard(spawningTasks, 'task-sync', async () => {
+ await gate.promise;
+ return 'agent-first';
+ });
+ const second = await withSpawnDedupGuard(spawningTasks, 'task-sync', async () => 'agent-second');
+ expect(second).toBe(SPAWN_DEDUP_SKIP);
+ gate.resolve();
+ expect(await first).toBe('agent-first');
});
});
-// ─── The race the user reported ──────────────────────────────────────────────
-
-describe('spawningTasks dedup — late-delete race', () => {
- it('unfixed: a second call between delete-from-guard and runner-enqueue spawns a SECOND agent (bug repro)', async () => {
- const task = { id: 'task-race-unfixed' };
- const dupes = [];
+// ─── The reported late-delete race, driven by the real guard ────────────────
+
+describe('spawnAgentForTask dedup — late-delete race (issue #2548 / #1563)', () => {
+ it('a concurrent spawn landing during the handoff window is deduped (only ONE agent)', async () => {
+ // Reproduce the reported race with the REAL guard. Call A holds the guard
+ // across its whole body — including the runner-enqueue handoff, modelled
+ // here by an awaited gate. Call B arrives DURING that handoff window: the
+ // exact boundary (after the in_progress flip, before the runner accepted
+ // the agent) where the pre-fix code had already released the guard and let
+ // a second agent spawn. Because withSpawnDedupGuard holds the guard until
+ // A's fn settles, B is deduped instead of spawning a duplicate.
+ const taskId = 'task-race';
const spawned = [];
-
- // Gate the runner-enqueue of the FIRST call so we can inject the second
- // call after the guard has been released but before the runner accepted
- // the agent.
- const runnerGate = deferred();
- let injectedSecondCall;
-
- const hooks = makeHooks({
- gate: runnerGate.promise,
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
- });
- // Pre-fix flow: the guard is released BEFORE this hook fires (production
- // line 511 happens before lines 528–536). Inject the second call here.
- // It must NOT be deduped because the bug already released the guard.
- hooks.postDeletePreSpawn = () => {
- // Second call uses its own hooks instance with NO gate so its runner
- // resolves immediately — we want to observe whether it spawned at all.
- const secondHooks = makeHooks({
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
+ const handoffGate = deferred();
+ let secondCall;
+
+ const first = withSpawnDedupGuard(spawningTasks, taskId, async () => {
+ // Inject the racer mid-handoff, while the guard is (correctly) still held.
+ secondCall = withSpawnDedupGuard(spawningTasks, taskId, async () => {
+ spawned.push('agent-second');
+ return 'agent-second';
});
- injectedSecondCall = unfixedSpawn(task, secondHooks);
- };
-
- const first = unfixedSpawn(task, hooks);
+ await handoffGate.promise; // runner-enqueue completing
+ spawned.push('agent-first');
+ return 'agent-first';
+ });
- // Drain the microtask queue so the first call reaches its
- // `postDeletePreSpawn` hook (which fires the second call).
- await new Promise((r) => setImmediate(r));
+ // Drain microtasks so A reaches the injection point + B runs its dedup path.
await new Promise((r) => setImmediate(r));
+ const secondResult = await secondCall;
- // At this point: the second call has already executed its full dedup
- // path. If the bug is present, it spawned a second agent.
- expect(injectedSecondCall).toBeDefined();
- const secondAgentId = await injectedSecondCall;
+ handoffGate.resolve();
+ const firstResult = await first;
- // Now let the first call's runner-enqueue complete.
- runnerGate.resolve();
- const firstAgentId = await first;
-
- // BUG: two distinct agents were spawned for the same task id.
- expect(dupes).toEqual([]); // dedup did NOT fire on the racer
- expect(spawned).toHaveLength(2); // ← TWO agents spawned, same task
- expect(spawned[0].id).toBe(task.id);
- expect(spawned[1].id).toBe(task.id);
- expect(firstAgentId).toBeTruthy();
- expect(secondAgentId).toBeTruthy();
- expect(firstAgentId).not.toBe(secondAgentId);
+ expect(secondResult).toBe(SPAWN_DEDUP_SKIP); // racer deduped, no second agent
+ expect(spawned).toEqual(['agent-first']); // exactly ONE agent spawned
+ expect(firstResult).toBe('agent-first');
+ expect(spawningTasks.has(taskId)).toBe(false); // released once A settled
});
- it('fixed: the same race is closed — the second call is deduped, only ONE agent spawns', async () => {
- const task = { id: 'task-race-fixed' };
- const dupes = [];
- const spawned = [];
+ it('the guard is per-attempt, not sticky — a later spawn for the same id proceeds', async () => {
+ // Sanity: after A completes and releases, a subsequent spawn for the same
+ // task id (e.g. a retry) must not be permanently blocked.
+ const taskId = 'task-seq';
+ const a = await withSpawnDedupGuard(spawningTasks, taskId, async () => 'agent-a');
+ const b = await withSpawnDedupGuard(spawningTasks, taskId, async () => 'agent-b');
+ expect(a).toBe('agent-a');
+ expect(b).toBe('agent-b');
+ expect(spawningTasks.has(taskId)).toBe(false);
+ });
+});
- const runnerGate = deferred();
- let injectedSecondCall;
+// ─── withMapEntryCleanup — the real runnerAgents completion cleanup ──────────
- const hooks = makeHooks({
- gate: runnerGate.promise,
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
+describe('withMapEntryCleanup — runnerAgents completion cleanup', () => {
+ it('runs the completion steps then deletes the map entry (happy path)', async () => {
+ runnerAgents.set('agent-A', { taskId: 'task-A' });
+ const steps = [];
+ await withMapEntryCleanup(runnerAgents, 'agent-A', async () => {
+ steps.push('completeAgent');
+ steps.push('updateTask');
+ steps.push('processAgentCompletion');
});
- // Same boundary as the unfixed test — but now the guard is held until
- // the runner-enqueue resolves (try/finally), so the injected second
- // call must hit the dedup-has-check.
- hooks.postDeletePreSpawn = () => {
- const secondHooks = makeHooks({
- onDuplicate: (id) => dupes.push(id),
- onSpawn: (agentId, id) => spawned.push({ agentId, id }),
- });
- injectedSecondCall = fixedSpawn(task, secondHooks);
- };
-
- const first = fixedSpawn(task, hooks);
-
- await new Promise((r) => setImmediate(r));
- await new Promise((r) => setImmediate(r));
-
- expect(injectedSecondCall).toBeDefined();
- const secondResult = await injectedSecondCall;
-
- runnerGate.resolve();
- const firstAgentId = await first;
-
- // FIX: the racer was deduped, only the first call produced an agent.
- expect(dupes).toEqual([task.id]);
- expect(secondResult).toBeNull();
- expect(spawned).toHaveLength(1);
- expect(spawned[0].id).toBe(task.id);
- expect(firstAgentId).toBeTruthy();
+ expect(steps).toEqual(['completeAgent', 'updateTask', 'processAgentCompletion']);
+ expect(runnerAgents.has('agent-A')).toBe(false);
});
- it('fixed: a runner-enqueue rejection still releases the guard (finally)', async () => {
- const task = { id: 'task-race-throw' };
- const hooks = {
- preUpdateWork: async () => {},
- updateTaskStatus: async () => {},
- runnerEnqueue: async () => { throw new Error('runner crashed'); },
- };
+ it('deletes the map entry even when an inner completion step throws', async () => {
+ // A throw from completeAgent / updateTask / processAgentCompletion /
+ // finalizeAgent must never leak the in-memory record — memory grows
+ // unboundedly and a stale entry can re-trigger/misroute completion.
+ runnerAgents.set('agent-B', { taskId: 'task-B' });
+ await expect(
+ withMapEntryCleanup(runnerAgents, 'agent-B', async () => {
+ throw new Error('completeAgent failed: state save error');
+ })
+ ).rejects.toThrow('completeAgent failed');
+ expect(runnerAgents.has('agent-B')).toBe(false);
+ });
- await expect(fixedSpawn(task, hooks)).rejects.toThrow('runner crashed');
+ it('propagates the inner error after cleanup (finally does not swallow it)', async () => {
+ runnerAgents.set('agent-C', { taskId: 'task-C' });
+ let caught;
+ try {
+ await withMapEntryCleanup(runnerAgents, 'agent-C', async () => {
+ throw new Error('updateTask failed');
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught?.message).toBe('updateTask failed');
+ expect(runnerAgents.has('agent-C')).toBe(false);
+ });
- // Critical: the guard must NOT leak across a thrown spawn, otherwise a
- // legitimate follow-up call for the same task id would be incorrectly
- // deduped forever.
- expect(spawningTasks.has(task.id)).toBe(false);
+ it('is safe when the entry was already removed (double-delete no-op)', async () => {
+ // handleAgentCompletion's early-return branches (paused / unknown agent)
+ // delete the entry before the guarded body; the finally delete must be a
+ // harmless no-op if the key is already gone.
+ const result = await withMapEntryCleanup(runnerAgents, 'agent-missing', async () => 'ok');
+ expect(result).toBe('ok');
+ expect(runnerAgents.has('agent-missing')).toBe(false);
});
});
-// ─── Regression guard against the buggy ordering ────────────────────────────
-//
-// Source-level assertion: the production `spawnAgentForTask` MUST release the
-// dedup guard inside a `finally` after the spawn call, NOT immediately after
-// the `updateTask` that flips the task to in_progress. The pre-fix code
-// released the guard between `updateTask` and `spawnViaRunner`/`spawnDirectly`
-// — a window in which a concurrent `task:ready` re-emit could race past the
-// dedup-has-check and spawn a duplicate agent.
+// ─── Wiring invariants: the orchestrators delegate to the guards ────────────
//
-// If a future refactor reverts the delete to its pre-fix position, this test
-// flips red and points the dev at the race the structural change re-opened.
-
-describe('agentLifecycle source — spawningTasks delete placement', () => {
- it('releases the dedup guard inside a finally block', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- expect(fnStart, 'spawnAgentForTask must exist').toBeGreaterThan(-1);
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
+// The behavioral tests above cover the guards themselves; these two source
+// checks pin that spawnAgentForTask / handleAgentCompletion actually route
+// their guard/cleanup through the extracted helpers, so a refactor that
+// re-inlines a hand-rolled try/finally (and re-opens the race) fails loudly.
+
+describe('agentLifecycle — guard wiring', () => {
+ it('spawnAgentForTask delegates the dedup guard to withSpawnDedupGuard(runAgentSpawn)', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
+ expect(idx, 'spawnAgentForTask must exist').toBeGreaterThan(-1);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1200);
+ expect(body).toMatch(
+ /withSpawnDedupGuard\(\s*spawningTasks\s*,\s*task\.id\s*,\s*\(\)\s*=>\s*runAgentSpawn\(task\)\s*\)/
+ );
+ // The dedup-skip sentinel is honored (returns null to the caller).
+ expect(body).toMatch(/SPAWN_DEDUP_SKIP/);
+ });
- expect(fnBody).toMatch(/spawningTasks\.add\(task\.id\)/);
+ it('handleAgentCompletion delegates runnerAgents cleanup to withMapEntryCleanup', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
+ expect(idx, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 60_000);
+ expect(body).toMatch(/withMapEntryCleanup\(\s*runnerAgents\s*,\s*agentId\s*,/);
+ });
+});
- // The dedup-delete must live inside a `finally { ... }` clause — the
- // structural guarantee that the guard outlives the spawn call regardless
- // of which runner/direct branch is taken or what intervening logic exists.
- const finallyPattern = /finally\s*\{[\s\S]{0,400}?spawningTasks\.delete\(task\.id\)/;
- expect(fnBody).toMatch(finallyPattern);
+// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────
+//
+// These pin control-flow orderings that live inside the ~470-LOC guarded spawn
+// body and can't be reached without mocking its 40+ imports. Anchored on
+// `runAgentSpawn` (the guarded body extracted from spawnAgentForTask, #2548).
+
+const RUN_SPAWN_START = AGENT_LIFECYCLE_SRC.indexOf('async function runAgentSpawn');
+const RUN_SPAWN_BODY = AGENT_LIFECYCLE_SRC.slice(RUN_SPAWN_START, RUN_SPAWN_START + 60_000);
+
+describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', () => {
+ it('uses a mutable handedOff flag to distinguish the two failure modes', () => {
+ // The flag is declared with `let` so the catch arm can read which side of
+ // the spawn handoff a throw came from.
+ expect(RUN_SPAWN_BODY).toMatch(/let\s+handedOff\s*=\s*false\s*;/);
+ // The catch arm rethrows for post-handoff failures (a live agent may exist).
+ expect(RUN_SPAWN_BODY).toMatch(/if\s*\(\s*handedOff\s*\)\s*\{[\s\S]{0,800}?throw\s+err\s*;/);
+ // The pre-spawn branch runs cleanupOnError + re-emits job:spawn-failed for
+ // autonomous-job tasks so cos.js can clear its job-level guard.
+ expect(RUN_SPAWN_BODY).toMatch(/cleanupOnError\(err\.message\)/);
+ expect(RUN_SPAWN_BODY).toMatch(/job:spawn-failed/);
+ expect(RUN_SPAWN_BODY).toMatch(/task\.metadata\??\.jobId/);
+ });
+
+ it('sets handedOff = true BEFORE the first spawn helper invocation', () => {
+ // Setting it after would misclassify a synchronous throw from building the
+ // helper's argument object as a pre-spawn failure even though the helper
+ // may have begun work.
+ const flipIdx = RUN_SPAWN_BODY.indexOf('handedOff = true');
+ expect(flipIdx, '`handedOff = true` must exist inside runAgentSpawn').toBeGreaterThan(-1);
+ for (const helper of ['spawnTuiAgent(', 'spawnViaRunner(', 'spawnDirectly(']) {
+ const idx = RUN_SPAWN_BODY.indexOf(helper);
+ expect(idx, `${helper} must appear AFTER \`handedOff = true\``).toBeGreaterThan(flipIdx);
+ }
});
});
@@ -346,48 +283,42 @@ describe('agentLifecycle source — spawningTasks delete placement', () => {
// `bindAppReviewAgent` before this spawn MUST be released on every
// pre-completion `return null` path, or the app reads "in review" until the next
// daemon restart. The shared `cleanupOnError` closure owns the release for the
-// four detected-error paths (provider resolution, prep deferred/blocked,
-// updateTask failure) + the pre-spawn catch arm; the two earliest returns
-// (max-spawns block, lane-acquire failure) release inline because they fire
-// before `cleanupOnError` is defined.
-
-describe('agentLifecycle source — app-review marker release (issue #989)', () => {
+// detected-error paths + the pre-spawn catch arm; the two earliest returns
+// (max-spawns block, lane-acquire failure) release inline before cleanupOnError
+// is defined.
+describe('runAgentSpawn source — app-review marker release (issue #989)', () => {
it('cleanupOnError releases the synthetic app-review marker', () => {
const start = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =');
expect(start, 'cleanupOnError must exist').toBeGreaterThan(-1);
- const body = AGENT_LIFECYCLE_SRC.slice(start, start + 800);
- expect(body, 'cleanupOnError must release the app-review marker').toMatch(/releaseAppReviewMarker\(task\.metadata\?\.app\)/);
+ const body = AGENT_LIFECYCLE_SRC.slice(start, start + 900);
+ expect(body, 'cleanupOnError must release the app-review marker').toMatch(
+ /releaseAppReviewMarker\(task\.metadata\?\.app\)/
+ );
});
it('every cleanupOnError call is awaited so the release persists before return null', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- // No bare `cleanupOnError(` call may exist — only `await cleanupOnError(`
- // (and the `const cleanupOnError =` definition). A bare call would fire the
- // async marker release without awaiting it, racing the `return null`.
- const bareCalls = fnBody.match(/(?<!await )(?<!const )cleanupOnError\(/g) || [];
+ // A bare `cleanupOnError(` call would fire the async marker release without
+ // awaiting it, racing the `return null`.
+ const bareCalls = RUN_SPAWN_BODY.match(/(?<!await )(?<!const )cleanupOnError\(/g) || [];
expect(bareCalls, 'all cleanupOnError calls must be awaited').toEqual([]);
});
it('the max-spawns and lane-acquire early returns release the marker inline', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- // Slice from the function start up to where cleanupOnError is defined —
- // the two earliest `return null` paths live in this prefix.
- const defIdx = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =', fnStart);
- const prefix = AGENT_LIFECYCLE_SRC.slice(fnStart, defIdx);
+ const defIdx = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =', RUN_SPAWN_START);
+ const prefix = AGENT_LIFECYCLE_SRC.slice(RUN_SPAWN_START, defIdx);
const inlineReleases = prefix.match(/await releaseAppReviewMarker\(task\.metadata\?\.app\)/g) || [];
expect(inlineReleases.length, 'max-spawns + lane-acquire returns must each release inline').toBe(2);
});
});
-// ─── spawnAgentForTask — permanent provider-config failure blocks the task ───
+// ─── runAgentSpawn — permanent provider-config failure blocks the task ───────
//
// A resolution failure marked `permanent` (an api-only provider pinned to an
// agent task, which has no file-writing harness) fails identically on every
// re-dispatch. Without a block, the task stays pending and silently re-fails
-// forever — the layered-intelligence "sits pending, never picked up" bug. Pin
-// that the permanent branch flips the task to blocked so it stops re-dispatching.
-describe('agentLifecycle source — permanent provider-config failure blocks the task', () => {
+// forever. Pin that the permanent branch flips the task to blocked BEFORE the
+// lease is released, so a federated peer can't be clobbered.
+describe('runAgentSpawn source — permanent provider-config failure blocks the task', () => {
it('the resolution-failure path blocks a permanent failure with a provider-config reason', () => {
const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
expect(idx, 'resolution call must exist').toBeGreaterThan(-1);
@@ -398,11 +329,6 @@ describe('agentLifecycle source — permanent provider-config failure blocks the
});
it('blocks BEFORE releasing the lease so a federated peer cannot be clobbered', () => {
- // The block write must run while the instance still holds the federation
- // lease and land BEFORE cleanupOnError releases it — otherwise a peer could
- // claim + start the task in the gap and have its live in_progress clobbered
- // to blocked. Pin the ordering: `if (resolution.permanent)` precedes the
- // `await cleanupOnError` inside the resolution-failure branch.
const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);
const permanentIdx = body.indexOf('if (resolution.permanent)');
@@ -413,375 +339,61 @@ describe('agentLifecycle source — permanent provider-config failure blocks the
});
});
-// ─── 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);
- });
-
- // ─── Widened try/catch/finally coverage ─────────────────────────────────
- //
- // Pre-fix, `spawnAgentForTask`'s try/finally only wrapped the final
- // `spawnViaRunner` / `spawnDirectly` calls. The ~400 LOC above
- // (buildAgentPrompt, writeFile, createAgentRun, registerAgent, etc.) was
- // not inside any try/catch — an uncaught throw on any of those paths
- // leaked `spawningTasks` forever, permanently blocking future spawns of
- // that task id.
- //
- // The fix widens the try to wrap from just after `spawningTasks.add` all
- // the way through the spawn call, with a `catch` arm that invokes
- // `cleanupOnError` and a `finally` that releases the guard
- // unconditionally. These tests replicate the post-fix flow with an
- // injected throw at each of the four documented async steps and assert
- // the guard is released. They match the inline-replica convention used
- // throughout this file (see the file header).
-
- async function simulateFixedSpawnPath({ taskId, agentId, throwAt, jobId = null, throwsAfterHandoff = false }) {
- spawningTasks.add(taskId);
- const harness = makeCleanupHarness(taskId, agentId);
- const jobSpawnFailedEmissions = [];
- let handedOff = false;
- try {
- // The injected step models the production flow: when
- // `throwsAfterHandoff` is set, we flip `handedOff` before throwing
- // to simulate a spawn-helper rejection (the helper may have already
- // created a live agent). Otherwise we throw before handoff to model
- // a pre-spawn setup failure (buildAgentPrompt / writeFile / etc.).
- if (throwsAfterHandoff) handedOff = true;
- await throwAt();
- handedOff = true; // matches the production `handedOff = true` flip just before the spawn helper call
- return { result: 'spawned', harness, jobSpawnFailedEmissions };
- } catch (err) {
- if (handedOff) {
- // Spawn-helper rejection — re-throw to mirror production. Finally
- // still releases the dedup guard; the spawn helper's own
- // on('error') handler is responsible for lane/execution cleanup.
- throw err;
- }
- harness.cleanupOnError(err.message);
- // Mirror the production catch arm: when the task was queued by an
- // autonomous job, re-emit `job:spawn-failed` so cos.js clears its
- // job-level spawn guard.
- if (jobId) jobSpawnFailedEmissions.push({ jobId });
- return { result: null, harness, jobSpawnFailedEmissions };
- } finally {
- spawningTasks.delete(taskId);
- }
- }
-
- function expectGuardReleased({ result, harness }, message) {
- expect(result).toBeNull();
- expect(harness.released).toHaveLength(1);
- expect(harness.errored[0].message).toBe(message);
- expect(harness.completed[0].success).toBe(false);
- }
-
- it('releases the dedup guard when buildAgentPrompt throws', async () => {
- // Production reference: `buildAgentPrompt(task, ...)` call.
- const msg = 'prompt build failed (ENOSPC)';
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-prompt-throw',
- agentId: 'agent-prompt',
- throwAt: async () => { throw new Error(msg); },
- });
- expect(spawningTasks.has('task-prompt-throw')).toBe(false);
- expectGuardReleased(outcome, msg);
- });
-
- it('releases the dedup guard when writeFile(prompt) throws', async () => {
- // Production reference: `writeFile(join(agentDir, 'prompt.txt'), prompt)`.
- const msg = 'writeFile failed (EACCES)';
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-writefile-throw',
- agentId: 'agent-writefile',
- throwAt: async () => { throw new Error(msg); },
- });
- expect(spawningTasks.has('task-writefile-throw')).toBe(false);
- expectGuardReleased(outcome, msg);
- });
-
- it('releases the dedup guard when createAgentRun throws', async () => {
- // Production reference: `createAgentRun(agentId, task, ...)`.
- const msg = 'createAgentRun failed (DB write)';
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-runs-throw',
- agentId: 'agent-runs',
- throwAt: async () => { throw new Error(msg); },
- });
- expect(spawningTasks.has('task-runs-throw')).toBe(false);
- expectGuardReleased(outcome, msg);
- });
-
- it('releases the dedup guard when registerAgent throws', async () => {
- // Production reference: `registerAgent(agentId, task.id, {...})`.
- const msg = 'registerAgent failed (state mutex lost)';
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-register-throw',
- agentId: 'agent-register',
- throwAt: async () => { throw new Error(msg); },
- });
- expect(spawningTasks.has('task-register-throw')).toBe(false);
- expectGuardReleased(outcome, msg);
- });
-
- it('emits job:spawn-failed when an autonomous-job task throws mid-setup', async () => {
- // Pre-widening, the throw propagated to subAgentSpawner's `task:ready`
- // catch (subAgentSpawner.js:158-168) which emitted `job:spawn-failed`
- // so cos.js could clear `spawningJobIds` and re-register the cron
- // schedule. The widened catch consumes the throw locally — without
- // re-emitting that event here, the job-level guard would stick until
- // its 5-minute safety timeout.
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-job-throw',
- agentId: 'agent-job',
- jobId: 'job-cron-42',
- throwAt: async () => { throw new Error('writeFile failed (EACCES)'); },
- });
- expect(outcome.result).toBeNull();
- expect(outcome.jobSpawnFailedEmissions).toEqual([{ jobId: 'job-cron-42' }]);
- });
-
- it('does not emit job:spawn-failed for non-autonomous-job tasks', async () => {
- const outcome = await simulateFixedSpawnPath({
- taskId: 'task-user-throw',
- agentId: 'agent-user',
- throwAt: async () => { throw new Error('prompt build failed'); },
- });
- expect(outcome.result).toBeNull();
- expect(outcome.jobSpawnFailedEmissions).toEqual([]);
- });
-
- it('re-throws when a spawn helper rejects after handoff (live agent may exist)', async () => {
- // Pre-fix: a spawn helper's rejection propagated to subAgentSpawner's
- // task:ready catch, which logged + (if jobId) emitted job:spawn-failed.
- // The widened structure preserves this — once `handedOff` flips true,
- // the catch arm re-throws so the helper's own on('error') handler owns
- // lane/execution cleanup. The dedup guard is still released in finally.
- await expect(simulateFixedSpawnPath({
- taskId: 'task-handoff-throw',
- agentId: 'agent-handoff',
- jobId: 'job-cron-99',
- throwsAfterHandoff: true,
- throwAt: async () => { throw new Error('runner rejected spawn'); },
- })).rejects.toThrow('runner rejected spawn');
- // Critically, after the re-throw, the dedup guard must still be cleared.
- expect(spawningTasks.has('task-handoff-throw')).toBe(false);
- });
-
- // Source-level assertions: the catch arm distinguishes the two failure
- // modes via the `handedOff` flag, calls cleanupOnError + emits
- // job:spawn-failed on the pre-spawn branch, and rethrows on the
- // post-handoff branch. Any future refactor that drops either branch
- // breaks loudly here.
- it('source: spawnAgentForTask uses handedOff flag to distinguish pre-spawn vs post-handoff failures', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- // The flag is declared with `let` so we can mutate it inside the try.
- expect(fnBody).toMatch(/let\s+handedOff\s*=\s*false\s*;/);
- // The catch arm gates on the flag and rethrows for handoff failures.
- expect(fnBody).toMatch(/if\s*\(\s*handedOff\s*\)\s*\{[\s\S]{0,800}?throw\s+err\s*;/);
- // Pre-spawn branch (the else case) still calls cleanupOnError and
- // re-emits job:spawn-failed for autonomous jobs.
- expect(fnBody).toMatch(/cleanupOnError\(err\.message\)/);
- expect(fnBody).toMatch(/job:spawn-failed/);
- expect(fnBody).toMatch(/task\.metadata\??\.jobId/);
- });
-
- // Source-level assertion: `handedOff = true` must be set BEFORE the
- // first spawn helper invocation (spawnTuiAgent / spawnViaRunner /
- // spawnDirectly). Setting it after would mean a synchronous throw from
- // building the helper's argument object falls into the pre-spawn cleanup
- // branch, which is wrong if the helper has already begun work.
- it('source: handedOff = true precedes the first spawn helper invocation', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const flipIdx = fnBody.indexOf('handedOff = true');
- expect(flipIdx, '`handedOff = true` must exist inside spawnAgentForTask').toBeGreaterThan(-1);
- for (const helper of ['spawnTuiAgent(', 'spawnViaRunner(', 'spawnDirectly(']) {
- const idx = fnBody.indexOf(helper);
- expect(idx, `${helper} must appear AFTER \`handedOff = true\``).toBeGreaterThan(flipIdx);
- }
- });
-});
-
-// ─── Instance provenance stamping (issue #1563, acceptance criterion 1) ──────
+// ─── Instance provenance stamping + claim ordering (issue #1563) ─────────────
//
-// Every spawned agent must record the producing machine's federation identity
-// so that, once CoS agent history federates across peers (the rest of #1563),
-// a node pair can attribute each agent + its worktree branch to the instance
-// that produced it — the prerequisite for never duplicating agent work. The
-// stamp rides in the `registerAgent` metadata and propagates into the
-// completed-agent archive's `metadata.json` automatically, since `completeAgent`
-// serializes `.metadata`. These source-level assertions break loudly if a
-// future refactor drops the stamp.
-describe('agentLifecycle — instance provenance stamping (#1563)', () => {
- it('source: imports the identity resolver from the instances service', () => {
+// Every spawned agent records the producing machine's federation identity, and
+// the cross-instance claim must be acquired (and re-checked against the fresh
+// record) BEFORE the agent is registered — otherwise two peers spawn for the
+// same task. These orderings live inside runAgentSpawn with no behavioral seam.
+describe('runAgentSpawn source — instance provenance + claim ordering (#1563)', () => {
+ it('imports the identity resolver from the instances service', () => {
expect(AGENT_LIFECYCLE_SRC).toMatch(
/import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instances\.js';/
);
});
- it('source: resolves instanceId via ensureInstanceId() before registering the agent', () => {
- // Resolution is delegated to the shared `ensureInstanceId()` helper in
- // instances.js (which handles the boot-time `unknown` sentinel cold path)
- // and is reused by the #1563 claim guard at the top of the spawn. The
- // contract is unchanged: the id is resolved before registerAgent stamps it.
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const resolveIdx = fnBody.indexOf('await ensureInstanceId()');
- const registerIdx = fnBody.indexOf('registerAgent(agentId, task.id, {');
- expect(resolveIdx, '`await ensureInstanceId()` must exist inside spawnAgentForTask').toBeGreaterThan(-1);
- expect(registerIdx, '`registerAgent(...)` must exist inside spawnAgentForTask').toBeGreaterThan(-1);
+ it('resolves instanceId via ensureInstanceId() before registering the agent', () => {
+ const resolveIdx = RUN_SPAWN_BODY.indexOf('await ensureInstanceId()');
+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');
+ expect(resolveIdx, '`await ensureInstanceId()` must exist inside runAgentSpawn').toBeGreaterThan(-1);
+ expect(registerIdx, '`registerAgent(...)` must exist inside runAgentSpawn').toBeGreaterThan(-1);
expect(resolveIdx, 'instanceId must be resolved BEFORE registerAgent is called').toBeLessThan(registerIdx);
});
- it('source: refuses to spawn a task under another instance\'s live lease (claim guard)', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const guardIdx = fnBody.indexOf('isClaimableBy(task.metadata, instanceId)');
- const registerIdx = fnBody.indexOf('registerAgent(agentId, task.id, {');
+ it("refuses to spawn a task under another instance's live lease (claim guard)", () => {
+ const guardIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');
+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');
expect(guardIdx, 'must gate the spawn on isClaimableBy').toBeGreaterThan(-1);
expect(guardIdx, 'the claim guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
});
- it('source: stamps the federation claim into the in_progress task update', () => {
+ it('stamps the federation claim into the in_progress task update', () => {
expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);
});
- it('source: acquires the claim (updateTask with buildClaim) BEFORE registering the agent', () => {
- // Codex review fix: the lease must be taken up front, not only at the
- // in_progress flip after worktree/agent setup, so a peer's claim that
- // synced in is honored before this instance commits to spawning.
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const acquireIdx = fnBody.indexOf('metadata: buildClaim(instanceId)');
- const registerIdx = fnBody.indexOf('registerAgent(agentId, task.id, {');
+ it('acquires the claim (updateTask with buildClaim) BEFORE registering the agent', () => {
+ const acquireIdx = RUN_SPAWN_BODY.indexOf('metadata: buildClaim(instanceId)');
+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');
expect(acquireIdx, 'must acquire the claim via updateTask(buildClaim) up front').toBeGreaterThan(-1);
expect(acquireIdx, 'claim must be acquired BEFORE registerAgent').toBeLessThan(registerIdx);
});
- it('source: re-reads the freshest task and yields if claimed during dispatch', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const rereadIdx = fnBody.indexOf('await getTaskById(task.id)');
- const recheckIdx = fnBody.indexOf('!isClaimableBy(freshTask.metadata, instanceId)');
+ it('re-reads the freshest task and yields if claimed during dispatch', () => {
+ const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
+ const recheckIdx = RUN_SPAWN_BODY.indexOf('!isClaimableBy(freshTask.metadata, instanceId)');
expect(rereadIdx, 'must re-read the freshest persisted task before claiming').toBeGreaterThan(-1);
expect(recheckIdx, 'must re-check claimability against the fresh metadata').toBeGreaterThan(rereadIdx);
});
- it('source: acquires the spawningTasks dedup guard before the first await', () => {
- // The guard must be taken synchronously (before `await ensureInstanceId()`
- // or `await getTaskById()`), or a concurrent task:ready re-emit could slip
- // past the has() check while this call is suspended and spawn a duplicate.
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const addIdx = fnBody.indexOf('spawningTasks.add(task.id)');
- // The first awaited CALL in the function (anchor on the real statement, not
- // the word "await" in a comment) is the identity resolution.
- const firstAwaitIdx = fnBody.indexOf('await ensureInstanceId()');
- expect(addIdx, 'spawningTasks.add must exist').toBeGreaterThan(-1);
- expect(firstAwaitIdx, 'await ensureInstanceId() must exist').toBeGreaterThan(-1);
- expect(addIdx, 'the dedup guard must be acquired BEFORE the first await').toBeLessThan(firstAwaitIdx);
- });
-
- it('source: releases the spawn guard if identity resolution rejects', () => {
- // ensureInstanceId() runs after spawningTasks.add but before the main
- // try/finally, so a rejection must not strand the task in spawningTasks.
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- const tryIdx = fnBody.indexOf('instanceId = await ensureInstanceId();');
- const catchSlice = fnBody.slice(tryIdx, tryIdx + 260);
- expect(tryIdx, 'ensureInstanceId must be awaited').toBeGreaterThan(-1);
- expect(catchSlice, 'a catch around ensureInstanceId must release the guard').toMatch(/catch[\s\S]*spawningTasks\.delete\(task\.id\)/);
- });
-
- it('source: releases the claim on a failed-setup early exit (cleanupOnError)', () => {
+ it('releases the claim on a failed-setup early exit (cleanupOnError)', () => {
const fnStart = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError = async');
const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 1200);
expect(fnBody.indexOf('claimAcquired'), 'cleanupOnError must gate on claimAcquired').toBeGreaterThan(-1);
expect(fnBody.indexOf('buildRelease()'), 'cleanupOnError must release the claim via buildRelease').toBeGreaterThan(-1);
});
- it('source: stamps instanceId into the registerAgent metadata', () => {
+ it('stamps instanceId into the registerAgent metadata', () => {
const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');
- // The metadata object literal opens at registerIdx; assert `instanceId,`
- // appears within it (before the workspacePath field that follows).
const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, registerIdx + 400);
expect(metaSlice).toMatch(/\binstanceId,/);
expect(metaSlice.indexOf('instanceId,')).toBeLessThan(metaSlice.indexOf('workspacePath'));
@@ -796,251 +408,22 @@ describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () =>
});
it('source: spawnViaRunner merges buildOpencodeEnvVars into the runner envVars so --model ollama/<id> is accepted', () => {
- // The direct-spawn path and the "Run Prompt" path already inject the dynamic
- // OPENCODE_CONFIG_CONTENT (models map); the runner path omitted it, so an
- // OpenCode Ollama CoS task on the runner rejected the model even after the
- // spawn succeeded. Assert the merge exists inside spawnViaRunner and that the
- // env passed to the runner unions it.
const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');
expect(fnStart, 'spawnViaRunner must exist').toBeGreaterThan(-1);
const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 4000);
const buildIdx = fnBody.indexOf('buildOpencodeEnvVars(provider, model)');
expect(buildIdx, 'must build the opencode env from provider+model').toBeGreaterThan(-1);
- // The spread must reach the envVars handed to spawnAgentViaRunner.
expect(fnBody).toMatch(/envVars:\s*\{[^}]*\.\.\.opencodeEnv[^}]*\}/);
expect(fnBody.indexOf('...opencodeEnv'), 'opencodeEnv must be spread AFTER provider.envVars so it overrides the static config')
.toBeGreaterThan(fnBody.indexOf('...provider.envVars'));
});
- it('source: spawnViaRunner pins GH_TOKEN via resolveForgeTokenEnv so the runner-spawned agent\'s `gh` uses the repo-owner account', () => {
- // The direct and TUI spawn paths inject the owner-matched GH_TOKEN; the
- // runner path must too, or a codex/CLI agent under the runner opens its PR
- // as gh's mutable active-user (the multi-account "must be a collaborator"
- // failure). Assert the resolve+spread exists inside spawnViaRunner.
+ it("source: spawnViaRunner pins GH_TOKEN via resolveForgeTokenEnv so the runner-spawned agent's `gh` uses the repo-owner account", () => {
const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');
const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 4000);
expect(fnBody).toContain('resolveForgeTokenEnv(workspacePath)');
expect(fnBody).toMatch(/envVars:\s*\{[^}]*\.\.\.forgeTokenEnv[^}]*\}/);
- // forgeTokenEnv before provider.envVars so an explicit provider GH_TOKEN wins.
expect(fnBody.indexOf('...forgeTokenEnv'), 'forgeTokenEnv must be spread BEFORE provider.envVars')
.toBeLessThan(fnBody.indexOf('...provider.envVars'));
});
});
-
-// ─── 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 handleAgentCompletion with the
- * try/finally added so `deleteRunner()` ALWAYS runs even when an inner
- * step throws. This is the behavioral contract enforced by the
- * regression tests below.
- */
-async function runCompletion(harness, effectiveSuccess) {
- try {
- 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, '');
- } finally {
- 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 (try/finally guard)', () => {
- beforeEach(() => {
- runnerAgents.clear();
- });
-
- it('a throw from completeAgent still removes the runner record (finally guard)', async () => {
- // handleAgentCompletion wraps the entire completion sequence in
- // try/finally so a throw from any inner step cannot leak the
- // runnerAgents Map entry. The error still propagates to the caller —
- // the finally only guards in-memory state.
- 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');
-
- expect(runnerAgents.has('agent-C')).toBe(false);
- // Downstream steps did not run, but the finally fired deleteRunner.
- expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'deleteRunner']);
- });
-
- it('a throw from updateTask still removes the runner record', async () => {
- 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(false);
- expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'updateTask', 'deleteRunner']);
- });
-
- it('a throw from processAgentCompletion (hook dispatch) still removes the runner record', async () => {
- 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(false);
- 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')).toBeDefined();
- });
-
- it('a throw from completeAgentRun still removes the runner record', async () => {
- 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(false);
- });
-});
-
-// Source-level regression: the runner-cleanup `runnerAgents.delete(agentId)`
-// MUST live inside a `finally` clause so it survives a throw from any step
-// of the completion sequence.
-describe('agentLifecycle source — try/finally guard', () => {
- it('handleAgentCompletion wraps the body in try/finally with runnerAgents.delete inside finally', () => {
- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
- expect(fnStart, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
- expect(fnBody).toMatch(/finally\s*\{[\s\S]{0,200}?runnerAgents\.delete\(agentId\)/);
- });
-});
-
-// 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\)/);
- });
-});