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: drain CoS agents before runner restarts (#8641)

[._.]/ Adam Eivy7b28960af5a2
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index dab5ee544c..060c7e9fc5 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -16,7 +16,7 @@ import { writeFile, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import http from 'http';
import { Server as SocketServer } from 'socket.io';
-import { ensureDir, PATHS, sleep, watchForFile } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, watchForFile } from '../lib/fileUtils.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
@@ -28,12 +28,14 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';
import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';
import { createStreamJsonParser } from '../lib/streamJsonParser.js';
-import { loadState, saveState, withState } from './runnerState.js';
+import { withState, drainState } 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 { createTuiExitHandler } from './tuiExit.js';
+import { createRunnerShutdown, registerRunnerShutdownSignals } from './shutdown.js';
+import { createHttpDrain } from '../lib/httpDrain.js';
import { PORTS } from '../lib/ports.js';
import { setupProcessErrorHandlers } from '../lib/errorHandler.js';
import { parseSentinelPayload } from '../lib/agentSentinel.js';
@@ -56,7 +58,6 @@ setupProcessErrorHandlers();
// windows are obvious at each call site instead of bare literals.
const SIGKILL_GRACE_MS = 5000; // wait after SIGTERM before forcing SIGKILL
const ORPHAN_CLEANUP_DELAY_MS = 3000; // delay on boot before reaping orphaned agents
-const SHUTDOWN_DRAIN_MS = 5000; // SIGTERM drain window before closing the server
// Agentic CLIs can spend several seconds loading config/plugins before their
// lightweight version command returns. Keep this aligned with commandExists'
// documented heavy-CLI probe budget so a cold but runnable provider is not
@@ -101,6 +102,41 @@ const io = new SocketServer(server, {
cors: { origin: '*' }
});
+const httpDrain = createHttpDrain([server]);
+let transportClose;
+const lifecycle = createRunnerShutdown({
+ stopIntake: (deadlineMs) => httpDrain.begin(deadlineMs),
+ closeTransports: () => {
+ transportClose ??= new Promise(resolve => {
+ io.close(resolve);
+ server.closeAllConnections?.();
+ });
+ return transportClose;
+ },
+ drainState,
+ exit: (code) => process.exit(code),
+});
+registerRunnerShutdownSignals(process, lifecycle);
+
+// Keep established sockets for outgoing completion events, but stop incoming
+// commands and new namespace connections as soon as shutdown starts.
+io.use((socket, next) => next(lifecycle.isStopping() ? new Error('Runner is shutting down') : undefined));
+
+async function persistCompletion(agentId, output, metadata) {
+ const agentDir = join(AGENTS_DIR, agentId);
+ await ensureDir(agentDir);
+ await writeFile(join(agentDir, 'output.txt'), output);
+ if (!metadata) return;
+ const metadataPath = join(agentDir, 'metadata.json');
+ const existing = JSON.parse(await readFile(metadataPath, 'utf-8').catch(err => {
+ if (err.code === 'ENOENT') return '{}';
+ throw err;
+ }));
+ await writeFile(metadataPath, JSON.stringify({
+ ...existing, agentId, ...metadata, outputSize: Buffer.byteLength(output),
+ }, null, 2));
+}
+
/**
* Emit event to connected portos-server instances
*/
@@ -163,7 +199,7 @@ app.get('/agents', async (req, res) => {
* runner owns process survival and emits normal agent completion if the server
* restarts before the TUI exits.
*/
-app.post('/spawn-tui', async (req, res) => {
+app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
const {
agentId,
taskId,
@@ -232,6 +268,7 @@ app.post('/spawn-tui', async (req, res) => {
env: childEnv,
cwd,
});
+ if (lifecycle.rejectSpawn(res)) return;
if (!runnable) {
return res.status(422).json({
error: `Command executable unavailable: ${basename(command)} did not pass the CoS Runner capability check. Reinstall it or update the provider command.`
@@ -296,27 +333,31 @@ app.post('/spawn-tui', async (req, res) => {
io.emit('tui:output', { sessionId, agentId, data });
});
- tuiProcess.onExit(createTuiExitHandler({
+ tuiProcess.onExit(lifecycle.agentExit(agentId, agent, createTuiExitHandler({
agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState,
- }));
+ persistCompletion, onError: lifecycle.reportFailure,
+ })));
if (doneSentinelPath) {
- agent.doneWatcher = watchForFile(doneSentinelPath, async () => {
- const current = activeAgents.get(agentId);
- if (!current) return;
- current.completedBySentinel = true;
- const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {
- console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);
- return '';
- });
- const { summary } = parseSentinelPayload(contents);
- if (summary) {
- emitToServer('agent:output', {
- agentId,
- text: `${SENTINEL_COMPLETION_MARKER}\n${summary.slice(0, 4096)}\n`,
+ agent.doneWatcher = watchForFile(doneSentinelPath, () => {
+ agent.sentinelWork = lifecycle.trackWork(async () => {
+ const current = activeAgents.get(agentId);
+ if (!current) return;
+ current.completedBySentinel = true;
+ const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {
+ console.error(`❌ TUI agent ${agentId} sentinel read failed: ${err.message}`);
+ return '';
});
- }
- current.process.kill();
+ const { summary } = parseSentinelPayload(contents);
+ if (summary) {
+ emitToServer('agent:output', {
+ agentId,
+ text: `${SENTINEL_COMPLETION_MARKER}\n${summary.slice(0, 4096)}\n`,
+ });
+ }
+ if (!current.exited) current.process.kill();
+ });
+ return agent.sentinelWork;
});
}
@@ -335,7 +376,7 @@ app.post('/spawn-tui', async (req, res) => {
console.log(`📟 Runner-owned TUI ${agentId} started (PID: ${tuiProcess.pid})`);
res.json({ success: true, agentId, sessionId, pid: tuiProcess.pid });
-});
+}));
/**
* Get process stats for a specific agent
@@ -364,7 +405,7 @@ app.get('/agents/:agentId/stats', async (req, res) => {
/**
* Spawn a new agent
*/
-app.post('/spawn', async (req, res) => {
+app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
const {
agentId,
taskId,
@@ -452,6 +493,11 @@ app.post('/spawn', async (req, res) => {
const { args: deliveredArgs, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(command, spawnArgs, prompt, { cwd });
const { command: spawnCommand, args: finalSpawnArgs } = prepareCliSpawn(command, deliveredArgs, childEnv);
+ if (lifecycle.rejectSpawn(res)) {
+ cleanupPromptFile();
+ return;
+ }
+
// Spawn the CLI process
const claudeProcess = spawn(spawnCommand, finalSpawnArgs, {
cwd,
@@ -467,7 +513,7 @@ app.post('/spawn', async (req, res) => {
const codexStderrFormatter = isCodexCli ? createCodexStderrFormatter(prompt) : null;
// Store in memory
- activeAgents.set(agentId, {
+ const agent = {
process: claudeProcess,
taskId,
pid: claudeProcess.pid,
@@ -484,7 +530,8 @@ app.post('/spawn', async (req, res) => {
stripStdoutAnsi: isStreamJson ? (text) => text : createStreamingAnsiStripper(),
stripStderrAnsi: createStreamingAnsiStripper(),
workspacePath: cwd
- });
+ };
+ activeAgents.set(agentId, agent);
// Guard the stdin pipe BEFORE writing: a child that exits before reading it
// (bad flag, missing CLI) emits EPIPE, and an unlistened stream 'error' out
@@ -497,7 +544,6 @@ app.post('/spawn', async (req, res) => {
// Handle stdout
claudeProcess.stdout.on('data', (data) => {
- const agent = activeAgents.get(agentId);
const text = agent?.stripStdoutAnsi ? agent.stripStdoutAnsi(data.toString()) : data.toString();
if (agent?.streamParser) {
@@ -526,7 +572,6 @@ app.post('/spawn', async (req, res) => {
// Handle stderr
claudeProcess.stderr.on('data', (data) => {
- const agent = activeAgents.get(agentId);
const decolored = agent?.stripStderrAnsi ? agent.stripStderrAnsi(data.toString()) : data.toString();
if (agent?.codexStderrFormatter) {
const lines = agent.codexStderrFormatter.processChunk(decolored);
@@ -556,102 +601,84 @@ app.post('/spawn', async (req, res) => {
});
// Handle process exit
- claudeProcess.on('close', async (code) => {
+ claudeProcess.on('close', lifecycle.agentExit(agentId, agent, async (code) => {
cleanupPromptFile();
try {
- const agent = activeAgents.get(agentId);
- // Cancel any pending SIGKILL timer — process already exited.
- if (agent?.killTimer) {
- clearTimeout(agent.killTimer);
- agent.killTimer = null;
- }
- const duration = Date.now() - (agent?.startedAt || Date.now());
-
- // Flush remaining stream parser data
- if (agent?.streamParser) {
- const remaining = agent.streamParser.flush();
- for (const line of remaining) {
- agent.outputBuffer += line + '\n';
- emitToServer('agent:output', { agentId, text: line + '\n' });
+ agent.exited = true;
+ // Cancel any pending SIGKILL timer — process already exited.
+ if (agent?.killTimer) {
+ clearTimeout(agent.killTimer);
+ agent.killTimer = null;
}
- // Use the parsed final result for the output file if available
- const finalResult = agent.streamParser.getFinalResult();
- if (finalResult) {
- agent.outputBuffer = finalResult;
+ const duration = Date.now() - (agent?.startedAt || Date.now());
+
+ // Flush remaining stream parser data
+ if (agent?.streamParser) {
+ const remaining = agent.streamParser.flush();
+ for (const line of remaining) {
+ agent.outputBuffer += line + '\n';
+ emitToServer('agent:output', { agentId, text: line + '\n' });
+ }
+ // Use the parsed final result for the output file if available
+ const finalResult = agent.streamParser.getFinalResult();
+ if (finalResult) {
+ agent.outputBuffer = finalResult;
+ }
}
- }
- if (agent?.codexStderrFormatter) {
- const remaining = agent.codexStderrFormatter.flush();
- for (const line of remaining) {
- agent.outputBuffer += line + '\n';
- emitToServer('agent:output', { agentId, text: line + '\n' });
+ if (agent?.codexStderrFormatter) {
+ const remaining = agent.codexStderrFormatter.flush();
+ for (const line of remaining) {
+ agent.outputBuffer += line + '\n';
+ emitToServer('agent:output', { agentId, text: line + '\n' });
+ }
}
- }
- const output = agent?.outputBuffer || '';
- const paused = agent?.paused === true;
+ const output = agent?.outputBuffer || '';
+ const paused = agent?.paused === true;
+
+ // A non-zero exit is a failure line, so it belongs on stderr where a
+ // stderr-based monitor can see it (#7945). A pause or a clean exit is
+ // ordinary progress and stays on stdout.
+ const logExit = !paused && code !== 0 ? console.error : console.log;
+ logExit(`${paused ? '⏸️' : code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}${paused ? ' after pause' : ''}`);
+
+ // Persist output and terminal evidence before publishing completion or
+ // removing durable ownership. Failed writes leave recovery evidence intact.
+ await persistCompletion(agentId, output, paused ? null : {
+ taskId,
+ completedAt: new Date().toISOString(),
+ exitCode: code,
+ success: code === 0,
+ duration,
+ });
+ if (paused) {
+ activeAgents.delete(agentId);
+ return;
+ }
- // A non-zero exit is a failure line, so it belongs on stderr where a
- // stderr-based monitor can see it (#7945). A pause or a clean exit is
- // ordinary progress and stays on stdout.
- const logExit = !paused && code !== 0 ? console.error : console.log;
- logExit(`${paused ? '⏸️' : code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}${paused ? ' after pause' : ''}`);
+ // Emit completion event
+ emitToServer('agent:completed', {
+ agentId,
+ taskId,
+ exitCode: code,
+ success: code === 0,
+ duration,
+ outputLength: output.length
+ });
- // Save output to agent directory
- const agentDir = join(AGENTS_DIR, agentId);
- if (!existsSync(agentDir)) {
- await ensureDir(agentDir);
- }
- await writeFile(join(agentDir, 'output.txt'), output)
- .catch(err => console.error(`❌ Agent ${agentId} failed to persist output.txt: ${err.message}`));
+ // Update state — serialize with the spawn write path via withState.
+ await withState((state) => {
+ state.stats.completed++;
+ if (code !== 0) state.stats.failed++;
+ delete state.agents[agentId];
+ });
- if (paused) {
activeAgents.delete(agentId);
- return;
- }
-
- // Persist completion status to disk BEFORE emitting event
- // This ensures recovery is possible even if the socket event is lost
- const metadataPath = join(agentDir, 'metadata.json');
- const existingMetadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
- const completionMetadata = {
- ...existingMetadata,
- agentId,
- taskId,
- completedAt: new Date().toISOString(),
- exitCode: code,
- success: code === 0,
- duration,
- outputSize: Buffer.byteLength(output)
- };
- // Recovery-critical: completion metadata is how a restart reconstructs a
- // finished task — never swallow a write failure here, log it.
- await writeFile(metadataPath, JSON.stringify(completionMetadata, null, 2))
- .catch(err => console.error(`❌ Agent ${agentId} failed to persist completion metadata: ${err.message}`));
-
- // Emit completion event
- emitToServer('agent:completed', {
- agentId,
- taskId,
- exitCode: code,
- success: code === 0,
- duration,
- outputLength: output.length
- });
-
- // Update state — serialize with the spawn write path via withState.
- await withState((state) => {
- state.stats.completed++;
- if (code !== 0) state.stats.failed++;
- delete state.agents[agentId];
- });
-
- activeAgents.delete(agentId);
} catch (err) {
- console.error(`❌ Agent ${agentId} close handler error: ${err.message}`);
+ lifecycle.reportFailure(err);
activeAgents.delete(agentId);
}
- });
+ }));
// Update state — use withState to serialize the read-modify-write with the
// close handler's own state update, preventing concurrent mutation of the
@@ -670,7 +697,7 @@ app.post('/spawn', async (req, res) => {
agentId,
pid: claudeProcess.pid
});
-});
+}));
/**
* Terminate an agent (graceful with SIGTERM, then SIGKILL after timeout)
@@ -830,6 +857,10 @@ app.get('/agents/:agentId/output', (req, res) => {
* Socket.IO connection handling
*/
io.on('connection', (socket) => {
+ if (lifecycle.isStopping()) { socket.disconnect(true); return; }
+ socket.use((packet, next) => {
+ if (!lifecycle.isStopping()) next();
+ });
console.log(`🔌 Client connected: ${socket.id}`);
socket.on('tui:input', ({ sessionId, data }) => {
@@ -881,21 +912,21 @@ io.on('connection', (socket) => {
* Emits a batch completion event for dead agents so main server can retry tasks
*/
async function cleanupOrphanedAgents() {
- const state = await loadState();
const orphaned = [];
-
- for (const [agentId, agentInfo] of Object.entries(state.agents)) {
- // Check if process is still running
- const isRunning = await checkProcessRunning(agentInfo.pid);
- if (!isRunning) {
- orphaned.push({ agentId, taskId: agentInfo.taskId });
- delete state.agents[agentId];
+ // Recovery can overlap a signal and finalizers. Keep its entire read/check/
+ // write in the same queue so an old snapshot cannot resurrect completed runs.
+ await withState(async (state) => {
+ for (const [agentId, agentInfo] of Object.entries(state.agents)) {
+ const isRunning = await checkProcessRunning(agentInfo.pid);
+ if (!isRunning) {
+ orphaned.push({ agentId, taskId: agentInfo.taskId });
+ delete state.agents[agentId];
+ }
}
- }
+ });
if (orphaned.length > 0) {
console.log(`🧹 Cleaned up ${orphaned.length} orphaned agents from state`);
- await saveState(state);
// Emit a single batch event with all orphaned agents
// This avoids log spam when many agents were orphaned
@@ -950,7 +981,8 @@ server.listen(PORT, HOST, async () => {
// Log and continue — a corrupt state file must not stop the runner from
// accepting new work, and the sweep re-runs on the next restart.
try {
- const orphaned = await cleanupOrphanedAgents();
+ if (lifecycle.isStopping()) return;
+ const orphaned = await lifecycle.trackWork(cleanupOrphanedAgents);
if (orphaned.length > 0) {
console.log(`🧹 Cleaned ${orphaned.length} orphaned agent(s)`);
}
@@ -959,22 +991,3 @@ server.listen(PORT, HOST, async () => {
}
}, ORPHAN_CLEANUP_DELAY_MS);
});
-
-// Graceful shutdown
-process.on('SIGTERM', async () => {
- console.log('📴 Received SIGTERM, shutting down gracefully...');
-
- // Terminate all agents
- for (const [agentId, agent] of activeAgents) {
- console.log(`🔪 Terminating agent ${agentId}`);
- killProcessTree(agent.process, 'SIGTERM');
- }
-
- // Wait for agents to terminate
- await sleep(SHUTDOWN_DRAIN_MS);
-
- server.close(() => {
- console.log('👋 CoS Agent Runner stopped');
- process.exit(0);
- });
-});
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index 646658711c..4b48e4b045 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -113,7 +113,7 @@ describe('cos-runner termination', () => {
});
it('binds TUI exit handling to the original process record', () => {
- expect(RUNNER_SRC).toContain('tuiProcess.onExit(createTuiExitHandler({');
+ expect(RUNNER_SRC).toContain('tuiProcess.onExit(lifecycle.agentExit(agentId, agent, createTuiExitHandler({');
expect(RUNNER_SRC).toContain('agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState,');
});
});
diff --git a/server/cos-runner/runnerState.js b/server/cos-runner/runnerState.js
index d6995000d3..06e4b72571 100644
--- a/server/cos-runner/runnerState.js
+++ b/server/cos-runner/runnerState.js
@@ -63,3 +63,8 @@ export function withState(mutatorFn) {
});
return stateLock;
}
+
+/** Await queued state writes after spawn and exit producers have drained. */
+export function drainState() {
+ return stateLock;
+}
diff --git a/server/cos-runner/runnerState.test.js b/server/cos-runner/runnerState.test.js
index f72f900938..d8e5eae488 100644
--- a/server/cos-runner/runnerState.test.js
+++ b/server/cos-runner/runnerState.test.js
@@ -57,4 +57,24 @@ describe('cos-runner runnerState', () => {
]);
expect([1, 2]).toContain((await loadState()).stats.spawned);
});
+ it('drains an entire queued mutation, including writes queued behind it', async () => {
+ const { withState, drainState, loadState } = await loadModule();
+ let release;
+ const gate = new Promise(resolve => { release = resolve; });
+ const first = withState(async state => {
+ await gate;
+ state.agents.example = { pid: 123 };
+ });
+ const last = withState(state => { state.stats.completed++; });
+ let drained = false;
+ const drain = drainState().then(() => { drained = true; });
+ await Promise.resolve();
+ expect(drained).toBe(false);
+ release();
+ await Promise.all([first, last, drain]);
+ expect(await loadState()).toMatchObject({
+ agents: { example: { pid: 123 } }, stats: { completed: 1 },
+ });
+ });
+
});
diff --git a/server/cos-runner/shutdown.js b/server/cos-runner/shutdown.js
new file mode 100644
index 0000000000..009ead83af
--- /dev/null
+++ b/server/cos-runner/shutdown.js
@@ -0,0 +1,119 @@
+import { killProcessTree } from '../lib/bufferedSpawn.js';
+import { armForceKill } from './forceKill.js';
+
+// Owns processes until their actual exit AND asynchronous finalization, even
+// when a terminate route has already removed them from the public agent map.
+export function createRunnerShutdown({
+ stopIntake, closeTransports, drainState, exit, logError = console.error,
+ deadlineMs = 25_000, graceMs = 5000,
+}) {
+ const owned = new Set();
+ const pending = new Set();
+ let stopping = false;
+ let failed = false;
+ let shutdownPromise;
+
+ const reportFailure = (err) => {
+ failed = true;
+ logError(`❌ Runner drain failed: ${err.message}`);
+ };
+
+ const trackWork = (work) => {
+ // Invoke synchronously: admission and registration happen before the next
+ // signal can run. Keep a separate settled promise to avoid orphan rejections.
+ const promise = (async () => work())();
+ const settled = promise.then(() => {}, reportFailure).finally(() => pending.delete(settled));
+ pending.add(settled);
+ return promise;
+ };
+
+ const rejectSpawn = (res) => {
+ if (!stopping) return false;
+ res.status(503).json({ error: 'Runner is shutting down', code: 'SHUTTING_DOWN' });
+ return true;
+ };
+
+ const spawnRoute = (handler) => (req, res) => {
+ if (rejectSpawn(res)) return;
+ return trackWork(() => handler(req, res));
+ };
+
+ const agentExit = (agentId, agent, finalize) => {
+ const ownership = { agentId, agent };
+ owned.add(ownership);
+ let finish;
+ const completed = new Promise(resolve => { finish = resolve; });
+ pending.add(completed);
+ let finalization;
+ return (...args) => {
+ if (finalization) return finalization;
+ owned.delete(ownership);
+ if (agent.killTimer) clearTimeout(agent.killTimer);
+ agent.killTimer = null;
+ finalization = trackWork(() => finalize(...args)).catch(() => {}).finally(() => {
+ pending.delete(completed);
+ finish();
+ });
+ return finalization;
+ };
+ };
+
+ const shutdown = () => {
+ if (shutdownPromise) return shutdownPromise;
+ stopping = true;
+ // Establish the hard deadline before calling any dependency. No stalled
+ // preparation, persistence write or upgraded socket can extend it.
+ let timer;
+ const deadline = new Promise(resolve => {
+ timer = setTimeout(() => resolve(false), deadlineMs);
+ });
+ let intake;
+ try {
+ intake = stopIntake(deadlineMs);
+ } catch (err) {
+ reportFailure(err);
+ }
+ for (const { agentId, agent } of owned) {
+ // Arm first so a synchronous exit from a process double can cancel it.
+ armForceKill(new Map([[agentId, agent]]), agentId, agent, { graceMs });
+ try {
+ killProcessTree(agent.process, 'SIGTERM');
+ } catch (err) {
+ reportFailure(err);
+ }
+ }
+ const drain = async () => {
+ while (pending.size) await Promise.all([...pending]);
+ await drainState();
+ await closeTransports();
+ await intake;
+ return !failed;
+ };
+ shutdownPromise = Promise.race([drain().catch(err => {
+ reportFailure(err);
+ return false;
+ }), deadline]).then(clean => {
+ clearTimeout(timer);
+ if (!clean) {
+ logError('❌ Runner shutdown interrupted; preserving unfinished recovery records');
+ // Best effort only: the deadline also bounds Socket.IO's close callback.
+ try {
+ Promise.resolve(closeTransports()).catch(reportFailure);
+ } catch (err) {
+ reportFailure(err);
+ }
+ }
+ exit(clean ? 0 : 1);
+ return clean;
+ });
+ return shutdownPromise;
+ };
+
+ return { isStopping: () => stopping, rejectSpawn, spawnRoute, agentExit, trackWork, reportFailure, shutdown };
+}
+
+export function registerRunnerShutdownSignals(process, lifecycle) {
+ for (const signal of ['SIGINT', 'SIGTERM']) {
+ process.on(signal, () => { void lifecycle.shutdown(); });
+ }
+}
diff --git a/server/cos-runner/shutdown.test.js b/server/cos-runner/shutdown.test.js
new file mode 100644
index 0000000000..88d634c3a2
--- /dev/null
+++ b/server/cos-runner/shutdown.test.js
@@ -0,0 +1,206 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { readFileSync } from 'node:fs';
+import { join, basename } from 'node:path';
+import { runInNewContext } from 'node:vm';
+
+vi.mock('../lib/bufferedSpawn.js', () => ({
+ killProcessTree: vi.fn((child, signal) => child.kill(signal)),
+}));
+import { killProcessTree } from '../lib/bufferedSpawn.js';
+import { createRunnerShutdown, registerRunnerShutdownSignals } from './shutdown.js';
+import { createTuiExitHandler } from './tuiExit.js';
+import { armForceKill } from './forceKill.js';
+import { createHttpDrain } from '../lib/httpDrain.js';
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(r => { resolve = r; });
+ return { promise, resolve };
+};
+
+// Execute the real route/signal wiring with isolated transports, children and
+// storage. No listening port, real child, live PATHS or runner data is touched.
+const source = readFileSync(new URL('./index.js', import.meta.url), 'utf8')
+ .replace(/\r\n/g, '\n').replace(/^import .+ from .+;\n/gm, '');
+
+function runner() {
+ const routes = new Map();
+ const app = { use: vi.fn(), get: vi.fn(), post: (path, handler) => routes.set(path, handler) };
+ const express = Object.assign(() => app, { json: vi.fn() });
+ const server = Object.assign(new EventEmitter(), {
+ listen: vi.fn(), close: vi.fn(cb => cb?.()), closeAllConnections: vi.fn(),
+ });
+ const io = Object.assign(new EventEmitter(), {
+ use: vi.fn(), close: vi.fn(cb => cb?.()),
+ });
+ const process = Object.assign(new EventEmitter(), { env: {}, exit: vi.fn() });
+ const state = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };
+ const files = new Map();
+ const writeFile = vi.fn(async (path, content) => { files.set(path, content); });
+ const withState = vi.fn(async fn => fn(state));
+ const drainState = vi.fn(async () => {});
+ const children = [];
+ const makeChild = () => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 123, stdout: new EventEmitter(), stderr: new EventEmitter(),
+ kill: vi.fn(), write: vi.fn(), resize: vi.fn(),
+ });
+ child.onData = fn => child.on('data', fn);
+ child.onExit = fn => child.on('exit', fn);
+ children.push(child);
+ return child;
+ };
+ const spawn = vi.fn(makeChild);
+ const pty = { spawn: vi.fn(makeChild) };
+ const commandExists = vi.fn(async () => true);
+ runInNewContext(source, {
+ express, http: { createServer: () => server }, SocketServer: function () { return io; },
+ process, console, Buffer, Date, setTimeout, clearTimeout, join, basename,
+ PATHS: { root: '/example', cosAgents: '/example/agents' }, PORTS: { COS: 0 },
+ setupProcessErrorHandlers: vi.fn(), existsSync: () => true, ensureDir: async () => {},
+ readFile: async path => files.get(path) ?? '{}', writeFile, withState, drainState,
+ createRunnerShutdown, registerRunnerShutdownSignals, createTuiExitHandler, createHttpDrain,
+ armForceKillShared: armForceKill, killProcessTree, spawn, pty,
+ buildCliChildEnv: () => ({}), prepareCliSpawn: (command, args) => ({ command, args }),
+ prepareCliPrompt: (command, args) => ({ args, useStdin: false, cleanup: vi.fn() }),
+ commandExists, findCommandOnPath: command => command,
+ isAllowedCommand: () => true, ALLOWED_COMMANDS: ['example-cli'],
+ guardChildStdin: vi.fn(), deliverChildStdin: vi.fn(),
+ createStreamingAnsiStripper: () => text => text, isKnownCliStderrNoise: () => false,
+ });
+ const request = (path, extra = {}) => {
+ const res = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json: vi.fn() };
+ const done = routes.get(path)({ body: {
+ agentId: 'agent-1', taskId: 'task-1', prompt: 'example', cliCommand: 'example-cli',
+ command: 'example-cli', ...extra,
+ } }, res);
+ return { res, done };
+ };
+ return { request, process, server, io, state, files, children, spawn, pty, commandExists, writeFile, withState, drainState };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
+
+describe('runner shutdown through its real spawn and signal handlers', () => {
+ it.each(['SIGINT', 'SIGTERM'])('%s drains CLI output, completion and state exactly once', async signal => {
+ const run = runner();
+ await run.request('/spawn').done;
+ const child = run.children[0];
+ child.stdout.emit('data', Buffer.from('final output'));
+ const write = deferred();
+ run.writeFile.mockImplementationOnce(async (path, output) => {
+ await write.promise;
+ run.files.set(path, output);
+ });
+ run.process.emit(signal);
+ run.process.emit(signal === 'SIGINT' ? 'SIGTERM' : 'SIGINT');
+ expect(run.server.close).toHaveBeenCalledTimes(1);
+ expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGTERM');
+ child.emit('close', 0);
+ child.emit('close', 0);
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(run.process.exit).not.toHaveBeenCalled();
+ expect(run.io.close).not.toHaveBeenCalled();
+ write.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.files.get(join('/example/agents', 'agent-1', 'output.txt'))).toBe('final output');
+ expect(JSON.parse(run.files.get(join('/example/agents', 'agent-1', 'metadata.json')))).toMatchObject({ success: true, exitCode: 0 });
+ expect(run.state).toEqual({ agents: {}, stats: { spawned: 1, completed: 1, failed: 0 } });
+ expect(run.process.exit).toHaveBeenCalledExactlyOnceWith(0);
+ expect(run.io.close).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects both new spawn routes and a TUI whose preparation resumes after shutdown', async () => {
+ const run = runner();
+ const probe = deferred();
+ run.commandExists.mockReturnValueOnce(probe.promise);
+ const preparing = run.request('/spawn-tui');
+ run.process.emit('SIGINT');
+ for (const route of ['/spawn', '/spawn-tui']) {
+ const refused = run.request(route);
+ await refused.done;
+ expect(refused.res.statusCode).toBe(503);
+ }
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(run.process.exit).not.toHaveBeenCalled();
+ probe.resolve(true);
+ await preparing.done;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(preparing.res.statusCode).toBe(503);
+ expect(run.spawn).not.toHaveBeenCalled();
+ expect(run.pty.spawn).not.toHaveBeenCalled();
+ expect(run.process.exit).toHaveBeenCalledExactlyOnceWith(0);
+ });
+
+ it('escalates a resistant TUI and waits for its terminal evidence and final state write', async () => {
+ const run = runner();
+ await run.request('/spawn-tui').done;
+ const child = run.children[0];
+ child.emit('data', 'terminal tail');
+ const write = deferred();
+ run.withState.mockImplementationOnce(async fn => { await write.promise; fn(run.state); });
+ run.process.emit('SIGTERM');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);
+ child.emit('exit', { exitCode: 1, signal: 9 });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.files.get(join('/example/agents', 'agent-1', 'output.txt'))).toBe('terminal tail');
+ expect(JSON.parse(run.files.get(join('/example/agents', 'agent-1', 'metadata.json')))).toMatchObject({ success: false, signal: 9 });
+ expect(run.process.exit).not.toHaveBeenCalled();
+ write.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.state.stats).toEqual({ spawned: 1, completed: 1, failed: 1 });
+ expect(run.process.exit).toHaveBeenCalledExactlyOnceWith(0);
+ });
+
+ it.each(['child', 'write', 'socket'])('bounds stalled %s completion and preserves unfinished evidence', async stalled => {
+ const run = runner();
+ await run.request('/spawn').done;
+ if (stalled === 'write') run.writeFile.mockReturnValueOnce(new Promise(() => {}));
+ if (stalled === 'socket') run.io.close.mockImplementation(() => {});
+ run.process.exit.mockImplementation(() => { expect(run.io.close).toHaveBeenCalled(); });
+ run.process.emit('SIGTERM');
+ if (stalled !== 'child') run.children[0].emit('close', 0);
+ await vi.advanceTimersByTimeAsync(24_999);
+ expect(run.process.exit).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(run.process.exit).toHaveBeenCalledExactlyOnceWith(1);
+ expect(run.io.close).toHaveBeenCalledTimes(1);
+ if (stalled !== 'socket') {
+ expect(run.state.agents['agent-1']).toBeDefined();
+ expect(run.state.stats.completed).toBe(0);
+ expect(run.files.has(join('/example/agents', 'agent-1', 'metadata.json'))).toBe(false);
+ }
+ });
+
+ it('reports a persistence failure without deleting the durable agent record', async () => {
+ const run = runner();
+ await run.request('/spawn').done;
+ run.writeFile.mockRejectedValueOnce(new Error('disk unavailable'));
+ run.process.emit('SIGTERM');
+ run.children[0].emit('close', 0);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.process.exit).toHaveBeenCalledExactlyOnceWith(1);
+ expect(run.state.agents['agent-1']).toBeDefined();
+ expect(run.state.stats.completed).toBe(0);
+ });
+
+ it('does not stop children when only the main-server socket disconnects', async () => {
+ const run = runner();
+ await run.request('/spawn-tui').done;
+ const socket = Object.assign(new EventEmitter(), { use: vi.fn(), id: 'example-client' });
+ run.io.emit('connection', socket);
+ socket.emit('disconnect');
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(run.children[0].kill).not.toHaveBeenCalled();
+ expect(run.process.exit).not.toHaveBeenCalled();
+ expect(run.state.agents['agent-1']).toBeDefined();
+ });
+});
diff --git a/server/cos-runner/tuiExit.js b/server/cos-runner/tuiExit.js
index 1b5e01936f..3b59bdbae1 100644
--- a/server/cos-runner/tuiExit.js
+++ b/server/cos-runner/tuiExit.js
@@ -6,7 +6,7 @@
// buffer and is enough to carry a CLI's startup diagnostic.
const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;
-export function createTuiExitHandler({ agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState }) {
+export function createTuiExitHandler({ agentId, taskId, sessionId, agent, activeAgents, io, emitToServer, withState, persistCompletion, onError }) {
return async ({ exitCode, signal }) => {
try {
// The force-kill timer removes the registry entry before node-pty emits
@@ -25,11 +25,18 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
clearTimeout(current.killTimer);
current.killTimer = null;
}
+ // A sentinel read already in flight owns its completion output too.
+ await current.sentinelWork;
const duration = Date.now() - current.startedAt;
const success = current.completedBySentinel;
const effectiveExitCode = success ? 0 : exitCode;
const effectiveSignal = success ? 0 : signal;
const outputTail = current.outputBuffer.slice(-TUI_EXIT_OUTPUT_TAIL_CHARS);
+ await persistCompletion(agentId, current.outputBuffer, current.paused ? null : {
+ taskId, completedAt: new Date().toISOString(), exitCode: effectiveExitCode,
+ signal: effectiveSignal, success: !!success, duration,
+ completionReason: success ? 'agent-signaled-done' : 'tui-exit',
+ });
io.emit('tui:exit', {
sessionId,
agentId,
@@ -58,6 +65,7 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
} catch (err) {
console.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);
activeAgents.delete(agentId);
+ onError?.(err);
}
};
}
diff --git a/server/cos-runner/tuiExit.test.js b/server/cos-runner/tuiExit.test.js
index e0b41253f1..d1d3fccafc 100644
--- a/server/cos-runner/tuiExit.test.js
+++ b/server/cos-runner/tuiExit.test.js
@@ -17,7 +17,7 @@ function setup(extra = {}) {
const withState = vi.fn(async fn => fn(state));
const onExit = createTuiExitHandler({
agentId: 'agent-old', taskId: 'task-1', sessionId: 'session-1',
- agent, activeAgents, io, emitToServer, withState,
+ agent, activeAgents, io, emitToServer, withState, persistCompletion: vi.fn().mockResolvedValue(),
});
return { agent, activeAgents, state, io, emitToServer, withState, onExit };
}