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

fix: make completeAgent idempotent for already-completed agents (#3384)

[._.]/ Adam Eivyca2e056fdff3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 877d4b55cd..7d1aeb4cf2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
+- **`completeAgent` is now idempotent, so the caller-level guard is no longer the only line of defense.** Six call sites funnel every terminal agent write through `completeAgent`, and each carried the same latent "I might be second" assumption. A duplicate call re-recorded `result` (success verdict, exit code, error analysis) and re-ran the completed-agent directory move; the guards that caught the TUI double-finalize above read the record *outside* the state lock, so they narrowed the race rather than closing it. `completeAgent` now returns an already-`completed` record unmutated from inside the lock it already holds — and skips the budget-ledger charge and the second `agent:completed` emit that would otherwise re-run the scheduler hand-off. `paused` records are still completable, so a resumed agent can't wedge.
## Changed
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index de023b95c5..49c97331fc 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -78,6 +78,10 @@ export async function updateAgent(agentId, updates) {
}
export async function completeAgent(agentId, result = {}) {
+ // Set inside the lock when the record is already terminal, so the post-lock
+ // tail below (budget ledger + `agent:completed`) is skipped too — see #3384.
+ let alreadyCompleted = false;
+
const completed = await withStateLock(async () => {
const state = await loadState();
@@ -85,6 +89,19 @@ export async function completeAgent(agentId, result = {}) {
return null;
}
+ // Idempotence (#3384): six call sites funnel here and each carries the
+ // "I might be second" assumption. A duplicate completion used to overwrite
+ // the recorded verdict — a stray runner `agent:completed` once replaced a
+ // real success with `success: false, exitCode: 143`, flipping the card to
+ // Failed and requeueing a finished task. Caller-level guards read the record
+ // outside this lock, so they narrow the window rather than closing it.
+ // Guard on `completed` specifically, NOT `!== 'running'`: `paused` records
+ // are legitimately completed on resume.
+ if (state.agents[agentId].status === 'completed') {
+ alreadyCompleted = true;
+ return state.agents[agentId];
+ }
+
state.agents[agentId] = {
...state.agents[agentId],
status: 'completed',
@@ -146,6 +163,14 @@ export async function completeAgent(agentId, result = {}) {
return state.agents[agentId];
});
+ // A duplicate completion is a total no-op: re-recording the domain-usage
+ // action would double-charge the daily budget, and re-emitting
+ // `agent:completed` would re-run the scheduler hand-off for an agent that
+ // already finished (#3384). The existing record still comes back to the caller.
+ if (alreadyCompleted) {
+ return completed;
+ }
+
// Daily CoS budget accounting (#711): count only AUTONOMOUS runs (non-user
// tasks) — the same set the CoS auto-run gate withholds when over budget —
// toward the domain's actions/minutes ledger. Recorded outside the state lock
diff --git a/server/services/cosAgents.test.js b/server/services/cosAgents.test.js
index 9426b1df86..16a99143fa 100644
--- a/server/services/cosAgents.test.js
+++ b/server/services/cosAgents.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdir, rm, writeFile, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
import { join } from 'path';
const mockCosState = vi.hoisted(() => ({
@@ -23,7 +24,7 @@ vi.mock('./domainUsage.js', () => ({
recordDomainUsage: vi.fn(async () => {})
}));
-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent } from './cosAgents.js';
+import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent } from './cosAgents.js';
import { saveState } from './cosState.js';
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
@@ -150,6 +151,151 @@ describe('completeAgent budget-ledger ordering (#1683)', () => {
});
});
+describe('completeAgent idempotence (#3384)', () => {
+ const emittedCompletions = [];
+
+ beforeEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ mockCosState.state = { agents: {}, stats: { tasksCompleted: 0, errors: 0 } };
+ emittedCompletions.length = 0;
+ recordDomainUsage.mockClear();
+ recordDomainUsage.mockImplementation(async () => {});
+ cosEvents.on('agent:completed', (agent) => emittedCompletions.push(agent));
+ });
+
+ afterEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ cosEvents.removeAllListeners('agent:completed');
+ });
+
+ it('keeps the first verdict when a duplicate completion arrives', async () => {
+ // Regression: a stray runner `agent:completed` for an agent that had already
+ // finalized on its own sentinel replaced a recorded success with
+ // `success: false, exitCode: 143`, flipping the card to Failed and requeueing
+ // a finished task.
+ const agentId = 'agent-duplicate-completion';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+
+ const first = await completeAgent(agentId, { success: true, exitCode: 0, duration: 1000 });
+ expect(first.result.success).toBe(true);
+
+ saveState.mockClear();
+ recordDomainUsage.mockClear();
+ emittedCompletions.length = 0;
+
+ const second = await completeAgent(agentId, {
+ success: false,
+ exitCode: 143,
+ errorAnalysis: { category: 'startup-failure' }
+ });
+
+ expect(second.result).toEqual(first.result);
+ expect(second.result.success).toBe(true);
+ expect(second.result.errorAnalysis).toBeUndefined();
+ expect(second.completedAt).toBe(first.completedAt);
+ expect(mockCosState.state.agents[agentId].result.success).toBe(true);
+
+ // A no-op all the way out: no state write, no double budget charge, and no
+ // second `agent:completed` (whose handler schedules the next task).
+ expect(saveState).not.toHaveBeenCalled();
+ expect(recordDomainUsage).not.toHaveBeenCalled();
+ expect(emittedCompletions).toEqual([]);
+ expect(mockCosState.state.stats).toEqual({ tasksCompleted: 1, errors: 0 });
+ });
+
+ it('does not re-run the completed-agent directory move on a duplicate', async () => {
+ const agentId = 'agent-duplicate-archive';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+
+ const first = await completeAgent(agentId, { success: true, exitCode: 0 });
+ const archivedMetadata = join(
+ mockCosState.agentsDir, first.completedAt.slice(0, 10), agentId, 'metadata.json'
+ );
+ expect(existsSync(archivedMetadata)).toBe(true);
+
+ // Late output can land back in the flat dir after the archive move. A second
+ // completion must leave it alone rather than sweeping it into the bucket.
+ const flatDir = join(mockCosState.agentsDir, agentId);
+ await mkdir(flatDir, { recursive: true });
+ await writeFile(join(flatDir, 'output.txt'), 'post-archive line\n');
+
+ await completeAgent(agentId, { success: false, exitCode: 143 });
+
+ expect(existsSync(join(flatDir, 'output.txt'))).toBe(true);
+ const archived = JSON.parse(await readFile(archivedMetadata, 'utf8'));
+ expect(archived.result.success).toBe(true);
+ expect(archived.result.exitCode).toBe(0);
+ });
+
+ it('completes a still-paused agent (the guard is completed-only, not running-only)', async () => {
+ const agentId = 'agent-paused-completion';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'paused',
+ pausedAt: '2026-05-25T12:00:00.000Z',
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+
+ const done = await completeAgent(agentId, { success: true, exitCode: 0 });
+
+ expect(done.status).toBe('completed');
+ expect(done.result.success).toBe(true);
+ });
+
+ it('completes a paused agent that resumed back to running', async () => {
+ const agentId = 'agent-resumed-completion';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+
+ const paused = await updateAgent(agentId, { status: 'paused', pausedAt: '2026-05-25T12:00:00.000Z' });
+ expect(paused.status).toBe('paused');
+
+ const resumed = await updateAgent(agentId, { status: 'running' });
+ expect(resumed.status).toBe('running');
+
+ const done = await completeAgent(agentId, { success: true, exitCode: 0 });
+
+ expect(done.status).toBe('completed');
+ expect(done.result.success).toBe(true);
+ expect(emittedCompletions).toHaveLength(1);
+ });
+
+ it('re-registering an id resets it to running so a retry can complete again', async () => {
+ // Spawns mint a fresh `agent-<uuid>` id, so this only matters if one ever
+ // collides — registerAgent must still hand back a completable record.
+ const agentId = 'agent-reregistered';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'running',
+ metadata: { taskType: 'scheduled' },
+ output: []
+ };
+ await completeAgent(agentId, { success: false, exitCode: 1 });
+
+ const reregistered = await registerAgent(agentId, 'task-retry', { taskType: 'scheduled' });
+ expect(reregistered.status).toBe('running');
+
+ const done = await completeAgent(agentId, { success: true, exitCode: 0 });
+ expect(done.result.success).toBe(true);
+ });
+});
+
describe('createAgentOutputBatcher', () => {
const agentId = 'agent-batch';