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
feat([issue-2184]): production plans — directive, cd-plan planner, generalized advance loop (CDO Phase 2)
Adam Eivy207e987ae57e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0c94d49a6d..97508dbf31 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -145,6 +145,10 @@- **[issue-2235] Expired-token detection is now Cloud-aware, so a Jira Cloud token expiry gives the same friendly "regenerate your token" message as Server.** The JIRA client's expiry detector only recognized the Server/DC signal — a 200 response whose body is the HTML login page (`<!DOCTYPE`) — so a Cloud instance, which instead returns a JSON **401** on an invalid/expired token, never hit the friendly branch and surfaced the raw HTTP 401 instead. Detection is now instance-type-aware alongside the auth header: the `<!DOCTYPE` heuristic is gated to Server (so a Cloud JSON payload can't accidentally trip on the marker string), and a 401 from either instance type maps to one shared "token expired or invalid — regenerate your token" error. Both instance types now report expiry from one place. (`server/services/jira.js`)- **Configuring an app's JIRA integration now auto-detects the workspace instead of hand-typing ids.** When you pick a JIRA instance + project in an app's JIRA settings, PortOS now detects that project's **boards** and offers them as a dropdown (`id — name (type)`) rather than a free-text "Board ID" field — the field where a board id silently went stale. If the app's saved board id isn't among the project's live boards (e.g. carried over from a Server instance after a Cloud migration, where ids are reassigned), it's flagged with an amber "pick a current one" warning; the selected board also shows its current **active sprint** as confirmation. The **Epic Key** field gained live search-by-name (type a name → pick from matching epics) and validates a typed/pasted key against the instance — confirming it resolves as an Epic, or warning when it's the wrong type or no longer resolves. New read-only endpoints back this: `GET /jira/instances/:id/projects/:key/boards` and `GET /jira/instances/:id/issues/:key`. (`server/services/jira.js`, `server/routes/jira.js`, `client/src/components/apps/EditAppDrawer.jsx`)+## Creative Director++- **[issue-2184] Production plans: a directive, a planner agent (`cd-plan`), and a generalized advance loop (CDO Phase 2).** Builds on the Phase 1 tool registry (#2183) to promote the Creative Director from a hardcoded treatment→scene→stitch video producer into a general orchestrator you can hand a *directive* ("produce a 6-issue noir comic in universe X, with covers and a teaser") and let it plan + execute using any tool in the creative suite. The CD project record grows two additive fields (`directive` + `plan.steps[]`) alongside the existing treatment/scenes — a legacy video project leaves both null and behaves exactly as before (the back-compat discriminator the advance loop keys on). A directive-driven project runs a new machinery that mirrors the scene loop's shape: the **planner** is a cognitive CoS-agent task (`enqueuePlanTask` beside `enqueueTreatmentTask`) whose `cd-plan` prompt receives the directive + the resolved tool-registry specs (`getToolSpecs()`) + the current plan and PATCHes a Zod-validated step list to `/:id/plan`; the **generalized advance loop** (`advanceAfterPlanStepSettled`, `server/services/creativeDirector/planAdvance.js`) is a pure next-step function over the plan DAG — sequential, `dependsOn`-respecting, in-memory-deduped, idempotent — that dispatches each step through the Phase 1 gated `dispatchCreativeTool` chokepoint (so the whole plan runs under the `creative` autonomy domain + daily budget; an off/over-budget gate blocks the step and pauses the project). Long-running steps (media renders) stay `running` until their media job settles via a completion listener; a step failure triggers **bounded re-planning** (`MAX_REPLAN_ROUNDS`, default 2) — the planner revises the remaining steps, preserving already-completed steps by `stepId` — then the project pauses with residuals for human review (autopilot's convergence-pause contract, never a silent retry). Boot recovery resets stuck `running` plan steps and re-fires the loop; each step records a `plan-step` run row for the Phase 4 plan board. Federation-safe: `creativeDirectorProjects` schema version bumped 1→2 (per-category gate) and a stage-seed migration (175) ships the `cd-plan` prompt to existing installs. No user-facing surface yet — the directive composer + plan board arrive in Phase 4. (`server/services/creativeDirector/{planAdvance,projectsLogic,agentBridge,completionHook,recovery}.js`, `server/lib/{creativeDirectorValidation,creativeDirectorPrompts,schemaVersions}.js`, `data.reference/prompts/stages/cd-plan.md`, `scripts/migrations/175-cd-plan-stage.js`)+## Internal- **[issue-2256] Removed the dead cos-runner `/run` devtools endpoint (latent Windows ENOENT bug).** The CoS runner's `POST /run` devtools path spawned a bare command under `shell:false` with the prompt passed as an argv — the same Windows `spawn ENOENT` bug the CoS agent path had (#2243), but no code called it: the live "Run Prompt" flow goes through `server/services/runner.js` (already fixed), and `executeCliRunViaRunner` + the `/runs`, `/runs/:id/output`, `/runs/:id/active`, `/runs/:id/stop` sibling endpoints and their client wrappers (`getActiveRunsFromRunner`, `isRunActiveInRunner`, `getRunOutputFromRunner`, `stopRunViaRunner`) were referenced only by their own tests. Rather than refactor dead code to be Windows-safe (a prompt-via-stdin rewrite to dodge the ~8191-char `cmd.exe /c` command-line limit), the whole devtools-run cluster is removed — the endpoint, its in-memory `activeRuns` map + `ensureRunsDir` helper, the `run:data`/`run:complete`/`run:error` socket forwarders, and the now-orphaned client functions and their tests. The main server and cos-runner sidecar ship in one repo and deploy together, so there's no cross-install compatibility concern. (`server/cos-runner/index.js`, `server/services/cosRunnerClient.js`, `server/services/cosRunnerClient.test.js`)diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 975fdf1922..095417d2ea 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -84,6 +84,13 @@"returnsJson": false,"variables": []},+ "cd-plan": {+ "name": "Creative Director — Production Plan",+ "description": "Turn a production directive into a validated plan: an ordered list of creative-tool-registry tool calls (with dependsOn ordering) the generalized advance loop executes step-by-step.",+ "model": "default",+ "returnsJson": false,+ "variables": []+ },"app-detection": {"name": "App Detection","description": "Analyze a project directory and detect its configuration",diff --git a/data.reference/prompts/stages/cd-plan.md b/data.reference/prompts/stages/cd-plan.mdnew file mode 100644index 0000000000..2e2fc629f9--- /dev/null+++ b/data.reference/prompts/stages/cd-plan.md@@ -0,0 +1,74 @@+# Creative Director — Production Plan task++You are the Creative Director acting as a general creative ORCHESTRATOR. Your job in this task is to turn a production DIRECTIVE into a validated PLAN — an ordered list of tool calls the server will then execute step-by-step through a gated tool registry (no further agent task is needed to run the steps — the server orchestrates that, one step at a time, respecting dependencies).++## Project: "{{project.name}}" (id: {{project.id}})++## Directive++**Goal:** {{directive.goal}}++{{#directive.hasDeliverables}}**Requested deliverables:**+{{#directive.deliverables}}+- {{value}}+{{/directive.deliverables}}+{{/directive.hasDeliverables}}++**Constraints (JSON):** {{directive.constraintsJson}}++{{#hasCurrentPlan}}+## Current plan (revise this)++A plan already exists — a prior step failed and you are re-planning. Keep every step that is already `done`/`skipped` VERBATIM (same `stepId`), and revise ONLY the remaining `pending`/`failed`/`blocked` steps. The server preserves the results of already-completed steps by `stepId`.++Current steps (JSON): {{currentPlanJson}}+{{/hasCurrentPlan}}++## Available tools++You may ONLY use these registry tools. Each step's `toolName` MUST be one of these names, and its `args` MUST match the tool's parameter schema. Steps that create records are free; steps that call an LLM or a renderer consume the daily action budget and long-running steps (renders, autopilot) complete asynchronously via events — express ordering between them with `dependsOn`.++{{#tools}}+### `{{name}}`+{{description}}++Parameters (JSON schema): {{parametersJson}}++{{/tools}}++## Task++1. Decompose the directive into the smallest sequence of registry tool calls that delivers the requested deliverables. Prefer existing records over creating new ones where the constraints name a target universe/series id.+2. Give every step a stable, unique `stepId` (e.g. `create-series`, `cover-issue-1`).+3. Use `dependsOn` to encode ordering — a step runs only after every id in its `dependsOn` reaches a terminal-success state. Steps with no dependencies run in listed order (execution is sequential; there are no parallel branches).+4. Do NOT invent tool names or arguments. If a deliverable cannot be produced with the available tools, omit it rather than fabricating a step.++## Output contract++Issue ONE HTTP request to write the plan, then exit:++```+PATCH {{apiUrl}}/api/creative-director/{{project.id}}/plan+Content-Type: application/json++{+ "steps": [+ {+ "stepId": "create-series",+ "toolName": "pipeline_createSeries",+ "args": { "name": "<series name>" },+ "dependsOn": []+ },+ {+ "stepId": "cover-issue-1",+ "toolName": "pipeline_renderComicCover",+ "args": { "issueId": "<issue id>", "coverScript": "<concept>" },+ "dependsOn": ["create-series"]+ }+ ]+}+```++On a 200 response your task is complete. The server will begin executing the plan step-by-step — do not create any additional tasks yourself.++If the PATCH returns 4xx, fix the validation issue (read the error body — a bad `toolName` or malformed `args` is the usual cause) and retry. Do not retry on 5xx more than twice.diff --git a/scripts/migrations/175-cd-plan-stage.js b/scripts/migrations/175-cd-plan-stage.jsnew file mode 100644index 0000000000..d7aaa45fcc--- /dev/null+++ b/scripts/migrations/175-cd-plan-stage.js@@ -0,0 +1,20 @@+/**+ * Seed the `cd-plan` prompt stage into existing installs (#2184, CDO Phase 2 —+ * production plans).+ *+ * Mirrors 174-series-voice-discover-stage.js — copies the `.md` template from+ * `data.reference/prompts/stages/` and merges the stage-config entry into+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) BEFORE+ * the AI toolkit reads stage-config.json, but does NOT run `setup-data.js`.+ * Without this migration, an upgrade that pulls main and `pm2 restart`s (rather+ * than running `update.sh`) leaves the new stage unregistered — the planner agent+ * (`enqueuePlanTask`) would throw "Stage cd-plan not found" the first time a+ * directive-driven project starts.+ *+ * Customization-safe + idempotent: the template is copied only when missing and+ * the config entry merged only when absent.+ */++import { makeSeedMigration } from './_seedStageHelpers.js';++export default makeSeedMigration('cd-plan');diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.jsindex f2a67e0d0e..d1383bc13d 100644--- a/server/lib/creativeDirectorPresets.js+++ b/server/lib/creativeDirectorPresets.js@@ -42,6 +42,27 @@ export const SCENE_STATUSES = Object.freeze(['pending', 'rendering', 'evaluating', 'accepted', 'failed',]);+// Production-plan step lifecycle states (CDO Phase 2, #2184). A plan step is+// `pending` until its `dependsOn[]` are all terminal-success (done/skipped) and+// the advance loop dispatches it; `running` while a synchronous tool executes or+// a long-running job/run is in flight; `blocked` when an underlying run pauses+// for human review (or the orchestrator gate rejects it — off/budget); `done`+// on success; `failed` on an unrecoverable tool error; `skipped` when the plan+// (re-planner) drops it. Mirrors SCENE_STATUSES' role for the legacy video flow.+export const PLAN_STEP_STATUSES = Object.freeze([+ 'pending', 'running', 'blocked', 'done', 'failed', 'skipped',+]);++// Terminal-SUCCESS plan-step states — a step in one of these is finished and its+// dependents are unblocked. `failed` is terminal but NOT success (a dependent+// can never run), so it is deliberately excluded.+export const PLAN_STEP_TERMINAL_SUCCESS = Object.freeze(new Set(['done', 'skipped']));++// Bounded re-planning: after a plan step fails, the planner may revise the+// remaining steps at most this many times before the project pauses with+// residuals for human review (autopilot's convergence-pause contract).+export const MAX_REPLAN_ROUNDS = 2;+/*** Map a project's aspectRatio + quality + scene durationSeconds to the* concrete render-API body.diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.jsindex a62d049b8d..9977f797ed 100644--- a/server/lib/creativeDirectorPrompts.js+++ b/server/lib/creativeDirectorPrompts.js@@ -79,6 +79,43 @@ export async function buildTreatmentPrompt(project) {return buildPrompt('cd-treatment', view);}+// CDO Phase 2 (#2184) — the planner view. `toolSpecs` is the resolved+// getToolSpecs() output from the creative tool registry, passed IN by the+// caller (agentBridge) rather than imported here: the registry is a services+// module and lib must not import it (nor pull its heavy import-time tool graph+// into every prompt build). The template iterates `tools` + renders the+// directive brief + the current plan (present only on a re-plan).+function buildPlanView(project, toolSpecs) {+ const directive = project.directive && typeof project.directive === 'object' ? project.directive : {};+ const deliverables = Array.isArray(directive.deliverables) ? directive.deliverables : [];+ const tools = (Array.isArray(toolSpecs) ? toolSpecs : []).map((s) => ({+ name: s?.function?.name || '',+ description: s?.function?.description || '',+ parametersJson: JSON.stringify(s?.function?.parameters ?? {}),+ }));+ const currentSteps = Array.isArray(project.plan?.steps) ? project.plan.steps : [];+ return {+ project: buildProjectView(project),+ apiUrl: PORTOS_API_URL,+ directive: {+ goal: directive.goal || '',+ hasDeliverables: deliverables.length > 0,+ deliverables: deliverables.map((value) => ({ value })),+ constraintsJson: JSON.stringify(directive.constraints ?? {}),+ },+ tools,+ hasCurrentPlan: currentSteps.length > 0,+ currentPlanJson: JSON.stringify(+ currentSteps.map((s) => ({ stepId: s.stepId, toolName: s.toolName, status: s.status })),+ ),+ };+}++export async function buildPlanPrompt(project, { toolSpecs } = {}) {+ const view = buildPlanView(project, toolSpecs);+ return buildPrompt('cd-plan', view);+}+function frameTimelineLabel(i, total) {if (total <= 1) return 'only frame';const pct = Math.round((i / (total - 1)) * 100);diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 64b5d49e6f..559581638e 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -1,5 +1,5 @@import { z } from 'zod';-import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './creativeDirectorPresets.js';+import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES, PLAN_STEP_STATUSES } from './creativeDirectorPresets.js';import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';import { BIBLE_LIMITS } from './storyBible.js';import { emptyToUndefined } from './zodCompat.js';@@ -50,6 +50,24 @@ export const creativeDirectorCastMemberSchema = z.object({summary: z.string().max(500).optional(),});+// Production directive (CDO Phase 2, #2184) — the brief the planner agent turns+// into a plan. `goal` is the free-text intent ("produce a 6-issue noir comic in+// universe X with covers and a teaser trailer"); `deliverables` is the checklist+// of requested outputs; `constraints` scopes the run (target universe/series+// ids, output formats, and a daily-action budget cap). Kept permissive on the+// constraint values — the plan advance loop gates each tool call at dispatch, so+// the directive is context for the planner, not an enforcement surface itself.+export const creativeDirectorDirectiveSchema = z.object({+ goal: z.string().min(1).max(5000),+ deliverables: z.array(z.string().min(1).max(200)).max(20).default([]),+ constraints: z.object({+ universeId: z.string().max(120).nullable().optional(),+ seriesId: z.string().max(120).nullable().optional(),+ formats: z.array(z.string().min(1).max(64)).max(20).optional(),+ budgetCap: z.number().int().min(0).max(100000).nullable().optional(),+ }).default({}),+});+export const creativeDirectorProjectCreateSchema = z.object({name: z.string().min(1).max(200),aspectRatio: creativeDirectorAspectRatioSchema,@@ -76,6 +94,11 @@ export const creativeDirectorProjectCreateSchema = z.object({// used by the stitch step to mix in audio-stage music. Bare CD projects// (no pipeline origin) leave this null.sourceIssueId: z.string().min(1).max(64).nullable().optional(),+ // Production directive (CDO Phase 2, #2184). When present the project is+ // PLAN-driven: the planner agent turns this brief into a validated step list+ // the generalized advance loop executes through the gated creative tool+ // registry. Absent → the legacy video treatment/scene flow (unchanged).+ directive: creativeDirectorDirectiveSchema.nullable().optional(),});// Autonomous auto-cast (#1810). `types` narrows the catalog search to a set of@@ -196,6 +219,39 @@ export const creativeDirectorSceneUpdateSchema = z.object({}).nullable().optional(),}).strict();+// ---------------------------------------------------------------------------+// Production plans (CDO Phase 2, #2184).+//+// A plan is the validated step list the planner agent (`cd-plan`) writes for a+// directive-driven project. Each step names a creative-tool-registry tool+// (`toolName`) + its args, plus a `dependsOn[]` DAG edge list; the generalized+// advance loop executes steps sequentially (deps respected) through the gated+// `dispatchCreativeTool` chokepoint. `toolName` is validated as a bounded string+// here — the registry is a services module (lib can't import it), so the advance+// loop rejects an unknown tool at dispatch time (Unknown creative tool).+// ---------------------------------------------------------------------------++export const creativeDirectorPlanStepSchema = z.object({+ stepId: z.string().min(1).max(64),+ toolName: z.string().min(1).max(64),+ // Free-form tool args — each tool re-validates against its own Zod schema at+ // dispatch, so the plan gate stays permissive (an over-strict gate here would+ // duplicate every tool's schema and drift from it).+ args: z.record(z.any()).default({}),+ // DAG edges: stepIds that must reach a terminal-success state before this step+ // runs. Empty = runnable immediately (subject to sequential ordering).+ dependsOn: z.array(z.string().min(1).max(64)).max(50).default([]),+ // Runtime fields — the agent may omit them on a fresh plan; the sanitizer+ // (applyPlan) defaults status→pending, retryCount→0, result→null.+ status: z.enum(PLAN_STEP_STATUSES).optional(),+ retryCount: z.number().int().min(0).max(10).optional(),+ result: z.record(z.any()).nullable().optional(),+}).strict();++export const creativeDirectorPlanSchema = z.object({+ steps: z.array(creativeDirectorPlanStepSchema).min(1).max(60),+}).strict();+// ---------------------------------------------------------------------------// Create Suite — Importer.//diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex eb16e05758..11729293c0 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -330,7 +330,21 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// to 2 then (where a v1 peer would round-trip the new shape through an unaware// sanitizer). The project body is LWW-overwritten whole; scene video renders// ride the project's linked media collection (federated separately).- creativeDirectorProjects: 1,+ // v2 = `directive` + `plan` added (CDO Phase 2, #2184) — the production-plan+ // layer (a directive brief + a validated `plan.steps[]` the generalized advance+ // loop executes through the gated tool registry). Additive: a legacy video+ // project leaves both null and behaves exactly as before. Version-gated for the+ // same reason as every prior additive field — the project body is+ // LWW-overwritten WHOLE (`mergeProjectRecord`), so a ≤v1 peer that receives a+ // plan-driven project, re-sanitizes it through its directive/plan-unaware+ // path, and pushes back would silently strip both fields and last-writer-wins+ // the loss onto the newer peer. Bumping makes the older peer reject the+ // ahead-version project transfer instead. Per-category gate → only CD-project+ // sync pauses with old peers; every other category keeps flowing. No record+ // rewrite is needed — existing legacy projects simply lack both keys and the+ // advance loop treats an absent key identically to null (falsy → legacy video+ // flow); migration 175 only seeds the new `cd-plan` prompt stage.+ creativeDirectorProjects: 2,// v1 = Mood boards (PostgreSQL `mood_boards`) federated via the per-record// peer-sync push pipeline (record kind `moodBoard`, sync category `moodBoards`,// #1564). Same posture as `creativeDirectorProjects` above: a brand-NEW synceddiff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 803244db86..f1f8f2de40 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -14,6 +14,7 @@ import {creativeDirectorProjectCreateSchema,creativeDirectorProjectUpdateSchema,creativeDirectorTreatmentSchema,+ creativeDirectorPlanSchema,creativeDirectorSceneUpdateSchema,creativeDirectorAutoCastSuggestSchema,creativeDirectorAutoCastApplySchema,@@ -25,6 +26,7 @@ import {updateProject,deleteProject,setTreatment,+ setPlan,updateScene,} from '../services/creativeDirector/local.js';import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';@@ -191,6 +193,20 @@ router.patch('/:id/treatment', asyncHandler(async (req, res) => {res.json(updated);}));+// Agent-callable (CDO Phase 2, #2184): write the production plan. The planner+// agent (cd-plan) PATCHes a validated step list here; the server then executes+// it step-by-step through the gated tool registry. Idempotent re-PATCH (a+// re-plan) preserves already-completed steps by stepId (see applyPlan). Nudges+// the plan advance loop so execution begins on the returned plan.+router.patch('/:id/plan', asyncHandler(async (req, res) => {+ const plan = validateRequest(creativeDirectorPlanSchema, req.body);+ const updated = await setPlan(req.params.id, plan);+ const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');+ advanceAfterPlanStepSettled(req.params.id)+ .catch((e) => console.log(`⚠️ CD plan advance failed: ${e.message}`));+ res.json(updated);+}));+// Agent-callable: update a single scene's status / evaluation / retry count.router.patch('/:id/scene/:sceneId', asyncHandler(async (req, res) => {const data = validateRequest(creativeDirectorSceneUpdateSchema, req.body);diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex b6d6d22706..82da142875 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -16,7 +16,8 @@import { randomUUID } from 'crypto';import { addTask, cosEvents } from '../cos.js';-import { buildTreatmentPrompt, buildEvaluatePrompt } from '../../lib/creativeDirectorPrompts.js';+import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../../lib/creativeDirectorPrompts.js';+import { getToolSpecs } from '../creative/toolRegistry.js';import { recordRun } from './local.js';function buildTaskRecord(project, kind, scene, context) {@@ -53,6 +54,9 @@ function buildDescription(project, kind, scene) {if (kind === 'treatment') {return `Creative Director — Treatment for "${project.name}"`;}+ if (kind === 'plan') {+ return `Creative Director — Production Plan for "${project.name}"`;+ }if (kind === 'evaluate' && scene) {const total = project.treatment?.scenes?.length || '?';const intent = (scene.intent || '').slice(0, 60);@@ -83,6 +87,18 @@ export async function enqueueTreatmentTask(project) {return persistAndEmit(built, project, 'treatment', null);}+// CDO Phase 2 (#2184) — the planner. Mirrors enqueueTreatmentTask: an internal+// CoS task whose prompt (cd-plan) receives the directive + the resolved creative+// tool registry specs + the current plan (on a re-plan), and PATCHes a validated+// plan back via /:id/plan. `getToolSpecs()` runs here (services) so lib's prompt+// builder never imports the registry. Malformed plan output retries like the+// treatment stage — the agent reads the 4xx error body and re-PATCHes.+export async function enqueuePlanTask(project) {+ const context = await buildPlanPrompt(project, { toolSpecs: getToolSpecs() });+ const built = buildTaskRecord(project, 'plan', null, context);+ return persistAndEmit(built, project, 'plan', null);+}+export async function enqueueEvaluateTask(project, scene) {if (!scene) throw new Error('enqueueEvaluateTask: scene is required');const context = await buildEvaluatePrompt(project, scene);diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsindex 68211dc5a4..c2327c6670 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -26,6 +26,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { getProject, updateProject, updateScene, updateRun, recordRun } from './local.js';import { enqueueTreatmentTask } from './agentBridge.js';+import { advanceAfterPlanStepSettled } from './planAdvance.js';import { dispatchSceneEvaluation } from './sceneEvaluator.js';import { runSceneRender } from './sceneRunner.js';import { runStitch } from './stitchRunner.js';@@ -83,6 +84,14 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {if (!fresh) return;if (fresh.status === 'paused' || fresh.status === 'failed') return;+ // CDO Phase 2 (#2184): a directive-driven project runs the generalized plan+ // advance loop (the `plan` completion is the planner writing the plan; every+ // subsequent step runs server-side through the tool registry, no agent task).+ // Legacy video projects (no directive) stay on the scene loop below.+ if (fresh.directive) {+ return advanceAfterPlanStepSettled(fresh.id);+ }+// Always advance — advanceAfterSceneSettled is idempotent and inspects// project state to decide what comes next. Calling it for unknown kinds// (e.g. legacy 'scene' tasks from before the treatment/evaluate split)@@ -523,9 +532,12 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {/*** Convenience: kick off the project from the user's "Start" button. Skips- * straight to advancing.+ * straight to advancing. Routes a directive-driven project (CDO Phase 2) to the+ * generalized plan advance loop; legacy video projects to the scene loop.*/export async function startCreativeDirectorProject(projectId) {+ const project = await getProject(projectId).catch(() => null);+ if (project?.directive) return advanceAfterPlanStepSettled(projectId);return advanceAfterSceneSettled(projectId);}diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 770bc4f240..f57e5714ed 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -142,6 +142,18 @@ export async function setTreatment(id, treatmentInput) {return next;}+export async function setPlan(id, planInput) {+ const next = await (await selectBackend()).setPlan(id, planInput);+ emitRecordUpdated('creativeDirectorProject', id);+ return next;+}++export async function updatePlanStep(id, stepId, patch) {+ const result = await (await selectBackend()).updatePlanStep(id, stepId, patch);+ emitRecordUpdated('creativeDirectorProject', id);+ return result;+}+export async function updateScene(id, sceneId, patch) {const result = await (await selectBackend()).updateScene(id, sceneId, patch);emitRecordUpdated('creativeDirectorProject', id);diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsnew file mode 100644index 0000000000..4ac55da9ce--- /dev/null+++ b/server/services/creativeDirector/planAdvance.js@@ -0,0 +1,335 @@+/**+ * Creative Director — production-plan advance loop (CDO Phase 2, #2184).+ *+ * The generalized sibling of completionHook.js#advanceAfterSceneSettled. For a+ * DIRECTIVE-driven project (`project.directive` present), "what happens next" is+ * a pure function of the plan DAG on the project record — never a stored cursor:+ *+ * - No plan yet → enqueue the planner agent (cd-plan) to write one.+ * - A runnable step → dispatch it through the gated creative tool+ * registry (`dispatchCreativeTool`), one at a time,+ * sequentially, respecting `dependsOn`.+ * - A long-running step → stays `running` until its media job settles (a+ * completion event re-fires this loop).+ * - A step failed → bounded re-plan (MAX_REPLAN_ROUNDS), then pause+ * with residuals for human review.+ * - A blocked step → pause with the block reason (never silently retry+ * around a human-review pause).+ * - All steps terminal → the project is complete.+ *+ * Legacy video projects (no `directive`/`plan`) never enter here — the treatment/+ * scene flow in completionHook.js is unchanged. Idempotent + driven by CoS+ * completions (the planner task), media-job events (long-running steps), and boot+ * recovery — the same shape as the scene loop.+ */++import { getProject, updateProject, updatePlanStep, recordRun, updateRun } from './local.js';+import { enqueuePlanTask } from './agentBridge.js';+import { dispatchCreativeTool } from '../creative/toolRegistry.js';+import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';+import { MAX_REPLAN_ROUNDS, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';++const nowISO = () => new Date().toISOString();++/**+ * Pure next-step derivation over a plan DAG. Exported + side-effect-free so the+ * ordering/dependency/terminal logic is unit-tested directly against fixtures.+ *+ * Returns one of:+ * - `{ type: 'empty' }` — plan has no steps → nothing to execute.+ * - `{ type: 'waiting', step }` — a step is `running`; wait for it to settle.+ * - `{ type: 'blocked', step }` — a step is `blocked` (human-review pause).+ * - `{ type: 'run', step }` — the next runnable pending step (deps all+ * terminal-success), in listed order.+ * - `{ type: 'stuck', steps }` — pending steps remain but none is runnable+ * (a dependency failed or is missing).+ * - `{ type: 'failed', steps }` — every step terminal and ≥1 failed.+ * - `{ type: 'complete' }` — every step done/skipped.+ *+ * Sequential by construction: even when two pending steps are both runnable it+ * returns the FIRST (array order) — v1 has no parallel branches.+ *+ * @param {{steps?: Array<object>}} plan+ */+export function deriveNextPlanAction(plan) {+ const steps = Array.isArray(plan?.steps) ? plan.steps : [];+ if (!steps.length) return { type: 'empty' };+ const byId = new Map(steps.map((s) => [s.stepId, s]));++ const running = steps.find((s) => s.status === 'running');+ if (running) return { type: 'waiting', step: running };++ const blocked = steps.find((s) => s.status === 'blocked');+ if (blocked) return { type: 'blocked', step: blocked };++ const depsSatisfied = (s) => (Array.isArray(s.dependsOn) ? s.dependsOn : []).every((id) => {+ const dep = byId.get(id);+ return dep && PLAN_STEP_TERMINAL_SUCCESS.has(dep.status);+ });++ const pending = steps.filter((s) => s.status === 'pending');+ const runnable = pending.find(depsSatisfied);+ if (runnable) return { type: 'run', step: runnable };+ // No pending step is runnable and nothing is running → the plan can't progress+ // (a dependency failed/missing, or a cycle). Surface as residuals.+ if (pending.length) return { type: 'stuck', steps: pending };++ const failed = steps.filter((s) => s.status === 'failed');+ if (failed.length) return { type: 'failed', steps: failed };+ return { type: 'complete' };+}++// In-memory dedup, same role as completionHook's inflight sets. `inflightPlanner`+// covers the updateProject→enqueue window for the planner; `inflightPlanStep`+// covers the getProject→recordRun window for a dispatch (released once the+// persisted `running` step+run guard re-entry). `planJobCleanups` holds the+// teardown for every armed long-running media-job listener so tests can drop them.+const inflightPlanner = new Set();+const inflightPlanStep = new Set();+const planJobCleanups = new Map();++async function pausePlanWithResidual(projectId, reason) {+ await updateProject(projectId, { status: 'paused', failureReason: reason })+ .catch((e) => console.log(`⚠️ CD plan pause for ${projectId} failed: ${e.message}`));+ console.log(`⏸️ CD plan ${projectId} paused: ${reason}`);+}++async function finishRun(projectId, runId, status, failureReason) {+ if (!runId) return;+ await updateRun(projectId, runId, {+ status,+ completedAt: nowISO(),+ ...(failureReason ? { failureReason } : {}),+ }).catch((e) => console.log(`⚠️ CD plan finishRun ${runId} on ${projectId} failed: ${e.message}`));+}++// Compact, id-only summary of a tool result so the plan step's `result` never+// bloats with a full render payload / record body (mirrors the run ledger's+// digest-not-payload rule).+function summarizeResult(result) {+ if (!result || typeof result !== 'object') return {};+ const out = {};+ for (const k of ['id', 'jobId', 'seriesId', 'issueId', 'universeId', 'name', 'status']) {+ if (result[k] != null) out[k] = result[k];+ }+ return out;+}++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;+ 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));+}++/**+ * The generalized advance loop. Pure next-step over the plan, idempotent, safe+ * to call from a CoS completion, a media-job settle, boot recovery, or a manual+ * resume — it re-reads project state and derives the one next action every time.+ *+ * @param {string} projectId+ */+export async function advanceAfterPlanStepSettled(projectId) {+ const project = await getProject(projectId).catch(() => null);+ if (!project) return;+ if (project.status === 'paused' || project.status === 'failed') return;+ // Legacy video project — the scene loop owns it; never plan-advance it.+ if (!project.directive) return;++ // No plan yet → enqueue the planner (mirrors the no-treatment branch).+ if (!Array.isArray(project.plan?.steps)) {+ return enqueuePlannerOnce(project);+ }++ const action = deriveNextPlanAction(project.plan);+ switch (action.type) {+ case 'waiting':+ // A step is running (a long-running job in flight). Its settle re-fires us.+ return;+ case 'blocked':+ return pausePlanWithResidual(+ projectId,+ `Step "${action.step.stepId}" is blocked: ${action.step.result?.reason || 'awaiting human review'}`,+ );+ case 'stuck':+ return pausePlanWithResidual(+ projectId,+ `No runnable step — ${action.steps.length} pending step(s) blocked by a failed or missing dependency`,+ );+ case 'failed':+ // Safety net: a step is 'failed' but the executor didn't route it (e.g. a+ // hand-edited/legacy record). Send it through the failure handler.+ return handlePlanStepFailure(projectId, action.steps[0]);+ case 'empty':+ case 'complete':+ if (project.status !== 'complete') {+ await updateProject(projectId, { status: 'complete' })+ .catch((e) => console.log(`⚠️ CD plan complete for ${projectId} failed: ${e.message}`));+ console.log(`✅ CD plan ${projectId} complete`);+ }+ return;+ case 'run':+ return runPlanStep(project, action.step);+ default:+ return;+ }+}++async function runPlanStep(project, step) {+ const projectId = project.id;+ const key = `${projectId}:${step.stepId}`;+ if (inflightPlanStep.has(key)) return;+ // A persisted 'running' run for this step means a concurrent advance already+ // dispatched it — don't double-dispatch.+ const alreadyRunning = (project.runs || []).some(+ (r) => r.kind === 'plan-step' && r.stepId === step.stepId && r.status === 'running',+ );+ if (alreadyRunning) return;+ inflightPlanStep.add(key);+ let run;+ try {+ if (project.status !== 'rendering') await updateProject(projectId, { status: 'rendering' });+ await updatePlanStep(projectId, step.stepId, { status: 'running', startedAt: nowISO() });+ run = await recordRun(projectId, {+ kind: 'plan-step', stepId: step.stepId, toolName: step.toolName, status: 'running',+ });+ } finally {+ // The persisted 'running' step + run row now guard re-entry — release the+ // in-memory key so a raced advance sees the persisted state and bails.+ inflightPlanStep.delete(key);+ }+ console.log(`▶️ CD plan ${projectId}: dispatching step "${step.stepId}" (${step.toolName})`);+ // Outside the request lifecycle — catch so a throw becomes a settle, never an+ // unhandled rejection.+ const dispatch = await dispatchCreativeTool(step.toolName, step.args || {}, { projectId })+ .catch((err) => ({ ok: false, threw: true, error: err.message }));+ return settlePlanStepDispatch(projectId, step, run?.runId, dispatch);+}++async function settlePlanStepDispatch(projectId, step, runId, dispatch) {+ // Gate rejection (autonomy off / over budget / wrapped-service refusal): the+ // step did no work. Block it + pause so a human can raise the budget / flip+ // autonomy and Resume — the CD never silently retries around a governance stop.+ if (!dispatch || (dispatch.ok !== true && !dispatch.threw)) {+ const reason = dispatch?.reason || 'rejected';+ await finishRun(projectId, runId, 'failed', reason);+ await updatePlanStep(projectId, step.stepId, { status: 'blocked', result: { reason } });+ return pausePlanWithResidual(+ projectId,+ `Step "${step.stepId}" (${step.toolName}) rejected by the creative gate: ${reason}`,+ );+ }+ // Real tool error → mark failed, then bounded re-plan or pause.+ if (dispatch.threw) {+ const error = dispatch.error || 'tool error';+ await finishRun(projectId, runId, 'failed', error);+ const bumped = (step.retryCount || 0) + 1;+ await updatePlanStep(projectId, step.stepId, { status: 'failed', retryCount: bumped, result: { error } });+ return handlePlanStepFailure(projectId, { ...step, retryCount: bumped });+ }+ // dry-run — the whole plan is walked as a preview (no side effects executed).+ if (dispatch.planned || dispatch.mode === 'dry-run') {+ await finishRun(projectId, runId, 'completed');+ await updatePlanStep(projectId, step.stepId, { status: 'done', result: { planned: true } });+ return advanceAfterPlanStepSettled(projectId);+ }+ // Long-running (media render / job): stay `running` until the underlying job+ // settles; a completion event re-fires the loop.+ if (dispatch.longRunning) {+ const jobId = dispatch.result?.jobId;+ if (jobId) return armPlanJobListener(projectId, step.stepId, jobId, runId);+ // A long-running tool with no observable job handle — Series Autopilot returns+ // a run handle, not a jobId; its in-process progress/pause event bridge lands+ // in CDO Phase 3. For now a successful START counts as step completion so the+ // plan makes progress; the underlying run continues on its own.+ console.log(`⚠️ CD plan ${projectId}: step "${step.stepId}" (${step.toolName}) is long-running with no jobId — marking done on start (event bridge lands in Phase 3)`);+ await finishRun(projectId, runId, 'completed');+ await updatePlanStep(projectId, step.stepId, { status: 'done', result: summarizeResult(dispatch.result) });+ return advanceAfterPlanStepSettled(projectId);+ }+ // Synchronous success (free / llm non-long-running).+ await finishRun(projectId, runId, 'completed');+ await updatePlanStep(projectId, step.stepId, { status: 'done', result: summarizeResult(dispatch.result) });+ console.log(`✅ CD plan ${projectId}: step "${step.stepId}" done`);+ return advanceAfterPlanStepSettled(projectId);+}++// Bounded re-planning (autopilot's convergence-pause contract): on a step+// failure the planner may revise the remaining steps at most MAX_REPLAN_ROUNDS+// times, then the project pauses with residuals for human review.+async function handlePlanStepFailure(projectId, step) {+ const project = await getProject(projectId).catch(() => null);+ if (!project || project.status === 'paused' || project.status === 'failed') return;+ const rounds = project.plan?.replanRounds || 0;+ if (rounds < MAX_REPLAN_ROUNDS && !inflightPlanner.has(projectId)) {+ 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));+ return;+ }+ return pausePlanWithResidual(+ projectId,+ `Step "${step.stepId}" (${step.toolName || 'tool'}) failed after ${rounds} re-plan round(s) — paused for human review`,+ );+}++// Register a one-shot listener that settles a long-running plan step when its+// media job reaches a terminal state. Idempotent teardown; closes the race where+// the job already settled between dispatch returning and the listener attaching.+function armPlanJobListener(projectId, stepId, jobId, runId) {+ const key = `${projectId}:${stepId}`;+ let fired = false;+ const teardown = () => {+ mediaJobEvents.off('completed', settle);+ mediaJobEvents.off('failed', settle);+ mediaJobEvents.off('canceled', settle);+ planJobCleanups.delete(key);+ };+ function settle(job) {+ if (fired || job?.id !== jobId) return;+ fired = true;+ teardown();+ const success = job.status === 'completed';+ // Runs outside the request lifecycle (media-queue emitter) — never throw out.+ (async () => {+ await finishRun(projectId, runId, success ? 'completed' : 'failed', success ? undefined : `job ${job.status}`);+ if (success) {+ await updatePlanStep(projectId, stepId, { status: 'done', result: { jobId } });+ await advanceAfterPlanStepSettled(projectId);+ } else {+ await updatePlanStep(projectId, stepId, { status: 'failed', result: { jobId, jobStatus: job.status } });+ await handlePlanStepFailure(projectId, { stepId, toolName: '(long-running job)', retryCount: 0 });+ }+ })().catch((e) => console.log(`⚠️ CD plan ${projectId} job settle for ${stepId} failed: ${e.message}`));+ }+ mediaJobEvents.on('completed', settle);+ mediaJobEvents.on('failed', settle);+ mediaJobEvents.on('canceled', settle);+ planJobCleanups.set(key, teardown);+ console.log(`⏳ CD plan ${projectId}: step "${stepId}" waiting on job ${String(jobId).slice(0, 8)}`);+ // The job may already be terminal (settled between dispatch and attach) — its+ // event fired and won't repeat. Re-check and settle immediately if so.+ const current = listJobs().find((j) => j.id === jobId);+ if (current && (current.status === 'completed' || current.status === 'failed' || current.status === 'canceled')) {+ settle(current);+ }+}++// Test-only: clear module-level dedup + tear down any armed media-job listeners+// so a suite that leaves a long-running step pending can't leak a live listener+// into a later test.+export function __resetPlanInflightState() {+ for (const teardown of planJobCleanups.values()) teardown();+ planJobCleanups.clear();+ inflightPlanner.clear();+ inflightPlanStep.clear();+}diff --git a/server/services/creativeDirector/planAdvance.test.js b/server/services/creativeDirector/planAdvance.test.jsnew file mode 100644index 0000000000..175d250c46--- /dev/null+++ b/server/services/creativeDirector/planAdvance.test.js@@ -0,0 +1,234 @@+/**+ * CDO Phase 2 (#2184) — production-plan advance loop.+ *+ * Two layers:+ * 1. `deriveNextPlanAction` — pure next-step derivation over a plan DAG. No+ * mocks; locks the ordering/dependency/terminal semantics.+ * 2. `advanceAfterPlanStepSettled` — the executor, over a mocked local store ++ * mocked `dispatchCreativeTool`. Locks: dispatch → step transitions, gated+ * rejection pauses, bounded re-planning, and the legacy-project no-op.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ---- pure derivation (no mocks needed) -------------------------------------+import { deriveNextPlanAction } from './planAdvance.js';++const step = (id, over = {}) => ({ stepId: id, toolName: 't', args: {}, dependsOn: [], status: 'pending', ...over });++describe('deriveNextPlanAction (pure)', () => {+ it('empty plan → { type: empty }', () => {+ expect(deriveNextPlanAction({ steps: [] }).type).toBe('empty');+ expect(deriveNextPlanAction(null).type).toBe('empty');+ });+ it('a running step short-circuits to waiting', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'running' }), step('b')] });+ expect(a).toMatchObject({ type: 'waiting', step: { stepId: 'a' } });+ });+ it('a blocked step short-circuits to blocked', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'done' }), step('b', { status: 'blocked' })] });+ expect(a).toMatchObject({ type: 'blocked', step: { stepId: 'b' } });+ });+ it('runs the first pending step with all deps terminal-success', () => {+ const a = deriveNextPlanAction({ steps: [step('a'), step('b', { dependsOn: ['a'] })] });+ expect(a).toMatchObject({ type: 'run', step: { stepId: 'a' } });+ });+ it('respects dependsOn — a dependent waits until its dep is done, then runs', () => {+ const notYet = deriveNextPlanAction({ steps: [step('a', { status: 'done' }), step('b', { dependsOn: ['a'] })] });+ expect(notYet).toMatchObject({ type: 'run', step: { stepId: 'b' } });+ // While the dep is still pending, only the dep is runnable (sequential).+ const first = deriveNextPlanAction({ steps: [step('a'), step('b', { dependsOn: ['a'] })] });+ expect(first.step.stepId).toBe('a');+ });+ it('treats a skipped dep as satisfied', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'skipped' }), step('b', { dependsOn: ['a'] })] });+ expect(a).toMatchObject({ type: 'run', step: { stepId: 'b' } });+ });+ it('is sequential — returns ONE runnable step even when two are eligible', () => {+ const a = deriveNextPlanAction({ steps: [step('a'), step('b')] });+ expect(a).toMatchObject({ type: 'run', step: { stepId: 'a' } });+ });+ it('pending steps blocked by a FAILED dependency → stuck (pause with residuals)', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'failed' }), step('b', { dependsOn: ['a'] })] });+ expect(a.type).toBe('stuck');+ expect(a.steps.map((s) => s.stepId)).toEqual(['b']);+ });+ it('pending step depending on an UNKNOWN id → stuck', () => {+ const a = deriveNextPlanAction({ steps: [step('b', { dependsOn: ['ghost'] })] });+ expect(a.type).toBe('stuck');+ });+ it('all steps done/skipped → complete', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'done' }), step('b', { status: 'skipped' })] });+ expect(a.type).toBe('complete');+ });+ it('all terminal with a failed step → failed', () => {+ const a = deriveNextPlanAction({ steps: [step('a', { status: 'done' }), step('b', { status: 'failed' })] });+ expect(a.type).toBe('failed');+ expect(a.steps.map((s) => s.stepId)).toEqual(['b']);+ });+});++// ---- executor (mocked store + dispatch) ------------------------------------++const mockGetProject = vi.fn();+const mockUpdateProject = vi.fn();+const mockUpdatePlanStep = vi.fn();+const mockRecordRun = vi.fn();+const mockUpdateRun = vi.fn();+const mockEnqueuePlanTask = vi.fn();+const mockDispatch = vi.fn();+const mockListJobs = vi.fn();++vi.mock('./local.js', () => ({+ getProject: (...a) => mockGetProject(...a),+ updateProject: (...a) => mockUpdateProject(...a),+ updatePlanStep: (...a) => mockUpdatePlanStep(...a),+ recordRun: (...a) => mockRecordRun(...a),+ updateRun: (...a) => mockUpdateRun(...a),+}));+vi.mock('./agentBridge.js', () => ({+ enqueuePlanTask: (...a) => mockEnqueuePlanTask(...a),+}));+vi.mock('../creative/toolRegistry.js', () => ({+ dispatchCreativeTool: (...a) => mockDispatch(...a),+}));+vi.mock('../mediaJobQueue/index.js', () => ({+ listJobs: (...a) => mockListJobs(...a),+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },+}));++const { advanceAfterPlanStepSettled, __resetPlanInflightState } = await import('./planAdvance.js');++// A tiny in-memory project the mocked store mutates so recursion sees fresh state.+function makeStore(initial) {+ let project = structuredClone(initial);+ mockGetProject.mockImplementation(async () => structuredClone(project));+ mockUpdateProject.mockImplementation(async (_id, patch) => {+ project = { ...project, ...patch };+ return structuredClone(project);+ });+ mockUpdatePlanStep.mockImplementation(async (_id, stepId, patch) => {+ const idx = project.plan.steps.findIndex((s) => s.stepId === stepId);+ if (idx < 0) return null;+ project.plan.steps[idx] = { ...project.plan.steps[idx], ...patch };+ return structuredClone(project.plan.steps[idx]);+ });+ mockRecordRun.mockImplementation(async (_id, entry) => {+ const run = { runId: `run-${(project.runs?.length || 0) + 1}`, ...entry };+ project.runs = [...(project.runs || []), run];+ return run;+ });+ mockUpdateRun.mockImplementation(async (_id, runId, patch) => {+ const idx = (project.runs || []).findIndex((r) => r.runId === runId);+ if (idx >= 0) project.runs[idx] = { ...project.runs[idx], ...patch };+ return null;+ });+ return () => project;+}++beforeEach(() => {+ vi.clearAllMocks();+ __resetPlanInflightState();+ mockListJobs.mockReturnValue([]);+ mockEnqueuePlanTask.mockResolvedValue(undefined);+});++const planProject = (steps, over = {}) => ({+ id: 'cd-1',+ status: 'rendering',+ directive: { goal: 'do it', deliverables: [], constraints: {} },+ plan: { steps, replanRounds: 0 },+ runs: [],+ ...over,+});++describe('advanceAfterPlanStepSettled — executor', () => {+ it('is a no-op for a legacy project (no directive)', async () => {+ makeStore({ id: 'cd-1', status: 'rendering', directive: null, plan: null, runs: [] });+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockDispatch).not.toHaveBeenCalled();+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();+ });++ it('enqueues the planner when a directive project has no plan yet', async () => {+ makeStore({ id: 'cd-1', status: 'draft', directive: { goal: 'g', deliverables: [], constraints: {} }, plan: null, runs: [] });+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockUpdateProject).toHaveBeenCalledWith('cd-1', { status: 'planning' });+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);+ });++ it('dispatches a synchronous step, marks it done, and advances to the next', async () => {+ const read = makeStore(planProject([+ step('a', { toolName: 'pipeline_createSeries' }),+ step('b', { toolName: 'pipeline_generateStage', dependsOn: ['a'] }),+ ]));+ mockDispatch.mockResolvedValue({ ok: true, mode: 'execute', result: { id: 's1' } });+ await advanceAfterPlanStepSettled('cd-1');+ // Both steps dispatched in order, then project completes.+ expect(mockDispatch).toHaveBeenNthCalledWith(1, 'pipeline_createSeries', {}, { projectId: 'cd-1' });+ expect(mockDispatch).toHaveBeenNthCalledWith(2, 'pipeline_generateStage', {}, { projectId: 'cd-1' });+ const p = read();+ expect(p.plan.steps.map((s) => s.status)).toEqual(['done', 'done']);+ expect(p.status).toBe('complete');+ });++ it('records a run per step and stores an id-only result summary', async () => {+ const read = makeStore(planProject([step('a', { toolName: 'pipeline_createSeries' })]));+ mockDispatch.mockResolvedValue({ ok: true, mode: 'execute', result: { id: 's1', seriesId: 's1', huge: 'x'.repeat(9999) } });+ await advanceAfterPlanStepSettled('cd-1');+ const p = read();+ expect(p.runs.some((r) => r.kind === 'plan-step' && r.stepId === 'a')).toBe(true);+ expect(p.plan.steps[0].result).toEqual({ id: 's1', seriesId: 's1' });+ });++ it('pauses with residuals when the gate rejects a step (over budget)', async () => {+ const read = makeStore(planProject([step('a', { toolName: 'pipeline_generateStage' })]));+ mockDispatch.mockResolvedValue({ ok: false, rejected: true, reason: 'budget' });+ await advanceAfterPlanStepSettled('cd-1');+ const p = read();+ expect(p.status).toBe('paused');+ expect(p.plan.steps[0].status).toBe('blocked');+ expect(p.failureReason).toMatch(/budget/);+ });++ it('bounded re-plan: a failed step re-enqueues the planner until MAX_REPLAN_ROUNDS, then pauses', async () => {+ // replanRounds already at the max → the failure must pause, not re-plan.+ const read = makeStore(planProject([step('a', { toolName: 'pipeline_generateStage' })], { plan: { steps: [step('a', { toolName: 'pipeline_generateStage' })], replanRounds: 2 } }));+ mockDispatch.mockResolvedValue({ ok: false, threw: true, error: 'boom' });+ await advanceAfterPlanStepSettled('cd-1');+ const p = read();+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();+ expect(p.status).toBe('paused');+ expect(p.plan.steps[0].status).toBe('failed');+ });++ it('a failed step under the replan budget re-enqueues the planner', async () => {+ makeStore(planProject([step('a', { toolName: 'pipeline_generateStage' })]));+ mockDispatch.mockResolvedValue({ ok: false, threw: true, error: 'boom' });+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1);+ });++ it('leaves a long-running step running until its job settles (does not advance past it)', async () => {+ const read = makeStore(planProject([+ step('a', { toolName: 'pipeline_renderComicCover' }),+ step('b', { toolName: 'pipeline_generateStage', dependsOn: ['a'] }),+ ]));+ mockDispatch.mockResolvedValue({ ok: true, mode: 'execute', longRunning: true, result: { jobId: 'job-1' } });+ await advanceAfterPlanStepSettled('cd-1');+ const p = read();+ // Step a stays running (waiting on job-1); step b is untouched.+ expect(p.plan.steps[0].status).toBe('running');+ expect(p.plan.steps[1].status).toBe('pending');+ expect(mockDispatch).toHaveBeenCalledTimes(1);+ expect(p.status).not.toBe('complete');+ });++ it('does not double-dispatch a step already running (idempotent)', async () => {+ makeStore(planProject([step('a', { toolName: 'pipeline_createSeries', status: 'running' })], {+ runs: [{ runId: 'r0', kind: 'plan-step', stepId: 'a', status: 'running' }],+ }));+ await advanceAfterPlanStepSettled('cd-1');+ expect(mockDispatch).not.toHaveBeenCalled();+ });+});diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.jsindex 6b687bf540..4ed92d337a 100644--- a/server/services/creativeDirector/projectsDB.js+++ b/server/services/creativeDirector/projectsDB.js@@ -28,6 +28,8 @@ import {buildProjectRecord,applyProjectPatch,applyTreatment,+ applyPlan,+ applyPlanStepUpdate,applySceneUpdate,appendRun,applyRunUpdate,@@ -231,6 +233,19 @@ export async function setTreatment(id, treatmentInput) {return project;}+export async function setPlan(id, planInput) {+ const { project } = await withLockedProject(id, (p) => ({ project: applyPlan(p, planInput) }));+ return project;+}++export async function updatePlanStep(id, stepId, patch) {+ const { result } = await withLockedProject(id, (p) => {+ const { project, updated } = applyPlanStepUpdate(p, stepId, patch);+ return { project, result: updated };+ });+ return result;+}+export async function updateScene(id, sceneId, patch) {const { result } = await withLockedProject(id, (p) => {const { project, updated } = applySceneUpdate(p, sceneId, patch);diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.jsindex 1f78891c5d..fb9324519f 100644--- a/server/services/creativeDirector/projectsFile.js+++ b/server/services/creativeDirector/projectsFile.js@@ -21,6 +21,8 @@ import {buildProjectRecord,applyProjectPatch,applyTreatment,+ applyPlan,+ applyPlanStepUpdate,applySceneUpdate,appendRun,applyRunUpdate,@@ -171,6 +173,27 @@ export async function setTreatment(id, treatmentInput) {return all[idx];}+export async function setPlan(id, planInput) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ // Missing OR tombstoned (#1564 soft-delete) → gone for user-facing mutators, so a+ // post-delete write can't resurrect + re-push a modified tombstone.+ if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ all[idx] = applyPlan(all[idx], planInput);+ await saveAll(all);+ return all[idx];+}++export async function updatePlanStep(id, stepId, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { project, updated } = applyPlanStepUpdate(all[idx], stepId, patch);+ all[idx] = project;+ await saveAll(all);+ return updated;+}+export async function updateScene(id, sceneId, patch) {const all = await loadAll();const idx = all.findIndex((p) => p.id === id);diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 515d7315ca..050c0495b1 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -12,8 +12,8 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';-import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';-import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';+import { creativeDirectorTreatmentSchema, creativeDirectorPlanSchema } from '../../lib/validation.js';+import { PROJECT_STATUSES, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';import { compareNewerWins } from '../../lib/lwwTimestamp.js';import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';import { localImageFilename } from '../../lib/localImageFilename.js';@@ -86,7 +86,7 @@ export function buildProjectRecord(input, { id, now, collectionId }) {name, aspectRatio, quality, modelId, targetDurationSeconds,styleSpec = '', startingImageFile = null, userStory = null,disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,- cast = [], generateFirstPass = false,+ cast = [], generateFirstPass = false, directive = null,} = input;return {id,@@ -131,6 +131,16 @@ export function buildProjectRecord(input, { id, now, collectionId }) {// needs no schema-version bump.musicBed: null,treatment: null,+ // Production directive + plan (CDO Phase 2, #2184). A directive-driven+ // project turns `directive` into `plan.steps[]` via the planner agent, then+ // the generalized advance loop executes them through the gated tool+ // registry. Both null on a legacy video project — the treatment/scene flow+ // never touches them, so `plan === null` is the back-compat discriminator+ // the advance loop keys on (schema-version gated for federation; see+ // schemaVersions.js creativeDirectorProjects v2 + migration 175). Additive —+ // the whole record round-trips through the JSONB column verbatim.+ directive: directive && typeof directive === 'object' ? directive : null,+ plan: null,runs: [],// Soft-delete / LWW tombstone trio (#1564) — projects federate across peers// via the per-record push pipeline (record kind `creativeDirectorProject`,@@ -232,6 +242,83 @@ export function applyTreatment(project, treatmentInput) {};}+/**+ * Validate + apply a production plan to a project (CDO Phase 2, #2184). Returns+ * the next record. Normalizes each step's runtime fields (status→pending unless+ * the agent supplied one, retryCount→0, result→null) and, on a RE-PLAN (a plan+ * already exists), PRESERVES the status/result/retryCount of any incoming step+ * whose `stepId` matches an already terminal-SUCCESS local step — so the bounded+ * re-planner can revise remaining steps without re-running work already done.+ * `plan.replanRounds` counts how many times a plan has been (re)written: 0 for+ * the first plan, +1 each subsequent one — the advance loop's MAX_REPLAN_ROUNDS+ * gate reads it. Flips a draft/planning project to `rendering` so the advance+ * loop starts executing; preserves paused/failed (a human parked it).+ */+export function applyPlan(project, planInput) {+ const parsed = creativeDirectorPlanSchema.safeParse(planInput);+ if (!parsed.success) {+ throw new ServerError(+ `Plan validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ const prevSteps = Array.isArray(project.plan?.steps) ? project.plan.steps : [];+ const prevById = new Map(prevSteps.map((s) => [s.stepId, s]));+ const steps = parsed.data.steps.map((s) => {+ const prior = prevById.get(s.stepId);+ // Preserve a step the prior plan already finished successfully — a re-plan+ // must not re-run a completed render or re-issue a created record.+ if (prior && PLAN_STEP_TERMINAL_SUCCESS.has(prior.status)) {+ return {+ ...s,+ status: prior.status,+ result: prior.result ?? null,+ retryCount: prior.retryCount ?? 0,+ dependsOn: Array.isArray(s.dependsOn) ? s.dependsOn : [],+ };+ }+ return {+ ...s,+ status: s.status || 'pending',+ retryCount: s.retryCount ?? 0,+ result: s.result ?? null,+ dependsOn: Array.isArray(s.dependsOn) ? s.dependsOn : [],+ };+ });+ const replanRounds = project.plan ? (project.plan.replanRounds || 0) + 1 : 0;+ const nextStatus = (project.status === 'paused' || project.status === 'failed')+ ? project.status+ : 'rendering';+ return {+ ...project,+ plan: { steps, replanRounds, updatedAt: new Date().toISOString() },+ status: nextStatus,+ updatedAt: new Date().toISOString(),+ };+}++/**+ * Patch a single plan step. Returns `{ project, updated }`; `updated` is null+ * (and `project` unchanged) when the project has no plan or the stepId is+ * unknown — mirrors applyRunUpdate's "return null, don't throw" contract so the+ * advance loop's fire-and-forget writes never 500 on a raced delete/replan.+ */+export function applyPlanStepUpdate(project, stepId, patch) {+ const steps = Array.isArray(project.plan?.steps) ? project.plan.steps : null;+ if (!steps) return { project, updated: null };+ const idx = steps.findIndex((s) => s.stepId === stepId);+ if (idx < 0) return { project, updated: null };+ const updated = { ...steps[idx], ...patch };+ const nextSteps = steps.slice();+ nextSteps[idx] = updated;+ const next = {+ ...project,+ plan: { ...project.plan, steps: nextSteps, updatedAt: new Date().toISOString() },+ updatedAt: new Date().toISOString(),+ };+ return { project: next, updated };+}+/*** Apply a patch to a single scene. Returns `{ project, updated }` (the next* record + the updated scene). Throws if the project has no treatment or thediff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsindex 155b58b208..97c851cbc2 100644--- a/server/services/creativeDirector/projectsLogic.test.js+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -13,6 +13,8 @@ import {buildProjectRecord,applyProjectPatch,applyTreatment,+ applyPlan,+ applyPlanStepUpdate,applySceneUpdate,appendRun,applyRunUpdate,@@ -278,3 +280,102 @@ describe('mergeProjectRecord (LWW, tombstone-aware)', () => {expect(mergeProjectRecord(at('2026-06-23T00:00:00.000Z'), { name: 'no id' }).next).toBeNull();});});++// =============================================================================+// CDO Phase 2 (#2184) — production directive + plan transforms.+// =============================================================================++const VALID_PLAN = {+ steps: [+ { stepId: 'a', toolName: 'pipeline_createSeries', args: { name: 'Noir' } },+ { stepId: 'b', toolName: 'pipeline_renderComicCover', args: { issueId: 'i1' }, dependsOn: ['a'] },+ ],+};++describe('buildProjectRecord — directive/plan (CDO Phase 2)', () => {+ it('defaults directive and plan to null on a bare project', () => {+ const p = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 },+ { id: 'cd-1', now: 'T', collectionId: 'col-1' },+ );+ expect(p.directive).toBeNull();+ expect(p.plan).toBeNull();+ });+ it('stores a supplied directive object verbatim', () => {+ const directive = { goal: 'make a comic', deliverables: ['covers'], constraints: { universeId: 'u1' } };+ const p = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9, directive },+ { id: 'cd-1', now: 'T', collectionId: 'col-1' },+ );+ expect(p.directive).toEqual(directive);+ expect(p.plan).toBeNull();+ });+ it('coerces a non-object directive to null', () => {+ const p = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9, directive: 'nope' },+ { id: 'cd-1', now: 'T', collectionId: 'col-1' },+ );+ expect(p.directive).toBeNull();+ });+});++describe('applyPlan', () => {+ it('normalizes steps (status→pending, retryCount→0, result→null, dependsOn→[]) and flips planning→rendering', () => {+ const next = applyPlan({ id: 'cd-1', status: 'planning' }, VALID_PLAN);+ expect(next.status).toBe('rendering');+ expect(next.plan.replanRounds).toBe(0);+ expect(next.plan.steps[0]).toMatchObject({ stepId: 'a', status: 'pending', retryCount: 0, result: null, dependsOn: [] });+ expect(next.plan.steps[1]).toMatchObject({ stepId: 'b', status: 'pending', dependsOn: ['a'] });+ });+ it('preserves paused/failed status (a human parked it)', () => {+ expect(applyPlan({ id: 'cd-1', status: 'paused' }, VALID_PLAN).status).toBe('paused');+ expect(applyPlan({ id: 'cd-1', status: 'failed' }, VALID_PLAN).status).toBe('failed');+ });+ it('throws a validation error on a malformed plan', () => {+ expect(() => applyPlan({ id: 'cd-1', status: 'planning' }, { steps: [] })).toThrow(/Plan validation failed/);+ expect(() => applyPlan({ id: 'cd-1', status: 'planning' }, { steps: [{ stepId: 'a' }] })).toThrow(/Plan validation failed/);+ });+ it('on a RE-PLAN preserves an already-done step verbatim and bumps replanRounds', () => {+ const first = applyPlan({ id: 'cd-1', status: 'planning' }, VALID_PLAN);+ // Mark step "a" done as the advance loop would.+ first.plan.steps[0].status = 'done';+ first.plan.steps[0].result = { seriesId: 's1' };+ const revised = applyPlan(first, {+ steps: [+ { stepId: 'a', toolName: 'pipeline_createSeries', args: { name: 'Noir' } },+ { stepId: 'c', toolName: 'pipeline_generateStage', args: { issueId: 'i1', stageId: 'prose' }, dependsOn: ['a'] },+ ],+ });+ expect(revised.plan.replanRounds).toBe(1);+ // "a" keeps its terminal-success status + result — never re-run.+ expect(revised.plan.steps[0]).toMatchObject({ stepId: 'a', status: 'done', result: { seriesId: 's1' } });+ // The revised remaining step is fresh pending.+ expect(revised.plan.steps[1]).toMatchObject({ stepId: 'c', status: 'pending' });+ });+ it('does NOT preserve a failed step across a re-plan (re-runs it)', () => {+ const first = applyPlan({ id: 'cd-1', status: 'planning' }, VALID_PLAN);+ first.plan.steps[0].status = 'failed';+ const revised = applyPlan(first, VALID_PLAN);+ expect(revised.plan.steps[0].status).toBe('pending');+ });+});++describe('applyPlanStepUpdate', () => {+ it('patches a single step and returns the updated step', () => {+ const base = applyPlan({ id: 'cd-1', status: 'planning' }, VALID_PLAN);+ const { project, updated } = applyPlanStepUpdate(base, 'b', { status: 'running' });+ expect(updated).toMatchObject({ stepId: 'b', status: 'running' });+ expect(project.plan.steps.find((s) => s.stepId === 'b').status).toBe('running');+ expect(project.plan.steps.find((s) => s.stepId === 'a').status).toBe('pending');+ });+ it('returns { updated: null } (project unchanged) for an unknown stepId', () => {+ const base = applyPlan({ id: 'cd-1', status: 'planning' }, VALID_PLAN);+ const { project, updated } = applyPlanStepUpdate(base, 'zzz', { status: 'done' });+ expect(updated).toBeNull();+ expect(project).toBe(base);+ });+ it('returns { updated: null } when the project has no plan', () => {+ const { updated } = applyPlanStepUpdate({ id: 'cd-1', plan: null }, 'a', { status: 'done' });+ expect(updated).toBeNull();+ });+});diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.jsindex fa19dbb300..edeb0b97f6 100644--- a/server/services/creativeDirector/recovery.js+++ b/server/services/creativeDirector/recovery.js@@ -25,7 +25,7 @@* fresh evaluate task, runs the stitch, etc.*/-import { listProjects, updateScene, updateRun, updateProject } from './local.js';+import { listProjects, updateScene, updatePlanStep, updateRun, updateProject } from './local.js';import { listJobs, cancelJob } from '../mediaJobQueue/index.js';import { updateTask } from '../cos.js';@@ -75,9 +75,25 @@ export async function recoverInFlightProjects() {}const { advanceAfterSceneSettled } = await import('./completionHook.js');+ const { advanceAfterPlanStepSettled } = await import('./planAdvance.js');let resumed = 0;const completedAt = new Date().toISOString();for (const project of needsCleanup) {+ // CDO Phase 2 (#2184): a directive-driven project's plan steps stuck in+ // `running` lost their in-memory dispatch/job listener when the process+ // died — reset them to `pending` so the advance loop re-dispatches. (Their+ // stale `plan-step` run rows are reaped by the staleRuns pass below, same as+ // treatment/evaluate runs.)+ const planSteps = Array.isArray(project.plan?.steps) ? project.plan.steps : [];+ const stuckPlanSteps = planSteps.filter((s) => s.status === 'running');+ for (const step of stuckPlanSteps) {+ await updatePlanStep(project.id, step.stepId, { status: 'pending' })+ .catch((e) => console.log(`⚠️ CD recovery: reset plan step ${step.stepId} of ${project.id} failed: ${e.message}`));+ }+ if (stuckPlanSteps.length) {+ console.log(`🔄 CD recovery: ${project.id} reset ${stuckPlanSteps.length} stuck plan step(s) to pending`);+ }+const scenes = project.treatment?.scenes || [];const stuck = scenes.filter((s) => STUCK_SCENE_STATUSES.has(s.status));for (const scene of stuck) {@@ -159,8 +175,13 @@ export async function recoverInFlightProjects() {// while we're iterating projects here. queuedAt > recoveryStartedAt// means it's a brand-new user-initiated job, not a stale snapshot// entry, and canceling it would silently kill the user's action.+ // Match BOTH owner conventions: the scene loop tags renders `cd:<id>:<sceneId>`;+ // a Phase-2 plan render step tags media jobs `creative-director:<id>` (the+ // registry's resolveOwner). Both must be canceled so the reset step's fresh+ // dispatch doesn't race a doomed sibling for the same output.const orphaned = listJobs()- .filter((j) => typeof j.owner === 'string' && j.owner.startsWith(`cd:${project.id}:`))+ .filter((j) => typeof j.owner === 'string'+ && (j.owner.startsWith(`cd:${project.id}:`) || j.owner === `creative-director:${project.id}`)).filter((j) => j.status === 'queued' || j.status === 'running').filter((j) => {const qa = new Date(j.queuedAt || 0).getTime();@@ -177,6 +198,15 @@ export async function recoverInFlightProjects() {// `paused` projects skip this — the cleanup above is enough to make a// future Resume click work.if (RECOVERABLE_STATUSES.has(project.status)) {+ // CDO Phase 2 (#2184): a directive-driven project resumes through the+ // generalized plan advance loop (deriveNextPlanAction re-derives the next+ // step from the reset plan). Legacy video projects stay on the scene loop.+ if (project.directive) {+ advanceAfterPlanStepSettled(project.id)+ .catch((e) => console.log(`⚠️ CD recovery: plan advance for ${project.id} failed: ${e.message}`));+ resumed += 1;+ continue;+ }// Special case: a project that was mid-stitch when the server died// still has status='stitching'. advanceAfterSceneSettled exits// early when it sees that status (its stitch dedup guard), so it