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([issue-5622]): corroborate CoS runner listings before treating agents as live (#5633)

[._.]/ Adam Eivy1ed339de7dc6
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 609760305e..c861045588 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -26,6 +26,7 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { createStreamJsonParser } from './streamJsonParser.js';
import { loadState, saveState, withState } from './runnerState.js';
import { getProcessStats, checkProcessRunning } from './processStats.js';
+import { usableAgentPid, runnerAgentLivenessFields } from '../lib/runnerAgentLiveness.js';
import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';
import { armForceKill as armForceKillShared } from './forceKill.js';
import { PORTS } from '../lib/ports.js';
@@ -120,23 +121,34 @@ app.get('/health', (req, res) => {
});
});
+async function inspectAgentProcess(agent) {
+ const pid = usableAgentPid(agent.pid);
+ const stats = pid ? await getProcessStats(pid) : null;
+ return { stats, ...runnerAgentLivenessFields(agent, stats) };
+}
+
/**
* Get list of active agents with process stats
*/
app.get('/agents', async (req, res) => {
const agents = [];
for (const [agentId, agent] of activeAgents) {
- const stats = await getProcessStats(agent.pid);
+ // onExit stamps exited then awaits disk I/O; skip so a dying handle is
+ // not advertised as a stale listing that sweeps would reap before
+ // agent:completed lands.
+ if (agent.exited === true) continue;
+ const inspected = await inspectAgentProcess(agent);
agents.push({
id: agentId,
taskId: agent.taskId,
pid: agent.pid,
startedAt: agent.startedAt,
runningTime: Date.now() - agent.startedAt,
- processActive: stats.active,
- cpu: stats.cpu,
- memoryMb: stats.memoryMb,
- state: stats.state,
+ processActive: inspected.processActive,
+ cpu: inspected.cpu,
+ memoryMb: inspected.memoryMb,
+ state: inspected.state,
+ liveness: inspected.liveness,
kind: agent.kind || 'cli',
sessionId: agent.sessionId || null,
command: agent.command || null,
@@ -241,6 +253,9 @@ app.post('/spawn-tui', async (req, res) => {
doneSentinelPath,
completedBySentinel: false,
doneWatcher: null,
+ // node-pty reports pid 0 for ConPTY on Windows, so a pid probe is not a
+ // liveness signal. onExit is the runner's authority; GET /agents reads this.
+ exited: false,
};
activeAgents.set(agentId, agent);
@@ -258,6 +273,11 @@ app.post('/spawn-tui', async (req, res) => {
try {
const current = activeAgents.get(agentId);
if (!current) return;
+ current.exited = true;
+ // Drop the handle before the awaited state write so GET /agents cannot
+ // publish processActive:false for a TUI whose completion event is still
+ // in flight (completeAgent keeps the first terminal verdict).
+ activeAgents.delete(agentId);
current.doneWatcher?.();
// Cancel any pending SIGKILL timer — process already exited.
if (current.killTimer) {
@@ -301,7 +321,6 @@ app.post('/spawn-tui', async (req, res) => {
if (!success) state.stats.failed++;
delete state.agents[agentId];
});
- activeAgents.delete(agentId);
} catch (err) {
console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);
activeAgents.delete(agentId);
@@ -356,8 +375,17 @@ app.get('/agents/:agentId/stats', async (req, res) => {
return res.status(404).json({ error: 'Agent not found or not running' });
}
- const stats = await getProcessStats(agent.pid);
- res.json({ agentId, pid: agent.pid, ...stats });
+ const inspected = await inspectAgentProcess(agent);
+ res.json({
+ agentId,
+ pid: agent.pid,
+ active: inspected.processActive,
+ cpu: inspected.cpu,
+ memoryKb: inspected.stats?.memoryKb ?? 0,
+ memoryMb: inspected.memoryMb,
+ state: inspected.state,
+ liveness: inspected.liveness,
+ });
});
/**
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index 2d15dd9d25..51eadc7cd8 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -133,6 +133,27 @@ describe('cos-runner durable TUI ownership (#3202)', () => {
expect(RUNNER_SRC).toContain('const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(executable, args, childEnv);');
});
+ it('tracks TUI liveness from onExit bookkeeping rather than a pid probe', () => {
+ // node-pty reports pid 0 for ConPTY on Windows, so getProcessStats(pid)
+ // reads every runner-owned TUI as invalid/dead. GET /agents must use the
+ // runner's own onExit flag, then tag the row so sweeps can tell a real
+ // processActive from that pid-0 artifact.
+ expect(RUNNER_SRC).toMatch(
+ /import\s*\{[^}]*\brunnerAgentLivenessFields\b[^}]*\}\s*from\s*'\.\.\/lib\/runnerAgentLiveness\.js';/
+ );
+ expect(RUNNER_SRC).toMatch(/exited:\s*false/);
+ expect(RUNNER_SRC).toMatch(/current\.exited\s*=\s*true/);
+ const onExitIdx = RUNNER_SRC.indexOf('tuiProcess.onExit');
+ const exitedIdx = RUNNER_SRC.indexOf('current.exited = true');
+ expect(exitedIdx, 'onExit must stamp exited before deleting the handle').toBeGreaterThan(onExitIdx);
+ const deleteIdx = RUNNER_SRC.indexOf('activeAgents.delete(agentId);', exitedIdx);
+ expect(deleteIdx, 'onExit must drop the handle before awaiting completion I/O').toBeGreaterThan(exitedIdx);
+ expect(deleteIdx).toBeLessThan(RUNNER_SRC.indexOf('await withState((state) => {', exitedIdx));
+ expect(RUNNER_SRC).toMatch(/if\s*\(\s*agent\.exited\s*===\s*true\s*\)\s*continue;/);
+ expect(RUNNER_SRC).toMatch(/runnerAgentLivenessFields\(agent,\s*stats\)/);
+ expect(RUNNER_SRC).toMatch(/inspectAgentProcess\(agent\)/);
+ });
+
it('spawns the PTY through the shared Windows-safe CLI wrapper', () => {
expect(RUNNER_SRC).toMatch(/app\.post\('\/spawn-tui'/);
expect(RUNNER_SRC).toMatch(/prepareCliSpawn\(executable, args, childEnv\)/);
diff --git a/server/lib/README.md b/server/lib/README.md
index 5979a65f30..92523bf207 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -454,6 +454,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `shellCd.js` | `buildCdCommand(path, shell)` + `formatShellCommandLine(command, args, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. `formatShellCommandLine` joins a command + argv into one quoted line and is shared by `agentTuiSpawning.js#buildTuiSpawnConfig` and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. |
| `shellExit.js` | `buildRunThenExitCommand(commandLine, shell)` — "run this CLI, then close the shell with its status", in the dialect the session speaks. An agent TUI shell exists only to host one CLI and must die with it. The POSIX `cmd; exit $?` was applied everywhere and is actively wrong off-POSIX: in PowerShell `$?` is a BOOLEAN, so `exit $?` reports success as 1 and failure as 0 (inverted) — use `$LASTEXITCODE`, pre-seeded to 1 so a command that never ran still exits non-zero; in cmd.exe `;` is an argument separator, so the CLI is handed `;`/`exit`/`$?` as arguments — use `& exit`. Verified against node-pty on Windows 11 for pwsh 7, PowerShell 5.1 and cmd.exe. |
| `shellLivenessProbe.js` | `buildLivenessProbeCommand(shellPid, platform?)` + `parseLivenessProbeOutput(stdout, shellPid)` + `shellHasLiveChild(shellPid, opts?)` — platform-aware process-liveness probe for a launched TUI command in a persistent PTY shell. POSIX (`ps -Ao ppid=`) / Windows (`Get-CimInstance Win32_Process \| Select-Object -ExpandProperty ParentProcessId` via PowerShell). Resolves true (assume alive) when the probe fails or cannot run. |
+| `runnerAgentLiveness.js` | CoS Runner GET /agents liveness. Presence in the runner's handle map is not proof of life: `runnerAgentLivenessFields` produces `processActive` + `liveness` (`pty` from TUI onExit bookkeeping, `pid` from a CLI probe) so Windows ConPTY `pid: 0` no longer reports every TUI as dead; `runnerEntryShieldsRunningRecord` is the corroboration gate both zombie/orphan sweeps use before a listing can keep a durable `running` record. |
| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |
| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. |
| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |
diff --git a/server/lib/index.js b/server/lib/index.js
index 48c5444a6c..0d4d6bd05a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -430,6 +430,7 @@ export * from './repoStateExpectations.js';
export * from './shellCd.js';
export * from './shellExit.js';
export * from './shellLivenessProbe.js';
+export * from './runnerAgentLiveness.js';
export * from './shellQuote.js';
export * from './shellReadinessProbe.js';
export * from './sidecarProcess.js';
diff --git a/server/lib/runnerAgentLiveness.js b/server/lib/runnerAgentLiveness.js
new file mode 100644
index 0000000000..6a4db531f7
--- /dev/null
+++ b/server/lib/runnerAgentLiveness.js
@@ -0,0 +1,99 @@
+/**
+ * CoS Runner agent liveness — presence in GET /agents is not proof of life.
+ *
+ * The runner's map is a list of PTY/child handles it has not seen exit. A
+ * failed kill (or a Windows ConPTY pid of 0) leaves a handle advertised after
+ * the process is gone. Sweeps must corroborate a listing with either a live
+ * pid or a liveness field that means more than "registered".
+ *
+ * `liveness: 'pty'` — TUI rows, from the runner's own onExit bookkeeping.
+ * `liveness: 'pid'` — CLI rows, from a pid probe.
+ * Older runners omit `liveness`; a TUI row's processActive is then a pid-0
+ * artifact and must not be read as dead.
+ */
+
+export const RUNNER_LIVENESS_PID = 'pid';
+export const RUNNER_LIVENESS_PTY = 'pty';
+
+export function usableAgentPid(pid) {
+ const n = Number.parseInt(pid, 10);
+ return Number.isInteger(n) && n > 0 ? n : null;
+}
+
+/**
+ * Fields a GET /agents row should carry for one in-memory runner handle.
+ * `stats` is a getProcessStats result when the pid was usable; otherwise null.
+ */
+export function runnerAgentLivenessFields(agent, stats) {
+ if (agent?.kind === 'tui') {
+ const active = agent.exited !== true;
+ return {
+ processActive: active,
+ state: active
+ ? (stats?.state && stats.state !== 'invalid' && stats.state !== 'dead' ? stats.state : 'running')
+ : 'dead',
+ cpu: stats?.cpu ?? 0,
+ memoryMb: stats?.memoryMb ?? 0,
+ liveness: RUNNER_LIVENESS_PTY,
+ };
+ }
+ return {
+ processActive: stats?.active === true,
+ state: stats?.state ?? 'unknown',
+ cpu: stats?.cpu ?? 0,
+ memoryMb: stats?.memoryMb ?? 0,
+ liveness: RUNNER_LIVENESS_PID,
+ };
+}
+
+/**
+ * Sync read of a GET /agents row: is this a live process, not just a handle?
+ * Does not probe pids — pair with `runnerEntryShieldsRunningRecord` when a
+ * live-pid corroboration is wanted.
+ */
+export function runnerListedAgentIsLive(entry) {
+ if (!entry || typeof entry !== 'object') return false;
+ if (entry.liveness === RUNNER_LIVENESS_PTY) return entry.processActive === true;
+ if (entry.liveness === RUNNER_LIVENESS_PID) return entry.processActive === true;
+ if (entry.processActive === true) return true;
+ // Pre-fix Windows TUI: node-pty reports pid 0, so processActive is always
+ // false whether the session is alive or dead. Presence is all we have.
+ // A pre-fix POSIX TUI has a real pid and a working probe — do not treat
+ // processActive:false as live just because kind is tui.
+ return entry.kind === 'tui' && !usableAgentPid(entry.pid);
+}
+
+/**
+ * Should a runner listing shield a durable `running` record from a sweep?
+ * A usable pid that is gone means the listing is stale even if the handle
+ * remains. TUI rows with no usable pid (Windows ConPTY) fall back to the
+ * onExit-backed processActive flag.
+ *
+ * `pidIsAlive` is injected so callers reuse their existing probe; awaited so
+ * both sync and async probes work.
+ */
+const defaultPidIsAlive = (pid) => {
+ const n = Number.parseInt(pid, 10);
+ if (!Number.isInteger(n) || n <= 0) return false;
+ try {
+ process.kill(n, 0);
+ return true;
+ } catch (err) {
+ return err?.code === 'EPERM';
+ }
+};
+
+export async function runnerEntryShieldsRunningRecord(entry, pidIsAlive = defaultPidIsAlive) {
+ if (!entry || typeof entry !== 'object') return false;
+ if (entry.liveness === RUNNER_LIVENESS_PTY) {
+ return entry.processActive === true;
+ }
+ const pid = usableAgentPid(entry.pid);
+ if (entry.liveness === RUNNER_LIVENESS_PID) {
+ if (entry.processActive === true) return true;
+ return pid ? Boolean(await pidIsAlive(pid)) : false;
+ }
+ if (entry.processActive === true) return true;
+ if (entry.kind === 'tui' && !pid) return true;
+ return pid ? Boolean(await pidIsAlive(pid)) : false;
+}
diff --git a/server/lib/runnerAgentLiveness.test.js b/server/lib/runnerAgentLiveness.test.js
new file mode 100644
index 0000000000..2b28e14876
--- /dev/null
+++ b/server/lib/runnerAgentLiveness.test.js
@@ -0,0 +1,164 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ RUNNER_LIVENESS_PID,
+ RUNNER_LIVENESS_PTY,
+ usableAgentPid,
+ runnerAgentLivenessFields,
+ runnerListedAgentIsLive,
+ runnerEntryShieldsRunningRecord,
+} from './runnerAgentLiveness.js';
+
+describe('usableAgentPid', () => {
+ it('accepts a positive integer and rejects ConPTY / invalid pids', () => {
+ expect(usableAgentPid(1234)).toBe(1234);
+ expect(usableAgentPid('99')).toBe(99);
+ expect(usableAgentPid(0)).toBeNull();
+ expect(usableAgentPid(-1)).toBeNull();
+ expect(usableAgentPid(null)).toBeNull();
+ expect(usableAgentPid('nope')).toBeNull();
+ });
+});
+
+describe('runnerAgentLivenessFields', () => {
+ it('reports a TUI as live from onExit bookkeeping, not a pid-0 probe', () => {
+ const fields = runnerAgentLivenessFields({ kind: 'tui', pid: 0, exited: false }, {
+ active: false, state: 'invalid', cpu: 0, memoryMb: 0,
+ });
+ expect(fields).toEqual({
+ processActive: true,
+ state: 'running',
+ cpu: 0,
+ memoryMb: 0,
+ liveness: RUNNER_LIVENESS_PTY,
+ });
+ });
+
+ it('reports a TUI as dead once onExit has fired', () => {
+ const fields = runnerAgentLivenessFields({ kind: 'tui', pid: 0, exited: true }, null);
+ expect(fields.processActive).toBe(false);
+ expect(fields.state).toBe('dead');
+ expect(fields.liveness).toBe(RUNNER_LIVENESS_PTY);
+ });
+
+ it('keeps CPU/memory from a usable TUI pid while processActive follows onExit', () => {
+ const fields = runnerAgentLivenessFields(
+ { kind: 'tui', pid: 4321, exited: false },
+ { active: true, state: 'S', cpu: 1.5, memoryMb: 12.3 },
+ );
+ expect(fields.processActive).toBe(true);
+ expect(fields.state).toBe('S');
+ expect(fields.cpu).toBe(1.5);
+ expect(fields.memoryMb).toBe(12.3);
+ expect(fields.liveness).toBe(RUNNER_LIVENESS_PTY);
+ });
+
+ it('treats a CLI row as a pid probe', () => {
+ const live = runnerAgentLivenessFields(
+ { kind: 'cli', pid: 7 },
+ { active: true, state: 'R', cpu: 2, memoryMb: 8 },
+ );
+ expect(live).toMatchObject({
+ processActive: true, state: 'R', liveness: RUNNER_LIVENESS_PID,
+ });
+ const dead = runnerAgentLivenessFields(
+ { pid: 7 },
+ { active: false, state: 'dead', cpu: 0, memoryMb: 0 },
+ );
+ expect(dead).toMatchObject({
+ processActive: false, state: 'dead', liveness: RUNNER_LIVENESS_PID,
+ });
+ });
+});
+
+describe('runnerListedAgentIsLive', () => {
+ it('trusts processActive when the runner tagged how it measured', () => {
+ expect(runnerListedAgentIsLive({
+ processActive: true, liveness: RUNNER_LIVENESS_PTY, kind: 'tui',
+ })).toBe(true);
+ expect(runnerListedAgentIsLive({
+ processActive: false, liveness: RUNNER_LIVENESS_PTY, kind: 'tui',
+ })).toBe(false);
+ expect(runnerListedAgentIsLive({
+ processActive: false, liveness: RUNNER_LIVENESS_PID, kind: 'cli',
+ })).toBe(false);
+ });
+
+ it('does not treat a pre-fix Windows TUI processActive false as dead', () => {
+ expect(runnerListedAgentIsLive({
+ kind: 'tui', pid: 0, processActive: false,
+ })).toBe(true);
+ });
+
+ it('does not treat a pre-fix POSIX TUI with a dead pid as live', () => {
+ expect(runnerListedAgentIsLive({
+ kind: 'tui', pid: 4242, processActive: false,
+ })).toBe(false);
+ });
+
+ it('does not treat a bare CLI listing as live', () => {
+ expect(runnerListedAgentIsLive({ id: 'agent-1', kind: 'cli', pid: 9 })).toBe(false);
+ expect(runnerListedAgentIsLive({
+ kind: 'cli', pid: 9, processActive: false,
+ })).toBe(false);
+ });
+});
+
+describe('runnerEntryShieldsRunningRecord', () => {
+ const pidIsAlive = vi.fn();
+
+ it('shields a live TUI from onExit bookkeeping without probing pid 0', async () => {
+ pidIsAlive.mockResolvedValue(false);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'tui', pid: 0, processActive: true, liveness: RUNNER_LIVENESS_PTY,
+ }, pidIsAlive)).resolves.toBe(true);
+ expect(pidIsAlive).not.toHaveBeenCalled();
+ });
+
+ it('does not shield a TUI whose onExit bookkeeping says the process is gone', async () => {
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'tui', pid: 0, processActive: false, liveness: RUNNER_LIVENESS_PTY,
+ }, pidIsAlive)).resolves.toBe(false);
+ });
+
+ it('does not shield a CLI listing whose pid probe says dead', async () => {
+ pidIsAlive.mockResolvedValue(false);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'cli', pid: 4242, processActive: false, liveness: RUNNER_LIVENESS_PID,
+ }, pidIsAlive)).resolves.toBe(false);
+ });
+
+ it('still shields a CLI whose processActive flaked but the pid is alive', async () => {
+ pidIsAlive.mockResolvedValue(true);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'cli', pid: 4242, processActive: false, liveness: RUNNER_LIVENESS_PID,
+ }, pidIsAlive)).resolves.toBe(true);
+ });
+
+ it('shields a pre-fix Windows TUI listed with a pid-0 artifact', async () => {
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'tui', pid: 0, processActive: false,
+ }, pidIsAlive)).resolves.toBe(true);
+ });
+
+ it('does not shield a pre-fix POSIX TUI listing unless the pid is still alive', async () => {
+ pidIsAlive.mockResolvedValue(false);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'tui', pid: 4242, processActive: false,
+ }, pidIsAlive)).resolves.toBe(false);
+ pidIsAlive.mockResolvedValue(true);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'tui', pid: 4242, processActive: false,
+ }, pidIsAlive)).resolves.toBe(true);
+ });
+
+ it('does not shield a pre-fix CLI listing unless the pid is still alive', async () => {
+ pidIsAlive.mockResolvedValue(false);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'cli', pid: 4242, processActive: false,
+ }, pidIsAlive)).resolves.toBe(false);
+ pidIsAlive.mockResolvedValue(true);
+ await expect(runnerEntryShieldsRunningRecord({
+ kind: 'cli', pid: 4242, processActive: false,
+ }, pidIsAlive)).resolves.toBe(true);
+ });
+});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 028404a534..7ccf30a388 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -18,9 +18,10 @@ import { completeAgent, updateAgent, getAgents, getAgentRecord, AGENT_RECORD_UNR
import { updateTask, addTask, getTaskById, reviveBlockedTask, evaluateTasks } from './cos.js';
import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, pauseMetadata, isAgentPausedTask, isResumablePausedTask, registerPauseReleaseAdapter } from '../lib/taskPauseHold.js';
import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
+import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, isAgentOwnedLocally, unregisterSpawnedAgent } from './agentState.js';
+import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, unregisterSpawnedAgent } 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
@@ -1018,10 +1019,10 @@ async function runCleanupOrphanedAgents() {
return { available: false, agents: [] };
},
);
- const runnerActiveIds = new Set();
+ const runnerById = new Map();
const runnerAgentsList = runnerProbe.agents;
- for (const agent of runnerAgentsList) {
- runnerActiveIds.add(agent.id);
+ for (const row of runnerAgentsList) {
+ if (row?.id) runnerById.set(row.id, row);
}
// Also sync runner agents to our local map for event handling
@@ -1055,7 +1056,10 @@ async function runCleanupOrphanedAgents() {
for (const agent of agents) {
if (agent.status === 'running') {
- const inRemoteRunner = runnerActiveIds.has(agent.id);
+ const inRemoteRunner = await runnerEntryShieldsRunningRecord(
+ runnerById.get(agent.id),
+ isPidAlive,
+ );
// A runner-owned agent may still be alive while the runner is booting or
// reconnecting. Its absence from a failed probe is not evidence that the
@@ -1073,98 +1077,103 @@ async function runCleanupOrphanedAgents() {
continue;
}
- 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);
- if (stillAlive) {
- console.log(`🔄 Agent ${agent.id} (PID ${agent.pid}) still running, re-syncing to runner tracking`);
- const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';
- runnerAgents.set(agent.id, {
- id: agent.id, pid: agent.pid, taskId: agent.taskId,
- task: { id: agent.taskId, taskType: inferredType, description: 'Re-synced from PID check' }
- });
- continue;
- }
- }
-
- const interrupted = interruptedByRestart.has(agent.id);
- const errorMessage = interrupted
- ? 'Agent was interrupted by a PortOS server restart'
- : 'Agent process terminated unexpectedly';
- console.log(interrupted
- ? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`
- : `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
- // Record the reap in the lifecycle ledger BEFORE the run is closed
- // (#4540), so the ordered stream reads "orphaned, then finalized" and a
- // replay can tell an agent that died from one that exited. Emitted even
- // when the agent record carries no `runId` — a survivor whose run id
- // never landed is precisely the case the mutable records cannot explain,
- // so it keys off the agent instead of disappearing.
- await appendRunEvent({
- kind: 'run.orphan-recovered',
- // Explicit natural key rather than the content-derived default: this
- // sweep runs every 15 minutes and can re-observe the same dead agent
- // if the `completeAgent` write below ever fails to land, and the
- // content hash covers the wall-clock `at`, so a retry would otherwise
- // mint a second "this agent died" fact. An agent dies once per life,
- // and `id + startedAt` names exactly that.
- eventId: `orphan:${agent.id}:${agent.startedAt || 'unknown'}`,
- runId: agent.metadata?.runId,
- agentId: agent.id,
- taskId: agent.taskId,
- data: {
- interruptedByRestart: interrupted,
- pid: agent.pid ?? null,
- hasRunId: Boolean(agent.metadata?.runId),
- startedAt: agent.startedAt ?? null,
- },
- });
- const task = agent.taskId ? await getTaskById(agent.taskId).catch(() => null) : null;
- await dispatchRecoveredTaskOutputHook({
- agentId: agent.id,
- task,
- success: false,
- workspacePath: agent.metadata?.workspacePath || null,
- });
- if (agent.metadata?.runId) {
- const bufferedOutput = Array.isArray(agent.output)
- ? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
- : '';
- const output = await tryReadFile(join(PATHS.cosAgents, agent.id, 'output.txt')) ?? bufferedOutput;
- const startedAt = Date.parse(agent.startedAt);
- const duration = Number.isFinite(startedAt) ? Math.max(0, Date.now() - startedAt) : 0;
- // Close the run BEFORE the agent record. If the run write fails, the
- // agent remains eligible for the next sweep; if the later agent write
- // fails, completeAgentRun's endTime guard makes this retry harmless.
- await completeAgentRun(agent.metadata.runId, output, interrupted ? 143 : 1, duration, {
- message: errorMessage,
- category: interrupted ? 'interrupted' : 'orphaned',
+ // Direct-spawn handles in this process are live. Leftover runnerAgents
+ // ownership from an earlier adopt is not — a stale listing must not keep
+ // the durable record running forever.
+ if (activeAgents.has(agent.id)) continue;
+ if (inRemoteRunner) continue;
+ if (runnerAgents.has(agent.id)) runnerAgents.delete(agent.id);
+
+ // Before marking as orphaned, check if the process is actually still running
+ if (agent.pid) {
+ const stillAlive = await isPidAlive(agent.pid);
+ if (stillAlive) {
+ console.log(`🔄 Agent ${agent.id} (PID ${agent.pid}) still running, re-syncing to runner tracking`);
+ const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';
+ runnerAgents.set(agent.id, {
+ id: agent.id, pid: agent.pid, taskId: agent.taskId,
+ task: { id: agent.taskId, taskType: inferredType, description: 'Re-synced from PID check' }
});
+ continue;
}
- await completeAgent(agent.id, {
- success: false,
- error: errorMessage,
- orphaned: true,
- // Post-mortem telemetry on the agent record (nothing reads it yet —
- // the human-visible distinction is the `error` string above). Worth
- // persisting because an infrastructure interruption and a real agent
- // fault are indistinguishable from the process's point of view once
- // the record is written.
+ }
+
+ const interrupted = interruptedByRestart.has(agent.id);
+ const errorMessage = interrupted
+ ? 'Agent was interrupted by a PortOS server restart'
+ : 'Agent process terminated unexpectedly';
+ console.log(interrupted
+ ? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`
+ : `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
+ // Record the reap in the lifecycle ledger BEFORE the run is closed
+ // (#4540), so the ordered stream reads "orphaned, then finalized" and a
+ // replay can tell an agent that died from one that exited. Emitted even
+ // when the agent record carries no `runId` — a survivor whose run id
+ // never landed is precisely the case the mutable records cannot explain,
+ // so it keys off the agent instead of disappearing.
+ await appendRunEvent({
+ kind: 'run.orphan-recovered',
+ // Explicit natural key rather than the content-derived default: this
+ // sweep runs every 15 minutes and can re-observe the same dead agent
+ // if the `completeAgent` write below ever fails to land, and the
+ // content hash covers the wall-clock `at`, so a retry would otherwise
+ // mint a second "this agent died" fact. An agent dies once per life,
+ // and `id + startedAt` names exactly that.
+ eventId: `orphan:${agent.id}:${agent.startedAt || 'unknown'}`,
+ runId: agent.metadata?.runId,
+ agentId: agent.id,
+ taskId: agent.taskId,
+ data: {
interruptedByRestart: interrupted,
+ pid: agent.pid ?? null,
+ hasRunId: Boolean(agent.metadata?.runId),
+ startedAt: agent.startedAt ?? null,
+ },
+ });
+ const task = agent.taskId ? await getTaskById(agent.taskId).catch(() => null) : null;
+ await dispatchRecoveredTaskOutputHook({
+ agentId: agent.id,
+ task,
+ success: false,
+ workspacePath: agent.metadata?.workspacePath || null,
+ });
+ if (agent.metadata?.runId) {
+ const bufferedOutput = Array.isArray(agent.output)
+ ? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
+ : '';
+ const output = await tryReadFile(join(PATHS.cosAgents, agent.id, 'output.txt')) ?? bufferedOutput;
+ const startedAt = Date.parse(agent.startedAt);
+ const duration = Number.isFinite(startedAt) ? Math.max(0, Date.now() - startedAt) : 0;
+ // Close the run BEFORE the agent record. If the run write fails, the
+ // agent remains eligible for the next sweep; if the later agent write
+ // fails, completeAgentRun's endTime guard makes this retry harmless.
+ await completeAgentRun(agent.metadata.runId, output, interrupted ? 143 : 1, duration, {
+ message: errorMessage,
+ category: interrupted ? 'interrupted' : 'orphaned',
});
- cleanedCount++;
-
- if (agent.taskId) {
- // Carry the agent's metadata forward rather than re-reading the record
- // later: `getAgent` on a completed agent still hits the disk to hydrate
- // its output.txt tail (capped since #3498, but not free), and the
- // worktree fields the resume pointer needs are stamped once at
- // registerAgent and never mutated.
- // `startedAt` rides along too — it's the window the commit probe in
- // handleOrphanedTask needs to tell this run's commits from the repo's.
- orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata, agentStartedAt: agent.startedAt });
- }
+ }
+ await completeAgent(agent.id, {
+ success: false,
+ error: errorMessage,
+ orphaned: true,
+ // Post-mortem telemetry on the agent record (nothing reads it yet —
+ // the human-visible distinction is the `error` string above). Worth
+ // persisting because an infrastructure interruption and a real agent
+ // fault are indistinguishable from the process's point of view once
+ // the record is written.
+ interruptedByRestart: interrupted,
+ });
+ cleanedCount++;
+
+ if (agent.taskId) {
+ // Carry the agent's metadata forward rather than re-reading the record
+ // later: `getAgent` on a completed agent still hits the disk to hydrate
+ // its output.txt tail (capped since #3498, but not free), and the
+ // worktree fields the resume pointer needs are stamped once at
+ // registerAgent and never mutated.
+ // `startedAt` rides along too — it's the window the commit probe in
+ // handleOrphanedTask needs to tell this run's commits from the repo's.
+ orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata, agentStartedAt: agent.startedAt });
}
}
}
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 1a1509165c..354f1a8793 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -141,7 +141,11 @@ const fakeChildProcess = (kill = vi.fn()) =>
import { hasPauseReleaseAdapter, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';
describe('cleanupOrphanedAgents — startup recovery coordination', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ runnerAgents.clear();
+ });
it('shares one in-flight sweep between concurrent startup callers', async () => {
let releaseProbe;
@@ -215,6 +219,99 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
expect(markAgentComplete).not.toHaveBeenCalled();
expect(updateTask).not.toHaveBeenCalled();
});
+
+ it('reaps a durable running record whose runner listing is stale', async () => {
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-stale',
+ status: 'running',
+ pid: 2147483646,
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner' },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce([{
+ id: 'agent-stale',
+ pid: 2147483646,
+ kind: 'cli',
+ processActive: false,
+ liveness: 'pid',
+ }]);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-stale', expect.objectContaining({
+ success: false,
+ orphaned: true,
+ }));
+ });
+
+ it('does not reap a live runner-owned TUI advertised via onExit liveness', async () => {
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-tui',
+ status: 'running',
+ pid: 0,
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner-tui' },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce([{
+ id: 'agent-tui',
+ pid: 0,
+ kind: 'tui',
+ processActive: true,
+ liveness: 'pty',
+ }]);
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
+
+ it('reaps a stale listing even if runnerAgents already adopted the id', async () => {
+ runnerAgents.set('agent-stale', { taskId: 'task-1' });
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-stale',
+ status: 'running',
+ pid: 2147483646,
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner' },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce([{
+ id: 'agent-stale',
+ pid: 2147483646,
+ kind: 'cli',
+ processActive: false,
+ liveness: 'pid',
+ }]);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-stale', expect.objectContaining({
+ success: false,
+ orphaned: true,
+ }));
+ expect(runnerAgents.has('agent-stale')).toBe(false);
+ });
+
+ it('does not reap a pre-fix Windows TUI whose processActive is a pid-0 artifact', async () => {
+ getAgents.mockResolvedValueOnce([{
+ id: 'agent-tui-old',
+ status: 'running',
+ pid: 0,
+ taskId: 'task-1',
+ metadata: { useRunner: true, executionMode: 'runner-tui' },
+ }]);
+ getActiveAgentsFromRunner.mockResolvedValueOnce([{
+ id: 'agent-tui-old',
+ pid: 0,
+ kind: 'tui',
+ processActive: false,
+ }]);
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
});
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.js
index 2fee88b8ba..a5e22d2051 100644
--- a/server/services/agentRunnerSync.js
+++ b/server/services/agentRunnerSync.js
@@ -12,6 +12,7 @@
*/
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
+import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { isInternalTaskId } from '../lib/taskParser.js';
import { isAgentOwnedLocally, runnerAgents } from './agentState.js';
import { AGENT_RECORD_UNREADABLE, isLiveAgentRecord, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';
@@ -65,6 +66,10 @@ export async function syncRunnerAgents() {
let syncedCount = 0;
for (const agent of agents) {
+ // A stale runner handle (listed, process gone) is not a survivor to
+ // re-adopt — adopting it would put it in runnerAgents and the orphan
+ // sweep would treat that local map as ownership. Live rows still sync.
+ if (!(await runnerEntryShieldsRunningRecord(agent))) continue;
// Only sync if this process isn't already driving it
if (!isAgentOwnedLocally(agent.id)) {
const task = taskMap.get(agent.taskId);
diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.js
index d3b79167ef..79102f326e 100644
--- a/server/services/agentRunnerSync.test.js
+++ b/server/services/agentRunnerSync.test.js
@@ -67,6 +67,8 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
pid: 1234,
startedAt: Date.now(),
kind: 'tui',
+ processActive: true,
+ liveness: 'pty',
sessionId: 'tui-session-1',
command: 'codex',
workspacePath: '/tmp/example-workspace',
@@ -102,7 +104,8 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
metadata: { runId: 'run-abc123', model: 'claude-opus-5' },
});
vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
- id: 'agent-1', taskId: 'task-1', pid: 1234, startedAt: Date.now(), kind: 'cli',
+ id: 'agent-1', taskId: 'task-1', pid: 1234, startedAt: Date.now(),
+ kind: 'cli', processActive: true, liveness: 'pid',
}]);
await expect(syncRunnerAgents()).resolves.toBe(1);
@@ -121,7 +124,8 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
// event lands. The run stays open, which the warning line says out loud.
vi.mocked(readAgentRecordOrUnreadable).mockResolvedValue(AGENT_RECORD_UNREADABLE);
vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
- id: 'agent-2', taskId: 'task-1', pid: 99, startedAt: Date.now(), kind: 'cli',
+ id: 'agent-2', taskId: 'task-1', pid: 99, startedAt: Date.now(),
+ kind: 'cli', processActive: true, liveness: 'pid',
}]);
await expect(syncRunnerAgents()).resolves.toBe(1);
@@ -147,9 +151,9 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
return { id, status: 'running' };
});
vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([
- { id: 'agent-finalized', taskId: 'task-1', pid: 1, startedAt: Date.now(), kind: 'cli' },
- { id: 'agent-gone', taskId: 'task-1', pid: 2, startedAt: Date.now(), kind: 'cli' },
- { id: 'agent-real', taskId: 'task-1', pid: 3, startedAt: Date.now(), kind: 'cli' },
+ { id: 'agent-finalized', taskId: 'task-1', pid: 1, startedAt: Date.now(), kind: 'cli', processActive: true, liveness: 'pid' },
+ { id: 'agent-gone', taskId: 'task-1', pid: 2, startedAt: Date.now(), kind: 'cli', processActive: true, liveness: 'pid' },
+ { id: 'agent-real', taskId: 'task-1', pid: 3, startedAt: Date.now(), kind: 'cli', processActive: true, liveness: 'pid' },
]);
await expect(syncRunnerAgents()).resolves.toBe(1);
@@ -175,11 +179,13 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
pid: 4321,
startedAt: Date.now(),
kind: 'tui',
+ processActive: true,
+ liveness: 'pty',
sessionId: 'tui-session-live',
command: 'claude',
workspacePath: '/tmp/example-workspace',
},
- { id: 'agent-orphan', taskId: 'task-1', pid: 8765, startedAt: Date.now(), kind: 'cli' },
+ { id: 'agent-orphan', taskId: 'task-1', pid: 8765, startedAt: Date.now(), kind: 'cli', processActive: true, liveness: 'pid' },
]);
await expect(syncRunnerAgents()).resolves.toBe(1);
@@ -191,6 +197,21 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
expect(connectTuiSessionViaRunner).not.toHaveBeenCalled();
expect(shellService.registerExternalSession).not.toHaveBeenCalled();
});
+
+ it('does not re-adopt a stale runner handle whose process is gone', async () => {
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-stale',
+ taskId: 'task-1',
+ pid: 2147483646,
+ startedAt: Date.now(),
+ kind: 'cli',
+ processActive: false,
+ liveness: 'pid',
+ }]);
+
+ await expect(syncRunnerAgents()).resolves.toBe(0);
+ expect(runnerAgents.has('agent-stale')).toBe(false);
+ });
});
describe('syncRunnerAgents — reconnect boundary (#4540)', () => {
@@ -204,7 +225,8 @@ describe('syncRunnerAgents — reconnect boundary (#4540)', () => {
const survivingTui = {
id: 'agent-1', taskId: 'task-1', pid: 42, startedAt: Date.now(),
- kind: 'tui', sessionId: 'tui-session-1', workspacePath: '/repo/worktree', command: 'claude',
+ kind: 'tui', processActive: true, liveness: 'pty',
+ sessionId: 'tui-session-1', workspacePath: '/repo/worktree', command: 'claude',
};
it('records the PTY re-attach separately from the run re-adoption', async () => {
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index bb5157f78b..5aa675c213 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -17,6 +17,7 @@ import { cosEvents } from './cosEvents.js';
import { ServerError } from '../lib/errorHandler.js';
import { loadState, saveState, withStateLock, readAgentsStateForSafetyCheck, AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir, readFileTail, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
import { loadAgentIndex, saveAgentIndex, getAgentDir } from './cosAgentIndex.js';
@@ -657,15 +658,24 @@ async function isPidAlive(pid) {
// Cleanup zombie agents - agents marked as running but whose process is dead
export async function cleanupZombieAgents() {
- // Check local tracking maps (read from the side-effect-free state module, not
- // subAgentSpawner — avoids pulling in the heavier orchestrator just to read the maps).
- const { getActiveAgentIds } = await import('./agentState.js');
- const activeIds = getActiveAgentIds();
+ // Direct-spawn handles in this process (not leftover runnerAgents adopts —
+ // those are only a handle, same as GET /agents). Read from the side-effect-free
+ // state module, not subAgentSpawner.
+ const { activeAgents } = await import('./agentState.js');
// Also check with the CoS runner for agents it's actively tracking
const { getActiveAgentsFromRunner } = await import('./cosRunnerClient.js');
- const runnerAgents = await getActiveAgentsFromRunner().catch(() => []);
- const runnerAgentIds = new Set(runnerAgents.map(a => a.id));
+ const runnerProbe = await getActiveAgentsFromRunner().then(
+ (agents) => Array.isArray(agents)
+ ? { available: true, agents }
+ : { available: false, agents: [] },
+ () => ({ available: false, agents: [] }),
+ );
+ const runnerById = new Map(
+ runnerProbe.agents
+ .filter((row) => row?.id)
+ .map((row) => [row.id, row]),
+ );
return withStateLock(async () => {
const state = await loadState();
@@ -673,8 +683,20 @@ export async function cleanupZombieAgents() {
const cleaned = [];
for (const agent of runningAgents) {
- // Skip if tracked in local maps or runner
- if (activeIds.includes(agent.id) || runnerAgentIds.has(agent.id)) {
+ // A runner listing is only a shield when corroborated (live pid or
+ // processActive from onExit/pid probe). Leftover runnerAgents ownership
+ // from an earlier adopt is not.
+ if (activeAgents.has(agent.id)) continue;
+ const executionMode = agent.metadata?.executionMode;
+ const runnerOwned = agent.metadata?.useRunner === true
+ || agent.metadata?.useRunner === 'true'
+ || executionMode === 'runner'
+ || executionMode === 'runner-tui';
+ // Same as the orphan sweep: a failed probe is not evidence the runner
+ // process died. A pid-0 TUI after restart would otherwise be archived
+ // as "never started" the moment the runner is unreachable.
+ if (!runnerProbe.available && runnerOwned) continue;
+ if (await runnerEntryShieldsRunningRecord(runnerById.get(agent.id), isPidAlive)) {
continue;
}
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index 3ec894de49..3d1cfe813d 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -54,16 +54,25 @@ vi.mock('fs/promises', async (importOriginal) => {
};
});
-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
+vi.mock('./cosRunnerClient.js', () => ({
+ getActiveAgentsFromRunner: vi.fn().mockResolvedValue([]),
+}));
+
+import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.js';
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
+import { getActiveAgentsFromRunner } from './cosRunnerClient.js';
+import { activeAgents, runnerAgents } from './agentState.js';
describe('cosAgentLifecycle', () => {
beforeEach(async () => {
await rm(mockCosState.agentsDir, { recursive: true, force: true });
await mkdir(mockCosState.agentsDir, { recursive: true });
mockCosState.state = { agents: {} };
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([]);
+ activeAgents.clear();
+ runnerAgents.clear();
});
afterEach(async () => {
@@ -640,3 +649,97 @@ describe('createAgentOutputBatcher', () => {
expect(logged).toBe(true);
});
});
+
+describe('cleanupZombieAgents — runner listing is not proof of life', () => {
+ beforeEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ mockCosState.state = { agents: {} };
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([]);
+ activeAgents.clear();
+ runnerAgents.clear();
+ });
+
+ afterEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ });
+
+ it('does not reap a runner-owned TUI while the runner probe is unavailable', async () => {
+ mockCosState.state.agents['agent-tui'] = {
+ id: 'agent-tui',
+ status: 'running',
+ pid: 0,
+ startedAt: new Date(Date.now() - 60_000).toISOString(),
+ metadata: { useRunner: true, executionMode: 'runner-tui' },
+ };
+ vi.mocked(getActiveAgentsFromRunner).mockRejectedValueOnce(new Error('runner is booting'));
+
+ const result = await cleanupZombieAgents();
+ expect(result.cleaned).toEqual([]);
+ expect(mockCosState.state.agents['agent-tui'].status).toBe('running');
+ });
+
+ it('leaves a live runner-owned TUI whose onExit liveness is true', async () => {
+ mockCosState.state.agents['agent-tui'] = {
+ id: 'agent-tui',
+ status: 'running',
+ pid: 0,
+ startedAt: new Date(Date.now() - 60_000).toISOString(),
+ };
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-tui',
+ pid: 0,
+ kind: 'tui',
+ processActive: true,
+ liveness: 'pty',
+ }]);
+
+ const result = await cleanupZombieAgents();
+ expect(result.cleaned).toEqual([]);
+ expect(mockCosState.state.agents['agent-tui'].status).toBe('running');
+ });
+
+ it('retires a stale listing even if runnerAgents already adopted the id', async () => {
+ await writeFile(join(mockCosState.agentsDir, 'index.json'), '{}');
+ runnerAgents.set('agent-stale', { taskId: 'task-1' });
+ mockCosState.state.agents['agent-stale'] = {
+ id: 'agent-stale',
+ status: 'running',
+ pid: 2147483646,
+ startedAt: new Date(Date.now() - 60_000).toISOString(),
+ };
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-stale',
+ pid: 2147483646,
+ kind: 'cli',
+ processActive: false,
+ liveness: 'pid',
+ }]);
+
+ const result = await cleanupZombieAgents();
+ expect(result.cleaned).toEqual(['agent-stale']);
+ expect(mockCosState.state.agents['agent-stale'].status).toBe('completed');
+ });
+
+ it('retires a durable running record whose runner listing is stale', async () => {
+ await writeFile(join(mockCosState.agentsDir, 'index.json'), '{}');
+ mockCosState.state.agents['agent-stale'] = {
+ id: 'agent-stale',
+ status: 'running',
+ pid: 2147483646,
+ startedAt: new Date(Date.now() - 60_000).toISOString(),
+ };
+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{
+ id: 'agent-stale',
+ pid: 2147483646,
+ kind: 'cli',
+ processActive: false,
+ liveness: 'pid',
+ }]);
+
+ const result = await cleanupZombieAgents();
+ expect(result.cleaned).toEqual(['agent-stale']);
+ expect(mockCosState.state.agents['agent-stale'].status).toBe('completed');
+ expect(mockCosState.state.agents['agent-stale'].result.error).toMatch(/terminated unexpectedly/);
+ });
+});