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

stop syncRunnerAgents adopting live TUI agents and double-finalizing them as failed

[._.]/ Adam Eivyc7bb102ce0d4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..ed259714c4
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,9 @@
+## Fixed
+
+- **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.
+
+## Changed
+
+- **"Does this process own the agent?" is now one named predicate.** Ownership is split across `activeAgents` and `runnerAgents` by spawn mode, and which map an agent lands in isn't guessable from its `executionMode` — a `runner-tui` agent is driven locally and registers in `activeAgents` even though the runner owns its process and lists it. That implicit protocol was open-coded at three sites, one of which had it wrong (above). `isAgentOwnedLocally` in `agentState.js` now owns the invariant, and `syncRunnerAgents` + `cleanupOrphanedAgents` both call it.
+- `handleAgentCompletion` bails when the persisted record is already terminal — the same check its post-restart branch has always had — so any double-completion path is a no-op rather than a clobbering re-finalize.
+- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index f443679ffe..7346d83f10 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -27,7 +27,13 @@ import { readFile, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { cosEvents, emitLog } from './cosEvents.js';
import { registerAgent, updateAgent, completeAgent } from './cosAgents.js';
-import { getConfig, updateTask, getTaskById, getAgent as getAgentRecord } from './cos.js';
+// `getAgentRecord`, NOT `getAgent`: the record without its transcript. Both
+// consumers below want only `.status` / `.metadata`, and `getAgent` hydrates a
+// completed or paused record by reading the whole output.txt, line-splitting it
+// into per-line objects, and running `repairCodexTaskSummary` (which can write
+// metadata.json back). That is megabytes and a disk write on a long TUI run —
+// paid to read one string. Same trap documented at agentWorktreeCleanup.js:562.
+import { getConfig, updateTask, getTaskById, getAgentRecord } from './cos.js';
import { spawnAgentViaRunner, getRunnerHealth } from './cosRunnerClient.js';
import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
@@ -853,8 +859,35 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// 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).
+ // error still propagates to the caller (agentGuards.js, issue #2548). The
+ // already-finalized guard below sits INSIDE it so its early return drops the
+ // entry too, rather than hand-rolling a second delete.
return withMapEntryCleanup(runnerAgents, agentId, async () => {
+ // The persisted record, read once and shared with the PR-ownership check
+ // further down. Read off the PERSISTED record, not the in-memory
+ // `runnerAgents` entry: the entry carries only `providerId` (and a
+ // post-restart survivor recovered by syncRunnerAgents carries even less), so
+ // a lean `--bare` runner agent would read as slashdo-capable — and be
+ // downgraded for not opening a PR PortOS was about to open for it.
+ // `registerAgent` writes those fields into metadata precisely so this
+ // question survives a restart, and nothing mutates them mid-run.
+ const persistedAgent = await getAgentRecord(agentId).catch(() => null);
+
+ // Already-finalized backstop, mirroring the untracked branch above. Another
+ // owner may have written the terminal record before this event arrived —
+ // most often the TUI spawner's `finish()`, which finalizes on its own
+ // sentinel and THEN kills the session, so the runner reports that kill as a
+ // late exit-143 completion. Finalizing again would overwrite the recorded
+ // success with this event's exit code and an `analyzeAgentFailure` verdict
+ // read from an output buffer this path cannot see (a TUI writes output.txt
+ // under the dated run dir, not AGENTS_DIR/<id>) — i.e. an empty buffer
+ // classified `startup-failure`. See syncRunnerAgents for how a live TUI came
+ // to be in `runnerAgents` at all.
+ if (persistedAgent && persistedAgent.status !== 'running') {
+ console.log(`✅ Agent ${agentId} already ${persistedAgent.status} — ignoring duplicate completion (exit ${exitCode})`);
+ return;
+ }
+
// 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.
@@ -913,13 +946,9 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// one. When PortOS owns it the PR is created by that cleanup, i.e. AFTER
// finalize, so verifying here would fail every correct run.
//
- // Read off the PERSISTED record, not the in-memory `runnerAgents` entry: the
- // entry carries only `providerId` (and a post-restart survivor recovered by
- // syncRunnerAgents carries even less), so a lean `--bare` runner agent would
- // read as slashdo-capable — and be downgraded for not opening a PR PortOS
- // was about to open for it. registerAgent writes both fields into metadata
- // precisely so this question survives a restart.
- const persistedAgent = await getAgentRecord(agentId).catch(() => null);
+ // `persistedAgent` is the record read once at the top of this callback — see
+ // the note there for why the metadata must come off disk rather than the
+ // in-memory entry.
const runnerAgentOwnsPR = isTruthyMeta(task?.metadata?.openPR) && canTypeSlashCommands({
providerId: persistedAgent?.metadata?.providerId ?? agent.providerId,
providerCommand: persistedAgent?.metadata?.providerCommand ?? null,
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 04584f080b..ef20c4f5c4 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -247,6 +247,34 @@ describe('agentLifecycle — guard wiring', () => {
expect(body).toMatch(/withMapEntryCleanup\(\s*runnerAgents\s*,\s*agentId\s*,/);
});
+ // A tracked agent can already be terminal by the time its completion event
+ // lands: a runner-backed TUI is finalized by spawnTuiAgent's `finish()`, which
+ // then kills the session — and the runner reports THAT as an exit-143
+ // completion. Without this guard the event ran a second finalizeAgent that
+ // overwrote a sentinel-signalled success with a `startup-failure` verdict.
+ it('handleAgentCompletion bails on a duplicate completion for an already-terminal record', () => {
+ const body = trackedCompletionPreamble();
+ // Reads the PERSISTED record — the in-memory maps say nothing about whether
+ // another owner already wrote the terminal record.
+ expect(body).toMatch(/await getAgentRecord\(agentId\)/);
+ expect(body).toMatch(/persistedAgent && persistedAgent\.status !== 'running'/);
+ });
+
+ // The record backs BOTH the terminal-status guard and the PR-ownership check,
+ // and `getAgent` (the transcript-hydrating reader) would line-split a completed
+ // run's whole output.txt — megabytes on the very path the guard exists to catch,
+ // plus a possible metadata.json rewrite via repairCodexTaskSummary.
+ it('handleAgentCompletion reads the record once, via the transcript-free reader', () => {
+ const body = trackedCompletionPreamble();
+ expect(body).toMatch(/const persistedAgent = await getAgentRecord\(agentId\)/);
+ // Imported unaliased, so `getAgent` can't be smuggled back in under this name.
+ expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{[^}]*\bgetAgentRecord\b[^}]*\} from '\.\/cos\.js'/);
+ expect(AGENT_LIFECYCLE_SRC).not.toMatch(/getAgent as getAgentRecord/);
+ // Exactly one read for the whole tracked path.
+ const reads = AGENT_LIFECYCLE_SRC.match(/await getAgentRecord\(agentId\)/g) || [];
+ expect(reads).toHaveLength(1);
+ });
+
it('finalizeAgent stamps the LI execution verdict into the completion task write (#2779)', () => {
const idx = AGENT_FINALIZATION_SRC.indexOf('export async function finalizeAgent');
expect(idx, 'finalizeAgent must exist').toBeGreaterThan(-1);
@@ -306,6 +334,20 @@ function recoveryBranchSource() {
return AGENT_LIFECYCLE_SRC.slice(start, end);
}
+/**
+ * Source of the TRACKED completion preamble in handleAgentCompletion — from
+ * entering the withMapEntryCleanup body to the first real work it does. Both
+ * anchors are real statements, so the window can't silently widen to swallow the
+ * rest of the completion body as the function grows.
+ */
+function trackedCompletionPreamble() {
+ const start = AGENT_LIFECYCLE_SRC.indexOf('withMapEntryCleanup(runnerAgents, agentId,');
+ expect(start, 'withMapEntryCleanup wrapper must exist').toBeGreaterThan(-1);
+ const end = AGENT_LIFECYCLE_SRC.indexOf("Normalize the agent's task shape", start);
+ expect(end, 'end anchor (task-shape normalization) must exist').toBeGreaterThan(start);
+ return AGENT_LIFECYCLE_SRC.slice(start, end);
+}
+
// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────
//
// These pin control-flow orderings that live inside the ~470-LOC guarded spawn
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index b5345ac0d1..8018ebb2ab 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -14,7 +14,7 @@ import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAg
import { unregisterSpawnedAgent } from './agents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner } from './agentState.js';
+import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, isAgentOwnedLocally } from './agentState.js';
// Both were extracted out of agentLifecycle.js (issue #2837) so this module no
// longer depends on the lifecycle orchestrator — which depends on THIS module
// for handleOrphanedTask. Importing them from their own leaf modules is what
@@ -594,11 +594,9 @@ export async function cleanupOrphanedAgents() {
for (const agent of agents) {
if (agent.status === 'running') {
- const inLocalDirect = activeAgents.has(agent.id);
- const inLocalRunner = runnerAgents.has(agent.id);
const inRemoteRunner = runnerActiveIds.has(agent.id);
- if (!inLocalDirect && !inLocalRunner && !inRemoteRunner) {
+ if (!isAgentOwnedLocally(agent.id) && !inRemoteRunner) {
// Before marking as orphaned, check if the process is actually still running
if (agent.pid) {
const stillAlive = await isPidAlive(agent.pid);
diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.js
index 53beee8052..1ce42c44e5 100644
--- a/server/services/agentRunnerSync.js
+++ b/server/services/agentRunnerSync.js
@@ -13,13 +13,25 @@
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { runnerAgents } from './agentState.js';
+import { isAgentOwnedLocally, runnerAgents } from './agentState.js';
import { getAgent } from './cosAgents.js';
import * as shellService from './shell.js';
/**
* Sync running agents from the runner (recovery after server restart).
* This allows us to receive completion events for agents spawned before restart.
+ *
+ * Recovery adopts only agents this process does NOT already own — see
+ * `isAgentOwnedLocally` for why that question needs both maps, and why asking
+ * `runnerAgents` alone silently hoisted live TUI runs. `cleanupOrphanedAgents`
+ * calls this every 15 minutes, so the bug reached any TUI run that outlived a
+ * single health-check tick: once hoisted, the `agent:completed` the runner emits
+ * when the TUI spawner's own `finish()` kills the session passed subAgentSpawner's
+ * `if (!agent) return` guard and ran a SECOND `finalizeAgent`, overwriting a
+ * sentinel-signalled success with `success: false, exitCode: 143` and a bogus
+ * `startup-failure` analysis — which flipped the agent card to Failed and requeued
+ * the finished task. Observed on a 55-min release-check run that had already
+ * published its release and merged all of its PRs.
*/
export async function syncRunnerAgents() {
const agents = await getActiveAgentsFromRunner().catch(err => {
@@ -52,8 +64,8 @@ export async function syncRunnerAgents() {
let syncedCount = 0;
for (const agent of agents) {
- // Only sync if not already tracked
- if (!runnerAgents.has(agent.id)) {
+ // Only sync if this process isn't already driving it
+ if (!isAgentOwnedLocally(agent.id)) {
const task = taskMap.get(agent.taskId);
const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';
diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.js
index 31d0e72d7d..f9cf35788c 100644
--- a/server/services/agentRunnerSync.test.js
+++ b/server/services/agentRunnerSync.test.js
@@ -37,13 +37,14 @@ vi.mock('./cosAgents.js', () => ({
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { getAgent } from './cosAgents.js';
-import { runnerAgents } from './agentState.js';
+import { activeAgents, runnerAgents } from './agentState.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
describe('syncRunnerAgents runner-owned TUI recovery', () => {
beforeEach(() => {
vi.clearAllMocks();
runnerAgents.clear();
+ activeAgents.clear();
vi.mocked(shellService.getSession).mockReturnValue(null);
vi.mocked(getAgent).mockResolvedValue(null);
});
@@ -113,4 +114,37 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
await expect(syncRunnerAgents()).resolves.toBe(1);
expect(runnerAgents.get('agent-2')).toMatchObject({ runId: null });
});
+
+ // A live runner-TUI is owned by this process's spawnTuiAgent closure, which
+ // registers in `activeAgents` — never in `runnerAgents`. Hoisting it here made
+ // subAgentSpawner's `agent:completed` handler run a second finalizeAgent over
+ // the TUI's own sentinel-signalled success, flipping the agent card to failed.
+ // `cleanupOrphanedAgents` calls this every 15 minutes, so every TUI run longer
+ // than one tick was exposed. The unowned agent in the same sweep pins that this
+ // skips one entry rather than abandoning the loop.
+ it('skips a TUI this process already owns while still adopting real survivors', async () => {
+ activeAgents.set('agent-live', { task: { id: 'task-1' }, startedAt: Date.now() });
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([
+ {
+ id: 'agent-live',
+ taskId: 'task-1',
+ pid: 4321,
+ startedAt: Date.now(),
+ kind: 'tui',
+ sessionId: 'tui-session-live',
+ command: 'claude',
+ workspacePath: '/tmp/example-workspace',
+ },
+ { id: 'agent-orphan', taskId: 'task-1', pid: 8765, startedAt: Date.now(), kind: 'cli' },
+ ]);
+
+ await expect(syncRunnerAgents()).resolves.toBe(1);
+
+ expect(runnerAgents.has('agent-live')).toBe(false);
+ expect(runnerAgents.has('agent-orphan')).toBe(true);
+ // The owned TUI's shell relay is already registered by its spawner;
+ // re-attaching would hand the same PTY two readers.
+ expect(connectTuiSessionViaRunner).not.toHaveBeenCalled();
+ expect(shellService.registerExternalSession).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/agentState.js b/server/services/agentState.js
index 4305e00b9c..a2a60a5718 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -30,6 +30,19 @@ export const setUseRunner = (val) => { useRunner = val; };
// `subAgentSpawner` re-exports it for backward compatibility.
export const getActiveAgentIds = () => [...activeAgents.keys(), ...runnerAgents.keys()];
+// Does THIS process already own the agent's lifecycle?
+//
+// Ownership is split across the two maps by spawn mode, and which map an agent
+// lands in is not guessable from its `executionMode`: a runner-backed TUI
+// (`runner-tui`) is driven by the live `spawnTuiAgent` closure, so it registers
+// in `activeAgents` — NEVER in `runnerAgents`, even though the runner owns its
+// process and lists it in `/agents`. Only `spawnViaRunner` populates
+// `runnerAgents`. Consult this rather than either map alone: checking
+// `runnerAgents` by itself reads a live TUI as an unowned restart survivor,
+// which is exactly how `syncRunnerAgents` came to hoist running TUI agents and
+// let a stray runner `agent:completed` event double-finalize them.
+export const isAgentOwnedLocally = (agentId) => activeAgents.has(agentId) || runnerAgents.has(agentId);
+
// Metadata booleans may arrive as true/'true' or false/'false' (JSON vs TASKS.md string round-trip)
export const isTruthyMeta = (value) => value === true || value === 'true';
export const isFalsyMeta = (value) => value === false || value === 'false';
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 3ff92af24c..51efa2aff5 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -149,6 +149,10 @@ async function runInitSpawner() {
// A runner-owned TUI is finalized by spawnTuiAgent while this server
// remains connected. Only a TUI recovered into runnerAgents after a
// server restart should use the generic runner completion path.
+ // That invariant is upheld elsewhere — `syncRunnerAgents` must not adopt an
+ // agent this process already owns (see `isAgentOwnedLocally`). When it did,
+ // this guard passed for a live TUI and double-finalized it; the sibling
+ // `agent:output` and `agent:error` handlers key off the same membership.
if (!agent) return;
clearTimeout(agent.initializationTimeout);
// Drain pending output before completion so the final lines land in