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-2186]): CD studio UI — directive composer, plan board, blocked-step triage, dry-run preview (CDO Phase 4)
Adam Eivy7b8688c61169
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 03d3420647..6244788a1e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -161,6 +161,8 @@## Creative Director+- **[issue-2186] Studio UI — directive composer, plan board, blocked-step triage, dry-run preview (CDO Phase 4).** The user-facing half of the orchestrator, on the Phase 2 plan loop (#2184) + Phase 3 autopilot bridge (#2185). The CD detail page grows a deep-linkable **Plan** tab (`/media/creative-director/:id/plan`, `useValidTab` — a stale deep link degrades to Overview) that renders a directive project's `plan.steps[]` as a **step board**: per-step status + cost-class badges (hydrated from a new `GET /creative-director/tools` catalog — every registered tool's `costClass`/`longRunning`/`destructive`), run timing pulled from the project's `plan-step` runs, dependency edges, per-step result deep-links into the owning surface (created series → `/pipeline/series/:id`, issue → its page, universe/work/minted CD sub-project → theirs), and a progress/cost summary header. Live via the detail page's existing 5s poll — mutations update local state directly, no full refetch. **Blocked-step triage:** when the plan pauses, the pause reason renders prominently with actions — **Resume** (retry the blocked step via `POST /:id/plan/step/:stepId {action:'retry'}`), **Skip** (mark it `skipped`, unblocking dependents), and **Request re-plan** (`POST /:id/replan` drops the plan and re-runs the planner) — all toast-based, no `window.confirm`. **Approval affordances:** a destructive or over-budget step (flagged against the catalog's budget status) renders an explicit **Approve** button instead of auto-running. **Directive composer:** a shared `DirectiveComposer` (goal text, deliverable checklist, target universe/series pickers, budget cap) hosted in the shared `Drawer` — on the CD list page a deep-linkable "New directive" drawer (`?new=directive`) creates a studio project, and on the Plan tab an "Add/Edit directive" drawer converts an existing project (`POST /:id/directive` clears the plan and re-plans). **Dry-run preview:** the catalog's `creative` autonomy `mode` drives a banner — in `dry-run` the board shows each step's proposed cost class without executing (mirrors autopilot's dry-run frames); `off` shows a review-only notice. The CD nav-manifest entry gains `producer`/`orchestrator` aliases + `directive`/`studio`/`plan board` keywords so ⌘K + voice reach the tab. Pure plan-board presentation logic (annotate/cost-summary/status-summary/approval/deep-link) lives in `client/src/lib/creativeDirectorPlan.js`, unit-tested alongside the `PlanTab` state-transition + blocked-triage component tests and the new route tests. (`client/src/components/creative-director/{PlanTab,DirectiveComposer}.jsx`, `client/src/pages/{CreativeDirector,CreativeDirectorDetail}.jsx`, `client/src/lib/creativeDirectorPlan.js`, `server/routes/creativeDirector.js`, `server/services/creative/toolRegistry.js`, `server/lib/{creativeDirectorValidation,navManifest}.js`)+- **[issue-2185] CD ⇄ Series Autopilot bridge, both directions (CDO Phase 3).** Wires the two conductors together so they share resources instead of living in parallel silos, building on the Phase 2 plan loop (#2184) + Phase 1 registry (#2183). **CD → Autopilot:** a directive-driven plan can now run the Series Autopilot as one long-running plan step (`pipeline_startSeriesAutopilot`). Series Autopilot returns a run handle (a `runId`, not a media `jobId`), so a new lightweight **in-process event bus** (`autopilotEvents` beside the SSE broadcast in `seriesAutopilot.js` — every frame mirrored onto the bus keyed by seriesId, SSE behavior unchanged) lets the plan-advance loop observe the run without opening an HTTP/SSE client: the plan step stays `running` until the autopilot reaches a terminal frame, then settles — `complete` → step done + advance; **`paused` → step `blocked` and the plan pauses for human review (never auto-retried)**; `error` → failed → bounded re-plan. This replaces the Phase 2 caveat where a long-running autopilot step completed on start. An already-active run is attached to (via the autopilot's own `alreadyRunning` dedup) rather than double-started, and the already-terminal attach race is closed by reading the persisted `series.autopilot` marker. **Autopilot/pipeline → CD:** a new `cd_produceVideoFromIssue` registry tool (+ `produceVideoFromIssue` service) mints a FRESH Creative Director teaser/trailer project seeded from a pipeline issue — the #842 bridge pattern (generate a treatment from the issue's prose via the shared `writers-room-cd-bridge` stage + shaper, `createProject` + `setTreatment` + `sourceIssueId` link, auto-cast the series canon into CD casting with `ref_kind:'creative-director'` refs, then explicitly start it) — never mutating an existing project, rolling back the orphaned project + collection on a post-create failure. The same deliverable is also available as an **opt-in, default-off** post-`visualDraft` autopilot step (`produceTeaser`, config-gated + budget-charged like every other autopilot step; a teaser failure is advisory — it files a gap but never strands the finished story). No user-facing surface yet — the plan board + directive composer arrive in Phase 4. (`server/services/creativeDirector/{bridgeFromIssue,planAdvance}.js`, `server/services/creative/tools/cd.js`, `server/services/creative/toolRegistry.js`, `server/services/pipeline/seriesAutopilot.js`, `server/services/writersRoom/liveDirector.js`)- **[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`)diff --git a/client/src/components/creative-director/DirectiveComposer.jsx b/client/src/components/creative-director/DirectiveComposer.jsxnew file mode 100644index 0000000000..7a0665eca2--- /dev/null+++ b/client/src/components/creative-director/DirectiveComposer.jsx@@ -0,0 +1,152 @@+import { DELIVERABLE_OPTIONS } from '../../lib/creativeDirectorPlan.js';++/**+ * Directive composer fields (CDO Phase 4, #2186) — the studio "brief" a directive+ * project turns into a plan: goal text, a deliverable checklist, target+ * universe/series pickers, and a budget cap. Controlled + presentational: all+ * state is hoisted into the host (the list-page create form or the detail-page+ * "convert to directive" Drawer) so the Drawer's per-tab remount can't reset it+ * (the CLAUDE.md Drawer state-hoisting rule), and the host owns the submit+ * affordances (Create / Preview plan / Cancel).+ *+ * `directive` shape mirrors the server schema:+ * { goal, deliverables: string[], constraints: { universeId, seriesId, budgetCap } }+ *+ * @param {{+ * directive: object,+ * onChange: (next: object) => void,+ * universes?: Array<{id,name}>,+ * series?: Array<{id,name,title?}>,+ * idPrefix?: string,+ * disabled?: boolean,+ * }} props+ */+export default function DirectiveComposer({+ directive,+ onChange,+ universes = [],+ series = [],+ idPrefix = 'directive',+ disabled = false,+}) {+ const goal = directive?.goal || '';+ const deliverables = Array.isArray(directive?.deliverables) ? directive.deliverables : [];+ const constraints = directive?.constraints || {};++ const patch = (next) => onChange({+ ...directive,+ ...next,+ constraints: { ...constraints, ...(next.constraints || {}) },+ });++ const toggleDeliverable = (id) => {+ const set = new Set(deliverables);+ if (set.has(id)) set.delete(id); else set.add(id);+ patch({ deliverables: Array.from(set) });+ };++ return (+ <div className="space-y-4">+ <div>+ <label htmlFor={`${idPrefix}-goal`} className="block text-sm text-port-text-muted mb-1">+ Goal+ </label>+ <textarea+ id={`${idPrefix}-goal`}+ value={goal}+ disabled={disabled}+ onChange={(e) => patch({ goal: e.target.value })}+ placeholder="Produce a 6-issue noir comic in universe X, with covers, a polished manuscript, and a teaser trailer…"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm h-28 font-mono disabled:opacity-50"+ maxLength={5000}+ />+ </div>++ <fieldset className="border-0 p-0 m-0">+ <legend className="text-sm text-port-text-muted mb-1.5">Deliverables</legend>+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {DELIVERABLE_OPTIONS.map((opt) => {+ const checked = deliverables.includes(opt.id);+ return (+ <label+ key={opt.id}+ htmlFor={`${idPrefix}-deliverable-${opt.id}`}+ className={`flex items-center gap-2 text-sm px-2 py-1.5 rounded border cursor-pointer ${+ checked ? 'border-port-accent bg-port-accent/10 text-port-accent' : 'border-port-border text-port-text-muted'+ } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}+ >+ <input+ id={`${idPrefix}-deliverable-${opt.id}`}+ type="checkbox"+ className="accent-port-accent"+ checked={checked}+ disabled={disabled}+ onChange={() => toggleDeliverable(opt.id)}+ />+ {opt.label}+ </label>+ );+ })}+ </div>+ </fieldset>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor={`${idPrefix}-universe`} className="block text-sm text-port-text-muted mb-1">+ Target universe+ </label>+ <select+ id={`${idPrefix}-universe`}+ value={constraints.universeId || ''}+ disabled={disabled}+ onChange={(e) => patch({ constraints: { universeId: e.target.value || null } })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="">— none —</option>+ {universes.map((u) => (+ <option key={u.id} value={u.id}>{u.name || u.id}</option>+ ))}+ </select>+ </div>++ <div>+ <label htmlFor={`${idPrefix}-series`} className="block text-sm text-port-text-muted mb-1">+ Target series+ </label>+ <select+ id={`${idPrefix}-series`}+ value={constraints.seriesId || ''}+ disabled={disabled}+ onChange={(e) => patch({ constraints: { seriesId: e.target.value || null } })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="">— none —</option>+ {series.map((s) => (+ <option key={s.id} value={s.id}>{s.title || s.name || s.id}</option>+ ))}+ </select>+ </div>+ </div>++ <div>+ <label htmlFor={`${idPrefix}-budget`} className="block text-sm text-port-text-muted mb-1">+ Budget cap (autonomous actions/day — blank = use the shared default)+ </label>+ <input+ id={`${idPrefix}-budget`}+ type="number"+ min={0}+ max={100000}+ value={constraints.budgetCap ?? ''}+ disabled={disabled}+ onChange={(e) => {+ const v = e.target.value;+ patch({ constraints: { budgetCap: v === '' ? null : Math.max(0, Math.floor(Number(v)) || 0) } });+ }}+ placeholder="e.g. 50"+ className="w-full sm:w-48 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"+ />+ </div>+ </div>+ );+}diff --git a/client/src/components/creative-director/PlanTab.jsx b/client/src/components/creative-director/PlanTab.jsxnew file mode 100644index 0000000000..e4489b787c--- /dev/null+++ b/client/src/components/creative-director/PlanTab.jsx@@ -0,0 +1,363 @@+import { useEffect, useMemo, useState, useCallback } from 'react';+import { Link, useSearchParams } from 'react-router-dom';+import { SkipForward, RotateCw, CheckCircle2, RefreshCw, AlertTriangle, Sparkles, ExternalLink } from 'lucide-react';+import toast from '../ui/Toast';+import Drawer from '../Drawer';+import DirectiveComposer from './DirectiveComposer.jsx';+import {+ getCreativeToolCatalog,+ setCreativeDirectorDirective,+ replanCreativeDirectorProject,+ updateCreativeDirectorPlanStep,+} from '../../services/apiCreativeDirector.js';+import { listUniverses } from '../../services/apiUniverseBuilder.js';+import { listPipelineSeries } from '../../services/apiPipeline.js';+import {+ annotatePlanSteps,+ planCostSummary,+ planStatusSummary,+ stepResultLink,+ PLAN_STEP_STATUS_META,+ COST_CLASS_META,+ TONE_BADGE,+} from '../../lib/creativeDirectorPlan.js';+import { formatDateTime, formatDurationMs } from '../../utils/formatters';++const Badge = ({ tone, children, title }) => (+ <span title={title} className={`text-xs px-2 py-0.5 rounded ${TONE_BADGE[tone] || TONE_BADGE.muted}`}>{children}</span>+);++const EMPTY_DIRECTIVE = { goal: '', deliverables: [], constraints: { universeId: null, seriesId: null, budgetCap: null } };++export default function PlanTab({ project, onProjectUpdate }) {+ const [catalog, setCatalog] = useState({ tools: [], mode: 'execute', budget: { withinBudget: true } });+ const [busyStep, setBusyStep] = useState(null); // `${stepId}:${action}` while a triage call is in flight+ const [replanning, setReplanning] = useState(false);+ const [searchParams, setSearchParams] = useSearchParams();+ const composerOpen = searchParams.get('directive') === 'edit';++ // Composer state hoisted above the Drawer body (Drawer state-hoisting rule).+ const [draft, setDraft] = useState(EMPTY_DIRECTIVE);+ const [savingDirective, setSavingDirective] = useState(false);+ const [universes, setUniverses] = useState([]);+ const [series, setSeries] = useState([]);++ // Tool catalog drives cost-class badges + the dry-run banner + approval gating.+ // Fetched once (silent — the board degrades gracefully to no cost badges on+ // failure rather than toasting on a passive tab open).+ useEffect(() => {+ let alive = true;+ getCreativeToolCatalog({ silent: true })+ .then((data) => { if (alive && data) setCatalog(data); })+ .catch(() => {});+ return () => { alive = false; };+ }, []);++ const toolMap = useMemo(() => {+ const m = new Map();+ for (const t of (catalog.tools || [])) m.set(t.id, t);+ return m;+ }, [catalog.tools]);++ const withinBudget = catalog.budget?.withinBudget !== false;+ const steps = useMemo(+ () => annotatePlanSteps(project.plan?.steps, project.runs, toolMap, { withinBudget }),+ [project.plan, project.runs, toolMap, withinBudget],+ );+ const costCounts = useMemo(() => planCostSummary(steps), [steps]);+ const statusCounts = useMemo(() => planStatusSummary(steps), [steps]);++ const openComposer = useCallback(() => {+ setDraft(project.directive+ ? { ...EMPTY_DIRECTIVE, ...project.directive, constraints: { ...EMPTY_DIRECTIVE.constraints, ...(project.directive.constraints || {}) } }+ : EMPTY_DIRECTIVE);+ setSearchParams((prev) => { const n = new URLSearchParams(prev); n.set('directive', 'edit'); return n; }, { replace: true });+ // Lazy-load the pickers on open.+ if (!universes.length) listUniverses({ silent: true }).then((u) => setUniverses(Array.isArray(u) ? u : (u?.items || []))).catch(() => {});+ if (!series.length) listPipelineSeries({ silent: true }).then((s) => setSeries(Array.isArray(s) ? s : (s?.items || []))).catch(() => {});+ }, [project.directive, setSearchParams, universes.length, series.length]);++ const closeComposer = useCallback(() => {+ setSearchParams((prev) => { const n = new URLSearchParams(prev); n.delete('directive'); return n; }, { replace: true });+ }, [setSearchParams]);++ const submitDirective = async () => {+ if (!draft.goal.trim()) { toast.error('Goal is required'); return; }+ setSavingDirective(true);+ const updated = await setCreativeDirectorDirective(project.id, {+ goal: draft.goal.trim(),+ deliverables: draft.deliverables || [],+ constraints: draft.constraints || {},+ }).catch((e) => { toast.error(e.message || 'Failed to save directive'); return null; });+ setSavingDirective(false);+ if (!updated) return;+ onProjectUpdate?.(updated);+ toast.success(project.directive ? 'Directive updated — re-planning' : 'Directive set — planning');+ closeComposer();+ };++ const runStepAction = async (stepId, action) => {+ const key = `${stepId}:${action}`;+ setBusyStep(key);+ const updated = await updateCreativeDirectorPlanStep(project.id, stepId, action, { silent: true })+ .catch((e) => { toast.error(e.message || `Failed to ${action} step`); return null; });+ setBusyStep(null);+ if (!updated) return;+ onProjectUpdate?.(updated);+ toast.success(action === 'skip' ? 'Step skipped' : 'Step re-queued');+ };++ const handleReplan = async () => {+ setReplanning(true);+ const updated = await replanCreativeDirectorProject(project.id)+ .catch((e) => { toast.error(e.message || 'Failed to re-plan'); return null; });+ setReplanning(false);+ if (!updated) return;+ onProjectUpdate?.(updated);+ toast.success('Re-planning — the planner will propose a fresh step list');+ };++ const directiveDrawer = (+ <Drawer+ open={composerOpen}+ onClose={closeComposer}+ title={project.directive ? 'Edit directive' : 'Add a directive'}+ size="lg"+ closeOnEsc={false}+ closeOnBackdrop={false}+ >+ <p className="text-xs text-port-text-muted mb-3">+ A directive turns this project into a studio production: the planner agent derives a plan of creative-tool+ steps (series, covers, teaser, …) and the generalized advance loop executes them one at a time through the+ governed dispatch gate.+ </p>+ <DirectiveComposer+ directive={draft}+ onChange={setDraft}+ universes={universes}+ series={series}+ idPrefix="cd-directive"+ disabled={savingDirective}+ />+ <div className="flex gap-2 justify-end mt-5 pt-4 border-t border-port-border">+ <button onClick={closeComposer} className="px-3 py-1.5 rounded text-sm bg-port-bg border border-port-border">Cancel</button>+ <button+ onClick={submitDirective}+ disabled={savingDirective || !draft.goal.trim()}+ className="px-3 py-1.5 rounded text-sm bg-port-accent text-white disabled:opacity-50"+ >+ {savingDirective ? 'Saving…' : (project.directive ? 'Save & re-plan' : 'Set directive & plan')}+ </button>+ </div>+ </Drawer>+ );++ // ---- Legacy video project (no directive) — offer to convert. -------------+ if (!project.directive) {+ return (+ <div className="max-w-3xl">+ <div className="bg-port-card border border-port-border rounded p-5 text-sm text-port-text-muted">+ <div className="flex items-center gap-2 text-port-text mb-2">+ <Sparkles className="w-4 h-4 text-port-accent" />+ <span className="font-medium">No production directive</span>+ </div>+ <p className="mb-3">+ This is a legacy video project — it runs the built-in treatment / scene flow. Add a directive to+ promote it into a studio production the Creative Director plans and executes across the whole creative+ suite.+ </p>+ <button onClick={openComposer} className="px-3 py-1.5 rounded text-sm bg-port-accent text-white">+ Add a directive+ </button>+ </div>+ {directiveDrawer}+ </div>+ );+ }++ const blocked = project.status === 'paused' && (steps.some((s) => s.status === 'blocked') || project.failureReason);+ const planning = project.status === 'planning';+ const hasPlan = steps.length > 0;++ return (+ <div className="max-w-4xl space-y-4">+ {/* Directive summary */}+ <div className="bg-port-card border border-port-border rounded p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="text-xs uppercase tracking-wide text-port-text-muted mb-1">Directive</div>+ <div className="text-sm text-port-text whitespace-pre-wrap break-words">{project.directive.goal}</div>+ {Array.isArray(project.directive.deliverables) && project.directive.deliverables.length > 0 && (+ <div className="flex flex-wrap gap-1.5 mt-2">+ {project.directive.deliverables.map((d) => (+ <span key={d} className="text-xs px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-port-text-muted">{d}</span>+ ))}+ </div>+ )}+ {project.directive.constraints?.budgetCap != null && (+ <div className="text-xs text-port-text-muted mt-2">Budget cap: {project.directive.constraints.budgetCap} actions/day</div>+ )}+ </div>+ <div className="flex gap-1 shrink-0">+ <button onClick={openComposer} className="px-2 py-1 rounded text-xs bg-port-bg border border-port-border">Edit</button>+ <button onClick={handleReplan} disabled={replanning} className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-bg border border-port-border disabled:opacity-50">+ <RefreshCw className="w-3 h-3" /> {replanning ? 'Re-planning…' : 'Re-plan'}+ </button>+ </div>+ </div>+ </div>++ {/* Dry-run banner */}+ {catalog.mode === 'dry-run' && (+ <div className="bg-port-accent/10 border border-port-accent/40 rounded p-3 text-xs text-port-accent">+ Creative autonomy is in <span className="font-semibold">dry-run</span> mode — plan steps are previewed+ (cost classes shown below) but not executed. Switch to <span className="font-mono">execute</span> in+ Settings to run the plan.+ </div>+ )}+ {catalog.mode === 'off' && (+ <div className="bg-port-warning/10 border border-port-warning/40 rounded p-3 text-xs text-port-warning">+ Creative autonomy is <span className="font-semibold">off</span> — the plan will not execute until you+ enable it in Settings. Steps below are shown for review only.+ </div>+ )}++ {/* Blocked-step triage banner */}+ {blocked && (+ <div className="bg-port-error/10 border border-port-error/40 rounded p-4">+ <div className="flex items-center gap-2 text-port-error font-medium mb-1">+ <AlertTriangle className="w-4 h-4" /> Plan paused+ </div>+ {project.failureReason && (+ <p className="text-sm text-port-text-muted mb-3 break-words">{project.failureReason}</p>+ )}+ <div className="flex flex-wrap gap-2">+ {steps.filter((s) => s.status === 'blocked' || s.status === 'failed').map((s) => (+ <button+ key={s.stepId}+ onClick={() => runStepAction(s.stepId, 'retry')}+ disabled={busyStep === `${s.stepId}:retry`}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent/30 text-port-accent disabled:opacity-50"+ >+ <RotateCw className="w-3 h-3" /> Resume “{s.stepId}”+ </button>+ ))}+ <button onClick={handleReplan} disabled={replanning} className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-bg border border-port-border disabled:opacity-50">+ <RefreshCw className="w-3 h-3" /> Request re-plan+ </button>+ </div>+ </div>+ )}++ {/* Plan progress summary */}+ {hasPlan && (+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span className="text-port-text-muted">{steps.length} step{steps.length === 1 ? '' : 's'}:</span>+ {Object.entries(statusCounts).filter(([, n]) => n > 0).map(([status, n]) => (+ <Badge key={status} tone={PLAN_STEP_STATUS_META[status]?.tone}>{n} {PLAN_STEP_STATUS_META[status]?.label || status}</Badge>+ ))}+ <span className="text-port-text-muted ml-2">cost:</span>+ {Object.entries(costCounts).filter(([, n]) => n > 0).map(([cls, n]) => (+ <Badge key={cls} tone={COST_CLASS_META[cls]?.tone}>{n} {COST_CLASS_META[cls]?.label || cls}</Badge>+ ))}+ </div>+ )}++ {/* Planning / empty state */}+ {!hasPlan && (+ <div className="bg-port-card border border-port-border rounded p-5 text-sm text-port-text-muted">+ {planning+ ? 'The planner is deriving a step list from the directive… this tab updates as the plan lands.'+ : 'No plan yet. Start the project (or re-plan) to have the planner derive a step list from the directive.'}+ </div>+ )}++ {/* Step board */}+ {hasPlan && (+ <div className="space-y-2">+ {steps.map((s) => {+ const statusMeta = PLAN_STEP_STATUS_META[s.status] || PLAN_STEP_STATUS_META.pending;+ const link = stepResultLink(s);+ const durationMs = s.startedAt && s.completedAt ? new Date(s.completedAt) - new Date(s.startedAt) : null;+ const canSkip = s.status === 'pending' || s.status === 'blocked' || s.status === 'failed';+ const canRetry = s.status === 'blocked' || s.status === 'failed';+ const needsApproval = s.requiresApproval && (s.status === 'pending' || s.status === 'blocked');+ return (+ <div key={s.stepId} className="bg-port-card border border-port-border rounded p-3">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-medium text-sm truncate">{s.stepId}</span>+ <Badge tone={statusMeta.tone}>{statusMeta.label}</Badge>+ {s.costClass && <Badge tone={COST_CLASS_META[s.costClass]?.tone} title="Cost class">{COST_CLASS_META[s.costClass]?.label}</Badge>}+ {s.longRunning && <Badge tone="muted" title="Long-running (completes via events)">long-running</Badge>}+ {s.destructive && <Badge tone="error" title="Destructive — requires approval">destructive</Badge>}+ {s.unknownTool && <Badge tone="warning" title="Tool not in the current registry">unknown tool</Badge>}+ </div>+ <div className="text-xs text-port-text-muted font-mono mt-1 truncate">{s.toolName}</div>+ {Array.isArray(s.dependsOn) && s.dependsOn.length > 0 && (+ <div className="text-xs text-port-text-muted mt-1">depends on: {s.dependsOn.join(', ')}</div>+ )}+ <div className="text-xs text-port-text-muted mt-1">+ {s.startedAt && formatDateTime(s.startedAt)}+ {s.completedAt && ` → ${formatDateTime(s.completedAt)}`}+ {durationMs != null && ` (${formatDurationMs(durationMs)})`}+ {s.retryCount ? ` · retries: ${s.retryCount}` : ''}+ </div>+ {s.result?.reason && (+ <div className="text-xs text-port-warning mt-1 break-words">{s.result.reason}</div>+ )}+ {s.result?.error && (+ <div className="text-xs text-port-error mt-1 break-words">{s.result.error}</div>+ )}+ {link && (+ <Link to={link.to} className="inline-flex items-center gap-1 text-xs text-port-accent mt-1">+ <ExternalLink className="w-3 h-3" /> {link.label}+ </Link>+ )}+ {needsApproval && (+ <div className="text-xs text-port-warning mt-1">+ {s.destructive ? 'Destructive step — needs approval before it runs.' : 'Over the action budget — raise the cap, then approve.'}+ </div>+ )}+ </div>+ <div className="flex flex-col gap-1 shrink-0">+ {needsApproval && (+ <button+ onClick={() => runStepAction(s.stepId, 'retry')}+ disabled={busyStep === `${s.stepId}:retry`}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent/30 text-port-accent disabled:opacity-50"+ >+ <CheckCircle2 className="w-3 h-3" /> Approve+ </button>+ )}+ {canRetry && !needsApproval && (+ <button+ onClick={() => runStepAction(s.stepId, 'retry')}+ disabled={busyStep === `${s.stepId}:retry`}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-bg border border-port-border disabled:opacity-50"+ >+ <RotateCw className="w-3 h-3" /> Retry+ </button>+ )}+ {canSkip && (+ <button+ onClick={() => runStepAction(s.stepId, 'skip')}+ disabled={busyStep === `${s.stepId}:skip`}+ className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-bg border border-port-border disabled:opacity-50"+ >+ <SkipForward className="w-3 h-3" /> Skip+ </button>+ )}+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}++ {directiveDrawer}+ </div>+ );+}diff --git a/client/src/components/creative-director/PlanTab.test.jsx b/client/src/components/creative-director/PlanTab.test.jsxnew file mode 100644index 0000000000..8d8cf7ac61--- /dev/null+++ b/client/src/components/creative-director/PlanTab.test.jsx@@ -0,0 +1,187 @@+/**+ * Plan-board state transitions + blocked-step triage (CDO Phase 4, #2186).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++vi.mock('../../services/apiCreativeDirector.js', () => ({+ getCreativeToolCatalog: vi.fn(),+ setCreativeDirectorDirective: vi.fn(),+ replanCreativeDirectorProject: vi.fn(),+ updateCreativeDirectorPlanStep: vi.fn(),+}));+vi.mock('../../services/apiUniverseBuilder.js', () => ({ listUniverses: vi.fn(async () => []) }));+vi.mock('../../services/apiPipeline.js', () => ({ listPipelineSeries: vi.fn(async () => []) }));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));++import PlanTab from './PlanTab.jsx';+import {+ getCreativeToolCatalog,+ replanCreativeDirectorProject,+ updateCreativeDirectorPlanStep,+} from '../../services/apiCreativeDirector.js';+import toast from '../ui/Toast';++const CATALOG = {+ tools: [+ { id: 'pipeline_createSeries', costClass: 'free', longRunning: false, destructive: false },+ { id: 'story_generateStep', costClass: 'llm', longRunning: false, destructive: false },+ { id: 'media_enqueueImage', costClass: 'render', longRunning: true, destructive: false },+ { id: 'universe_delete', costClass: 'free', longRunning: false, destructive: true },+ ],+ mode: 'execute',+ budget: { withinBudget: true },+};++const directiveProject = (overrides = {}) => ({+ id: 'cd-1',+ name: 'Noir',+ status: 'rendering',+ directive: { goal: 'Produce a noir series', deliverables: ['story', 'covers'], constraints: { budgetCap: 50 } },+ plan: {+ steps: [+ { stepId: 'series', toolName: 'pipeline_createSeries', status: 'done', dependsOn: [], result: { seriesId: 's9' } },+ { stepId: 'draft', toolName: 'story_generateStep', status: 'running', dependsOn: ['series'] },+ { stepId: 'cover', toolName: 'media_enqueueImage', status: 'pending', dependsOn: ['draft'] },+ ],+ },+ runs: [{ kind: 'plan-step', stepId: 'series', startedAt: '2026-07-01T00:00:00Z', completedAt: '2026-07-01T00:01:00Z' }],+ ...overrides,+});++const renderTab = (project, onProjectUpdate = () => {}) =>+ render(<MemoryRouter><PlanTab project={project} onProjectUpdate={onProjectUpdate} /></MemoryRouter>);++beforeEach(() => {+ vi.clearAllMocks();+ getCreativeToolCatalog.mockResolvedValue(CATALOG);+});++describe('legacy project (no directive)', () => {+ it('offers to add a directive', () => {+ renderTab({ id: 'cd-1', name: 'X', status: 'draft', directive: null, plan: null, runs: [] });+ expect(screen.getByText(/No production directive/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Add a directive/i })).toBeTruthy();+ });+});++describe('plan board', () => {+ it('renders each step with its status + cost class badge', async () => {+ renderTab(directiveProject());+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ expect(screen.getByText('series')).toBeTruthy();+ expect(screen.getByText('draft')).toBeTruthy();+ expect(screen.getByText('cover')).toBeTruthy();+ // done + running + pending statuses present+ expect(screen.getByText('Done')).toBeTruthy();+ expect(screen.getByText('Running')).toBeTruthy();+ // cost badges (Render for the long-running image step)+ await waitFor(() => expect(screen.getAllByText('Render').length).toBeGreaterThan(0));+ });++ it('links a completed series step into the pipeline series route', async () => {+ renderTab(directiveProject());+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ const link = await screen.findByRole('link', { name: /Open series/i });+ expect(link.getAttribute('href')).toBe('/pipeline/series/s9');+ });++ it('shows the directive goal + deliverables + budget cap', () => {+ renderTab(directiveProject());+ expect(screen.getByText('Produce a noir series')).toBeTruthy();+ expect(screen.getByText('story')).toBeTruthy();+ expect(screen.getByText('covers')).toBeTruthy();+ expect(screen.getByText(/Budget cap: 50/)).toBeTruthy();+ });++ it('renders a dry-run banner when creative autonomy is dry-run', async () => {+ getCreativeToolCatalog.mockResolvedValue({ ...CATALOG, mode: 'dry-run' });+ renderTab(directiveProject());+ await waitFor(() => expect(screen.getByText(/previewed/i)).toBeTruthy());+ });+});++describe('blocked-step triage', () => {+ const blockedProject = () => directiveProject({+ status: 'paused',+ failureReason: 'Step "draft" is blocked: awaiting human review',+ plan: {+ steps: [+ { stepId: 'series', toolName: 'pipeline_createSeries', status: 'done', dependsOn: [], result: { seriesId: 's9' } },+ { stepId: 'draft', toolName: 'story_generateStep', status: 'blocked', dependsOn: ['series'], result: { reason: 'awaiting human review' } },+ ],+ },+ });++ it('surfaces the pause reason and a resume affordance for the blocked step', async () => {+ renderTab(blockedProject());+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ expect(screen.getByText(/Plan paused/i)).toBeTruthy();+ // Rendered both in the pause banner (failureReason) and the step's result reason.+ expect(screen.getAllByText(/awaiting human review/i).length).toBeGreaterThan(0);+ expect(screen.getByRole('button', { name: /Resume .*draft/i })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Request re-plan/i })).toBeTruthy();+ });++ it('retries a blocked step and pushes the returned project up', async () => {+ const onProjectUpdate = vi.fn();+ updateCreativeDirectorPlanStep.mockResolvedValue({ id: 'cd-1', status: 'rendering', plan: { steps: [] } });+ renderTab(blockedProject(), onProjectUpdate);+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /Resume .*draft/i }));+ await waitFor(() => expect(updateCreativeDirectorPlanStep).toHaveBeenCalledWith('cd-1', 'draft', 'retry', { silent: true }));+ await waitFor(() => expect(onProjectUpdate).toHaveBeenCalledWith({ id: 'cd-1', status: 'rendering', plan: { steps: [] } }));+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/re-queued/i));+ });++ it('requests a re-plan', async () => {+ const onProjectUpdate = vi.fn();+ replanCreativeDirectorProject.mockResolvedValue({ id: 'cd-1', status: 'planning', plan: null });+ renderTab(blockedProject(), onProjectUpdate);+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /Request re-plan/i }));+ await waitFor(() => expect(replanCreativeDirectorProject).toHaveBeenCalledWith('cd-1'));+ await waitFor(() => expect(onProjectUpdate).toHaveBeenCalledWith({ id: 'cd-1', status: 'planning', plan: null }));+ });++ it('skips a pending step', async () => {+ updateCreativeDirectorPlanStep.mockResolvedValue({ id: 'cd-1', status: 'rendering', plan: { steps: [] } });+ renderTab(directiveProject());+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ // The pending 'cover' step has a Skip button.+ const skipButtons = screen.getAllByRole('button', { name: /^Skip$/i });+ fireEvent.click(skipButtons[skipButtons.length - 1]);+ await waitFor(() => expect(updateCreativeDirectorPlanStep).toHaveBeenCalledWith('cd-1', 'cover', 'skip', { silent: true }));+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/skipped/i));+ });+});++describe('approval affordances', () => {+ it('renders an Approve button for a budgeted step when over budget', async () => {+ getCreativeToolCatalog.mockResolvedValue({ ...CATALOG, budget: { withinBudget: false } });+ renderTab(directiveProject({+ plan: {+ steps: [+ { stepId: 'draft', toolName: 'story_generateStep', status: 'pending', dependsOn: [] },+ ],+ },+ }));+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ expect(await screen.findByRole('button', { name: /Approve/i })).toBeTruthy();+ expect(screen.getByText(/Over the action budget/i)).toBeTruthy();+ });++ it('renders an Approve button for a destructive step', async () => {+ renderTab(directiveProject({+ plan: {+ steps: [+ { stepId: 'wipe', toolName: 'universe_delete', status: 'pending', dependsOn: [] },+ ],+ },+ }));+ await waitFor(() => expect(getCreativeToolCatalog).toHaveBeenCalled());+ expect(await screen.findByRole('button', { name: /Approve/i })).toBeTruthy();+ expect(screen.getByText(/Destructive step/i)).toBeTruthy();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a8796cfab4..b846fd28fe 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -38,6 +38,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. || `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. |+| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). || `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |diff --git a/client/src/lib/creativeDirectorPlan.js b/client/src/lib/creativeDirectorPlan.jsnew file mode 100644index 0000000000..d4d15ab728--- /dev/null+++ b/client/src/lib/creativeDirectorPlan.js@@ -0,0 +1,159 @@+// Pure helpers for the Creative Director studio Plan board (CDO Phase 4, #2186).+//+// The Plan tab renders a directive project's `plan.steps[]` as a step board with+// live status, cost-class badges (hydrated from the creative-tool catalog), run+// timing, and blocked-step triage. These helpers keep that presentation logic+// pure + unit-tested so the component stays a thin renderer. No React, no I/O.++// The deliverable checklist offered by the directive composer. Free-form on the+// wire (the planner reads the labels as intent); this is the curated menu the UI+// surfaces. `id` is the token stored in `directive.deliverables[]`.+export const DELIVERABLE_OPTIONS = Object.freeze([+ { id: 'story', label: 'Story / series' },+ { id: 'manuscript-polish', label: 'Manuscript polish' },+ { id: 'covers', label: 'Covers' },+ { id: 'video-teaser', label: 'Video teaser' },+ { id: 'concept-art', label: 'Concept art' },+ { id: 'music-bed', label: 'Music bed' },+]);++// Plan-step lifecycle → display metadata. Mirrors server PLAN_STEP_STATUSES.+export const PLAN_STEP_STATUS_META = Object.freeze({+ pending: { label: 'Pending', tone: 'muted' },+ running: { label: 'Running', tone: 'accent' },+ blocked: { label: 'Blocked', tone: 'warning' },+ done: { label: 'Done', tone: 'success' },+ failed: { label: 'Failed', tone: 'error' },+ skipped: { label: 'Skipped', tone: 'muted' },+});++// Cost class → display metadata. Mirrors server COST_CLASSES.+export const COST_CLASS_META = Object.freeze({+ free: { label: 'Free', tone: 'muted' },+ llm: { label: 'LLM', tone: 'accent' },+ render: { label: 'Render', tone: 'warning' },+});++// Cost classes that consume the daily autonomous-action budget (mirror of the+// server's BUDGETED_COST_CLASSES) — a step in one of these is gated when the+// shared budget is exhausted.+const BUDGETED = new Set(['llm', 'render']);++// A tone token → Tailwind badge classes (port design tokens). Central so status+// and cost badges stay visually consistent.+export const TONE_BADGE = Object.freeze({+ muted: 'bg-port-border text-port-text',+ accent: 'bg-port-accent/30 text-port-accent',+ warning: 'bg-port-warning/30 text-port-warning',+ success: 'bg-port-success/30 text-port-success',+ error: 'bg-port-error/30 text-port-error',+});++/**+ * Does a step need explicit human approval before dispatch? True when the tool+ * is destructive (delete/overwrite) or a budgeted (llm/render) tool while the+ * shared action budget is exhausted. Absent metadata (unknown tool) never+ * auto-approves — surface it as "unknown" instead.+ *+ * @param {{costClass?: string, destructive?: boolean}|null} meta+ * @param {{withinBudget?: boolean}} [ctx]+ */+export function stepRequiresApproval(meta, { withinBudget } = {}) {+ if (!meta) return false;+ if (meta.destructive) return true;+ if (BUDGETED.has(meta.costClass) && withinBudget === false) return true;+ return false;+}++// Normalize a `toolMap` accessor over either a Map or a plain object.+function resolveMeta(toolMap, name) {+ if (!toolMap) return null;+ if (typeof toolMap.get === 'function') return toolMap.get(name) || null;+ return toolMap[name] || null;+}++/**+ * Annotate a plan's steps with tool metadata, the latest matching run's timing,+ * and gate flags (cost class, longRunning, destructive, requiresApproval,+ * unknownTool). Pure — returns a fresh array; never mutates inputs.+ *+ * @param {Array<object>} steps plan.steps[]+ * @param {Array<object>} runs project.runs[] (kind:'plan-step' carry timing)+ * @param {Map|object} toolMap toolName → { costClass, longRunning, destructive }+ * @param {{withinBudget?: boolean}} [ctx]+ */+export function annotatePlanSteps(steps, runs, toolMap, { withinBudget } = {}) {+ const list = Array.isArray(steps) ? steps : [];+ const runList = Array.isArray(runs) ? runs : [];+ // Latest plan-step run per stepId — the board shows the current attempt's timing.+ const runByStep = new Map();+ for (const r of runList) {+ if (!r || r.kind !== 'plan-step' || !r.stepId) continue;+ const prev = runByStep.get(r.stepId);+ if (!prev || new Date(r.startedAt || 0) >= new Date(prev.startedAt || 0)) {+ runByStep.set(r.stepId, r);+ }+ }+ return list.map((s) => {+ const meta = resolveMeta(toolMap, s.toolName);+ const run = runByStep.get(s.stepId) || null;+ return {+ ...s,+ status: s.status || 'pending',+ costClass: meta?.costClass || null,+ longRunning: Boolean(meta?.longRunning),+ destructive: Boolean(meta?.destructive),+ unknownTool: !meta,+ requiresApproval: stepRequiresApproval(meta, { withinBudget }),+ startedAt: run?.startedAt || null,+ completedAt: run?.completedAt || null,+ };+ });+}++/** Count annotated steps by cost class (for the plan summary header). */+export function planCostSummary(annotated) {+ const counts = { free: 0, llm: 0, render: 0 };+ for (const s of annotated || []) {+ if (s.costClass && counts[s.costClass] != null) counts[s.costClass] += 1;+ }+ return counts;+}++/** Count annotated steps by lifecycle status (for the progress header). */+export function planStatusSummary(annotated) {+ const counts = { pending: 0, running: 0, blocked: 0, done: 0, failed: 0, skipped: 0 };+ for (const s of annotated || []) {+ if (counts[s.status] != null) counts[s.status] += 1;+ }+ return counts;+}++/**+ * Resolve a deep link into the owning surface from a step's `result` summary+ * (the compact id-only digest the advance loop writes). Returns `{ to, label }`+ * or null. Series/issue/universe/work/project links mirror the design record's+ * "per-step results with links into the owning surface".+ */+export function stepResultLink(step) {+ const r = step?.result;+ if (!r || typeof r !== 'object') return null;+ if (r.seriesId) return { to: `/pipeline/series/${r.seriesId}`, label: 'Open series' };+ if (r.issueId) return { to: `/pipeline/issues/${r.issueId}`, label: 'Open issue' };+ if (r.universeId) return { to: `/universes/${r.universeId}`, label: 'Open universe' };+ if (r.workId) return { to: `/writers-room/works/${r.workId}`, label: 'Open work' };+ // A minted CD sub-project (cd.* tools return an `id`).+ if (r.id && typeof step.toolName === 'string' && step.toolName.startsWith('cd')) {+ return { to: `/media/creative-director/${r.id}/overview`, label: 'Open project' };+ }+ return null;+}++/**+ * Is this project directive-driven (studio mode) vs a legacy video project?+ * The Plan tab renders the composer/empty-state for a bare project and the board+ * once a directive exists.+ */+export function isDirectiveProject(project) {+ return Boolean(project?.directive);+}diff --git a/client/src/lib/creativeDirectorPlan.test.js b/client/src/lib/creativeDirectorPlan.test.jsnew file mode 100644index 0000000000..a8848ece2d--- /dev/null+++ b/client/src/lib/creativeDirectorPlan.test.js@@ -0,0 +1,137 @@+import { describe, it, expect } from 'vitest';+import {+ annotatePlanSteps,+ planCostSummary,+ planStatusSummary,+ stepRequiresApproval,+ stepResultLink,+ isDirectiveProject,+ DELIVERABLE_OPTIONS,+} from './creativeDirectorPlan.js';++const toolMap = new Map([+ ['universe_create', { costClass: 'free', longRunning: false, destructive: false }],+ ['story_generateStep', { costClass: 'llm', longRunning: false, destructive: false }],+ ['media_enqueueImage', { costClass: 'render', longRunning: true, destructive: false }],+ ['universe_delete', { costClass: 'free', longRunning: false, destructive: true }],+]);++describe('annotatePlanSteps', () => {+ const steps = [+ { stepId: 'a', toolName: 'universe_create', status: 'done', dependsOn: [] },+ { stepId: 'b', toolName: 'story_generateStep', status: 'running', dependsOn: ['a'] },+ { stepId: 'c', toolName: 'media_enqueueImage', status: 'pending', dependsOn: ['b'] },+ { stepId: 'd', toolName: 'ghost_tool', status: 'pending', dependsOn: [] },+ ];+ const runs = [+ { kind: 'plan-step', stepId: 'a', startedAt: '2026-07-01T00:00:00Z', completedAt: '2026-07-01T00:01:00Z' },+ { kind: 'plan-step', stepId: 'a', startedAt: '2026-07-01T00:05:00Z', completedAt: '2026-07-01T00:06:00Z' },+ { kind: 'plan', stepId: undefined, startedAt: '2026-07-01T00:00:00Z' },+ ];++ it('annotates cost class, longRunning, destructive from the tool map', () => {+ const out = annotatePlanSteps(steps, runs, toolMap, { withinBudget: true });+ expect(out[0]).toMatchObject({ stepId: 'a', costClass: 'free', longRunning: false, destructive: false, unknownTool: false });+ expect(out[2]).toMatchObject({ stepId: 'c', costClass: 'render', longRunning: true });+ });++ it('flags an unknown tool and never auto-approves it', () => {+ const out = annotatePlanSteps(steps, runs, toolMap, { withinBudget: false });+ const ghost = out.find((s) => s.stepId === 'd');+ expect(ghost.unknownTool).toBe(true);+ expect(ghost.costClass).toBeNull();+ expect(ghost.requiresApproval).toBe(false);+ });++ it('attaches the LATEST matching plan-step run timing', () => {+ const out = annotatePlanSteps(steps, runs, toolMap, {});+ expect(out[0].startedAt).toBe('2026-07-01T00:05:00Z');+ expect(out[0].completedAt).toBe('2026-07-01T00:06:00Z');+ });++ it('requires approval for a budgeted step when the budget is exhausted', () => {+ const out = annotatePlanSteps(steps, runs, toolMap, { withinBudget: false });+ expect(out.find((s) => s.stepId === 'b').requiresApproval).toBe(true); // llm, over budget+ expect(out.find((s) => s.stepId === 'c').requiresApproval).toBe(true); // render, over budget+ expect(out.find((s) => s.stepId === 'a').requiresApproval).toBe(false); // free+ });++ it('does not require approval for budgeted steps when within budget', () => {+ const out = annotatePlanSteps(steps, runs, toolMap, { withinBudget: true });+ expect(out.every((s) => s.requiresApproval === false)).toBe(true);+ });++ it('returns [] for a null/undefined step list', () => {+ expect(annotatePlanSteps(undefined, runs, toolMap, {})).toEqual([]);+ expect(annotatePlanSteps(null, null, null, {})).toEqual([]);+ });++ it('accepts a plain object tool map as well as a Map', () => {+ const out = annotatePlanSteps(steps, [], { universe_create: { costClass: 'free' } }, {});+ expect(out[0].costClass).toBe('free');+ });+});++describe('stepRequiresApproval', () => {+ it('is true for destructive tools regardless of budget', () => {+ expect(stepRequiresApproval({ costClass: 'free', destructive: true }, { withinBudget: true })).toBe(true);+ });+ it('is true for budgeted tools only when over budget', () => {+ expect(stepRequiresApproval({ costClass: 'llm' }, { withinBudget: false })).toBe(true);+ expect(stepRequiresApproval({ costClass: 'llm' }, { withinBudget: true })).toBe(false);+ });+ it('is false for missing metadata', () => {+ expect(stepRequiresApproval(null, { withinBudget: false })).toBe(false);+ });+});++describe('planCostSummary / planStatusSummary', () => {+ const annotated = [+ { costClass: 'free', status: 'done' },+ { costClass: 'llm', status: 'running' },+ { costClass: 'llm', status: 'blocked' },+ { costClass: null, status: 'pending' },+ ];+ it('counts cost classes', () => {+ expect(planCostSummary(annotated)).toEqual({ free: 1, llm: 2, render: 0 });+ });+ it('counts statuses', () => {+ expect(planStatusSummary(annotated)).toEqual({ pending: 1, running: 1, blocked: 1, done: 1, failed: 0, skipped: 0 });+ });+});++describe('stepResultLink', () => {+ it('links a series result to the pipeline series route', () => {+ expect(stepResultLink({ toolName: 'pipeline_createSeries', result: { seriesId: 's1' } }))+ .toEqual({ to: '/pipeline/series/s1', label: 'Open series' });+ });+ it('links an issue result', () => {+ expect(stepResultLink({ result: { issueId: 'i1' } })).toEqual({ to: '/pipeline/issues/i1', label: 'Open issue' });+ });+ it('links a universe result', () => {+ expect(stepResultLink({ result: { universeId: 'u1' } })).toEqual({ to: '/universes/u1', label: 'Open universe' });+ });+ it('links a work result', () => {+ expect(stepResultLink({ result: { workId: 'w1' } })).toEqual({ to: '/writers-room/works/w1', label: 'Open work' });+ });+ it('links a minted cd sub-project by id', () => {+ expect(stepResultLink({ toolName: 'cd_produceVideoFromIssue', result: { id: 'cd-9' } }))+ .toEqual({ to: '/media/creative-director/cd-9/overview', label: 'Open project' });+ });+ it('returns null with no linkable result', () => {+ expect(stepResultLink({ result: null })).toBeNull();+ expect(stepResultLink({ result: { planned: true } })).toBeNull();+ });+});++describe('isDirectiveProject / DELIVERABLE_OPTIONS', () => {+ it('detects a directive project', () => {+ expect(isDirectiveProject({ directive: { goal: 'x' } })).toBe(true);+ expect(isDirectiveProject({ directive: null })).toBe(false);+ expect(isDirectiveProject({})).toBe(false);+ });+ it('exposes a stable deliverable menu', () => {+ expect(DELIVERABLE_OPTIONS.map((o) => o.id)).toContain('covers');+ expect(DELIVERABLE_OPTIONS.map((o) => o.id)).toContain('video-teaser');+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex bea78eed62..4db1a4de0c 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -20,6 +20,7 @@ export * from './beatColors.js';export * from './beatGrid.js';export * from './bibleLimits.js';export * from './catalogTypes.js';+export * from './creativeDirectorPlan.js';export * from './editorialRoadmap.js';export * from './imageCleaners.js';export * from './imageGenBackends.js';diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex 62fa8cfb4f..9e89f3b24e 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback } from 'react';-import { Link, useLocation, useNavigate } from 'react-router-dom';-import { Plus, Film, Trash2, Play, Pause, FlaskConical, Sparkles } from 'lucide-react';+import { Link, useLocation, useNavigate, useSearchParams } from 'react-router-dom';+import { Plus, Film, Trash2, Play, Pause, FlaskConical, Sparkles, Wand2 } from 'lucide-react';import toast from '../components/ui/Toast';import {listCreativeDirectorProjects,@@ -12,8 +12,12 @@ import {} from '../services/apiCreativeDirector.js';import { listCatalogIngredientsByIds } from '../services/apiCatalog.js';import { listVideoModels } from '../services/apiImageVideo.js';+import { listUniverses } from '../services/apiUniverseBuilder.js';+import { listPipelineSeries } from '../services/apiPipeline.js';import ModelSelect from '../components/ModelSelect';import PageHeader from '../components/PageHeader';+import Drawer from '../components/Drawer';+import DirectiveComposer from '../components/creative-director/DirectiveComposer.jsx';const ASPECT_RATIOS = ['16:9', '9:16', '1:1'];const QUALITIES = ['draft', 'standard', 'high'];@@ -28,13 +32,25 @@ const STATUS_COLORS = {failed: 'bg-port-error/30 text-port-error',};+const EMPTY_DIRECTIVE = { goal: '', deliverables: [], constraints: { universeId: null, seriesId: null, budgetCap: null } };+export default function CreativeDirector() {const location = useLocation();const navigate = useNavigate();+ const [searchParams, setSearchParams] = useSearchParams();const [projects, setProjects] = useState([]);const [loading, setLoading] = useState(true);const [showForm, setShowForm] = useState(false);const [models, setModels] = useState([]);+ // Directive composer (CDO Phase 4, #2186) — deep-linkable drawer (`?new=directive`)+ // that creates a studio production project seeded with a directive. State is+ // hoisted here (above the Drawer body) per the Drawer state-hoisting rule.+ const directiveOpen = searchParams.get('new') === 'directive';+ const [directiveName, setDirectiveName] = useState('');+ const [directiveDraft, setDirectiveDraft] = useState(EMPTY_DIRECTIVE);+ const [creatingDirective, setCreatingDirective] = useState(false);+ const [universes, setUniverses] = useState([]);+ const [series, setSeries] = useState([]);// Catalog "Remix into… → Creative Director" handoff (#1808). The ingredient// ids arrive in the generic `location.state.remix.ingredientIds`; we hydrate// them for the chip list and forward the ids on create so the server folds@@ -131,6 +147,45 @@ export default function CreativeDirector() {}};+ const openDirective = () => {+ setDirectiveName('');+ setDirectiveDraft(EMPTY_DIRECTIVE);+ setSearchParams((prev) => { const n = new URLSearchParams(prev); n.set('new', 'directive'); return n; }, { replace: true });+ if (!universes.length) listUniverses({ silent: true }).then((u) => setUniverses(Array.isArray(u) ? u : (u?.items || []))).catch(() => {});+ if (!series.length) listPipelineSeries({ silent: true }).then((s) => setSeries(Array.isArray(s) ? s : (s?.items || []))).catch(() => {});+ };+ const closeDirective = () => {+ setSearchParams((prev) => { const n = new URLSearchParams(prev); n.delete('new'); return n; }, { replace: true });+ };++ const handleCreateDirective = async () => {+ if (!directiveName.trim()) { toast.error('Name is required'); return; }+ if (!directiveDraft.goal.trim()) { toast.error('Directive goal is required'); return; }+ const modelId = form.modelId || models.find((m) => !m.deprecated)?.id || models[0]?.id;+ if (!modelId) { toast.error('No video model available'); return; }+ setCreatingDirective(true);+ // A directive project still carries the base video params (the built-in video+ // production template uses them); the planner drives the rest from the brief.+ const created = await createCreativeDirectorProject({+ name: directiveName.trim(),+ aspectRatio: form.aspectRatio,+ quality: form.quality,+ modelId,+ targetDurationSeconds: Number(form.targetDurationSeconds) || 60,+ directive: {+ goal: directiveDraft.goal.trim(),+ deliverables: directiveDraft.deliverables || [],+ constraints: directiveDraft.constraints || {},+ },+ }).catch((err) => { toast.error(err.message || 'Failed to create directive project'); return null; });+ setCreatingDirective(false);+ if (!created) return;+ setProjects((prev) => [created, ...prev]);+ toast.success(`Created directive "${created.name}"`);+ closeDirective();+ navigate(`/media/creative-director/${created.id}/plan`);+ };+// Optimistic-update the row in place rather than refetching the whole list// (per CLAUDE.md "Reactive UI updates"). The detail page's poll picks up the// server's authoritative status within 5s if anything diverges.@@ -194,6 +249,14 @@ export default function CreativeDirector() {<FlaskConical className="w-4 h-4" />Run smoke test</button>+ <button+ onClick={openDirective}+ className="flex items-center gap-2 bg-port-card border border-port-border hover:bg-port-card/60 text-port-text px-3 py-2 rounded text-sm"+ title="Compose a directive — the Creative Director plans and executes it across the creative suite"+ >+ <Wand2 className="w-4 h-4" />+ New directive+ </button><buttononClick={() => { setShowForm((s) => !s); clearRemix(); }}className="flex items-center gap-2 bg-port-accent hover:bg-port-accent/80 text-white px-3 py-2 rounded text-sm"@@ -375,6 +438,46 @@ export default function CreativeDirector() {))}</div></div>++ <Drawer+ open={directiveOpen}+ onClose={closeDirective}+ title="New directive"+ subtitle="A studio production the Creative Director plans and executes"+ size="lg"+ closeOnEsc={false}+ closeOnBackdrop={false}+ >+ <div className="mb-4">+ <label htmlFor="directive-project-name" className="block text-sm text-port-text-muted mb-1">Project name</label>+ <input+ id="directive-project-name"+ value={directiveName}+ onChange={(e) => setDirectiveName(e.target.value)}+ placeholder="Noir Anthology"+ maxLength={200}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"+ />+ </div>+ <DirectiveComposer+ directive={directiveDraft}+ onChange={setDirectiveDraft}+ universes={universes}+ series={series}+ idPrefix="new-directive"+ disabled={creatingDirective}+ />+ <div className="flex gap-2 justify-end mt-5 pt-4 border-t border-port-border">+ <button onClick={closeDirective} className="px-3 py-1.5 rounded text-sm bg-port-bg border border-port-border">Cancel</button>+ <button+ onClick={handleCreateDirective}+ disabled={creatingDirective || !directiveName.trim() || !directiveDraft.goal.trim()}+ className="px-3 py-1.5 rounded text-sm bg-port-accent text-white disabled:opacity-50"+ >+ {creatingDirective ? 'Creating…' : 'Create directive'}+ </button>+ </div>+ </Drawer></div>);}diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 96ec8f71b0..cb6fa7b718 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -11,6 +11,7 @@ import {import OverviewTab from '../components/creative-director/OverviewTab.jsx';import TreatmentTab from '../components/creative-director/TreatmentTab.jsx';import SegmentsTab from '../components/creative-director/SegmentsTab.jsx';+import PlanTab from '../components/creative-director/PlanTab.jsx';import RunsTab from '../components/creative-director/RunsTab.jsx';import ActiveAgentsBanner from '../components/creative-director/ActiveAgentsBanner.jsx';import { getCosAgents } from '../services/apiAgents.js';@@ -22,6 +23,7 @@ const TERMINAL_PROJECT_STATUSES = new Set(['complete', 'failed', 'paused', 'drafconst TABS = [{ id: 'overview', label: 'Overview' },+ { id: 'plan', label: 'Plan' },{ id: 'treatment', label: 'Treatment' },{ id: 'segments', label: 'Segments' },{ id: 'runs', label: 'Runs' },@@ -218,6 +220,12 @@ export default function CreativeDirectorDetail() {onAsyncWorkQueued={extendPollingForAsyncWork}/>)}+ {activeTab === 'plan' && (+ <PlanTab+ project={project}+ onProjectUpdate={(updated) => setProject((p) => (p ? { ...p, ...updated } : updated))}+ />+ )}{activeTab === 'treatment' && <TreatmentTab project={project} />}{activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} />}{activeTab === 'runs' && <RunsTab project={project} />}diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex ea5aaac694..13a3e34ec5 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -30,6 +30,33 @@ export const resumeCreativeDirectorProject = (id) => request(`/creative-directorexport const createSmokeTestCreativeDirectorProject = () => request('/creative-director/smoke-test', {method: 'POST',});+// Creative tool catalog (CDO Phase 4, #2186) — `{ tools: [{ id, description,+// costClass, longRunning, destructive }], mode, budget }`. The Plan board+// hydrates per-step cost-class badges + approval affordances from it; `mode`+// drives the dry-run banner. `options.silent` defers error toasting to a caller+// that owns its own error UI.+export const getCreativeToolCatalog = (options = {}) => request('/creative-director/tools', options);+// Attach/replace a directive on an existing project ("convert to directive").+// Clears any prior plan so the planner re-derives one; returns the updated+// project for reactive state swap.+export const setCreativeDirectorDirective = (id, directive) => request(`/creative-director/${encodeURIComponent(id)}/directive`, {+ method: 'POST',+ body: JSON.stringify(directive),+});+// Request a fresh plan (drops the current plan, re-runs the planner). Blocked-step+// triage "re-plan" action.+export const replanCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}/replan`, {+ method: 'POST',+});+// Blocked-step triage: `skip` a step or `retry` (reset a blocked/failed step to+// pending — also the "approve" affordance for a gate-blocked step). Returns the+// updated project. `options.silent` defers error toasting.+export const updateCreativeDirectorPlanStep = (id, stepId, action, options = {}) =>+ request(`/creative-director/${encodeURIComponent(id)}/plan/step/${encodeURIComponent(stepId)}`, {+ method: 'POST',+ body: JSON.stringify({ action }),+ ...options,+ });// Autonomous auto-cast (#1810). `suggest` previews the catalog ingredients the// director would propose for a free-text brief (no mutation). `apply` derives the// brief from the project (or accepts an explicit one), appends the freshdiff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 559581638e..506fd9b440 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -252,6 +252,19 @@ export const creativeDirectorPlanSchema = z.object({steps: z.array(creativeDirectorPlanStepSchema).min(1).max(60),}).strict();+// Blocked-step triage actions (CDO Phase 4, #2186). The studio UI's Plan tab+// dispatches one of these against a single plan step:+// - `skip` → mark the step `skipped` (a terminal-success state), unblocking+// its dependents, and resume the plan advance loop.+// - `retry` → reset a `blocked`/`failed` step back to `pending` (clearing its+// prior result + retryCount) so the advance loop re-dispatches it.+// Doubles as the "approve" affordance for a step the gate blocked+// (destructive / over-budget): once the human raises the budget or+// flips autonomy, retry re-runs just that step.+export const creativeDirectorPlanStepActionSchema = z.object({+ action: z.enum(['skip', 'retry']),+}).strict();+// ---------------------------------------------------------------------------// Create Suite — Importer.//diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex a3ad2e3b0d..d1ddfd948a 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -19,7 +19,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },{ id: 'nav.media.annotate', path: '/media/annotate', label: 'Annotate', section: 'Create', aliases: ['annotate', 'media-annotate', 'sketch', 'draw-over', 'markup'], keywords: ['annotation', 'sketch', 'draw', 'markup', 'scribble', 'label', 'canvas', 'overlay', 'stroke'] },{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },- { id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },+ { id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },{ id: 'nav.media.music-video', path: '/media/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex d93106e2e9..d5a718faa5 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -15,6 +15,8 @@ import {creativeDirectorProjectUpdateSchema,creativeDirectorTreatmentSchema,creativeDirectorPlanSchema,+ creativeDirectorPlanStepActionSchema,+ creativeDirectorDirectiveSchema,creativeDirectorSceneUpdateSchema,creativeDirectorAutoCastSuggestSchema,creativeDirectorAutoCastApplySchema,@@ -27,6 +29,7 @@ import {deleteProject,setTreatment,setPlan,+ updatePlanStep,updateScene,} from '../services/creativeDirector/local.js';import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';@@ -41,6 +44,33 @@ router.get('/', asyncHandler(async (_req, res) => {res.json(await listProjects());}));+// Creative tool catalog (CDO Phase 4, #2186) — the studio Plan board + directive+// composer hydrate per-step cost-class badges + approval affordances from this+// (mirrors the palette hydrating from the voice-tool registry). Also returns the+// current `creative` autonomy mode (off | dry-run | execute) and the shared cos+// action-budget status so the board can render a dry-run banner and flag steps+// the gate would block (over budget). Registered before `/:id` so the literal+// path can't be shadowed by the param route. Pure read — no LLM, no mutation.+router.get('/tools', asyncHandler(async (_req, res) => {+ // Dynamic-imported (like the /plan advance-loop nudge below) so the heavy tool+ // graph + cos state modules aren't pulled at route module-load — keeps the+ // route unit test fast and free of those services' import-time side effects.+ const [{ getAllCreativeToolMetadata }, { getCreativeAutonomyMode }, { getDomainBudgetStatus }, { loadState }] = await Promise.all([+ import('../services/creative/toolRegistry.js'),+ import('../lib/domainAutonomy.js'),+ import('../services/domainUsage.js'),+ import('../services/cosState.js'),+ ]);+ const state = await loadState().catch(() => ({ config: {} }));+ const mode = getCreativeAutonomyMode(state.config);+ const budget = await getDomainBudgetStatus('cos').catch(() => ({ withinBudget: true, exceeded: null }));+ res.json({+ tools: getAllCreativeToolMetadata(),+ mode,+ budget: { withinBudget: budget.withinBudget, exceeded: budget.exceeded },+ });+}));+// Slim projection of a project for polling consumers (pipeline EpisodeVideoStage// polls every 4s; the full project carries `runs[]` history and the full// treatment text the poll doesn't need). The shape covers exactly what the@@ -197,6 +227,73 @@ router.patch('/:id/plan', asyncHandler(async (req, res) => {res.json(updated);}));+// User-callable (CDO Phase 4, #2186): attach a directive to an EXISTING project+// ("convert to directive") or replace one. Validates the directive, clears any+// prior plan so the planner re-derives one from the new brief, flips the project+// to `planning`, and nudges the generalized advance loop — which enqueues the+// planner agent (the project now has a directive but no plan). A paused/failed+// project is left parked (the user re-runs it explicitly). Reactive: returns the+// updated project so the UI swaps state without a refetch.+router.post('/:id/directive', asyncHandler(async (req, res) => {+ const directive = validateRequest(creativeDirectorDirectiveSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const parked = project.status === 'paused' || project.status === 'failed';+ const updated = await updateProject(req.params.id, {+ directive,+ plan: null,+ ...(parked ? {} : { status: 'planning', failureReason: null }),+ });+ if (!parked) {+ const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');+ advanceAfterPlanStepSettled(req.params.id)+ .catch((e) => console.log(`⚠️ CD directive advance failed: ${e.message}`));+ }+ res.json(updated);+}));++// User-callable (CDO Phase 4, #2186): request a fresh plan. Drops the current+// plan (preserving the directive) and re-runs the planner via the advance loop.+// Blocked-step triage "re-plan" action. No-op on a project without a directive.+router.post('/:id/replan', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (!project.directive) throw new ServerError('Project has no directive to re-plan', { status: 400, code: 'NO_DIRECTIVE' });+ const updated = await updateProject(req.params.id, { plan: null, status: 'planning', failureReason: null });+ const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');+ advanceAfterPlanStepSettled(req.params.id)+ .catch((e) => console.log(`⚠️ CD replan advance failed: ${e.message}`));+ res.json(updated);+}));++// User-callable (CDO Phase 4, #2186): blocked-step triage. `skip` marks a step+// `skipped` (terminal-success — unblocks dependents); `retry` resets a+// blocked/failed step to `pending` (clearing its result + retryCount) so the+// advance loop re-dispatches it — also the "approve" affordance for a gate-blocked+// step. Either way we clear a plan-level pause (paused → rendering) and nudge the+// advance loop. Returns the updated project for reactive state swap; 404 when the+// step is unknown (updatePlanStep returns the project unchanged).+router.post('/:id/plan/step/:stepId', asyncHandler(async (req, res) => {+ const { action } = validateRequest(creativeDirectorPlanStepActionSchema, req.body);+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const step = (project.plan?.steps || []).find((s) => s.stepId === req.params.stepId);+ if (!step) throw new ServerError('Plan step not found', { status: 404, code: 'NOT_FOUND' });+ const patch = action === 'skip'+ ? { status: 'skipped', result: { skippedByUser: true } }+ : { status: 'pending', retryCount: 0, result: null };+ await updatePlanStep(req.params.id, req.params.stepId, patch);+ // Clear a plan-level pause so the advance loop isn't short-circuited by the+ // paused guard; a still-blocked project stays parked otherwise.+ if (project.status === 'paused') {+ await updateProject(req.params.id, { status: 'rendering', failureReason: null });+ }+ const { advanceAfterPlanStepSettled } = await import('../services/creativeDirector/planAdvance.js');+ advanceAfterPlanStepSettled(req.params.id)+ .catch((e) => console.log(`⚠️ CD plan step ${action} advance failed: ${e.message}`));+ res.json(await getProject(req.params.id));+}));+// 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/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 6421989be4..68ea3c55d5 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -6,9 +6,11 @@ vi.mock('../services/creativeDirector/local.js', () => ({listProjects: vi.fn(async () => [{ id: 'cd-1', name: 'A' }]),getProject: vi.fn(),createProject: vi.fn(),- updateProject: vi.fn(),+ updateProject: vi.fn(async (id, patch) => ({ id, ...patch })),deleteProject: vi.fn(async () => ({ ok: true })),setTreatment: vi.fn(),+ setPlan: vi.fn(),+ updatePlanStep: vi.fn(async () => ({})),updateScene: vi.fn(),}));@@ -17,6 +19,18 @@ vi.mock('../services/creativeDirector/completionHook.js', () => ({advanceAfterSceneSettled: vi.fn(async () => undefined),}));+// CDO Phase 4 (#2186) — the new studio routes dynamic-import these; mock so the+// route test stays off the heavy tool graph + cos state modules.+vi.mock('../services/creativeDirector/planAdvance.js', () => ({+ advanceAfterPlanStepSettled: vi.fn(async () => undefined),+}));+vi.mock('../services/creative/toolRegistry.js', () => ({+ getAllCreativeToolMetadata: vi.fn(() => [{ id: 'universe_create', costClass: 'free', longRunning: false, destructive: false }]),+}));+vi.mock('../lib/domainAutonomy.js', () => ({ getCreativeAutonomyMode: vi.fn(() => 'dry-run') }));+vi.mock('../services/domainUsage.js', () => ({ getDomainBudgetStatus: vi.fn(async () => ({ withinBudget: false, exceeded: 'actions' })) }));+vi.mock('../services/cosState.js', () => ({ loadState: vi.fn(async () => ({ config: {} })) }));+// Mock the auto-cast service so the route test doesn't pull the real// catalogDB/embeddings graph; the route's job here is to validate + dispatch.vi.mock('../services/creativeDirector/autoCast.js', () => ({@@ -511,4 +525,108 @@ describe('creativeDirector routes', () => {expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();});});++ // CDO Phase 4 (#2186) — studio UI routes.+ describe('GET /tools', () => {+ it('returns the tool catalog + mode + budget', async () => {+ const r = await request(app).get('/api/creative-director/tools');+ expect(r.status).toBe(200);+ expect(r.body.tools).toEqual([{ id: 'universe_create', costClass: 'free', longRunning: false, destructive: false }]);+ expect(r.body.mode).toBe('dry-run');+ expect(r.body.budget).toEqual({ withinBudget: false, exceeded: 'actions' });+ });+ });++ describe('POST /:id/directive', () => {+ it('sets a directive, clears the plan, flips to planning, and nudges the advance loop', async () => {+ const planAdvance = await import('../services/creativeDirector/planAdvance.js');+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'draft' });+ const r = await request(app).post('/api/creative-director/cd-1/directive')+ .send({ goal: 'Make a noir series', deliverables: ['story'], constraints: { budgetCap: 10 } });+ expect(r.status).toBe(200);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', expect.objectContaining({+ plan: null, status: 'planning', directive: expect.objectContaining({ goal: 'Make a noir series' }),+ }));+ expect(planAdvance.advanceAfterPlanStepSettled).toHaveBeenCalledWith('cd-1');+ });++ it('leaves a paused project parked (no advance)', async () => {+ const planAdvance = await import('../services/creativeDirector/planAdvance.js');+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'paused' });+ const r = await request(app).post('/api/creative-director/cd-1/directive').send({ goal: 'x' });+ expect(r.status).toBe(200);+ expect(planAdvance.advanceAfterPlanStepSettled).not.toHaveBeenCalled();+ });++ it('400s on a missing goal', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'draft' });+ const r = await request(app).post('/api/creative-director/cd-1/directive').send({ deliverables: ['x'] });+ expect(r.status).toBe(400);+ });++ it('404s on an unknown project', async () => {+ cdService.getProject.mockResolvedValue(null);+ const r = await request(app).post('/api/creative-director/nope/directive').send({ goal: 'x' });+ expect(r.status).toBe(404);+ });+ });++ describe('POST /:id/replan', () => {+ it('clears the plan and re-runs the planner', async () => {+ const planAdvance = await import('../services/creativeDirector/planAdvance.js');+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'rendering', directive: { goal: 'x' } });+ const r = await request(app).post('/api/creative-director/cd-1/replan');+ expect(r.status).toBe(200);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { plan: null, status: 'planning', failureReason: null });+ expect(planAdvance.advanceAfterPlanStepSettled).toHaveBeenCalledWith('cd-1');+ });++ it('400s when the project has no directive', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'draft', directive: null });+ const r = await request(app).post('/api/creative-director/cd-1/replan');+ expect(r.status).toBe(400);+ });+ });++ describe('POST /:id/plan/step/:stepId', () => {+ const projectWithStep = (status = 'rendering') => ({+ id: 'cd-1', status, directive: { goal: 'x' },+ plan: { steps: [{ stepId: 'draft', toolName: 'story_generateStep', status: 'blocked' }] },+ });++ it('skips a step, then nudges the advance loop', async () => {+ const planAdvance = await import('../services/creativeDirector/planAdvance.js');+ cdService.getProject.mockResolvedValue(projectWithStep());+ const r = await request(app).post('/api/creative-director/cd-1/plan/step/draft').send({ action: 'skip' });+ expect(r.status).toBe(200);+ expect(cdService.updatePlanStep).toHaveBeenCalledWith('cd-1', 'draft', expect.objectContaining({ status: 'skipped' }));+ expect(planAdvance.advanceAfterPlanStepSettled).toHaveBeenCalledWith('cd-1');+ });++ it('retries a step, resetting it to pending', async () => {+ cdService.getProject.mockResolvedValue(projectWithStep());+ const r = await request(app).post('/api/creative-director/cd-1/plan/step/draft').send({ action: 'retry' });+ expect(r.status).toBe(200);+ expect(cdService.updatePlanStep).toHaveBeenCalledWith('cd-1', 'draft', { status: 'pending', retryCount: 0, result: null });+ });++ it('clears a plan-level pause (paused → rendering) before advancing', async () => {+ cdService.getProject.mockResolvedValue(projectWithStep('paused'));+ const r = await request(app).post('/api/creative-director/cd-1/plan/step/draft').send({ action: 'retry' });+ expect(r.status).toBe(200);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'rendering', failureReason: null });+ });++ it('404s on an unknown step', async () => {+ cdService.getProject.mockResolvedValue(projectWithStep());+ const r = await request(app).post('/api/creative-director/cd-1/plan/step/ghost').send({ action: 'skip' });+ expect(r.status).toBe(404);+ });++ it('400s on an invalid action', async () => {+ cdService.getProject.mockResolvedValue(projectWithStep());+ const r = await request(app).post('/api/creative-director/cd-1/plan/step/draft').send({ action: 'nuke' });+ expect(r.status).toBe(400);+ });+ });});diff --git a/server/services/creative/toolRegistry.js b/server/services/creative/toolRegistry.jsindex 87dd437055..25f0650f7d 100644--- a/server/services/creative/toolRegistry.js+++ b/server/services/creative/toolRegistry.js@@ -139,6 +139,16 @@ export const getToolSpecs = ({ includeDestructive = false } = {}) =>export const getAllCreativeToolNames = () => CREATIVE_TOOLS.map((t) => t.name);+/**+ * Plain metadata for EVERY registered tool (id, description, costClass,+ * longRunning, destructive) — the plan-board / directive-composer consumers+ * (CDO Phase 4) hydrate cost-class badges + approval affordances from this+ * without pulling the LLM-shaped `getToolSpecs()`. Destructive tools ARE+ * included here (unlike the default spec set) so a hand-authored or bridged plan+ * step naming one still renders with its real cost/approval flags.+ */+export const getAllCreativeToolMetadata = () => CREATIVE_TOOLS.map((t) => getCreativeToolMetadata(t.name));+/*** Plain metadata for one tool (for non-LLM consumers, e.g. a plan board or the* command palette). Shape-independent from getToolSpecs.