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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: fail a CD plan/treatment run that signals done but never PATCHes (#4146)
[._.]/ Adam Eivy32f5e52f3b91
diff --git a/.changelog/next/fixed-issue-4146.md b/.changelog/next/fixed-issue-4146.mdnew file mode 100644index 0000000000..f412c163df--- /dev/null+++ b/.changelog/next/fixed-issue-4146.md@@ -0,0 +1 @@+- Creative Director: a plan/treatment agent that exits cleanly without writing its plan/treatment is now recorded as a failed run and, after two consecutive empty completions, the project is paused with an actionable reason instead of endlessly re-dispatching the same incapable modeldiff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.jsindex 0661b6a4c8..615d9264d2 100644--- a/server/lib/creativeDirectorPresets.js+++ b/server/lib/creativeDirectorPresets.js@@ -79,6 +79,17 @@ export const PLAN_STEP_TERMINAL_SUCCESS = Object.freeze(new Set(['done', 'skippe// residuals for human review (autopilot's convergence-pause contract).export const MAX_REPLAN_ROUNDS = 2;+// Bounded re-dispatch of a COGNITIVE stage (plan / treatment) whose agent keeps+// exiting cleanly without writing its deliverable (#4146). A non-tool-calling+// local model narrates a done-message and PATCHes nothing; re-handing it the same+// task is guaranteed to fail the same way, so after this many consecutive empty+// completions the stage is surfaced to the user as a blocked/paused project+// (naming the remedy: assign a tool-capable model) rather than re-dispatched.+// 2 — one retry covers a genuine one-off (a truncated response, a transient+// provider hiccup) without burning a third identical run on a model that has now+// demonstrated twice that it cannot perform the PATCH.+export const MAX_CONSECUTIVE_MISSED_DELIVERABLES = 2;+/*** Map a project's aspectRatio + quality + scene durationSeconds to the* concrete render-API body.diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex 808b9307b9..1ac4e31755 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -21,6 +21,7 @@ import { getToolSpecs } from '../creative/toolRegistry.js';import { getSettings } from '../settings.js';import { resolveStagePin } from './projectsLogic.js';import { recordRun } from './local.js';+import { DELIVERABLE_KINDS, deliverableMark } from './deliverableGate.js';// Treatment and production planning are CoS tasks, so unlike scene evaluation// they need a CLI/TUI provider with an agent harness. Resolution prefers the@@ -140,12 +141,21 @@ async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {}// Record the run as `running` so the Runs tab shows in-flight state.// completionHook updates the same runId on finish.+ //+ // `deliverableMark` is the BASELINE fingerprint of what this stage is supposed+ // to write (#4146). completionHook compares the project's mark against it when+ // the run settles, so an agent that exits 0 having PATCHed nothing is recorded+ // as the failure it is instead of a success the re-dispatch guard skips over.+ // Only stamped for kinds with a verifiable PATCH deliverable — the key is+ // ABSENT (not null) for the rest, which is exactly how `deliverableLanded`+ // recognizes "no baseline recorded" and declines to manufacture a failure.await recordRun(project.id, {runId,taskId: effective.id,kind,sceneId: sceneId || null,status: 'running',+ ...(DELIVERABLE_KINDS.has(kind) ? { deliverableMark: deliverableMark(project, kind) } : {}),}).catch((err) => console.log(`⚠️ CD recordRun(running) failed: ${err.message}`));cosEvents.emit('task:ready', effective);console.log(`📤 CD task enqueued: ${effective.id} (${kind}${sceneId ? ` for ${sceneId}` : ''} on ${project.id})`);diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.jsindex 4d317bc8d6..0911cdfa69 100644--- a/server/services/creativeDirector/agentBridge.test.js+++ b/server/services/creativeDirector/agentBridge.test.js@@ -26,7 +26,7 @@ vi.mock('../creative/toolRegistry.js', () => ({ getToolSpecs: mocks.getToolSpecsvi.mock('../settings.js', () => ({ getSettings: mocks.getSettings }));vi.mock('./local.js', () => ({ recordRun: mocks.recordRun }));-const { enqueueTreatmentTask, enqueuePlanTask } = await import('./agentBridge.js');+const { enqueueTreatmentTask, enqueuePlanTask, enqueueEvaluateTask } = await import('./agentBridge.js');const project = { id: 'cd-1', name: 'Test project', treatment: { scenes: [] } };@@ -165,3 +165,28 @@ describe('persistAndEmit duplicate handling (#2614 — addTask dedup also matcheexpect(taskA.description).not.toBe(taskB.description);});});++describe('deliverable baseline stamped on the run row (#4146)', () => {+ it('records the plan baseline so completionHook can tell a real PATCH from a no-op', async () => {+ mocks.addTask.mockResolvedValue();+ await enqueuePlanTask({ id: 'cd-1', name: 'p', plan: { steps: [{ stepId: 'a' }], replanRounds: 1 } });+ expect(mocks.recordRun.mock.calls[0][1]).toMatchObject({ kind: 'plan', deliverableMark: 'plan:1' });+ });++ it('records a NULL baseline (recorded-and-absent, not "unknown") when there is no plan yet', async () => {+ await enqueuePlanTask({ id: 'cd-1', name: 'p', plan: null });+ const entry = mocks.recordRun.mock.calls[0][1];+ expect(entry).toHaveProperty('deliverableMark', null);+ });++ it('records the treatment baseline', async () => {+ await enqueueTreatmentTask({ id: 'cd-1', name: 'p', treatment: null });+ expect(mocks.recordRun.mock.calls[0][1]).toMatchObject({ kind: 'treatment', deliverableMark: null });+ });++ it('omits the key entirely for a kind with no verifiable PATCH deliverable', async () => {+ mocks.buildEvaluatePrompt.mockResolvedValue('evaluate context');+ await enqueueEvaluateTask({ id: 'cd-1', name: 'p', treatment: { scenes: [{ sceneId: 's1', order: 0 }] } }, { sceneId: 's1', order: 0, intent: 'x' });+ expect(mocks.recordRun.mock.calls[0][1]).not.toHaveProperty('deliverableMark');+ });+});diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsindex c2327c6670..9fe7b9af49 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -33,6 +33,14 @@ import { runStitch } from './stitchRunner.js';import { sampleEvaluationFrames } from '../videoGen/local.js';import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';import { PATHS } from '../../lib/fileUtils.js';+import {+ DELIVERABLE_KINDS,+ blockedStageReason,+ closeDeliverableStreak,+ deliverableLanded,+ exhaustedDeliverableStreak,+ missedDeliverableReason,+} from './deliverableGate.js';export async function handleCreativeDirectorCompletion(task, agentId, success) {const meta = task?.metadata?.creativeDirector;@@ -43,17 +51,35 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {return;}+ // #4146 — a `plan`/`treatment` agent's deliverable is the PATCH its prompt+ // describes, not its exit code. A non-tool-calling model narrates a+ // done-message, exits 0, and writes nothing; recording that as `completed`+ // makes the re-dispatch guard in enqueuePlannerOnce / advanceAfterSceneSettled+ // see no in-flight run and hand the SAME model the SAME task again, forever.+ // Compare the project's deliverable against the baseline stamped on the run at+ // dispatch: an exit-0 run with no PATCH is recorded as the failure it is, so+ // the guard reaps it LIVE instead of waiting for boot recovery.+ const runId = meta.runId;+ const priorRun = runId ? (project.runs || []).find((r) => r.runId === runId) : null;+ const deliverableKind = DELIVERABLE_KINDS.has(meta.kind) ? meta.kind : null;+ const missedDeliverable = Boolean(success && deliverableKind+ && !deliverableLanded(project, deliverableKind, priorRun?.deliverableMark));+// Update / create the run record so the Runs tab reflects this agent run.const completedAt = new Date().toISOString();- const runId = meta.runId;+ const runStatus = success && !missedDeliverable ? 'completed' : 'failed';+ const missedFields = missedDeliverable+ ? { deliverableMissing: true, failureReason: missedDeliverableReason(meta.kind) }+ : {};const updatedExisting = runId? await updateRun(project.id, runId, {agentId,- status: success ? 'completed' : 'failed',+ status: runStatus,completedAt,kind: meta.kind,sceneId: meta.sceneId || null,taskId: task.id,+ ...missedFields,}): null;if (!updatedExisting) {@@ -63,11 +89,20 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {taskId: task.id,kind: meta.kind,sceneId: meta.sceneId || null,- status: success ? 'completed' : 'failed',+ status: runStatus,completedAt,+ ...missedFields,}).catch((err) => console.log(`⚠️ CD recordRun failed: ${err.message}`));}+ if (missedDeliverable) {+ // NOT a project failure: the advance loop below re-dispatches once (the+ // agent may simply have run out of context), and the bounded gate in+ // enqueuePlannerOnce / the no-treatment branch parks the project once the+ // stage has come back empty MAX_CONSECUTIVE_MISSED_DELIVERABLES times.+ console.log(`⚠️ CD ${meta.kind} run on ${project.id} exited cleanly but never wrote its ${meta.kind} — run marked failed`);+ }+if (!success) {// Surface a concrete reason on the project so the UI's failure banner// has actionable context. Without this, a project flips to 'failed'@@ -220,6 +255,19 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {(r) => r.kind === 'treatment' && r.status !== 'completed' && r.status !== 'failed');if (hasInflightTreatmentRun || inflightTreatment.has(projectId)) return;+ // #4146 — bounded blocked-stage gate. Once the treatment agent has come back+ // empty MAX_CONSECUTIVE_MISSED_DELIVERABLES times in a row, re-dispatching+ // the same task to the same model is guaranteed to fail the same way. Park+ // the project with an actionable reason instead, and CLOSE the streak so a+ // Resume after switching models gets a fresh budget rather than re-pausing.+ const emptyStreak = exhaustedDeliverableStreak(project.runs, 'treatment');+ if (emptyStreak) {+ await closeDeliverableStreak(project.id, project.runs, 'treatment');+ await updateProject(project.id, { status: 'paused', failureReason: blockedStageReason('treatment', emptyStreak) })+ .catch((e) => console.log(`⚠️ CD updateProject(paused) for ${project.id} failed: ${e.message}`));+ console.log(`⏸️ CD project ${project.id}: treatment agent came back empty ${emptyStreak}× — paused for a model change`);+ return;+ }inflightTreatment.add(projectId);await updateProject(project.id, { status: 'planning' }).catch((e) => { inflightTreatment.delete(projectId); throw e; });diff --git a/server/services/creativeDirector/completionHook.test.js b/server/services/creativeDirector/completionHook.test.jsnew file mode 100644index 0000000000..949f19f41c--- /dev/null+++ b/server/services/creativeDirector/completionHook.test.js@@ -0,0 +1,179 @@+/**+ * CD completion hook — deliverable verification (#4146).+ *+ * A `plan`/`treatment` agent's deliverable is the PATCH its prompt describes, not+ * its exit code. These lock the finalization semantics: an exit-0 run that never+ * PATCHed is recorded `failed` (so the live re-dispatch guard reaps it instead of+ * boot recovery), a run that DID PATCH is recorded `completed`, and the bounded+ * gate parks the project once the treatment stage has come back empty too often.+ *+ * The scene-loop behaviour of `advanceAfterSceneSettled` is covered in+ * orchestrator.test.js; this file only exercises the completion/gate paths.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { MAX_CONSECUTIVE_MISSED_DELIVERABLES } from '../../lib/creativeDirectorPresets.js';++const mockGetProject = vi.fn();+const mockUpdateProject = vi.fn(async () => undefined);+const mockUpdateScene = vi.fn(async () => undefined);+const mockUpdateRun = vi.fn(async () => ({}));+const mockRecordRun = vi.fn(async () => ({}));+const mockEnqueueTreatmentTask = vi.fn(async () => undefined);+const mockAdvancePlan = vi.fn(async () => undefined);+const mockRunSceneRender = vi.fn(async () => undefined);++vi.mock('./local.js', () => ({+ getProject: (...a) => mockGetProject(...a),+ updateProject: (...a) => mockUpdateProject(...a),+ updateScene: (...a) => mockUpdateScene(...a),+ updateRun: (...a) => mockUpdateRun(...a),+ recordRun: (...a) => mockRecordRun(...a),+}));+vi.mock('./agentBridge.js', () => ({ enqueueTreatmentTask: (...a) => mockEnqueueTreatmentTask(...a) }));+vi.mock('./planAdvance.js', () => ({ advanceAfterPlanStepSettled: (...a) => mockAdvancePlan(...a) }));+vi.mock('./sceneEvaluator.js', () => ({ dispatchSceneEvaluation: vi.fn(async () => undefined) }));+vi.mock('./sceneRunner.js', () => ({ runSceneRender: (...a) => mockRunSceneRender(...a) }));+vi.mock('./stitchRunner.js', () => ({ runStitch: vi.fn(async () => undefined) }));+vi.mock('../videoGen/local.js', () => ({ sampleEvaluationFrames: vi.fn(async () => []) }));+vi.mock('../mediaJobQueue/index.js', () => ({+ listJobs: vi.fn(() => []),+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },+}));++const { handleCreativeDirectorCompletion, advanceAfterSceneSettled, __resetInflightState } = await import('./completionHook.js');++const planTask = (runId = 'run-1') => ({+ id: 'task-1',+ metadata: { creativeDirector: { projectId: 'cd-1', kind: 'plan', runId } },+});++const planProject = (over = {}) => ({+ id: 'cd-1',+ status: 'planning',+ directive: { goal: 'g', deliverables: [], constraints: {} },+ plan: null,+ runs: [{ runId: 'run-1', kind: 'plan', status: 'running', deliverableMark: null }],+ ...over,+});++const missedTreatmentRun = (runId) => ({ runId, kind: 'treatment', status: 'failed', deliverableMissing: true });++beforeEach(() => {+ vi.clearAllMocks();+ __resetInflightState();+});++describe('handleCreativeDirectorCompletion — plan deliverable', () => {+ it('marks an exit-0 plan run FAILED when no plan was PATCHed', async () => {+ mockGetProject.mockResolvedValue(planProject());+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({+ status: 'failed',+ deliverableMissing: true,+ failureReason: expect.stringMatching(/never wrote the plan/),+ }));+ // The PROJECT is not failed — the advance loop still gets to re-dispatch once.+ expect(mockUpdateProject).not.toHaveBeenCalled();+ expect(mockAdvancePlan).toHaveBeenCalledWith('cd-1');+ });++ it('marks a plan run COMPLETED when the plan did land', async () => {+ mockGetProject.mockResolvedValue(planProject({ plan: { steps: [{ stepId: 'a' }], replanRounds: 0 } }));+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'completed' }));+ expect(mockUpdateRun.mock.calls[0][2]).not.toHaveProperty('deliverableMissing');+ expect(mockAdvancePlan).toHaveBeenCalledWith('cd-1');+ });++ it('marks a RE-plan run failed when it left the existing plan untouched', async () => {+ mockGetProject.mockResolvedValue(planProject({+ plan: { steps: [{ stepId: 'a' }], replanRounds: 1 },+ runs: [{ runId: 'run-1', kind: 'plan', status: 'running', deliverableMark: 'plan:1' }],+ }));+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'failed', deliverableMissing: true }));+ });++ it('marks a RE-plan run completed when replanRounds advanced (a new plan landed)', async () => {+ mockGetProject.mockResolvedValue(planProject({+ plan: { steps: [{ stepId: 'a' }], replanRounds: 2 },+ runs: [{ runId: 'run-1', kind: 'plan', status: 'running', deliverableMark: 'plan:1' }],+ }));+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'completed' }));+ });++ it('does not manufacture a failure for a legacy run that recorded no baseline', async () => {+ // Run row predates the mark (no `deliverableMark` key at all) — presence of a+ // plan is all we can honestly check.+ mockGetProject.mockResolvedValue(planProject({+ plan: { steps: [{ stepId: 'a' }], replanRounds: 1 },+ runs: [{ runId: 'run-1', kind: 'plan', status: 'running' }],+ }));+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'completed' }));+ });++ it('leaves a genuinely failed run on the project-failed path (unchanged)', async () => {+ mockGetProject.mockResolvedValue(planProject());+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', false);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'failed' }));+ expect(mockUpdateRun.mock.calls[0][2]).not.toHaveProperty('deliverableMissing');+ expect(mockUpdateProject).toHaveBeenCalledWith('cd-1', expect.objectContaining({ status: 'failed' }));+ expect(mockAdvancePlan).not.toHaveBeenCalled();+ });++ it('does not deliverable-check an evaluate run (no verifiable PATCH deliverable)', async () => {+ mockGetProject.mockResolvedValue({+ id: 'cd-1', status: 'rendering', directive: null, treatment: { scenes: [] },+ runs: [{ runId: 'run-1', kind: 'evaluate', status: 'running' }],+ });+ await handleCreativeDirectorCompletion({+ id: 'task-1', metadata: { creativeDirector: { projectId: 'cd-1', kind: 'evaluate', runId: 'run-1', sceneId: 's1' } },+ }, 'agent-1', true);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'completed' }));+ });++ it('falls back to recordRun (carrying the miss) when the run row is gone', async () => {+ mockUpdateRun.mockResolvedValueOnce(null);+ mockGetProject.mockResolvedValue(planProject());+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);+ expect(mockRecordRun).toHaveBeenCalledWith('cd-1', expect.objectContaining({ status: 'failed', deliverableMissing: true }));+ });+});++describe('advanceAfterSceneSettled — bounded treatment gate', () => {+ const noTreatment = (runs) => ({ id: 'cd-1', name: 'p', status: 'planning', directive: null, treatment: null, runs });++ it('re-enqueues the treatment task while the empty streak is under the bound', async () => {+ mockGetProject.mockResolvedValue(noTreatment([missedTreatmentRun('t1')]));+ await advanceAfterSceneSettled('cd-1');+ expect(mockEnqueueTreatmentTask).toHaveBeenCalledTimes(1);+ expect(mockUpdateProject).toHaveBeenCalledWith('cd-1', { status: 'planning' });+ });++ it('pauses the project instead of re-dispatching once the bound is reached', async () => {+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES }, (_, i) => missedTreatmentRun(`t${i}`));+ mockGetProject.mockResolvedValue(noTreatment(runs));+ await advanceAfterSceneSettled('cd-1');+ expect(mockEnqueueTreatmentTask).not.toHaveBeenCalled();+ expect(mockUpdateProject).toHaveBeenCalledWith('cd-1', {+ status: 'paused',+ failureReason: expect.stringMatching(/tool-capable model/),+ });+ // Streak closed so a Resume after switching models gets a fresh budget.+ for (const run of runs) {+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', run.runId, { deliverableStreakClosed: true });+ }+ });++ it('re-dispatches again after the streak was closed (Resume gets a fresh budget)', async () => {+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES }, (_, i) => ({+ ...missedTreatmentRun(`t${i}`), deliverableStreakClosed: true,+ }));+ mockGetProject.mockResolvedValue(noTreatment(runs));+ await advanceAfterSceneSettled('cd-1');+ expect(mockEnqueueTreatmentTask).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/creativeDirector/deliverableGate.js b/server/services/creativeDirector/deliverableGate.jsnew file mode 100644index 0000000000..b83a0860d5--- /dev/null+++ b/server/services/creativeDirector/deliverableGate.js@@ -0,0 +1,157 @@+/**+ * Creative Director — agent-deliverable gate (#4146).+ *+ * A CD `plan` / `treatment` agent's real deliverable is the HTTP PATCH its+ * prompt describes (`PATCH /api/creative-director/:id/plan` or `/treatment`),+ * NOT a commit and NOT its exit code. A non-tool-calling local model can narrate+ * a done-message, signal completion, and exit 0 having PATCHed nothing — the+ * completion hook then marked the run `completed`, the re-dispatch guard in+ * `enqueuePlannerOnce` / `advanceAfterSceneSettled` saw no in-flight run, and the+ * SAME incapable model was handed the SAME task forever. Only boot recovery ever+ * reaped it.+ *+ * This module supplies the two pure decisions that close that loop:+ *+ * 1. `deliverableMark` + `deliverableLanded` — did the PATCH actually land+ * during this run? A mark is stamped onto the run row at DISPATCH time+ * (agentBridge) and compared against the project's mark once the run+ * settles. Presence alone is not enough for `plan`: a bounded RE-plan runs+ * against a project that already has one, so the mark carries+ * `replanRounds` (bumped by every accepted PATCH) to tell "the planner+ * rewrote it" from "the planner did nothing".+ *+ * 2. `countConsecutiveMissedDeliverables` — how many times in a row the stage+ * has come back empty, so the caller can stop re-dispatching and surface a+ * blocked stage instead of burning the provider indefinitely.+ *+ * Sentinel discipline (root CLAUDE.md): `undefined` = no baseline recorded (a run+ * enqueued before this change) and `null` = recorded-and-absent are DISTINCT.+ * Collapsing them would either mis-fail every legacy run or mis-pass every empty+ * one.+ */++import { updateRun } from './local.js';+import { MAX_CONSECUTIVE_MISSED_DELIVERABLES } from '../../lib/creativeDirectorPresets.js';++// The CD agent kinds whose deliverable is a project-record PATCH we can verify.+// `evaluate` is deliberately absent: its deliverable is a per-scene verdict, and+// an evaluate run that writes nothing is already reaped by the orphaned-+// `evaluating` scene path in completionHook.+export const DELIVERABLE_KINDS = new Set(['plan', 'treatment']);++/**+ * A comparable fingerprint of the deliverable `kind` on `project`, or `null` when+ * the deliverable is absent. Pure.+ *+ * @param {object|null} project+ * @param {string} kind — 'plan' | 'treatment'+ * @returns {string|null}+ */+export function deliverableMark(project, kind) {+ if (kind === 'plan') {+ const plan = project?.plan;+ if (!Array.isArray(plan?.steps)) return null;+ // `replanRounds` is bumped by applyPlan on EVERY accepted PATCH, so it+ // separates a rewrite from a no-op even when two plans have the same shape+ // (and, unlike a timestamp, can't collide inside one millisecond).+ return `plan:${plan.replanRounds ?? 0}`;+ }+ if (kind === 'treatment') {+ const scenes = project?.treatment?.scenes;+ if (!Array.isArray(scenes)) return null;+ return `treatment:${scenes.length}:${project.treatment.logline || ''}`;+ }+ return null;+}++/**+ * Did the `kind` deliverable land while this run was in flight? Pure.+ *+ * @param {object|null} project — the project AFTER the run settled.+ * @param {string} kind+ * @param {string|null|undefined} markBefore — the mark stamped on the run row at+ * dispatch. `undefined` means no baseline was recorded (a run enqueued by an+ * older build); we cannot prove a miss, so presence alone counts as landed+ * rather than manufacturing a false failure.+ */+export function deliverableLanded(project, kind, markBefore) {+ const after = deliverableMark(project, kind);+ if (after === null) return false;+ if (markBefore === undefined) return true;+ return after !== markBefore;+}++/**+ * How many of the MOST RECENT runs of `kind` settled without their deliverable —+ * the consecutive-empty streak. Walks backwards over runs of that kind and stops+ * at the first one that either delivered or belongs to an already-closed streak.+ * Pure.+ *+ * @param {Array<object>|undefined} runs+ * @param {string} kind+ * @returns {number}+ */+export function countConsecutiveMissedDeliverables(runs, kind) {+ if (!Array.isArray(runs)) return 0;+ let streak = 0;+ for (let i = runs.length - 1; i >= 0; i -= 1) {+ const run = runs[i];+ if (run?.kind !== kind) continue;+ if (run.deliverableMissing !== true || run.deliverableStreakClosed === true) break;+ streak += 1;+ }+ return streak;+}++/**+ * The streak length when the stage has exhausted its budget of consecutive empty+ * completions and must be surfaced to the user instead of re-dispatched, else 0.+ * Pure. Returns the count (not a boolean) so a caller can name the number in the+ * reason it shows the user without walking `runs` a second time.+ */+export function exhaustedDeliverableStreak(runs, kind) {+ const streak = countConsecutiveMissedDeliverables(runs, kind);+ return streak >= MAX_CONSECUTIVE_MISSED_DELIVERABLES ? streak : 0;+}++/**+ * Stamp the current empty streak as CLOSED once the stage has been surfaced as+ * blocked. Without this the streak would still be at the bound the moment the+ * user hits Resume, so the project would re-pause immediately and stay dead even+ * after they switched to a tool-capable model. Closing it hands the next attempt+ * a fresh budget while the run ledger keeps the honest `deliverableMissing`+ * record of what happened.+ *+ * Runs outside the request lifecycle (completion hooks / event bus) — never+ * throws out.+ *+ * @param {string} projectId+ * @param {Array<object>|undefined} runs+ * @param {string} kind+ */+export async function closeDeliverableStreak(projectId, runs, kind) {+ if (!Array.isArray(runs)) return;+ for (let i = runs.length - 1; i >= 0; i -= 1) {+ const run = runs[i];+ if (run?.kind !== kind) continue;+ if (run.deliverableMissing !== true || run.deliverableStreakClosed === true) break;+ await updateRun(projectId, run.runId, { deliverableStreakClosed: true })+ .catch((e) => console.log(`⚠️ CD close streak on run ${run.runId} of ${projectId} failed: ${e.message}`));+ }+}++/**+ * The user-facing reason shown on a project parked by the gate. Names the stage+ * and the concrete remedy (pick a tool-capable model) rather than a bare+ * "failed", so the CD failure banner is actionable.+ */+export function blockedStageReason(kind, streak) {+ return `The ${kind} agent finished ${streak} time(s) in a row without writing a ${kind}. `+ + `The model assigned to the Creative Director "${kind}" stage is not performing the required PATCH — `+ + 'pick a tool-capable model for that stage, then Resume.';+}++/** The reason stamped on an individual run that exited clean but delivered nothing. */+export function missedDeliverableReason(kind) {+ return `Agent exited cleanly but never wrote the ${kind} (no PATCH landed)`;+}diff --git a/server/services/creativeDirector/deliverableGate.test.js b/server/services/creativeDirector/deliverableGate.test.jsnew file mode 100644index 0000000000..f91830d7fe--- /dev/null+++ b/server/services/creativeDirector/deliverableGate.test.js@@ -0,0 +1,138 @@+/**+ * CD agent-deliverable gate (#4146) — the pure decisions behind "did the PATCH+ * actually land?" and "has this stage come back empty too many times to keep+ * re-dispatching?".+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { MAX_CONSECUTIVE_MISSED_DELIVERABLES } from '../../lib/creativeDirectorPresets.js';++const mockUpdateRun = vi.fn(async () => ({}));+vi.mock('./local.js', () => ({ updateRun: (...a) => mockUpdateRun(...a) }));++const {+ DELIVERABLE_KINDS,+ blockedStageReason,+ closeDeliverableStreak,+ countConsecutiveMissedDeliverables,+ deliverableLanded,+ deliverableMark,+ exhaustedDeliverableStreak,+ missedDeliverableReason,+} = await import('./deliverableGate.js');++const missed = (over = {}) => ({ runId: `r-${Math.random()}`, kind: 'plan', status: 'failed', deliverableMissing: true, ...over });++beforeEach(() => vi.clearAllMocks());++describe('deliverableMark (pure)', () => {+ it('is null when the plan is absent or has no steps array', () => {+ expect(deliverableMark({}, 'plan')).toBeNull();+ expect(deliverableMark({ plan: {} }, 'plan')).toBeNull();+ expect(deliverableMark(null, 'plan')).toBeNull();+ });+ it('keys a plan on replanRounds so a re-plan is distinguishable from a no-op', () => {+ expect(deliverableMark({ plan: { steps: [], replanRounds: 0 } }, 'plan')).toBe('plan:0');+ expect(deliverableMark({ plan: { steps: [], replanRounds: 3 } }, 'plan')).toBe('plan:3');+ });+ it('is null when the treatment is absent, and shape-keyed when present', () => {+ expect(deliverableMark({}, 'treatment')).toBeNull();+ expect(deliverableMark({ treatment: {} }, 'treatment')).toBeNull();+ expect(deliverableMark({ treatment: { scenes: [{}, {}], logline: 'L' } }, 'treatment')).toBe('treatment:2:L');+ });+ it('is null for a kind with no verifiable PATCH deliverable', () => {+ expect(deliverableMark({ treatment: { scenes: [] } }, 'evaluate')).toBeNull();+ expect(DELIVERABLE_KINDS.has('evaluate')).toBe(false);+ });+});++describe('deliverableLanded (pure)', () => {+ it('is false when the deliverable is still absent', () => {+ expect(deliverableLanded({ plan: null }, 'plan', null)).toBe(false);+ });+ it('is true when it went from absent to present', () => {+ expect(deliverableLanded({ plan: { steps: [{}], replanRounds: 0 } }, 'plan', null)).toBe(true);+ });+ it('is FALSE for a re-plan that left the existing plan untouched', () => {+ const project = { plan: { steps: [{}], replanRounds: 1 } };+ expect(deliverableLanded(project, 'plan', 'plan:1')).toBe(false);+ });+ it('is true for a re-plan that rewrote the plan (replanRounds advanced)', () => {+ const project = { plan: { steps: [{}], replanRounds: 2 } };+ expect(deliverableLanded(project, 'plan', 'plan:1')).toBe(true);+ });+ it('distinguishes an ABSENT baseline (undefined) from a recorded-absent one (null)', () => {+ const project = { plan: { steps: [{}], replanRounds: 1 } };+ // undefined = a run enqueued before the mark existed — never manufacture a+ // failure from a baseline we never took.+ expect(deliverableLanded(project, 'plan', undefined)).toBe(true);+ // null = we DID record "there was no plan", and there still is one now.+ expect(deliverableLanded(project, 'plan', null)).toBe(true);+ // …but an unchanged plan with a recorded baseline is a miss.+ expect(deliverableLanded(project, 'plan', 'plan:1')).toBe(false);+ });+});++describe('countConsecutiveMissedDeliverables (pure)', () => {+ it('is 0 for no runs, a non-array, or runs of another kind', () => {+ expect(countConsecutiveMissedDeliverables(undefined, 'plan')).toBe(0);+ expect(countConsecutiveMissedDeliverables([], 'plan')).toBe(0);+ expect(countConsecutiveMissedDeliverables([missed({ kind: 'treatment' })], 'plan')).toBe(0);+ });+ it('counts the trailing streak of empty runs of that kind', () => {+ expect(countConsecutiveMissedDeliverables([missed(), missed()], 'plan')).toBe(2);+ });+ it('ignores interleaved runs of OTHER kinds without breaking the streak', () => {+ const runs = [missed(), { runId: 'e1', kind: 'evaluate', status: 'completed' }, missed()];+ expect(countConsecutiveMissedDeliverables(runs, 'plan')).toBe(2);+ });+ it('stops at the most recent run of that kind that DID deliver', () => {+ const runs = [missed(), { runId: 'ok', kind: 'plan', status: 'completed' }, missed()];+ expect(countConsecutiveMissedDeliverables(runs, 'plan')).toBe(1);+ });+ it('stops at an already-closed streak so a Resume gets a fresh budget', () => {+ const runs = [missed({ deliverableStreakClosed: true }), missed({ deliverableStreakClosed: true })];+ expect(countConsecutiveMissedDeliverables(runs, 'plan')).toBe(0);+ expect(countConsecutiveMissedDeliverables([...runs, missed()], 'plan')).toBe(1);+ });+ it('does not count an ordinary failed run (one that never reached the deliverable check)', () => {+ expect(countConsecutiveMissedDeliverables([{ runId: 'x', kind: 'plan', status: 'failed' }], 'plan')).toBe(0);+ });+});++describe('exhaustedDeliverableStreak', () => {+ it('trips exactly at the named bound, reporting the streak length', () => {+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES - 1 }, () => missed());+ expect(exhaustedDeliverableStreak(runs, 'plan')).toBe(0);+ expect(exhaustedDeliverableStreak([...runs, missed()], 'plan')).toBe(MAX_CONSECUTIVE_MISSED_DELIVERABLES);+ });+});++describe('closeDeliverableStreak', () => {+ it('stamps every run in the trailing streak and nothing older', async () => {+ const runs = [+ missed({ runId: 'old', deliverableStreakClosed: true }),+ { runId: 'ok', kind: 'plan', status: 'completed' },+ missed({ runId: 'a' }),+ missed({ runId: 'b' }),+ ];+ await closeDeliverableStreak('cd-1', runs, 'plan');+ expect(mockUpdateRun).toHaveBeenCalledTimes(2);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'b', { deliverableStreakClosed: true });+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'a', { deliverableStreakClosed: true });+ });+ it('is a no-op with no runs, and swallows a store error (runs outside the request lifecycle)', async () => {+ await closeDeliverableStreak('cd-1', undefined, 'plan');+ expect(mockUpdateRun).not.toHaveBeenCalled();+ mockUpdateRun.mockRejectedValueOnce(new Error('boom'));+ await expect(closeDeliverableStreak('cd-1', [missed({ runId: 'a' })], 'plan')).resolves.toBeUndefined();+ });+});++describe('reason strings', () => {+ it('name the stage and the concrete remedy', () => {+ expect(blockedStageReason('plan', 2)).toMatch(/plan agent finished 2 time\(s\)/);+ expect(blockedStageReason('plan', 2)).toMatch(/tool-capable model/);+ expect(missedDeliverableReason('treatment')).toMatch(/never wrote the treatment/);+ });+});diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsindex ff0c9d1ceb..bb3760d62d 100644--- a/server/services/creativeDirector/planAdvance.js+++ b/server/services/creativeDirector/planAdvance.js@@ -30,6 +30,7 @@ import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';import { autopilotEvents, isAutopilotActive, AUTOPILOT_TERMINAL_TYPES } from '../pipeline/seriesAutopilot.js';import { getSeries } from '../pipeline/series.js';import { MAX_REPLAN_ROUNDS, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';+import { blockedStageReason, closeDeliverableStreak, exhaustedDeliverableStreak } from './deliverableGate.js';// The registry tool that runs Series Autopilot as a plan step. A long-running// step whose dispatch returns a run handle (a `runId`, not a media `jobId`)@@ -253,17 +254,49 @@ function summarizeResult(result) {return out;}+// Flip the project to `planning` and hand the planner agent a fresh task. Shared+// by the no-plan-yet branch and the bounded re-planner so they can never drift on+// the in-flight bookkeeping. Callers own their own pre-guards AND must have taken+// `inflightPlanner` already (this releases it).+async function dispatchPlanner(projectId) {+ await updateProject(projectId, { status: 'planning' })+ .catch((e) => { inflightPlanner.delete(projectId); throw e; });+ const fresh = await getProject(projectId);+ await enqueuePlanTask(fresh).finally(() => inflightPlanner.delete(projectId));+}++/**+ * #4146 — bounded blocked-stage gate in front of every planner dispatch.+ *+ * The planner agent's deliverable is `PATCH /:id/plan`. When it exits cleanly+ * without PATCHing, completionHook now records the run `failed` — which is what+ * lets the guard above re-dispatch LIVE rather than at boot. But re-handing the+ * SAME task to a model that has already demonstrated it cannot perform the PATCH+ * just burns the provider in a tight loop (and the re-plan route can't even be+ * bounded by MAX_REPLAN_ROUNDS: `replanRounds` only advances when a plan actually+ * lands). After MAX_CONSECUTIVE_MISSED_DELIVERABLES empty completions, surface+ * the stage to the user instead — and close the streak so a Resume after+ * switching models starts from a clean budget.+ *+ * Returns true when the caller must NOT dispatch.+ */+async function plannerBlockedOnEmptyRuns(project) {+ const streak = exhaustedDeliverableStreak(project.runs, 'plan');+ if (!streak) return false;+ await closeDeliverableStreak(project.id, project.runs, 'plan');+ await pausePlanWithResidual(project.id, blockedStageReason('plan', streak));+ return true;+}+async function enqueuePlannerOnce(project) {const projectId = project.id;const hasInflightPlanRun = (project.runs || []).some((r) => r.kind === 'plan' && r.status !== 'completed' && r.status !== 'failed',);if (hasInflightPlanRun || inflightPlanner.has(projectId)) return;+ if (await plannerBlockedOnEmptyRuns(project)) return;inflightPlanner.add(projectId);- await updateProject(projectId, { status: 'planning' })- .catch((e) => { inflightPlanner.delete(projectId); throw e; });- const fresh = await getProject(projectId);- await enqueuePlanTask(fresh).finally(() => inflightPlanner.delete(projectId));+ return dispatchPlanner(projectId);}/**@@ -440,12 +473,14 @@ async function handlePlanStepFailure(projectId, step) {if (!project || project.status === 'paused' || project.status === 'failed') return;const rounds = project.plan?.replanRounds || 0;if (rounds < MAX_REPLAN_ROUNDS && !inflightPlanner.has(projectId)) {+ // MAX_REPLAN_ROUNDS alone cannot bound this path: `replanRounds` is bumped by+ // applyPlan, so a planner that never PATCHes leaves it at the same value and+ // this branch would re-fire forever (#4146). The empty-run gate is what+ // terminates that loop.+ if (await plannerBlockedOnEmptyRuns(project)) return;console.log(`🔁 CD plan ${projectId}: step "${step.stepId}" failed — re-planning (round ${rounds + 1}/${MAX_REPLAN_ROUNDS})`);inflightPlanner.add(projectId);- await updateProject(projectId, { status: 'planning' })- .catch((e) => { inflightPlanner.delete(projectId); throw e; });- const fresh = await getProject(projectId);- await enqueuePlanTask(fresh).finally(() => inflightPlanner.delete(projectId));+ await dispatchPlanner(projectId);return;}return pausePlanWithResidual(diff --git a/server/services/creativeDirector/planAdvance.test.js b/server/services/creativeDirector/planAdvance.test.jsindex 19bdf8bed8..b7db4fa96e 100644--- a/server/services/creativeDirector/planAdvance.test.js+++ b/server/services/creativeDirector/planAdvance.test.js@@ -10,6 +10,7 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';+import { MAX_CONSECUTIVE_MISSED_DELIVERABLES } from '../../lib/creativeDirectorPresets.js';// ---- pure derivation (no mocks needed) -------------------------------------import { deriveNextPlanAction, lastRenderedVideoJobId, resolvePlanStepArgs } from './planAdvance.js';@@ -518,3 +519,74 @@ describe('advanceAfterPlanStepSettled — runAutopilot plan step', () => {expect(p.status).toBe('paused');});});++// ---- #4146 bounded planner gate --------------------------------------------++describe('advanceAfterPlanStepSettled — empty-planner gate (#4146)', () => {+ const missedPlanRun = (runId, over = {}) => ({+ runId, kind: 'plan', status: 'failed', deliverableMissing: true, ...over,+ });+ const noPlan = (runs) => ({+ id: 'cd-1', status: 'planning', directive: { goal: 'g', deliverables: [], constraints: {} },+ plan: null, runs,+ });++ it('re-dispatches the planner once a run that never PATCHed is marked failed', async () => {+ // The whole point of failing the empty run: the `hasInflightPlanRun` guard+ // treats it as terminal, so the loop re-enqueues LIVE instead of waiting for+ // boot recovery to reap a run stuck at `completed`.+ makeStore(noPlan([missedPlanRun('r1')]));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);+ });++ it('still refuses to re-dispatch while a plan run is genuinely in flight', async () => {+ makeStore(noPlan([{ runId: 'r1', kind: 'plan', status: 'running' }]));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();+ });++ it('pauses the project instead of re-dispatching once the empty streak hits the bound', async () => {+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES }, (_, i) => missedPlanRun(`r${i}`));+ const read = makeStore(noPlan(runs));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();+ const p = read();+ expect(p.status).toBe('paused');+ expect(p.failureReason).toMatch(/tool-capable model/);+ // Streak closed so a Resume after switching models starts from a fresh budget.+ expect(p.runs.every((r) => r.deliverableStreakClosed === true)).toBe(true);+ });++ it('re-dispatches again after the streak was closed (Resume gets a fresh budget)', async () => {+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES }, (_, i) => (+ missedPlanRun(`r${i}`, { deliverableStreakClosed: true })+ ));+ makeStore(noPlan(runs));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);+ });++ it('bounds the RE-PLAN route too — replanRounds never advances on an empty planner', async () => {+ // A failed step routes through handlePlanStepFailure, which is budgeted by+ // MAX_REPLAN_ROUNDS. But `replanRounds` is only bumped when a plan actually+ // lands, so an empty planner would loop there forever without this gate.+ const steps = [step('a', { toolName: 'pipeline_generateStage', status: 'failed' })];+ const runs = Array.from({ length: MAX_CONSECUTIVE_MISSED_DELIVERABLES }, (_, i) => missedPlanRun(`r${i}`));+ const read = makeStore(planProject(steps, { plan: { steps, replanRounds: 0 }, runs }));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();+ expect(read().status).toBe('paused');+ });++ it('still re-plans on a failed step when the planner has been delivering', async () => {+ const steps = [step('a', { toolName: 'pipeline_generateStage', status: 'failed' })];+ const read = makeStore(planProject(steps, {+ plan: { steps, replanRounds: 0 },+ runs: [{ runId: 'r1', kind: 'plan', status: 'completed' }],+ }));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);+ expect(read().status).toBe('planning');+ });+});diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 8b6e432e11..92f1594799 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -167,7 +167,9 @@ export function isNonCommittingCoordinatorTask(task) {/*** Whether a task declares NO commit criterion: the static- * coordinator set above, OR a TRACKER-FILING task whose dispatch derived+ * coordinator set above, a NO-CODE-OUTPUT task (its deliverable is an action —+ * an HTTP PATCH, a filed issue — and its prompt never asks for a commit), OR a+ * TRACKER-FILING task whose dispatch derived* `worktreeChangesExpected: false` (cosTaskGenerator.js#resolveTrackerFilingBlock,* referenceRepos.js#triggerReferenceAnalysis).*@@ -202,6 +204,19 @@ export function declaresNoCommitCriterion(task) {// SUCCESSFUL run a validation miss and drags that provider/model's learning// bucket toward 0% — the #2696/#3273 artifact, arriving by a third route.if (isTruthyMeta(task?.metadata?.discardWorktree)) return true;+ // `noCodeOutput` tasks deliver something the agent DOES — an HTTP PATCH, a filed+ // issue, an API call — and their prompt routes through+ // agentPromptBuilder#buildActionOutputCompletionSection, which explicitly does+ // NOT tell them to commit or open a PR. Creative Director tasks are the shipped+ // instance of that shape (their deliverable is `PATCH /api/creative-director/…`),+ // and they run with `useWorktree: false` against the live checkout — so+ // workspacePath IS set and the commit criterion scored every SUCCESSFUL run as a+ // miss, the #2696/#3273 artifact reaching CD by a fourth route (#4146). Resolved+ // exactly as agentPromptBuilder resolves it (flag OR the creativeDirector+ // metadata block) so the criterion and the prompt can't disagree about whether a+ // commit was ever asked for. Their REAL deliverable is verified in the CD+ // completion hook, which is the only place the project record is visible.+ if (isTruthyMeta(task?.metadata?.noCodeOutput) || task?.metadata?.creativeDirector) return true;if (!isTrackerFilingDispatch(task)) return false;return isFalsyMeta(task?.metadata?.worktreeChangesExpected);}diff --git a/server/services/taskTypeHooks.noCommit.test.js b/server/services/taskTypeHooks.noCommit.test.jsindex 6975f043c3..460d854ebe 100644--- a/server/services/taskTypeHooks.noCommit.test.js+++ b/server/services/taskTypeHooks.noCommit.test.js@@ -24,6 +24,19 @@ describe('declaresNoCommitCriterion', () => {expect(declaresNoCommitCriterion(task({ discardWorktree: 'true' }))).toBe(true);});+ it('exempts a no-code-output task, whose deliverable is an action not a commit (#4146)', () => {+ expect(declaresNoCommitCriterion(task({ noCodeOutput: true }))).toBe(true);+ expect(declaresNoCommitCriterion(task({ noCodeOutput: 'true' }))).toBe(true);+ // Creative Director tasks are the shipped instance: they run against the live+ // checkout (useWorktree:false) so workspacePath IS set, and their deliverable+ // is `PATCH /api/creative-director/:id/plan|treatment`. Commit-checking them+ // scored every successful run as a miss. Resolved the same way+ // agentPromptBuilder resolves noCodeOutput, so prompt and criterion agree.+ expect(declaresNoCommitCriterion(task({+ creativeDirector: { projectId: 'cd-1', kind: 'plan', runId: 'r1' },+ }))).toBe(true);+ });+describe('tracker-filing runs', () => {it('exempts a SCHEDULED type whose dispatch derived a clean tree', () => {expect(declaresNoCommitCriterion(task({