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

refactor: make completion-cleanup step-failure policy and PR ownership explicit per entry point (#9202)

Adam Eivy226fbec0dc53
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 755ac8114b..3fa8027c68 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -47,6 +47,25 @@ import { ensureTaskThread } from './brainTaskThreads.js';
const ROOT_DIR = PATHS.root;
+/**
+ * What a failed completion-cleanup step does to the steps after it. Chosen once,
+ * at the entry point, because it is a property of the CALLER: the runner hands a
+ * throw to its completion handler; the in-process spawners, which run this from
+ * a `finally`, log it and keep going so one bad step cannot strand the worktree
+ * cleanup or the pipeline hand-off behind it.
+ */
+export const STEP_ERROR_POLICY = Object.freeze({
+ PROPAGATE: 'propagate',
+ LOG_AND_CONTINUE: 'log-and-continue',
+});
+
+const STEP_FAILURE_HANDLERS = {
+ [STEP_ERROR_POLICY.PROPAGATE]: (err) => { throw err; },
+ [STEP_ERROR_POLICY.LOG_AND_CONTINUE]: (err, name, { agentId, task }) => {
+ emitLog('warn', `${name} failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id });
+ },
+};
+
/**
* Advance a pipeline to its next stage after the current stage completes.
* Creates a new task for the next stage or marks the pipeline as complete/failed.
@@ -295,9 +314,11 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
const agentState = await getAgentState(agentId).catch(() => null);
try {
+ // Inside the `try`: a throw here must still reach the retry-hold release.
+ const prOwnership = resolveRunnerPrOwnership({ task, agent, agentState });
await runCompletionCleanupSteps({
- agentId, task, agent, agentState, effectiveSuccess, outputBuffer, prClaimVerified, branchProvenEmpty,
- });
+ agentId, task, agent, agentState, effectiveSuccess, prOwnership, outputBuffer, prClaimVerified, branchProvenEmpty,
+ }, { onStepError: STEP_ERROR_POLICY.PROPAGATE });
} finally {
await releaseRetryHold({
agentId,
@@ -310,23 +331,23 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
/**
* One ordered post-finalize sequence for every completion path. Public entry
- * points own retry-hold release independently of these steps.
+ * points own retry-hold release independently of these steps, and choose
+ * `onStepError` (a `STEP_ERROR_POLICY` value) for how a failed step is treated.
+ *
+ * `context.prOwnership` is `{ taskOpenPR, agentOpensOwnPr }`, resolved by the
+ * entry point from its own source of truth.
*/
-async function runCompletionCleanupSteps(context) {
- // The spawners have always logged failed steps and continued; the runner
- // propagates them to its completion handler. Both execute the same sequence.
- const runStep = (name, step) => step().catch(err => {
- if (!context.continueOnError) throw err;
- emitLog('warn', `${name} failed for ${context.agentId}: ${err.message}`, { agentId: context.agentId, taskId: context.task?.id });
- });
+async function runCompletionCleanupSteps(context, { onStepError }) {
+ const onFailure = STEP_FAILURE_HANDLERS[onStepError];
+ if (!onFailure) throw new Error(`Unknown completion-cleanup step error policy: ${onStepError}`);
+ const runStep = (name, step) => step().catch(err => onFailure(err, name, context));
await runStep('JIRA hand-off', () => completeJiraHandOff(context));
await runStep('Plan question notification', () => notifyPlanQuestionIfNeeded(context));
await runStep('Pipeline progression', () => handlePipelineProgression(context.task, context.agentId, context.effectiveSuccess));
await runStep('Creative Director completion', () => advanceCreativeDirectorIfNeeded(context));
const cleanupWarnings = await runStep('Worktree cleanup', () => completeWorktreeCleanup(context));
await runStep('Cleanup warning reporting', () => reportWorktreeCleanupWarnings({ ...context, cleanupWarnings }));
- // Last, and never fatal: `runStep` RETHROWS on the runner path
- // (`continueOnError` is unset there), so a janitorial `rm` that hits EPERM
+ // Last, and never fatal under either policy: a janitorial `rm` that hits EPERM
// must not be able to abort the worktree cleanup and pipeline hand-off above.
//
// Gated on the record actually reaching an outcome. `finalizeAgent` runs
@@ -524,13 +545,12 @@ export async function removeCompletionSentinel({ agentId, agent, agentState }) {
await rmGuarded(resolveDoneSentinelPath(workspace, agentId), { force: true });
}
-async function completeWorktreeCleanup({ agentId, task, agent, agentState, effectiveSuccess, prOwnership, outputBuffer, prClaimVerified, branchProvenEmpty }) {
+async function completeWorktreeCleanup({ agentId, task, effectiveSuccess, prOwnership, outputBuffer, prClaimVerified, branchProvenEmpty }) {
if (task?.metadata?.jiraBranch) return;
- const ownership = prOwnership ?? resolveRunnerPrOwnership({ task, agent, agentState });
return cleanupAgentWorktree(agentId, effectiveSuccess, await resolveWorktreeCleanupOptions({
agentId, task, outputBuffer,
- taskOpenPR: ownership.taskOpenPR,
- agentOpensOwnPr: ownership.agentOpensOwnPr,
+ taskOpenPR: prOwnership.taskOpenPR,
+ agentOpensOwnPr: prOwnership.agentOpensOwnPr,
prClaimVerified, branchProvenEmpty,
}));
}
@@ -574,16 +594,17 @@ async function reportWorktreeCleanupWarnings({ agentId, task, cleanupWarnings })
* must reach cleanup, or a run that opened no PR is cleaned up as a success and
* loses its retry state (#3358).
*/
-export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwnership, prClaimVerified = false, branchProvenEmpty = false, outputBuffer }) {
+export async function runSpawnerCompletionCleanup({ agentId, task, success: effectiveSuccess, prOwnership, prClaimVerified = false, branchProvenEmpty = false, outputBuffer }) {
+ let agentState = null;
try {
const { getAgent } = await import('./cos.js');
- const agentState = await getAgent(agentId).catch(() => null);
+ agentState = await getAgent(agentId).catch(() => null);
await runCompletionCleanupSteps({
- agentId, task, agentState, effectiveSuccess: success, prOwnership,
- prClaimVerified, branchProvenEmpty, outputBuffer, continueOnError: true,
- });
+ agentId, task, agentState, effectiveSuccess, prOwnership,
+ prClaimVerified, branchProvenEmpty, outputBuffer,
+ }, { onStepError: STEP_ERROR_POLICY.LOG_AND_CONTINUE });
} finally {
- await releaseRetryHold({ agentId, task, success })
+ await releaseRetryHold({ agentId, task, success: effectiveSuccess, agentMetadata: agentState?.metadata ?? null })
.catch(err => emitLog('warn', `Retry-hold release failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id }));
}
}
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 48a47d7f6a..538a92c71a 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -41,6 +41,7 @@ vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedV
import { handlePipelineProgression, runAgentCompletionCleanup, runSpawnerCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';
import { updateTask, addTask, reviveBlockedTask, getAgent } from './cos.js';
+import { emitLog } from './cosEvents.js';
import { cleanupAgentWorktree, releaseRetryHold, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { promptOpensOwnPr } from './promptSections/completion.js';
@@ -530,7 +531,7 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (
expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.objectContaining({
prCreation: 'always', skipMerge: false, agentOutput: 'out', originalTask: task,
}));
- expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task, success: true });
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1', task, success: true }));
});
it('threads the resolved reviewer options and the task\'s PR completion through to the worktree cleanup', async () => {
@@ -573,7 +574,7 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (
expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', false, expect.objectContaining({ prCreation: 'always' }));
expect(cleanupAgentWorktree.mock.calls[0][2]).not.toHaveProperty('reviewers');
- expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task: args.task, success: false });
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1', task: args.task, success: false }));
});
// ...and a worktree cleanup that rejects must not either (#3373): the hold is
@@ -584,7 +585,7 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (
await expect(runSpawnerCompletionCleanup(args)).resolves.toBeUndefined();
- expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task: args.task, success: false });
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1', task: args.task, success: false }));
});
it('continues cleanup and releases the hold when pipeline persistence fails', async () => {
@@ -592,7 +593,7 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (
const task = { id: 't', metadata: { pipeline: runningPipeline({ currentStage: 1 }) } };
await runSpawnerCompletionCleanup(spawnerArgs({ task }));
expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.any(Object));
- expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task, success: true });
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1', task, success: true }));
});
// The dominant path: a harness that opened and landed its own PR. Cleanup can
@@ -686,6 +687,27 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {
expect(await readFile(join(workspace, '.agent-done-a2'), 'utf8')).toContain('Still working');
});
+ // The one difference between the two entry points. A failing step BEFORE the
+ // worktree cleanup (pipeline persistence here — a JIRA-branch task skips the
+ // cleanup by design, so it cannot show the contrast) either aborts the
+ // sequence (runner, handled by its completion handler) or is logged while the
+ // remaining steps still run (spawners, which call this from a `finally`).
+ // Both still release the retry hold.
+ it('treats a failing early step per entry point: runner propagates and skips worktree cleanup, spawner logs and continues', async () => {
+ updateTask.mockRejectedValueOnce(new Error('pipeline unavailable'));
+ const pipelineMeta = { pipeline: runningPipeline({ currentStage: 1 }) };
+
+ if (path === 'runner') {
+ await expect(complete(pipelineMeta)).rejects.toThrow('pipeline unavailable');
+ expect(cleanupAgentWorktree).not.toHaveBeenCalled();
+ } else {
+ await complete(pipelineMeta);
+ expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('Pipeline progression failed for a1: pipeline unavailable'), expect.any(Object));
+ expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.any(Object));
+ }
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }));
+ });
+
it('turns the plan-question marker into a notification and consumes it before cleanup', async () => {
const marker = '# Plan Question: Choose the example scope\nPlease clarify the example.';
await writeFile(join(workspace, '.plan-questions.md'), marker);