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: stamp LI execution verdicts on every dead-agent recovery path (#8440)

[._.]/ Adam Eivy2771e3ad7fed
diff --git a/server/services/agentCompletionRouting.test.js b/server/services/agentCompletionRouting.test.js
index 6c7cd596bb..18d88aa232 100644
--- a/server/services/agentCompletionRouting.test.js
+++ b/server/services/agentCompletionRouting.test.js
@@ -42,6 +42,11 @@ vi.mock('./agentFinalization.js', () => ({
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
stampLiExecutionVerdict: vi.fn(async (update) => update),
+ // `retireDeadAgent`'s own step-order/private-security contract is pinned for real
+ // (mocked leaves) in `agentFinalization.retireDeadAgent.test.js`. This suite only
+ // needs it to echo the `success` it was handed, since the router branches on the
+ // returned value.
+ retireDeadAgent: vi.fn(async ({ success }) => ({ success })),
}));
vi.mock('./agentManagement.js', () => ({
@@ -62,7 +67,7 @@ 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 { retireDeadAgent } from './agentFinalization.js';
import { handleOrphanedTask } from './agentManagement.js';
beforeEach(() => {
@@ -122,18 +127,22 @@ describe('handleAgentCompletion — pause guard (data-loss guard)', () => {
// 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: {} });
+ getAgent.mockResolvedValueOnce({ id: 'agent-live', status: 'running', taskId: null, metadata: {} });
await handleAgentCompletion('agent-live', 0, true, 1000);
- expect(completeAgent).toHaveBeenCalledWith('agent-live', expect.objectContaining({ orphaned: true }));
+ // Retirement itself is `retireDeadAgent`'s job now (#8440) — reaching it at
+ // all is what proves the guard didn't swallow the event.
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-live' }),
+ }));
});
});
describe('handleAgentCompletion — post-restart recovery hand-off', () => {
it('retires an untracked agent from persisted cos state', async () => {
getAgent.mockResolvedValueOnce({
- agentId: 'agent-gone',
+ id: 'agent-gone',
status: 'running',
taskId: 'task-9',
startedAt: '2020-01-01T00:00:00.000Z',
@@ -143,16 +152,22 @@ describe('handleAgentCompletion — post-restart recovery hand-off', () => {
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 }));
+ // `retireDeadAgent` (#8440) is the single retirement step list — this only
+ // checks the router hands it the right facts; its own step order and the
+ // completeAgent/output-hook calls it makes are pinned in
+ // `agentFinalization.retireDeadAgent.test.js`.
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-gone' }),
+ success: true,
+ exitCode: 0,
+ duration: 500,
+ }));
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',
+ id: 'agent-gone',
status: 'running',
taskId: 'task-9',
startedAt: '2020-01-01T00:00:00.000Z',
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index cfe6a88ac5..77f5980ab9 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -22,8 +22,9 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
import { join } from 'path';
import { execGit } from '../lib/execGit.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { cosEvents, emitLog } from './cosEvents.js';
+import { removeCompletionSentinel } from './agentCompletionCleanup.js';
// The DEFINING module, not a barrel (#3450) — see the note in
// `agentManagement.js`. This module is a LEAF that both transition modules
// import, which puts it inside the facade's closure, so the facade is out of
@@ -1012,6 +1013,85 @@ export function dispatchRecoveredTaskOutputHook({ agentId, task, success, worksp
});
}
+/**
+ * Retire an agent whose process is gone — the one step list both recovery
+ * paths now share (issue #8440). Before this, the orphan sweep
+ * (`runCleanupOrphanedAgents`) and the post-restart recovery
+ * (`completeUntrackedAgentFromCosState`) each hand-maintained their own copy
+ * of this sequence, and the copies drifted (only the sweep closed the run
+ * record; #3182's output-hook fix had to land in both).
+ *
+ * Order matters and is preserved from the sweep, the stricter of the two
+ * originals: the output hook reads the last surviving sentinel/output before
+ * it is removed, the run record closes BEFORE the agent record (so a run
+ * write failure leaves the agent eligible for the next sweep to retry, while
+ * a later agent-write failure is harmless because `completeAgentRun`'s
+ * `endTime` guard makes a retry a no-op), and the agent record closes last.
+ *
+ * A private-security task/agent has no immutable source inventory with which
+ * to validate a report, so it is always retired as a failure (the caller's
+ * `success` is overridden) and its run-record output is redacted to a fixed
+ * notice rather than the raw transcript.
+ *
+ * @param {object} params
+ * @param {object} params.agent the dead agent's record (`id`, `metadata`, `output`, `startedAt`)
+ * @param {object|null} params.task the agent's task, if resolvable (drives the private-security check
+ * and the programmatic-I/O output hook)
+ * @param {boolean} params.success the run's outcome; overridden to `false` for a private-security task
+ * @param {number} params.exitCode the exit code recorded on the closed run (143/1 for the sweep's
+ * interrupted/orphaned reap, the real exit code for post-restart recovery)
+ * @param {number} params.duration the run's wall-clock duration in ms, for the closed run record
+ * @param {string} [params.errorMessage] the error recorded on the agent (and, wrapped, on the run record)
+ * @param {string} [params.category] the run-record error category (e.g. `orphaned` / `interrupted`)
+ * @param {object} [params.agentResultExtra] caller-specific fields merged into the agent-record
+ * result (e.g. the sweep's `interruptedByRestart` telemetry) — kept out of the shared shape so
+ * one caller's bookkeeping detail doesn't leak an unused field onto the other's records
+ * @returns {Promise<{ success: boolean }>} the effective success used for the retirement (post
+ * private-security override), so callers that branch on it don't have to re-derive it
+ */
+export async function retireDeadAgent({ agent, task, success, exitCode, duration, errorMessage, category, agentResultExtra = {} }) {
+ const isPrivateSecurity = isPrivateSecurityTask(task) || isPrivateSecurityTask(agent);
+ const effectiveSuccess = isPrivateSecurity ? false : success;
+
+ await dispatchRecoveredTaskOutputHook({
+ agentId: agent.id,
+ task,
+ success: effectiveSuccess,
+ workspacePath: agent.metadata?.workspacePath || null,
+ });
+
+ // Recovery retires the run without reaching finalizeAgent's completion
+ // cleanup, so the sentinel has no other owner — and the hook above was the
+ // last thing to read it.
+ await removeCompletionSentinel({ agentId: agent.id, agentState: agent })
+ .catch(err => emitLog('warn', `Completion sentinel removal failed for ${agent.id}: ${err.message}`, { agentId: agent.id }));
+
+ if (agent.metadata?.runId) {
+ const bufferedOutput = Array.isArray(agent.output)
+ ? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
+ : '';
+ const output = await tryReadFile(join(PATHS.cosAgents, agent.id, 'output.txt')) ?? bufferedOutput;
+ await completeAgentRun(
+ agent.metadata.runId,
+ isPrivateSecurity ? 'Private security assessment interrupted; inspect its local assessment archive.' : output,
+ exitCode,
+ duration,
+ { message: errorMessage, category },
+ );
+ }
+
+ await completeAgent(agent.id, {
+ success: effectiveSuccess,
+ exitCode,
+ duration,
+ orphaned: true,
+ error: errorMessage,
+ ...agentResultExtra,
+ });
+
+ return { success: effectiveSuccess };
+}
+
/**
* Stamp an LI hand-off's per-proposal execution verdict into a completion `taskUpdate`'s
* federated metadata (#2779), mutating `taskUpdate.metadata` in place. Shared by every
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index caf6a8def6..341b6a38ba 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -74,6 +74,10 @@ import { MAX_TASK_RETRIES, resolveFailedTaskUpdate } from './agentErrorAnalysis.
const __dirname = dirname(fileURLToPath(import.meta.url));
const MANAGEMENT_SOURCE = readFileSync(join(__dirname, 'agentManagement.js'), 'utf8');
const LIFECYCLE_SOURCE = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf8');
+// The orphan sweep and post-restart recovery both retire through the shared
+// `retireDeadAgent` (#8440) now, so its own ordering is the thing to pin — see
+// the source-text tests just below.
+const FINALIZATION_SOURCE = readFileSync(join(__dirname, 'agentFinalization.js'), 'utf8');
const TASK = {
id: 'sys-example',
taskType: 'internal',
@@ -290,19 +294,28 @@ describe('recovery output-hook dispatch (#3182)', () => {
});
});
-describe('recovery path wiring (#3182)', () => {
- it('dispatches before orphan cleanup marks the agent complete', () => {
- const start = MANAGEMENT_SOURCE.indexOf('async function runCleanupOrphanedAgents');
- const body = MANAGEMENT_SOURCE.slice(start, start + 12_000);
+describe('recovery path wiring (#3182, #8440)', () => {
+ // Both recovery paths (the orphan sweep in agentManagement.js and post-restart
+ // recovery in agentLifecycle.js) call the shared `retireDeadAgent` (#8440) for
+ // this step list now, so the ordering guard moved to pin ITS body instead of
+ // each caller's inlined copy.
+ it('retireDeadAgent dispatches the output hook before marking the agent complete', () => {
+ const start = FINALIZATION_SOURCE.indexOf('export async function retireDeadAgent');
+ expect(start, 'retireDeadAgent must exist').toBeGreaterThan(-1);
+ const end = FINALIZATION_SOURCE.indexOf('\n}', start);
+ const body = FINALIZATION_SOURCE.slice(start, end);
expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);
expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agent.id'));
});
- it('dispatches before post-restart recovery marks the agent complete', () => {
- const start = LIFECYCLE_SOURCE.indexOf('Completing untracked agent');
- const body = LIFECYCLE_SOURCE.slice(start, start + 2_000);
- expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);
- expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agentId'));
+ it('both recovery paths retire through the shared retireDeadAgent', () => {
+ const sweepStart = MANAGEMENT_SOURCE.indexOf('async function runCleanupOrphanedAgents');
+ const sweepBody = MANAGEMENT_SOURCE.slice(sweepStart, sweepStart + 12_000);
+ expect(sweepBody).toMatch(/await retireDeadAgent\(/);
+
+ const recoveryStart = LIFECYCLE_SOURCE.indexOf('Completing untracked agent');
+ const recoveryBody = LIFECYCLE_SOURCE.slice(recoveryStart, recoveryStart + 2_000);
+ expect(recoveryBody).toMatch(/await retireDeadAgent\(/);
});
});
diff --git a/server/services/agentFinalization.retireDeadAgent.test.js b/server/services/agentFinalization.retireDeadAgent.test.js
new file mode 100644
index 0000000000..ecd4ba0d5d
--- /dev/null
+++ b/server/services/agentFinalization.retireDeadAgent.test.js
@@ -0,0 +1,154 @@
+/**
+ * Tests for `retireDeadAgent` (#8440) — the single retirement step list the
+ * orphan sweep (`runCleanupOrphanedAgents` in agentManagement.js) and the
+ * post-restart recovery (`completeUntrackedAgentFromCosState` in
+ * agentLifecycle.js) now both call, in place of each hand-maintaining its
+ * own copy. Exercises the REAL function against mocked leaves so a future
+ * drift between the two callers' expectations shows up here instead of only
+ * in production.
+ *
+ * `dispatchRecoveredTaskOutputHook` and `removeCompletionSentinel` are
+ * mocked rather than exercised for real: the output-hook dispatch machinery
+ * has its own suite (`agentFinalization.outputHooks.test.js`) and sentinel
+ * removal has its own (`agentCompletionCleanup.test.js`). This file's job is
+ * the ORCHESTRATION — order, the private-security override, and which
+ * per-caller facts land where.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./cosAgentLifecycle.js', () => ({
+ getAgent: vi.fn(async () => null),
+ updateAgent: vi.fn(async () => null),
+ completeAgent: vi.fn(async () => null),
+}));
+vi.mock('./agentCompletionCleanup.js', () => ({
+ removeCompletionSentinel: vi.fn(async () => undefined),
+}));
+vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn(async () => null) }));
+vi.mock('./cos.js', () => ({ updateTask: vi.fn(async () => ({})), addTask: vi.fn(async () => ({ id: 'investigation-test' })) }));
+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn(), cosEvents: { emit: vi.fn(), on: vi.fn() } }));
+vi.mock('./taskTypeHooks.js', () => ({
+ canRunTaskOutputHookWithoutPayload: vi.fn(() => true),
+ getTaskOutputHook: vi.fn(async () => null),
+ getTaskOutputPayloadPredicate: vi.fn(async () => null),
+ declaresNoCommitCriterion: vi.fn(() => false),
+ isProgrammaticIoTaskType: vi.fn(() => false),
+ // No task in this suite carries an analysisType, so the real resolver's
+ // taskType fallback is fine — mirrors production, unlike the sibling
+ // output-hook suite which forces null to isolate its own dispatch cases.
+ resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || task?.taskType || null),
+}));
+vi.mock('./agentErrorAnalysis.js', () => ({ resolveFailedTaskUpdate: vi.fn(), resolveTypeFailureSignal: vi.fn() }));
+vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));
+vi.mock('./investigationTaskProducer.js', () => ({
+ investigationCircuitOpen: vi.fn(() => false),
+ noteInvestigationFiled: vi.fn(),
+ readAllTasksFlat: vi.fn(async () => []),
+ recentInvestigationCreations: vi.fn(() => []),
+}));
+vi.mock('./taskSchedule.js', () => ({
+ recordTaskTypeFailure: vi.fn(async () => null),
+ recordTaskTypeSuccess: vi.fn(async () => null),
+}));
+vi.mock('./codeReview.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getGoalFidelityConfig: vi.fn(async () => null),
+}));
+
+import { completeAgent } from './cosAgentLifecycle.js';
+import { removeCompletionSentinel } from './agentCompletionCleanup.js';
+import { completeAgentRun } from './agentRunTracking.js';
+import { retireDeadAgent } from './agentFinalization.js';
+import { PRIVATE_SECURITY_TASK_TYPE } from '../lib/privateSecurityPolicy.js';
+
+const AGENT = { id: 'agent-dead', metadata: {}, output: [], startedAt: '2026-09-25T00:00:00Z' };
+const TASK = { id: 'task-1', taskType: 'user', metadata: {} };
+
+describe('retireDeadAgent (#8440)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ removeCompletionSentinel.mockResolvedValue(undefined);
+ completeAgentRun.mockResolvedValue(undefined);
+ completeAgent.mockResolvedValue(undefined);
+ });
+
+ it('closes the run record before completing the agent record, when the agent carries a runId', async () => {
+ const order = [];
+ completeAgentRun.mockImplementation(async () => { order.push('run'); });
+ completeAgent.mockImplementation(async () => { order.push('agent'); });
+
+ await retireDeadAgent({
+ agent: { ...AGENT, metadata: { runId: 'run-1' } },
+ task: TASK,
+ success: false,
+ exitCode: 1,
+ duration: 500,
+ errorMessage: 'Agent process terminated unexpectedly',
+ category: 'orphaned',
+ });
+
+ expect(order).toEqual(['run', 'agent']);
+ expect(completeAgentRun).toHaveBeenCalledWith('run-1', '', 1, 500, {
+ message: 'Agent process terminated unexpectedly',
+ category: 'orphaned',
+ });
+ expect(completeAgent).toHaveBeenCalledWith('agent-dead', {
+ success: false,
+ exitCode: 1,
+ duration: 500,
+ orphaned: true,
+ error: 'Agent process terminated unexpectedly',
+ });
+ });
+
+ it('skips closing the run record for an agent with no runId', async () => {
+ await retireDeadAgent({ agent: AGENT, task: TASK, success: true, exitCode: 0, duration: 100 });
+
+ expect(completeAgentRun).not.toHaveBeenCalled();
+ expect(completeAgent).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ success: true }));
+ });
+
+ it('removes the completion sentinel before checking for a runId', async () => {
+ await retireDeadAgent({ agent: AGENT, task: TASK, success: false, exitCode: 1, duration: 0 });
+
+ expect(removeCompletionSentinel).toHaveBeenCalledWith({ agentId: 'agent-dead', agentState: AGENT });
+ });
+
+ // No immutable source inventory survives to validate a recovered private-security
+ // report, so the run is always retired as a failure — no matter what the caller
+ // believed — and the run record's output is redacted rather than the raw transcript.
+ it('forces success:false and redacts the run-record output for a private-security task', async () => {
+ const privateTask = { ...TASK, metadata: { analysisType: PRIVATE_SECURITY_TASK_TYPE } };
+
+ const result = await retireDeadAgent({
+ agent: { ...AGENT, metadata: { runId: 'run-private' } },
+ task: privateTask,
+ success: true,
+ exitCode: 0,
+ duration: 10,
+ });
+
+ expect(result).toEqual({ success: false });
+ expect(completeAgentRun).toHaveBeenCalledWith(
+ 'run-private',
+ 'Private security assessment interrupted; inspect its local assessment archive.',
+ 0,
+ 10,
+ expect.anything(),
+ );
+ expect(completeAgent).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ success: false }));
+ });
+
+ it('merges caller-specific extra fields into the agent-record result without leaking them into the run record', async () => {
+ await retireDeadAgent({
+ agent: AGENT,
+ task: TASK,
+ success: false,
+ exitCode: 143,
+ duration: 0,
+ agentResultExtra: { interruptedByRestart: true },
+ });
+
+ expect(completeAgent).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ interruptedByRestart: true }));
+ });
+});
diff --git a/server/services/agentFinalization.stampLiExecutionVerdict.test.js b/server/services/agentFinalization.stampLiExecutionVerdict.test.js
new file mode 100644
index 0000000000..5df924825d
--- /dev/null
+++ b/server/services/agentFinalization.stampLiExecutionVerdict.test.js
@@ -0,0 +1,50 @@
+/**
+ * Tests for `stampLiExecutionVerdict` (#2779) against its REAL dynamic-import
+ * dependencies (`taskLearning/metrics.js#buildLiExecutionVerdict` and
+ * `layeredIntelligenceOutcomes.js#LI_EXECUTION_VERDICT_KEY`) rather than a
+ * mock — every existing caller mocks this function to an identity passthrough
+ * (see `agentLifecycle.test.js`, `agentCompletionRouting.test.js`,
+ * `agentManagement.test.js`), so its own no-op/build behavior had no coverage
+ * of its own before issue #8440.
+ */
+import { describe, expect, it } from 'vitest';
+import { stampLiExecutionVerdict } from './agentFinalization.js';
+import { LI_EXECUTION_VERDICT_KEY } from './layeredIntelligenceOutcomes.js';
+
+const LI_PROPOSAL = { appId: 'app-example', slug: 'example-slug', scope: 'repo' };
+
+describe('stampLiExecutionVerdict (#2779, #8440)', () => {
+ it('leaves the update untouched when the task carries no liProposal', async () => {
+ const taskUpdate = { status: 'completed' };
+ const task = { id: 'task-1', metadata: {} };
+
+ const result = await stampLiExecutionVerdict(taskUpdate, task, { success: true });
+
+ expect(result).toBe(taskUpdate);
+ expect(result.metadata).toBeUndefined();
+ });
+
+ it('stamps a success verdict for a hand-off task settled completed', async () => {
+ const task = { id: 'task-1', metadata: { liProposal: LI_PROPOSAL } };
+
+ const result = await stampLiExecutionVerdict({ status: 'completed' }, task, { success: true });
+
+ expect(result.metadata[LI_EXECUTION_VERDICT_KEY]).toMatchObject({
+ appId: 'app-example',
+ slug: 'example-slug',
+ success: true,
+ });
+ });
+
+ it('stamps a failure verdict for a hand-off task settled blocked', async () => {
+ const task = { id: 'task-1', metadata: { liProposal: LI_PROPOSAL } };
+
+ const result = await stampLiExecutionVerdict({ status: 'blocked' }, task, { success: false });
+
+ expect(result.metadata[LI_EXECUTION_VERDICT_KEY]).toMatchObject({
+ appId: 'app-example',
+ slug: 'example-slug',
+ success: false,
+ });
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 999e36cb2a..ec33a51286 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -54,8 +54,8 @@ import { isUpdateInProgress } from './updateChecker.js';
import { createAgentSpawnContext, prepareAgentSpawn } from './agentSpawnPreparation.js';
import { dispatchAgentRun } from './agentSpawnDispatch.js';
import { releaseRetryHold } from './agentWorktreeCleanup.js';
-import { runAgentCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';
-import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';
+import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';
+import { finalizeAgent, releaseAgentLane, retireDeadAgent, stampLiExecutionVerdict } from './agentFinalization.js';
import { extractFinalSummary } from './agentSummaryExtraction.js';
import { handleOrphanedTask } from './agentManagement.js';
@@ -413,9 +413,14 @@ export async function extractPipelineOutputSummary(task, workspacePath, outputBu
* 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.
+ * than redo the work. `retireDeadAgent` (#8440) supplies everything finalize
+ * would normally do that still matters here — output hook, sentinel removal,
+ * run-record close, agent completion — as the same shared step list the
+ * orphan sweep uses. Only the direct-success LI verdict stamp below stays
+ * here: it doesn't go through `handleOrphanedTask`, so nothing else stamps
+ * it. The failure-path stamp moved INTO `handleOrphanedTask` (every terminal
+ * settlement there is now stamped), so this function no longer re-reads the
+ * task after calling it.
*
* Split out of `handleAgentCompletion` (#3872) so that function reads as
* "route, then complete the live agent" instead of two unrelated jobs sharing
@@ -442,55 +447,36 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, du
}
console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);
const task = cosAgent.taskId ? await getTaskById(cosAgent.taskId).catch(() => null) : null;
- // Recovery has no immutable source inventory with which to validate a report.
- if (isPrivateSecurityTask(task) || isPrivateSecurityTask(cosAgent)) success = false;
- await dispatchRecoveredTaskOutputHook({
- agentId,
+ // `retireDeadAgent` forces a private-security run to `success: false` no
+ // matter what the caller passed — mirror that here so the recorded `error`
+ // message agrees with the record it lands on instead of leaving a failed
+ // record with no error string.
+ const willSucceed = success && !isPrivateSecurityTask(task) && !isPrivateSecurityTask(cosAgent);
+ const { success: retiredSuccess } = await retireDeadAgent({
+ agent: cosAgent,
task,
- success,
- workspacePath: cosAgent.metadata?.workspacePath || null,
- });
- // Recovery retires the run without reaching finalizeAgent's completion
- // cleanup, so the sentinel has no other owner — and the hook above was the
- // last thing to read it. Mirrored in agentManagement's orphan sweep.
- await removeCompletionSentinel({ agentId, agentState: cosAgent })
- .catch(err => emitLog('warn', `Completion sentinel removal failed for ${agentId}: ${err.message}`, { agentId }));
- await completeAgent(agentId, {
success,
exitCode,
duration,
- orphaned: true,
- error: success ? undefined : 'Agent completed after server restart'
+ errorMessage: willSucceed ? 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(() => {});
- }
- }
- }
+ if (cosAgent.taskId && task && task.status !== 'completed') {
+ if (retiredSuccess) {
+ // 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: retiredSuccess });
+ 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. `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 });
}
}
}
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 7f278d97ec..0f4334b6fb 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -504,19 +504,28 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {
expect(body).toMatch(/\[LI_EXECUTION_VERDICT_KEY\]:\s*verdict/);
});
- it('the post-restart recovery completion path also stamps the LI verdict (#2779, codex P2)', () => {
+ it('the post-restart recovery completion path also stamps the LI verdict on direct success (#2779, codex P2)', () => {
// A hand-off that finished while the server was down completes via this bypass, not
// finalizeAgent — it must still stamp so the outcome federates to the originating peer.
// End-anchored on the statement that follows the branch rather than a fixed
// char count: a fixed window silently shrinks its coverage every time the
// branch grows, and a later addition pushed the assertions below out of it.
const body = recoveryBranchSource();
- // Success path stamps a clean completion…
- expect(body).toMatch(/await stampLiExecutionVerdict\(\{ status: 'completed' \}, task, \{ success \}\)/);
- // …and the FAILURE path re-reads the task after orphan recovery and stamps the failure
- // verdict when recovery settled it into terminal `blocked` (codex P2 round 2).
- expect(body).toMatch(/settled\.status === 'blocked' && settled\.metadata\?\.liProposal/);
- expect(body).toMatch(/await stampLiExecutionVerdict\(\{\}, settled, \{ success: false \}\)/);
+ // The direct-success completion doesn't route through handleOrphanedTask, so it
+ // stamps its own clean-completion verdict here.
+ expect(body).toMatch(/await stampLiExecutionVerdict\(\{ status: 'completed' \}, task, \{ success: retiredSuccess \}\)/);
+ });
+
+ // The failure-path re-stamp used to live here too (re-reading the task after
+ // `handleOrphanedTask` settled it `blocked`) — moved INTO `handleOrphanedTask`
+ // itself (#8440), so every terminal settlement it makes is stamped, on every
+ // caller (the orphan sweep, `resetOrphanedTasks`, and this post-restart path),
+ // not just this one. See `agentManagement.test.js`'s
+ // "stamps the LI execution verdict" coverage for the new location.
+ it('no longer re-reads the task after handleOrphanedTask to re-stamp a failure verdict', () => {
+ const body = recoveryBranchSource();
+ expect(body).not.toMatch(/settled\.status === 'blocked'/);
+ expect(body).not.toMatch(/await stampLiExecutionVerdict\(\{\}, settled/);
});
// This bypass never runs worktree cleanup, so the dead run's tree is still on
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index d7a6596aa7..40ecdadf4c 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -5,7 +5,6 @@
* and orphaned task retry logic.
*/
-import { join } from 'path';
import { rm } from 'node:fs/promises';
import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -35,14 +34,12 @@ import { REQUEUED_AT_KEY, LAST_SPAWNED_AT_KEY } from '../lib/taskRequeue.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
-import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
-import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';
-import { removeCompletionSentinel } from './agentCompletionCleanup.js';
+import { retireDeadAgent, stampLiExecutionVerdict } from './agentFinalization.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
import { buildInvestigationFingerprint } from '../lib/investigationTasks.js';
-import { PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { readHostShutdownMarker, clearHostShutdownMarker, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { release } from './executionLanes.js';
@@ -1275,43 +1272,27 @@ async function runCleanupOrphanedAgents() {
},
});
const task = agent.taskId ? await getTaskById(agent.taskId).catch(() => null) : null;
- await dispatchRecoveredTaskOutputHook({
- agentId: agent.id,
+ const startedAt = Date.parse(agent.startedAt);
+ // Same shared step list the post-restart recovery in agentLifecycle.js uses
+ // (issue #8440) — output hook, sentinel removal, run-record close, agent
+ // completion, in that order. A hard kill (`pm2 restart`, reboot) lands here,
+ // so this is the path that leaves dirt in a managed app repo if any of it
+ // is skipped.
+ await retireDeadAgent({
+ agent,
task,
success: false,
- workspacePath: agent.metadata?.workspacePath || null,
- });
- // Same reason as the post-restart recovery in agentLifecycle.js: this
- // sweep retires the run without reaching completion cleanup, and the hook
- // above was the last sentinel read. A hard kill (`pm2 restart`, reboot)
- // lands here, so this is the path that leaves dirt in a managed app repo.
- await removeCompletionSentinel({ agentId: agent.id, agentState: agent })
- .catch(err => emitLog('warn', `Completion sentinel removal failed for ${agent.id}: ${err.message}`, { agentId: agent.id }));
- if (agent.metadata?.runId) {
- const bufferedOutput = Array.isArray(agent.output)
- ? agent.output.map((entry) => typeof entry === 'string' ? entry : entry?.line).filter(Boolean).join('\n')
- : '';
- const output = await tryReadFile(join(PATHS.cosAgents, agent.id, 'output.txt')) ?? bufferedOutput;
- const startedAt = Date.parse(agent.startedAt);
- const duration = Number.isFinite(startedAt) ? Math.max(0, Date.now() - startedAt) : 0;
- // Close the run BEFORE the agent record. If the run write fails, the
- // agent remains eligible for the next sweep; if the later agent write
- // fails, completeAgentRun's endTime guard makes this retry harmless.
- await completeAgentRun(agent.metadata.runId, isPrivateSecurityTask(task) || isPrivateSecurityTask(agent) ? 'Private security assessment interrupted; inspect its local assessment archive.' : output, interrupted ? 143 : 1, duration, {
- message: errorMessage,
- category: interrupted ? 'interrupted' : 'orphaned',
- });
- }
- await completeAgent(agent.id, {
- success: false,
- error: errorMessage,
- orphaned: true,
- // 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,
+ exitCode: interrupted ? 143 : 1,
+ duration: Number.isFinite(startedAt) ? Math.max(0, Date.now() - startedAt) : 0,
+ errorMessage,
+ category: interrupted ? 'interrupted' : 'orphaned',
+ // 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. Kept off the shared `retireDeadAgent` shape since the
+ // post-restart path has no equivalent fact to report.
+ agentResultExtra: { interruptedByRestart: interrupted },
});
cleanedCount++;
@@ -1458,10 +1439,11 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
if (task.status === 'completed') return;
const { privateSecurityScratchCwd } = await import('../lib/privateSecuritySandbox.js');
await rm(privateSecurityScratchCwd(agentId), { recursive: true, force: true });
- await updateTask(taskId, { status: 'blocked', metadata: { ...task.metadata,
+ const taskUpdate = await stampLiExecutionVerdict({ status: 'blocked', metadata: { ...task.metadata,
blockedAt: new Date().toISOString(), blockedCategory: 'private-security-assessment-failed',
blockedReason: 'Private assessment was interrupted. Inspect its local output and explicitly rerun it; no automatic investigation or provider fallback will run.',
- } }, task.taskType || 'user');
+ } }, task, { success: false });
+ await updateTask(taskId, taskUpdate, task.taskType || 'user');
return;
}
@@ -1519,7 +1501,8 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
&& await committedDuringRun(agentMetadata?.workspacePath || ROOT_DIR, orphanRunStartedAt);
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');
+ const taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success: true });
+ await updateTask(taskId, taskUpdate, task.taskType || 'user');
return;
}
@@ -1622,7 +1605,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
taskId, cooldownMinutes, retryCount
});
- await updateTask(taskId, {
+ await updateTask(taskId, await stampLiExecutionVerdict({
status: 'blocked',
metadata: {
...task.metadata,
@@ -1638,7 +1621,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
blockedAt: new Date().toISOString(),
cooldownUntil: new Date(Date.now() + cooldownRemaining).toISOString()
}
- }, taskType);
+ }, task, { success: false }), taskType);
} else {
const reason = totalExceeded
? `total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`
@@ -1649,7 +1632,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
totalSpawns
});
- await updateTask(taskId, {
+ await updateTask(taskId, await stampLiExecutionVerdict({
status: 'blocked',
metadata: {
...task.metadata,
@@ -1660,7 +1643,7 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
blockedCategory: 'max-retries',
blockedAt: new Date().toISOString()
}
- }, taskType);
+ }, task, { success: false }), taskType);
const description = `[Auto-Fix] Investigate repeated agent orphaning for task ${taskId}
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 557ae63829..86f2f562e6 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -29,8 +29,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ChildProcess } from '../lib/childProcess.js';
import { readFileSync } from 'fs';
-import { mkdtemp, writeFile, readFile, rm } from 'fs/promises';
-import { tmpdir } from 'os';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
@@ -104,7 +102,17 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
cleanupAgentWorktree: vi.fn(),
resolveTaskResumePatch: vi.fn().mockResolvedValue({})
}));
-vi.mock('./agentFinalization.js', () => ({ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined) }));
+// `retireDeadAgent`'s own step-order/private-security/argument-shaping behavior has its
+// own suite (`agentFinalization.retireDeadAgent.test.js`) against the real function — this
+// file only asserts that the sweep WIRES it with the right facts. Mocked here as a plain
+// stub (not `importOriginal`) to keep this suite from dragging in agentFinalization.js's
+// whole provider/codeReview/agentCompletion closure, same reason the rest of this file
+// mocks its neighbors.
+vi.mock('./agentFinalization.js', () => ({
+ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined),
+ retireDeadAgent: vi.fn().mockResolvedValue({ success: false }),
+ stampLiExecutionVerdict: vi.fn(async (taskUpdate) => taskUpdate),
+}));
// 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) => ({
@@ -123,6 +131,7 @@ vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettle
vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));
import { handleOrphanedTask, pauseAgent, resumeAgent, relaunchAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';
+import { retireDeadAgent, stampLiExecutionVerdict } from './agentFinalization.js';
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
import { updateRun, getProject } from './creativeDirector/local.js';
@@ -132,7 +141,6 @@ import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask, force
import { pauseAgentViaRunner, terminateAgentViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
-import { completeAgentRun } from './agentRunTracking.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
import { activeAgents, runnerAgents, pausedAgents, consumePausedAgentExit } from './agentState.js';
@@ -245,9 +253,9 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
await cleanupOrphanedAgents();
- expect(markAgentComplete).toHaveBeenCalledWith('agent-stale', expect.objectContaining({
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-stale' }),
success: false,
- orphaned: true,
}));
});
@@ -255,15 +263,19 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
// cleanup, so this sweep is the path that retires the run — and a
// worktree-less run executes in a REAL checkout (the PortOS repo or a managed
// app's own), where a skipped sentinel is untracked dirt in the user's repo.
- it("removes the reaped run's completion sentinel from its workspace", async () => {
- const workspace = await mkdtemp(join(tmpdir(), 'orphan-sentinel-'));
- await writeFile(join(workspace, '.agent-done-agent-stale'), '## Summary\nDied mid-run');
+ //
+ // Sentinel removal itself moved to the shared `retireDeadAgent` (#8440) and is
+ // exercised for real (actual fs writes) in `agentCompletionCleanup.test.js` and
+ // against the mocked leaf in `agentFinalization.retireDeadAgent.test.js`. This
+ // suite's job is only to confirm the sweep hands `retireDeadAgent` the agent
+ // whose metadata carries the workspace the sentinel lives in.
+ it("hands the reaped agent's workspace to retireDeadAgent so its completion sentinel is removed", async () => {
getAgents.mockResolvedValueOnce([{
id: 'agent-stale',
status: 'running',
pid: 2147483646,
taskId: 'task-1',
- metadata: { useRunner: true, executionMode: 'runner', workspacePath: workspace },
+ metadata: { useRunner: true, executionMode: 'runner', workspacePath: '/example/workspace' },
}]);
getActiveAgentsFromRunner.mockResolvedValueOnce([{
id: 'agent-stale', pid: 2147483646, kind: 'cli', processActive: false, liveness: 'pid',
@@ -272,9 +284,9 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
await cleanupOrphanedAgents();
- await expect(readFile(join(workspace, '.agent-done-agent-stale')))
- .rejects.toMatchObject({ code: 'ENOENT' });
- await rm(workspace, { recursive: true, force: true });
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-stale', metadata: expect.objectContaining({ workspacePath: '/example/workspace' }) }),
+ }));
});
it('does not reap a live runner-owned TUI advertised via onExit liveness', async () => {
@@ -318,9 +330,9 @@ describe('cleanupOrphanedAgents — startup recovery coordination', () => {
await cleanupOrphanedAgents();
- expect(markAgentComplete).toHaveBeenCalledWith('agent-stale', expect.objectContaining({
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-stale' }),
success: false,
- orphaned: true,
}));
expect(runnerAgents.has('agent-stale')).toBe(false);
});
@@ -570,6 +582,79 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {
});
expect(addTask.mock.calls[0][0].description).toContain('Why this is held for you');
});
+
+ // #8440: before this fix, only the post-restart recovery path
+ // (`completeUntrackedAgentFromCosState`) stamped the LI hand-off verdict — a
+ // task orphaned by the boot/health-check sweep (this function) reached a
+ // terminal state with NO verdict, so the originating peer never learned
+ // whether its proposal worked. These three pin every terminal settlement
+ // `handleOrphanedTask` itself makes. `stampLiExecutionVerdict` is mocked to an
+ // identity passthrough in this file (see the `./agentFinalization.js` mock
+ // above) — its own no-op/build behavior is covered for real in
+ // `agentFinalization.stampLiExecutionVerdict.test.js` — so these assert on the
+ // WIRING: is it called, with the task and the right success flag, before the
+ // task is persisted terminal.
+ describe('stamps the LI execution verdict on every terminal settlement (#8440)', () => {
+ const liTask = (overrides) => ({
+ id: 'task-foo',
+ status: 'in_progress',
+ taskType: 'user',
+ description: 'Original work',
+ metadata: { liProposal: { appId: 'app-example', slug: 'example-slug' }, ...overrides },
+ });
+
+ it('stamps success:false when the retry budget is exhausted (blocked, max-retries)', async () => {
+ const exhaustedTask = liTask({ orphanRetryCount: 2, totalSpawnCount: 2 });
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+
+ await handleOrphanedTask('task-foo', 'agent-orphaned', vi.fn().mockResolvedValue(exhaustedTask));
+
+ expect(stampLiExecutionVerdict).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'blocked' }),
+ exhaustedTask,
+ { success: false }
+ );
+ expect(updateTask).toHaveBeenCalledWith('task-foo', expect.objectContaining({ status: 'blocked' }), 'user');
+ });
+
+ it('stamps success:false when the orphan retry is in cooldown (blocked, orphan-cooldown)', async () => {
+ const cooldownTask = liTask({ orphanRetryCount: 1, lastOrphanedAt: new Date().toISOString() });
+
+ await handleOrphanedTask('task-foo', 'agent-orphaned', vi.fn().mockResolvedValue(cooldownTask));
+
+ expect(stampLiExecutionVerdict).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'blocked' }),
+ cooldownTask,
+ { success: false }
+ );
+ });
+
+ it('stamps success:true when the commit probe finds the dead run actually finished (completed)', async () => {
+ const task = liTask({});
+ committedDuringRun.mockResolvedValueOnce(true);
+
+ await handleOrphanedTask('task-foo', 'agent-orphaned', vi.fn().mockResolvedValue(task), {
+ agentStartedAt: new Date().toISOString(),
+ });
+
+ expect(stampLiExecutionVerdict).toHaveBeenCalledWith(
+ { status: 'completed' },
+ task,
+ { success: true }
+ );
+ expect(updateTask).toHaveBeenCalledWith('task-foo', expect.objectContaining({ status: 'completed' }), 'user');
+ });
+
+ it('still calls the stamp (a no-op for it) for a task with no liProposal', async () => {
+ const task = { id: 'task-foo', status: 'in_progress', taskType: 'user',
+ description: 'Original work', metadata: { orphanRetryCount: 2, totalSpawnCount: 2 } };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+
+ await handleOrphanedTask('task-foo', 'agent-orphaned', vi.fn().mockResolvedValue(task));
+
+ expect(stampLiExecutionVerdict).toHaveBeenCalledWith(expect.anything(), task, { success: false });
+ });
+ });
});
describe('pauseAgent', () => {
@@ -1721,33 +1806,27 @@ describe('orphan retries resume what the dead run left behind', () => {
expect(resolveTaskResumePatch).not.toHaveBeenCalled();
});
- it('closes the orphaned run before completing the agent record', async () => {
+ // The run-record-before-agent-record ordering, and the runId-gated skip, are now
+ // `retireDeadAgent`'s own contract — pinned for real (mocked leaves, real function)
+ // in `agentFinalization.retireDeadAgent.test.js`. This suite only confirms the sweep
+ // hands it the per-caller facts (the interrupted/orphaned exit code, the elapsed
+ // duration, the error message and category) it needs to close that run correctly.
+ it('hands retireDeadAgent the orphaned exit code, duration and category for the dead run', async () => {
getAgents.mockResolvedValue([{
...deadAgent,
startedAt: new Date(Date.now() - 1000).toISOString(),
metadata: { ...deadMetadata, runId: 'run-orphan' },
output: [{ line: 'last buffered line' }],
}]);
- const order = [];
- completeAgentRun.mockImplementation(() => { order.push('run'); });
- markAgentComplete.mockImplementation(() => { order.push('agent'); });
await cleanupOrphanedAgents();
- expect(completeAgentRun).toHaveBeenCalledWith(
- 'run-orphan',
- 'last buffered line',
- 1,
- expect.any(Number),
- { message: 'Agent process terminated unexpectedly', category: 'orphaned' },
- );
- expect(order.slice(0, 2)).toEqual(['run', 'agent']);
- });
-
- it('skips run completion for legacy agents without a runId', async () => {
- await cleanupOrphanedAgents();
-
- expect(completeAgentRun).not.toHaveBeenCalled();
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ exitCode: 1,
+ duration: expect.any(Number),
+ errorMessage: 'Agent process terminated unexpectedly',
+ category: 'orphaned',
+ }));
});
// A caller that doesn't know which agent died (resetOrphanedTasks on an archived
@@ -2098,18 +2177,15 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
await cleanupOrphanedAgents();
- expect(markAgentComplete).toHaveBeenCalledWith('agent-dead', expect.objectContaining({
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agent: expect.objectContaining({ id: 'agent-dead' }),
success: false,
- interruptedByRestart: true,
- error: expect.stringContaining('restart'),
+ exitCode: 143,
+ duration: 0,
+ errorMessage: expect.stringContaining('restart'),
+ category: 'interrupted',
+ agentResultExtra: { interruptedByRestart: true },
}));
- expect(completeAgentRun).toHaveBeenCalledWith(
- 'run-interrupted',
- '',
- 143,
- 0,
- { message: expect.stringContaining('restart'), category: 'interrupted' },
- );
expect(clearHostShutdownMarker).toHaveBeenCalled();
});
@@ -2119,7 +2195,9 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
await cleanupOrphanedAgents();
expect(clearHostShutdownMarker).not.toHaveBeenCalled();
- expect(markAgentComplete).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ interruptedByRestart: false }));
+ expect(retireDeadAgent).toHaveBeenCalledWith(expect.objectContaining({
+ agentResultExtra: { interruptedByRestart: false },
+ }));
});
});