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-842]): Writers Room → Creative Director bridge
Adam Eivy56e61a0e58c2
diff --git a/client/src/components/writers-room/CdBridgePanel.jsx b/client/src/components/writers-room/CdBridgePanel.jsxnew file mode 100644index 0000000000..7a9e2d349b--- /dev/null+++ b/client/src/components/writers-room/CdBridgePanel.jsx@@ -0,0 +1,171 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useNavigate } from 'react-router-dom';+import { Clapperboard, Loader2, Send } from 'lucide-react';+import toast from '../ui/Toast';+import {+ suggestWritersRoomCdBridge,+ sendWritersRoomCdBridge,+} from '../../services/apiWritersRoom';+import useMounted from '../../hooks/useMounted';++// Phase 5 Creative Director bridge panel. While the work has live mode opted+// in, the writer can ask the Creative Director to turn the prose around the+// cursor into a short film treatment — a logline, synopsis, overall visual+// treatment (styleSpec), and 2–6 filmable scenes — then send it into a NEW+// Creative Director project. Unlike LiveContinuationPanel this owns NO debounce+// timer: proposing a treatment is a deliberate, heavier action behind an+// explicit button. It draws on the SAME daily call budget as the continuation+// panel (both are text LLM calls), so the readout reflects the shared counter.+export default function CdBridgePanel({ workId, liveMode, getCursorContext, onLinked }) {+ const navigate = useNavigate();+ const [proposal, setProposal] = useState(null);+ const [loading, setLoading] = useState(false);+ const [sending, setSending] = useState(false);+ const [notice, setNotice] = useState(null);+ // Local usage mirror so a fresh proposal updates the "N left today" readout+ // immediately; re-synced from the prop on a parent-driven liveMode change.+ const [usage, setUsage] = useState(liveMode?.usage || null);+ useEffect(() => { setUsage(liveMode?.usage || null); }, [liveMode?.usage]);+ const mountedRef = useMounted();++ // Staleness guard for overlapping proposal requests — a second click while+ // the first is in flight tags a new generation and discards the older+ // response. Simpler than LiveContinuationPanel's rerun-queue because there's+ // no debounce firing behind the user's back.+ const genRef = useRef(0);+ const ctxGetterRef = useRef(getCursorContext);+ const workIdRef = useRef(workId);+ useEffect(() => { ctxGetterRef.current = getCursorContext; }, [getCursorContext]);+ useEffect(() => { workIdRef.current = workId; }, [workId]);++ const requestProposal = useCallback(async () => {+ const ctx = ctxGetterRef.current?.();+ if (!ctx || (!ctx.before?.trim() && !ctx.after?.trim() && !ctx.selection?.trim())) {+ setNotice('Place your cursor in some prose, then propose a treatment.');+ return;+ }+ const gen = ++genRef.current;+ setLoading(true);+ setNotice(null);+ setProposal(null);+ const res = await suggestWritersRoomCdBridge(workIdRef.current, ctx, { silent: true }).catch((err) => {+ if (mountedRef.current && gen === genRef.current) {+ if (err?.status === 429) setNotice('Daily suggestion budget reached — resets at UTC midnight.');+ else if (err?.status === 409) setNotice('Live mode is off for this work.');+ else toast.error(`Proposal failed: ${err.message}`);+ }+ return null;+ });+ if (!mountedRef.current || gen !== genRef.current) return;+ setLoading(false);+ if (!res) return;+ if (res.usage) setUsage(res.usage);+ if (!res.proposal) {+ setNotice('No treatment this time — keep writing and try again.');+ return;+ }+ setProposal(res.proposal);+ }, [mountedRef]);++ const sendToCd = useCallback(async () => {+ if (!proposal || sending) return;+ setSending(true);+ const res = await sendWritersRoomCdBridge(workIdRef.current, proposal, { silent: true }).catch((err) => {+ if (mountedRef.current) toast.error(`Send failed: ${err.message}`);+ return null;+ });+ if (!mountedRef.current) return;+ setSending(false);+ if (!res?.project) return;+ onLinked?.(res.project.id);+ toast.success('Sent to Creative Director');+ navigate(`/creative-director/${encodeURIComponent(res.project.id)}/overview`);+ }, [proposal, sending, onLinked, navigate, mountedRef]);++ // When live mode flips off, clear any stale proposal so the panel doesn't+ // keep advertising a treatment against prose the writer has moved past.+ useEffect(() => {+ if (!liveMode?.enabled) {+ setProposal(null);+ setNotice(null);+ }+ }, [liveMode?.enabled]);++ if (!liveMode?.enabled) return null;++ const budget = liveMode?.dailyCallBudget ?? 0;+ const spent = usage?.count ?? 0;+ const remainingLabel = budget > 0 ? `${Math.max(0, budget - spent)} / ${budget} left today` : 'unlimited';++ return (+ <div className="px-3 py-2 border-b border-port-border">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5 text-[11px] font-semibold text-port-accent">+ <Clapperboard size={12} /> CD Bridge+ </div>+ <div className="flex items-center gap-2">+ <span className="text-[10px] text-gray-500" title="Shares the daily suggestion budget">{remainingLabel}</span>+ <button+ type="button"+ onClick={requestProposal}+ disabled={loading}+ className="flex items-center gap-1 px-2 py-0.5 text-[10px] rounded bg-port-bg border border-port-border text-gray-300 hover:text-white disabled:opacity-50"+ title="Propose a Creative Director treatment from the cursor"+ >+ {loading ? <Loader2 size={10} className="animate-spin" /> : <Clapperboard size={10} />}+ Propose treatment+ </button>+ </div>+ </div>++ {notice && (+ <div className="mt-1.5 text-[10px] text-gray-400">{notice}</div>+ )}++ {!notice && !proposal && !loading && (+ <div className="mt-1 text-[10px] text-gray-500">+ Turn the prose around your cursor into a short film treatment — scenes + a visual look — and send it into Creative Director.+ </div>+ )}++ {proposal && (+ <div className="mt-2 space-y-2">+ {proposal.logline && (+ <div className="text-[11px] font-medium text-gray-200">{proposal.logline}</div>+ )}+ {proposal.synopsis && (+ <div className="text-[10px] text-gray-400 whitespace-pre-wrap">{proposal.synopsis}</div>+ )}+ {proposal.styleSpec && (+ <div className="rounded border border-port-border bg-port-bg/60 p-2">+ <div className="text-[9px] uppercase tracking-wide text-port-warning mb-0.5">Visual treatment</div>+ <div className="text-[10px] text-gray-400 whitespace-pre-wrap">{proposal.styleSpec}</div>+ </div>+ )}+ <div className="space-y-1.5">+ {(proposal.scenes || []).map((scene, i) => (+ <div key={i} className="rounded border border-port-border bg-port-card/60 p-2">+ <div className="flex items-center justify-between gap-2 mb-0.5">+ <span className="text-[9px] uppercase tracking-wide text-port-accent">Scene {i + 1}</span>+ <span className="text-[9px] text-gray-600">{scene.durationSeconds}s</span>+ </div>+ <div className="text-[11px] text-gray-300">{scene.intent}</div>+ <div className="text-[10px] text-gray-500 italic mt-0.5 whitespace-pre-wrap">{scene.prompt}</div>+ </div>+ ))}+ </div>+ <button+ type="button"+ onClick={sendToCd}+ disabled={sending}+ className="flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-port-accent/15 text-port-accent hover:bg-port-accent/25 disabled:opacity-50"+ title="Create a Creative Director project seeded with this treatment"+ >+ {sending ? <Loader2 size={10} className="animate-spin" /> : <Send size={10} />}+ Send to Creative Director+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex e7d395a5be..5424330c15 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -46,6 +46,7 @@ import { countWords } from '../../utils/formatters';import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';import LiveContinuationPanel from './LiveContinuationPanel';import LiveRenderPanel from './LiveRenderPanel';+import CdBridgePanel from './CdBridgePanel';import AnalysisHistory from './AnalysisHistory';import ProseReader from './ProseReader';import SyncedReview from './SyncedReview';@@ -439,6 +440,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOnavigate(`/pipeline/issues/${encodeURIComponent(work.pipelineIssueId)}/prose`);};+ const handleOpenInCreativeDirector = () => {+ if (!work.cdProjectId) return;+ navigate(`/creative-director/${encodeURIComponent(work.cdProjectId)}/overview`);+ };+const commitTitle = async () => {if (title === work.title) return;const updated = await updateWritersRoomWork(work.id, { title }).catch((err) => {@@ -862,6 +868,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO) : (<MenuItem icon={Film} label={promoting ? 'Promoting…' : 'Promote to pipeline'} running={promoting} onClick={closeOverflowAnd(handlePromoteToPipeline)} />)}+ {work.cdProjectId && (+ <MenuItem icon={ExternalLink} label="Open in Creative Director" onClick={closeOverflowAnd(handleOpenInCreativeDirector)} />+ )}</MenuSection><MenuSection label="View"><MenuItem@@ -1000,6 +1009,12 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOregisterTrigger={registerLiveTrigger}/></div>+ <CdBridgePanel+ workId={work.id}+ liveMode={liveMode}+ getCursorContext={getCursorContext}+ onLinked={(cdProjectId) => onChange?.({ ...work, cdProjectId })}+ /></>)}<StoryboardPaneldiff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 2c0d43d8d2..3ae6ae9874 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -94,6 +94,28 @@ export const reserveWritersRoomRenderPreview = (workId, options) =>...(options || {}),});+// CD bridge (Phase 5): propose a Creative Director treatment from the cursor+// context. Draws on the SAME daily call budget as live continuation (both text+// calls); the server gates on the live-mode toggle (409) and that budget (429).+// Returns { proposal, usage, budget } — proposal is null when no usable+// treatment came back. Callers own their own error UI, so pass { silent: true }.+export const suggestWritersRoomCdBridge = (workId, context, options) =>+ request(`/writers-room/works/${enc(workId)}/cd-bridge/suggest`, {+ method: 'POST',+ body: JSON.stringify(context || {}),+ ...(options || {}),+ });++// Send a reviewed CD-bridge proposal into a NEW Creative Director project+// (non-destructive). Returns { project } — the seeded CD project with its+// treatment applied. Callers own their own error UI, so pass { silent: true }.+export const sendWritersRoomCdBridge = (workId, proposal, options) =>+ request(`/writers-room/works/${enc(workId)}/cd-bridge/send`, {+ method: 'POST',+ body: JSON.stringify({ proposal }),+ ...(options || {}),+ });+// Synced review (Phase 4): a read-model that maps prose segments ↔ script// scenes ↔ generated media with provenance + stale detection. Derived on the// server from the active draft's segment index and the `script` analysisdiff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex aabf0a9a7d..61d16ea808 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -49,6 +49,13 @@"returnsJson": true,"variables": []},+ "writers-room-cd-bridge": {+ "name": "Writers Room — Creative Director Bridge",+ "description": "From the prose around the cursor, propose a short Creative Director treatment — a logline, synopsis, overall visual treatment (styleSpec), and 2–6 filmable scenes (intent + visual prompt + duration). The writer reviews it and sends it into a new Creative Director project. Drives the opt-in live-mode side panel in the editor.",+ "model": "quick",+ "returnsJson": true,+ "variables": []+ },"catalog-ideas-scenes-concepts": {"name": "Catalog Ingest — Ideas / Scenes / Concepts","description": "Extract reusable narrative fragments — ideas (premises), scenes (dramatic beats), and concepts (lore, magic systems, factions) — from a raw user-pasted scrap into the Creative Ingredients Catalog. Runs alongside the character/place/object writers-room passes during catalog ingest.",diff --git a/data.reference/prompts/stages/writers-room-cd-bridge.md b/data.reference/prompts/stages/writers-room-cd-bridge.mdnew file mode 100644index 0000000000..80a944299a--- /dev/null+++ b/data.reference/prompts/stages/writers-room-cd-bridge.md@@ -0,0 +1,56 @@+# Writers Room — Creative Director Bridge++You are a Creative Director reading over the writer's shoulder. They have paused at a cursor and want you to imagine how this moment could become a short visual sequence — a handful of filmable scenes plus an overall visual treatment. You are pitching a direction the writer can hand off to production, not rewriting their prose.++## Work being written++- Title: {{work.title}}+- Kind: {{work.kind}}+- Status: {{work.status}}++## Prose before the cursor++```+{{before}}+```++## Prose after the cursor++```+{{after}}+```++## Selected passage (the writer is focused here — may be empty)++```+{{selection}}+```++## Task++From the prose around the cursor, propose a short Creative Director **treatment** — a tiny film treatment for the next stretch of story. It has three parts:++1. A one-line **logline** for the sequence.+2. A short **synopsis** (2–4 sentences) of what happens across the scenes.+3. A **visual treatment** (`styleSpec`): the overall look — palette, lighting, mood, lens/cinematography feel — that should carry across every scene. One short paragraph.+4. **2 to 6 scenes**, each a single filmable beat. For each scene:+ - `intent`: the dramatic purpose / the beat or alternate-scene direction (1–2 sentences).+ - `prompt`: a concrete visual shot description an image/video model could render — subject, action, framing, setting. Write it as a vivid prompt, not a sentence of narration.+ - `durationSeconds`: how long the shot should run, an integer from 1 to 10.++Stay faithful to the established setting, tone, and characters. Prefer concrete, visual moves over abstract description. If the selected passage is non-empty, treat it as the focus and build the sequence around it.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "logline": "string",+ "synopsis": "string",+ "styleSpec": "string",+ "scenes": [+ { "intent": "string", "prompt": "string", "durationSeconds": 5 }+ ]+}+```diff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdindex 59c063b585..0e43242468 100644--- a/docs/features/writers-room.md+++ b/docs/features/writers-room.md@@ -541,9 +541,9 @@ Exit criteria:Goal: evolve from manual passes to controlled live assistance.- Optional live story continuation suggestions while writing. **[shipped]**-- Optional render previews on selected scenes. *(planned)*+- Optional render previews on selected scenes. **[shipped]**- Creative Director can propose next beats, alternate scenes, and visual- treatments from the active cursor context. *(planned)*+ treatments from the active cursor context. **[shipped]**- Add throttling, debouncing, budget controls, and explicit opt-in per work. **[shipped]**This phase should wait until manual analysis quality, mapping, and render costs@@ -566,10 +566,18 @@ Backed by the `writers-room-continue` prompt stage (quick tier) and`server/services/writersRoom/liveDirector.js`; per-work live config persists onthe work manifest.-**Still planned for this phase:** live render previews on selected scenes from-the cursor context, and a Creative Director bridge that proposes next-beats/alternate scenes/visual treatments (injecting into a CD treatment) rather-than only prose continuations.+**Shipped (Creative Director bridge slice):** alongside the inline prose+continuations, the live-mode sidebar can turn the prose around the cursor into a+short Creative Director **treatment** — a logline, synopsis, an overall visual+treatment (palette/lighting/cinematography), and 2–6 filmable scenes (each a+beat + a visual prompt + a duration). The writer reviews the proposal in the+"CD Bridge" panel and, with one click, sends it into a **new Creative Director+project** seeded with that treatment and visual style — then jumps straight to+it via an "Open in Creative Director" link on the work menu. The bridge is+non-destructive (it always creates a fresh project, never overwrites an existing+one) and draws on the same per-work opt-in and daily suggestion budget as the+continuation panel. Backed by the `writers-room-cd-bridge` prompt stage and the+existing Creative Director treatment store.## Test Plandiff --git a/docs/plans/2026-06-05-issue-842-writers-room-cd-bridge.md b/docs/plans/2026-06-05-issue-842-writers-room-cd-bridge.mdnew file mode 100644index 0000000000..81a15284b7--- /dev/null+++ b/docs/plans/2026-06-05-issue-842-writers-room-cd-bridge.md@@ -0,0 +1,77 @@+# Issue #842 — Writers Room ↔ Creative Director bridge (Phase 5, slice 3)++## Context++Writers Room Phase 5 ("realtime Creative Director feedback") shipped two of three slices: **live continuation** (PR #837 — inline beat/prose/dialogue options from cursor context) and **live render previews** (#841). This is the **third and final slice** (#842): from the cursor context, let the Creative Director propose *next beats, alternate scenes, and visual treatments* — and **bridge those into actual Creative Director state** (a CD project's `treatment.scenes` + project `styleSpec`), not just inline prose.++Unlike the shipped `writers-room-continue` stage (which returns inline prose), this produces a **CD treatment proposal** the writer reviews and sends into Creative Director. It reuses the established WR→downstream bridge model (`promoteToPipeline` + `linkToPipeline` + an "Open in pipeline" CTA) rather than inventing new linkage, and reuses the CD orchestration helpers/store rather than duplicating CD logic — exactly as the issue requests.++**Confirmed design decisions (asked + answered):**+- **Injection:** create a NEW CD project seeded with the proposal (non-destructive), recording a `cdProjectId` link on the WR manifest with an "Open in Creative Director" CTA. Mirrors `promoteToPipeline`. (Reusing/clobbering one linked project was rejected — it fights `setTreatment`'s whole-treatment-replace semantics.)+- **Budget:** the bridge's LLM proposal call draws on the **existing** `dailyCallBudget` / `usage` text-suggest counter (both are text calls) — no new budget field/migration.++## Approach++A two-step flow mirroring the continuation slice's shape: **(1) suggest** (LLM, budget-gated) returns a reviewable proposal; **(2) send** (no LLM) creates a CD project from the proposal and links it.++### Server++**1. Prompt stage** — `data.reference/prompts/stages/writers-room-cd-bridge.md` (new)+- Sibling of `writers-room-continue.md`. Same cursor-context variables (`work`, `before`, `after`, `selection`, `returnsJson`).+- Task: propose a Creative Director **treatment** from the cursor context — a logline, short synopsis, **2–6 scenes** (each: `intent` = the beat/alternate-scene direction, `prompt` = a visual/cinematic shot description, `durationSeconds` 1–10), plus a `styleSpec` (the overall **visual treatment**: palette, mood, cinematography). Output contract is strict JSON: `{ logline, synopsis, styleSpec, scenes: [{ intent, prompt, durationSeconds }] }`.++**2. stage-config** — add `writers-room-cd-bridge` entry to `data.reference/prompts/stage-config.json` (model `quick`, `returnsJson: true`, `variables: []`), matching the `writers-room-continue` entry.++**3. Migration** — `scripts/migrations/071-writers-room-cd-bridge-prompt.js` (+ `.test.js`)+- Seed-only copy + stage-config merge, **byte-for-byte mirror of `065-writers-room-continue-prompt.js`** (FIRST-SHIPMENT SEED ONLY, no MD5 hashing). `data/` is gitignored, so the new stage must ship via `data.reference/` AND be seeded into existing installs that `pull + pm2 restart` without re-running `setup-data.js`. (Note: `070-` is already used twice; this takes `071-`.)++**4. Service** — `server/services/writersRoom/liveDirector.js` (extend)+- `suggestCdBridge(workId, { before, after, selection })`: reuse `assertLiveBudget(live, { usage: live.usage, budget: live.dailyCallBudget, label: 'suggestion' })` (same gate as `suggestContinuation`), require some cursor prose, `runStagedLLM('writers-room-cd-bridge', …)`, shape the proposal (clamp scenes 2–6, coerce `durationSeconds` into 1–10, trim strings), charge budget via `recordLiveModeUsage`. Returns `{ proposal, usage, budget }`.+- `sendToCreativeDirector(workId, { proposal })`: no LLM/budget. `createProject(...)` (from `creativeDirector/local.js`) with `name = work.title`, `styleSpec = proposal.styleSpec`, and CD render defaults (aspectRatio/quality/modelId/targetDurationSeconds — reuse the CD New-Project defaults from `creativeDirectorPresets.js`); then `setTreatment(project.id, { logline, synopsis, scenes })` where the service assigns each scene a `sceneId` (`randomUUID`), `order` (index), and `useContinuationFromPrior: false` to satisfy `creativeDirectorSceneSchema`. Finally `linkToCreativeDirector(workId, { projectId: project.id })`. Returns `{ project }`. Wrap create→treatment→link in try/catch with `deleteProject` rollback on failure (mirrors `promoteToPipeline`'s orphan-cleanup rationale — multi-step write, re-throw after cleanup).++**5. Manifest link** — `server/services/writersRoom/local.js` (extend)+- `linkToCreativeDirector(id, { projectId = null })`: set `cdProjectId` on the manifest (mirror of `linkToPipeline`; not user-editable, so it lives outside `updateWork`). `updateWork`'s `allowed` list already excludes it, so a crafted PATCH can't set it.++**6. Validation** — `server/lib/validation.js` (extend)+- `writersRoomCdBridgeSuggestSchema`: identical to `writersRoomLiveSuggestSchema` (before/after/selection, same caps, `.strict()`).+- `writersRoomCdBridgeSendSchema`: the reviewed proposal — `{ logline (1–500), synopsis (1–5000), styleSpec (max 5000 default ''), scenes: array(2..?).of({ intent 1–1000, prompt 1–8000, durationSeconds 1–10 }).min(1).max(120) }`, `.strict()`. Caps align with `creativeDirectorTreatmentSchema` so `setTreatment` won't 400 after the gate passes.++**7. Routes** — `server/routes/writersRoom.js` (extend, in the Phase-5 live block)+- `POST /works/:id/cd-bridge/suggest` → `validateRequest(writersRoomCdBridgeSuggestSchema, …)` → `suggestCdBridge`. (409 live-off / 429 budget already mapped from the service's coded `ServerError`s.)+- `POST /works/:id/cd-bridge/send` → `validateRequest(writersRoomCdBridgeSendSchema, …)` → `sendToCreativeDirector`. No new route middleware; bubbles to centralized error handler (no try/catch in handlers).++### Client++**8. API** — `client/src/services/apiWritersRoom.js` (extend)+- `suggestWritersRoomCdBridge(workId, context, options)` and `sendWritersRoomCdBridge(workId, proposal, options)` — same shape as `suggestWritersRoomContinuation` (POST, `{ silent: true }` passthrough since the panel owns its error UI).++**9. Panel** — `client/src/components/writers-room/CdBridgePanel.jsx` (new)+- Modeled on `LiveContinuationPanel.jsx`: a presentation + fetch shell driven by a parent-supplied `getCursorContext`; **no timers** (manual "Propose treatment" button — this is a heavier, deliberate action, not a debounced-on-pause one). Same overlapping-call generation guard + `useMounted`, same inline 409/429 notices (not red toasts), same "N / budget left today" readout sourced from `liveMode.usage`/`dailyCallBudget` (shared text budget).+- Renders the proposal: logline, synopsis, visual-treatment (`styleSpec`) block, and the scene list (`intent` + `prompt` + duration). A **"Send to Creative Director"** button calls `sendWritersRoomCdBridge`; on success toasts, calls `onLinked?.(projectId)` (parent updates manifest with `cdProjectId`), and navigates to the CD project route.++**10. Editor wiring** — `client/src/components/writers-room/WorkEditor.jsx` (extend)+- Render `<CdBridgePanel>` in the live-mode sidebar block alongside `LiveRenderPanel`/`LiveContinuationPanel` (gated on `liveEnabled && viewMode === 'edit'`), passing `workId`, `liveMode`, `getCursorContext` (already defined), and an `onLinked` that optimistically sets `cdProjectId` via `onChange?.({ ...work, cdProjectId })`.+- Add an **"Open in Creative Director"** overflow-menu item (icon `ExternalLink`) shown when `work.cdProjectId` is set — mirrors the existing "Open in pipeline" item; navigates to the CD project route. (Verify the exact client route for a CD project detail page — `apiCreativeDirector` uses `/creative-director`; confirm the React route, expected `/creative-director/:id`, before wiring nav.)++### Docs + changelog+- `docs/features/writers-room.md`: flip the two "*(planned)*" CD-bridge lines + the "**Still planned**" paragraph to shipped, with a short description of the bridge (matches the live-continuation write-up's tone).+- `.changelog/NEXT.md`: user-facing entry, slug-bracketed: `**[issue-842] Send a draft into Creative Director from the editor** — …`.++## Files++- New: `data.reference/prompts/stages/writers-room-cd-bridge.md`, `scripts/migrations/071-writers-room-cd-bridge-prompt.js` (+ test), `client/src/components/writers-room/CdBridgePanel.jsx`+- Edit: `data.reference/prompts/stage-config.json`, `server/services/writersRoom/liveDirector.js`, `server/services/writersRoom/local.js`, `server/lib/validation.js`, `server/routes/writersRoom.js`, `client/src/services/apiWritersRoom.js`, `client/src/components/writers-room/WorkEditor.jsx`, `docs/features/writers-room.md`, `.changelog/NEXT.md`++## Reuse (do not re-implement)+- `assertLiveBudget`, `recordLiveModeUsage`, `resolveLiveMode`, `utcDayKey`, `ERR_LIVE_MODE_OFF`/`ERR_BUDGET_EXCEEDED` — `liveDirector.js` / `local.js`+- `createProject`, `setTreatment`, `deleteProject` — `creativeDirector/local.js`+- `creativeDirectorTreatmentSchema`, `creativeDirectorSceneSchema`, `writersRoomLiveSuggestSchema` — `validation.js`+- `linkToPipeline` / "Open in pipeline" / `promoteToPipeline` rollback pattern — bridge precedent+- `LiveContinuationPanel.jsx` generation-guard + inline-notice pattern; `useMounted`+- Migration `065-writers-room-continue-prompt.js` — exact seed-migration template++## Verification+- `cd server && npm test -- liveDirector` and `-- validation` / `-- writersRoom` (route + service); add cases: suggest charges budget + 409/429 gating reuses text counter; send creates project + sets treatment + links manifest + rolls back on `setTreatment` failure.+- `cd server && npm test -- migrations` (or run the 071 test) — seeds when missing, no-ops when present.+- Barrel/README invariants: no new `server/lib` or `client/src/lib` modules added, so `index.test.js` is unaffected; confirm.+- Manual: enable Live mode on a work, place cursor in prose, "Propose treatment" → review → "Send to Creative Director" → lands on a new CD project with the treatment scenes + styleSpec; the work menu now shows "Open in Creative Director". Confirm budget readout decrements and the shared text-suggest counter is the one charged.diff --git a/scripts/migrations/071-writers-room-cd-bridge-prompt.js b/scripts/migrations/071-writers-room-cd-bridge-prompt.jsnew file mode 100644index 0000000000..101ad2857c--- /dev/null+++ b/scripts/migrations/071-writers-room-cd-bridge-prompt.js@@ -0,0 +1,83 @@+/**+ * Seed the Writers Room Creative-Director-bridge prompt stage into existing installs.+ *+ * Single-stage sibling of the other writers-room prompt seeds (see migration+ * 065): copies the `writers-room-cd-bridge.md` template from+ * `data.reference/prompts/stages/` and merges its stage-config entry into+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than+ * running the full setup) would otherwise leave the new stage unseeded and the+ * first cd-bridge suggest call would throw "Stage not found".+ *+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when+ * missing and never overwrites an install's existing prompt. A FUTURE migration+ * that AMENDS this prompt must follow migration 003's hash-driven pattern+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.+ */++import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';+import { dirname, join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++// The prompt file's basename doubles as its stage-config key (sans `.md`).+const STAGE = 'writers-room-cd-bridge';++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ // 1. Copy the prompt template if it's missing.+ const filename = `${STAGE}.md`;+ const dataPath = join(stagesDir, filename);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 writers-room prompt: ${filename} already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ writers-room: sample missing for ${filename} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${filename}`);+ } catch (err) {+ console.warn(`⚠️ writers-room: copy failed for ${filename}: ${err.message}`);+ }+ }+ }++ // 2. Merge the stage-config entry if it's missing.+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn('⚠️ writers-room: data.reference stage-config.json missing — skipping config write');+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};+ if (installed.stages[STAGE]) {+ console.log(`📝 writers-room stage-config: ${STAGE} already present`);+ return;+ }+ if (!sample?.stages?.[STAGE]) {+ console.warn(`⚠️ writers-room: sample stage-config missing ${STAGE} — skipping`);+ return;+ }+ installed.stages[STAGE] = sample.stages[STAGE];+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 writers-room stage-config (${action}): ${STAGE} added`);+ } catch (err) {+ console.warn(`⚠️ writers-room: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/071-writers-room-cd-bridge-prompt.test.js b/scripts/migrations/071-writers-room-cd-bridge-prompt.test.jsnew file mode 100644index 0000000000..e52b6c9891--- /dev/null+++ b/scripts/migrations/071-writers-room-cd-bridge-prompt.test.js@@ -0,0 +1,58 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './071-writers-room-cd-bridge-prompt.js';++const STAGE = 'writers-room-cd-bridge';+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 071 — seed Writers Room CD-bridge prompt', () => {+ let rootDir;+ let installedStagesDir;+ let installedConfigPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-071-'));+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ mkdirSync(refStagesDir, { recursive: true });+ writeFileSync(join(refStagesDir, `${STAGE}.md`), `# ${STAGE}\n\nbody\n`);+ const refConfig = { stages: { [STAGE]: { name: STAGE, model: 'quick', returnsJson: true, variables: [] } } };+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, null, 2) + '\n');++ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds the prompt file + stage-config entry on a fresh install', async () => {+ await migration.up({ rootDir });+ expect(existsSync(join(installedStagesDir, `${STAGE}.md`))).toBe(true);+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();+ });++ it('merges into an existing stage-config without clobbering other stages', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');+ await migration.up({ rootDir });+ const config = readJson(installedConfigPath);+ expect(config.stages['pipeline-prose']).toBeTruthy();+ expect(config.stages[STAGE]).toBeTruthy();+ });++ it('is idempotent and preserves a user-customized installed prompt', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ const customPath = join(installedStagesDir, `${STAGE}.md`);+ writeFileSync(customPath, '# CUSTOM bridge\n');+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ // Second run is a clean no-op.+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2c830b947c..bcbd4b3248 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -904,6 +904,33 @@ export const writersRoomLiveSuggestSchema = z.object({// payload (e.g. an attempt to smuggle a usage counter) instead of ignoring it.export const writersRoomLiveRenderPreviewSchema = z.object({}).strict();+// Cursor-context payload for the CD-bridge suggest route — identical shape to+// the live continuation suggest (the server only needs a window around the+// cursor, not the whole manuscript).+export const writersRoomCdBridgeSuggestSchema = z.object({+ before: z.string().max(12_000).optional().default(''),+ after: z.string().max(12_000).optional().default(''),+ selection: z.string().max(8_000).optional().default(''),+}).strict();++// The reviewed CD-bridge proposal the writer sends into a new Creative Director+// project. Caps align with creativeDirectorTreatmentSchema / creativeDirectorSceneSchema+// so a gate-passing proposal always validates again at setTreatment time. The+// scene shape here is the PROPOSAL subset (intent/prompt/duration); the service+// assigns sceneId/order/useContinuationFromPrior before calling setTreatment.+export const writersRoomCdBridgeSendSchema = z.object({+ proposal: z.object({+ logline: z.string().trim().min(1).max(500),+ synopsis: z.string().trim().min(1).max(5000),+ styleSpec: z.string().max(5000).optional().default(''),+ scenes: z.array(z.object({+ intent: z.string().trim().min(1).max(1000),+ prompt: z.string().trim().min(1).max(8000),+ durationSeconds: z.number().int().min(1).max(10),+ }).strict()).min(1).max(120),+ }).strict(),+}).strict();+export const writersRoomDraftSaveSchema = z.object({body: z.string().max(5_000_000), // 5 MB ceiling — well over a long novel in plain text// Catalog ingredient ids this draft version references. Optional: whendiff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex 20249c0da7..66e1f375c9 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -18,6 +18,8 @@ import {writersRoomAnalysisCreateSchema,writersRoomLiveSuggestSchema,writersRoomLiveRenderPreviewSchema,+ writersRoomCdBridgeSuggestSchema,+ writersRoomCdBridgeSendSchema,writersRoomCharacterCreateSchema,writersRoomCharacterUpdateSchema,writersRoomPlaceCreateSchema,@@ -36,7 +38,9 @@ import {runAnalysis, listAnalyses, getAnalysis, attachSceneImage,} from '../services/writersRoom/evaluator.js';import { getSyncedReview } from '../services/writersRoom/syncedReview.js';-import { suggestContinuation, reserveRenderPreview } from '../services/writersRoom/liveDirector.js';+import {+ suggestContinuation, reserveRenderPreview, suggestCdBridge, sendToCreativeDirector,+} from '../services/writersRoom/liveDirector.js';import {listCharacters, createCharacter, updateCharacter, deleteCharacter,} from '../services/writersRoom/characters.js';@@ -212,6 +216,25 @@ router.post('/works/:id/live-render-preview', asyncHandler(async (req, res) => {res.json(await reserveRenderPreview(req.params.id));}));+// Propose a Creative Director treatment (logline + synopsis + visual treatment+// + 2–6 filmable scenes) from the cursor context. Draws on the SAME daily+// call budget + opt-in as live-suggest (409 if off, 429 if spent). Returns+// { proposal, usage, budget } — proposal is null when the model couldn't+// produce a usable treatment.+router.post('/works/:id/cd-bridge/suggest', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomCdBridgeSuggestSchema, req.body || {});+ res.json(await suggestCdBridge(req.params.id, data));+}));++// Send a reviewed proposal into a NEW Creative Director project (non-destructive),+// seeding its treatment + styleSpec and recording the bridge link on the work+// manifest. No budget — the proposal was already generated + charged by the+// suggest call. Returns { project }.+router.post('/works/:id/cd-bridge/send', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomCdBridgeSendSchema, req.body || {});+ res.status(201).json(await sendToCreativeDirector(req.params.id, data));+}));+// ---------- synced review (Phase 4: prose ↔ script ↔ media) ----------// Read-model assembled on demand from the active draft's segment index and thediff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsindex f92e0ad5ec..705f63a598 100644--- a/server/routes/writersRoom.test.js+++ b/server/routes/writersRoom.test.js@@ -71,6 +71,20 @@ vi.mock('../services/writersRoom/liveDirector.js', () => ({renderUsage: { date: '2026-06-03', count: 1 },renderBudget: 20,})),+ suggestCdBridge: vi.fn(async () => ({+ proposal: {+ logline: 'A courier outruns the storm.',+ synopsis: 'Cross the flooded city.',+ styleSpec: 'Rain-slick neon.',+ scenes: [+ { intent: 'Deluge', prompt: 'Wide shot', durationSeconds: 6 },+ { intent: 'Run', prompt: 'Tracking shot', durationSeconds: 4 },+ ],+ },+ usage: { date: '2026-06-03', count: 1 },+ budget: 100,+ })),+ sendToCreativeDirector: vi.fn(async () => ({ project: { id: 'cd-1' } })),}));import * as svc from '../services/writersRoom/local.js';@@ -446,5 +460,50 @@ describe('writersRoom routes', () => {expect(r.status).toBe(400);expect(liveSvc.reserveRenderPreview).not.toHaveBeenCalled();});++ it('POST /works/:id/cd-bridge/suggest forwards the cursor context and returns a proposal', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/cd-bridge/suggest')+ .send({ before: 'The levee groaned.', after: '', selection: '' });+ expect(r.status).toBe(200);+ expect(r.body.proposal.scenes).toHaveLength(2);+ expect(liveSvc.suggestCdBridge).toHaveBeenCalledWith('wr-work-1', {+ before: 'The levee groaned.', after: '', selection: '',+ });+ });++ it('POST /works/:id/cd-bridge/suggest rejects an over-long before window', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/cd-bridge/suggest')+ .send({ before: 'x'.repeat(12_001) });+ expect(r.status).toBe(400);+ expect(liveSvc.suggestCdBridge).not.toHaveBeenCalled();+ });++ it('POST /works/:id/cd-bridge/send creates a CD project from the proposal', async () => {+ const proposal = {+ logline: 'A courier outruns the storm.',+ synopsis: 'Cross the flooded city.',+ styleSpec: 'Rain-slick neon.',+ scenes: [+ { intent: 'Deluge', prompt: 'Wide shot', durationSeconds: 6 },+ { intent: 'Run', prompt: 'Tracking shot', durationSeconds: 4 },+ ],+ };+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/cd-bridge/send')+ .send({ proposal });+ expect(r.status).toBe(201);+ expect(r.body.project.id).toBe('cd-1');+ expect(liveSvc.sendToCreativeDirector).toHaveBeenCalledWith('wr-work-1', { proposal });+ });++ it('POST /works/:id/cd-bridge/send rejects a proposal with an empty logline', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/cd-bridge/send')+ .send({ proposal: { logline: '', synopsis: 's', scenes: [{ intent: 'i', prompt: 'p', durationSeconds: 5 }] } });+ expect(r.status).toBe(400);+ expect(liveSvc.sendToCreativeDirector).not.toHaveBeenCalled();+ });});});diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.jsindex 4b22841f7f..a249ab1d04 100644--- a/server/services/writersRoom/liveDirector.js+++ b/server/services/writersRoom/liveDirector.js@@ -17,11 +17,20 @@ import { ServerError } from '../../lib/errorHandler.js';import { runStagedLLM } from '../../lib/stageRunner.js';import {getWork, resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, utcDayKey,+ linkToCreativeDirector,} from './local.js';+import { createProject, setTreatment, deleteProject } from '../creativeDirector/local.js';+import { defaultVideoModelId } from '../videoGen/local.js';import { badRequest } from './_shared.js';const STAGE = 'writers-room-continue';+const CD_BRIDGE_STAGE = 'writers-room-cd-bridge';const MAX_OPTIONS = 4;+// CD-bridge proposal bounds. The prompt asks for 2–6 filmable scenes; we clamp+// to that range (and the LLM may overshoot, so MAX is a hard cap) — well under+// creativeDirectorTreatmentSchema's 1..120, so a sent proposal always validates.+const MIN_BRIDGE_SCENES = 2;+const MAX_BRIDGE_SCENES = 6;// Surface the two soft-failure modes as typed codes so the route can map them// to the right HTTP status (live-mode off → 409 conflict; budget spent → 429).@@ -125,3 +134,138 @@ export async function reserveRenderPreview(workId) {const renderUsage = (await recordLiveModeRenderUsage(workId)).renderUsage;return { renderUsage, renderBudget: live.dailyRenderBudget };}++// Coerce one raw LLM scene into the shape the CD-bridge proposal carries.+// Returns null for an unusable scene (no intent/prompt) so the caller can drop+// it before clamping to the 2–6 range.+function shapeBridgeScene(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const intent = typeof raw.intent === 'string' ? raw.intent.trim() : '';+ const prompt = typeof raw.prompt === 'string' ? raw.prompt.trim() : '';+ if (!intent || !prompt) return null;+ // durationSeconds: round into the CD scene's 1..10 integer range; default to+ // a mid 5s when the model omits or fumbles it.+ const rawDur = Number(raw.durationSeconds);+ const durationSeconds = Number.isFinite(rawDur)+ ? Math.min(10, Math.max(1, Math.round(rawDur)))+ : 5;+ return { intent: intent.slice(0, 1000), prompt: prompt.slice(0, 8000), durationSeconds };+}++// Shape a raw LLM response into a CD treatment proposal. Trims the text fields+// to the CD treatment schema caps and clamps scenes to the 2–6 prompt range.+// Returns null when the response can't yield at least MIN_BRIDGE_SCENES usable+// scenes — the route surfaces that as an empty proposal, not a crash.+function shapeProposal(parsed) {+ const scenes = (Array.isArray(parsed?.scenes) ? parsed.scenes : [])+ .map(shapeBridgeScene)+ .filter(Boolean)+ .slice(0, MAX_BRIDGE_SCENES);+ if (scenes.length < MIN_BRIDGE_SCENES) return null;+ return {+ logline: typeof parsed?.logline === 'string' ? parsed.logline.trim().slice(0, 500) : '',+ synopsis: typeof parsed?.synopsis === 'string' ? parsed.synopsis.trim().slice(0, 5000) : '',+ styleSpec: typeof parsed?.styleSpec === 'string' ? parsed.styleSpec.trim().slice(0, 5000) : '',+ scenes,+ };+}++/**+ * Generate a Creative Director treatment proposal from the cursor context.+ * Unlike suggestContinuation (which returns inline prose options), this returns+ * a reviewable mini-treatment — logline, synopsis, visual treatment (styleSpec),+ * and 2–6 filmable scenes — that the writer can send into a new CD project.+ *+ * Reuses the SAME daily call budget + opt-in gate as the text-suggest path+ * (both are text LLM calls). Throws the coded 409 (live mode off) / 429 (budget+ * spent) ServerErrors the route maps to a status. On success returns+ * `{ proposal, usage, budget }`; `proposal` is null when the model couldn't+ * produce a usable treatment.+ */+export async function suggestCdBridge(workId, { before = '', after = '', selection = '' } = {}) {+ const manifest = await getWork(workId); // 404s if the work is missing+ const live = resolveLiveMode(manifest);+ assertLiveBudget(live, { usage: live.usage, budget: live.dailyCallBudget, label: 'suggestion' });++ if (!before.trim() && !after.trim() && !selection.trim()) {+ throw badRequest('Need some prose around the cursor to propose a treatment');+ }++ const variables = {+ work: { title: manifest.title, kind: manifest.kind, status: manifest.status },+ before, after, selection,+ returnsJson: true,+ };+ const { content } = await runStagedLLM(CD_BRIDGE_STAGE, variables, {+ source: 'writers-room-cd-bridge',+ returnsJson: true,+ });+ const proposal = shapeProposal(content);++ // Charge the shared text-suggest budget for every call that reached the LLM —+ // same rationale as suggestContinuation: the provider cost is incurred whether+ // or not the response parsed into a usable proposal.+ const usage = (await recordLiveModeUsage(workId)).usage;++ return { proposal, usage, budget: live.dailyCallBudget };+}++/**+ * Send a reviewed CD-bridge proposal into a NEW Creative Director project.+ * Non-destructive (never clobbers an existing project's treatment): it mints a+ * fresh CD project seeded with the work's title + the proposal's styleSpec, then+ * writes the treatment (logline/synopsis/scenes), then records the bridge link+ * on the WR manifest so the editor can show an "Open in Creative Director" CTA.+ *+ * No LLM, no budget — the proposal was already generated + charged by+ * suggestCdBridge; this is the cheap commit half. createProject + setTreatment+ * are wrapped so a setTreatment/link failure rolls back the orphaned project+ * (mirrors promoteToPipeline's orphan-cleanup rationale — multi-step write that+ * re-throws the original error after best-effort cleanup). Returns `{ project }`.+ */+export async function sendToCreativeDirector(workId, { proposal } = {}) {+ const manifest = await getWork(workId); // 404s if the work is missing++ // Assign the CD scene runtime fields the schema requires but the LLM proposal+ // doesn't carry: a stable sceneId, render order, and the continuation flag.+ const scenes = (proposal.scenes || []).map((s, i) => ({+ sceneId: `sc-${i + 1}`,+ order: i,+ intent: s.intent,+ prompt: s.prompt,+ durationSeconds: s.durationSeconds,+ useContinuationFromPrior: i > 0,+ }));++ // CD render defaults — match the client New-Project form (16:9 / standard /+ // 60s) and resolve the default video model server-side so a bridged project+ // doesn't start on a legacy backend.+ const project = await createProject({+ name: manifest.title,+ aspectRatio: '16:9',+ quality: 'standard',+ modelId: defaultVideoModelId(),+ targetDurationSeconds: 60,+ styleSpec: proposal.styleSpec || '',+ });++ // setTreatment returns the full project with the treatment applied — capture+ // it so the route can return the seeded project without a re-read.+ let withTreatment;+ try {+ withTreatment = await setTreatment(project.id, {+ logline: proposal.logline,+ synopsis: proposal.synopsis,+ scenes,+ });+ await linkToCreativeDirector(workId, { projectId: project.id });+ } catch (err) {+ // Roll back the orphaned project so a validation/link failure doesn't leave+ // a treatment-less project behind with no manifest link. Best-effort —+ // swallow the cleanup error so the original cause reaches the caller.+ await deleteProject(project.id).catch(() => {});+ throw err;+ }++ return { project: withTreatment };+}diff --git a/server/services/writersRoom/liveDirector.test.js b/server/services/writersRoom/liveDirector.test.jsindex b576b3ea00..54cb98f160 100644--- a/server/services/writersRoom/liveDirector.test.js+++ b/server/services/writersRoom/liveDirector.test.js@@ -15,15 +15,32 @@ vi.mock('../../lib/fileUtils.js', async () => {const runStagedLLM = vi.fn();vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLM(...a) }));+// Mock the Creative Director store + video-model helper so the CD-bridge send+// path is a focused unit test of the orchestration (create → setTreatment →+// link → rollback) without dragging in media-collection side effects.+const createProject = vi.fn();+const setTreatment = vi.fn();+const deleteProject = vi.fn();+vi.mock('../creativeDirector/local.js', () => ({+ createProject: (...a) => createProject(...a),+ setTreatment: (...a) => setTreatment(...a),+ deleteProject: (...a) => deleteProject(...a),+}));+vi.mock('../videoGen/local.js', () => ({ defaultVideoModelId: () => 'ltxv-default' }));+const local = await import('./local.js');const { createWork, updateWork, getWork } = local;const {- suggestContinuation, reserveRenderPreview, ERR_LIVE_MODE_OFF, ERR_BUDGET_EXCEEDED,+ suggestContinuation, reserveRenderPreview, suggestCdBridge, sendToCreativeDirector,+ ERR_LIVE_MODE_OFF, ERR_BUDGET_EXCEEDED,} = await import('./liveDirector.js');beforeEach(() => {tempRoot = mkdtempSync(join(tmpdir(), 'wr-live-test-'));runStagedLLM.mockReset();+ createProject.mockReset();+ setTreatment.mockReset();+ deleteProject.mockReset();});afterEach(() => {@@ -180,3 +197,116 @@ describe('reserveRenderPreview', () => {expect(res.renderUsage).toMatchObject({ date: '2026-06-04', count: 1 });});});++const BRIDGE_RESPONSE = {+ content: {+ logline: 'A courier outruns the storm.',+ synopsis: 'She must cross the flooded city before the levee breaks.',+ styleSpec: 'Rain-slick neon, handheld, teal-and-amber.',+ scenes: [+ { intent: 'Establish the deluge', prompt: 'Wide shot of a drowned street, neon reflections', durationSeconds: 6 },+ { intent: 'The courier runs', prompt: 'Tracking shot, sprinting through ankle-deep water', durationSeconds: 4.4 },+ ],+ },+};++describe('suggestCdBridge', () => {+ it('throws LIVE_MODE_OFF when the work has not opted in', async () => {+ const work = await createWork({ title: 'Off' });+ await expect(suggestCdBridge(work.id, { before: 'words here' }))+ .rejects.toMatchObject({ code: ERR_LIVE_MODE_OFF, status: 409 });+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('shapes a proposal, clamps duration, and charges the SHARED suggest budget', async () => {+ runStagedLLM.mockResolvedValue(BRIDGE_RESPONSE);+ const work = await createWork({ title: 'On' });+ await updateWork(work.id, { liveMode: { enabled: true } });++ const res = await suggestCdBridge(work.id, { before: 'The door creaked open.' });+ expect(res.proposal.logline).toBe('A courier outruns the storm.');+ expect(res.proposal.scenes).toHaveLength(2);+ expect(res.proposal.scenes[1].durationSeconds).toBe(4); // 4.4 → rounded into 1..10+ // Draws on the same daily call budget as suggestContinuation (not a render slot).+ expect(res.usage.count).toBe(1);+ const reloaded = await getWork(work.id);+ expect(reloaded.liveMode.renderUsage).toMatchObject({ count: 0 });+ });++ it('returns a null proposal (but still charges budget) when fewer than 2 usable scenes come back', async () => {+ runStagedLLM.mockResolvedValue({ content: { logline: 'x', synopsis: 'y', styleSpec: 'z', scenes: [{ intent: 'only one', prompt: 'shot' }] } });+ const work = await createWork({ title: 'Thin' });+ await updateWork(work.id, { liveMode: { enabled: true } });++ const res = await suggestCdBridge(work.id, { before: 'something' });+ expect(res.proposal).toBeNull();+ expect(res.usage.count).toBe(1); // reached the LLM → charged+ });++ it('shares the daily budget with suggestContinuation (one pool, not two)', async () => {+ runStagedLLM.mockResolvedValue(BRIDGE_RESPONSE);+ const work = await createWork({ title: 'Shared' });+ await updateWork(work.id, { liveMode: { enabled: true, dailyCallBudget: 1 } });++ await suggestCdBridge(work.id, { before: 'first' }); // count -> 1+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ await expect(suggestContinuation(work.id, { before: 'second' }))+ .rejects.toMatchObject({ code: ERR_BUDGET_EXCEEDED, status: 429 });+ });++ it('rejects an empty cursor context before spending an LLM call', async () => {+ const work = await createWork({ title: 'Blank' });+ await updateWork(work.id, { liveMode: { enabled: true } });+ await expect(suggestCdBridge(work.id, { before: ' ', after: '', selection: '' }))+ .rejects.toThrow(/prose around the cursor/);+ expect(runStagedLLM).not.toHaveBeenCalled();+ });+});++describe('sendToCreativeDirector', () => {+ const PROPOSAL = {+ logline: 'A courier outruns the storm.',+ synopsis: 'Cross the flooded city before the levee breaks.',+ styleSpec: 'Rain-slick neon.',+ scenes: [+ { intent: 'Establish the deluge', prompt: 'Wide shot', durationSeconds: 6 },+ { intent: 'The courier runs', prompt: 'Tracking shot', durationSeconds: 4 },+ ],+ };++ it('creates a project, seeds the treatment, and records the manifest link', async () => {+ createProject.mockResolvedValue({ id: 'cd-1' });+ setTreatment.mockImplementation(async (id, treatment) => ({ id, treatment }));+ const work = await createWork({ title: 'My Draft' });++ const res = await sendToCreativeDirector(work.id, { proposal: PROPOSAL });++ // Project created with work title + styleSpec + a resolved (non-legacy) model.+ expect(createProject).toHaveBeenCalledWith(expect.objectContaining({+ name: 'My Draft', styleSpec: 'Rain-slick neon.', modelId: 'ltxv-default',+ }));+ // Treatment scenes carry the runtime fields the schema needs.+ const [, treatment] = setTreatment.mock.calls[0];+ expect(treatment.scenes[0]).toMatchObject({ sceneId: 'sc-1', order: 0, useContinuationFromPrior: false });+ expect(treatment.scenes[1]).toMatchObject({ sceneId: 'sc-2', order: 1, useContinuationFromPrior: true });+ expect(res.project).toMatchObject({ id: 'cd-1' });++ // The bridge link is persisted on the work manifest.+ const reloaded = await getWork(work.id);+ expect(reloaded.cdProjectId).toBe('cd-1');+ });++ it('rolls back the orphaned project when setTreatment fails, and leaves the work unlinked', async () => {+ createProject.mockResolvedValue({ id: 'cd-orphan' });+ setTreatment.mockRejectedValue(new Error('treatment invalid'));+ deleteProject.mockResolvedValue({ ok: true });+ const work = await createWork({ title: 'Doomed' });++ await expect(sendToCreativeDirector(work.id, { proposal: PROPOSAL }))+ .rejects.toThrow(/treatment invalid/);+ expect(deleteProject).toHaveBeenCalledWith('cd-orphan');++ const reloaded = await getWork(work.id);+ expect(reloaded.cdProjectId ?? null).toBeNull();+ });+});diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsindex bb21538f7b..6e7a5fb577 100644--- a/server/services/writersRoom/local.js+++ b/server/services/writersRoom/local.js@@ -408,6 +408,25 @@ export async function linkToPipeline(id, { seriesId = null, issueId = null } = {return next;}+/**+ * Bidirectional bridge link: record that this work seeded a Creative Director+ * project (Phase 5 CD-bridge slice). Set once by liveDirector.sendToCreativeDirector;+ * the WR side reads it to render the "Open in Creative Director" CTA on the work+ * detail page. Distinct from `updateWork` because the link isn't user-editable+ * (the allow-list in updateWork excludes it, so a crafted PATCH can't set it).+ * Mirrors `linkToPipeline`. Pass `null` to unlink.+ */+export async function linkToCreativeDirector(id, { projectId = null } = {}) {+ const manifest = await getWork(id);+ const next = {+ ...manifest,+ cdProjectId: projectId ? String(projectId).slice(0, 64) : null,+ updatedAt: nowIso(),+ };+ await saveManifest(id, next);+ return next;+}+// UTC day key (YYYY-MM-DD) for the daily budget window. UTC (not local) so the// reset boundary is deterministic across machines a single user federates.// Exported so the live-director's pre-call budget check compares against the