Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2185]): CD ⇄ Series Autopilot bridge, both directions (CDO Phase 3)

Adam Eivy2aede5daafe7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 43e62cc0f9..2034e5e28c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -157,6 +157,8 @@
## Creative Director
+- **[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`)
## Internal
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index 216b26f3cd..c670dfa179 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -212,6 +212,12 @@ export const pipelineEditorialChecksSettingsSchema = z.object({
// informational signal — so this is the one autopilot setting that's opt-OUT.
// Optional + additive so older peers fall through to the default.
notifyOnPause: z.boolean().optional(),
+ // Autopilot → CD teaser deliverable (CDO Phase 3, #2185). When on, once a comic
+ // issue is text-ready + drafted the autopilot OPTIONALLY mints + starts a
+ // Creative Director teaser/trailer video project seeded from it. Defaults OFF
+ // (opt-in) — producing video is a fresh burst of LLM + render spend. Optional +
+ // additive so older peers fall through to off.
+ produceTeaser: z.boolean().optional(),
}).strict();
// Cursor-context payload for the CD-bridge suggest route — identical shape to
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index 9477c38b32..4aba2a3509 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -78,6 +78,10 @@ const autopilotStartSchema = z.object({
// pipelineEditorialChecks.notifyOnPause, then true (on by default — a zero-cost
// informational signal). Set false to silence pause notifications for this run.
notifyOnPause: z.boolean().optional(),
+ // Autopilot → CD teaser deliverable (CDO Phase 3, #2185). When true, once every
+ // comic issue is drafted the run mints + starts a Creative Director teaser video
+ // per issue. Falls back to pipelineEditorialChecks.produceTeaser, then off.
+ produceTeaser: z.boolean().optional(),
});
router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {
diff --git a/server/services/creative/toolRegistry.js b/server/services/creative/toolRegistry.js
index 8b45567b4f..87dd437055 100644
--- a/server/services/creative/toolRegistry.js
+++ b/server/services/creative/toolRegistry.js
@@ -30,6 +30,7 @@ import { WRITERS_ROOM_TOOLS } from './tools/writersRoom.js';
import { PIPELINE_TOOLS } from './tools/pipeline.js';
import { MEDIA_TOOLS } from './tools/media.js';
import { CATALOG_TOOLS } from './tools/catalog.js';
+import { CD_TOOLS } from './tools/cd.js';
// The daily action budget the creative gate charges against. Creative
// orchestration mirrors the cos autonomy posture (see getCreativeAutonomyMode),
@@ -46,6 +47,7 @@ export const CREATIVE_TOOLS = [
...PIPELINE_TOOLS,
...MEDIA_TOOLS,
...CATALOG_TOOLS,
+ ...CD_TOOLS,
];
const COST_SET = new Set(COST_CLASSES);
diff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.js
index 977f9db323..d0f8d17275 100644
--- a/server/services/creative/toolRegistry.test.js
+++ b/server/services/creative/toolRegistry.test.js
@@ -100,10 +100,10 @@ beforeEach(() => {
});
describe('registry shape', () => {
- it('registers the six-domain tool inventory with unique names', () => {
+ it('registers the seven-domain tool inventory with unique names', () => {
const names = getAllCreativeToolNames();
expect(new Set(names).size).toBe(names.length);
- for (const prefix of ['universe_', 'storyBuilder_', 'writersRoom_', 'pipeline_', 'media_', 'catalog_']) {
+ for (const prefix of ['universe_', 'storyBuilder_', 'writersRoom_', 'pipeline_', 'media_', 'catalog_', 'cd_']) {
expect(names.some((n) => n.startsWith(prefix))).toBe(true);
}
});
diff --git a/server/services/creative/tools/cd.js b/server/services/creative/tools/cd.js
new file mode 100644
index 0000000000..15b18c53be
--- /dev/null
+++ b/server/services/creative/tools/cd.js
@@ -0,0 +1,41 @@
+/**
+ * Creative-Director-domain creative tools (CDO Phase 3, #2185). The
+ * pipeline/autopilot → Creative Director direction of the bridge: mint + start a
+ * fresh CD teaser/trailer video project seeded from a pipeline issue. Wraps the
+ * `produceVideoFromIssue` conductor (createProject + setTreatment + auto-cast +
+ * start — never mutates an existing project's treatment, the #842 rule).
+ */
+
+import { z } from 'zod';
+import { produceVideoFromIssue } from '../../creativeDirector/bridgeFromIssue.js';
+import { COST_LLM } from './shared.js';
+
+export const CD_TOOLS = [
+ {
+ name: 'cd_produceVideoFromIssue',
+ description:
+ 'Mint AND start a fresh Creative Director teaser/trailer video project seeded from a pipeline issue. '
+ + 'Generates a treatment from the issue\'s prose/script + series canon, auto-casts the series ingredients, links the source issue (for the music bed), and kicks off rendering. '
+ + 'Non-destructive: always creates a NEW project, never overwrites an existing one. Costs one LLM call for the treatment; the project\'s renders proceed asynchronously.',
+ costClass: COST_LLM,
+ schema: z.object({
+ issueId: z.string().min(1),
+ name: z.string().max(200).optional(),
+ aspectRatio: z.enum(['16:9', '9:16', '1:1']).optional(),
+ quality: z.enum(['draft', 'standard', 'high']).optional(),
+ targetDurationSeconds: z.number().int().min(5).max(600).optional(),
+ }),
+ parameters: {
+ type: 'object',
+ properties: {
+ issueId: { type: 'string', description: 'Pipeline issue id to seed the teaser from (required).' },
+ name: { type: 'string', description: 'Project name (defaults to "<issue title> — Teaser").' },
+ aspectRatio: { type: 'string', enum: ['16:9', '9:16', '1:1'], description: 'Video aspect ratio (default 16:9).' },
+ quality: { type: 'string', enum: ['draft', 'standard', 'high'], description: 'Render quality (default standard).' },
+ targetDurationSeconds: { type: 'integer', description: 'Target teaser length in seconds (5–600, default 60).' },
+ },
+ required: ['issueId'],
+ },
+ execute: ({ issueId, ...options }) => produceVideoFromIssue(issueId, options),
+ },
+];
diff --git a/server/services/creativeDirector/bridgeFromIssue.js b/server/services/creativeDirector/bridgeFromIssue.js
new file mode 100644
index 0000000000..d993c5e6f2
--- /dev/null
+++ b/server/services/creativeDirector/bridgeFromIssue.js
@@ -0,0 +1,166 @@
+/**
+ * Creative Director — produce a video from a pipeline issue (CDO Phase 3, #2185).
+ *
+ * The autopilot/pipeline → Creative Director direction of the bridge: take a
+ * finished pipeline issue (its prose / comic script + the series context) and
+ * mint a FRESH Creative Director video project — a teaser/trailer — seeded from
+ * it, then start it. This is the #842 write pattern (createProject + setTreatment
+ * + link, never clobber an existing project) applied to a pipeline issue instead
+ * of a writers-room work.
+ *
+ * Conductor, not re-implementation:
+ * - Treatment is generated by the SAME `writers-room-cd-bridge` stage +
+ * `shapeProposal` shaper the WR→CD send path uses (imported from
+ * liveDirector.js) — the treatment-from-prose contract lives in one place.
+ * - Casting reuses `applyAutoCastToProject` so the series' catalog ingredients
+ * (canon characters/places/objects) are pulled into CD casting AND linked as
+ * `ref_kind: 'creative-director'` refs, exactly like the manual remix path —
+ * autonomous and manual paths converge on the same ingredients.
+ * - The project is STARTED via `startCreativeDirectorProject` (the same entry
+ * the Start button and the plan-advance loop call).
+ *
+ * `startCreativeDirectorProject` is imported dynamically inside the function to
+ * keep the module graph acyclic: it pulls in the CD plan-advance loop → the
+ * creative tool registry → the pipeline tools → seriesAutopilot, and this module
+ * is itself reachable from seriesAutopilot's teaser step.
+ */
+
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import {
+ CD_BRIDGE_STAGE,
+ shapeProposal,
+ bridgeScenesToTreatmentScenes,
+} from '../writersRoom/liveDirector.js';
+import { getIssue } from '../pipeline/issues.js';
+import { getSeries } from '../pipeline/series.js';
+import { defaultVideoModelId } from '../videoGen/local.js';
+import { createProject, setTreatment, deleteProject } from './local.js';
+import { applyAutoCastToProject } from './autoCast.js';
+import { deleteCollection } from '../mediaCollections.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+// Cap the source prose fed to the treatment stage — a full 24-page script would
+// blow the context window; the CD bridge only needs enough to shape a teaser.
+const SOURCE_PROSE_MAX = 12000;
+
+// Prefer the finished prose draft as the teaser's source (it's continuous
+// narrative the treatment stage reads best); fall back to the comic script, then
+// the beat sheet. Returns '' when the issue carries no usable text.
+function issueSourceProse(issue) {
+ const stages = issue?.stages || {};
+ const text = stages.prose?.output || stages.comicScript?.output || stages.idea?.output || '';
+ const trimmed = typeof text === 'string' ? text.trim() : '';
+ return trimmed.length > SOURCE_PROSE_MAX ? trimmed.slice(0, SOURCE_PROSE_MAX) : trimmed;
+}
+
+// Assemble a casting brief from the series + issue context so autoCast's hybrid
+// search pulls the right canon ingredients. Series premise + issue title/logline
+// name the characters/places the teaser should feature.
+function deriveTeaserBrief(series, issue, proposal) {
+ return [series?.name, series?.premise, issue?.title, proposal?.logline, proposal?.synopsis]
+ .filter((v) => typeof v === 'string' && v.trim())
+ .map((v) => v.trim())
+ .join('\n\n');
+}
+
+/**
+ * Produce a Creative Director teaser/trailer video project from a pipeline issue.
+ *
+ * Steps: load the issue + series → generate a treatment proposal from the issue's
+ * prose via the CD-bridge stage → mint a fresh CD project (seeded with
+ * `sourceIssueId` so the stitch step mixes in the issue's audio-stage music) →
+ * apply the treatment → auto-cast the series canon → start it. The multi-step
+ * write rolls back the orphaned project + its media collection on a failure after
+ * create (mirrors sendToCreativeDirector's orphan-cleanup).
+ *
+ * @param {string} issueId
+ * @param {{ providerDefault?: string, modelDefault?: string, name?: string,
+ * aspectRatio?: string, quality?: string, targetDurationSeconds?: number }} [options]
+ * @returns {Promise<{ project: object, proposal: object }>}
+ */
+export async function produceVideoFromIssue(issueId, options = {}) {
+ const issue = await getIssue(issueId);
+ if (!issue) throw new ServerError('Issue not found', { status: 404, code: 'NOT_FOUND' });
+ const series = await getSeries(issue.seriesId).catch(() => null);
+
+ const before = issueSourceProse(issue);
+ if (!before) {
+ throw new ServerError(
+ 'Issue has no prose / script to build a teaser from — generate its text stages first.',
+ { status: 400, code: 'NO_SOURCE_PROSE' },
+ );
+ }
+
+ // Reuse the SAME CD-bridge stage the writers-room send path uses. `work`
+ // carries the series/issue framing; the issue prose is the cursor context.
+ const variables = {
+ work: {
+ title: issue.title || series?.name || 'Untitled',
+ kind: 'comic',
+ status: 'ready',
+ },
+ before,
+ after: '',
+ selection: '',
+ returnsJson: true,
+ };
+ const stageOpts = { source: 'pipeline-cd-teaser', returnsJson: true };
+ if (options.providerDefault) stageOpts.providerDefault = options.providerDefault;
+ if (options.modelDefault) stageOpts.modelDefault = options.modelDefault;
+ const { content } = await runStagedLLM(CD_BRIDGE_STAGE, variables, stageOpts);
+ const proposal = shapeProposal(content);
+ if (!proposal) {
+ throw new ServerError(
+ 'The model could not produce a usable teaser treatment from this issue.',
+ { status: 422, code: 'NO_TREATMENT' },
+ );
+ }
+
+ const scenes = bridgeScenesToTreatmentScenes(proposal.scenes);
+
+ // Mint the fresh project. sourceIssueId links it back to the issue (and feeds
+ // the stitch step's music mux). CD render defaults match the New-Project form.
+ const project = await createProject({
+ name: options.name || `${issue.title || series?.name || 'Issue'} — Teaser`,
+ aspectRatio: options.aspectRatio || '16:9',
+ quality: options.quality || 'standard',
+ modelId: defaultVideoModelId(),
+ targetDurationSeconds: options.targetDurationSeconds || 60,
+ styleSpec: proposal.styleSpec || '',
+ sourceIssueId: issueId,
+ });
+
+ let started;
+ try {
+ started = await setTreatment(project.id, {
+ logline: proposal.logline,
+ synopsis: proposal.synopsis,
+ scenes,
+ });
+ // Shared cast/canon (#2185): pull the series' catalog ingredients into CD
+ // casting + write creative-director refs so autonomous and manual paths
+ // converge on the same ingredients. Best-effort — the treatment already
+ // landed, and a series with no cataloged canon simply adds nothing.
+ const brief = deriveTeaserBrief(series, issue, proposal);
+ if (brief) {
+ await applyAutoCastToProject(project.id, { brief })
+ .then((r) => {
+ if (r?.added?.length) console.log(`🎬 Teaser auto-cast: ${r.added.length} ingredient(s) → CD project ${project.id}`);
+ })
+ .catch((err) => console.error(`❌ Teaser auto-cast failed for CD project ${project.id}: ${err.message}`));
+ }
+ // Explicitly start it (the #842 rule: a bridged record's owning step starts
+ // it — nothing auto-starts). Imported here to keep the module graph acyclic.
+ const { startCreativeDirectorProject } = await import('./completionHook.js');
+ await startCreativeDirectorProject(project.id);
+ } catch (err) {
+ // Roll back the orphaned project + its auto-created media collection so a
+ // setTreatment/start failure doesn't leave a treatment-less shell behind.
+ await deleteProject(project.id).catch(() => {});
+ if (project.collectionId) await deleteCollection(project.collectionId).catch(() => {});
+ throw err;
+ }
+
+ console.log(`🎬 Produced CD teaser project ${project.id} from issue ${issueId}`);
+ return { project: started || project, proposal };
+}
diff --git a/server/services/creativeDirector/bridgeFromIssue.test.js b/server/services/creativeDirector/bridgeFromIssue.test.js
new file mode 100644
index 0000000000..a262d6155a
--- /dev/null
+++ b/server/services/creativeDirector/bridgeFromIssue.test.js
@@ -0,0 +1,127 @@
+/**
+ * CDO Phase 3 (#2185) — autopilot/pipeline → Creative Director bridge.
+ *
+ * Locks the mint-and-start contract: produceVideoFromIssue generates a treatment
+ * from the issue's prose (via the shared CD-bridge stage + shaper), mints a FRESH
+ * CD project seeded with sourceIssueId, applies the treatment, auto-casts the
+ * series canon, and STARTS it — never mutating an existing project (the #842
+ * rule). Rolls back on a post-create failure.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mockRunStagedLLM = vi.fn();
+const mockGetIssue = vi.fn();
+const mockGetSeries = vi.fn();
+const mockCreateProject = vi.fn();
+const mockSetTreatment = vi.fn();
+const mockDeleteProject = vi.fn();
+const mockApplyAutoCast = vi.fn();
+const mockDeleteCollection = vi.fn();
+const mockStartProject = vi.fn();
+
+// stageRunner is shared by bridgeFromIssue AND liveDirector (which provides the
+// real shapeProposal/CD_BRIDGE_STAGE we deliberately keep unmocked).
+vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => mockRunStagedLLM(...a) }));
+vi.mock('../pipeline/issues.js', () => ({ getIssue: (...a) => mockGetIssue(...a) }));
+vi.mock('../pipeline/series.js', () => ({ getSeries: (...a) => mockGetSeries(...a) }));
+vi.mock('../videoGen/local.js', () => ({ defaultVideoModelId: () => 'ltx-model' }));
+// './local.js' from here === '../creativeDirector/local.js' from liveDirector —
+// one mock covers both importers.
+vi.mock('./local.js', () => ({
+ createProject: (...a) => mockCreateProject(...a),
+ setTreatment: (...a) => mockSetTreatment(...a),
+ deleteProject: (...a) => mockDeleteProject(...a),
+ updateProject: vi.fn(),
+}));
+vi.mock('./autoCast.js', () => ({ applyAutoCastToProject: (...a) => mockApplyAutoCast(...a) }));
+vi.mock('../mediaCollections.js', () => ({ deleteCollection: (...a) => mockDeleteCollection(...a) }));
+// Dynamically imported inside produceVideoFromIssue to break the module cycle.
+vi.mock('./completionHook.js', () => ({ startCreativeDirectorProject: (...a) => mockStartProject(...a) }));
+
+const { produceVideoFromIssue } = await import('./bridgeFromIssue.js');
+
+const goodProposal = {
+ logline: 'A weary detective returns.',
+ synopsis: 'Across one rain-soaked night the detective confronts an old ghost.',
+ styleSpec: 'noir, high-contrast',
+ scenes: [
+ { intent: 'establish', prompt: 'wide neon-lit street', durationSeconds: 4 },
+ { intent: 'confront', prompt: 'close-up in the rain', durationSeconds: 6 },
+ ],
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetIssue.mockResolvedValue({ id: 'iss-1', seriesId: 'ser-1', title: 'Issue One', stages: { prose: { output: 'Once upon a rainy night...' } } });
+ mockGetSeries.mockResolvedValue({ id: 'ser-1', name: 'Noir Nights', premise: 'A city of shadows' });
+ mockRunStagedLLM.mockResolvedValue({ content: goodProposal });
+ mockCreateProject.mockImplementation(async (input) => ({ id: 'cd-9', collectionId: 'col-9', ...input }));
+ mockSetTreatment.mockImplementation(async (id) => ({ id, status: 'rendering' }));
+ mockApplyAutoCast.mockResolvedValue({ added: [{ ingredientId: 'ing-1' }] });
+ mockStartProject.mockResolvedValue(undefined);
+ mockDeleteProject.mockResolvedValue(undefined);
+ mockDeleteCollection.mockResolvedValue(undefined);
+});
+
+describe('produceVideoFromIssue (#2185)', () => {
+ it('mints a fresh project seeded from the issue, applies the treatment, casts, and starts it', async () => {
+ const { project, proposal } = await produceVideoFromIssue('iss-1');
+
+ // A NEW project is created (never a pre-existing one) with the source link.
+ expect(mockCreateProject).toHaveBeenCalledTimes(1);
+ expect(mockCreateProject.mock.calls[0][0]).toMatchObject({
+ sourceIssueId: 'iss-1',
+ modelId: 'ltx-model',
+ styleSpec: 'noir, high-contrast',
+ name: 'Issue One — Teaser',
+ });
+
+ // Treatment applied to the minted project with scenes mapped to the CD shape.
+ expect(mockSetTreatment).toHaveBeenCalledWith('cd-9', expect.objectContaining({
+ logline: goodProposal.logline,
+ synopsis: goodProposal.synopsis,
+ }));
+ const scenes = mockSetTreatment.mock.calls[0][1].scenes;
+ expect(scenes).toHaveLength(2);
+ expect(scenes[0]).toMatchObject({ sceneId: 'sc-1', order: 0, useContinuationFromPrior: false });
+ expect(scenes[1]).toMatchObject({ sceneId: 'sc-2', order: 1, useContinuationFromPrior: true });
+
+ // Shared cast/canon + explicit start.
+ expect(mockApplyAutoCast).toHaveBeenCalledWith('cd-9', expect.objectContaining({ brief: expect.stringContaining('Noir Nights') }));
+ expect(mockStartProject).toHaveBeenCalledWith('cd-9');
+ expect(project.id).toBe('cd-9');
+ expect(proposal.logline).toBe(goodProposal.logline);
+ });
+
+ it('falls back to the comic script when there is no prose', async () => {
+ mockGetIssue.mockResolvedValue({ id: 'iss-1', seriesId: 'ser-1', title: 'T', stages: { comicScript: { output: 'PAGE 1 PANEL 1 ...' } } });
+ await produceVideoFromIssue('iss-1');
+ expect(mockRunStagedLLM.mock.calls[0][1].before).toContain('PAGE 1');
+ });
+
+ it('rejects when the issue has no prose/script to build from (no project minted)', async () => {
+ mockGetIssue.mockResolvedValue({ id: 'iss-1', seriesId: 'ser-1', title: 'T', stages: {} });
+ await expect(produceVideoFromIssue('iss-1')).rejects.toThrow(/no prose/i);
+ expect(mockCreateProject).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the model cannot produce a usable treatment (no project minted)', async () => {
+ mockRunStagedLLM.mockResolvedValue({ content: { logline: '', synopsis: '', scenes: [] } });
+ await expect(produceVideoFromIssue('iss-1')).rejects.toThrow(/usable teaser treatment/i);
+ expect(mockCreateProject).not.toHaveBeenCalled();
+ });
+
+ it('rolls back the orphaned project + collection when start fails after create', async () => {
+ mockStartProject.mockRejectedValue(new Error('boom'));
+ await expect(produceVideoFromIssue('iss-1')).rejects.toThrow('boom');
+ expect(mockDeleteProject).toHaveBeenCalledWith('cd-9');
+ expect(mockDeleteCollection).toHaveBeenCalledWith('col-9');
+ });
+
+ it('threads the run provider/model into the treatment stage call', async () => {
+ await produceVideoFromIssue('iss-1', { providerDefault: 'anthropic', modelDefault: 'opus' });
+ const stageOpts = mockRunStagedLLM.mock.calls[0][2];
+ expect(stageOpts).toMatchObject({ providerDefault: 'anthropic', modelDefault: 'opus' });
+ });
+});
diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.js
index 4ac55da9ce..abe1327a79 100644
--- a/server/services/creativeDirector/planAdvance.js
+++ b/server/services/creativeDirector/planAdvance.js
@@ -27,8 +27,15 @@ import { getProject, updateProject, updatePlanStep, recordRun, updateRun } from
import { enqueuePlanTask } from './agentBridge.js';
import { dispatchCreativeTool } from '../creative/toolRegistry.js';
import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';
+import { autopilotEvents, isAutopilotActive, AUTOPILOT_TERMINAL_TYPES } from '../pipeline/seriesAutopilot.js';
+import { getSeries } from '../pipeline/series.js';
import { MAX_REPLAN_ROUNDS, PLAN_STEP_TERMINAL_SUCCESS } from '../../lib/creativeDirectorPresets.js';
+// The registry tool that runs Series Autopilot as a plan step. A long-running
+// step whose dispatch returns a run handle (a `runId`, not a media `jobId`)
+// settles via the in-process autopilot event bus (CDO Phase 3, #2185).
+const AUTOPILOT_TOOL_NAME = 'pipeline_startSeriesAutopilot';
+
const nowISO = () => new Date().toISOString();
/**
@@ -244,11 +251,19 @@ async function settlePlanStepDispatch(projectId, step, runId, dispatch) {
if (dispatch.longRunning) {
const jobId = dispatch.result?.jobId;
if (jobId) return armPlanJobListener(projectId, step.stepId, jobId, runId);
- // A long-running tool with no observable job handle — Series Autopilot returns
- // a run handle, not a jobId; its in-process progress/pause event bridge lands
- // in CDO Phase 3. For now a successful START counts as step completion so the
- // plan makes progress; the underlying run continues on its own.
- console.log(`⚠️ CD plan ${projectId}: step "${step.stepId}" (${step.toolName}) is long-running with no jobId — marking done on start (event bridge lands in Phase 3)`);
+ // Series Autopilot returns a run handle (`runId`), not a media jobId — settle
+ // this step off the in-process autopilot event bus (CDO Phase 3, #2185): the
+ // step stays `running` until the underlying autopilot run reaches a terminal
+ // frame. A pause surfaces as a BLOCKED step (never auto-retried); an error
+ // routes through the failure handler. `alreadyRunning` means the tool
+ // attached to a live run instead of double-starting — we observe it the same.
+ const seriesId = step.args?.seriesId;
+ if (step.toolName === AUTOPILOT_TOOL_NAME && seriesId && dispatch.result?.runId) {
+ return armAutopilotListener(projectId, step.stepId, seriesId, runId, dispatch.result);
+ }
+ // A long-running tool with no observable handle at all — mark done on start so
+ // the plan makes progress; the underlying work continues on its own.
+ console.log(`⚠️ CD plan ${projectId}: step "${step.stepId}" (${step.toolName}) is long-running with no observable handle — marking done on start`);
await finishRun(projectId, runId, 'completed');
await updatePlanStep(projectId, step.stepId, { status: 'done', result: summarizeResult(dispatch.result) });
return advanceAfterPlanStepSettled(projectId);
@@ -324,6 +339,109 @@ function armPlanJobListener(projectId, stepId, jobId, runId) {
}
}
+// Compact summary of an autopilot terminal frame for the plan step `result` —
+// carries the run id + the "clean complete but with residual concerns" counters
+// the autopilot's own `complete` frame surfaces (#1572/#1573), so a plan reader
+// sees the same qualifications an SSE client would.
+function summarizeAutopilotResult(payload) {
+ const out = {};
+ for (const k of ['runId', 'steps', 'craftGapIssues', 'craftGapFindings', 'editorialCheckErrors']) {
+ if (payload?.[k] != null) out[k] = payload[k];
+ }
+ return out;
+}
+
+// Map an autopilot terminal frame onto the plan step's persisted state.
+// - complete → step `done`, advance the plan.
+// - paused / canceled → step `blocked` (human-review pause; never auto-retried).
+// - error → step `failed`, route through bounded re-plan.
+// Runs off the event bus / a marker read — outside any request lifecycle — so it
+// must never throw out (the caller wraps it, but keep it self-contained).
+async function settleAutopilotStep(projectId, stepId, runId, payload) {
+ const type = payload?.type;
+ if (type === 'complete') {
+ await finishRun(projectId, runId, 'completed');
+ await updatePlanStep(projectId, stepId, { status: 'done', result: summarizeAutopilotResult(payload) });
+ console.log(`✅ CD plan ${projectId}: autopilot step "${stepId}" complete`);
+ return advanceAfterPlanStepSettled(projectId);
+ }
+ if (type === 'paused' || type === 'canceled') {
+ const reason = payload?.reason
+ || (type === 'canceled' ? 'autopilot run was canceled' : 'autopilot paused for human review');
+ await finishRun(projectId, runId, 'failed', reason);
+ // BLOCKED, not failed — a pause is a human-review gate. The advance loop sees
+ // the blocked step and pauses the whole plan with the reason; it is never
+ // silently retried around (the autopilot pause contract).
+ await updatePlanStep(projectId, stepId, {
+ status: 'blocked',
+ result: { reason, residualFindings: payload?.residualFindings || [], pauseKind: payload?.pauseKind || null },
+ });
+ console.log(`⏸️ CD plan ${projectId}: autopilot step "${stepId}" blocked: ${reason}`);
+ return advanceAfterPlanStepSettled(projectId);
+ }
+ // error frame.
+ const error = payload?.error || 'autopilot run error';
+ await finishRun(projectId, runId, 'failed', error);
+ await updatePlanStep(projectId, stepId, { status: 'failed', result: { error } });
+ return handlePlanStepFailure(projectId, { stepId, toolName: '(series autopilot)', retryCount: 0 });
+}
+
+// Read the persisted autopilot marker for the race where the run reached a
+// terminal state between dispatch returning and our listener attaching (its
+// event fired and won't repeat). Returns a synthetic terminal frame or null when
+// the run is still `running`/absent (the live listener will catch the real one).
+async function readAutopilotMarker(seriesId) {
+ const series = await getSeries(seriesId).catch(() => null);
+ const marker = series?.autopilot;
+ if (!marker) return null;
+ if (marker.status === 'done') {
+ return { type: 'complete', runId: marker.runId, craftGapIssues: marker.craftGapIssues, craftGapFindings: marker.craftGapFindings, editorialCheckErrors: marker.editorialCheckErrors };
+ }
+ if (marker.status === 'paused') {
+ return { type: 'paused', runId: marker.runId, reason: marker.lastError, residualFindings: marker.residualFindings || [], pauseKind: marker.pauseKind || null };
+ }
+ if (marker.status === 'error') {
+ return { type: 'error', runId: marker.runId, error: marker.lastError };
+ }
+ return null; // 'running' or unknown — not terminal.
+}
+
+// Attach a listener to the in-process autopilot event bus for `seriesId`, settling
+// the plan step on the first terminal frame. Idempotent teardown (reuses the
+// shared planJobCleanups map so __resetPlanInflightState drops it too). Closes the
+// already-terminal race via the persisted marker, mirroring armPlanJobListener.
+function armAutopilotListener(projectId, stepId, seriesId, runId, apResult) {
+ const key = `${projectId}:${stepId}`;
+ let fired = false;
+ const teardown = () => {
+ autopilotEvents.off(seriesId, handler);
+ planJobCleanups.delete(key);
+ };
+ function handler(payload) {
+ if (fired || !payload || !AUTOPILOT_TERMINAL_TYPES.has(payload.type)) return;
+ fired = true;
+ teardown();
+ settleAutopilotStep(projectId, stepId, runId, payload)
+ .catch((e) => console.log(`⚠️ CD plan ${projectId} autopilot settle for ${stepId} failed: ${e.message}`));
+ }
+ autopilotEvents.on(seriesId, handler);
+ planJobCleanups.set(key, teardown);
+ console.log(`⏳ CD plan ${projectId}: step "${stepId}" attached to autopilot run for series ${String(seriesId).slice(0, 8)}${apResult?.alreadyRunning ? ' (already running)' : ''}`);
+ // The run may already have reached a terminal state (settled between dispatch
+ // returning and this attach) — its event fired and won't repeat. Re-check via
+ // isAutopilotActive + the persisted marker and settle immediately if so.
+ if (!isAutopilotActive(seriesId)) {
+ (async () => {
+ const marker = await readAutopilotMarker(seriesId);
+ if (marker && !fired) {
+ fired = true;
+ teardown();
+ await settleAutopilotStep(projectId, stepId, runId, marker);
+ }
+ })().catch((e) => console.log(`⚠️ CD plan ${projectId} autopilot marker settle for ${stepId} failed: ${e.message}`));
+ }
+}
+
// Test-only: clear module-level dedup + tear down any armed media-job listeners
// so a suite that leaves a long-running step pending can't leak a live listener
// into a later test.
diff --git a/server/services/creativeDirector/planAdvance.test.js b/server/services/creativeDirector/planAdvance.test.js
index 175d250c46..fd3f8492f8 100644
--- a/server/services/creativeDirector/planAdvance.test.js
+++ b/server/services/creativeDirector/planAdvance.test.js
@@ -79,6 +79,21 @@ const mockEnqueuePlanTask = vi.fn();
const mockDispatch = vi.fn();
const mockListJobs = vi.fn();
+// Shared in-process autopilot bus + controls (CDO Phase 3, #2185). A minimal
+// hand-rolled emitter (on/off/emit) built in vi.hoisted so the vi.mock factory
+// closes over the SAME instance the tests emit on. Controls (`active`, `marker`)
+// are mutated per-test to drive the already-terminal race + attach paths.
+const ap = vi.hoisted(() => {
+ const listeners = new Map();
+ const autopilotEvents = {
+ on(name, fn) { (listeners.get(name) || listeners.set(name, new Set()).get(name)).add(fn); },
+ off(name, fn) { listeners.get(name)?.delete(fn); },
+ emit(name, payload) { for (const fn of [...(listeners.get(name) || [])]) fn(payload); },
+ };
+ const ctl = { active: true, marker: null };
+ return { autopilotEvents, ctl, AUTOPILOT_TERMINAL_TYPES: new Set(['complete', 'paused', 'canceled', 'error']) };
+});
+
vi.mock('./local.js', () => ({
getProject: (...a) => mockGetProject(...a),
updateProject: (...a) => mockUpdateProject(...a),
@@ -96,9 +111,22 @@ vi.mock('../mediaJobQueue/index.js', () => ({
listJobs: (...a) => mockListJobs(...a),
mediaJobEvents: { on: vi.fn(), off: vi.fn() },
}));
+vi.mock('../pipeline/seriesAutopilot.js', () => ({
+ autopilotEvents: ap.autopilotEvents,
+ isAutopilotActive: () => ap.ctl.active,
+ AUTOPILOT_TERMINAL_TYPES: ap.AUTOPILOT_TERMINAL_TYPES,
+}));
+vi.mock('../pipeline/series.js', () => ({
+ getSeries: async () => ap.ctl.marker && { autopilot: ap.ctl.marker },
+}));
const { advanceAfterPlanStepSettled, __resetPlanInflightState } = await import('./planAdvance.js');
+// Drain the fire-and-forget async settle chain a terminal frame / marker read
+// kicks off (finishRun → updatePlanStep → advanceAfterPlanStepSettled → pause),
+// which spans several microtask hops the emit doesn't await.
+const flush = async () => { for (let i = 0; i < 20; i += 1) await Promise.resolve(); };
+
// A tiny in-memory project the mocked store mutates so recursion sees fresh state.
function makeStore(initial) {
let project = structuredClone(initial);
@@ -131,6 +159,8 @@ beforeEach(() => {
__resetPlanInflightState();
mockListJobs.mockReturnValue([]);
mockEnqueuePlanTask.mockResolvedValue(undefined);
+ ap.ctl.active = true;
+ ap.ctl.marker = null;
});
const planProject = (steps, over = {}) => ({
@@ -232,3 +262,92 @@ describe('advanceAfterPlanStepSettled — executor', () => {
expect(mockDispatch).not.toHaveBeenCalled();
});
});
+
+// ---- CD → Autopilot bridge (CDO Phase 3, #2185) ----------------------------
+
+const autopilotStep = (over = {}) => step('a', { toolName: 'pipeline_startSeriesAutopilot', args: { seriesId: 'ser-1' }, ...over });
+const autopilotDispatch = (result = {}) => ({
+ ok: true, mode: 'execute', longRunning: true, result: { runId: 'r1', alreadyRunning: false, mode: 'execute', ...result },
+});
+
+describe('advanceAfterPlanStepSettled — runAutopilot plan step', () => {
+ it('a running autopilot step stays running until a terminal frame arrives (no jobId)', async () => {
+ const read = makeStore(planProject([
+ autopilotStep(),
+ step('b', { toolName: 'pipeline_generateStage', dependsOn: ['a'] }),
+ ]));
+ mockDispatch.mockResolvedValue(autopilotDispatch());
+ await advanceAfterPlanStepSettled('cd-1');
+ const p = read();
+ expect(p.plan.steps[0].status).toBe('running');
+ expect(p.plan.steps[1].status).toBe('pending');
+ expect(p.status).not.toBe('complete');
+ });
+
+ it('a `complete` frame settles the step done and advances the plan', async () => {
+ const read = makeStore(planProject([
+ autopilotStep(),
+ step('b', { toolName: 'pipeline_generateStage', dependsOn: ['a'] }),
+ ]));
+ mockDispatch.mockResolvedValueOnce(autopilotDispatch()); // start autopilot
+ mockDispatch.mockResolvedValueOnce({ ok: true, mode: 'execute', result: { id: 'x' } }); // step b
+ await advanceAfterPlanStepSettled('cd-1');
+ // Emit the terminal frame the live autopilot run would broadcast.
+ ap.autopilotEvents.emit('ser-1', { type: 'complete', runId: 'r1', steps: 7, craftGapIssues: 1 });
+ await flush();
+ const p = read();
+ expect(p.plan.steps[0].status).toBe('done');
+ // The complete frame's qualifier counters land in the step result.
+ expect(p.plan.steps[0].result).toMatchObject({ runId: 'r1', steps: 7, craftGapIssues: 1 });
+ expect(p.plan.steps[1].status).toBe('done');
+ expect(p.status).toBe('complete');
+ });
+
+ it('a `paused` frame BLOCKS the step and pauses the plan (never auto-retried)', async () => {
+ const read = makeStore(planProject([autopilotStep()]));
+ mockDispatch.mockResolvedValue(autopilotDispatch());
+ await advanceAfterPlanStepSettled('cd-1');
+ ap.autopilotEvents.emit('ser-1', { type: 'paused', runId: 'r1', reason: 'editorial review paused', residualFindings: [{ severity: 'high' }], pauseKind: 'maxRounds' });
+ await flush();
+ const p = read();
+ expect(p.plan.steps[0].status).toBe('blocked');
+ expect(p.plan.steps[0].result).toMatchObject({ reason: 'editorial review paused', pauseKind: 'maxRounds' });
+ expect(p.status).toBe('paused');
+ expect(p.failureReason).toMatch(/blocked/);
+ // The planner is NEVER re-enqueued around a human-review pause.
+ expect(mockEnqueuePlanTask).not.toHaveBeenCalled();
+ });
+
+ it('an `error` frame fails the step and routes through bounded re-plan', async () => {
+ const read = makeStore(planProject([autopilotStep()]));
+ mockDispatch.mockResolvedValue(autopilotDispatch());
+ await advanceAfterPlanStepSettled('cd-1');
+ ap.autopilotEvents.emit('ser-1', { type: 'error', runId: 'r1', error: 'run crashed' });
+ await flush();
+ const p = read();
+ expect(p.plan.steps[0].status).toBe('failed');
+ expect(mockEnqueuePlanTask).toHaveBeenCalledTimes(1); // under the replan budget
+ });
+
+ it('attaches to a live run (alreadyRunning) and settles on its terminal frame', async () => {
+ const read = makeStore(planProject([autopilotStep()]));
+ mockDispatch.mockResolvedValue(autopilotDispatch({ alreadyRunning: true }));
+ await advanceAfterPlanStepSettled('cd-1');
+ expect(read().plan.steps[0].status).toBe('running');
+ ap.autopilotEvents.emit('ser-1', { type: 'complete', runId: 'r1', steps: 3 });
+ await flush();
+ expect(read().plan.steps[0].status).toBe('done');
+ });
+
+ it('settles immediately off the persisted marker when the run already finished (attach race)', async () => {
+ ap.ctl.active = false; // run is no longer active by the time we attach
+ ap.ctl.marker = { status: 'paused', runId: 'r1', lastError: 'canon gate', residualFindings: [], pauseKind: 'canon' };
+ const read = makeStore(planProject([autopilotStep()]));
+ mockDispatch.mockResolvedValue(autopilotDispatch());
+ await advanceAfterPlanStepSettled('cd-1');
+ await flush();
+ const p = read();
+ expect(p.plan.steps[0].status).toBe('blocked');
+ expect(p.status).toBe('paused');
+ });
+});
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index da702c0213..83d6df5583 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -66,6 +66,7 @@
*/
import { randomUUID } from 'crypto';
+import { EventEmitter } from 'events';
import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
import { getDomainMode } from '../../lib/domainAutonomy.js';
import { parseComicScript } from '../../lib/comicScriptParser.js';
@@ -106,6 +107,25 @@ import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS
// cleanupTimer, startedAt, mode, options, runState, activeChild }>
const runs = new Map();
+// In-process progress bus (CDO Phase 3, #2185). Every SSE frame the run
+// broadcasts to attached HTTP clients is ALSO emitted here keyed by seriesId, so
+// a SERVER-SIDE consumer — the Creative Director plan-advance loop running an
+// autopilot as one plan step — can observe progress/pause/terminal frames
+// without opening an HTTP/SSE client. SSE behavior is unchanged; this is a
+// parallel tap, not a replacement. Listeners are per-seriesId and short-lived
+// (attached for the life of one plan step), but a busy install could run several
+// concurrently, so lift the default 10-listener cap to avoid a spurious leak
+// warning. The payloads are the exact SSE frames (they carry `type`).
+export const autopilotEvents = new EventEmitter();
+autopilotEvents.setMaxListeners(0);
+
+// The frame `type`s that mean the run reached a terminal/paused state — a
+// server-side consumer settles its plan step on any of these. `complete` (or a
+// dry-run `complete`), `paused` (convergence/budget/child pause), `canceled`
+// (user stop), and `error` (run-ending throw) are exhaustive of the run's exit
+// frames (see the fire-and-forget coordinator in startSeriesAutopilot).
+export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled', 'error']);
+
// Bounded convergence loops — re-verify/re-review at most this many rounds, then
// pause for human review with the residual findings (see module header). These
// are the floor defaults; an install can raise them persistently via
@@ -190,6 +210,29 @@ export function resolveAutopilotNotifyOnPause(options = {}, settings = null) {
return DEFAULT_NOTIFY_ON_PAUSE;
}
+// Autopilot → CD teaser deliverable (CDO Phase 3, #2185). Once a comic issue is
+// text-ready + drafted, the autopilot can OPTIONALLY mint + start a Creative
+// Director video project (a teaser/trailer) seeded from the issue — the reverse
+// of the CD→autopilot bridge. Defaults OFF: producing video is a fresh burst of
+// LLM + render spend the user must opt into, so existing runs are unchanged.
+// Per-run option wins, then the persisted setting, then false. Stamped onto run
+// options once at start so the resolver, the dry-run plan, and a later resume
+// all read the same effective flag.
+export const DEFAULT_PRODUCE_TEASER = false;
+export function resolveAutopilotProduceTeaser(options = {}, settings = null) {
+ if (typeof options?.produceTeaser === 'boolean') return options.produceTeaser;
+ const pec = settings?.pipelineEditorialChecks || {};
+ if (typeof pec?.produceTeaser === 'boolean') return pec.produceTeaser;
+ return DEFAULT_PRODUCE_TEASER;
+}
+
+// Does THIS run want to produce a teaser deliverable? Gated on the resolved
+// `produceTeaser` flag AND that visuals ran (a teaser is a visual deliverable —
+// pointless on a text-only run).
+export function wantsTeaser(options = {}) {
+ return options.produceTeaser === true && wantsVisual(options);
+}
+
// Per-gate copy for the non-convergence pause — shared by the arc-verify and
// editorial loops so the two messages can't drift.
const PAUSE_GATES = {
@@ -558,6 +601,18 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
}
}
+ // STEP 7 — teaser video deliverable (CDO Phase 3, #2185, opt-in, default off).
+ // After every issue is text-ready + drafted, OPTIONALLY mint + start a Creative
+ // Director video project seeded from each issue. Gated on wantsTeaser (which
+ // itself requires visuals). Attempted-once per issue this run so a started (or
+ // failed) teaser can't re-loop the resolver back here.
+ if (VISUAL_DRAFT_ENABLED && wantsTeaser(options) && wantsComic(series, options)) {
+ for (const issue of ordered) {
+ if (setHas(runState.teaserProduced, issue.id)) continue;
+ return { kind: 'produceTeaser', issueId: issue.id, reason: 'teaser video not yet produced' };
+ }
+ }
+
return { kind: 'done' };
}
@@ -596,6 +651,15 @@ function broadcast(seriesId, payload) {
const run = runs.get(seriesId);
if (!run) return;
broadcastSse(run, payload);
+ // Mirror every frame onto the in-process bus (CDO Phase 3, #2185) so a
+ // server-side consumer (CD plan step) sees the same progress/pause/terminal
+ // frames as an SSE client. Emit is best-effort — a listener throw must never
+ // abort the run (this runs inside the fire-and-forget coordinator).
+ try {
+ autopilotEvents.emit(seriesId, payload);
+ } catch (err) {
+ console.log(`⚠️ autopilot: event emit failed for ${seriesId.slice(0, 12)}: ${err.message}`);
+ }
}
function scheduleCleanup(seriesId, record) {
@@ -1486,6 +1550,41 @@ async function runCanonVerify(sId, record) {
};
}
+// Teaser deliverable (CDO Phase 3, #2185, opt-in). Mint + start a Creative
+// Director video project seeded from this issue — the autopilot→CD direction of
+// the bridge. Attempted-once per issue (marked up front so a failure can't
+// re-loop the resolver). Bills one cos action like every other autopilot step
+// (the CD project's own downstream render spend is gated by the creative/cos
+// budget on its side). A teaser is an OPTIONAL, terminal-phase deliverable, so a
+// failure is ADVISORY: it broadcasts a skip + files a gap, but does NOT pause the
+// whole run (the story is already done — a failed trailer shouldn't strand it).
+// bridgeFromIssue is imported dynamically to keep the pipeline↔creative-director
+// module graph acyclic (it transitively pulls the CD plan loop + tool registry).
+async function runProduceTeaser(sId, issueId, record) {
+ record.runState.teaserProduced.add(issueId);
+ const issue = await getIssue(issueId).catch(() => null);
+ try {
+ const { produceVideoFromIssue } = await import('../creativeDirector/bridgeFromIssue.js');
+ // The treatment-from-prose LLM call runs through stageRunner's soft channel,
+ // so thread the run's provider/model as providerDefault/modelDefault.
+ const { project } = await produceVideoFromIssue(issueId, providerOverrideOpts(record));
+ await recordDomainUsage('cos', { actions: 1 });
+ broadcast(sId, { type: 'teaser:produced', issueId, projectId: project?.id });
+ console.log(`🎬 autopilot teaser — series=${sId.slice(0, 12)} issue=${issue?.number ?? issueId} → CD project ${project?.id?.slice(0, 8) ?? '?'}`);
+ return {};
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 300);
+ broadcast(sId, { type: 'step:skip', kind: 'produceTeaser', issueId, reason: `teaser production failed: ${message}` });
+ await fileGap(record, sId, {
+ gapKind: 'teaser-failed',
+ issueId,
+ summary: `The optional teaser video for issue ${issue?.number ?? issueId} could not be produced: ${message}. The story is complete — this deliverable can be retried from the Creative Director.`,
+ context: `issueId=${issueId}`,
+ });
+ return {};
+ }
+}
+
async function dispatchStep(sId, step, record) {
switch (step.kind) {
case 'generateArc': {
@@ -1545,6 +1644,8 @@ async function dispatchStep(sId, step, record) {
return runCanonVerify(sId, record);
case 'visualDraft':
return runVisualDraft(sId, step.issueId, record);
+ case 'produceTeaser':
+ return runProduceTeaser(sId, step.issueId, record);
default:
return {};
}
@@ -1645,6 +1746,10 @@ function buildDryRunPlan(series, issues, options, costContext = {}) {
// interior page. The interior-page count isn't known until the script parses,
// so the estimate counts the two covers and notes the per-page additions.
if (visualNeeded) plan.push({ kind: 'visualDraft', count: visualNeeded, note: 'cover + back + all pages (draft) — +1 action per interior page', estActions: visualNeeded * 2 });
+ // Teaser deliverable (#2185, opt-in, default off): one CD video project per
+ // issue. Each mint+start bills one cos action for the treatment LLM call; the
+ // CD project's own render spend is gated on the creative/cos budget its side.
+ if (wantsTeaser(options)) plan.push({ kind: 'produceTeaser', count: ordered.length, note: 'mint + start a Creative Director teaser video per issue (opt-in)', estActions: ordered.length });
}
return plan;
}
@@ -1689,6 +1794,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
readinessGate: resolveAutopilotReadinessGate(options, settings),
checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),
notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),
+ produceTeaser: resolveAutopilotProduceTeaser(options, settings),
severityWeights: mergeSeverityWeights(seriesRecord?.severityWeights),
blockingSets: {
arc: resolveBlockingSet(seriesRecord?.blockingSeverities, 'arc'),
@@ -1729,6 +1835,9 @@ export async function startSeriesAutopilot(sId, options = {}) {
textAttempted: new Set(),
scriptChecked: new Set(),
visualDrafted: new Set(),
+ // #2185 — issues whose optional teaser deliverable has been produced (or
+ // attempted) this run, so the resolver can't re-loop into produceTeaser.
+ teaserProduced: new Set(),
// #1572 — issues whose ADVISORY craft gate filed a blocking gap task, and
// the total blocking-finding count. Carried into the terminal `complete`
// frame + persisted marker so a "clean complete" doesn't hide downstream
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 1210469ebd..251774d25d 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -650,6 +650,73 @@ describe('resolveNextStep (pure)', () => {
);
expect(step.kind).toBe('editorialReview');
});
+
+ // CDO Phase 3 (#2185) — the opt-in teaser deliverable is the LAST step, after
+ // visuals are drafted, and only when produceTeaser is on.
+ const rendered = {
+ idea: ready(),
+ comicScript: ready(VALID_SCRIPT),
+ comicPages: {
+ cover: { proofImage: { jobId: 'j' } },
+ backCover: { proofImage: { jobId: 'jb' } },
+ pages: [{ panels: [{ description: 'x' }], proofImage: { jobId: 'p0' } }],
+ },
+ };
+ const fullyReady = { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true };
+
+ it('does NOT ask for a teaser by default (produceTeaser off) — stays done', () => {
+ const step = resolveNextStep(comic, [issue({ stages: rendered })], fullyReady, { includeVisual: true });
+ expect(step.kind).toBe('done');
+ });
+
+ it('asks for a teaser once visuals are drafted and produceTeaser is on', () => {
+ const step = resolveNextStep(comic, [issue({ stages: rendered })], fullyReady, { includeVisual: true, produceTeaser: true });
+ expect(step).toMatchObject({ kind: 'produceTeaser', issueId: 'iss1' });
+ });
+
+ it('is done once the teaser has been produced this run', () => {
+ const step = resolveNextStep(comic, [issue({ stages: rendered })], { ...fullyReady, teaserProduced: new Set(['iss1']) }, { includeVisual: true, produceTeaser: true });
+ expect(step.kind).toBe('done');
+ });
+
+ it('never asks for a teaser on a text-only run even with produceTeaser on', () => {
+ const step = resolveNextStep(comic, [issue({ stages: rendered })], fullyReady, { target: 'text', produceTeaser: true });
+ expect(step.kind).toBe('done');
+ });
+});
+
+describe('resolveAutopilotProduceTeaser (config gate, #2185)', () => {
+ it('defaults OFF', () => {
+ expect(autopilot.resolveAutopilotProduceTeaser({}, null)).toBe(false);
+ });
+ it('per-run option wins over the persisted setting', () => {
+ expect(autopilot.resolveAutopilotProduceTeaser({ produceTeaser: true }, { pipelineEditorialChecks: { produceTeaser: false } })).toBe(true);
+ });
+ it('falls back to the persisted setting when no per-run option', () => {
+ expect(autopilot.resolveAutopilotProduceTeaser({}, { pipelineEditorialChecks: { produceTeaser: true } })).toBe(true);
+ });
+});
+
+describe('autopilotEvents in-process bus (#2185)', () => {
+ it('mirrors the SSE frames a real run broadcasts onto the bus keyed by seriesId', async () => {
+ cosMode = 'dry-run';
+ const { seriesId } = await seedComplete();
+ const frames = [];
+ const handler = (p) => frames.push(p);
+ autopilot.autopilotEvents.on(seriesId, handler);
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ autopilot.autopilotEvents.off(seriesId, handler);
+ // The bus received the same terminal frame the SSE client sees (lastPayload).
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(frames).toContainEqual(last);
+ expect(frames.some((f) => f.type === 'start')).toBe(true);
+ expect(frames.some((f) => f.type === 'complete')).toBe(true);
+ });
+
+ it('exposes the terminal frame types a server-side consumer settles on', () => {
+ expect([...autopilot.AUTOPILOT_TERMINAL_TYPES]).toEqual(['complete', 'paused', 'canceled', 'error']);
+ });
});
describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.js
index fb6826bf01..5b7e9ebf35 100644
--- a/server/services/writersRoom/liveDirector.js
+++ b/server/services/writersRoom/liveDirector.js
@@ -25,7 +25,11 @@ import { defaultVideoModelId } from '../videoGen/local.js';
import { badRequest } from './_shared.js';
const STAGE = 'writers-room-continue';
-const CD_BRIDGE_STAGE = 'writers-room-cd-bridge';
+// Exported so other conductors that mint a CD project from prose — the
+// pipeline→CD "produce video from issue" bridge (CDO Phase 3, #2185) — reuse the
+// SAME stage + proposal shaper rather than duplicating the treatment-from-prose
+// contract.
+export 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
@@ -157,7 +161,7 @@ function shapeBridgeScene(raw) {
// 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) {
+export function shapeProposal(parsed) {
const scenes = (Array.isArray(parsed?.scenes) ? parsed.scenes : [])
.map(shapeBridgeScene)
.filter(Boolean)
@@ -218,6 +222,24 @@ export async function suggestCdBridge(workId, { before = '', after = '', selecti
return { proposal, usage, budget: live.dailyCallBudget };
}
+/**
+ * Assign the CD scene runtime fields the treatment schema requires but a raw
+ * CD-bridge LLM proposal doesn't carry: a stable sceneId, render order, and the
+ * continuation flag (every scene after the first continues from its prior).
+ * Exported so the pipeline→CD bridge (CDO Phase 3, #2185) maps proposal scenes
+ * into a treatment identically to the writers-room send path.
+ */
+export function bridgeScenesToTreatmentScenes(scenes) {
+ return (Array.isArray(scenes) ? scenes : []).map((s, i) => ({
+ sceneId: `sc-${i + 1}`,
+ order: i,
+ intent: s.intent,
+ prompt: s.prompt,
+ durationSeconds: s.durationSeconds,
+ useContinuationFromPrior: i > 0,
+ }));
+}
+
/**
* Send a reviewed CD-bridge proposal into a NEW Creative Director project.
* Non-destructive (never clobbers an existing project's treatment): it mints a
@@ -236,14 +258,7 @@ export async function sendToCreativeDirector(workId, { proposal } = {}) {
// 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,
- }));
+ const scenes = bridgeScenesToTreatmentScenes(proposal.scenes);
// 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