Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: give the CLI and TUI spawners one shared agent finalize sequence (#6619)
[._.]/ Adam Eivyd71ef4ad0546
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 0f3e48ac7a..00c60b989f 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -23,7 +23,8 @@ import { completeAgentRun } from './agentRunTracking.js';import { appendRunEvent } from './agentRunEventLog.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';-import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';+import { finalizeAgentRunCommon } from './agentRunFinalize.js';+import { activeAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import { safeJSONParse, PATHS, writeFileGuarded } from '../lib/fileUtils.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';@@ -43,7 +44,7 @@ import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prClaimWasVerified } from '../lib/prDisposition.js';import { resolvePrOwnership } from '../lib/slashdoInvocation.js';import { doneSentinelPath } from '../lib/agentSentinel.js';-import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';import { isPublicReviewRestrictedProfile } from '../lib/agentExecutionProfiles.js';@@ -327,6 +328,20 @@ export async function getClaudeSettingsEnv() {return _claudeSettingsEnvCache;}+/**+ * What went wrong with a direct-CLI run, or `null` when there is nothing to+ * analyze — a successful run, or a private security assessment whose transcript+ * must not be read (its findings stay in the local assessment archive).+ *+ * The raw stream buffer is preferred over the display buffer: it still carries+ * the full stream-json payload, error details included. A fallback signal the+ * run already raised (a usage-limit hit, say) outranks a keyword sweep.+ */+function resolveCliErrorAnalysis({ finalSuccess, task, model, rawStreamBuffer, outputBuffer, immediateFallbackAnalysis }) {+ if (finalSuccess || isPrivateSecurityTask(task)) return null;+ return immediateFallbackAnalysis || analyzeAgentFailure(rawStreamBuffer || outputBuffer, task, model);+}+/*** Spawn agent directly (fallback when runner not available).* `isTruthyMetaFn` is the lifecycle's shared metadata predicate, passed in by@@ -759,6 +774,54 @@ export async function spawnDirectly({}};+ /**+ * The close handler threw — outside any request lifecycle, so nothing above+ * will catch it and the process now SURVIVES rather than restarting. Leave+ * nothing held: free a lane the throw beat, and persist a terminal record so+ * the agent/run aren't stuck `running` with no live process to finish them.+ *+ * A paused agent was already persisted + lane-released by `markAgentPaused`, so+ * it gets ONLY the in-memory cleanup — finalizing it as failed here would+ * overwrite the paused state and break a later resume.+ *+ * Each persistence call is guarded on its own so a failure can't re-crash.+ */+ const recoverFromCloseHandlerFailure = async (handlerErr, { code, laneReleased, outputBuffer }) => {+ console.error(`❌ Agent ${agentId} close handler error: ${handlerErr.message}`);+ if (pausedAgents.has(agentId)) {+ consumePausedAgentExit(agentId);+ unregisterSpawnedAgent(claudeProcess.pid);+ activeAgents.delete(agentId);+ return;+ }+ if (!laneReleased) {+ try {+ releaseAgentLane({+ agentId,+ success: false,+ exitCode: code,+ executionId,+ laneName,+ errorExecutionMessage: `Agent close handler error: ${handlerErr.message}`,+ });+ } catch (releaseErr) {+ console.error(`❌ Agent ${agentId} lane release failed during recovery: ${releaseErr.message}`);+ }+ }+ try {+ await completeAgent(agentId, { success: false, error: `Close handler error: ${handlerErr.message}` });+ } catch (completeErr) {+ console.error(`❌ Agent ${agentId} completeAgent failed during recovery: ${completeErr.message}`);+ }+ try {+ await completeAgentRun(runId, isPrivateSecurityTask(task) ? 'Private security assessment failed; inspect its local assessment archive.' : outputBuffer, 1, 0, { message: handlerErr.message, category: 'close-handler-error' });+ } catch (runErr) {+ console.error(`❌ Agent ${agentId} completeAgentRun failed during recovery: ${runErr.message}`);+ }+ unregisterSpawnedAgent(claudeProcess.pid);+ activeAgents.delete(agentId);+ };+handleClose = async (code) => {// Runs outside the request lifecycle — a throw from outputBatcher.flush,// analyzeAgentFailure, or finalizeAgent would re-escape this async handler@@ -781,27 +844,16 @@ export async function spawnDirectly({agentData.killTimer = null;}- const terminatedByUser = userTerminatedAgents.has(agentId);- if (terminatedByUser) userTerminatedAgents.delete(agentId);// This run's own sentinel (see doneSentinelName) — a worktree-less agent// shares its workspace and must not read a sibling's signal as its own.const sentinelPath = doneSentinelPath(cwd, agentId);const completionSentinelPresent = !!sentinelPath && existsSync(sentinelPath);- const completedBeforeHostShutdown = isHostShuttingDown() && completionSentinelPresent;-- // If the user terminated the agent, force success=false even if the- // process happened to exit 0 in the race window — otherwise the run is- // recorded as successful while the task remains blocked. Mirrors the TUI- // `finish` path's `finalSuccess = terminatedByUser ? false : success`.// A mid-stream fallback signal (e.g. usage-limit hit) kills the CLI; if it// races to exit 0, don't record success or the fallback/retry never fires.// A completion sentinel written before host shutdown is also authoritative:// TreeKill may surface its otherwise-completed child with a null exit code.- // Mirrors the runner path (`runner.js`) and the TUI finish() handling.- const finalSuccess = terminatedByUser- ? false- : ((success || completedBeforeHostShutdown) && !immediateFallbackAnalysis);- const finalError = terminatedByUser ? 'Agent terminated by user' : null;+ const completedBeforeHostShutdown = isHostShuttingDown() && completionSentinelPresent;+ const rawSuccess = (success || completedBeforeHostShutdown) && !immediateFallbackAnalysis;// Drain any queued transcript writes before reading/appending outputBuffer// for finalization — a still-pending stdout/stderr write would otherwise@@ -838,33 +890,27 @@ export async function spawnDirectly({await writeFileGuarded(outputFile, outputBuffer).catch(() => {});- // Paused agents are finalized in `markAgentPaused` (which already released- // the lane + execution). Return BEFORE `releaseAgentLane` below — re-running- // it on the same executionId logs a spurious "Invalid state transition".- // Mirrors the TUI path's pause-check-before-releaseAgentLane ordering.- if (pausedAgents.has(agentId)) {- consumePausedAgentExit(agentId);- if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);- activeAgents.delete(agentId);- 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 `cleanupAgentWorktree`,- // 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 (shouldAbandonForHostShutdown({+ // The teardown both in-process spawners share: paused early return, then+ // the host-shutdown abandon gate, the user-termination consume, the+ // final success/error derivation, and the lane release (done before the+ // error-analysis + state-write chain, since lanes serialize related work).+ // The transcript is already flushed and output.txt written above, so every+ // early-out below still leaves a complete record. See agentRunFinalize.js.+ const finalizeOutcome = finalizeAgentRunCommon({+ agentId,+ agentData,+ success: rawSuccess,+ error: null,+ exitCode: code,+ duration,+ executionId,+ laneName,sentinelPresent: completionSentinelPresent,- terminatedByUser,- paused: pausedAgents.has(agentId),- })) {+ });++ if (finalizeOutcome.outcome === 'paused') return;++ if (finalizeOutcome.outcome === 'abandoned') {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([@@ -877,24 +923,12 @@ export async function spawnDirectly({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- // killAgent before close fired.- releaseAgentLane({- agentId,- success: finalSuccess,- duration,- exitCode: code,- executionId: agentData?.executionId || executionId,- laneName: agentData?.laneName || laneName,- errorExecutionMessage: finalError || undefined,- });+ const { finalSuccess, finalError, terminatedByUser } = finalizeOutcome;laneReleased = true;- // Use raw stream buffer for error analysis (contains full JSON with error details)- const analysisBuffer = rawStreamBuffer || outputBuffer;- const errorAnalysis = finalSuccess || isPrivateSecurityTask(task) ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));+ const errorAnalysis = resolveCliErrorAnalysis({+ finalSuccess, task, model, rawStreamBuffer, outputBuffer, immediateFallbackAnalysis,+ });// Every CLI agent that is a real coding harness drives its own push → PR →// review → merge (#3733): a slashdo-capable Claude runs `/simplify` +@@ -922,9 +956,8 @@ export async function spawnDirectly({// try/finally so a throw from finalizeAgent still runs the local cleanup// (the shared completion dispatch, pid unregister, activeAgents delete).- // Mirrors the TUI path's pattern.- // See the TUI path: a PR-claim downgrade must reach cleanup, or a run that- // opened no PR is cleaned up as a success and loses its retry state (#3358).+ // A PR-claim downgrade must reach cleanup, or a run that opened no PR is+ // cleaned up as a success and loses its retry state (#3358).let cleanupSuccess = finalSuccess;try {const finalized = await finalizeAgent({@@ -968,50 +1001,7 @@ export async function spawnDirectly({activeAgents.delete(agentId);}} catch (handlerErr) {- console.error(`❌ Agent ${agentId} close handler error: ${handlerErr.message}`);- // A paused agent was already persisted + lane-released by markAgentPaused;- // if the throw beat the pause guard above, do ONLY the in-memory cleanup- // (mirrors the normal pause path) — finalizing it as failed here would- // overwrite the paused state and break later resume.- if (pausedAgents.has(agentId)) {- consumePausedAgentExit(agentId);- unregisterSpawnedAgent(claudeProcess.pid);- activeAgents.delete(agentId);- } else {- // If the throw beat releaseAgentLane, the lane/execution is still held.- // The process now survives instead of restarting, so a held lane would- // block later tasks indefinitely — release it on the recovery path too.- if (!laneReleased) {- try {- releaseAgentLane({- agentId,- success: false,- exitCode: code,- executionId,- laneName,- errorExecutionMessage: `Agent close handler error: ${handlerErr.message}`,- });- } catch (releaseErr) {- console.error(`❌ Agent ${agentId} lane release failed during recovery: ${releaseErr.message}`);- }- }- // Persist a terminal failure record so the agent/run don't stay stuck as- // running with no live process to finish them — the process now survives- // instead of restarting. Mirrors the error handler's completion path;- // each call is guarded so a persistence failure can't re-crash.- try {- await completeAgent(agentId, { success: false, error: `Close handler error: ${handlerErr.message}` });- } catch (completeErr) {- console.error(`❌ Agent ${agentId} completeAgent failed during recovery: ${completeErr.message}`);- }- try {- await completeAgentRun(runId, isPrivateSecurityTask(task) ? 'Private security assessment failed; inspect its local assessment archive.' : outputBuffer, 1, 0, { message: handlerErr.message, category: 'close-handler-error' });- } catch (runErr) {- console.error(`❌ Agent ${agentId} completeAgentRun failed during recovery: ${runErr.message}`);- }- unregisterSpawnedAgent(claudeProcess.pid);- activeAgents.delete(agentId);- }+ await recoverFromCloseHandlerFailure(handlerErr, { code, laneReleased, outputBuffer });}};diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex 548457c1ec..2e15a06747 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -35,6 +35,7 @@ const CLUSTER = ['subAgentSpawner.js','cosAgentLifecycle.js','agentFinalization.js',+ 'agentRunFinalize.js','agentSummaryExtraction.js','agentRunnerSync.js','agentRunnerOutputBatchers.js',@@ -129,11 +130,11 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {});it('keeps the extracted leaves free of back-edges into the cluster orchestrators', () => {- // These four exist ONLY to be depended on. If any of them grows an import of+ // These exist ONLY to be depended on. If any of them grows an import of// an orchestrator, the cycle comes straight back — fail loudly and early// rather than waiting for the graph walk above to go red for a subtler reason.const orchestrators = ['agentLifecycle.js', 'agentCliSpawning.js', 'agentTuiSpawning.js', 'agentManagement.js', 'subAgentSpawner.js'];- for (const leaf of ['agentFinalization.js', 'agentSummaryExtraction.js', 'agentRunnerSync.js', 'agentRunnerOutputBatchers.js']) {+ for (const leaf of ['agentFinalization.js', 'agentRunFinalize.js', 'agentSummaryExtraction.js', 'agentRunnerSync.js', 'agentRunnerOutputBatchers.js']) {const back = (graph.get(leaf) || []).filter(dep => orchestrators.includes(dep));expect(back, `${leaf} must not import ${back.join(', ')}`).toEqual([]);}diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex a10b37d63b..3f358ca320 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -40,6 +40,7 @@ const normalizeEol = (s) => s.replace(/\r\n/g, '\n');const AGENT_CLI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentCliSpawning.js'), 'utf-8'));const AGENT_TUI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentTuiSpawning.js'), 'utf-8'));const AGENT_LIFECYCLE_SRC = normalizeEol(readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8'));+const AGENT_RUN_FINALIZE_SRC = normalizeEol(readFileSync(join(__dirname, 'agentRunFinalize.js'), 'utf-8'));const AGENT_MANAGEMENT_SRC = normalizeEol(readFileSync(join(__dirname, 'agentManagement.js'), 'utf-8'));// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl). Mocked@@ -1425,10 +1426,16 @@ describe('pause-release adapter registration', () => {describe('close-handler skip-finalization — source contract', () => {// Helper: extract the body of a function from source text.// Returns everything from the function's opening brace to its matched closing brace.- function extractFunctionBody(src, fnSignatureSubstring) {+ // `bodyAnchor` (optional) is a substring searched forward from the signature;+ // the body's opening brace is the first `{` after IT rather than after the+ // signature. Needed for a function whose parameter list is destructured — its+ // `{` would otherwise brace-match as the whole body.+ function extractFunctionBody(src, fnSignatureSubstring, bodyAnchor = null) {const fnStart = src.indexOf(fnSignatureSubstring);if (fnStart === -1) return null;- const braceStart = src.indexOf('{', fnStart);+ const searchFrom = bodyAnchor ? src.indexOf(bodyAnchor, fnStart) : fnStart;+ if (searchFrom === -1) return null;+ const braceStart = src.indexOf('{', searchFrom);let depth = 0;for (let i = braceStart; i < src.length; i++) {if (src[i] === '{') depth++;@@ -1437,66 +1444,56 @@ describe('close-handler skip-finalization — source contract', () => {return null;}- it('CLI close handler guards with pausedAgents.has and returns before finalizeAgent', () => {- // The real body lives in `handleClose`, not in the `claudeProcess.on('close')`- // registration — that registration is a forwarding shim attached in the same- // tick as spawn() so a fast-exiting child's close event isn't dropped while- // the async setup is still yielding (#5791).- const closeIdx = AGENT_CLI_SRC.indexOf('handleClose = async (code)');- expect(closeIdx, 'CLI handleClose handler must exist').toBeGreaterThan(-1);-- // Extract the full callback body via brace-balancing rather than a fixed- // slice — a try/catch crash-guard wrapper can push finalizeAgent past any- // fixed window (see #1825).- const closeBody = extractFunctionBody(AGENT_CLI_SRC, 'handleClose = async (code)');- expect(closeBody, 'CLI handleClose handler body must be extractable').toBeTruthy();-- // Guard present- expect(closeBody).toMatch(/pausedAgents\.has\(agentId\)/);-- // Guard appears BEFORE finalizeAgent in the close body- const guardPos = closeBody.indexOf('pausedAgents.has(agentId)');- const finalizePos = closeBody.indexOf('finalizeAgent(');- expect(guardPos, 'pause guard must precede finalizeAgent call').toBeLessThan(finalizePos);-- // There is a `return` inside the pause guard block before finalizeAgent- // (the guard block ends with a bare `return;` or `return` before reaching finalize)- const guardBlock = closeBody.slice(guardPos, finalizePos);- expect(guardBlock).toMatch(/\breturn\b/);- });-- it('TUI finish() guards with pausedAgents.has and returns before finalizeAgent', () => {- // finish() is defined as a const arrow-function inside spawnTuiAgent.- // The signature is: const finish = async ({ ... }) => {- // We need the body that starts at `=> {`, not the destructured params `{`.- const finishIdx = AGENT_TUI_SRC.indexOf('const finish = async');- expect(finishIdx, 'finish function must exist in agentTuiSpawning').toBeGreaterThan(-1);-- // Find the `=> {` that opens the arrow body (past the parameter list)- const arrowIdx = AGENT_TUI_SRC.indexOf('=> {', finishIdx);- expect(arrowIdx, "'=> {' of finish() must exist").toBeGreaterThan(finishIdx);+ // The pause guard moved out of both spawners into `finalizeAgentRunCommon`+ // (#6619) — they used to hold two hand-mirrored copies of it, running their+ // paused and host-shutdown gates in OPPOSITE order. The behavioral counterpart+ // of these checks is the paired 'shared finalize sequence (#6619)' suite in+ // agentCliSpawning.test.js / agentTuiSpawning.test.js, which drives a real+ // paused exit through both spawners. What only a source check can pin is the+ // ORDERING — that each spawner consults the shared sequence and bails on its+ // 'paused' verdict BEFORE it can reach finalizeAgent.+ for (const [label, src, signature, bodyAnchor] of [+ ['CLI close handler', AGENT_CLI_SRC, 'handleClose = async (code)', null],+ ['TUI finish()', AGENT_TUI_SRC, 'const finish = async', '=> '],+ ]) {+ it(`${label} routes through finalizeAgentRunCommon and returns on its paused verdict before finalizeAgent`, () => {+ const body = extractFunctionBody(src, signature, bodyAnchor);+ expect(body, `${label} body must be extractable`).toBeTruthy();++ const sequencePos = body.indexOf('finalizeAgentRunCommon(');+ expect(sequencePos, `${label} must run the shared finalize sequence`).toBeGreaterThan(-1);++ const finalizePos = body.indexOf('finalizeAgent(');+ expect(finalizePos, `${label} must still call finalizeAgent`).toBeGreaterThan(-1);+ expect(sequencePos, 'shared finalize sequence must precede finalizeAgent').toBeLessThan(finalizePos);++ // The paused verdict is handled with an early return, before finalize.+ const window = body.slice(sequencePos, finalizePos);+ expect(window, `${label} must bail on the 'paused' outcome`).toMatch(/'paused'[\s\S]*?\breturn\b/);+ });+ }- // Extract body from the arrow body's `{` to its matched closing `}`- const braceStart = arrowIdx + 3; // points at `{`- let depth = 0;- let bodyEnd = braceStart;- for (let i = braceStart; i < AGENT_TUI_SRC.length; i++) {- if (AGENT_TUI_SRC[i] === '{') depth++;- else if (AGENT_TUI_SRC[i] === '}') { depth--; if (depth === 0) { bodyEnd = i; break; } }+ // The canonical order the extraction made explicit: the paused return runs+ // BEFORE the host-shutdown abandon gate, and both precede the lane release.+ // Re-releasing an already-released executionId logs a spurious "Invalid state+ // transition"; abandoning a paused run would skip the bookkeeping that the+ // paused path owns. Nothing enforced this while the sequence was mirrored.+ it('finalizeAgentRunCommon checks pausedAgents before the abandon gate and the lane release', () => {+ const body = extractFunctionBody(AGENT_RUN_FINALIZE_SRC, 'export function finalizeAgentRunCommon(', '}) ');+ expect(body, 'finalizeAgentRunCommon must exist and be extractable').toBeTruthy();++ const guardPos = body.indexOf('pausedAgents.has(agentId)');+ expect(guardPos, 'pause guard must be present').toBeGreaterThan(-1);++ for (const [label, marker] of [+ ['host-shutdown abandon gate', 'shouldAbandonAgentRun('],+ ['lane release', 'releaseAgentLane('],+ ]) {+ const pos = body.indexOf(marker);+ expect(pos, `${marker} must exist in finalizeAgentRunCommon`).toBeGreaterThan(-1);+ expect(guardPos, `pause guard must precede the ${label}`).toBeLessThan(pos);+ expect(body.slice(guardPos, pos), `pause guard must return before the ${label}`).toMatch(/\breturn\b/);}- const finishBody = AGENT_TUI_SRC.slice(braceStart, bodyEnd + 1);-- // Guard present- expect(finishBody).toMatch(/pausedAgents\.has\(agentId\)/);-- // Guard appears BEFORE finalizeAgent- const guardPos = finishBody.indexOf('pausedAgents.has(agentId)');- const finalizePos = finishBody.indexOf('finalizeAgent(');- expect(guardPos, 'pause guard must precede finalizeAgent in finish()').toBeLessThan(finalizePos);-- // There is a return inside the guard block before reaching finalizeAgent- const guardBlock = finishBody.slice(guardPos, finalizePos);- expect(guardBlock).toMatch(/\breturn\b/);});// The behavioral counterpart of this guard lives indiff --git a/server/services/agentRunFinalize.js b/server/services/agentRunFinalize.jsnew file mode 100644index 0000000000..c2341ae6fd--- /dev/null+++ b/server/services/agentRunFinalize.js@@ -0,0 +1,142 @@+/**+ * The finalize sequence both in-process agent spawners share.+ *+ * The direct-CLI spawner's `handleClose` and the TUI spawner's `finish` end a+ * run through the same six steps — a paused early return, the host-shutdown+ * abandon gate, consuming the user-termination marker, deriving the final+ * success/error pair, and releasing the execution lane. They used to hold two+ * hand-mirrored copies of it, ~1,000 lines apart in two of the highest-churn+ * files in the tree, kept in sync by prose comments naming the other file — and+ * running their two gates in OPPOSITE order (#6619).+ *+ * The drift is not cosmetic. Skipping the paused return before+ * `releaseAgentLane` re-releases an already-released `executionId`, which the+ * lane bookkeeping records as a spurious "Invalid state transition"; skipping+ * the `userTerminatedAgents` consume records a run the user killed as a success+ * while its task stays blocked. `shouldAbandonForHostShutdown`+ * (`../lib/hostShutdown.js`) is the precedent — exactly this class of shared+ * decision, extracted after #3202. This is the rest of that sequence.+ *+ * Canonical order: **the paused return runs before the abandon gate.** A paused+ * run can then never reach the abandon path even if `shouldAbandonForHostShutdown`+ * later stops taking `paused`, which makes that argument redundant rather than+ * load-bearing — so neither spawner passes it any more.+ */++import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, unregisterSpawnedAgent } from './agentState.js';+import { releaseAgentLane } from './agentFinalization.js';+import { shouldAbandonForHostShutdown } from '../lib/hostShutdown.js';++/** Recorded on a run the user killed, whatever exit code the process reported. */+export const USER_TERMINATED_ERROR = 'Agent terminated by user';++/**+ * Should this exit be preserved for restart recovery instead of finalized?+ *+ * Wraps `shouldAbandonForHostShutdown` with the canonical precedence: a paused+ * run is never abandoned (it has its own don't-finalize path, which owns the+ * paused bookkeeping), and the user-termination marker is read from the live+ * registry rather than passed in, so both call sites cannot disagree about it.+ *+ * Exported for the TUI path, which must consult the gate BEFORE its sentinel+ * ingest / merge-gate check — work that must not run while the host is going+ * down. Everything after that point goes through `finalizeAgentRunCommon`.+ *+ * @param {object} params+ * @param {string} params.agentId+ * @param {boolean} [params.sentinelPresent] - the run wrote its own `.agent-done`+ * @returns {boolean}+ */+export function shouldAbandonAgentRun({ agentId, sentinelPresent = false }) {+ if (pausedAgents.has(agentId)) return false;+ return shouldAbandonForHostShutdown({+ sentinelPresent,+ terminatedByUser: userTerminatedAgents.has(agentId),+ });+}++/**+ * Run the shared finalize sequence and report which path the run took.+ *+ * On `'finalize'` the execution lane has already been released — deliberately+ * BEFORE the caller's error-analysis / state-write chain, since neither call+ * blocks on I/O but lanes serialize related work. `'paused'` and `'abandoned'`+ * release nothing; the caller returns without finalizing, doing only its own+ * teardown (the TUI's `abandonForHostShutdown`, the CLI's inline equivalent).+ *+ * @param {object} params+ * @param {string} params.agentId+ * @param {object|null} [params.agentData] - the `activeAgents` record, when the+ * caller already looked it up; its `executionId`/`laneName`/`pid` win over the+ * outer-scope fallbacks, which cover an entry cleared before the exit landed.+ * @param {boolean} [params.success] - the caller's verdict BEFORE the+ * user-termination override (the CLI folds its sentinel/fallback reading in).+ * @param {string|null} [params.error] - the caller's error, same proviso.+ * @param {number|null} [params.exitCode]+ * @param {number} [params.duration]+ * @param {string|null} [params.executionId] - outer-scope fallback+ * @param {string|null} [params.laneName] - outer-scope fallback+ * @param {boolean} [params.sentinelPresent] - the run wrote its own `.agent-done`+ * @param {string} [params.errorExecutionFallback] - execution-tracking message for+ * a run that failed without one of its own+ * @returns {{outcome: 'paused'}+ * | {outcome: 'abandoned'}+ * | {outcome: 'finalize', finalSuccess: boolean, finalError: string|null, terminatedByUser: boolean}}+ */+export function finalizeAgentRunCommon({+ agentId,+ agentData = null,+ success = false,+ error = null,+ exitCode = null,+ duration = 0,+ executionId = null,+ laneName = null,+ sentinelPresent = false,+ errorExecutionFallback = undefined,+}) {+ // Paused agents were already finalized by `markAgentPaused`, which released+ // the lane + execution. Return BEFORE `releaseAgentLane` below — re-running it+ // on the same executionId logs a spurious "Invalid state transition".+ if (pausedAgents.has(agentId)) {+ consumePausedAgentExit(agentId);+ // Prefer the live registry (the TUI reads it here) and fall back to the+ // caller's record for an entry `killAgent` cleared before the exit landed.+ const pid = activeAgents.get(agentId)?.pid ?? agentData?.pid;+ if (pid) unregisterSpawnedAgent(pid);+ activeAgents.delete(agentId);+ return { outcome: 'paused' };+ }++ // PortOS is going down and took this child with it (pm2's TreeKill walks+ // portos-server's descendants). Abandoning rather than finalizing is what+ // keeps the interruption from being written down as an outcome — finalizing+ // would charge the task's failure budget for a fault the agent didn't have,+ // and its cleanup hands the worktree to `cleanupAgentWorktree`, discarding the+ // state a resume needs. The caller leaves the record `running` so the next+ // boot's orphan sweep can requeue it from the host-shutdown marker (#3202).+ if (shouldAbandonAgentRun({ agentId, sentinelPresent })) {+ return { outcome: 'abandoned' };+ }++ const terminatedByUser = userTerminatedAgents.has(agentId);+ if (terminatedByUser) userTerminatedAgents.delete(agentId);++ // Force failure on a user-terminated run even when the process happened to+ // exit 0 in the race window — otherwise it is recorded as successful while+ // the task remains blocked.+ const finalSuccess = terminatedByUser ? false : success;+ const finalError = terminatedByUser ? USER_TERMINATED_ERROR : error;++ releaseAgentLane({+ agentId,+ success: finalSuccess,+ duration,+ exitCode,+ executionId: agentData?.executionId || executionId,+ laneName: agentData?.laneName || laneName,+ errorExecutionMessage: finalError || errorExecutionFallback,+ });++ return { outcome: 'finalize', finalSuccess, finalError, terminatedByUser };+}diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 0845bbe5e4..ff7644e797 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -14,13 +14,14 @@ import { emitLog } from './cosEvents.js';import { updateAgent } from './cosAgentLifecycle.js';import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';-import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';+import { finalizeAgent } from './agentFinalization.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';-import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';+import { activeAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import { PATHS, watchForFile } from '../lib/fileUtils.js';import { resolveAgentCliCwd } from '../lib/spawnCwd.js';import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';-import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { finalizeAgentRunCommon, shouldAbandonAgentRun } from './agentRunFinalize.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';import { prClaimWasVerified, leavesPrForHuman } from '../lib/prDisposition.js';import { resolvePrOwnership } from '../lib/slashdoInvocation.js';@@ -993,6 +994,39 @@ export async function spawnTuiAgent({return agentData;};+ /**+ * Everything this run held, released in one place: its own `.agent-done`+ * sentinel, the shared completion dispatch, the pid registration, the+ * `activeAgents` entry, and the PTY session.+ *+ * Called from `finish()`'s `finally`, so it must run even when `finalizeAgent`+ * threw — a memory-extraction crash would otherwise strand the worktree and+ * the shell session on disk.+ */+ const releaseRunResources = async ({ agentData, cleanupSuccess, prOwnership, prClaimVerified, noChangesToShip }) => {+ // This run's sentinel only — a sibling agent sharing this workspace owns+ // its own file and may still be running.+ if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});++ // Pipeline progression → worktree cleanup with the PR disposition →+ // retry-hold release, in the one owner both in-process spawners share.+ // Caught so a throw there cannot skip the in-memory teardown below — this+ // runs off a PTY exit, outside any request lifecycle.+ await runSpawnerCompletionCleanup({+ agentId,+ task,+ success: cleanupSuccess,+ prOwnership,+ prClaimVerified,+ noChangesToShip,+ outputBuffer: getOutputBuffer(),+ }).catch(err => emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId }));++ if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);+ activeAgents.delete(agentId);+ if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);+ };+const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {// `finalized` alone used to be the whole re-entrancy guard, safe because it// was set SYNCHRONOUSLY as this function's first act. The merge-gate check@@ -1029,11 +1063,7 @@ export async function spawnTuiAgent({// recovery's user-terminated skip would miss it and resurrect the run. And a// run the user paused already has its own don't-finalize branch below, which// owns the paused bookkeeping (pid unregister, activeAgents delete).- if (shouldAbandonForHostShutdown({- sentinelPresent: sentinelPresent(),- terminatedByUser: userTerminatedAgents.has(agentId),- paused: pausedAgents.has(agentId),- })) {+ if (shouldAbandonAgentRun({ agentId, sentinelPresent: sentinelPresent() })) {await abandonForHostShutdown();return;}@@ -1080,35 +1110,39 @@ export async function spawnTuiAgent({await drainLines();await drainRaw();- if (pausedAgents.has(agentId)) {- consumePausedAgentExit(agentId);- const pausedAgentData = activeAgents.get(agentId);- if (pausedAgentData?.pid) unregisterSpawnedAgent(pausedAgentData.pid);- activeAgents.delete(agentId);- return;- }-- const duration = Date.now() - (agentData?.startedAt || Date.now());- const terminatedByUser = userTerminatedAgents.has(agentId);- if (terminatedByUser) userTerminatedAgents.delete(agentId);-- const finalSuccess = terminatedByUser ? false : success;- const finalError = terminatedByUser ? 'Agent terminated by user' : error;-- // Release the lane + complete execution tracking BEFORE the+ // The teardown both in-process spawners share: paused early return, then+ // the host-shutdown abandon gate, the user-termination consume, the final+ // success/error derivation, and the lane release — done before the// potentially-slow error-analysis / completeAgent / processAgentCompletion- // chain — neither call blocks on I/O, but lanes serialize related work- // and we don't want them held longer than necessary.- releaseAgentLane({+ // chain, since lanes serialize related work. See agentRunFinalize.js.+ //+ // The abandon gate is consulted a second time here on purpose: the gate at+ // the top of finish() ran before ingestDoneSentinel and the merge-gate probe,+ // which can take seconds, and a host restart that begins in that window is+ // still an interruption rather than an outcome (#3202).+ const duration = Date.now() - (agentData?.startedAt || Date.now());+ const finalizeOutcome = finalizeAgentRunCommon({agentId,- success: finalSuccess,- duration,+ agentData,+ success,+ error,exitCode,- executionId: agentData?.executionId || executionId,- laneName: agentData?.laneName || laneName,- errorExecutionMessage: finalError || `TUI agent ended: ${reason}`,+ duration,+ executionId,+ laneName,+ sentinelPresent: sentinelPresent(),+ errorExecutionFallback: `TUI agent ended: ${reason}`,});+ if (finalizeOutcome.outcome === 'paused') return;++ if (finalizeOutcome.outcome === 'abandoned') {+ await abandonForHostShutdown();+ return;+ }++ const { finalSuccess, finalError, terminatedByUser } = finalizeOutcome;+// output.txt has already been incrementally appended via the spooler;// do NOT writeFile() it from the output buffer at finalize — the buffer is// capped at OUTPUT_BUFFER_CAP and would silently truncate the on-disk@@ -1181,27 +1215,7 @@ export async function spawnTuiAgent({prClaimVerified = prClaimWasVerified(finalized?.prVerdict);noChangesToShip = finalized?.prVerdict?.noChangesToShip === true;} finally {- // This run's sentinel only — a sibling agent sharing this workspace owns- // its own file and may still be running.- if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});-- // Pipeline progression → worktree cleanup with the PR disposition →- // retry-hold release, in the one owner both in-process spawners share.- // Caught so a throw there cannot skip the in-memory teardown below — this- // runs off a PTY exit, outside any request lifecycle.- await runSpawnerCompletionCleanup({- agentId,- task,- success: cleanupSuccess,- prOwnership,- prClaimVerified,- noChangesToShip,- outputBuffer: getOutputBuffer(),- }).catch(err => emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId }));-- if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);- activeAgents.delete(agentId);- if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);+ await releaseRunResources({ agentData, cleanupSuccess, prOwnership, prClaimVerified, noChangesToShip });}};