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: harden orphan run recovery durability (#3211)

[._.]/ Adam Eivyfcd5b1ce3d6e
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 393bf470b1..db87b879bb 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -796,7 +796,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
}
// Check if the agent actually committed work before treating as orphaned
- const commitFound = await checkForTaskCommit(taskId, ROOT_DIR);
+ const commitFound = await checkForTaskCommit(taskId, agentMetadata?.workspacePath || ROOT_DIR);
if (commitFound) {
emitLog('info', `✅ Orphaned agent ${agentId} actually completed work - commit found for task ${taskId}`, { taskId, agentId });
await updateTask(taskId, { status: 'completed' }, task.taskType || 'user');
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 3cf439a39c..10a56f3899 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -108,7 +108,7 @@ import { pauseAgentViaRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { completeAgent as markAgentComplete } from './cos.js';
-import { completeAgentRun } from './agentRunTracking.js';
+import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';
import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
@@ -891,6 +891,18 @@ describe('orphan retries resume what the dead run left behind', () => {
expect(resolveTaskResumePatch).toHaveBeenCalledWith(expect.objectContaining({ agentMetadata: null }));
expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
});
+
+ it('checks for completed work in the orphaned agent’s actual workspace', async () => {
+ checkForTaskCommit.mockResolvedValueOnce(true);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {
+ agentMetadata: { workspacePath: '/example-app' },
+ });
+
+ expect(checkForTaskCommit).toHaveBeenCalledWith('task-1', '/example-app');
+ expect(updateTask).toHaveBeenCalledWith('task-1', { status: 'completed' }, 'user');
+ });
});
// A PortOS restart kills every server-owned agent. Charging those runs the same
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 7a834f1208..d2f17ee11d 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -140,15 +140,19 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
}
}
- await atomicWrite(metaPath, metadata);
+ // Persist output first so endTime remains the durable completion marker. If
+ // this write fails, the still-open metadata lets recovery retry the whole
+ // operation; once metadata lands, every run artifact is already complete.
await writeFile(join(runDir, 'output.txt'), output || '');
+ await atomicWrite(metaPath, metadata);
- // Record usage for successful CoS agent runs. Prefers the provider CLI's own
+ // Record usage for every completed CoS agent run: failed and interrupted
+ // providers still consumed tokens. Prefers the provider CLI's own
// per-message token counts (read from its on-disk transcript, including the
// prompt-cache tiers) and falls back to the prompt-length/stdout estimate.
// `metadata` already carries the endTime stamped above, which bounds the
// transcript window. Owns its own error handling.
- if (exitCode === 0 && metadata.providerId && metadata.model) {
+ if (metadata.providerId && metadata.model) {
recordCompletedRunUsage(metadata, output);
}
}
diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.js
index bf5ed1ecb4..6dc37d1c16 100644
--- a/server/services/agentRunTracking.test.js
+++ b/server/services/agentRunTracking.test.js
@@ -105,4 +105,59 @@ describe('completeAgentRun idempotency', () => {
expect(atomicWrite).not.toHaveBeenCalled();
expect(writeFile).not.toHaveBeenCalled();
});
+
+ it('writes the transcript before stamping the terminal metadata', async () => {
+ vi.resetModules();
+ const order = [];
+ const atomicWrite = vi.fn().mockImplementation(() => { order.push('metadata'); });
+ const writeFile = vi.fn().mockImplementation(() => { order.push('output'); });
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue({
+ id: 'run-open',
+ endTime: null,
+ taskId: null,
+ providerId: null,
+ }),
+ atomicWrite,
+ }));
+ vi.doMock('fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeFile,
+ }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ await completeAgentRun('run-open', 'output', 1, 100, { message: 'failed' });
+
+ expect(order).toEqual(['output', 'metadata']);
+ });
+
+ it('reconciles usage for failed runs as well as successful ones', async () => {
+ vi.resetModules();
+ const recordCompletedRunUsage = vi.fn();
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue({
+ id: 'run-failed',
+ endTime: null,
+ taskId: null,
+ providerId: 'codex',
+ model: 'example-model',
+ }),
+ atomicWrite: vi.fn(),
+ }));
+ vi.doMock('fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeFile: vi.fn(),
+ }));
+ vi.doMock('./usageReconciler.js', () => ({ recordCompletedRunUsage }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ await completeAgentRun('run-failed', 'partial output', 1, 100, { message: 'failed' });
+
+ expect(recordCompletedRunUsage).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'run-failed', success: false }),
+ 'partial output',
+ );
+ });
});