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

address review (codex): retire CD task + advance on orphan-settle to fix boot-recovery race

Adam Eivyae5fd21ace29
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index f48692e284..b1ef7516f2 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -486,10 +486,30 @@ export async function isPidAlive(pid) {
* its `runs[]` row stuck `running`. `maybeEnqueuePlan`'s guard then treats that
* non-terminal run as "a worker is already on it" and refuses to re-dispatch — so
* the project wedges in `planning` until the NEXT server restart runs boot
- * recovery (`recoverInFlightProjects`). Reaping the run here — mirroring recovery's
- * reap — lets the project advance without a restart (the orphan-task retry then
- * re-dispatches the plan). No-op for non-CD tasks; the `creativeDirector/local.js`
- * import is deferred so non-CD orphans pay nothing. Exported for unit testing.
+ * recovery (`recoverInFlightProjects`). This helper reproduces recovery's per-project
+ * reap so the project recovers without a restart. It does THREE things, in the
+ * same order and shape recovery does — this is boot-ordering-critical:
+ *
+ * 1. **Fail the stuck run** so `maybeEnqueuePlan`'s non-terminal-run guard clears.
+ * 2. **Retire the CoS task** (`status:'completed'`), NOT leave it running for
+ * `handleOrphanedTask` to requeue. This is load-bearing for boot ordering:
+ * `cleanupOrphanedAgents` runs BEFORE `recoverInFlightProjects` awaits its gate
+ * (`cos.js` start sequence), and recovery only reaps runs still marked
+ * `running` — so once we've failed the run in step 1, recovery would no longer
+ * retire this task. If we left it, `handleOrphanedTask` would requeue a stale
+ * agent that races recovery's fresh dispatch. Retiring it here makes
+ * `handleOrphanedTask` skip it (it skips `completed` tasks) — matching exactly
+ * what recovery's own `updateTask(status:'completed')` reap does. (#2705 review)
+ * 3. **Re-dispatch via the deduped advance loop** (`advanceAfterPlanStepSettled` for
+ * directive projects, `advanceAfterSceneSettled` otherwise) — the SAME functions
+ * recovery calls, so the project retries on its own in steady state, and at boot
+ * the call is idempotent with recovery's advance (both go through the in-memory
+ * inflight-dedup guards, so no double dispatch). This deliberately does NOT use
+ * `handleOrphanedTask`/`resetOrphanedTasks`' raw task respawn, which the
+ * `cdRecoveryDone` gate exists to keep from racing recovery.
+ *
+ * No-op for non-CD tasks; the CD-module imports are deferred so non-CD orphans pay
+ * nothing. Exported for unit testing.
*
* @param {object|null} task - the orphaned agent's task record.
* @returns {Promise<boolean>} true if a CD run was settled, false for a non-CD task.
@@ -497,12 +517,36 @@ export async function isPidAlive(pid) {
export async function settleOrphanedCreativeDirectorRun(task) {
const cd = task?.metadata?.creativeDirector;
if (!cd?.projectId || !cd?.runId) return false;
- const { updateRun } = await import('./creativeDirector/local.js');
+ const now = new Date().toISOString();
+ const { updateRun, getProject } = await import('./creativeDirector/local.js');
+ // 1. Fail the stuck run (clears the maybeEnqueuePlan non-terminal-run guard).
await updateRun(cd.projectId, cd.runId, {
status: 'failed',
- completedAt: new Date().toISOString(),
+ completedAt: now,
failureReason: 'agent process terminated unexpectedly (orphaned)',
}).catch((err) => console.log(`⚠️ CD orphan settle: run ${cd.runId?.slice(0, 8)} of ${cd.projectId} failed: ${err.message}`));
+ // 2. Retire the task the same way recovery does, so handleOrphanedTask (which
+ // skips `completed` tasks) can't requeue a stale agent to race recovery.
+ // CD tasks are internal (agentBridge#persistAndEmit adds them as 'internal').
+ if (task.id) {
+ await updateTask(task.id, {
+ status: 'completed',
+ metadata: { ...task.metadata, orphanedRunSettledAt: now },
+ }, 'internal').catch((err) => console.log(`⚠️ CD orphan settle: retire task ${task.id} failed: ${err.message}`));
+ }
+ // 3. Re-dispatch via the deduped advance loop (fire-and-forget, like recovery).
+ const project = await getProject(cd.projectId).catch(() => null);
+ if (project && project.status !== 'paused' && project.status !== 'failed') {
+ if (project.directive) {
+ const { advanceAfterPlanStepSettled } = await import('./creativeDirector/planAdvance.js');
+ advanceAfterPlanStepSettled(cd.projectId)
+ .catch((e) => console.log(`⚠️ CD orphan settle: plan advance for ${cd.projectId} failed: ${e.message}`));
+ } else {
+ const { advanceAfterSceneSettled } = await import('./creativeDirector/completionHook.js');
+ advanceAfterSceneSettled(cd.projectId)
+ .catch((e) => console.log(`⚠️ CD orphan settle: advance for ${cd.projectId} failed: ${e.message}`));
+ }
+ }
return true;
}
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index f685948435..c7c2a2f5fd 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -74,10 +74,17 @@ vi.mock('./agentLifecycle.js', () => ({
syncRunnerAgents: vi.fn().mockResolvedValue(0)
}));
vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));
-vi.mock('./creativeDirector/local.js', () => ({ updateRun: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./creativeDirector/local.js', () => ({
+ updateRun: vi.fn().mockResolvedValue(undefined),
+ getProject: vi.fn().mockResolvedValue(null),
+}));
+vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));
import { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun } from './agentManagement.js';
-import { updateRun } from './creativeDirector/local.js';
+import { updateRun, getProject } from './creativeDirector/local.js';
+import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';
+import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';
import { updateTask, addTask, getTaskById } from './cos.js';
import { updateAgent } from './cosAgents.js';
import { pauseAgentViaRunner } from './cosRunnerClient.js';
@@ -87,26 +94,62 @@ import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
beforeEach(() => vi.clearAllMocks());
- it('marks the orphaned CD plan agent run failed with an orphan reason', async () => {
+ it('fails the run AND retires the task (so handleOrphanedTask skips it), then advances the plan', async () => {
+ // Directive project → the deduped plan-advance loop re-dispatches.
+ getProject.mockResolvedValueOnce({ id: 'cd-p1', status: 'planning', directive: { goal: 'x' } });
const task = {
id: 'cd-cd-p1-plan-abc',
metadata: { creativeDirector: { projectId: 'cd-p1', runId: 'run-abc', kind: 'plan', sceneId: null } },
};
const settled = await settleOrphanedCreativeDirectorRun(task);
expect(settled).toBe(true);
+ // (1) run failed with an orphan reason
expect(updateRun).toHaveBeenCalledWith(
'cd-p1',
'run-abc',
expect.objectContaining({ status: 'failed', failureReason: expect.stringContaining('orphaned') }),
);
+ // (2) task retired to `completed` — the boot-race fix: handleOrphanedTask skips completed tasks
+ expect(updateTask).toHaveBeenCalledWith(
+ 'cd-cd-p1-plan-abc',
+ expect.objectContaining({ status: 'completed' }),
+ 'internal',
+ );
+ // (3) re-dispatch via the deduped advance loop, not raw task respawn
+ expect(advanceAfterPlanStepSettled).toHaveBeenCalledWith('cd-p1');
+ expect(advanceAfterSceneSettled).not.toHaveBeenCalled();
+ });
+
+ it('uses the scene-advance loop for a legacy (non-directive) project', async () => {
+ getProject.mockResolvedValueOnce({ id: 'cd-p2', status: 'rendering', directive: null });
+ await settleOrphanedCreativeDirectorRun({
+ id: 'cd-cd-p2-evaluate-x',
+ metadata: { creativeDirector: { projectId: 'cd-p2', runId: 'run-xyz', kind: 'evaluate', sceneId: 's1' } },
+ });
+ expect(advanceAfterSceneSettled).toHaveBeenCalledWith('cd-p2');
+ expect(advanceAfterPlanStepSettled).not.toHaveBeenCalled();
});
- it('is a no-op (no updateRun) for a non-CD task or a CD task missing projectId/runId', async () => {
+ it('does NOT re-dispatch a paused or failed project', async () => {
+ getProject.mockResolvedValueOnce({ id: 'cd-p3', status: 'paused', directive: { goal: 'x' } });
+ await settleOrphanedCreativeDirectorRun({
+ id: 'cd-cd-p3-plan-z',
+ metadata: { creativeDirector: { projectId: 'cd-p3', runId: 'run-z', kind: 'plan' } },
+ });
+ // still failed the run + retired the task, but no advance for a paused project
+ expect(updateRun).toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith('cd-cd-p3-plan-z', expect.objectContaining({ status: 'completed' }), 'internal');
+ expect(advanceAfterPlanStepSettled).not.toHaveBeenCalled();
+ expect(advanceAfterSceneSettled).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op (no updateRun/updateTask) for a non-CD task or a CD task missing projectId/runId', async () => {
expect(await settleOrphanedCreativeDirectorRun({ id: 't', metadata: {} })).toBe(false);
expect(await settleOrphanedCreativeDirectorRun(null)).toBe(false);
// metadata present but incomplete — must not settle a run it can't identify.
expect(await settleOrphanedCreativeDirectorRun({ metadata: { creativeDirector: { projectId: 'cd-p1' } } })).toBe(false);
expect(updateRun).not.toHaveBeenCalled();
+ expect(updateTask).not.toHaveBeenCalled();
});
});