Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-3202]): record a server restart as an agent interruption, not a completed run

[._.]/ Adam Eivy410be46bb555
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b4b2b7ed77..fd50507d60 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,7 @@
- **[issue-3180] Agents no longer run in the PortOS folder when your app's repository path is wrong** — picking an app as the workspace (in a CoS task, or Settings → Providers → Run Prompt) and asking the agent to create a file could put the file in the PortOS directory instead of your app. If the app's Repository Path was empty, mistyped, or pointed somewhere that no longer exists, PortOS quietly fell back to its own folder and said nothing, so the run looked like it had worked. Now PortOS names the directory it chose for every run and in the CoS task log; a run whose workspace doesn't exist stops with a message telling you which path to fix; and a CoS task whose app has no usable Repository Path is blocked before the agent starts, rather than turned loose in the PortOS checkout. A path saved as `~/Projects/MyApp` is also accepted. Troubleshooting steps — including why `PORTOS_WORKSPACE_ROOTS` is unrelated to this — are in `docs/TROUBLESHOOTING.md`.
- **[issue-3193] OpenCode agents now run in the app you selected, not the PortOS folder** — even with a correct Repository Path, agents on an OpenCode provider wrote their files into the PortOS directory and reported the PortOS path as their working folder. OpenCode decides where it is by reading an environment variable that describes the folder PortOS itself was started in, rather than the folder it was actually handed, so the workspace you picked was quietly ignored — only on OpenCode, which is why Codex, Claude Code, and Gemini looked fine. PortOS now sets that variable to the real working directory everywhere it starts an agent, a provider run, a TUI session, or a terminal. Troubleshooting steps for telling this apart from a mistyped Repository Path are in `docs/TROUBLESHOOTING.md`.
- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.
+- **[issue-3202] Restarting PortOS no longer marks a running agent "completed" or burns its retry budget** — a restart kills every agent PortOS owns, and the terminal-based ones reported that as a clean finish. The task was recorded as done with nothing but two startup lines to show for it, and the folder holding its work was deleted on the way out. When the task did come back, the restart was counted against it as a failure: three routine restarts were enough to block the task outright, and two in a row left it sitting in a 30-minute cooldown. PortOS now recognizes that it was the one that pulled the plug. An agent cut short by a restart is recorded as interrupted rather than finished, its working folder is left untouched, and the task returns to the queue immediately — resuming from what the interrupted run left behind, with no retry charged and no cooldown. An agent that had already reported its results still completes normally, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them alive across one is separate work.
- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.
## Image generation
diff --git a/server/lib/README.md b/server/lib/README.md
index 5c91cdae4c..9994f333eb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -161,6 +161,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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). `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.
| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
+| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing, read by the TUI spawner so a PTY that dies under pm2's TreeKill is abandoned (worktree preserved) instead of finalized as a completed run. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
diff --git a/server/lib/hostShutdown.js b/server/lib/hostShutdown.js
new file mode 100644
index 0000000000..c89a627ed6
--- /dev/null
+++ b/server/lib/hostShutdown.js
@@ -0,0 +1,125 @@
+/**
+ * Host-shutdown signal + durable marker.
+ *
+ * `portos-server` is restarted routinely — pm2's memory ceiling, a manual
+ * `pm2 restart`, a code deploy. pm2's TreeKill signals every descendant of the
+ * server, so a CoS TUI agent whose PTY the server owns dies WITH the server
+ * even though the durable `portos-cos` runner never went down (issue #3202).
+ *
+ * That teardown is an INTERRUPTION, not an outcome, and PortOS has to be able to
+ * tell the two apart later — after the process that witnessed it is gone. Two
+ * signals do that:
+ *
+ * 1. **In-process flag** (`markHostShuttingDown` / `isHostShuttingDown`) —
+ * read by the TUI spawner's PTY-exit handler so a PTY that vanishes mid
+ * shutdown is never finalized as a completed run. Sync, allocation-free,
+ * and safe to set first thing inside a signal handler.
+ * 2. **Durable marker** (`writeHostShutdownMarker`) — a small JSON file naming
+ * the agents that were live when the signal arrived. The next boot's orphan
+ * sweep reads it to classify those agents as *interrupted by a host
+ * restart* rather than as ordinary orphans, so they don't burn orphan-retry
+ * budget or trip the 30-minute orphan cooldown for a fault they didn't
+ * cause.
+ *
+ * The marker is deliberately tiny and best-effort: it is written inside the
+ * graceful-shutdown window (which has a hard 10s ceiling), so every function
+ * here is non-throwing and returns a falsy/empty result rather than propagating
+ * an I/O failure into shutdown. A missing marker simply degrades recovery to the
+ * pre-existing orphan path — the old, safe behavior.
+ */
+
+import { join } from 'path';
+import { rm } from 'fs/promises';
+import { PATHS, atomicWrite, readJSONFile } from './fileUtils.js';
+
+/** Completion reason recorded for a run the host restart tore down. */
+export const HOST_SHUTDOWN_REASON = 'host-shutdown';
+
+/**
+ * Marker file. Lives beside the other CoS state so a data wipe clears it too.
+ *
+ * Resolved lazily rather than as a module-level constant: this module is
+ * imported by the TUI spawner, whose suites stub `fileUtils` with a partial
+ * `PATHS`. A `join(PATHS.cos, …)` evaluated at import time throws there and
+ * takes the whole suite down with it — for a path most callers never touch.
+ */
+export const hostShutdownMarkerPath = () => join(PATHS.cos, 'host-shutdown.json');
+
+// Process-local. Never persisted — a fresh process is by definition not the one
+// that was shutting down, so this always starts false.
+let shuttingDown = false;
+
+/**
+ * Latch the in-process shutdown flag. Idempotent; call it as the FIRST thing in
+ * a SIGTERM/SIGINT handler, before any await, so anything that races the
+ * teardown (a PTY exiting, a finalize hook firing) already sees it.
+ */
+export function markHostShuttingDown() {
+ shuttingDown = true;
+}
+
+/** Is this process on its way down? */
+export function isHostShuttingDown() {
+ return shuttingDown;
+}
+
+/**
+ * Reset the flag. Test-only — production never un-shuts-down.
+ */
+export function resetHostShutdownFlagForTests() {
+ shuttingDown = false;
+}
+
+/**
+ * Persist the marker naming the agents that were live at shutdown.
+ *
+ * @param {object} params
+ * @param {string[]} params.agentIds - ids of agents running when the signal landed
+ * @param {string} [params.signal] - the signal that triggered shutdown (diagnostic)
+ * @returns {Promise<boolean>} true when the marker landed on disk
+ */
+export async function writeHostShutdownMarker({ agentIds = [], signal = null } = {}) {
+ const ids = [...new Set(agentIds.filter((id) => typeof id === 'string' && id))];
+ // Nothing was running — don't leave a marker the next boot has to reason
+ // about (and don't overwrite a prior one; a marker with no agents is noise).
+ if (ids.length === 0) return false;
+ const ok = await atomicWrite(hostShutdownMarkerPath(), {
+ at: new Date().toISOString(),
+ signal,
+ agentIds: ids,
+ }).then(() => true, (err) => {
+ console.error(`❌ Failed to write host-shutdown marker: ${err.message}`);
+ return false;
+ });
+ if (ok) console.log(`🛑 Host shutdown marker written for ${ids.length} live agent(s)`);
+ return ok;
+}
+
+/**
+ * Read the marker left by the previous process.
+ *
+ * Returns a normalized `{ at, signal, agentIds }` — `agentIds` is ALWAYS an
+ * array, so a truncated/garbled marker degrades to "no agents were interrupted"
+ * instead of throwing during boot recovery. Returns null when no marker exists.
+ */
+export async function readHostShutdownMarker() {
+ const raw = await readJSONFile(hostShutdownMarkerPath(), null, { logError: false });
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ return {
+ at: typeof raw.at === 'string' ? raw.at : null,
+ signal: typeof raw.signal === 'string' ? raw.signal : null,
+ agentIds: Array.isArray(raw.agentIds) ? raw.agentIds.filter((id) => typeof id === 'string' && id) : [],
+ };
+}
+
+/**
+ * Remove the marker once boot recovery has consumed it. Non-throwing: a marker
+ * that can't be removed would only cause the NEXT boot to re-classify agents
+ * that are already settled, which the orphan sweep tolerates (it only ever looks
+ * at agents still marked `running`).
+ */
+export async function clearHostShutdownMarker() {
+ await rm(hostShutdownMarkerPath(), { force: true }).catch((err) => {
+ console.error(`❌ Failed to clear host-shutdown marker: ${err.message}`);
+ });
+}
diff --git a/server/lib/hostShutdown.test.js b/server/lib/hostShutdown.test.js
new file mode 100644
index 0000000000..e7419bbb70
--- /dev/null
+++ b/server/lib/hostShutdown.test.js
@@ -0,0 +1,144 @@
+/**
+ * Tests for the host-shutdown signal + durable marker (#3202).
+ *
+ * The marker is what lets the NEXT boot tell "PortOS was restarted out from
+ * under a running agent" apart from "the agent's own process died" — so the
+ * contract that matters most here is that every read path DEGRADES rather than
+ * throws. A garbled/absent marker must yield "nobody was interrupted", which
+ * routes those agents through the pre-existing (safe) orphan path instead of
+ * crashing boot recovery.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtemp, rm, readFile, writeFile, mkdir } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+let tmpRoot;
+
+// PATHS.cos is where the marker lives; point it at a scratch dir so the suite
+// never touches the install's real data/.
+vi.mock('./fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, get PATHS() { return { ...actual.PATHS, cos: globalThis.__hostShutdownTestCos }; } };
+});
+
+const {
+ markHostShuttingDown,
+ isHostShuttingDown,
+ resetHostShutdownFlagForTests,
+ writeHostShutdownMarker,
+ readHostShutdownMarker,
+ clearHostShutdownMarker,
+ hostShutdownMarkerPath,
+ HOST_SHUTDOWN_REASON,
+} = await import('./hostShutdown.js');
+
+beforeEach(async () => {
+ tmpRoot = await mkdtemp(join(tmpdir(), 'portos-host-shutdown-'));
+ globalThis.__hostShutdownTestCos = tmpRoot;
+ resetHostShutdownFlagForTests();
+});
+
+afterEach(async () => {
+ await rm(tmpRoot, { recursive: true, force: true });
+ delete globalThis.__hostShutdownTestCos;
+});
+
+describe('in-process shutdown flag', () => {
+ it('starts false and latches once marked', () => {
+ expect(isHostShuttingDown()).toBe(false);
+ markHostShuttingDown();
+ expect(isHostShuttingDown()).toBe(true);
+ // Idempotent — a second signal must not un-latch it.
+ markHostShuttingDown();
+ expect(isHostShuttingDown()).toBe(true);
+ });
+
+ it('names a stable completion reason', () => {
+ expect(HOST_SHUTDOWN_REASON).toBe('host-shutdown');
+ });
+});
+
+describe('marker round-trip', () => {
+ it('writes the live agent ids and reads them back', async () => {
+ expect(await writeHostShutdownMarker({ agentIds: ['a1', 'a2'], signal: 'SIGTERM' })).toBe(true);
+
+ const marker = await readHostShutdownMarker();
+ expect(marker.agentIds).toEqual(['a1', 'a2']);
+ expect(marker.signal).toBe('SIGTERM');
+ expect(marker.at).toEqual(expect.any(String));
+ });
+
+ it('dedupes ids and drops non-string entries', async () => {
+ await writeHostShutdownMarker({ agentIds: ['a1', 'a1', '', null, 7, 'a2'], signal: 'SIGINT' });
+
+ expect((await readHostShutdownMarker()).agentIds).toEqual(['a1', 'a2']);
+ });
+
+ it('writes nothing when no agents were live', async () => {
+ expect(await writeHostShutdownMarker({ agentIds: [], signal: 'SIGTERM' })).toBe(false);
+ expect(await readHostShutdownMarker()).toBeNull();
+ });
+
+ it('clears the marker', async () => {
+ await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });
+ await clearHostShutdownMarker();
+
+ expect(await readHostShutdownMarker()).toBeNull();
+ });
+
+ it('clearing a marker that is not there is a no-op, not a throw', async () => {
+ await expect(clearHostShutdownMarker()).resolves.toBeUndefined();
+ });
+});
+
+// Every one of these would previously have to be handled by the caller. Boot
+// recovery runs before anything else, so a throw here would be a boot crash —
+// the degraded answer ("nobody was interrupted") is always the right one.
+describe('a damaged marker degrades to "nobody was interrupted"', () => {
+ const writeRaw = async (contents) => {
+ await mkdir(tmpRoot, { recursive: true });
+ await writeFile(hostShutdownMarkerPath(), contents);
+ };
+
+ it('returns null for absent', async () => {
+ expect(await readHostShutdownMarker()).toBeNull();
+ });
+
+ it('returns null for unparseable JSON', async () => {
+ await writeRaw('{ "agentIds": ["a1"');
+ expect(await readHostShutdownMarker()).toBeNull();
+ });
+
+ it('returns null for a JSON array (wrong shape)', async () => {
+ await writeRaw('["a1","a2"]');
+ expect(await readHostShutdownMarker()).toBeNull();
+ });
+
+ it('returns an empty agent list when agentIds is missing or not an array', async () => {
+ await writeRaw(JSON.stringify({ at: 'x', signal: 'SIGTERM' }));
+ expect((await readHostShutdownMarker()).agentIds).toEqual([]);
+
+ await writeRaw(JSON.stringify({ agentIds: 'a1' }));
+ expect((await readHostShutdownMarker()).agentIds).toEqual([]);
+ });
+
+ it('normalizes non-string at/signal to null rather than surfacing junk', async () => {
+ await writeRaw(JSON.stringify({ at: 12345, signal: { x: 1 }, agentIds: ['a1'] }));
+
+ const marker = await readHostShutdownMarker();
+ expect(marker.at).toBeNull();
+ expect(marker.signal).toBeNull();
+ expect(marker.agentIds).toEqual(['a1']);
+ });
+});
+
+describe('marker location', () => {
+ it('lives under the CoS data dir so a data wipe clears it too', async () => {
+ await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });
+
+ expect(hostShutdownMarkerPath()).toBe(join(tmpRoot, 'host-shutdown.json'));
+ expect(JSON.parse(await readFile(hostShutdownMarkerPath(), 'utf8')).agentIds).toEqual(['a1']);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index c173dfed8f..d99112ebe5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -150,6 +150,7 @@ export * from './bashResolver.js';
export * from './bufferedSpawn.js';
export * from './commandSecurity.js';
export * from './detachedSpawn.js';
+export * from './hostShutdown.js';
export * from './execGit.js';
export * from './ffmpeg.js';
export * from './ffmpegRenderGuard.js';
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 5c2c0bee3f..287652e456 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -613,6 +613,16 @@ export const COMPLETION_REASON_ANALYSES = {
message: 'Agent did not wrap up when asked at its max runtime',
suggestedFix: 'The agent was asked to write its completion sentinel and did not respond within the grace window — its provider/CLI is likely wedged rather than merely slow. Check the raw transcript for a stalled request, and check for open or merged-but-uncleaned PRs it left behind.'
},
+ // The PTY was terminated by a signal rather than exiting on its own — almost
+ // always pm2's TreeKill taking portos-server's descendants down with it on a
+ // restart (#3202). Not actionable as an agent fault: the run was cut short by
+ // infrastructure, and the task is requeued to resume from what it left behind.
+ 'shell-signaled': {
+ category: 'process-killed',
+ actionable: false,
+ message: 'Agent session was terminated by a signal',
+ suggestedFix: 'The TUI session was killed rather than exiting on its own — usually a PortOS restart taking its child processes down. The task resumes from the preserved worktree; no agent-side fix is needed.'
+ },
'command-not-found': {
category: 'spawn-error',
actionable: true,
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 59872bfcdc..efd89c617e 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -24,6 +24,7 @@ import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
import { checkForTaskCommit } from './agentRunTracking.js';
import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';
import { PATHS } from '../lib/fileUtils.js';
+import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
@@ -560,6 +561,20 @@ export async function cleanupOrphanedAgents() {
let cleanedCount = 0;
const orphanedTaskIds = [];
+ // Agents the PREVIOUS process owned when it was signalled down (#3202). Their
+ // processes died because PortOS restarted, not because they failed — so they
+ // are *interrupted*, and must not be charged orphan-retry budget or held in the
+ // 30-minute orphan cooldown. A missing/garbled marker yields an empty set,
+ // which is exactly the pre-existing behavior (everything is an ordinary orphan).
+ const shutdownMarker = await readHostShutdownMarker().catch(() => null);
+ const interruptedByRestart = new Set(shutdownMarker?.agentIds || []);
+ if (interruptedByRestart.size > 0) {
+ emitLog('info', `🛑 Host restart marker: ${interruptedByRestart.size} agent(s) were interrupted by a PortOS restart`, {
+ count: interruptedByRestart.size,
+ shutdownAt: shutdownMarker?.at || null,
+ });
+ }
+
// Get list of agents actively running in the CoS Runner
const runnerActiveIds = new Set();
const runnerAgentsList = await getActiveAgentsFromRunner().catch(() => []);
@@ -596,7 +611,10 @@ export async function cleanupOrphanedAgents() {
}
}
- console.log(`🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
+ const interrupted = interruptedByRestart.has(agent.id);
+ console.log(interrupted
+ ? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`
+ : `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
const task = agent.taskId ? await getTask(agent.taskId).catch(() => null) : null;
await dispatchRecoveredTaskOutputHook({
agentId: agent.id,
@@ -606,8 +624,14 @@ export async function cleanupOrphanedAgents() {
});
await markComplete(agent.id, {
success: false,
- error: 'Agent process terminated unexpectedly',
- orphaned: true
+ error: interrupted
+ ? 'Agent was interrupted by a PortOS server restart'
+ : 'Agent process terminated unexpectedly',
+ orphaned: true,
+ // Distinguishes the two in the agent record so the UI and any
+ // post-mortem can tell an infrastructure interruption from a real
+ // agent fault — they look identical from the process's point of view.
+ interruptedByRestart: interrupted,
});
cleanedCount++;
@@ -645,9 +669,18 @@ export async function cleanupOrphanedAgents() {
// pointer reflects what actually survived — a dirty tree aborts removal, leaving
// the whole worktree in place.
for (const { taskId, agentId, agentMetadata } of orphanedTaskIds) {
- await handleOrphanedTask(taskId, agentId, getTask, { agentMetadata });
+ await handleOrphanedTask(taskId, agentId, getTask, {
+ agentMetadata,
+ interrupted: interruptedByRestart.has(agentId),
+ });
}
+ // Consume the marker. Doing it AFTER the retry pass (not before) means a crash
+ // mid-sweep leaves it in place and the next boot still classifies these agents
+ // correctly; re-reading a stale marker is harmless because the sweep only ever
+ // looks at agents still marked `running`.
+ if (interruptedByRestart.size > 0) await clearHostShutdownMarker();
+
// Trigger evaluation to spawn new agents for retried tasks
if (cleanedCount > 0) {
emitLog('info', `Cleaned up ${cleanedCount} orphaned agents, triggering evaluation`, { cleanedCount });
@@ -674,8 +707,12 @@ export async function cleanupOrphanedAgents() {
* @param {object} [options.agentMetadata] - the dead agent's registered metadata
* (`isWorktree` / `sourceWorkspace` / `worktreeBranch` / `workspacePath`), used
* to work out whether its branch or worktree is worth resuming.
+ * @param {boolean} [options.interrupted] - the run died because PortOS itself was
+ * restarted (identified from the host-shutdown marker), not because the agent
+ * failed. Such a run is requeued immediately WITHOUT charging orphan-retry
+ * budget or arming the orphan cooldown — see the retry-budget note below (#3202).
*/
-export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null } = {}) {
+export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null, interrupted = false } = {}) {
const task = await getTaskByIdFn(taskId).catch(() => null);
if (!task) {
emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });
@@ -715,8 +752,19 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
return;
}
- // Get current retry count from task metadata
- const retryCount = (Number(task.metadata?.orphanRetryCount) || 0) + 1;
+ // Get current retry count from task metadata.
+ //
+ // Retry budget and the cooldown exist to stop a task that keeps KILLING ITS OWN
+ // agent from spawning forever. A PortOS host restart is not that: the agent was
+ // healthy and PortOS took it down (#3202). Charging it a retry — and arming the
+ // 30-minute cooldown — punishes the task for our maintenance, and three routine
+ // restarts were enough to exhaust the budget and block the task outright. So an
+ // interrupted run costs no retry and arms no cooldown; it just requeues with a
+ // resume pointer. `MAX_TOTAL_SPAWNS` still applies, so nothing can spawn
+ // unboundedly even under a restart loop.
+ const retryCount = interrupted
+ ? (Number(task.metadata?.orphanRetryCount) || 0)
+ : (Number(task.metadata?.orphanRetryCount) || 0) + 1;
const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
const taskType = task.taskType || 'user';
@@ -726,13 +774,21 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
// Enforce cooldown between orphan retries
const lastOrphanedAt = task.metadata?.lastOrphanedAt ? new Date(task.metadata.lastOrphanedAt).getTime() : 0;
const cooldownRemaining = lastOrphanedAt ? ORPHAN_RETRY_COOLDOWN_MS - (Date.now() - lastOrphanedAt) : 0;
- const inCooldown = cooldownRemaining > 0;
+ const inCooldown = !interrupted && cooldownRemaining > 0;
+
+ // An interrupted run is exempt from the orphan ceiling for the same reason it
+ // is exempt from the counter: it isn't one of the failures the ceiling counts.
+ // `totalExceeded` still gates it, so a restart loop can't spawn without bound.
+ const withinOrphanBudget = interrupted || retryCount < MAX_ORPHAN_RETRIES;
- if (retryCount < MAX_ORPHAN_RETRIES && !totalExceeded && !inCooldown) {
- emitLog('info', `Resetting orphaned task ${taskId} for retry (attempt ${retryCount}/${MAX_ORPHAN_RETRIES}, total spawns ${totalSpawns}/${MAX_TOTAL_SPAWNS})`, {
+ if (withinOrphanBudget && !totalExceeded && !inCooldown) {
+ emitLog('info', interrupted
+ ? `Resuming task ${taskId} interrupted by a PortOS restart (no retry charged; total spawns ${totalSpawns}/${MAX_TOTAL_SPAWNS})`
+ : `Resetting orphaned task ${taskId} for retry (attempt ${retryCount}/${MAX_ORPHAN_RETRIES}, total spawns ${totalSpawns}/${MAX_TOTAL_SPAWNS})`, {
taskId,
retryCount,
totalSpawns,
+ interrupted,
maxRetries: MAX_ORPHAN_RETRIES
});
@@ -748,13 +804,27 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
return {};
});
+ // An interrupted run records WHAT happened without touching the orphan
+ // bookkeeping: `lastOrphanedAt` stays as-is so a later genuine orphan's
+ // cooldown is still measured from the last genuine orphan, not from our
+ // restart.
+ const recoveryMetadata = interrupted
+ ? {
+ lastInterruptedAt: new Date().toISOString(),
+ lastInterruptedAgentId: agentId,
+ interruptedByRestart: true,
+ }
+ : {
+ orphanRetryCount: retryCount,
+ lastOrphanedAt: new Date().toISOString(),
+ lastOrphanedAgentId: agentId,
+ };
+
await updateTask(taskId, {
status: 'pending',
metadata: {
...task.metadata,
- orphanRetryCount: retryCount,
- lastOrphanedAt: new Date().toISOString(),
- lastOrphanedAgentId: agentId,
+ ...recoveryMetadata,
...resumePatch
}
}, taskType);
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index af85589d2d..9090f37b93 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -78,6 +78,10 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
resolveTaskResumePatch: vi.fn().mockResolvedValue({})
}));
vi.mock('./agentFinalization.js', () => ({ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('../lib/hostShutdown.js', () => ({
+ readHostShutdownMarker: vi.fn().mockResolvedValue(null),
+ clearHostShutdownMarker: vi.fn().mockResolvedValue(undefined),
+}));
vi.mock('./agentRunnerSync.js', () => ({ syncRunnerAgents: vi.fn().mockResolvedValue(0) }));
vi.mock('./agentRunnerOutputBatchers.js', () => ({ flushRunnerOutputBatcher: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));
@@ -98,6 +102,8 @@ import { updateTask, addTask, getTaskById } from './cos.js';
import { updateAgent } from './cosAgents.js';
import { pauseAgentViaRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
+import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
+import { completeAgent as markAgentComplete } from './cos.js';
import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
@@ -852,3 +858,110 @@ describe('orphan retries resume what the dead run left behind', () => {
expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
});
});
+
+// A PortOS restart kills every server-owned agent. Charging those runs the same
+// retry budget as a self-inflicted crash meant three routine restarts blocked the
+// task outright — and the second restart in the reported reproduction landed it in
+// the 30-minute orphan cooldown instead of resuming it (#3202).
+describe('host-restart interruptions are not charged orphan-retry budget (#3202)', () => {
+ const deadMetadata = { isWorktree: true, sourceWorkspace: '/repo', worktreeBranch: 'cos/task-1/agent-dead' };
+ const deadAgent = { id: 'agent-dead', status: 'running', pid: null, taskId: 'task-1', metadata: deadMetadata };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgents.mockResolvedValue([deadAgent]);
+ resolveTaskResumePatch.mockResolvedValue({ existingBranch: 'cos/task-1/agent-dead', resumedFromAgentId: 'agent-dead' });
+ readHostShutdownMarker.mockResolvedValue(null);
+ activeAgents.clear();
+ runnerAgents.clear();
+ });
+
+ const requeuedMetadata = () => updateTask.mock.calls.at(-1)[1].metadata;
+
+ it('requeues an interrupted run without incrementing orphanRetryCount or stamping lastOrphanedAt', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ metadata: { orphanRetryCount: 1, lastOrphanedAt: '2020-01-01T00:00:00.000Z' },
+ });
+ readHostShutdownMarker.mockResolvedValue({ at: '2026-07-29T00:00:00.000Z', signal: 'SIGTERM', agentIds: ['agent-dead'] });
+
+ await cleanupOrphanedAgents();
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
+ const metadata = requeuedMetadata();
+ // Budget untouched: same count, and the cooldown clock is NOT re-armed —
+ // a later genuine orphan still measures its cooldown from the last genuine one.
+ expect(metadata.orphanRetryCount).toBe(1);
+ expect(metadata.lastOrphanedAt).toBe('2020-01-01T00:00:00.000Z');
+ // ...but the interruption IS recorded, and the run stays resumable.
+ expect(metadata.interruptedByRestart).toBe(true);
+ expect(metadata.lastInterruptedAgentId).toBe('agent-dead');
+ expect(metadata.existingBranch).toBe('cos/task-1/agent-dead');
+ });
+
+ it('resumes an interrupted run even at the orphan-retry ceiling', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ metadata: { orphanRetryCount: 3, totalSpawnCount: 3 },
+ });
+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGINT', agentIds: ['agent-dead'] });
+
+ await cleanupOrphanedAgents();
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('bypasses the orphan cooldown for an interrupted run', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ // Orphaned a minute ago — an ordinary orphan would be blocked on cooldown.
+ metadata: { orphanRetryCount: 1, lastOrphanedAt: new Date(Date.now() - 60_000).toISOString() },
+ });
+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-dead'] });
+
+ await cleanupOrphanedAgents();
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
+ expect(requeuedMetadata().blockedCategory).toBeUndefined();
+ });
+
+ it('still charges an agent NOT named in the marker (a genuine orphan alongside an interrupted one)', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ metadata: { orphanRetryCount: 1 },
+ });
+ // Marker names a DIFFERENT agent — this one really did die on its own.
+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-other'] });
+
+ await cleanupOrphanedAgents();
+
+ const metadata = requeuedMetadata();
+ expect(metadata.orphanRetryCount).toBe(2);
+ expect(metadata.lastOrphanedAt).toEqual(expect.any(String));
+ expect(metadata.interruptedByRestart).toBeUndefined();
+ });
+
+ it('flags the interruption on the agent record and consumes the marker', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-dead'] });
+
+ await cleanupOrphanedAgents();
+
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-dead', expect.objectContaining({
+ success: false,
+ interruptedByRestart: true,
+ error: expect.stringContaining('restart'),
+ }));
+ expect(clearHostShutdownMarker).toHaveBeenCalled();
+ });
+
+ it('leaves the marker alone when it names nobody (nothing to reclassify)', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+
+ await cleanupOrphanedAgents();
+
+ expect(clearHostShutdownMarker).not.toHaveBeenCalled();
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ interruptedByRestart: false }));
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 1a2ab881d7..0a04ac5e65 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -19,6 +19,7 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';
+import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
@@ -405,6 +406,19 @@ export async function spawnTuiAgent({
const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {
if (finalized) return;
+ // PortOS is going down. Whatever path got here — the PTY exiting under
+ // TreeKill, the idle reaper, a paste that failed because the shell died —
+ // the cause is the host restart, not the agent, so there is no outcome to
+ // record. Abandoning instead of finalizing is what keeps an interrupted run
+ // from being written down as completed AND keeps its worktree (which
+ // finalize's cleanup would delete) intact for the resume (#3202).
+ //
+ // An agent that already wrote its `.agent-done` sentinel is the exception:
+ // that IS a valid completion signal, so it finalizes normally.
+ if (isHostShuttingDown() && !sentinelPresent()) {
+ await abandonForHostShutdown();
+ return;
+ }
finalized = true;
const agentData = activeAgents.get(agentId);
@@ -548,6 +562,52 @@ export async function spawnTuiAgent({
}
};
+ /**
+ * Abandon the run because PortOS itself is going down (#3202).
+ *
+ * Deliberately NOT `finish()`: finalizing here would record an outcome for a
+ * run that never reached one, and its cleanup path removes the `.agent-done`
+ * sentinel and hands the worktree to `cleanupWorktreeFn` — destroying exactly
+ * the state a resume needs. So this only stops the machinery and flushes what
+ * was captured; the agent record stays `running` and the worktree stays on
+ * disk. The next boot's orphan sweep reads the host-shutdown marker, sees this
+ * agent named in it, and requeues the task as *interrupted* — resumable, and
+ * without charging it orphan-retry budget.
+ *
+ * Sets `finalized` so every other path (idle reaper, sentinel poll, paste
+ * retry) becomes a no-op for the rest of this process's life.
+ */
+ const abandonForHostShutdown = async () => {
+ if (finalized) return;
+ finalized = true;
+
+ const agentData = activeAgents.get(agentId);
+ if (agentData?.idleTimer) clearInterval(agentData.idleTimer);
+ if (agentData?.promptTimer) clearInterval(agentData.promptTimer);
+ if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);
+ if (pasteEnterTimer) { clearInterval(pasteEnterTimer); pasteEnterTimer = null; }
+ if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }
+ if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }
+ if (maxRuntimeTimer) { clearTimeout(maxRuntimeTimer); maxRuntimeTimer = null; }
+ if (wrapUpTimer) { clearTimeout(wrapUpTimer); wrapUpTimer = null; }
+ postPasteBuffer = null;
+
+ appendLine('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');
+ // Flush what the PTY produced before the teardown so the post-mortem
+ // transcript isn't missing its final seconds.
+ await drainLines().catch(() => {});
+ await drainRaw().catch(() => {});
+ // Best-effort UI breadcrumb. The record stays `running` on purpose — boot
+ // recovery owns the transition — so this only refines the phase label.
+ await updateAgent(agentId, { metadata: { phase: 'interrupted', interruptedBy: HOST_SHUTDOWN_REASON } })
+ .catch(err => emitLog('warn', `Could not mark TUI agent ${agentId} interrupted: ${err.message}`, { agentId }));
+ emitLog('warn', `TUI agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
+ // NOTE: the activeAgents entry is intentionally left in place. The shutdown
+ // handler reads that map to build the host-shutdown marker, and the PTY can
+ // exit before that write runs — deleting here would drop this agent from the
+ // marker and get it misclassified as an ordinary orphan on the next boot.
+ };
+
const handleData = async (data) => {
// EventEmitter listeners run outside the request lifecycle — a rejection
// here on Node ≥15 will kill the process unless we catch locally. The
@@ -658,14 +718,29 @@ export async function spawnTuiAgent({
}
};
- const handleExit = async ({ exitCode, killed }) => {
+ const handleExit = async ({ exitCode, killed, signal = null }) => {
if (finalized) return;
+ // A host restart reaches here as a plain PTY exit (pm2's TreeKill walks
+ // portos-server's descendants), which the `success` reading below would
+ // record as a completed run. finish() intercepts that case — see its
+ // host-shutdown guard (#3202).
const code = typeof exitCode === 'number' ? exitCode : killed ? 130 : 0;
+ // A signal-terminated shell reports the wait-status exit code — 0 for a
+ // plain SIGTERM/SIGHUP — so `code === 0` alone cannot mean "finished
+ // normally". Treat any signal as an abnormal end. This is the backstop for
+ // the case the host-shutdown guard can't cover: a SIGKILL'd or crashed
+ // portos-server never runs its shutdown handler, so the flag is never set,
+ // yet the agent's PTY still dies with us (#3202).
+ const signaled = signal !== null && signal !== undefined && signal !== 0;
await finish({
- success: code === 0 && !killed,
+ success: code === 0 && !killed && !signaled,
exitCode: code,
- error: killed ? 'TUI shell session was killed' : null,
- reason: killed ? 'shell-killed' : 'shell-exit'
+ error: killed
+ ? 'TUI shell session was killed'
+ : signaled
+ ? `TUI shell session was terminated by signal ${signal} — the run was cut short, not completed`
+ : null,
+ reason: killed ? 'shell-killed' : signaled ? 'shell-signaled' : 'shell-exit'
});
};
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 576ba99df1..32aeb035b9 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -185,6 +185,9 @@ import * as cosAgents from './cosAgents.js';
import * as gitService from './git.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
import { MAX_RUNTIME_WRAP_UP_GRACE_MS } from '../lib/tuiHandshake.js';
+// Real module, not a mock: the flag is a plain process-local boolean, so driving
+// it directly exercises the same code path production does.
+import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
describe('agent TUI spawning', () => {
it('builds a codex TUI command without a model flag for the configured-default sentinel', () => {
@@ -1833,6 +1836,93 @@ describe('spawnTuiAgent runtime', () => {
expect(outputTxtWrites).toContain('Implemented the fix.');
expect(outputTxtWrites).toContain('https://example.com/pr/42');
});
+
+ // ── 11. A PortOS host restart is an interruption, never a completion ─────────
+ //
+ // Reported in #3202: `pm2 restart portos-server` TreeKills the agent's PTY.
+ // node-pty reports that as exit code 0, so `success: code === 0 && !killed`
+ // recorded a run that had produced nothing as SUCCESSFUL — and worse, finalize
+ // handed the worktree to cleanupWorktreeFn, destroying the state a resume
+ // needs. Both halves are asserted here.
+ describe('host restart (#3202)', () => {
+ afterEach(() => resetHostShutdownFlagForTests());
+
+ it('abandons instead of finalizing when the PTY dies during shutdown', async () => {
+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ const spawnPromise = runSpawn({ helpers: { cleanupWorktreeFn, isTruthyMetaFn: (v) => !!v } });
+ await flushMicrotasks();
+
+ markHostShuttingDown();
+ // Exactly what pm2's TreeKill looks like from node-pty: a clean exit code.
+ await capturedOnExit({ exitCode: 0, killed: false });
+ await flushMicrotasks();
+ await spawnPromise;
+
+ // No outcome recorded, and — critically — the worktree is left alone.
+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
+ expect(cleanupWorktreeFn).not.toHaveBeenCalled();
+ // The record stays `running`; only the phase label is refined, so boot
+ // recovery still sees it as an agent to reconcile from the marker.
+ expect(vi.mocked(cosAgents.updateAgent).mock.calls.some(
+ ([, patch]) => patch?.metadata?.phase === 'interrupted' && patch?.metadata?.interruptedBy === 'host-shutdown'
+ )).toBe(true);
+ });
+
+ it('still finalizes as success when the agent had already written its sentinel', async () => {
+ vi.mocked(existsSync).mockReturnValue(true);
+ vi.mocked(readFile).mockImplementation(async (p) =>
+ typeof p === 'string' && p.endsWith('.agent-done') ? '## Summary\nDone.' : ''
+ );
+
+ const spawnPromise = runSpawn({ workspacePath: '/tmp/ws' });
+ await flushMicrotasks();
+
+ markHostShuttingDown();
+ await capturedOnExit({ exitCode: 0, killed: false });
+ await flushMicrotasks();
+ await spawnPromise;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', success: true })
+ );
+ });
+
+ // The backstop for a SIGKILL'd or crashed portos-server, which never runs its
+ // shutdown handler — so the in-process flag is never set, and the only
+ // evidence left is node-pty's `signal`.
+ it('records a signal-terminated PTY as a failure even with exit code 0', async () => {
+ const spawnPromise = runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnExit({ exitCode: 0, killed: false, signal: 15 });
+ await flushMicrotasks();
+ await spawnPromise;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ completionReason: 'shell-signaled',
+ error: expect.stringContaining('signal 15'),
+ })
+ );
+ });
+
+ // Guard against over-correcting: a TUI that genuinely exits 0 on its own,
+ // outside a shutdown and with no signal, keeps its prior success semantics.
+ it('leaves an ordinary clean exit alone', async () => {
+ const spawnPromise = runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnExit({ exitCode: 0, killed: false, signal: null });
+ await flushMicrotasks();
+ await spawnPromise;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ success: true, completionReason: 'shell-exit' })
+ );
+ });
+ });
});
// Issue #2074 — the idle reaper must extend its grace while a swarm orchestrator
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 2afbf101ef..571a2fc850 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -28,6 +28,7 @@ import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
import { createAIToolkit } from '../lib/aiToolkit/index.js';
import { verifyCollectionVersions } from '../lib/collectionStore.js';
import { conflictJournalStore } from '../lib/conflictJournal.js';
+import { markHostShuttingDown, writeHostShutdownMarker } from '../lib/hostShutdown.js';
import { setUserCatalogTypes } from '../lib/catalogTypes.js';
import { runMigrations } from '../../scripts/run-migrations.js';
@@ -45,6 +46,10 @@ import { initSpawner } from './subAgentSpawner.js';
import { initCertRenewer } from './certRenewer.js';
import * as cos from './cos.js';
+// Side-effect-free shared state module — importing it here does NOT pull in the
+// agent-lifecycle orchestrator graph (that's why activeAgents lives in its own
+// leaf module), so the shutdown handler can read the live agent set cheaply.
+import { activeAgents } from './agentState.js';
import * as automationScheduler from './automationScheduler.js';
import * as agentActionExecutor from './agentActionExecutor.js';
import * as telegram from './telegram.js';
@@ -844,6 +849,11 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
const shutdown = async (signal) => {
if (shuttingDown) return;
shuttingDown = true;
+ // Latch the host-shutdown flag BEFORE anything can await. pm2's TreeKill
+ // signals the whole descendant tree, so a server-owned agent PTY can exit
+ // microseconds from now — and its exit handler must already know the PTY
+ // died because PortOS is going down, not because the agent finished (#3202).
+ markHostShuttingDown();
// Diagnostic context for the shutdown trigger. ppid tells us whether the
// signal came from PM2 (parent is the PM2 god process), a TTY (parent is
// the user's shell), or some external orchestrator. pm_* env vars are set
@@ -864,6 +874,19 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// other handle has closed we should exit immediately, not wait out the timer.
forceExitTimer.unref?.();
+ // Record which agents this process owned, so the NEXT boot's orphan sweep can
+ // tell "PortOS was restarted out from under a healthy agent" apart from "the
+ // agent's own process died" and skip the retry-budget/cooldown penalty for a
+ // fault the agent didn't cause (#3202). Only `activeAgents` — the ones whose
+ // child processes live in THIS process's tree — belong here; runner-mode
+ // agents are owned by portos-cos and survive this restart untouched.
+ // Best-effort and bounded: a marker we fail to write only degrades recovery
+ // to the pre-existing orphan path.
+ await withGrace('Host-shutdown marker', 1500, (finish) =>
+ writeHostShutdownMarker({ agentIds: [...activeAgents.keys()], signal })
+ .then((wrote) => finish(wrote ? '✅ Host-shutdown marker written' : null),
+ (err) => finish(`⚠️ Host-shutdown marker failed: ${err.message}`, true)));
+
// Drop existing long-lived sockets (SSE + keep-alive) up front so the closes
// below don't wait on connections that never end on their own.
try { httpServer.closeAllConnections?.(); } catch (e) { console.error(`⚠️ closeAllConnections(http): ${e.message}`); }
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
new file mode 100644
index 0000000000..1de592e902
--- /dev/null
+++ b/server/services/bootstrap.shutdown.test.js
@@ -0,0 +1,76 @@
+/**
+ * Source contract for the graceful-shutdown handler's host-restart bookkeeping (#3202).
+ *
+ * `registerShutdownHandlers` has no unit harness — it wires real signal handlers
+ * around a live HTTP/Socket.IO/DB stack — so the two ordering guarantees it must
+ * uphold are asserted against the source instead. Both are the kind of thing a
+ * well-meaning refactor silently breaks:
+ *
+ * 1. `markHostShuttingDown()` runs BEFORE the handler's first `await`. pm2's
+ * TreeKill signals the whole tree at once, so an agent PTY can exit during
+ * the very first await — and if the flag isn't latched yet, that exit is
+ * recorded as a completed run, which is the bug this issue is about.
+ * 2. The marker is built from `activeAgents` (the agents THIS process owns),
+ * not from `getActiveAgentIds()` — runner-mode agents live in portos-cos,
+ * survive the restart untouched, and must never be named as interrupted.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SRC = readFileSync(join(__dirname, 'bootstrap.js'), 'utf-8').replace(/\r\n/g, '\n');
+
+/**
+ * Slice out a function body by brace-matching from its opening `{`. A fixed
+ * character window would read into whatever happens to follow — the trap noted
+ * in the repo's other source-contract guards.
+ */
+function bodyAfter(source, anchor) {
+ const start = source.indexOf(anchor);
+ expect(start, `anchor not found: ${anchor}`).toBeGreaterThan(-1);
+ let i = source.indexOf('{', start);
+ let depth = 0;
+ for (let j = i; j < source.length; j += 1) {
+ if (source[j] === '{') depth += 1;
+ else if (source[j] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(i, j + 1);
+ }
+ }
+ throw new Error(`unbalanced braces after: ${anchor}`);
+}
+
+/** Blank out comments so prose about `await` isn't mistaken for code. */
+const stripComments = (s) => s
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length))
+ .replace(/\/\/[^\n]*/g, (m) => ' '.repeat(m.length));
+
+describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
+ const shutdownBody = bodyAfter(SRC, 'const shutdown = async (signal) =>');
+
+ it('latches the host-shutdown flag before the handler awaits anything', () => {
+ const code = stripComments(shutdownBody);
+ const latchAt = code.indexOf('markHostShuttingDown()');
+ expect(latchAt, 'markHostShuttingDown() is not called in shutdown()').toBeGreaterThan(-1);
+
+ const firstAwaitAt = code.search(/\bawait\b/);
+ // No await at all would also satisfy the ordering requirement.
+ if (firstAwaitAt > -1) expect(latchAt).toBeLessThan(firstAwaitAt);
+ });
+
+ it('writes the marker from activeAgents only — runner agents survive the restart', () => {
+ expect(shutdownBody).toContain('writeHostShutdownMarker(');
+ expect(shutdownBody).toMatch(/writeHostShutdownMarker\(\{\s*agentIds:\s*\[\.\.\.activeAgents\.keys\(\)\]/);
+ // getActiveAgentIds() folds in runnerAgents — naming those would tell the
+ // next boot that portos-cos-owned agents were interrupted when they weren't.
+ expect(shutdownBody).not.toContain('getActiveAgentIds');
+ });
+
+ it('writes the marker before the process exits', () => {
+ expect(shutdownBody.indexOf('writeHostShutdownMarker('))
+ .toBeLessThan(shutdownBody.indexOf('process.exit(0)'));
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index 33a76bcb8b..03d26bfdce 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -205,12 +205,20 @@ export function createShellSession(socket, options = {}) {
});
// Handle pty exit
- ptyProcess.onExit(({ exitCode }) => {
- console.log(`🐚 Shell session ${sessionId.slice(0, 8)} exited (code: ${exitCode})`);
+ //
+ // `signal` is forwarded, not discarded: on POSIX a shell killed by a signal
+ // reports the wait-status exit code (0 for a plain SIGTERM/SIGHUP) with the
+ // signal number in the separate `signal` field. Dropping it made a
+ // pm2-treekilled agent shell indistinguishable from one that exited cleanly —
+ // which is how an agent whose PTY was torn down got recorded as a successful
+ // run (#3202). Consumers that care (the TUI spawner's onExit) MUST treat a
+ // non-null `signal` as an abnormal end regardless of `exitCode`.
+ ptyProcess.onExit(({ exitCode, signal }) => {
+ console.log(`🐚 Shell session ${sessionId.slice(0, 8)} exited (code: ${exitCode}${signal ? `, signal: ${signal}` : ''})`);
const session = shellSessions.get(sessionId);
shellSessions.delete(sessionId);
session?.socket?.emit('shell:exit', { sessionId, code: exitCode });
- if (session) runHook('onExit', session, session.onExit, { exitCode });
+ if (session) runHook('onExit', session, session.onExit, { exitCode, signal: signal ?? null });
broadcastSessionList();
});
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index b05bb0006c..bd0f601f5e 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -164,7 +164,19 @@ describe('createShellSession', () => {
await flushMicrotasks();
expect(shell.getSession(id)).toBeNull();
expect(socket.emit).toHaveBeenCalledWith('shell:exit', { sessionId: id, code: 0 });
- expect(onExit).toHaveBeenCalledWith({ exitCode: 0 });
+ expect(onExit).toHaveBeenCalledWith({ exitCode: 0, signal: null });
+ });
+
+ // node-pty reports a signal-terminated shell as exitCode 0 with the signal in a
+ // separate field. Forwarding it is what lets the TUI spawner tell "the shell
+ // finished" from "pm2 killed the shell out from under a running agent" (#3202).
+ it('on PTY exit: forwards node-pty signal to the onExit hook', async () => {
+ const onExit = vi.fn();
+ const id = shell.createShellSession(makeSocket(), { onExit });
+ ptyInstances[0].emitExit({ exitCode: 0, signal: 15 });
+ await flushMicrotasks();
+ expect(shell.getSession(id)).toBeNull();
+ expect(onExit).toHaveBeenCalledWith({ exitCode: 0, signal: 15 });
});
it('schedules initialCommand write after delay', () => {