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

refactor([issue-3202]): dedupe run teardown, reuse shared test helpers, cover the direct-CLI path

[._.]/ Adam Eivy9dc9ac8e924c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fd50507d60..484544ed60 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,7 +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.
+- **[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 — terminal-based or headless — 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, one you terminated yourself is still recorded as terminated, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them running 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/hostShutdown.js b/server/lib/hostShutdown.js
index c89a627ed6..b16122391e 100644
--- a/server/lib/hostShutdown.js
+++ b/server/lib/hostShutdown.js
@@ -45,6 +45,8 @@ export const HOST_SHUTDOWN_REASON = 'host-shutdown';
*/
export const hostShutdownMarkerPath = () => join(PATHS.cos, 'host-shutdown.json');
+const isNonEmptyString = (value) => typeof value === 'string' && !!value;
+
// 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;
@@ -79,37 +81,32 @@ export function resetHostShutdownFlagForTests() {
* @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))];
+ const ids = [...new Set(agentIds.filter(isNonEmptyString))];
// 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;
+ return atomicWrite(hostShutdownMarkerPath(), { at: new Date().toISOString(), signal, agentIds: ids })
+ .then(
+ () => { console.log(`🛑 Host shutdown marker written for ${ids.length} live agent(s)`); return true; },
+ (err) => { console.error(`❌ Failed to write host-shutdown marker: ${err.message}`); return false; },
+ );
}
/**
- * Read the marker left by the previous process.
+ * Read the marker left by the previous process. Returns null when there is
+ * none, otherwise `{ at, signal, agentIds }`.
*
- * 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.
+ * `agentIds` is ALWAYS an array of non-empty strings — that's the one field
+ * with a production consumer, and boot recovery runs before everything else, so
+ * a truncated/garbled marker has to degrade to "no agents were interrupted"
+ * rather than throw. `allowArray: false` does the rest of the shape check:
+ * `readJSONFile` already rejects an unparseable file AND any root that isn't a
+ * `{…}` object, so a falsy result is the only failure left to test for.
*/
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) : [],
- };
+ const raw = await readJSONFile(hostShutdownMarkerPath(), null, { logError: false, allowArray: false });
+ if (!raw) return null;
+ return { ...raw, agentIds: Array.isArray(raw.agentIds) ? raw.agentIds.filter(isNonEmptyString) : [] };
}
/**
diff --git a/server/lib/hostShutdown.test.js b/server/lib/hostShutdown.test.js
index e7419bbb70..592029e261 100644
--- a/server/lib/hostShutdown.test.js
+++ b/server/lib/hostShutdown.test.js
@@ -10,19 +10,24 @@
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { mkdtemp, rm, readFile, writeFile, mkdir } from 'fs/promises';
-import { tmpdir } from 'os';
+import { rm, readFile, writeFile, mkdir } from 'fs/promises';
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/.
+// never touches the install's real data/. The `dataRoot` FUNCTION form is what
+// makes this work with a per-test temp dir: the mock factory is hoisted above
+// beforeEach, so the proxy has to resolve the root lazily on each PATHS read.
vi.mock('./fileUtils.js', async (importOriginal) => {
- const actual = await importOriginal();
- return { ...actual, get PATHS() { return { ...actual.PATHS, cos: globalThis.__hostShutdownTestCos }; } };
+ const { makePathsProxy } = await import('./mockPathsDataRoot.js');
+ return makePathsProxy(await importOriginal(), {
+ dataRoot: () => tmpRoot,
+ extraOverrides: (root) => ({ cos: root }),
+ });
});
+const { createTempDataRoot } = await import('./mockPathsDataRoot.js');
const {
markHostShuttingDown,
isHostShuttingDown,
@@ -34,15 +39,13 @@ const {
HOST_SHUTDOWN_REASON,
} = await import('./hostShutdown.js');
-beforeEach(async () => {
- tmpRoot = await mkdtemp(join(tmpdir(), 'portos-host-shutdown-'));
- globalThis.__hostShutdownTestCos = tmpRoot;
+beforeEach(() => {
+ tmpRoot = createTempDataRoot('portos-host-shutdown-');
resetHostShutdownFlagForTests();
});
afterEach(async () => {
await rm(tmpRoot, { recursive: true, force: true });
- delete globalThis.__hostShutdownTestCos;
});
describe('in-process shutdown flag', () => {
@@ -124,13 +127,10 @@ describe('a damaged marker degrades to "nobody was interrupted"', () => {
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'] }));
+ it('drops non-string entries inside a valid agentIds array', async () => {
+ await writeRaw(JSON.stringify({ at: 'x', agentIds: ['a1', null, 7, '', 'a2'] }));
- const marker = await readHostShutdownMarker();
- expect(marker.at).toBeNull();
- expect(marker.signal).toBeNull();
- expect(marker.agentIds).toEqual(['a1']);
+ expect((await readHostShutdownMarker()).agentIds).toEqual(['a1', 'a2']);
});
});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 092b32d43e..69a3a08b55 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -34,6 +34,7 @@ import { resolveForgeTokenEnv } from './git.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
+import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -804,6 +805,30 @@ export async function spawnDirectly({
return;
}
+ // PortOS is going down and took this child with it (pm2's TreeKill walks
+ // portos-server's descendants). Abandon rather than finalize, for the same
+ // reasons as the TUI path (#3202): finalizing would charge the task's
+ // failure budget — and possibly file an investigation task — for a fault the
+ // agent didn't have, and its cleanup hands the worktree to `cleanupWorktreeFn`,
+ // which removes a clean tree, discarding the state a resume needs. Leaving
+ // the record `running` is what lets the next boot's orphan sweep see this
+ // agent in the host-shutdown marker and requeue it as interrupted.
+ // The transcript is already flushed and output.txt written above.
+ // A user-terminated run still finalizes, so it's recorded as such rather
+ // than resurrected by the requeue.
+ if (isHostShuttingDown() && !terminatedByUser) {
+ outputBatcher.push('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');
+ emitLog('warn', `Agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
+ await Promise.all([
+ outputBatcher.flush().catch(() => {}),
+ updateAgent(agentId, { metadata: { phase: 'interrupted', interruptedBy: HOST_SHUTDOWN_REASON } })
+ .catch(err => emitLog('warn', `Could not mark agent ${agentId} interrupted: ${err.message}`, { agentId })),
+ ]);
+ // activeAgents entry left in place — the shutdown handler reads that map
+ // to name the agents in the host-shutdown marker.
+ return;
+ }
+
// Release lane + complete execution tracking BEFORE the error-analysis +
// state-write chain — neither call blocks on I/O, but lanes serialize
// related work. Fall back to outer scope when activeAgents was cleared by
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 32f024f435..d381d7f63d 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -90,6 +90,9 @@ vi.mock('child_process', () => ({
}));
import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';
+// Real module — 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';
import { spawn } from 'child_process';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
@@ -798,4 +801,58 @@ describe('stream error containment', () => {
// The removed singular key must NOT be passed.
expect(opts.reviewer).toBeUndefined();
});
+
+ // pm2's TreeKill takes direct-CLI children down with portos-server exactly as
+ // it does TUI PTYs (#3202). Finalizing here would charge the task's failure
+ // budget — and possibly file an investigation task — for a fault the agent
+ // didn't have, and hand its worktree to cleanup, discarding the state a resume
+ // needs. The run is abandoned instead, leaving the record `running` for the
+ // next boot's orphan sweep to reconcile from the host-shutdown marker.
+ describe('host restart (#3202)', () => {
+ // The outer beforeEach re-sets implementations but not call history, and the
+ // mocks are module-scoped — clear so "was it called" reads only this test.
+ beforeEach(async () => {
+ const { finalizeAgent } = await import('./agentFinalization.js');
+ finalizeAgent.mockClear();
+ cosAgentsMocks.updateAgent.mockClear();
+ });
+
+ afterEach(() => resetHostShutdownFlagForTests());
+
+ const runToClose = async (args) => {
+ spawnDirectly(args);
+ await new Promise((r) => setTimeout(r, 10));
+ markHostShuttingDown();
+ fakeProcess.emit('close', 0);
+ await new Promise((r) => setTimeout(r, 80));
+ };
+
+ it('abandons without finalizing or cleaning up the worktree', async () => {
+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ const { finalizeAgent } = await import('./agentFinalization.js');
+
+ await runToClose({ ...minimalArgs, cleanupWorktreeFn });
+
+ expect(finalizeAgent).not.toHaveBeenCalled();
+ expect(cleanupWorktreeFn).not.toHaveBeenCalled();
+ // The breadcrumb the orphan sweep falls back on when no marker names the agent.
+ expect(cosAgentsMocks.updateAgent).toHaveBeenCalledWith(
+ minimalArgs.agentId,
+ { metadata: { phase: 'interrupted', interruptedBy: 'host-shutdown' } },
+ );
+ });
+
+ it('still finalizes a user-terminated run so it is recorded as terminated, not resurrected', async () => {
+ const { userTerminatedAgents } = await import('./agentState.js');
+ const { finalizeAgent } = await import('./agentFinalization.js');
+ userTerminatedAgents.add(minimalArgs.agentId);
+
+ await runToClose({ ...minimalArgs });
+
+ expect(finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ terminatedByUser: true, success: false }),
+ );
+ userTerminatedAgents.delete(minimalArgs.agentId);
+ });
+ });
});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index efd89c617e..50a2bca7e6 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -24,7 +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 { readHostShutdownMarker, clearHostShutdownMarker, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
@@ -566,12 +566,12 @@ export async function cleanupOrphanedAgents() {
// 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 shutdownMarker = await readHostShutdownMarker();
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,
+ shutdownAt: shutdownMarker?.at ?? null,
});
}
@@ -628,9 +628,11 @@ export async function cleanupOrphanedAgents() {
? '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.
+ // Post-mortem telemetry on the agent record (nothing reads it yet —
+ // the human-visible distinction is the `error` string above). Worth
+ // persisting because an infrastructure interruption and a real agent
+ // fault are indistinguishable from the process's point of view once
+ // the record is written.
interruptedByRestart: interrupted,
});
cleanedCount++;
@@ -707,12 +709,21 @@ 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).
+ * @param {boolean|null} [options.interrupted] - the run died because PortOS itself
+ * was restarted, 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). Pass it when the caller knows (the orphan sweep
+ * reads the host-shutdown marker); leave it null to derive from `agentMetadata`.
*/
-export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null, interrupted = false } = {}) {
+export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null, interrupted = null } = {}) {
+ // Callers that watched the agent die (the orphan sweep, which reads the
+ // host-shutdown marker) say so explicitly. The ones that didn't —
+ // `resetOrphanedTasks`, post-restart completion recovery — fall back to the
+ // breadcrumb the abandon path stamped on the agent itself, so an interrupted
+ // run is still recognized no matter which recovery path reaches it first.
+ // Without this, correctness depended on `cleanupOrphanedAgents` happening to
+ // run before `resetOrphanedTasks` in cos.js's boot sequence.
+ const wasInterrupted = interrupted ?? (agentMetadata?.interruptedBy === HOST_SHUTDOWN_REASON);
const task = await getTaskByIdFn(taskId).catch(() => null);
if (!task) {
emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });
@@ -762,9 +773,8 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
// 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 priorOrphanRetries = Number(task.metadata?.orphanRetryCount) || 0;
+ const retryCount = wasInterrupted ? priorOrphanRetries : priorOrphanRetries + 1;
const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
const taskType = task.taskType || 'user';
@@ -774,21 +784,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 = !interrupted && cooldownRemaining > 0;
+ const inCooldown = !wasInterrupted && 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;
+ const withinOrphanBudget = wasInterrupted || retryCount < MAX_ORPHAN_RETRIES;
if (withinOrphanBudget && !totalExceeded && !inCooldown) {
- emitLog('info', interrupted
+ emitLog('info', wasInterrupted
? `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,
+ interrupted: wasInterrupted,
maxRetries: MAX_ORPHAN_RETRIES
});
@@ -807,17 +817,22 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
// 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
+ // restart. The genuine-orphan branch clears `interruptedByRestart` — the
+ // metadata spread below carries every prior key forward, so leaving it set
+ // would make a task that was once restarted look permanently restart-
+ // interrupted, through this orphan and every later one.
+ const now = new Date().toISOString();
+ const recoveryMetadata = wasInterrupted
? {
- lastInterruptedAt: new Date().toISOString(),
+ lastInterruptedAt: now,
lastInterruptedAgentId: agentId,
interruptedByRestart: true,
}
: {
orphanRetryCount: retryCount,
- lastOrphanedAt: new Date().toISOString(),
+ lastOrphanedAt: now,
lastOrphanedAgentId: agentId,
+ interruptedByRestart: false,
};
await updateTask(taskId, {
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 9090f37b93..278be90f88 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -78,7 +78,10 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
resolveTaskResumePatch: vi.fn().mockResolvedValue({})
}));
vi.mock('./agentFinalization.js', () => ({ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined) }));
-vi.mock('../lib/hostShutdown.js', () => ({
+// Only the two I/O functions are stubbed — HOST_SHUTDOWN_REASON stays real so
+// the breadcrumb value the tests assert can't drift from the one production writes.
+vi.mock('../lib/hostShutdown.js', async (importOriginal) => ({
+ ...(await importOriginal()),
readHostShutdownMarker: vi.fn().mockResolvedValue(null),
clearHostShutdownMarker: vi.fn().mockResolvedValue(undefined),
}));
@@ -939,7 +942,39 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
const metadata = requeuedMetadata();
expect(metadata.orphanRetryCount).toBe(2);
expect(metadata.lastOrphanedAt).toEqual(expect.any(String));
- expect(metadata.interruptedByRestart).toBeUndefined();
+ expect(metadata.interruptedByRestart).toBe(false);
+ });
+
+ // The metadata spread carries every prior key forward, so a task interrupted
+ // once would otherwise read as restart-interrupted forever.
+ it('clears a stale interruptedByRestart flag when the next orphan is genuine', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ metadata: { interruptedByRestart: true, lastInterruptedAt: '2026-07-29T00:00:00.000Z' },
+ });
+
+ await cleanupOrphanedAgents();
+
+ expect(requeuedMetadata().interruptedByRestart).toBe(false);
+ });
+
+ // Callers that didn't watch the agent die (resetOrphanedTasks, post-restart
+ // completion recovery) pass no verdict — the breadcrumb the abandon path
+ // stamped on the agent supplies it, so correctness no longer rests on
+ // cleanupOrphanedAgents happening to run first in cos.js's boot sequence.
+ it('derives the interruption from the agent breadcrumb when the caller passes no verdict', async () => {
+ getTaskById.mockResolvedValue({
+ id: 'task-1', taskType: 'user', status: 'in_progress',
+ metadata: { orphanRetryCount: 1 },
+ });
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {
+ agentMetadata: { ...deadMetadata, interruptedBy: 'host-shutdown' },
+ });
+
+ const metadata = requeuedMetadata();
+ expect(metadata.orphanRetryCount).toBe(1);
+ expect(metadata.interruptedByRestart).toBe(true);
});
it('flags the interruption on the agent record and consumes the marker', async () => {
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 0a04ac5e65..c4b506098b 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -404,6 +404,35 @@ export async function spawnTuiAgent({
for (const line of truncated.split('\n')) appendLine(line);
};
+ /**
+ * Stop everything this run armed, and hand back the agent record so the
+ * caller doesn't need a second map lookup.
+ *
+ * Shared by the two paths that end a run — `finish()` (records an outcome) and
+ * `abandonForHostShutdown()` (records none). Every timer here is created inside
+ * this closure, so a teardown site that falls behind leaks an interval holding
+ * the closure and the PTY handle alive; this file has already grown two new
+ * timers since it was written (maxRuntime + wrapUp), which is exactly the drift
+ * a single teardown prevents.
+ */
+ const stopRunMachinery = () => {
+ 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; }
+ // Release the post-paste accumulator even when the run ends mid-paste-window.
+ // The pasteEnterTimer's own cleanup path nulls this too, but if the run ends
+ // from elsewhere (shell-exit, command-not-found, user termination, a host
+ // restart) that timer never gets a chance to run.
+ postPasteBuffer = null;
+ return agentData;
+ };
+
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
@@ -413,28 +442,18 @@ export async function spawnTuiAgent({
// 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()) {
+ // Two exceptions finalize normally. An agent that already wrote its
+ // `.agent-done` sentinel has given a valid completion signal. And a run the
+ // user terminated must reach finalizeAgent to be recorded `user-terminated`
+ // — abandoning it would leave the record `running` with no such mark, and
+ // boot recovery's user-terminated skip would miss it and resurrect the run.
+ if (isHostShuttingDown() && !sentinelPresent() && !userTerminatedAgents.has(agentId)) {
await abandonForHostShutdown();
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; }
- // Release the post-paste accumulator even when finalize fires mid-paste-
- // window. The pasteEnterTimer's own cleanup path nulls this too, but if
- // finalize comes from elsewhere (shell-exit, command-not-found, user
- // termination) the timer never gets a chance to run.
- postPasteBuffer = null;
+ const agentData = stopRunMachinery();
// Ingest the .agent-done sentinel BEFORE draining, so its markdown summary
// lands in outputBuffer/output.txt regardless of WHICH path finalized the
@@ -578,34 +597,29 @@ export async function spawnTuiAgent({
* retry) becomes a no-op for the rest of this process's life.
*/
const abandonForHostShutdown = async () => {
- if (finalized) return;
+ // No `finalized` guard: finish() — the only caller — already returned if it
+ // was set, and this sets it below.
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;
+ stopRunMachinery();
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.
+ // Concurrent, not sequential: nothing awaits this function (it runs off the
+ // PTY-exit handler, racing the shutdown handler's own process.exit), so the
+ // shorter the critical path the more of the transcript actually lands. The
+ // three targets are independent — output.txt + the state record, raw.txt, and
+ // the metadata patch — and the two that share the state lock still serialize
+ // on it. `phase` is a breadcrumb only: the record stays `running` on purpose,
+ // because boot recovery owns the transition.
+ await Promise.all([
+ drainLines().catch(() => {}),
+ drainRaw().catch(() => {}),
+ updateAgent(agentId, { metadata: { phase: 'interrupted', interruptedBy: HOST_SHUTDOWN_REASON } })
+ .catch(err => emitLog('warn', `Could not mark TUI agent ${agentId} interrupted: ${err.message}`, { agentId })),
+ ]);
+ // NOTE: the activeAgents entry is intentionally left in place — the shutdown
+ // handler reads that map to name the agents in the host-shutdown marker, and
+ // there is no reason to shrink it on the way out.
};
const handleData = async (data) => {
@@ -731,17 +745,13 @@ export async function spawnTuiAgent({
// 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 && !signaled,
- exitCode: code,
- 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'
- });
+ const signaled = !!signal;
+ const outcome = killed
+ ? { error: 'TUI shell session was killed', reason: 'shell-killed' }
+ : signaled
+ ? { error: `TUI shell session was terminated by signal ${signal} — the run was cut short, not completed`, reason: 'shell-signaled' }
+ : { error: null, reason: 'shell-exit' };
+ await finish({ success: code === 0 && !killed && !signaled, exitCode: code, ...outcome });
};
// Repo-owner-pinned GH_TOKEN for the agent's own `gh pr create` (see
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 571a2fc850..572eceff89 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -882,10 +882,12 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// 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)));
+ // Started here (the agent snapshot must be taken before anything can await)
+ // but awaited just before exit, so a stalled filesystem spends none of the
+ // graceful budget ahead of the teardown below. writeHostShutdownMarker logs
+ // both outcomes itself and never rejects, so `finish` needs no message.
+ const markerWritten = withGrace('Host-shutdown marker', 1500, (finish) =>
+ writeHostShutdownMarker({ agentIds: [...activeAgents.keys()], signal }).then(() => finish()));
// 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.
@@ -921,6 +923,7 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
console.warn('ℹ️ DB pool close not available; skipping DB shutdown');
}
+ await markerWritten;
clearTimeout(forceExitTimer);
process.exit(0);
};
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 1de592e902..3ec27d8f68 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -19,40 +19,28 @@ import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
+// The shared brace-walker + comment stripper. Hand-rolling either is what
+// server/lib/README.md explicitly warns against — the naive "first `{` after the
+// anchor" version silently slices the wrong region the moment a signature grows
+// a destructured or defaulted parameter.
+import { extractDeclaration, stripCommentsAndNormalize } from '../lib/mirrorParity.js';
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}`);
-}
+describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
+ const shutdownBody = extractDeclaration(SRC, 'shutdown');
-/** 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));
+ it('finds the shutdown handler at all', () => {
+ expect(shutdownBody, 'const shutdown = … not found in bootstrap.js').toBeTruthy();
+ });
-describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
- const shutdownBody = bodyAfter(SRC, 'const shutdown = async (signal) =>');
+ // Comments stripped for every assertion below: this file's own prose talks
+ // about `await` and `getActiveAgentIds`, and matching that would be matching
+ // the explanation rather than the code.
+ const code = stripCommentsAndNormalize(shutdownBody || '');
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);
@@ -61,16 +49,24 @@ describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
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\(\)\]/);
+ it('snapshots the agent set from activeAgents only — runner agents survive the restart', () => {
+ expect(code).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');
+ expect(code).not.toContain('getActiveAgentIds');
});
- it('writes the marker before the process exits', () => {
- expect(shutdownBody.indexOf('writeHostShutdownMarker('))
- .toBeLessThan(shutdownBody.indexOf('process.exit(0)'));
+ // The write is kicked off early (so the agent snapshot is taken before any
+ // await can let the set change) but awaited last, so a slow disk spends none
+ // of the graceful budget ahead of the socket/HTTP teardown.
+ it('starts the marker write before the teardown and awaits it before exiting', () => {
+ const startAt = code.indexOf('writeHostShutdownMarker(');
+ const awaitAt = code.indexOf('await markerWritten');
+ const exitAt = code.indexOf('process.exit(0)');
+
+ expect(startAt).toBeGreaterThan(-1);
+ expect(startAt).toBeLessThan(code.indexOf('closeAllConnections'));
+ expect(awaitAt).toBeGreaterThan(startAt);
+ expect(awaitAt).toBeLessThan(exitAt);
});
});