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
add CDO creative render tools with route-level cover persistence
[._.]/ Adam Eivy37cac885fbd6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d73759b859..9d178ea7ac 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -110,4 +110,6 @@- **[issue-2183] Creative Tool Registry + gated dispatch (CDO Phase 1).** Foundation for the Creative Director orchestrator (epic #2182): a single registry (`server/services/creative/toolRegistry.js` + per-domain modules under `creative/tools/`) of creative-suite tools an orchestrating agent can call — universe, story builder, writers room, pipeline, media, catalog — each a thin conductor wrapper over an existing service entry point (`createUniverse`, `generateStep`, `startSeriesAutopilot`, `enqueueJob`, …), never a re-implementation. All orchestrator calls flow through one governed chokepoint, `dispatchCreativeTool(name, args, ctx)`, which validates args (Zod), enforces a new `creative` autonomy mode, charges the daily action budget for `llm`/`render` tools, and appends a `{tool, argsDigest, outcome, timing}` entry to the calling project's run ledger. The `creative` autonomy domain (`server/lib/domainAutonomy.js` `getCreativeAutonomyMode`) is kept separate from the four core domains and defaults to mirror the `cos` mode, so existing autopilot users get consistent behavior with no migration, while an explicit `domainAutonomy.creative` value can override it later. Direct user actions through the existing routes are unchanged — the gate lives only on the orchestrator path. No user-facing surface yet; the directive composer and plan board arrive in later CDO phases.+- **[issue-2220] Creative render tools with route-level persistence (CDO Phase 2 slice).** The Creative Director orchestrator can now render comic-issue and volume (season) covers — `pipeline_renderComicCover`, `pipeline_renderComicBackCover`, `pipeline_renderVolumeCover`, `pipeline_renderVolumeBackCover` are registered creative tools. These render jobs need more than a bare enqueue: the media-job filename hook attaches the finished image only if the target cover slot already carries the returned `jobId`, and that slot write used to live in the route factory (`routes/pipeline/covers.js#makeCoverRenderHandler`), so wrapping the bare `enqueueComicCover`-style service in a tool would silently drop orchestrated covers. The enqueue+persist flow (build the in-flight render slot, script-gate, write it onto the record) now lives in shared service entry points — `renderComicCover` / `renderComicBackCover` (→ `stages.comicPages.{cover|backCover}` via the serialized `updateStageWithLatest` series write tail) and `renderVolumeCover` / `renderVolumeBackCover` (→ `series.seasons[].{cover|backCover}` via `updateSeasonOnSeries`) in `visualStages.js` — so the four cover-render routes and the four orchestrator tools share ONE code path. The persist keeps the script-gate semantics (absent `coverScript` preserves the persisted concept, empty string clears it) and serializes against a concurrent blur-save on the same record. Tools charge as `render` against the daily action budget. Cover render is the primary deliverable; wrapping the remaining route-persisted render actions (comic page render / refine-render) as tools stays tracked on #2220.+- **`getSettings()` now serves from an in-memory cache instead of re-reading settings.json on every call.** `getSettings()` is invoked 100+ times across the codebase (several per request), each previously doing a fresh filesystem read + JSON.parse of app-wide, rarely-changing data. It now memoizes the parsed settings, populated lazily on first read and refreshed off the `settings:updated` event that every `save()`/`updateSettings()`/`updateSettingsWith()` already emits — so app-driven writes keep the cache coherent while write paths still read fresh off disk inside their write queue for the read-merge-write, preserving write-ordering guarantees. Mirrors the existing `settings:updated`-invalidated cache in `sharing/annotationIdentity.js`. Alongside it, a few independent per-file read loops are now parallelized (`digital-twin-analysis.validateCompleteness`, editorial series-health's series+settings load) and hot page derivations memoized (`Review` grouping/sorting, `Tribe` care-queue), cutting redundant work on socket-driven re-renders.diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 2f14f9bc35..273c863987 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -76,7 +76,59 @@ vi.mock('../services/pipeline/autoRunner.js', () => ({isAutoRunActive: vi.fn(() => false),}));-vi.mock('../services/pipeline/visualStages.js', () => ({+vi.mock('../services/pipeline/visualStages.js', async () => {+ // The four cover-render entry points persist the in-flight slot themselves+ // now (#2220) — that write moved out of the route factory and into the+ // service. Drive it through the REAL (unmocked) issues/series write tails so+ // the route tests still exercise the persist + serialized-write + script-gate+ // behavior end-to-end. Mirrors renderComicCoverLike / renderVolumeCoverLike.+ const issuesSvc = await import('../services/pipeline/issues.js');+ const seriesSvc = await import('../services/pipeline/series.js');+ const { buildRenderSlot: buildSlot } = await import('../lib/renderSlot.js');+ const { slotKeyForVariant } = await import('../services/pipeline/owners.js');++ const persistComicCover = async (issueId, target, scriptField, body) => {+ const variant = body?.target === 'final' ? 'final' : 'proof';+ const jobId = `${target === 'cover' ? 'cover' : 'backcover'}-job-${++uuidCounter}`;+ const prompt = target === 'cover' ? 'cover art prompt' : 'back cover art prompt';+ const fromProof = variant === 'final' && body?.useProofAsBase === true;+ const slotKey = slotKeyForVariant(variant);+ const slotRecord = buildSlot({ slotKey, jobId, prompt, width: body?.width, height: body?.height, fromProof });+ const { issue, stage } = await issuesSvc.updateStageWithLatest(issueId, 'comicPages', (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof body?.[scriptField] === 'string') nextSlot.script = body[scriptField];+ return { [target]: nextSlot };+ });+ return {+ jobId, mode: 'local', prompt, variant, fromProof,+ [scriptField]: body?.[scriptField] ?? `default ${target === 'cover' ? 'cover' : 'back cover'} concept`,+ issue, stage,+ };+ };++ const persistVolumeCover = async (seriesId, seasonId, target, scriptField, body) => {+ const variant = body?.target === 'final' ? 'final' : 'proof';+ const jobId = `vol-${target === 'cover' ? 'cover' : 'backcover'}-job-${++uuidCounter}`;+ const prompt = target === 'cover' ? 'volume cover art prompt' : 'volume back cover art prompt';+ const fromProof = variant === 'final' && body?.useProofAsBase === true;+ const slotKey = slotKeyForVariant(variant);+ const slotRecord = buildSlot({ slotKey, jobId, prompt, width: body?.width, height: body?.height, fromProof });+ const series = await seriesSvc.updateSeasonOnSeries(seriesId, seasonId, (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof body?.[scriptField] === 'string') nextSlot.script = body[scriptField];+ return { [target]: nextSlot };+ });+ const season = (series.seasons || []).find((s) => s.id === seasonId);+ return {+ jobId, mode: 'local', prompt, variant, fromProof,+ [scriptField]: body?.[scriptField] ?? `default volume ${target === 'cover' ? 'cover' : 'back cover'} concept`,+ season, series,+ };+ };++ return {enqueueVisualImage: vi.fn(async (_issueId, stageId, opts) => ({jobId: `job-${++uuidCounter}`,mode: 'local',@@ -93,45 +145,15 @@ vi.mock('../services/pipeline/visualStages.js', () => ({variant: opts?.target === 'final' ? 'final' : 'proof',fromProof: opts?.target === 'final' && opts?.useProofAsBase === true,})),- // Front cover render. Returns shape the route merges with the persisted cover:- // { jobId, mode, prompt, coverScript, variant, fromProof }.- enqueueComicCover: vi.fn(async (_issueId, body) => ({- jobId: `cover-job-${++uuidCounter}`,- mode: 'local',- prompt: 'cover art prompt',- coverScript: body?.coverScript ?? 'default cover concept',- variant: body?.target === 'final' ? 'final' : 'proof',- fromProof: body?.target === 'final' && body?.useProofAsBase === true,- })),- // Back cover render — symmetric with front cover; the route's persist- // logic differs only in field names (backCover slot + backCoverScript).- enqueueComicBackCover: vi.fn(async (_issueId, body) => ({- jobId: `backcover-job-${++uuidCounter}`,- mode: 'local',- prompt: 'back cover art prompt',- backCoverScript: body?.backCoverScript ?? 'default back cover concept',- variant: body?.target === 'final' ? 'final' : 'proof',- fromProof: body?.target === 'final' && body?.useProofAsBase === true,- })),- // Volume (season) front + back cover. Route writes to series.seasons[].cover- // / .backCover via seriesSvc.updateSeasonOnSeries, so the mock shape mirrors- // the comic-cover mocks.- enqueueVolumeCover: vi.fn(async (_seriesId, _seasonId, body) => ({- jobId: `vol-cover-job-${++uuidCounter}`,- mode: 'local',- prompt: 'volume cover art prompt',- coverScript: body?.coverScript ?? 'default volume cover concept',- variant: body?.target === 'final' ? 'final' : 'proof',- fromProof: body?.target === 'final' && body?.useProofAsBase === true,- })),- enqueueVolumeBackCover: vi.fn(async (_seriesId, _seasonId, body) => ({- jobId: `vol-backcover-job-${++uuidCounter}`,- mode: 'local',- prompt: 'volume back cover art prompt',- backCoverScript: body?.backCoverScript ?? 'default volume back cover concept',- variant: body?.target === 'final' ? 'final' : 'proof',- fromProof: body?.target === 'final' && body?.useProofAsBase === true,- })),+ // Front cover render+persist. Lands the in-flight slot on+ // stages.comicPages.cover through the real issue write tail (#2220).+ renderComicCover: vi.fn((issueId, body) => persistComicCover(issueId, 'cover', 'coverScript', body || {})),+ // Back cover render+persist — symmetric; lands on stages.comicPages.backCover.+ renderComicBackCover: vi.fn((issueId, body) => persistComicCover(issueId, 'backCover', 'backCoverScript', body || {})),+ // Volume (season) front + back cover render+persist. Writes to+ // series.seasons[].cover / .backCover through the real per-series write tail.+ renderVolumeCover: vi.fn((seriesId, seasonId, body) => persistVolumeCover(seriesId, seasonId, 'cover', 'coverScript', body || {})),+ renderVolumeBackCover: vi.fn((seriesId, seasonId, body) => persistVolumeCover(seriesId, seasonId, 'backCover', 'backCoverScript', body || {})),// Single-scene video render. Returns the shape the route forwards verbatim// to clients: { jobId, prompt, sceneIndex, issue, stage }.enqueueStoryboardSceneVideo: vi.fn(async (issueId, sceneIndex) => ({@@ -192,7 +214,8 @@ vi.mock('../services/pipeline/visualStages.js', () => ({runId: 'run-mock-page-refine',providerId: 'mock-provider',})),-}));+ };+});// The episode-video handoff creates a CD project; stub it so the route test// doesn't have to spin up the whole CD machinery.diff --git a/server/routes/pipeline/covers.js b/server/routes/pipeline/covers.jsindex bc076b6003..b6400fc5a8 100644--- a/server/routes/pipeline/covers.js+++ b/server/routes/pipeline/covers.js@@ -15,17 +15,14 @@ import {refineImagePixelCap,PIXEL_CAP_MESSAGE,} from '../../lib/validation.js';-import * as seriesSvc from '../../services/pipeline/series.js';-import * as issuesSvc from '../../services/pipeline/issues.js';import * as arcPlanner from '../../services/pipeline/arcPlanner.js';import {- enqueueComicCover,- enqueueComicBackCover,- enqueueVolumeCover,- enqueueVolumeBackCover,- buildRenderSlot,+ renderComicCover,+ renderComicBackCover,+ renderVolumeCover,+ renderVolumeBackCover,} from '../../services/pipeline/visualStages.js';-import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../../services/pipeline/owners.js';+import { COMIC_PAGE_VARIANTS } from '../../services/pipeline/owners.js';import { IMAGE_GEN_MODE } from '../../services/imageGen/modes.js';import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE } from '../../services/pipeline/comicPdf.js';import { buildVolumePdf } from '../../services/pipeline/volumePdf.js';@@ -95,70 +92,34 @@ router.post('/series/:id/seasons/:seasonId/cover-concepts/generate', asyncHandleres.json(result);}));-// Cover-render factory — shared by the four cover-render routes (volume-// front/back + comic-issue front/back).-//-// Script-gate semantics: only update `script` when the body carried the-// field as a string — absent preserves, empty-string intentionally clears.-// Blur-save (PATCH stages/.../cover) owns the script field and races-// against render; writing the *resolved* value (which falls back to the-// persisted record's script when absent) would clobber a concurrent blur.-const buildCoverPatchFn = ({ slotField, scriptField, body, slotKey, slotRecord }) => (current) => {- const currentSlot = current?.[slotField] || {};- const nextSlot = { ...currentSlot, [slotKey]: slotRecord };- if (typeof body[scriptField] === 'string') nextSlot.script = body[scriptField];- return { [slotField]: nextSlot };-};--const makeCoverRenderHandler = ({- schema, slotField, scriptField, enqueue, applyWrite, buildResponse,-}) => asyncHandler(async (req, res) => {+// Cover-render route factory — shared by the four cover-render routes (volume+// front/back + comic-issue front/back). The enqueue+persist flow (build the+// render slot, script-gate, write it onto the record through the serialized+// write tail) now lives in the shared `renderXxx` service entry points+// (visualStages.js) so the route and the CDO orchestrator tool share ONE code+// path (#2220). The route keeps only Zod validation, service dispatch, and+// response shaping.+const makeCoverRenderHandler = ({ schema, render, buildResponse }) => asyncHandler(async (req, res) => {const body = validateRequest(schema, req.body ?? {});- const result = await enqueue(req, body).catch((err) => { throw mapServiceError(err); });-- const slotKey = slotKeyForVariant(result.variant);- const slotRecord = buildRenderSlot({- slotKey, jobId: result.jobId, prompt: result.prompt,- width: body.width, height: body.height, fromProof: result.fromProof,- });- const computeFn = buildCoverPatchFn({ slotField, scriptField, body, slotKey, slotRecord });- const writeResult = await applyWrite(req, computeFn)- .catch((err) => { throw mapServiceError(err); });- res.json(buildResponse({ result, writeResult, req }));+ const result = await render(req, body).catch((err) => { throw mapServiceError(err); });+ res.json(buildResponse({ result, req }));});-const buildVolumeCoverResponse = ({ result, writeResult: series, req }) => {- const season = (series.seasons || []).find((s) => s.id === req.params.seasonId);- return { ...result, season, series };-};--const updateVolumeSeason = (req, computeFn) =>- seriesSvc.updateSeasonOnSeries(req.params.id, req.params.seasonId, computeFn);--const updateComicPagesStage = (req, computeFn) =>- issuesSvc.updateStageWithLatest(req.params.id, 'comicPages', computeFn);--// Render the volume front cover. Persists the in-flight render slot onto-// season.cover via seriesSvc.updateSeasonOnSeries (queue-serialized) — the-// season-cover filename hook stamps the completed filename later.+// Render the volume front cover. `renderVolumeCover` persists the in-flight+// render slot onto season.cover through updateSeasonOnSeries (queue-serialized)+// — the season-cover filename hook stamps the completed filename later.// (Missing series / season surface as PIPELINE_SEASON_NOT_FOUND from// enqueueVolumeCover's loadSeasonContext, mapped to 404 by mapServiceError.)router.post('/series/:id/seasons/:seasonId/cover/render', makeCoverRenderHandler({schema: volumeCoverRenderSchema,- slotField: 'cover',- scriptField: 'coverScript',- enqueue: (req, body) => enqueueVolumeCover(req.params.id, req.params.seasonId, body),- applyWrite: updateVolumeSeason,- buildResponse: buildVolumeCoverResponse,+ render: (req, body) => renderVolumeCover(req.params.id, req.params.seasonId, body),+ buildResponse: ({ result }) => result,}));router.post('/series/:id/seasons/:seasonId/back-cover/render', makeCoverRenderHandler({schema: volumeBackCoverRenderSchema,- slotField: 'backCover',- scriptField: 'backCoverScript',- enqueue: (req, body) => enqueueVolumeBackCover(req.params.id, req.params.seasonId, body),- applyWrite: updateVolumeSeason,- buildResponse: buildVolumeCoverResponse,+ render: (req, body) => renderVolumeBackCover(req.params.id, req.params.seasonId, body),+ buildResponse: ({ result }) => result,}));// Compile a trade-paperback PDF: volume front → for each issue@@ -203,12 +164,8 @@ router.post('/issues/:id/cover-concepts/generate', asyncHandler(async (req, res)// running; the filename hook stamps `filename` on completion.router.post('/issues/:id/stages/comicPages/cover/render', makeCoverRenderHandler({schema: comicCoverRenderSchema,- slotField: 'cover',- scriptField: 'coverScript',- enqueue: (req, body) => enqueueComicCover(req.params.id, body),- applyWrite: updateComicPagesStage,- buildResponse: ({ result, writeResult: { issue, stage } }) =>- ({ ...result, cover: stage.cover, issue, stage }),+ render: (req, body) => renderComicCover(req.params.id, body),+ buildResponse: ({ result }) => ({ ...result, cover: result.stage.cover }),}));// Render the comic-issue BACK cover. Same flow as the front-cover route;@@ -216,12 +173,8 @@ router.post('/issues/:id/stages/comicPages/cover/render', makeCoverRenderHandler// persisted slot (`stages.comicPages.backCover.{proofImage|finalImage}`).router.post('/issues/:id/stages/comicPages/back-cover/render', makeCoverRenderHandler({schema: comicBackCoverRenderSchema,- slotField: 'backCover',- scriptField: 'backCoverScript',- enqueue: (req, body) => enqueueComicBackCover(req.params.id, body),- applyWrite: updateComicPagesStage,- buildResponse: ({ result, writeResult: { issue, stage } }) =>- ({ ...result, backCover: stage.backCover, issue, stage }),+ render: (req, body) => renderComicBackCover(req.params.id, body),+ buildResponse: ({ result }) => ({ ...result, backCover: result.stage.backCover }),}));// Print-ready PDF export of a comic issue's rendered pages. Streams thediff --git a/server/services/creative/toolRegistry.test.js b/server/services/creative/toolRegistry.test.jsindex ff58111e56..77e70c1f9d 100644--- a/server/services/creative/toolRegistry.test.js+++ b/server/services/creative/toolRegistry.test.js@@ -61,6 +61,12 @@ vi.mock('../pipeline/series.js', () => ({ createSeries: vi.fn(async () => ({ id:vi.mock('../pipeline/seriesGenerate.js', () => ({ generateSeriesConcept: vi.fn(async () => ({ name: 'C' })) }));vi.mock('../pipeline/textStages.js', () => ({ generateStage: vi.fn(async () => ({ stage: 'st' })) }));vi.mock('../pipeline/seriesAutopilot.js', () => ({ startSeriesAutopilot: vi.fn(async () => ({ runId: 'ap1' })) }));+vi.mock('../pipeline/visualStages.js', () => ({+ renderComicCover: vi.fn(async () => ({ jobId: 'cov1', variant: 'proof' })),+ renderComicBackCover: vi.fn(async () => ({ jobId: 'bcov1', variant: 'proof' })),+ renderVolumeCover: vi.fn(async () => ({ jobId: 'vcov1', variant: 'proof' })),+ renderVolumeBackCover: vi.fn(async () => ({ jobId: 'vbcov1', variant: 'proof' })),+}));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj1' })) }));vi.mock('../catalogDB.js', () => ({ listIngredients: vi.fn(async () => ({ items: [] })) }));vi.mock('../creativeDirector/autoCast.js', () => ({ suggestCastForBrief: vi.fn(async () => []) }));@@ -71,6 +77,7 @@ import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';import { createSeries } from '../pipeline/series.js';import { generateStage } from '../pipeline/textStages.js';import { startSeriesAutopilot } from '../pipeline/seriesAutopilot.js';+import { renderComicCover, renderVolumeCover } from '../pipeline/visualStages.js';import { enqueueJob } from '../mediaJobQueue/index.js';import {CREATIVE_TOOLS,@@ -257,6 +264,28 @@ describe('budget charging', () => {expect(getDomainBudgetStatus).not.toHaveBeenCalled();expect(recordDomainUsage).not.toHaveBeenCalled();});++ // #2220 — the cover-render tools wrap the shared render+persist service so an+ // orchestrated cover completes like a user-driven one; they charge as renders.+ it('dispatches pipeline_renderComicCover through the shared render service and charges one render action', async () => {+ setMode('execute');+ const out = await dispatchCreativeTool('pipeline_renderComicCover', { issueId: 'i1', coverScript: 'c' });+ expect(out).toMatchObject({ ok: true, tool: 'pipeline_renderComicCover', longRunning: true });+ expect(renderComicCover).toHaveBeenCalledWith('i1', { coverScript: 'c' });+ expect(recordDomainUsage).toHaveBeenCalledWith('cos', { actions: 1 });+ });++ it('dispatches pipeline_renderVolumeCover with seriesId + seasonId split from options', async () => {+ setMode('execute');+ await dispatchCreativeTool('pipeline_renderVolumeCover', { seriesId: 'ser1', seasonId: 'sea1', target: 'final' });+ expect(renderVolumeCover).toHaveBeenCalledWith('ser1', 'sea1', { target: 'final' });+ });++ it('rejects a cover-render tool call missing its required id via the Zod gate', async () => {+ setMode('execute');+ await expect(dispatchCreativeTool('pipeline_renderComicCover', {})).rejects.toBeInstanceOf(z.ZodError);+ expect(renderComicCover).not.toHaveBeenCalled();+ });});describe('wrapped-service self-rejection', () => {diff --git a/server/services/creative/tools/pipeline.js b/server/services/creative/tools/pipeline.jsindex 79f82455fa..ee7ad69211 100644--- a/server/services/creative/tools/pipeline.js+++ b/server/services/creative/tools/pipeline.js@@ -9,16 +9,53 @@ import { createSeries } from '../../pipeline/series.js';import { generateSeriesConcept } from '../../pipeline/seriesGenerate.js';import { generateStage } from '../../pipeline/textStages.js';import { startSeriesAutopilot } from '../../pipeline/seriesAutopilot.js';-import { COST_FREE, COST_LLM } from './shared.js';+import {+ renderComicCover,+ renderComicBackCover,+ renderVolumeCover,+ renderVolumeBackCover,+} from '../../pipeline/visualStages.js';+import { COST_FREE, COST_LLM, COST_RENDER } from './shared.js';-// NOTE: a `pipeline_enqueueComicCover` tool is intentionally NOT registered yet.-// The bare `enqueueComicCover()` service only queues the job — the cover's-// filename hook attaches the completed render only if the issue's active cover-// slot already carries the returned jobId, and that slot write lives in the-// route factory (routes/pipeline/covers.js#makeCoverRenderHandler), not the-// service. Wrapping the bare service would silently drop orchestrated covers;-// wrapping it faithfully needs the route's enqueue+persist flow extracted into a-// shared service first. Tracked as follow-up #2220.+// Shared render-option schema for the cover-render tools — mirrors the route's+// makeCoverRenderSchema (routes/pipeline/covers.js) so the orchestrator flows+// the same image-gen knobs the UI drawer does. Each tool merges its own script+// field (coverScript / backCoverScript) on top. The `renderXxx` services+// enqueue AND persist the in-flight render slot the filename hook needs (#2220),+// so an orchestrated cover completes exactly like a user-driven one — the bare+// `enqueueComicCover` was deliberately kept off the registry because it only+// queued the job and dropped the completed render.+const coverRenderOptionsShape = {+ negativePrompt: z.string().max(2000).optional(),+ extraStyle: z.string().max(2000).optional(),+ mode: z.enum(['local', 'codex']).optional(),+ modelId: z.string().max(64).optional(),+ width: z.number().int().positive().optional(),+ height: z.number().int().positive().optional(),+ steps: z.number().int().min(1).max(150).optional(),+ cfgScale: z.number().min(0).max(30).optional(),+ guidance: z.number().min(0).max(30).optional(),+ seed: z.number().int().min(0).optional(),+ target: z.enum(['proof', 'final']).optional(),+ useProofAsBase: z.boolean().optional(),+};++// OpenAI-function `parameters` fragment mirroring coverRenderOptionsShape so the+// orchestrator sees the render knobs it can pass.+const coverRenderParamProps = {+ negativePrompt: { type: 'string', description: 'Negative prompt tokens.' },+ extraStyle: { type: 'string', description: 'Extra style direction appended to the prompt.' },+ mode: { type: 'string', enum: ['local', 'codex'], description: 'Image-gen mode (defaults to the configured mode).' },+ modelId: { type: 'string', description: 'Image model id override.' },+ width: { type: 'integer', description: 'Render width in px.' },+ height: { type: 'integer', description: 'Render height in px.' },+ steps: { type: 'integer', description: 'Sampler steps.' },+ cfgScale: { type: 'number', description: 'CFG scale.' },+ guidance: { type: 'number', description: 'Guidance scale.' },+ seed: { type: 'integer', description: 'Deterministic seed.' },+ target: { type: 'string', enum: ['proof', 'final'], description: "Variant to render — 'proof' (fast layout) or 'final' (hi-res). Defaults to 'proof'." },+ useProofAsBase: { type: 'boolean', description: "For target=final: upscale off this slot's existing proof (i2i)." },+};export const PIPELINE_TOOLS = [{@@ -90,4 +127,74 @@ export const PIPELINE_TOOLS = [},execute: ({ seriesId, options }) => startSeriesAutopilot(seriesId, options || {}),},+ {+ name: 'pipeline_renderComicCover',+ description: "Enqueue AND persist a comic-issue FRONT cover render. Long-running: returns { jobId, ... }; the finished image attaches to stages.comicPages.cover via the media-job filename hook. Pass coverScript to set/update the persisted cover concept in the same call.",+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ issueId: z.string().min(1), coverScript: z.string().max(8000).optional(), ...coverRenderOptionsShape }),+ parameters: {+ type: 'object',+ properties: {+ issueId: { type: 'string', description: 'Comic issue id.' },+ coverScript: { type: 'string', description: 'Cover-art concept text; absent preserves the persisted script, empty string clears it.' },+ ...coverRenderParamProps,+ },+ required: ['issueId'],+ },+ execute: ({ issueId, ...options }) => renderComicCover(issueId, options),+ },+ {+ name: 'pipeline_renderComicBackCover',+ description: "Enqueue AND persist a comic-issue BACK cover render. Long-running: the finished image attaches to stages.comicPages.backCover via the filename hook. Pass backCoverScript to set/update the persisted back-cover concept.",+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ issueId: z.string().min(1), backCoverScript: z.string().max(8000).optional(), ...coverRenderOptionsShape }),+ parameters: {+ type: 'object',+ properties: {+ issueId: { type: 'string', description: 'Comic issue id.' },+ backCoverScript: { type: 'string', description: 'Back-cover concept text; absent preserves, empty string clears.' },+ ...coverRenderParamProps,+ },+ required: ['issueId'],+ },+ execute: ({ issueId, ...options }) => renderComicBackCover(issueId, options),+ },+ {+ name: 'pipeline_renderVolumeCover',+ description: "Enqueue AND persist a volume (season) FRONT cover render. Long-running: the finished image attaches to series.seasons[].cover via the season-cover filename hook. Pass coverScript to set/update the persisted concept.",+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ seriesId: z.string().min(1), seasonId: z.string().min(1), coverScript: z.string().max(8000).optional(), ...coverRenderOptionsShape }),+ parameters: {+ type: 'object',+ properties: {+ seriesId: { type: 'string', description: 'Series id.' },+ seasonId: { type: 'string', description: 'Season (volume) id on the series.' },+ coverScript: { type: 'string', description: 'Cover-art concept text; absent preserves, empty string clears.' },+ ...coverRenderParamProps,+ },+ required: ['seriesId', 'seasonId'],+ },+ execute: ({ seriesId, seasonId, ...options }) => renderVolumeCover(seriesId, seasonId, options),+ },+ {+ name: 'pipeline_renderVolumeBackCover',+ description: "Enqueue AND persist a volume (season) BACK cover render. Long-running: the finished image attaches to series.seasons[].backCover via the season-cover filename hook. Pass backCoverScript to set/update the persisted concept.",+ costClass: COST_RENDER,+ longRunning: true,+ schema: z.object({ seriesId: z.string().min(1), seasonId: z.string().min(1), backCoverScript: z.string().max(8000).optional(), ...coverRenderOptionsShape }),+ parameters: {+ type: 'object',+ properties: {+ seriesId: { type: 'string', description: 'Series id.' },+ seasonId: { type: 'string', description: 'Season (volume) id on the series.' },+ backCoverScript: { type: 'string', description: 'Back-cover concept text; absent preserves, empty string clears.' },+ ...coverRenderParamProps,+ },+ required: ['seriesId', 'seasonId'],+ },+ execute: ({ seriesId, seasonId, ...options }) => renderVolumeBackCover(seriesId, seasonId, options),+ },];diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex cf49472952..a25a76fed8 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -25,10 +25,10 @@import { enqueueJob } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';-import { getSeries } from './series.js';-import { getIssue, updateStage, assertStageUnlocked, VISUAL_STAGE_IDS } from './issues.js';+import { getSeries, updateSeasonOnSeries } from './series.js';+import { getIssue, updateStage, updateStageWithLatest, assertStageUnlocked, VISUAL_STAGE_IDS } from './issues.js';import { resolveGalleryImage } from '../../lib/fileUtils.js';-import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner } from './owners.js';+import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner, slotKeyForVariant } from './owners.js';import { getUniverse, joinInfluenceList } from '../universeBuilder.js';import { ServerError } from '../../lib/errorHandler.js';import {@@ -151,9 +151,12 @@ const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');// `buildRenderSlot` moved to server/lib/renderSlot.js so season-cover// render paths (which don't import from visualStages.js) can share the-// shape. Re-exported here for back-compat with route-level callers that-// still import it from this module.-export { buildRenderSlot } from '../../lib/renderSlot.js';+// shape. Imported for the shared cover-render persist path below and+// re-exported for back-compat with route-level callers that still import it+// from this module.+import { buildRenderSlot } from '../../lib/renderSlot.js';++export { buildRenderSlot };// Default denoise strength for the "use proof as base" upscale path. Low// enough to preserve composition (panel layout, character placement),@@ -651,6 +654,57 @@ export async function enqueueComicBackCover(issueId, options = {}) {return { ...rest, backCoverScript: script };}+/**+ * Enqueue + persist a comic-issue cover render (front or back) in ONE service+ * call — the shared entry point behind both the route handler and the CDO+ * orchestrator tool (#2220). The bare `enqueueComicCover*` only queues the job;+ * the filename hook attaches the completed render ONLY if the active cover slot+ * already carries the returned jobId, and that slot write used to live in the+ * route factory. Extracting it here means the orchestrator gets orchestrated+ * covers instead of silently dropping them.+ *+ * Persists the in-flight render slot onto+ * `stages.comicPages.{cover|backCover}.{proofImage|finalImage}` through+ * `updateStageWithLatest` (the series write tail) so it serializes against a+ * concurrent blur-save of the script field — the script-gate mirrors the route:+ * only overwrite `script` when the option is a string (absent preserves, empty+ * clears). `options` mirrors the route body (coverScript/backCoverScript,+ * width/height, target, useProofAsBase, mode, …).+ *+ * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,+ * issue, stage } — the enqueue result plus the persisted issue + comicPages stage.+ */+async function renderComicCoverLike(issueId, target, options = {}) {+ const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const { script, ...rest } = await enqueueComicCoverLike(issueId, target, options);+ const slotKey = slotKeyForVariant(rest.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: rest.jobId, prompt: rest.prompt,+ width: options.width, height: options.height, fromProof: rest.fromProof,+ });+ const { issue, stage } = await updateStageWithLatest(issueId, 'comicPages', (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];+ return { [target]: nextSlot };+ });+ return { ...rest, [scriptField]: script, issue, stage };+}++/**+ * Enqueue + persist a comic-issue FRONT cover render. Wraps `enqueueComicCover`+ * plus the slot persist the filename hook depends on. See `renderComicCoverLike`.+ */+export const renderComicCover = (issueId, options = {}) =>+ renderComicCoverLike(issueId, 'cover', options);++/**+ * Enqueue + persist a comic-issue BACK cover render. Lands on+ * `stages.comicPages.backCover`. See `renderComicCoverLike`.+ */+export const renderComicBackCover = (issueId, options = {}) =>+ renderComicCoverLike(issueId, 'backCover', options);+// ---- Volume (season) covers ---------------------------------------------const loadSeasonContext = async (seriesId, seasonId) => {@@ -775,6 +829,49 @@ export async function enqueueVolumeBackCover(seriesId, seasonId, options = {}) {return { ...rest, backCoverScript: script };}+/**+ * Enqueue + persist a volume (season) cover render (front or back) in ONE+ * service call — the shared entry point behind both the route handler and the+ * CDO orchestrator (#2220). Mirrors `renderComicCoverLike` but persists the+ * in-flight slot onto `series.seasons[].{cover|backCover}` through+ * `updateSeasonOnSeries` (the per-series write tail) so the season-cover+ * filename hook can attach the completed render.+ *+ * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,+ * season, series } — the enqueue result plus the updated season + series.+ */+async function renderVolumeCoverLike(seriesId, seasonId, target, options = {}) {+ const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, target, options);+ const slotKey = slotKeyForVariant(rest.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: rest.jobId, prompt: rest.prompt,+ width: options.width, height: options.height, fromProof: rest.fromProof,+ });+ const series = await updateSeasonOnSeries(seriesId, seasonId, (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];+ return { [target]: nextSlot };+ });+ const season = (series.seasons || []).find((s) => s.id === seasonId);+ return { ...rest, [scriptField]: script, season, series };+}++/**+ * Enqueue + persist a volume (season) FRONT cover render. See+ * `renderVolumeCoverLike`.+ */+export const renderVolumeCover = (seriesId, seasonId, options = {}) =>+ renderVolumeCoverLike(seriesId, seasonId, 'cover', options);++/**+ * Enqueue + persist a volume (season) BACK cover render. See+ * `renderVolumeCoverLike`.+ */+export const renderVolumeBackCover = (seriesId, seasonId, options = {}) =>+ renderVolumeCoverLike(seriesId, seasonId, 'backCover', options);+export function composeComicPagePrompt({series, world, page, pageNumber, extraStyle = '',matchedCharacters = [], matchedPlaces = [], matchedObjects = [],diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 69d6d3f116..ad64ab1f97 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -32,16 +32,35 @@ const updateStageMock = vi.fn(async (issueId, stageId, patch) => ({stage: { ...mockIssue.stages[stageId], ...patch },}));const assertStageUnlockedMock = vi.fn(() => undefined);+// updateStageWithLatest runs the caller's computeFn against the latest comicPages+// stage (mirrors the real serialized-write behavior) so the render+persist tests+// can assert the exact slot the route/tool would write.+const updateStageWithLatestMock = vi.fn(async (issueId, stageId, computeFn) => {+ const current = structuredClone(mockIssue.stages[stageId] || {});+ const patch = computeFn(current);+ const stage = { ...current, ...patch };+ return { issue: { ...mockIssue, stages: { ...mockIssue.stages, [stageId]: stage } }, stage };+});vi.mock('./issues.js', () => ({getIssue: (...a) => getIssueMock(...a),updateStage: (...a) => updateStageMock(...a),+ updateStageWithLatest: (...a) => updateStageWithLatestMock(...a),assertStageUnlocked: (...a) => assertStageUnlockedMock(...a),VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],}));+const SEASON = { id: 'sea-test', number: 1, title: 'Volume One' };+// updateSeasonOnSeries runs the caller's patchFn against the target season and+// returns the merged series (mirrors the real per-series write tail).+const updateSeasonOnSeriesMock = vi.fn(async (seriesId, seasonId, patchFn) => {+ const patch = patchFn(structuredClone(SEASON));+ const season = { ...SEASON, ...patch };+ return { id: seriesId, seasons: [season] };+});vi.mock('./series.js', () => ({- getSeries: vi.fn(async () => ({ id: 'ser-test', name: 'Test', styleNotes: 'noir', characters: [], settings: [] })),+ getSeries: vi.fn(async () => ({ id: 'ser-test', name: 'Test', styleNotes: 'noir', characters: [], settings: [], seasons: [SEASON] })),+ updateSeasonOnSeries: (...a) => updateSeasonOnSeriesMock(...a),STYLE_PROMPT_OVERRIDE_MODE_DEFAULT: 'prepend',}));@@ -88,6 +107,10 @@ const {composeVolumeCoverPrompt,composeTitleScreenPrompt,enqueueComicCover,+ renderComicCover,+ renderComicBackCover,+ renderVolumeCover,+ renderVolumeBackCover,enqueueStoryboardSceneVideo,enqueueStoryboardShotStartFrame,refineComicPanelPrompt,@@ -109,6 +132,8 @@ const { getUniverse } = await import('../universeBuilder.js');beforeEach(() => {getIssueMock.mockClear();updateStageMock.mockClear();+ updateStageWithLatestMock.mockClear();+ updateSeasonOnSeriesMock.mockClear();assertStageUnlockedMock.mockClear();enqueueJobMock.mockClear();// Restore the default implementation — several #904 tests install a@@ -1136,6 +1161,71 @@ describe('enqueueComicCover', () => {});});+// #2220 — the render+persist entry points behind BOTH the route handler and the+// CDO orchestrator tool: enqueue the job AND write the in-flight slot the+// filename hook depends on (the bare enqueue* alone silently drops orchestrated+// covers).+describe('renderComicCover / renderComicBackCover (enqueue + persist)', () => {+ beforeEach(() => {+ getIssueMock.mockImplementation(async () => ({+ ...structuredClone(mockIssue), number: 5, title: 'Hero Issue',+ }));+ });++ it('enqueues then persists the proof slot onto stages.comicPages.cover.proofImage', async () => {+ const result = await renderComicCover('iss-test', { width: 832, height: 1216 });+ expect(result.jobId).toBe('job-fake-1234');+ expect(enqueueJobMock).toHaveBeenCalledTimes(1);+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'comicPages', expect.any(Function));+ expect(result.stage.cover.proofImage).toMatchObject({+ jobId: 'job-fake-1234', filename: null, width: 832, height: 1216,+ });+ // proof slot must NOT carry the final-only fromProof flag+ expect(result.stage.cover.proofImage).not.toHaveProperty('fromProof');+ });++ it('persists onto finalImage (with fromProof) when target=final + useProofAsBase', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue), number: 5, title: 'Hero',+ stages: { ...mockIssue.stages, comicPages: { ...mockIssue.stages.comicPages, cover: { proofImage: { filename: 'proof.png' } } } },+ });+ const result = await renderComicCover('iss-test', { target: 'final', useProofAsBase: true });+ expect(result.variant).toBe('final');+ expect(result.stage.cover.finalImage).toMatchObject({ jobId: 'job-fake-1234', fromProof: true });+ });++ it('writes the coverScript into the slot only when supplied (absent preserves)', async () => {+ const withScript = await renderComicCover('iss-test', { coverScript: 'new concept' });+ expect(withScript.stage.cover.script).toBe('new concept');++ updateStageWithLatestMock.mockClear();+ const absent = await renderComicCover('iss-test', {});+ // computeFn returned a patch without `script`, so the persisted value is untouched+ expect(absent.stage.cover).not.toHaveProperty('script');+ });++ it('renderComicBackCover lands on the backCover slot', async () => {+ const result = await renderComicBackCover('iss-test', {});+ expect(result.stage.backCover.proofImage.jobId).toBe('job-fake-1234');+ expect(result.backCoverScript).toBeDefined();+ });+});++describe('renderVolumeCover / renderVolumeBackCover (enqueue + persist)', () => {+ it('enqueues then persists the proof slot onto season.cover.proofImage', async () => {+ const result = await renderVolumeCover('ser-test', 'sea-test', { width: 1024, height: 1536 });+ expect(result.jobId).toBe('job-fake-1234');+ expect(updateSeasonOnSeriesMock).toHaveBeenCalledWith('ser-test', 'sea-test', expect.any(Function));+ expect(result.season.cover.proofImage).toMatchObject({ jobId: 'job-fake-1234', width: 1024, height: 1536 });+ expect(result.series.seasons[0].cover.proofImage.jobId).toBe('job-fake-1234');+ });++ it('renderVolumeBackCover lands on the season.backCover slot', async () => {+ const result = await renderVolumeBackCover('ser-test', 'sea-test', {});+ expect(result.season.backCover.proofImage.jobId).toBe('job-fake-1234');+ });+});+describe('refineStoryboardScenePrompt', () => {it('rejects a non-integer sceneIndex', async () => {await expect(refineStoryboardScenePrompt('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);