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: close the pause and stale-timer holes the kill fix exposed

[._.]/ Adam Eivy78410b3bb051
diff --git a/server/cos-runner/forceKill.js b/server/cos-runner/forceKill.js
new file mode 100644
index 0000000000..167b2aebf8
--- /dev/null
+++ b/server/cos-runner/forceKill.js
@@ -0,0 +1,57 @@
+/**
+ * The runner's SIGTERM → grace → SIGKILL escalation.
+ *
+ * Every termination path in `index.js` is graceful-then-forced: `killProcessTree`
+ * decides what "kill" means for the agent's handle (a `taskkill /T /F` tree for a
+ * cmd.exe-wrapped CLI shim, #2243; a signal-free node-pty kill on Windows), and
+ * this is the grace window after it.
+ *
+ * Lives in its own module because `index.js` binds a socket server at import and
+ * can only be inspected as source text — and the stale-timer bug below was
+ * invisible to exactly that kind of test.
+ */
+
+import { killProcessTree } from '../lib/bufferedSpawn.js';
+
+/**
+ * Arm the force-kill escalation for an agent that was just signalled.
+ *
+ * Dropping the map entry when the grace expires is what keeps `GET /agents`
+ * honest: a process that outlives its own SIGKILL must not go on being
+ * advertised as an active run, or the PortOS server re-adopts it on every orphan
+ * sweep and counts it against the Update page's "N CoS agents running" gate.
+ *
+ * **A fresh termination always re-arms**, replacing any timer already on the
+ * agent. Refusing to arm because `killTimer` was truthy would let a *spent*
+ * timer — `/pause` leaves its own behind, and it neither clears the handle nor
+ * removes the map entry — swallow the escalation for a later `/terminate`,
+ * stranding the very phantom this exists to reap. The callback clears the handle
+ * so a settled timer never looks armed.
+ *
+ * `dropState` also clears the durable runner record. It belongs only to a kill
+ * relayed for an agent the PortOS server has ALREADY finalized, where nothing
+ * will ever revisit either copy — never to a paused agent, whose record is what
+ * a later resume reads.
+ *
+ * @param {Map<string, object>} activeAgents - the runner's live-agent map
+ * @param {string} agentId
+ * @param {object} agent - the map entry (its `process` is the killable)
+ * @param {{ graceMs: number, dropState?: boolean, onDropState?: (agentId: string) => void }} opts
+ */
+export function armForceKill(activeAgents, agentId, agent, { graceMs, dropState = false, onDropState } = {}) {
+ if (agent.killTimer) clearTimeout(agent.killTimer);
+ agent.killTimer = setTimeout(() => {
+ // Timer callback: an uncaught throw here has no request to bubble to and
+ // would take the whole runner down.
+ try {
+ agent.killTimer = null;
+ if (!activeAgents.delete(agentId)) return;
+ console.log(`💀 Agent ${agentId} outlived its termination grace — force killing`);
+ killProcessTree(agent.process, 'SIGKILL');
+ if (dropState) onDropState?.(agentId);
+ } catch (err) {
+ console.error(`❌ Force kill failed for ${agentId}: ${err.message}`);
+ }
+ }, graceMs);
+ return agent.killTimer;
+}
diff --git a/server/cos-runner/forceKill.test.js b/server/cos-runner/forceKill.test.js
new file mode 100644
index 0000000000..732ff3c9f5
--- /dev/null
+++ b/server/cos-runner/forceKill.test.js
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const { killProcessTree } = vi.hoisted(() => ({ killProcessTree: vi.fn() }));
+vi.mock('../lib/bufferedSpawn.js', () => ({ killProcessTree }));
+
+import { armForceKill } from './forceKill.js';
+
+const GRACE = 5000;
+
+describe('armForceKill', () => {
+ let activeAgents;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ activeAgents = new Map();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterEach(() => vi.useRealTimers());
+
+ const addAgent = (id, extra = {}) => {
+ const agent = { process: { kill: vi.fn() }, ...extra };
+ activeAgents.set(id, agent);
+ return agent;
+ };
+
+ it('force-kills and drops the agent when it outlives the grace window', () => {
+ const agent = addAgent('agent-1');
+ armForceKill(activeAgents, 'agent-1', agent, { graceMs: GRACE });
+
+ expect(activeAgents.has('agent-1')).toBe(true);
+ vi.advanceTimersByTime(GRACE);
+
+ expect(killProcessTree).toHaveBeenCalledWith(agent.process, 'SIGKILL');
+ // The drop is the load-bearing half: an entry the runner keeps advertising
+ // in GET /agents is re-adopted by the PortOS server on every orphan sweep
+ // and counts against the Update page's "N CoS agents running" gate.
+ expect(activeAgents.has('agent-1')).toBe(false);
+ });
+
+ // The regression: refusing to arm because `killTimer` was truthy let a SPENT
+ // timer swallow a later termination. /pause leaves one behind that neither
+ // clears the handle nor removes the entry, so a subsequent /terminate on that
+ // agent never escalated and never dropped it — stranding the exact phantom
+ // this escalation exists to reap.
+ it('re-arms over a stale timer left by an earlier pause', () => {
+ const agent = addAgent('agent-1', { paused: true });
+ // Stand in for /pause's own timer: it only SIGKILLs, never drops the entry.
+ agent.killTimer = setTimeout(() => {}, GRACE);
+
+ armForceKill(activeAgents, 'agent-1', agent, { graceMs: GRACE });
+ vi.advanceTimersByTime(GRACE);
+
+ expect(killProcessTree).toHaveBeenCalledWith(agent.process, 'SIGKILL');
+ expect(activeAgents.has('agent-1')).toBe(false);
+ });
+
+ it('clears the handle when it fires, so a settled timer never reads as armed', () => {
+ const agent = addAgent('agent-1');
+ armForceKill(activeAgents, 'agent-1', agent, { graceMs: GRACE });
+ expect(agent.killTimer).not.toBeNull();
+
+ vi.advanceTimersByTime(GRACE);
+
+ expect(agent.killTimer).toBeNull();
+ });
+
+ it('does nothing when the agent already exited and was removed', () => {
+ const agent = addAgent('agent-1');
+ armForceKill(activeAgents, 'agent-1', agent, { graceMs: GRACE });
+ activeAgents.delete('agent-1'); // a clean exit, or /kill, got there first
+
+ vi.advanceTimersByTime(GRACE);
+
+ expect(killProcessTree).not.toHaveBeenCalled();
+ });
+
+ // `dropState` clears the DURABLE runner record, which a resume reads. It is
+ // only ever right for a kill relayed after the server already finalized the
+ // agent — never for a pause.
+ it('clears the durable record only when dropState is set', () => {
+ const onDropState = vi.fn();
+ const kept = addAgent('agent-keep');
+ armForceKill(activeAgents, 'agent-keep', kept, { graceMs: GRACE, onDropState });
+ vi.advanceTimersByTime(GRACE);
+ expect(onDropState).not.toHaveBeenCalled();
+
+ const dropped = addAgent('agent-drop');
+ armForceKill(activeAgents, 'agent-drop', dropped, { graceMs: GRACE, dropState: true, onDropState });
+ vi.advanceTimersByTime(GRACE);
+ expect(onDropState).toHaveBeenCalledWith('agent-drop');
+ });
+
+ // The callback runs on a timer, outside any request: an uncaught throw would
+ // take the whole runner process down.
+ it('survives a throwing kill rather than crashing the runner', () => {
+ const agent = addAgent('agent-1');
+ killProcessTree.mockImplementationOnce(() => { throw new Error('handle already disposed'); });
+
+ armForceKill(activeAgents, 'agent-1', agent, { graceMs: GRACE });
+ expect(() => vi.advanceTimersByTime(GRACE)).not.toThrow();
+ expect(activeAgents.has('agent-1')).toBe(false);
+ });
+});
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 415d18cae0..609760305e 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -27,6 +27,7 @@ import { createStreamJsonParser } from './streamJsonParser.js';
import { loadState, saveState, withState } from './runnerState.js';
import { getProcessStats, checkProcessRunning } from './processStats.js';
import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';
+import { armForceKill as armForceKillShared } from './forceKill.js';
import { PORTS } from '../lib/ports.js';
import { setupProcessErrorHandlers } from '../lib/errorHandler.js';
import { parseSentinelPayload } from '../lib/agentSentinel.js';
@@ -77,41 +78,19 @@ const activeAgents = new Map();
const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;
const TUI_SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT']);
-/**
- * Arm the force-kill escalation for an agent that was just signalled.
- *
- * Every termination path here is SIGTERM-then-SIGKILL: `killProcessTree` sorts
- * out what "kill" means for the agent's kind (a `taskkill /T /F` tree for a
- * cmd.exe-wrapped CLI shim, #2243; a signal-free node-pty kill on Windows), and
- * this is the grace window after it. Dropping the map entry when the grace
- * expires is what keeps `GET /agents` honest: a process that outlives its own
- * SIGKILL must not go on being advertised as an active run, or the PortOS
- * server re-adopts it on every orphan sweep and counts it against the Update
- * page's "N CoS agents running" gate.
- *
- * The handle is stored on the agent so an exit handler can cancel it.
- * `dropState` also clears the durable runner record — used by the `tui:kill`
- * relay, whose kill arrives after the server has ALREADY finalized the agent, so
- * nothing else will ever revisit either copy.
- */
-function armForceKill(agentId, agent, { dropState = false } = {}) {
- if (agent.killTimer) return;
- agent.killTimer = setTimeout(() => {
- // Timer callback: an uncaught throw here has no request to bubble to and
- // would take the whole runner down.
- try {
- if (!activeAgents.delete(agentId)) return;
- console.log(`💀 Agent ${agentId} outlived its termination grace — force killing`);
- killProcessTree(agent.process, 'SIGKILL');
- if (dropState) {
- withState((state) => { delete state.agents[agentId]; })
- .catch(err => console.error(`❌ Reap state write failed for ${agentId}: ${err.message}`));
- }
- } catch (err) {
- console.error(`❌ Force kill failed for ${agentId}: ${err.message}`);
- }
- }, SIGKILL_GRACE_MS);
-}
+// Bind the shared escalation to this process's map, grace window, and durable
+// state. See forceKill.js for the contract (notably: a fresh termination always
+// re-arms, and `dropState` is only for a kill relayed after the PortOS server
+// has already finalized the agent).
+const armForceKill = (agentId, agent, opts = {}) =>
+ armForceKillShared(activeAgents, agentId, agent, {
+ graceMs: SIGKILL_GRACE_MS,
+ ...opts,
+ onDropState: (id) => {
+ withState((state) => { delete state.agents[id]; })
+ .catch(err => console.error(`❌ Reap state write failed for ${id}: ${err.message}`));
+ },
+ });
// Express app setup
const app = express();
@@ -281,7 +260,21 @@ app.post('/spawn-tui', async (req, res) => {
if (!current) return;
current.doneWatcher?.();
// Cancel any pending SIGKILL timer — process already exited.
- if (current.killTimer) clearTimeout(current.killTimer);
+ if (current.killTimer) {
+ clearTimeout(current.killTimer);
+ current.killTimer = null;
+ }
+ // A paused agent's process was stopped deliberately and its record is what
+ // a later resume reads, so report nothing: emitting `agent:completed` here
+ // would finalize it as FAILED and retire the task the pause meant to keep.
+ // Mirrors the CLI close handler's own pause guard below. This became
+ // reachable when the node-pty kill started landing on Windows — before
+ // that, pausing a runner-owned TUI threw and the PTY simply never exited.
+ if (current.paused === true) {
+ console.log(`⏸️ TUI agent ${agentId} exited after pause`);
+ activeAgents.delete(agentId);
+ return;
+ }
const duration = Date.now() - current.startedAt;
const success = current.completedBySentinel;
const effectiveExitCode = success ? 0 : exitCode;
@@ -723,6 +716,7 @@ app.post('/pause/:agentId', async (req, res) => {
// NOT armForceKill: a pause keeps its map entry (the agent is meant to be
// resumable) and only escalates while the pause is still in force.
agent.killTimer = setTimeout(() => {
+ agent.killTimer = null;
const current = activeAgents.get(agentId);
if (current?.paused) killProcessTree(current.process, 'SIGKILL');
}, SIGKILL_GRACE_MS);
@@ -840,7 +834,11 @@ io.on('connection', (socket) => {
const [agentId, agent] = entry;
if (agent.kind !== 'tui') return;
killProcessTree(agent.process, signal);
- armForceKill(agentId, agent, { dropState: true });
+ // `dropState` only for an agent the server has already FINALIZED. A pause
+ // also relays a kill (the server stops a TUI session through this socket),
+ // and its durable record is exactly what a later resume reads — reaping it
+ // would strand the paused run.
+ armForceKill(agentId, agent, { dropState: agent.paused !== true });
} catch (err) {
console.error(`❌ TUI termination relay failed: ${err.message}`);
}
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index 7855ba732d..2d15dd9d25 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -72,34 +72,38 @@ describe('cos-runner spawn — per-provider prompt delivery (antigravity --print
});
describe('cos-runner termination', () => {
- // How to kill an agent is the shared helper's job, not the runner's: a
- // `taskkill /T /F` tree for a cmd.exe-wrapped CLI shim (#2243) and a
- // signal-free node-pty kill on Windows, both decided by `instanceof
- // ChildProcess` inside killProcessTree. bufferedSpawn.test.js owns those
- // semantics; this file's job is that no path here hand-rolls its own kill.
+ // Both halves of a kill now live in modules that can actually be imported:
+ // killProcessTree (bufferedSpawn.js) decides what "kill" means for the
+ // handle, and armForceKill (forceKill.js) owns the SIGTERM -> grace ->
+ // SIGKILL escalation. bufferedSpawn.test.js and forceKill.test.js exercise
+ // those for real; all this file pins is that index.js delegates to both
+ // rather than hand-rolling either.
it('kills only through the shared killProcessTree helper', () => {
expect(RUNNER_SRC).toContain("import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';");
- // No path may signal a handle itself. (A BARE `.kill()` is still fine —
- // the sentinel watcher closes a finished TUI session that way, and a bare
- // kill is the one form node-pty accepts on every platform.)
+ // A BARE `.kill()` is still fine — the sentinel watcher closes a finished
+ // TUI session that way, and a bare kill is the one form node-pty accepts
+ // on every platform. What must not reappear is a hand-rolled signal kill.
expect(RUNNER_SRC).not.toContain(".process.kill('SIG");
});
- // Every terminate path is SIGTERM-then-SIGKILL, and the escalation must drop
- // the map entry: a process that outlives its own SIGKILL can't stay in
- // GET /agents, or the PortOS server re-adopts it on each orphan sweep and
- // counts it against the Update page's "N CoS agents running" gate.
- it('escalates through one shared force-kill that drops the agent from the active set', () => {
- const helperIdx = RUNNER_SRC.indexOf('function armForceKill(');
- expect(helperIdx, 'armForceKill must exist').toBeGreaterThan(-1);
- const helper = RUNNER_SRC.slice(helperIdx, helperIdx + 900);
- expect(helper).toContain('activeAgents.delete(agentId)');
- expect(helper).toContain("killProcessTree(agent.process, 'SIGKILL')");
- expect(helper).toContain('SIGKILL_GRACE_MS');
- // /terminate, /terminate-all and the post-finalize tui:kill relay all use
- // it; only the relay also clears the durable runner record.
+ it('escalates through the shared armForceKill on every terminate path', () => {
+ expect(RUNNER_SRC).toContain("import { armForceKill as armForceKillShared } from './forceKill.js';");
+ // /terminate and /terminate-all, plus the post-finalize tui:kill relay.
expect(RUNNER_SRC.split('armForceKill(agentId, agent);')).toHaveLength(3);
- expect(RUNNER_SRC).toContain('armForceKill(agentId, agent, { dropState: true })');
+ expect(RUNNER_SRC).toContain('armForceKill(agentId, agent, { dropState: agent.paused !== true })');
+ });
+
+ // A paused agent was stopped deliberately and its record is what a later
+ // resume reads. The CLI close handler always had this guard; the TUI one did
+ // not, and the node-pty kill fix is what made that path reachable on Windows
+ // (before it, the kill threw and the PTY never exited at all).
+ it('reports nothing when a paused TUI exits, instead of finalizing it failed', () => {
+ const exitIdx = RUNNER_SRC.indexOf('tuiProcess.onExit(');
+ expect(exitIdx, 'the TUI exit handler must exist').toBeGreaterThan(-1);
+ const completedIdx = RUNNER_SRC.indexOf("emitToServer('agent:completed'", exitIdx);
+ const handler = RUNNER_SRC.slice(exitIdx, completedIdx);
+ expect(handler).toContain('current.paused === true');
+ expect(handler).toContain('activeAgents.delete(agentId)');
});
});
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index b9fcec0667..17648359ff 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -119,11 +119,14 @@ function escapeCmdMetacharsIfUnquoted(value) {
// via the host's registerActiveRun) — it also exposes `.kill()`/`.pid`, but
// a raw `taskkill` against its pid bypasses node-pty's own Windows teardown
// (releasing its native ConPTY handle), leaking it. Any non-ChildProcess
-// killable always uses its own `.kill()` instead, on every platform — and with
-// NO signal on Windows, where node-pty throws `Signals not supported on
-// windows.` for any signal argument. Passing one there never killed the pty; it
-// threw past this function, so stopping a TUI run silently left it running. A
-// bare kill() still tears down node-pty's whole console process list.
+// killable always uses its own `.kill()` instead, on every platform.
+//
+// On Windows node-pty additionally throws `Signals not supported on windows.`
+// for any signal argument — so a signalled kill there killed nothing and threw
+// past this function, and stopping a TUI run silently left it running. The
+// signal is therefore offered first and the signal-free form used only for a
+// handle that refuses it (retrying is harmless — the first attempt did nothing);
+// dropping it unconditionally would downgrade other signal-forwarding killables.
// Mirrors server/lib/bufferedSpawn.js (this directory stays self-contained).
function killProcessTree(child) {
const isChildProcess = child instanceof ChildProcess;
@@ -133,7 +136,8 @@ function killProcessTree(child) {
.on('error', () => {})
.unref();
} else if (IS_WIN32 && !isChildProcess) {
- child.kill();
+ try { child.kill('SIGTERM'); }
+ catch { child.kill(); }
} else {
child.kill('SIGTERM');
}
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index c0c5753131..a933bcd6e7 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -215,18 +215,26 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;
* ConPTY handle), leaking it — so any non-ChildProcess killable always uses
* its own `.kill()` instead, on every platform.
*
- * That killable gets NO signal on Windows: node-pty's Windows backend throws
- * `Signals not supported on windows.` for any signal argument, so `kill(signal)`
- * against a pty there never kills anything — it throws past the caller, which
- * typically logs it and moves on while the PTY keeps running. A bare `kill()`
- * still tears down node-pty's whole console process list, so the graceful/forced
- * distinction is simply not expressible for a Windows pty. This is why every CoS
- * Runner TUI kill (terminate, force-kill, pause, and the server's post-finalize
- * relay) was a silent no-op on Windows: the codex/claude PTY survived, held its
- * worktree locked, and stayed in the runner's active set — which the PortOS
- * server re-adopted on every orphan sweep and counted against the Update page's
+ * node-pty's Windows backend additionally throws `Signals not supported on
+ * windows.` for ANY signal argument, so `kill(signal)` against a pty there never
+ * kills anything — it throws past the caller, which typically logs it and moves
+ * on while the PTY keeps running. That is why every CoS Runner TUI kill
+ * (terminate, force-kill, pause, and the server's post-finalize relay) was a
+ * silent no-op on Windows: the codex/claude PTY survived, held its worktree
+ * locked, and stayed in the runner's active set — which the PortOS server
+ * re-adopted on every orphan sweep and counted against the Update page's
* "N CoS agents running" gate, pausing updates indefinitely.
*
+ * So a non-ChildProcess killable is offered the caller's signal FIRST and falls
+ * back to a bare `kill()` only when the handle rejects it. Dropping the signal
+ * unconditionally would be wrong for the other non-ChildProcess killables in
+ * this codebase, which do accept one and forward it — `cosRunnerClient`'s TUI
+ * proxy relays `{ signal }` over a socket, so an unconditional drop would
+ * silently downgrade a force-kill to a graceful one. A bare `kill()` still tears
+ * down node-pty's whole console process list, so nothing is lost where the
+ * fallback does fire: the graceful/forced distinction simply is not expressible
+ * for a Windows pty.
+ *
* `processGroup` is for a child spawned `detached` on POSIX: without it the
* non-Windows branch signals a single pid, which leaves a shell's own children
* (the uv / pip / git an installer script shells out to) running. With it the
@@ -246,10 +254,11 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;
* @param {import('child_process').ChildProcess} child
* @param {NodeJS.Signals} [signal] - POSIX signal to send (default `SIGTERM`); ignored on Windows
* @param {{processGroup?: boolean}} [opts] - POSIX: signal the child's process group (it must have been spawned `detached`)
+ * @param {boolean} [isWin32] - platform override, injected so the Windows branches are testable off Windows (same shape as `resolveWindowsExecutable`)
*/
-export function killProcessTree(child, signal = 'SIGTERM', { processGroup = false } = {}) {
+export function killProcessTree(child, signal = 'SIGTERM', { processGroup = false } = {}, isWin32 = IS_WIN32) {
const isChildProcess = child instanceof ChildProcess;
- if (IS_WIN32 && child.pid && isChildProcess) {
+ if (isWin32 && child.pid && isChildProcess) {
child.killed = true;
spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' })
.on('error', () => {})
@@ -260,8 +269,15 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = fals
try { process.kill(-child.pid, signal); return; }
catch { /* ESRCH — the group is already gone; fall through to the pid */ }
}
- // A Windows pty rejects every signal — see the note above.
- if (IS_WIN32 && !isChildProcess) return child.kill();
+ if (isWin32 && !isChildProcess) {
+ // node-pty rejects the signal outright on Windows (see the note above);
+ // every other killable here accepts and forwards it, so ask first and only
+ // fall back to the signal-free form for the handle that refuses. Retrying a
+ // kill is harmless — the first attempt did nothing.
+ try { child.kill(signal); }
+ catch { child.kill(); }
+ return;
+ }
child.kill(signal);
}
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index 88fe9c5854..25fcd759cc 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -148,6 +148,58 @@ describe('killProcessTree', () => {
killSpy.mockRestore();
});
+ // A killable that exposes .kill()/.pid like a ChildProcess but isn't one
+ // (node-pty's IPty, registered via registerExternalRun for TUI runs). taskkill
+ // against its pid would bypass node-pty's own native teardown (releasing a
+ // Windows ConPTY handle) and leak it.
+ //
+ // The platform is INJECTED on these, not read from the host: the branch below
+ // is Windows-only, and a `if (!IS_WIN32) return` guard would assert nothing on
+ // a Linux CI runner — leaving the fix free to regress everywhere but a
+ // developer's Windows box.
+ const ptyLike = (onSignal) => ({ pid: 4321, kill: vi.fn(onSignal) });
+ // node-pty's Windows backend throws for ANY signal argument. A signalled kill
+ // there therefore killed nothing and threw past the caller, which logged it
+ // and moved on — which is how every CoS Runner TUI kill became a silent no-op
+ // on Windows, stranding the process and pinning the Update page on
+ // "N CoS agents running".
+ const rejectsSignals = (signal) => { if (signal) throw new Error('Signals not supported on windows.'); };
+
+ it('falls back to a signal-free kill on Windows for a handle that rejects signals', () => {
+ const pty = ptyLike(rejectsSignals);
+ killProcessTree(pty, 'SIGKILL', {}, true);
+ expect(pty.kill.mock.calls).toEqual([['SIGKILL'], []]);
+ // Never taskkill — that bypasses node-pty's ConPTY teardown and leaks the handle.
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('keeps the signal on Windows for a non-ChildProcess killable that accepts one', () => {
+ // cosRunnerClient's TUI proxy relays { signal } over a socket. Dropping the
+ // signal unconditionally would silently downgrade a force-kill to graceful.
+ const proxy = ptyLike(undefined);
+ killProcessTree(proxy, 'SIGKILL', {}, true);
+ expect(proxy.kill.mock.calls).toEqual([['SIGKILL']]);
+ });
+
+ it('forwards the signal to a node-pty handle off Windows, where node-pty honors it', () => {
+ const pty = ptyLike(undefined);
+ killProcessTree(pty, 'SIGKILL', {}, false);
+ expect(pty.kill.mock.calls).toEqual([['SIGKILL']]);
+ });
+
+ it('on Windows ignores processGroup — taskkill /T is already the tree', () => {
+ if (!IS_WIN32) return; // platform-gated behavior
+ const child = makeFakeChild({ pid: 777 });
+ const tk = makeFakeChild();
+ tk.unref = vi.fn();
+ spawnMock.mockReturnValueOnce(tk);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ killProcessTree(child, undefined, { processGroup: true });
+ expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/T', '/F', '/PID', '777'], expect.anything());
+ expect(killSpy).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
it('on Windows kills a non-ChildProcess killable (a node-pty session) with .kill() and NO signal', () => {
if (!IS_WIN32) return; // can't simulate platform branch from outside
// A killable that exposes .kill()/.pid like a ChildProcess but isn't one
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index a9fe2b05dd..1a1509165c 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -73,16 +73,15 @@ vi.mock('./agentRunTracking.js', () => ({
// The DEFINING module, not the `cosAgentLifecycle.js` module — mirrors the production
// import (#3450). Mocking the barrel here would silently stop applying and let
// the real state layer load.
-const { AGENT_RECORD_UNREADABLE } = vi.hoisted(() => ({
- AGENT_RECORD_UNREADABLE: Symbol('agent-record-unreadable'),
-}));
-vi.mock('./cosAgentLifecycle.js', () => ({
+// `isLiveAgentRecord` and the sentinel come from the real module — the reverse
+// prune turns on that predicate, so a re-implemented copy here would keep
+// passing while the real one changed underneath it.
+vi.mock('./cosAgentLifecycle.js', async (importOriginal) => ({
+ ...(await importOriginal()),
completeAgent: vi.fn().mockResolvedValue(undefined),
updateAgent: vi.fn().mockResolvedValue(undefined),
getAgents: vi.fn().mockResolvedValue([]),
getAgentRecord: vi.fn().mockResolvedValue(null),
- AGENT_RECORD_UNREADABLE,
- isLiveAgentRecord: (record) => Boolean(record) && record.status !== 'completed',
readAgentRecordOrUnreadable: vi.fn().mockResolvedValue(null),
}));
vi.mock('./cosRunnerClient.js', () => ({
@@ -119,7 +118,7 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettle
import { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
-import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
+import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
import { updateRun, getProject } from './creativeDirector/local.js';
import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';
import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';
diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.js
index 0402f516d4..d3b79167ef 100644
--- a/server/services/agentRunnerSync.test.js
+++ b/server/services/agentRunnerSync.test.js
@@ -30,14 +30,12 @@ vi.mock('./cos.js', () => ({
}),
}));
-// The real sentinel + predicate: the adoption guard's whole job is telling a
-// failed READ from an absent record, so a stubbed sentinel would prove nothing.
-const { AGENT_RECORD_UNREADABLE } = vi.hoisted(() => ({
- AGENT_RECORD_UNREADABLE: Symbol('agent-record-unreadable'),
-}));
-vi.mock('./cosAgentLifecycle.js', () => ({
- AGENT_RECORD_UNREADABLE,
- isLiveAgentRecord: (record) => Boolean(record) && record.status !== 'completed',
+// Stub ONLY the read. `isLiveAgentRecord` is the contract this guard turns on,
+// so it comes from the real module — a re-implemented copy here would keep
+// passing if the real predicate changed (e.g. started treating `paused` as
+// terminal) while production behavior flipped underneath it.
+vi.mock('./cosAgentLifecycle.js', async (importOriginal) => ({
+ ...(await importOriginal()),
readAgentRecordOrUnreadable: vi.fn(),
}));
@@ -49,7 +47,7 @@ vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
-import { readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';
+import { AGENT_RECORD_UNREADABLE, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';
import { activeAgents, runnerAgents } from './agentState.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 5028fea6d0..bb5157f78b 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -15,7 +15,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents } from './cosEvents.js';
import { ServerError } from '../lib/errorHandler.js';
-import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
+import { loadState, saveState, withStateLock, readAgentsStateForSafetyCheck, AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir, readFileTail, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
@@ -419,12 +419,24 @@ export const readAgentRecordOrUnreadable = (agentId) =>
* runner was still advertising, blocking the restart that would have cleared
* them. `registerAgent` writes the record before the spawn, and the whole spawn
* runs inside `spawningTasks`, so no genuinely starting agent falls through.
+ *
+ * **Fails CLOSED.** The one caller gates a pm2 restart that severs live agents,
+ * so this reads the records through `readAgentsStateForSafetyCheck` — which
+ * reports whether they could be established at all — rather than `loadState`,
+ * which silently substitutes an EMPTY default state for a corrupt file. Reading
+ * that default would judge every tracked id finalized and hand the gate a
+ * confident zero, restarting PortOS out from under whatever was running. When
+ * the records cannot be trusted, every tracked id counts as live instead.
*/
export async function filterLiveAgentIds(agentIds) {
if (agentIds.length === 0) return [];
const ids = [...new Set(agentIds)];
- const state = await loadState();
- return ids.filter(id => isLiveAgentRecord(state.agents[id]));
+ const { trusted, agents } = await readAgentsStateForSafetyCheck();
+ if (!trusted || !agents) {
+ console.warn(`⚠️ CoS agent records could not be established — treating all ${ids.length} tracked agent(s) as live`);
+ return ids;
+ }
+ return ids.filter(id => isLiveAgentRecord(agents[id]));
}
// Get agent by ID with full output from file
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index 048b85d6bd..3ec894de49 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -18,7 +18,10 @@ vi.mock('./cosState.js', () => ({
AGENTS_DIR: mockCosState.agentsDir,
loadState: vi.fn(async () => mockCosState.state),
saveState: vi.fn(),
- withStateLock: async (fn) => fn()
+ withStateLock: async (fn) => fn(),
+ // The uncached, non-defaulting read the update gate uses. Defaults to
+ // "trusted, and these are the records"; one test drives the untrusted answer.
+ readAgentsStateForSafetyCheck: vi.fn(async () => ({ trusted: true, agents: mockCosState.state?.agents ?? {} })),
}));
vi.mock('./domainUsage.js', () => ({
@@ -52,7 +55,7 @@ vi.mock('fs/promises', async (importOriginal) => {
});
import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
-import { saveState, loadState } from './cosState.js';
+import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.js';
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
@@ -108,6 +111,18 @@ describe('cosAgentLifecycle', () => {
await expect(filterLiveAgentIds([])).resolves.toEqual([]);
});
+ // The gate this feeds authorizes a pm2 restart that severs live agents, so an
+ // unreadable state file must not read as "nothing is running". `loadState`
+ // substitutes an EMPTY default state for a corrupt file — trusting that would
+ // hand the gate a confident zero and restart PortOS out from under whatever
+ // was live.
+ it('treats every tracked id as live when the records cannot be established', async () => {
+ vi.mocked(readAgentsStateForSafetyCheck).mockResolvedValueOnce({ trusted: false, agents: null });
+
+ await expect(filterLiveAgentIds(['agent-a', 'agent-b']))
+ .resolves.toEqual(['agent-a', 'agent-b']);
+ });
+
// "The read failed" and "there is no such record" lead to opposite decisions —
// one leaves live tracking alone, the other retires it — so the reader must
// never let an I/O failure arrive as a plain null.
diff --git a/server/services/cosState.js b/server/services/cosState.js
index cfefab84ff..b390d6da65 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -247,20 +247,41 @@ export async function loadState() {
return stateCache;
}
-// Read only the persisted Persistent Mind shape for source-transition safety
-// checks. Unlike loadState(), this deliberately does not replace malformed JSON
-// with defaults: an update gate must distinguish "known empty" from "could not
-// establish what is queued" before switching to an older source reader.
-export async function readPersistentMindStateForSafetyCheck() {
+// Read the persisted state for safety checks, bypassing both the cache and
+// loadState()'s defaulting. Unlike loadState(), this deliberately does not
+// replace malformed JSON with defaults: a gate that authorizes a destructive
+// action must distinguish "known empty" from "could not establish what is
+// there". `trusted: false` means the file exists but could not be read as an
+// object — every caller must treat that as "assume the worst", never as empty.
+async function readStateForSafetyCheck() {
await ensureDirectories();
- if (!existsSync(STATE_FILE)) return { trusted: true, persistentMind: null };
+ if (!existsSync(STATE_FILE)) return { trusted: true, state: null };
const content = await readFile(STATE_FILE, 'utf-8');
- if (!isValidJSON(content)) return { trusted: false, persistentMind: null };
+ if (!isValidJSON(content)) return { trusted: false, state: null };
const state = safeJSONParse(content, null, { logError: true, context: 'CoS state safety check' });
if (!state || typeof state !== 'object' || Array.isArray(state)) {
- return { trusted: false, persistentMind: null };
+ return { trusted: false, state: null };
}
- return { trusted: true, persistentMind: state.persistentMind };
+ return { trusted: true, state };
+}
+
+// The Persistent Mind slice, for the update route's image-work gate.
+export async function readPersistentMindStateForSafetyCheck() {
+ const { trusted, state } = await readStateForSafetyCheck();
+ return { trusted, persistentMind: trusted ? state?.persistentMind ?? null : null };
+}
+
+// The agent records, for the update route's live-agent gate. Same contract:
+// `trusted: false` is "the records could not be established", which that gate
+// must read as "an agent may be running", not as "no agents are running" —
+// getting that backwards restarts PortOS out from under a live agent.
+export async function readAgentsStateForSafetyCheck() {
+ const { trusted, state } = await readStateForSafetyCheck();
+ const agents = state?.agents;
+ return {
+ trusted,
+ agents: trusted && agents && typeof agents === 'object' && !Array.isArray(agents) ? agents : null,
+ };
}
export async function saveState(state) {