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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop phantom CoS agents from blocking the update page forever
[._.]/ Adam Eivyea7275c04be2
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 815b7ed595..415d18cae0 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -68,6 +68,7 @@ const HOST = process.env.HOST || '127.0.0.1';// Active agent processes (in memory)const activeAgents = new Map();+// `tui:output` is live telemetry, so an immediate process exit can beat its// socket delivery. Keep a small terminal tail with the exit event: the PortOS// spawner owns failure analysis and can persist it when no ordinary TUI chunk@@ -76,13 +77,41 @@ const activeAgents = new Map();const TUI_EXIT_OUTPUT_TAIL_CHARS = 16 * 1024;const TUI_SIGNALS = new Set(['SIGTERM', 'SIGKILL', 'SIGINT']);-const terminateRunnerProcess = (agent, signal = 'SIGTERM') => {- if (agent.kind === 'tui') {- agent.process.kill(signal);- return;- }- killProcessTree(agent.process, signal);-};+/**+ * 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);+}// Express app setupconst app = express();@@ -251,6 +280,8 @@ app.post('/spawn-tui', async (req, res) => {const current = activeAgents.get(agentId);if (!current) return;current.doneWatcher?.();+ // Cancel any pending SIGKILL timer — process already exited.+ if (current.killTimer) clearTimeout(current.killTimer);const duration = Date.now() - current.startedAt;const success = current.completedBySentinel;const effectiveExitCode = success ? 0 : exitCode;@@ -635,18 +666,8 @@ app.post('/terminate/:agentId', (req, res) => {console.log(`🔪 Terminating agent ${agentId}`);- // killProcessTree (not .kill) so a Windows cmd.exe-wrapped CLI shim's real- // child is taken down too, not orphaned (#2243). No-op difference on POSIX.- terminateRunnerProcess(agent, 'SIGTERM');-- // Force kill after timeout; store handle so it can be cancelled if the- // process exits cleanly before the grace window expires.- agent.killTimer = setTimeout(() => {- if (activeAgents.has(agentId)) {- terminateRunnerProcess(agent, 'SIGKILL');- activeAgents.delete(agentId);- }- }, SIGKILL_GRACE_MS);+ killProcessTree(agent.process, 'SIGTERM');+ armForceKill(agentId, agent);res.json({ success: true, agentId });});@@ -664,9 +685,7 @@ app.post('/kill/:agentId', async (req, res) => {console.log(`💀 Force killing agent ${agentId} (PID: ${agent.pid})`);- // Use SIGKILL for immediate termination — killProcessTree so a Windows- // cmd.exe-wrapped shim's real child isn't orphaned (#2243). POSIX unchanged.- terminateRunnerProcess(agent, 'SIGKILL');+ killProcessTree(agent.process, 'SIGKILL');// Clean up immediatelyactiveAgents.delete(agentId);@@ -700,12 +719,12 @@ app.post('/pause/:agentId', async (req, res) => {agent.pausedAt = pausedAt;agent.pauseReason = reason;- // killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).- terminateRunnerProcess(agent, 'SIGTERM');- // Store handle so the close handler can clear it when the process exits first.+ killProcessTree(agent.process, 'SIGTERM');+ // 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(() => {const current = activeAgents.get(agentId);- if (current?.paused) terminateRunnerProcess(current, 'SIGKILL');+ if (current?.paused) killProcessTree(current.process, 'SIGKILL');}, SIGKILL_GRACE_MS);res.json({ success: true, agentId, pid: agent.pid, pausedAt });@@ -724,14 +743,8 @@ app.post('/terminate-all', async (req, res) => {for (const agentId of agentIds) {const agent = activeAgents.get(agentId);if (agent) {- // killProcessTree so a Windows cmd.exe-wrapped shim's child isn't orphaned (#2243).- terminateRunnerProcess(agent, 'SIGTERM');- agent.killTimer = setTimeout(() => {- if (activeAgents.has(agentId)) {- terminateRunnerProcess(agent, 'SIGKILL');- activeAgents.delete(agentId);- }- }, SIGKILL_GRACE_MS);+ killProcessTree(agent.process, 'SIGTERM');+ armForceKill(agentId, agent);}}@@ -822,8 +835,12 @@ io.on('connection', (socket) => {socket.on('tui:kill', ({ sessionId, signal = 'SIGTERM' }) => {try {if (!TUI_SIGNALS.has(signal)) return;- const agent = [...activeAgents.values()].find(candidate => candidate.sessionId === sessionId);- if (agent?.kind === 'tui') terminateRunnerProcess(agent, signal);+ const entry = [...activeAgents.entries()].find(([, candidate]) => candidate.sessionId === sessionId);+ if (!entry) return;+ const [agentId, agent] = entry;+ if (agent.kind !== 'tui') return;+ killProcessTree(agent.process, signal);+ armForceKill(agentId, agent, { dropState: true });} catch (err) {console.error(`❌ TUI termination relay failed: ${err.message}`);}@@ -903,7 +920,7 @@ process.on('SIGTERM', async () => {// Terminate all agentsfor (const [agentId, agent] of activeAgents) {console.log(`🔪 Terminating agent ${agentId}`);- terminateRunnerProcess(agent, 'SIGTERM');+ killProcessTree(agent.process, 'SIGTERM');}// Wait for agents to terminatediff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex 34e2ba2962..7855ba732d 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -71,22 +71,35 @@ describe('cos-runner spawn — per-provider prompt delivery (antigravity --print});});-describe('cos-runner termination — Windows tree-kill for cmd.exe-wrapped shims (#2243)', () => {- it('imports killProcessTree from the shared bufferedSpawn helper', () => {- expect(RUNNER_SRC).toMatch(- /import\s*\{[^}]*\bkillProcessTree\b[^}]*\}\s*from\s*'\.\.\/lib\/bufferedSpawn\.js';/- );+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.+ 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.)+ expect(RUNNER_SRC).not.toContain(".process.kill('SIG");});- it('tree-kills wrapped CLI agents while using node-pty kill for TUI handles', () => {- // Once an agent is spawned as `cmd.exe /c opencode.cmd …` on Windows, a- // plain agent.process.kill() signals only cmd.exe and orphans the real CLI.- // node-pty handles are the exception: their own kill API releases the- // native PTY resources correctly.- expect(RUNNER_SRC).toMatch(- /if\s*\(\s*agent\.kind\s*===\s*'tui'\s*\)\s*\{[\s\S]{0,100}?agent\.process\.kill\(signal\)[\s\S]{0,100}?return;/- );- expect(RUNNER_SRC).toMatch(/killProcessTree\(agent\.process,\s*signal\)/);+ // 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.+ expect(RUNNER_SRC.split('armForceKill(agentId, agent);')).toHaveLength(3);+ expect(RUNNER_SRC).toContain('armForceKill(agentId, agent, { dropState: true })');});});diff --git a/server/lib/README.md b/server/lib/README.mdindex 1f6ee3b1b8..a5c5685f0c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -259,7 +259,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |-| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |+| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex cca0ad47be..b9fcec0667 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -119,13 +119,21 @@ 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.+// 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.+// Mirrors server/lib/bufferedSpawn.js (this directory stays self-contained).function killProcessTree(child) {- if (IS_WIN32 && child.pid && child instanceof ChildProcess) {+ const isChildProcess = child instanceof ChildProcess;+ if (IS_WIN32 && child.pid && isChildProcess) {child.killed = true;spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();+ } else if (IS_WIN32 && !isChildProcess) {+ child.kill();} else {child.kill('SIGTERM');}diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 18b7aadaf1..180ee6f9d1 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -3,6 +3,17 @@ import { mkdtemp, rm, readFile, writeFile } from 'fs/promises';import { join, basename } from 'path';import { tmpdir } from 'os';import EventEmitter from 'events';+import { ChildProcess } from 'child_process';++const IS_WIN32 = process.platform === 'win32';++/**+ * An external run's spawned handle. The prototype matters: killProcessTree+ * tells a spawned child from a node-pty session by `instanceof ChildProcess`,+ * and a plain object would silently exercise the pty branch.+ */+const externalChild = () =>+ Object.assign(Object.create(ChildProcess.prototype), { kill: vi.fn(), killed: false });vi.mock('child_process', async (importOriginal) => {const actual = await importOriginal();@@ -698,7 +709,7 @@ describe('AI Toolkit runner — declared extension points', () => {const runner = createRunnerService({ dataDir: './data' });expect(await runner.isRunActive('x')).toBe(false);- const child = { kill: vi.fn(), killed: false };+ const child = externalChild();runner.registerExternalRun('x', child);expect(runner.hasExternalRun('x')).toBe(true);expect(await runner.isRunActive('x')).toBe(true);@@ -712,6 +723,19 @@ describe('AI Toolkit runner — declared extension points', () => {expect(await runner.stopRun('x')).toBe(false);});+ // registerExternalRun also holds node-pty sessions (the host's TUI runs). On+ // Windows node-pty throws "Signals not supported on windows." for any signal,+ // so a signalled kill there stopped nothing and threw past stopRun, leaving+ // the TUI running while the run reported itself stopped.+ it('stopRun kills a node-pty external run without a signal on Windows', async () => {+ const runner = createRunnerService({ dataDir: './data' });+ const pty = { pid: 4321, kill: vi.fn((signal) => { if (signal && IS_WIN32) throw new Error('Signals not supported on windows.'); }) };+ runner.registerExternalRun('tui-run', pty);++ expect(await runner.stopRun('tui-run')).toBe(true);+ expect(pty.kill).toHaveBeenCalledWith(...(IS_WIN32 ? [] : ['SIGTERM']));+ });+it('stopRun aborts an AbortController-style external run', async () => {const runner = createRunnerService({ dataDir: './data' });const controller = { abort: vi.fn() };@@ -723,7 +747,7 @@ describe('AI Toolkit runner — declared extension points', () => {it('unregisterExternalRun clears a stale explicit-stop marker', async () => {const runner = createRunnerService({ dataDir: './data' });- const child = { kill: vi.fn(), killed: false };+ const child = externalChild();runner.registerExternalRun('done', child);await runner.stopRun('done');runner.unregisterExternalRun('done');@@ -733,7 +757,7 @@ describe('AI Toolkit runner — declared extension points', () => {it('deleteRun kills an in-flight external run before removing its dir', async () => {const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-del-'));const runner = createRunnerService({ dataDir });- const child = { kill: vi.fn(), killed: false };+ const child = externalChild();runner.registerExternalRun('live', child);// No on-disk dir for this run, but the live process must still be killed.diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 1c7338bb89..b8f01a736b 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -22031,7 +22031,7 @@"sources": [{"source": "server/routes/update.js",- "line": 104+ "line": 114}]},@@ -22042,7 +22042,7 @@"sources": [{"source": "server/routes/update.js",- "line": 179+ "line": 189}]},@@ -22053,7 +22053,7 @@"sources": [{"source": "server/routes/update.js",- "line": 118+ "line": 128}]},@@ -22064,7 +22064,7 @@"sources": [{"source": "server/routes/update.js",- "line": 110+ "line": 120}]},@@ -22075,7 +22075,7 @@"sources": [{"source": "server/routes/update.js",- "line": 94+ "line": 103}]},@@ -22086,7 +22086,7 @@"sources": [{"source": "server/routes/update.js",- "line": 129+ "line": 139}]},diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex 71e4865d7d..c0c5753131 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -215,6 +215,18 @@ 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+ * "N CoS agents running" gate, pausing updates indefinitely.+ ** `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@@ -236,7 +248,8 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;* @param {{processGroup?: boolean}} [opts] - POSIX: signal the child's process group (it must have been spawned `detached`)*/export function killProcessTree(child, signal = 'SIGTERM', { processGroup = false } = {}) {- if (IS_WIN32 && child.pid && child instanceof ChildProcess) {+ const isChildProcess = child instanceof ChildProcess;+ if (IS_WIN32 && child.pid && isChildProcess) {child.killed = true;spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' }).on('error', () => {})@@ -247,6 +260,8 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = falstry { 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();child.kill(signal);}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex abc9b13b38..88fe9c5854 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -148,16 +148,28 @@ describe('killProcessTree', () => {killSpy.mockRestore();});- it('on Windows still uses .kill() (not taskkill) for a non-ChildProcess killable, e.g. a node-pty session', () => {+ 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// (e.g. node-pty's IPty, registered via registerExternalRun for TUI// runs) — taskkill against its pid would bypass its own native teardown// (releasing a Windows ConPTY handle) and leak it.- const ptyLike = { pid: 4321, kill: vi.fn() };- killProcessTree(ptyLike);+ //+ // The signal must be DROPPED: node-pty's Windows backend throws+ // "Signals not supported on windows." for any signal argument, so a+ // signalled kill there killed nothing and threw past the caller — which is+ // how every CoS Runner TUI kill became a silent no-op on Windows.+ const ptyLike = { pid: 4321, kill: vi.fn((signal) => { if (signal) throw new Error('Signals not supported on windows.'); }) };+ killProcessTree(ptyLike, 'SIGKILL');expect(spawnMock).not.toHaveBeenCalled();- expect(ptyLike.kill).toHaveBeenCalledWith('SIGTERM');+ expect(ptyLike.kill).toHaveBeenCalledWith();+ });++ it('on non-Windows still forwards the signal to a node-pty session', () => {+ if (IS_WIN32) return; // platform-gated behavior+ const ptyLike = { pid: 4321, kill: vi.fn() };+ killProcessTree(ptyLike, 'SIGKILL');+ expect(ptyLike.kill).toHaveBeenCalledWith('SIGKILL');});});diff --git a/server/routes/update.js b/server/routes/update.jsindex f98b09fede..b2af17ed89 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -8,6 +8,7 @@ import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';import { getActiveAgentIds, spawningTasks } from '../services/agentState.js';import { readPersistentMindStateForSafetyCheck, withStateLock } from '../services/cosState.js';+import { filterLiveAgentIds } from '../services/cosAgentLifecycle.js';const router = Router();@@ -28,8 +29,16 @@ const router = Router();// reads this but before update.sh's pm2 restart. The route's post-lock re-check// below narrows it; fully closing it needs every CoS spawn engine to consult// updateInProgress (tracked in #4124) — the orphan reaper bounds the residual.-function countActiveCosAgents() {- return getActiveAgentIds().length + spawningTasks.size;+//+// The map ids are filtered through PortOS's own durable records first+// (`filterLiveAgentIds`). Neither map is self-cleaning, and `syncRunnerAgents`+// adopts whatever the CoS Runner still advertises — so a TUI the runner failed+// to kill stayed "active" until the next PortOS restart, permanently blocking+// the one action that would have cleared it. A restart cannot sever a run this+// process has already finalized, so a finalized id must not gate the update.+async function countActiveCosAgents() {+ const live = await filterLiveAgentIds(getActiveAgentIds());+ return live.length + spawningTasks.size;}// The 409 the update flow raises when a restart would sever a live/spawning@@ -93,11 +102,12 @@ const executeSchema = z.object({// restart out from under a running agent).router.get('/status', asyncHandler(async (req, res) => {await updateChecker.clearStaleUpdateInProgress();- const [status, persistentMindImages] = await Promise.all([+ const [status, persistentMindImages, activeCosAgents] = await Promise.all([updateChecker.getUpdateStatus(),getPersistentMindImageWorkGuard(),+ countActiveCosAgents(),]);- res.json({ ...status, activeCosAgents: countActiveCosAgents(), persistentMindImages });+ res.json({ ...status, activeCosAgents, persistentMindImages });}));// POST /api/update/check — triggers manual check@@ -182,14 +192,12 @@ router.post('/execute', asyncHandler(async (req, res) => {// Never restart PortOS out from under a live CoS agent. Both a normal update// and a reconcile run update.sh, which pm2-restarts THIS server process and// severs any in-flight agent (each agent's PTY/child process is a child of it).- // countActiveCosAgents() reflects exactly what a restart would kill — live- // processes plus in-flight spawns — so a stale persisted `status: 'running'`- // on disk can't spuriously block, and a paused agent (its process already- // stopped) correctly doesn't. Fast-fail here so it covers reconcile, normal- // update, and both fork variants (all funnel through /execute) before doing- // the git/fork work below; a second re-check after the lock closes the window- // an agent could start in during that work.- const preCheck = countActiveCosAgents();+ // countActiveCosAgents() reflects exactly what a restart would kill (see its+ // definition above). Fast-fail here so it covers reconcile, normal update, and+ // both fork variants (all funnel through /execute) before doing the git/fork+ // work below; a second re-check after the lock closes the window an agent+ // could start in during that work.+ const preCheck = await countActiveCosAgents();if (preCheck > 0) throw agentsActiveError(preCheck);const preImageCheck = await getPersistentMindImageWorkGuard();if (!preImageCheck.trusted) throw persistentMindStateUntrustedError();@@ -261,7 +269,7 @@ router.post('/execute', asyncHandler(async (req, res) => {// `updateChecker.isUpdateInProgress()`, which subAgentSpawner's `task:ready`// listener and `spawnAgentForTask` both check, holding the task as `pending`// until after the restart (issue #4124).- const postLock = countActiveCosAgents();+ const postLock = await countActiveCosAgents();if (postLock > 0) {await updateChecker.setUpdateInProgress(false);throw agentsActiveError(postLock);diff --git a/server/routes/update.test.js b/server/routes/update.test.jsindex db4720ddc5..ff2fd03a63 100644--- a/server/routes/update.test.js+++ b/server/routes/update.test.js@@ -27,6 +27,12 @@ vi.mock('../services/agentState.js', () => ({getActiveAgentIds: vi.fn().mockReturnValue([]),spawningTasks: mockSpawningTasks}));+// The map ids are filtered through PortOS's durable records before they count.+// Default the filter to "every tracked id has a live record" so the existing+// cases keep asserting the counting arithmetic; the stale-entry case overrides it.+vi.mock('../services/cosAgentLifecycle.js', () => ({+ filterLiveAgentIds: vi.fn(async (ids) => ids)+}));const { mockCosState } = vi.hoisted(() => ({mockCosState: {persistentMind: { queuedMessages: [], activeTurn: null },@@ -44,6 +50,7 @@ import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';import { getActiveAgentIds } from '../services/agentState.js';import { readPersistentMindStateForSafetyCheck } from '../services/cosState.js';+import { filterLiveAgentIds } from '../services/cosAgentLifecycle.js';import updateRoutes from './update.js';const makeApp = () => {@@ -71,6 +78,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {updateChecker.setUpdateInProgress.mockResolvedValue(true);executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);+ vi.mocked(filterLiveAgentIds).mockImplementation(async (ids) => ids);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({trusted: true,@@ -166,6 +174,7 @@ describe('POST /api/update/execute — active CoS agent gating', () => {updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);+ vi.mocked(filterLiveAgentIds).mockImplementation(async (ids) => ids);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({trusted: true,@@ -307,6 +316,19 @@ describe('POST /api/update/execute — active CoS agent gating', () => {expect(res.status).toBe(200);expect(executeUpdate).toHaveBeenCalled();});++ // The phantom that pinned the Update page: the CoS Runner kept advertising+ // TUIs it had failed to kill, `syncRunnerAgents` adopted them, and the count+ // blocked the restart — the only thing that would have cleared them.+ it('lets the update run when every tracked id is an already-finalized ghost', async () => {+ getActiveAgentIds.mockReturnValue(['agent-ghost-1', 'agent-ghost-2']);+ vi.mocked(filterLiveAgentIds).mockResolvedValue([]);++ const res = await request(makeApp()).post('/api/update/execute').send({});++ expect(res.status).toBe(200);+ expect(executeUpdate).toHaveBeenCalled();+ });});describe('GET /api/update/status — activeCosAgents', () => {@@ -316,6 +338,7 @@ describe('GET /api/update/status — activeCosAgents', () => {updateChecker.clearStaleUpdateInProgress.mockResolvedValue(false);updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());getActiveAgentIds.mockReturnValue([]);+ vi.mocked(filterLiveAgentIds).mockImplementation(async (ids) => ids);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({trusted: true,@@ -347,6 +370,18 @@ describe('GET /api/update/status — activeCosAgents', () => {expect(res.body.activeCosAgents).toBe(3);});+ // The maps are not self-cleaning: the CoS Runner keeps advertising a TUI it+ // failed to kill, and `syncRunnerAgents` adopts it. Counting those pinned the+ // Update page on "4 CoS agents are currently running" above an empty agent+ // list — and only a restart, the very thing being blocked, could clear it.+ it('ignores tracked ids PortOS has already finalized', async () => {+ getActiveAgentIds.mockReturnValue(['agent-ghost-1', 'agent-ghost-2', 'agent-live']);+ vi.mocked(filterLiveAgentIds).mockResolvedValue(['agent-live']);+ const res = await request(makeApp()).get('/api/update/status');+ expect(res.status).toBe(200);+ expect(res.body.activeCosAgents).toBe(1);+ });+it('reports 0 when no agents are running', async () => {const res = await request(makeApp()).get('/api/update/status');expect(res.status).toBe(200);diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 3526b4aec7..028404a534 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -14,7 +14,7 @@ import { emitLog } from './cosEvents.js';// to open. Inside the closure the single address for a transition is the module// that declares it; a barrel would be a third answer to "where does completeAgent// live", which is the thing this sequencing keeps removing.-import { completeAgent, updateAgent, getAgents, getAgentRecord } from './cosAgentLifecycle.js';+import { completeAgent, updateAgent, getAgents, getAgentRecord, AGENT_RECORD_UNREADABLE, isLiveAgentRecord, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';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';@@ -1032,6 +1032,27 @@ async function runCleanupOrphanedAgents() {}}+ // The reverse pass: drop `runnerAgents` entries with nothing behind them.+ // The sweep below walks durable RECORDS, so it can never reach a map entry+ // that has no record — and nothing else prunes the map either, so a phantom+ // adopted from the runner survived until the process restarted. It then+ // over-protected worktrees from the cleanup job, and counted against the+ // update gate that blocks a restart, which is the one thing that would have+ // cleared it.+ //+ // Scoped to `runnerAgents` on purpose. `activeAgents` entries hold live+ // PTY/child handles owned by this process's own spawn closures; dropping one+ // would flip `isAgentOwnedLocally` to false and re-open the #4540+ // double-finalize that `agentRunnerSync`'s ownership check exists to prevent.+ // A runner-side entry is only ever a mirror, so losing it costs nothing but a+ // re-adoption on the next sweep if the runner still advertises it.+ for (const agentId of [...runnerAgents.keys()]) {+ const read = await readAgentRecordOrUnreadable(agentId);+ if (read === AGENT_RECORD_UNREADABLE || isLiveAgentRecord(read)) continue;+ runnerAgents.delete(agentId);+ emitLog('info', `🧹 Dropped stale runner-agent tracking for ${agentId} — no live record behind it`, { agentId });+ }+for (const agent of agents) {if (agent.status === 'running') {const inRemoteRunner = runnerActiveIds.has(agent.id);diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 7e06b4914b..a9fe2b05dd 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -27,6 +27,7 @@*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { ChildProcess } from '../lib/childProcess.js';import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';@@ -72,11 +73,17 @@ 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', () => ({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', () => ({terminateAgentViaRunner: vi.fn(),@@ -112,7 +119,7 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettleimport { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';-import { getAgents, updateAgent, getAgentRecord, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';+import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, 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';@@ -123,6 +130,15 @@ import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutimport { completeAgentRun } from './agentRunTracking.js';import { committedDuringRun } from '../lib/gitCommitProbe.js';import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';++/**+ * A direct-mode agent's spawned handle. Its prototype is ChildProcess so it+ * takes killProcessTree's spawned-child branch (Windows `taskkill` tree / POSIX+ * signal) rather than the node-pty branch, exactly as a real `spawn()` result+ * would — mirroring `makeFakeChild` in `lib/bufferedSpawn.test.js`.+ */+const fakeChildProcess = (kill = vi.fn()) =>+ Object.assign(Object.create(ChildProcess.prototype), { kill });import { hasPauseReleaseAdapter, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';describe('cleanupOrphanedAgents — startup recovery coordination', () => {@@ -158,6 +174,34 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {expect(updateTask).not.toHaveBeenCalled();});+ // The sweep walks durable RECORDS, so it can never reach a `runnerAgents`+ // entry that has no record — and nothing else prunes that map. A phantom+ // adopted from the runner therefore survived until the process restarted,+ // over-protecting worktrees from the cleanup job and counting against the+ // update gate that blocks the very restart that would clear it.+ it('drops runner-agent tracking whose record is gone or finalized, keeping live and unknowable ones', async () => {+ runnerAgents.set('agent-ghost', { taskId: 'task-1' });+ runnerAgents.set('agent-done', { taskId: 'task-1' });+ runnerAgents.set('agent-live', { taskId: 'task-1' });+ runnerAgents.set('agent-unreadable', { taskId: 'task-1' });+ readAgentRecordOrUnreadable.mockImplementation(async (id) => {+ if (id === 'agent-ghost') return null;+ if (id === 'agent-done') return { id, status: 'completed' };+ if (id === 'agent-unreadable') return AGENT_RECORD_UNREADABLE;+ return { id, status: 'running' };+ });++ await cleanupOrphanedAgents();++ expect(runnerAgents.has('agent-ghost')).toBe(false);+ expect(runnerAgents.has('agent-done')).toBe(false);+ expect(runnerAgents.has('agent-live')).toBe(true);+ // A failed read proves nothing — dropping tracking on it would strand a run+ // whose completion event still has to land.+ expect(runnerAgents.has('agent-unreadable')).toBe(true);+ runnerAgents.clear();+ });+it('treats a malformed runner probe as unavailable', async () => {getAgents.mockResolvedValueOnce([{id: 'agent-runner',@@ -400,7 +444,7 @@ describe('pauseAgent', () => {it('marks a direct agent paused, blocks the task as agent-paused, and signals SIGTERM', async () => {const kill = vi.fn();activeAgents.set('agent-1', {- process: { kill },+ process: fakeChildProcess(kill),taskId: 'task-1',runId: 'run-1',pid: 123,@@ -666,7 +710,7 @@ describe('pauseAgent — TUI branch', () => {it('sends ESC to the TUI session and schedules a delayed killSession', async () => {const sessionId = 'tui-session-99';activeAgents.set('tui-agent-1', {- process: { kill: vi.fn() },+ process: fakeChildProcess(),taskId: 'task-tui-1',tuiSessionId: sessionId,runId: 'run-tui-1',@@ -698,7 +742,7 @@ describe('pauseAgent — TUI branch', () => {it('does NOT call process.kill (SIGTERM) for a TUI agent', async () => {const kill = vi.fn();activeAgents.set('tui-agent-2', {- process: { kill },+ process: fakeChildProcess(kill),taskId: 'task-tui-2',tuiSessionId: 'tui-session-100',pid: 888,@@ -1794,7 +1838,7 @@ describe('lifecycle ledger — pause and interruption', () => {// markAgentPaused is the single chokepoint both pause arms funnel through,// and `at: pausedAt` is what makes a retried persist file one paused event// instead of two.- activeAgents.set('agent-1', { process: { kill: vi.fn() }, taskId: 'task-1', runId: 'run-1', pid: 123, workspacePath: '/repo/worktree' });+ activeAgents.set('agent-1', { process: fakeChildProcess(), taskId: 'task-1', runId: 'run-1', pid: 123, workspacePath: '/repo/worktree' });await pauseAgent('agent-1', 'billing window');@@ -1811,7 +1855,7 @@ describe('lifecycle ledger — pause and interruption', () => {// for a pause that never stuck — the exact class of lie the ledger exists// to catch.const kill = vi.fn();- activeAgents.set('agent-1', { process: { kill }, taskId: 'task-1', runId: 'run-1', pid: 123 });+ activeAgents.set('agent-1', { process: fakeChildProcess(kill), taskId: 'task-1', runId: 'run-1', pid: 123 });updateAgent.mockRejectedValueOnce(new Error('agent record unwritable'));await pauseAgent('agent-1', 'billing window').catch(() => null);@@ -1821,7 +1865,7 @@ describe('lifecycle ledger — pause and interruption', () => {});it('records a termination REQUEST before either arm runs', async () => {- activeAgents.set('agent-1', { process: { kill: vi.fn() }, taskId: 'task-1', runId: 'run-1', pid: 123 });+ activeAgents.set('agent-1', { process: fakeChildProcess(), taskId: 'task-1', runId: 'run-1', pid: 123 });await terminateAgent('agent-1');diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex 30c0a1d579..2fee88b8ba 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -14,7 +14,7 @@import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isAgentOwnedLocally, runnerAgents } from './agentState.js';-import { getAgent } from './cosAgentLifecycle.js';+import { AGENT_RECORD_UNREADABLE, isLiveAgentRecord, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';import { appendRunEvent } from './agentRunEventLog.js';import * as shellService from './shell.js';@@ -80,7 +80,22 @@ export async function syncRunnerAgents() {// silently exempting the longest-lived runs in the system from all cost// accounting. Survivors are the normal case since #3202 made TUI agents// durable, so this cannot stay a best-effort null.- const persisted = await getAgent(agent.id).catch(() => null);+ // Adopt only what PortOS still believes is running. The runner keeps+ // advertising a PTY it never managed to kill, and adopting one of those+ // mints a phantom `runnerAgents` entry that nothing ever removes: it holds+ // an open run, reads as locally owned forever, and counts against the+ // "CoS agents running" gate that pauses the Update page — while the agent+ // list, built from the durable records, shows nothing at all.+ //+ // A read that FAILED is not a record that is absent: the failure proves+ // nothing, and the live process behind it still needs its completion event+ // to land, so it gets its own sentinel and is adopted anyway.+ const read = await readAgentRecordOrUnreadable(agent.id);+ if (read !== AGENT_RECORD_UNREADABLE && !isLiveAgentRecord(read)) {+ console.warn(`⚠️ Ignoring stale runner agent ${agent.id} — PortOS has no live record for it`);+ continue;+ }+ const persisted = read === AGENT_RECORD_UNREADABLE ? null : read;const recoveredRunId = persisted?.metadata?.runId || null;runnerAgents.set(agent.id, {taskId: agent.taskId,diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.jsindex 987541beb5..0402f516d4 100644--- a/server/services/agentRunnerSync.test.js+++ b/server/services/agentRunnerSync.test.js@@ -30,8 +30,15 @@ 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', () => ({- getAgent: vi.fn(),+ AGENT_RECORD_UNREADABLE,+ isLiveAgentRecord: (record) => Boolean(record) && record.status !== 'completed',+ readAgentRecordOrUnreadable: vi.fn(),}));// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) —@@ -42,7 +49,7 @@ vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';-import { getAgent } from './cosAgentLifecycle.js';+import { readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';import { activeAgents, runnerAgents } from './agentState.js';import { syncRunnerAgents } from './agentRunnerSync.js';@@ -52,7 +59,7 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {runnerAgents.clear();activeAgents.clear();vi.mocked(shellService.getSession).mockReturnValue(null);- vi.mocked(getAgent).mockResolvedValue(null);+ vi.mocked(readAgentRecordOrUnreadable).mockResolvedValue({ id: 'agent-1', status: 'running' });});it('reconciles one surviving TUI and restores its attachable shell relay', async () => {@@ -91,8 +98,9 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {// `completeAgentRun` returns early on a null id — and survivors are the normal// case since #3202 made TUI agents durable.it('recovers the run id and model from the persisted agent record', async () => {- vi.mocked(getAgent).mockResolvedValue({+ vi.mocked(readAgentRecordOrUnreadable).mockResolvedValue({id: 'agent-1',+ status: 'running',metadata: { runId: 'run-abc123', model: 'claude-opus-5' },});vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{@@ -101,18 +109,19 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {await expect(syncRunnerAgents()).resolves.toBe(1);- expect(getAgent).toHaveBeenCalledWith('agent-1');+ expect(readAgentRecordOrUnreadable).toHaveBeenCalledWith('agent-1');expect(runnerAgents.get('agent-1')).toMatchObject({runId: 'run-abc123',model: 'claude-opus-5',});});- it('recovers with a null run id rather than throwing when the record is gone', async () => {- // A record that cannot be read must not take the whole recovery sweep down- // with it — the surviving agent still needs re-adopting so its completion+ it('recovers with a null run id rather than throwing when the record is unreadable', async () => {+ // A record that cannot be READ must not take the whole recovery sweep down+ // with it, and must not be mistaken for one that is absent: the read proves+ // nothing, and the surviving agent still needs re-adopting so its completion// event lands. The run stays open, which the warning line says out loud.- vi.mocked(getAgent).mockRejectedValue(new Error('metadata.json unreadable'));+ vi.mocked(readAgentRecordOrUnreadable).mockResolvedValue(AGENT_RECORD_UNREADABLE);vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([{id: 'agent-2', taskId: 'task-1', pid: 99, startedAt: Date.now(), kind: 'cli',}]);@@ -129,6 +138,29 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {}));});+ // The runner goes on advertising a PTY it failed to kill. Adopting one mints a+ // phantom runnerAgents entry nothing ever removes — which is what pinned the+ // Update page on "4 CoS agents are currently running" above an empty agent+ // list, since the durable records those four were finalized in are long gone.+ it('ignores a runner agent PortOS has already finalized, and one with no record at all', async () => {+ vi.mocked(readAgentRecordOrUnreadable).mockImplementation(async (id) => {+ if (id === 'agent-finalized') return { id, status: 'completed' };+ if (id === 'agent-gone') return null;+ 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' },+ ]);++ await expect(syncRunnerAgents()).resolves.toBe(1);++ expect(runnerAgents.has('agent-finalized')).toBe(false);+ expect(runnerAgents.has('agent-gone')).toBe(false);+ expect(runnerAgents.has('agent-real')).toBe(true);+ });+// A live runner-TUI is owned by this process's spawnTuiAgent closure, which// registers in `activeAgents` — never in `runnerAgents`. Hoisting it here made// subAgentSpawner's `agent:completed` handler run a second finalizeAgent over@@ -169,7 +201,7 @@ describe('syncRunnerAgents — reconnect boundary (#4540)', () => {runnerAgents.clear();activeAgents.clear();vi.mocked(shellService.getSession).mockReturnValue(null);- vi.mocked(getAgent).mockResolvedValue({ metadata: { runId: 'run-abc123' } });+ vi.mocked(readAgentRecordOrUnreadable).mockResolvedValue({ status: 'running', metadata: { runId: 'run-abc123' } });});const survivingTui = {diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 727b9579df..5028fea6d0 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -375,6 +375,58 @@ export async function getAgents() {return Object.values(state.agents);}+/**+ * Is this agent record still work in flight, rather than a run PortOS has+ * already finalized?+ *+ * `completed` is the only terminal status; a missing record is terminal too,+ * because a finalized agent is archived out of `state.agents` into its date+ * bucket, and an id that was never registered is not a run at all. `paused`+ * counts as live: its task is still owed a resume, and pausing already removes+ * the agent from the in-memory maps, so it can never inflate a map-derived+ * count on its own.+ */+export const isLiveAgentRecord = (record) => Boolean(record) && record.status !== 'completed';++/**+ * Returned by `readAgentRecordOrUnreadable` when the READ ITSELF failed — which+ * is not the same answer as `null` ("there is genuinely no such record"), and+ * leads to the opposite decision: an absent record means the run is finalized+ * and its tracking can go, while a failed read proves nothing and must leave+ * live state alone.+ */+export const AGENT_RECORD_UNREADABLE = Symbol('agent-record-unreadable');++/**+ * `getAgentRecord` that reports an I/O failure as `AGENT_RECORD_UNREADABLE`+ * instead of collapsing it into `null`. Pair it with `isLiveAgentRecord`:+ *+ * const read = await readAgentRecordOrUnreadable(id);+ * if (read !== AGENT_RECORD_UNREADABLE && !isLiveAgentRecord(read)) { … }+ */+export const readAgentRecordOrUnreadable = (agentId) =>+ getAgentRecord(agentId).then(record => record, () => AGENT_RECORD_UNREADABLE);++/**+ * Narrow a set of in-memory agent ids to the ones PortOS still considers work+ * in flight.+ *+ * The in-memory maps (`activeAgents` / `runnerAgents`) are not self-cleaning:+ * `syncRunnerAgents` adopts whatever `GET /agents` on the CoS Runner reports,+ * so a TUI PTY the runner never managed to kill stays "active" for the life of+ * the process. That is how the Update page came to sit on "4 CoS agents are+ * currently running" above an empty agent list — four finalized codex TUIs the+ * 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.+ */+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]));+}+// Get agent by ID with full output from file/*** The agent record WITHOUT its transcript — in-memory state first, falling backdiff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex 05b5689983..048b85d6bd 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -51,8 +51,8 @@ vi.mock('fs/promises', async (importOriginal) => {};});-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';-import { saveState } from './cosState.js';+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 { recordDomainUsage } from './domainUsage.js';import { cosEvents } from './cosEvents.js';@@ -90,6 +90,39 @@ describe('cosAgentLifecycle', () => {expect(agent.outputTruncated).toBe(false);});+ // The predicate behind the "CoS agents running" update gate. Its whole job is+ // to keep the two failure directions apart: a tracked id whose run PortOS has+ // already finalized must not block a restart forever, and a genuinely live one+ // must still block it.+ it('narrows tracked ids to live records, dropping finalized and unknown ones', async () => {+ mockCosState.state.agents = {+ 'agent-running': { id: 'agent-running', status: 'running' },+ // A paused agent is still owed a resume, so its record stays live.+ 'agent-paused': { id: 'agent-paused', status: 'paused' },+ 'agent-done': { id: 'agent-done', status: 'completed', completedAt: '2026-05-25T12:00:00.000Z' }+ };++ await expect(filterLiveAgentIds([+ 'agent-running', 'agent-running', 'agent-paused', 'agent-done', 'agent-archived-away'+ ])).resolves.toEqual(['agent-running', 'agent-paused']);+ await expect(filterLiveAgentIds([])).resolves.toEqual([]);+ });++ // "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.+ it('reports an unreadable record as its own sentinel, not as an absent one', async () => {+ mockCosState.state.agents = { 'agent-running': { id: 'agent-running', status: 'running' } };++ await expect(readAgentRecordOrUnreadable('agent-running'))+ .resolves.toMatchObject({ id: 'agent-running' });+ await expect(readAgentRecordOrUnreadable('agent-never-existed')).resolves.toBeNull();++ loadState.mockRejectedValueOnce(new Error('state.json unreadable'));+ await expect(readAgentRecordOrUnreadable('agent-running'))+ .resolves.toBe(AGENT_RECORD_UNREADABLE);+ });+// #3498: output.txt is unbounded — a long TUI run writes tens of MB. Reading it// whole and mapping EVERY line to an object spiked heap on a single request.describe('transcript tail caps (#3498)', () => {diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex b0a7f0de22..1b6aa473eb 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -6,6 +6,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'events';+import { ChildProcess } from '../../lib/childProcess.js';// Spawn mock — capture every spawn call so tests can assert args, drive// stdout/stderr, capture the stdin-delivered prompt, and trigger the close@@ -15,6 +16,10 @@ import { EventEmitter } from 'events';const spawnCalls = [];const makeFakeChild = () => {const child = new EventEmitter();+ // killProcessTree tells a spawned child from a node-pty session by+ // `instanceof ChildProcess` (a pty takes a different kill shape), so the fake+ // has to carry the prototype the way a real spawn() result does.+ Object.setPrototypeOf(child, ChildProcess.prototype);child.stdout = new EventEmitter();child.stderr = new EventEmitter();child.stdin = { written: '', on: vi.fn(), write: vi.fn(function (s) { child.stdin.written += s; }), end: vi.fn() };diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 4eb7feaff8..60bdbc2f1d 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import EventEmitter from 'events';+import { ChildProcess } from '../lib/childProcess.js';// executeCliRun validates that a requested workspace actually exists before// spawning (#3180 — a bad repoPath used to silently run in the PortOS root), so@@ -106,6 +107,10 @@ const flushMicrotasks = () => new Promise((resolve) => setImmediate(resolve));function makeChild() {const child = new EventEmitter();+ // killProcessTree tells a spawned child from a node-pty session by+ // `instanceof ChildProcess` (a pty takes a different kill shape), so the fake+ // has to carry the prototype the way a real spawn() result does.+ Object.setPrototypeOf(child, ChildProcess.prototype);child.stdout = new EventEmitter();child.stderr = new EventEmitter();child.stdin = { write: vi.fn(), end: vi.fn() };diff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.jsindex 93aae3d755..4b3c3425cc 100644--- a/server/services/videoGen/grok.test.js+++ b/server/services/videoGen/grok.test.js@@ -6,12 +6,17 @@ import { existsSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'events';+import { ChildProcess } from '../../lib/childProcess.js';// Spawn mock — capture calls, drive stdout/stderr, capture the stdin-delivered// prompt (grok reads it via --prompt-file /dev/stdin).const spawnCalls = [];const makeFakeChild = () => {const child = new EventEmitter();+ // killProcessTree tells a spawned child from a node-pty session by+ // `instanceof ChildProcess` (a pty takes a different kill shape), so the fake+ // has to carry the prototype the way a real spawn() result does.+ Object.setPrototypeOf(child, ChildProcess.prototype);child.stdout = new EventEmitter();child.stderr = new EventEmitter();child.stdin = { written: '', on: vi.fn(), write: vi.fn(function (s) { child.stdin.written += s; }), end: vi.fn() };diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.jsindex 7b601ea1d0..1c153ba4ed 100644--- a/server/services/visionCli.test.js+++ b/server/services/visionCli.test.js@@ -2,6 +2,7 @@ import { describe, it, expect, vi } from 'vitest';import { posixPath } from '../lib/testHelper.js';import { EventEmitter } from 'events';+import { ChildProcess } from '../lib/childProcess.js';import { mkdtemp, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';@@ -142,6 +143,10 @@ describe('prepareCliVisionRun', () => {// A minimal child-process double: an EventEmitter with stdin/stdout/stderr.function makeFakeChild() {const child = new EventEmitter();+ // killProcessTree tells a spawned child from a node-pty session by+ // `instanceof ChildProcess` (a pty takes a different kill shape), so the fake+ // has to carry the prototype the way a real spawn() result does.+ Object.setPrototypeOf(child, ChildProcess.prototype);child.killed = false;child.kill = vi.fn(() => { child.killed = true; });child.stdin = { write: vi.fn(), end: vi.fn() };