Skip to content

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

fix: a restart that stops a not-yet-started agent no longer counts as the task's failure

Adam Eivy521169570392
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 88f8277f2d..da6c2b974f 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -435,7 +435,7 @@ export async function extractPipelineOutputSummary(task, workspacePath, outputBu
* "route, then complete the live agent" instead of two unrelated jobs sharing
* one name.
*/
-async function completeUntrackedAgentFromCosState(agentId, exitCode, success, duration) {
+async function completeUntrackedAgentFromCosState(agentId, exitCode, success, duration, { interruptedStartup = null } = {}) {
// 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');
@@ -467,7 +467,8 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, du
success,
exitCode,
duration,
- errorMessage: willSucceed ? undefined : 'Agent completed after server restart',
+ errorMessage: interruptedStartup?.message ?? (willSucceed ? undefined : 'Agent completed after server restart'),
+ ...(interruptedStartup ? { category: 'interrupted', agentResultExtra: { interruptedByRestart: true } } : {}),
});
if (cosAgent.taskId && task && task.status !== 'completed') {
if (retiredSuccess) {
@@ -485,7 +486,11 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, du
// that is sitting right there. `handleOrphanedTask` stamps the LI verdict
// itself on every terminal settlement (#8440), so there is nothing left
// to re-read and stamp here.
- await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata, agentStartedAt: cosAgent.startedAt });
+ await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, {
+ agentMetadata: cosAgent.metadata,
+ agentStartedAt: cosAgent.startedAt,
+ ...(interruptedStartup ? { interrupted: true } : {}),
+ });
}
}
await maintenance.finishResource('agent', agentId);
@@ -565,6 +570,24 @@ async function handleAdmittedAgentCompletion(agentId, exitCode, success, duratio
return;
}
+ // A recovered TUI whose runner positively knew no prompt had been submitted
+ // was stopped by PortOS itself (syncRunnerAgents); the task never began.
+ // Settle it as a restart interruption — no retry charged, spawn refunded, no
+ // task-type failure and no app cooldown — exactly like an agent the restart
+ // killed mid-run, instead of finalizing it as the task's own startup failure.
+ // Only for a FAILED exit with a readable persisted record: the marker is
+ // cleared only after the guarded stop answers, so a run that submitted and
+ // finished in that window must still finalize normally, and the untracked
+ // settlement has nothing to work from without the record.
+ if (agent.startupErrorAnalysis && !success && persistedAgent) {
+ if (laneName) release(agentId);
+ if (executionId) {
+ errorExecution(executionId, { message: agent.startupErrorAnalysis.message, code: exitCode });
+ completeExecution(executionId, { success: false });
+ }
+ return completeUntrackedAgentFromCosState(agentId, exitCode, false, duration, { interruptedStartup: agent.startupErrorAnalysis });
+ }
+
// Normalize the agent's task shape — recovered agents (post-restart,
// via syncRunnerAgents) may lack taskType AND metadata, both of which
// downstream paths spread / read without a guard.
diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.js
index 026187c3c4..9a6f1dd103 100644
--- a/server/services/agentLifecycle.spawnViaRunner.test.js
+++ b/server/services/agentLifecycle.spawnViaRunner.test.js
@@ -52,6 +52,7 @@ vi.mock('./agentFinalization.js', () => ({
dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined),
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
+ retireDeadAgent: vi.fn().mockResolvedValue({ success: false }),
stampLiExecutionVerdict: vi.fn(async (update) => update),
}));
@@ -65,6 +66,7 @@ vi.mock('./cos.js', () => ({
updateTask: vi.fn().mockResolvedValue(undefined),
getTaskById: vi.fn().mockResolvedValue(null),
getAgentRecord: vi.fn().mockResolvedValue(null),
+ getAgent: vi.fn().mockResolvedValue(null),
}));
vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
@@ -129,7 +131,9 @@ import { committedDuringRun } from '../lib/gitCommitProbe.js';
import { spawnAgentViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';
import { completeAgent, updateAgent } from './cosAgentLifecycle.js';
import { completeAgentRun } from './agentRunTracking.js';
-import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
+import { finalizeAgent, releaseAgentLane, retireDeadAgent } from './agentFinalization.js';
+import { getAgent, getAgentRecord, getTaskById } from './cos.js';
+import { release } from './executionLanes.js';
import { releaseRetryHold } from './agentWorktreeCleanup.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { handleOrphanedTask } from './agentManagement.js';
@@ -137,25 +141,69 @@ import { runnerAgents } from './agentState.js';
const REJECTION = 'Command not allowed: grok. Permitted commands: claude, codex';
-it('finalizes an interrupted TUI startup as retryable failure, without crediting a shared-checkout commit', async () => {
+it('settles an interrupted TUI startup as a restart interruption, charging the task nothing', async () => {
vi.clearAllMocks();
const startupErrorAnalysis = {
category: 'startup-failure', origin: 'runner', actionable: false,
message: 'Server restarted before the TUI task prompt was submitted',
};
+ const task = { id: 'task-interrupted', taskType: 'user', status: 'in_progress', metadata: {} };
+ const record = { id: 'agent-interrupted', status: 'running', taskId: task.id, metadata: { runId: 'run-interrupted' }, startedAt: '2026-10-20T17:00:51.000Z' };
+ vi.mocked(getAgent).mockResolvedValueOnce(record);
+ vi.mocked(getAgentRecord).mockResolvedValueOnce(record);
+ vi.mocked(getTaskById).mockResolvedValue(task);
runnerAgents.set('agent-interrupted', {
- task: { id: 'task-interrupted', taskType: 'user', metadata: {} },
- runId: 'run-interrupted', workspacePath: '/tmp/ws', startedAt: Date.now(),
- startupErrorAnalysis, recoveredFromRunner: true,
+ task, runId: 'run-interrupted', workspacePath: '/tmp/ws', startedAt: Date.now(),
+ laneName: 'standard', startupErrorAnalysis, recoveredFromRunner: true,
});
await handleAgentCompletion('agent-interrupted', 143, false, 1000);
- expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({
- agentId: 'agent-interrupted', success: false, errorAnalysis: startupErrorAnalysis,
+
+ // PortOS ended the run before the task began: the retry/ledger/cooldown charges
+ // all live behind finalizeAgent, and the restart-interruption path skips them.
+ expect(finalizeAgent).not.toHaveBeenCalled();
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: record, success: false, exitCode: 143, category: 'interrupted',
+ errorMessage: startupErrorAnalysis.message,
+ agentResultExtra: { interruptedByRestart: true },
}));
+ expect(handleOrphanedTask).toHaveBeenCalledWith('task-interrupted', 'agent-interrupted', getTaskById,
+ expect.objectContaining({ interrupted: true }));
+ expect(release).toHaveBeenCalledWith('agent-interrupted');
expect(committedDuringRun).not.toHaveBeenCalled();
expect(runnerAgents.has('agent-interrupted')).toBe(false);
});
+describe('interrupted TUI startup — cases that must keep finalizing normally', () => {
+ const startupErrorAnalysis = {
+ category: 'startup-failure', origin: 'runner', actionable: false,
+ message: 'Server restarted before the TUI task prompt was submitted',
+ };
+ const track = () => runnerAgents.set('agent-race', {
+ task: { id: 'task-race', taskType: 'user', metadata: {} },
+ runId: 'run-race', workspacePath: '/tmp/ws', startedAt: Date.now(),
+ startupErrorAnalysis, recoveredFromRunner: true,
+ });
+ const record = { id: 'agent-race', status: 'running', taskId: 'task-race', metadata: {} };
+
+ beforeEach(() => { vi.clearAllMocks(); runnerAgents.clear(); });
+
+ it('finalizes a run that submitted and succeeded while the guarded stop was still in flight', async () => {
+ track();
+ vi.mocked(getAgentRecord).mockResolvedValueOnce(record);
+ await handleAgentCompletion('agent-race', 0, true, 1000);
+ expect(retireDeadAgent).not.toHaveBeenCalled();
+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-race', success: true }));
+ });
+
+ it('finalizes with the in-memory entry when the persisted record cannot be read', async () => {
+ track();
+ vi.mocked(getAgentRecord).mockResolvedValueOnce(null);
+ await handleAgentCompletion('agent-race', 143, false, 1000);
+ expect(retireDeadAgent).not.toHaveBeenCalled();
+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-race', errorAnalysis: startupErrorAnalysis }));
+ });
+});
+
// The runner ANSWERED and declined. The shape mirrors what `spawnAgentViaRunner`
// stamps on a non-2xx (pinned in cosRunnerClient.test.js); a bare Error would
// classify as AMBIGUOUS, which is the whole point of the split (#4615).
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 99e77159d7..c39c178e31 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -537,7 +537,7 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {
// run that DID commit before dying is requeued as if it had produced nothing.
it('the post-restart recovery path hands the dead agent’s metadata to the retry handler', () => {
const body = recoveryBranchSource();
- expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata,\s*agentStartedAt: cosAgent\.startedAt\s*\}\)/);
+ expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata,\s*agentStartedAt: cosAgent\.startedAt,[\s\S]*?\}\)/);
});
});