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: split the post-restart recovery path out of handleAgentCompletion (#3872)
[._.]/ Adam Eivyc9fe0e9d3851
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e0916759ec..6287d52853 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -46,3 +46,4 @@- The Node version PortOS requires is now written down in exactly one place and checked before anything slow runs. The floor was copied into five sites that could drift apart — both setup scripts, `.nvmrc`, the CI workflows and the README — while the install path the README actually documents (`npm run setup`, `npm start`) checked none of them, so an unsupported Node installed happily for several minutes and then failed inside Vite with an error that never named the cause. `scripts/checkNodeVersion.js` now owns the number (22.12), runs first in the root `setup`, `start` and `dev` scripts so an old Node fails in the first second, and a drift test holds the other sites to it — the shell gates and the README to the floor exactly, `.nvmrc` and CI to at-or-above it, since running CI on 24 while supporting 22.12 is a preference rather than a mistake. All four `package.json` files now declare `engines` as well.- The Pipeline's Reverse Outline map now keeps the selected scene in the URL (`?scene=<id>`) instead of component state, so the open scene detail survives a reload and can be linked to or shared. A stale id — after regenerating the outline, say — falls back to the "click a marker" placeholder rather than a blank card, and regenerating clears the selection outright.- The six "file too large" toasts — album covers, artist portraits, tracks, author headshots, reference audio and OpenClaw attachments — now render their size cap through the shared `formatBytes` helper instead of each dividing by 1024 twice and gluing on "MB". The rendered text gains a space before the unit (`12 MB` rather than `12MB`), which is what the rest of PortOS already shows and what the reference-audio toast already read. The OpenClaw combined-attachment message picked up the same treatment for its decoded-size estimate, so the two limits it can report no longer print their units two different ways.+- The post-restart agent-recovery path is now its own function instead of a 65-line branch inlined at the top of `handleAgentCompletion`, so a change to either it or the live in-memory completion path no longer means reading past the other. The pause guard that path sits behind — the one keeping a stray completion event from cleaning the worktree out from under a later resume — is now pinned by tests that call the real function rather than by a source-text assertion that broke the moment the code moved.diff --git a/server/services/agentCompletionRouting.test.js b/server/services/agentCompletionRouting.test.jsnew file mode 100644index 0000000000..7810203b86--- /dev/null+++ b/server/services/agentCompletionRouting.test.js@@ -0,0 +1,188 @@+/**+ * Behavioral tests for `handleAgentCompletion`'s ROUTER (issue #3872).+ *+ * `handleAgentCompletion` has three mutually exclusive outcomes, picked before+ * any completion work runs:+ *+ * 1. the agent is paused → return immediately, finalize NOTHING (the resume+ * path owns the worktree and the task);+ * 2. the agent is not in `runnerAgents` (server restarted) → hand off to+ * `completeUntrackedAgentFromCosState`, which retires it from persisted+ * cos state without running finalize/worktree cleanup;+ * 3. the agent is live in `runnerAgents` → the full in-memory completion path.+ *+ * Outcome 1 is a data-loss guard: completing a paused agent cleans the worktree+ * and completes the task out from under a later resume. It used to be pinned by+ * a source-grep assertion in `agentManagement.test.js` ("`pausedAgents.has` must+ * appear before `completeAgent(` in the function's source text"), which broke the+ * moment the recovery path was extracted — the only `completeAgent(` in the+ * function moved with it. These tests drive the real exported function instead,+ * so they survive any future extraction and still fail if the guard is removed.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./cos.js', () => ({+ getConfig: vi.fn().mockResolvedValue({}),+ updateTask: vi.fn().mockResolvedValue(true),+ getTaskById: vi.fn().mockResolvedValue(null),+ getAgentRecord: vi.fn().mockResolvedValue(null),+ // The recovery path reaches for this via `await import('./cos.js')`.+ getAgent: vi.fn().mockResolvedValue(null),+}));++vi.mock('./cosAgentLifecycle.js', () => ({+ registerAgent: vi.fn().mockResolvedValue(undefined),+ updateAgent: vi.fn().mockResolvedValue(undefined),+ completeAgent: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('./agentFinalization.js', () => ({+ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined),+ finalizeAgent: vi.fn().mockResolvedValue(undefined),+ releaseAgentLane: vi.fn(),+ stampLiExecutionVerdict: vi.fn(async (update) => update),+}));++vi.mock('./agentManagement.js', () => ({+ handleOrphanedTask: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('./agentWorktreeCleanup.js', () => ({+ cleanupAgentWorktree: vi.fn().mockResolvedValue(undefined),+ releaseRetryHold: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('./agentCompletionCleanup.js', () => ({+ runAgentCompletionCleanup: vi.fn().mockResolvedValue(undefined),+}));++import { handleAgentCompletion } from './agentLifecycle.js';+import { runnerAgents, pausedAgents } from './agentState.js';+import { completeAgent } from './cosAgentLifecycle.js';+import { getAgent, getAgentRecord, getTaskById, updateTask } from './cos.js';+import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';+import { handleOrphanedTask } from './agentManagement.js';++beforeEach(() => {+ vi.clearAllMocks();+ // clearAllMocks does NOT drain a queued `mockResolvedValueOnce` — and the pause+ // tests deliberately leave theirs unconsumed (that IS the assertion), so without+ // an explicit reset the leftover leaks into the next test's first read.+ getAgent.mockReset().mockResolvedValue(null);+ getTaskById.mockReset().mockResolvedValue(null);+ runnerAgents.clear();+ pausedAgents.clear();+});++describe('handleAgentCompletion — pause guard (data-loss guard)', () => {+ // Deliberately staged so that WITHOUT the guard this call completes the agent:+ // the persisted record says `running`, and the agent is absent from+ // `runnerAgents` (the post-restart shape), so the recovery path would retire+ // it and requeue the task the resume was going to pick up.+ it('finalizes nothing for a paused agent the recovery path would otherwise retire', async () => {+ getAgent.mockResolvedValueOnce({ agentId: 'agent-paused', status: 'running', taskId: 'task-1', metadata: {} });+ pausedAgents.set('agent-paused', { pausedAt: Date.now(), reason: 'user' });++ await handleAgentCompletion('agent-paused', 143, false, 1000);++ // The whole point: no completion write of any kind.+ expect(completeAgent).not.toHaveBeenCalled();+ expect(getAgent).not.toHaveBeenCalled();+ expect(handleOrphanedTask).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();+ });++ // Same guard, live-agent shape: the pause must also win over the in-memory+ // completion path, which would run finalize + worktree cleanup. `getAgentRecord`+ // is that path's very first read, so never touching it proves we never entered it.+ it('does not enter the live completion path for a paused agent still in runnerAgents', async () => {+ pausedAgents.set('agent-paused', { pausedAt: Date.now(), reason: 'user' });+ runnerAgents.set('agent-paused', { task: { id: 'task-1' }, providerId: 'claude' });++ await handleAgentCompletion('agent-paused', 143, false, 1000);++ expect(getAgentRecord).not.toHaveBeenCalled();+ expect(completeAgent).not.toHaveBeenCalled();+ });++ it('drops both map entries so the pause is consumed and the slot is reclaimable', async () => {+ pausedAgents.set('agent-paused', { pausedAt: Date.now(), reason: 'user' });+ runnerAgents.set('agent-paused', { task: { id: 'task-1' } });++ await handleAgentCompletion('agent-paused', 143, false, 1000);++ expect(pausedAgents.has('agent-paused')).toBe(false);+ expect(runnerAgents.has('agent-paused')).toBe(false);+ });++ // Bypass probe: with the pause flag absent, the SAME call must reach a+ // completion path. Without this, a guard that swallowed every event+ // unconditionally (or a `return` moved to the top of the function) would pass+ // the two assertions above while breaking all completions.+ it('does NOT swallow the event when the agent is not paused', async () => {+ getAgent.mockResolvedValueOnce({ agentId: 'agent-live', status: 'running', taskId: null, metadata: {} });++ await handleAgentCompletion('agent-live', 0, true, 1000);++ expect(completeAgent).toHaveBeenCalledWith('agent-live', expect.objectContaining({ orphaned: true }));+ });+});++describe('handleAgentCompletion — post-restart recovery hand-off', () => {+ it('retires an untracked agent from persisted cos state', async () => {+ getAgent.mockResolvedValueOnce({+ agentId: 'agent-gone',+ status: 'running',+ taskId: 'task-9',+ startedAt: '2020-01-01T00:00:00.000Z',+ metadata: { workspacePath: '/repo/wt' },+ });+ getTaskById.mockResolvedValue({ id: 'task-9', status: 'running', taskType: 'user' });++ await handleAgentCompletion('agent-gone', 0, true, 500);++ expect(dispatchRecoveredTaskOutputHook).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-gone', workspacePath: '/repo/wt' })+ );+ expect(completeAgent).toHaveBeenCalledWith('agent-gone', expect.objectContaining({ orphaned: true, success: true }));+ expect(updateTask).toHaveBeenCalledWith('task-9', expect.objectContaining({ status: 'completed' }), 'user');+ });++ it('hands the dead run’s metadata + startedAt to the retry handler on failure', async () => {+ getAgent.mockResolvedValueOnce({+ agentId: 'agent-gone',+ status: 'running',+ taskId: 'task-9',+ startedAt: '2020-01-01T00:00:00.000Z',+ metadata: { worktreeBranch: 'cos/task-9' },+ });+ getTaskById.mockResolvedValue({ id: 'task-9', status: 'running', taskType: 'user' });++ await handleAgentCompletion('agent-gone', 1, false, 500);++ expect(handleOrphanedTask).toHaveBeenCalledWith(+ 'task-9',+ 'agent-gone',+ expect.any(Function),+ { agentMetadata: { worktreeBranch: 'cos/task-9' }, agentStartedAt: '2020-01-01T00:00:00.000Z' }+ );+ });++ it('ignores a completion for an agent whose persisted status is paused', async () => {+ getAgent.mockResolvedValueOnce({ agentId: 'agent-p', status: 'paused', taskId: 'task-9', metadata: {} });++ await handleAgentCompletion('agent-p', 143, false, 500);++ expect(completeAgent).not.toHaveBeenCalled();+ expect(handleOrphanedTask).not.toHaveBeenCalled();+ });++ it('ignores a completion for an agent with no persisted cos record', async () => {+ getAgent.mockResolvedValueOnce(null);++ await handleAgentCompletion('agent-unknown', 0, true, 500);++ expect(completeAgent).not.toHaveBeenCalled();+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex c0660376ca..712a8c724b 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -875,8 +875,96 @@ export async function extractPipelineOutputSummary(task, workspacePath, outputBureturn extractFinalSummary(outputBuffer);}+/**+ * Post-restart recovery: retire a completion event for an agent that is NOT in+ * the in-memory `runnerAgents` map, using the persisted cos state as the only+ * source of truth.+ *+ * A server restart drops every in-memory agent entry, so a completion that+ * lands afterwards has no live record to finalize. This path deliberately+ * BYPASSES `finalizeAgent` (and therefore worktree cleanup): the dead run's+ * worktree is still on disk, and `handleOrphanedTask` needs it to resume rather+ * than redo the work. Because it bypasses finalize, everything finalize would+ * normally do that still matters here — notably the LI hand-off verdict stamp+ * (#2779) — has to be done explicitly below.+ *+ * Split out of `handleAgentCompletion` (#3872) so that function reads as+ * "route, then complete the live agent" instead of two unrelated jobs sharing+ * one name.+ */+async function completeUntrackedAgentFromCosState(agentId, exitCode, success, duration) {+ // Dynamic import: `cos.js` imports back into this cluster, so a static import+ // of the transcript-hydrating `getAgent` here would close an import cycle.+ const { getAgent: getAgentState } = await import('./cos.js');+ const cosAgent = await getAgentState(agentId).catch(() => null);+ if (!cosAgent) {+ console.log(`⚠️ Received completion for unknown agent: ${agentId} (not in cos state)`);+ return;+ }+ if (cosAgent.status === 'completed') {+ console.log(`✅ Agent ${agentId} already completed (handled by orphan cleanup)`);+ return;+ }+ // Post-restart the in-memory pausedAgents map is empty, but the persisted+ // status still says paused — don't finalize a paused agent on a stray event.+ if (cosAgent.status === 'paused') {+ console.log(`⏸️ Ignoring completion for paused agent ${agentId} (awaiting resume)`);+ return;+ }+ console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);+ const task = cosAgent.taskId ? await getTaskById(cosAgent.taskId).catch(() => null) : null;+ await dispatchRecoveredTaskOutputHook({+ agentId,+ task,+ success,+ workspacePath: cosAgent.metadata?.workspacePath || null,+ });+ await completeAgent(agentId, {+ success,+ exitCode,+ duration,+ orphaned: true,+ error: success ? undefined : 'Agent completed after server restart'+ });+ if (cosAgent.taskId) {+ if (task && task.status !== 'completed') {+ if (success) {+ // Stamp the LI hand-off verdict here too (#2779, codex P2) — this post-restart+ // recovery bypasses finalizeAgent, so without it a hand-off that finished while+ // the server was down would never federate its outcome. Only `success` is known+ // on this path (no validationPassed/errorAnalysis), so it records a clean success.+ const taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success });+ await updateTask(cosAgent.taskId, taskUpdate, task.taskType || 'user');+ } else {+ // Hand the dead run's metadata to the retry handler so it can resume what+ // was left behind. This path bypasses `finalizeAgent` (and its worktree+ // cleanup), so the worktree is still on disk, branch and all — without it+ // the retry builds a fresh tree off the default branch and redoes work+ // that is sitting right there.+ await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata, agentStartedAt: cosAgent.startedAt });+ // If orphan recovery settled the task into a terminal `blocked` state (retry budget+ // exhausted), the local completion already recorded the proposal failure — so stamp+ // the LI failure verdict here too (#2779, codex P2) or the originating peer would+ // receive a terminal task with no verdict. A revived (pending) task carries no+ // settled outcome yet, so it is intentionally left unstamped until it re-completes.+ const settled = await getTaskById(cosAgent.taskId).catch(() => null);+ if (settled && settled.status === 'blocked' && settled.metadata?.liProposal) {+ const stamp = await stampLiExecutionVerdict({}, settled, { success: false });+ if (stamp.metadata) {+ await updateTask(cosAgent.taskId, stamp, settled.taskType || 'user').catch(() => {});+ }+ }+ }+ }+ }+}+/*** Handle agent completion (from runner events).+ *+ * Router, then the live in-memory completion path. The two early exits are the+ * pause guard and the post-restart recovery hand-off — both return before any+ * finalization runs against a live agent.*/export async function handleAgentCompletion(agentId, exitCode, success, duration) {// Paused agents are finalized by markAgentPaused, not here — skip so a stray@@ -889,70 +977,8 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration}const agent = runnerAgents.get(agentId);if (!agent) {- // Agent not in memory map (server restarted). Check cos state for context.- const { getAgent: getAgentState } = await import('./cos.js');- const cosAgent = await getAgentState(agentId).catch(() => null);- if (!cosAgent) {- console.log(`⚠️ Received completion for unknown agent: ${agentId} (not in cos state)`);- return;- }- if (cosAgent.status === 'completed') {- console.log(`✅ Agent ${agentId} already completed (handled by orphan cleanup)`);- return;- }- // Post-restart the in-memory pausedAgents map is empty, but the persisted- // status still says paused — don't finalize a paused agent on a stray event.- if (cosAgent.status === 'paused') {- console.log(`⏸️ Ignoring completion for paused agent ${agentId} (awaiting resume)`);- return;- }- console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);- const task = cosAgent.taskId ? await getTaskById(cosAgent.taskId).catch(() => null) : null;- await dispatchRecoveredTaskOutputHook({- agentId,- task,- success,- workspacePath: cosAgent.metadata?.workspacePath || null,- });- await completeAgent(agentId, {- success,- exitCode,- duration,- orphaned: true,- error: success ? undefined : 'Agent completed after server restart'- });- if (cosAgent.taskId) {- if (task && task.status !== 'completed') {- if (success) {- // Stamp the LI hand-off verdict here too (#2779, codex P2) — this post-restart- // recovery bypasses finalizeAgent, so without it a hand-off that finished while- // the server was down would never federate its outcome. Only `success` is known- // on this path (no validationPassed/errorAnalysis), so it records a clean success.- const taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success });- await updateTask(cosAgent.taskId, taskUpdate, task.taskType || 'user');- } else {- // Hand the dead run's metadata to the retry handler so it can resume what- // was left behind. This path bypasses `finalizeAgent` (and its worktree- // cleanup), so the worktree is still on disk, branch and all — without it- // the retry builds a fresh tree off the default branch and redoes work- // that is sitting right there.- await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata, agentStartedAt: cosAgent.startedAt });- // If orphan recovery settled the task into a terminal `blocked` state (retry budget- // exhausted), the local completion already recorded the proposal failure — so stamp- // the LI failure verdict here too (#2779, codex P2) or the originating peer would- // receive a terminal task with no verdict. A revived (pending) task carries no- // settled outcome yet, so it is intentionally left unstamped until it re-completes.- const settled = await getTaskById(cosAgent.taskId).catch(() => null);- if (settled && settled.status === 'blocked' && settled.metadata?.liProposal) {- const stamp = await stampLiExecutionVerdict({}, settled, { success: false });- if (stamp.metadata) {- await updateTask(cosAgent.taskId, stamp, settled.taskType || 'user').catch(() => {});- }- }- }- }- }- return;+ // Agent not in memory map (server restarted). Retire it from cos state.+ return completeUntrackedAgentFromCosState(agentId, exitCode, success, duration);}const { task, runId, model, executionId, laneName } = agent;diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex bbaa3b13da..afe094c2ff 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -327,14 +327,17 @@ describe('agentLifecycle — guard wiring', () => {});/**- * Source of the post-restart recovery branch in handleAgentCompletion, sliced- * between its opening log line and the first statement after it.+ * Source of the post-restart recovery path. It was an inline `if (!agent)`+ * branch of handleAgentCompletion until #3872 split it into its own function;+ * the slice follows it there rather than re-anchoring on a neighbouring+ * statement inside the router, so the window is the whole function body and+ * cannot silently shrink as the path grows.*/function recoveryBranchSource() {- const start = AGENT_LIFECYCLE_SRC.indexOf('Completing untracked agent');- expect(start, 'post-restart recovery branch must exist').toBeGreaterThan(-1);- const end = AGENT_LIFECYCLE_SRC.indexOf('const { task, runId, model', start);- expect(end, 'end anchor (the statement after the branch) must exist').toBeGreaterThan(start);+ const start = AGENT_LIFECYCLE_SRC.indexOf('async function completeUntrackedAgentFromCosState');+ expect(start, 'post-restart recovery path must exist').toBeGreaterThan(-1);+ const end = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion', start);+ expect(end, 'end anchor (the router that dispatches into it) must exist').toBeGreaterThan(start);return AGENT_LIFECYCLE_SRC.slice(start, end);}diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex b4e5c5568e..726cdea856 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -1022,29 +1022,40 @@ describe('close-handler skip-finalization — source contract', () => {expect(guardBlock).toMatch(/\breturn\b/);});- it('runner handleAgentCompletion guards with pausedAgents.has and returns before completeAgent', () => {- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');- expect(fnStart, 'handleAgentCompletion must exist').toBeGreaterThan(-1);-- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 6000);+ // The behavioral counterpart of this guard lives in+ // `agentCompletionRouting.test.js` — it calls the real `handleAgentCompletion`+ // with a paused agent and asserts nothing is completed. That is the durable+ // form (it survives extraction); this source check only pins the ORDERING+ // inside the router, which has no behavioral seam of its own.+ //+ // The window is the router's own brace-balanced body, and the assertion is+ // that the guard precedes BOTH ways out of it — the post-restart recovery+ // hand-off and the live in-memory path — rather than a bare `completeAgent(`,+ // which moved into `completeUntrackedAgentFromCosState` in #3872 and would+ // silently make this test vacuous (indexOf → -1) if it were still named here.+ it('runner handleAgentCompletion guards with pausedAgents.has and returns before either completion path', () => {+ const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'export async function handleAgentCompletion');+ expect(fnBody, 'handleAgentCompletion must exist and be extractable').toBeTruthy();// Guard presentexpect(fnBody).toMatch(/pausedAgents\.has\(agentId\)/);- // Guard appears BEFORE the main completeAgent / finalizeAgent callsconst guardPos = fnBody.indexOf('pausedAgents.has(agentId)');- const completePos = fnBody.indexOf('completeAgent(');- expect(guardPos, 'pause guard must precede completeAgent in handleAgentCompletion').toBeLessThan(completePos);-- // There is a return inside the guard block (early exit before finalization)- const guardBlock = fnBody.slice(guardPos, completePos);- expect(guardBlock).toMatch(/\breturn\b/);+ for (const [label, dispatch] of [+ ['post-restart recovery hand-off', 'completeUntrackedAgentFromCosState('],+ ['live in-memory completion path', 'withMapEntryCleanup('],+ ]) {+ const dispatchPos = fnBody.indexOf(dispatch);+ expect(dispatchPos, `${label} (${dispatch}) must exist in handleAgentCompletion`).toBeGreaterThan(-1);+ expect(guardPos, `pause guard must precede the ${label}`).toBeLessThan(dispatchPos);+ // There is a return inside the guard block (early exit before either path)+ expect(fnBody.slice(guardPos, dispatchPos)).toMatch(/\breturn\b/);+ }});it('runner pause guard also cleans up runnerAgents entry before returning', () => {// After returning early, the runner agent map entry must not be leaked.- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 6000);+ const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'export async function handleAgentCompletion');const guardPos = fnBody.indexOf('pausedAgents.has(agentId)');const returnAfterGuard = fnBody.indexOf('return', guardPos);