Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: direct the Cast & Sets check-in procedurally for code-first projects (#9549)
[._.]/ Adam Eivy6c4ebe30a33c
diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxindex 4bbe3f3440..873164c4db 100644--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -118,6 +118,29 @@ describe('AutopilotPanel kickoff', () => {expect(steps.alignLyrics).not.toHaveBeenCalled();});+ it('keeps the Cast & Sets check-in for a code-first project and plans only once it is settled', async () => {+ const project = { id: 'mv-4', trackId: 't1', automation, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 }, audioAnalysis: { sections: [] }, lyricCues: [] };+ const reviewing = { ...project, castAndSets: { status: 'review' } };+ const steps = {+ analyze: vi.fn(), importLyrics: vi.fn(async () => null), separateVocals: vi.fn(), alignLyrics: vi.fn(),+ castAndSets: vi.fn(async () => reviewing),+ plan: vi.fn(async () => {}),+ };+ const { unmount } = render(<KickoffHarness project={project} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(steps.castAndSets).toHaveBeenCalledWith(project));+ // Waiting for the director: nothing is planned yet.+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ expect(steps.plan).not.toHaveBeenCalled();+ unmount();++ steps.castAndSets.mockClear();+ render(<KickoffHarness project={{ ...project, castAndSets: { status: 'approved' } }} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(steps.plan).toHaveBeenCalled());+ expect(steps.castAndSets).not.toHaveBeenCalled();+ });+it('stops when the analysis fails', async () => {const analyzing = deferred();const steps = {diff --git a/client/src/hooks/useMusicVideoKickoff.js b/client/src/hooks/useMusicVideoKickoff.jsindex e959bd01d5..eac33e5ddf 100644--- a/client/src/hooks/useMusicVideoKickoff.js+++ b/client/src/hooks/useMusicVideoKickoff.js@@ -28,7 +28,8 @@ const castAndSetsDone = (project) => ['approved', 'skipped'].includes(project?.c* planned without sections — while a failed lyric, vocal or alignment step* leaves the plan to work with what exists.*- * The check-in is a gate: `castAndSets` resolves once the stage reaches a+ * The check-in runs for every project, code-first ones included (the server+ * picks its medium from the production policy and tools). It is a gate: `castAndSets` resolves once the stage reaches a* checkpoint, and the run plans only when that checkpoint is approved or* skipped. In review mode the stage stops at `review`, so the run ends there* ("Waiting for your check-in"); the director approves and runs the kickoff@@ -67,10 +68,10 @@ export default function useMusicVideoKickoff({ analyze, importLyrics, separateVoenter('align');project = (await attempt(alignLyrics, project)) || project;}- const codeFirst = project.productionPolicy?.strategy === 'code-first';- const needsPerformanceReference = (project.scenes || []).some((scene) => scene.shotMode === 'performance' && !scene.referenceImageId && !scene.videoHistoryId- && project.treatment?.shotDirections?.some((direction) => direction.sceneId === scene.sceneId && direction.medium === 'generated-footage'));- if (castAndSets && (!codeFirst || needsPerformanceReference) && !castAndSetsDone(project)) {+ // Code-first projects keep the check-in: the server directs it in the+ // procedural medium (how the characters are built and move, how the+ // world behaves), not as a photographic cast.+ if (castAndSets && !castAndSetsDone(project)) {enter('castAndSets');const checked = await attempt(castAndSets, project);// Waiting for the director (review), or the check-in failed: stop here.diff --git a/server/lib/musicVideoCreativeContext.js b/server/lib/musicVideoCreativeContext.jsindex 8425f93692..05d33df45d 100644--- a/server/lib/musicVideoCreativeContext.js+++ b/server/lib/musicVideoCreativeContext.js@@ -39,12 +39,30 @@ export function musicVideoCreativeContext(concept, { moodBoard = true } = {}) {export function musicVideoDirectionContext(direction) {if (!direction) return '';const p = direction.protagonist || {};+ // A procedural direction (castAndSetsDirection.js) carries how the cast is+ // built and moves in code and how the world behaves; the same lines reach+ // the planner and any code-authoring prompt that includes this context.+ const procedural = direction.medium === 'procedural';+ const w = direction.world || {};+ const lines = (label, pairs) => {+ const body = pairs.filter(([, v]) => v).map(([k, v]) => `${k}: ${trimTo(v, 300)}`).join('; ');+ return body ? [`${label} ${body}`] : [];+ };return [- 'Cast & Sets direction (authoritative locations and wardrobe):',+ procedural+ ? 'Cast & Sets direction (authoritative characters, environments, motion and camera; characters and scenes are authored in code, never photographed):'+ : 'Cast & Sets direction (authoritative locations and wardrobe):','The mood board is LOOK-ONLY: borrow palette, lighting and texture, never its literal locations, objects or narrative. Use the assigned set for each shot.',`Story: ${trimTo(direction.logline, 400)} ${trimTo(direction.interpretation, 600)}`,`Protagonist: ${[p.name, p.description, p.face, p.hair, p.signature, p.gesture, ...(p.rules || [])].filter(Boolean).map((s) => trimTo(s, 300)).join('; ')}`,+ ...(procedural ? lines('Character build:', [+ ['construction', p.construction], ['shape language', p.shapeLanguage], ['materials', p.materials], ['palette', p.palette],+ ['expressions', (p.expressions || []).join(' | ')], ['movement', p.movement],+ ]) : []),+ ...(procedural ? lines('World rules:', [+ ['layout', w.layout], ['depth', w.depth], ['lighting', w.lighting], ['camera', w.camera], ['transitions', w.transitions],+ ]) : []),...((direction.looks || []).slice(0, 8).map((l) => `Look ${trimTo(l.name, 80)}: ${trimTo(l.description, 300)}; chapters: ${trimTo(l.chapters, 120)}`)),- ...((direction.sets || []).slice(0, 8).map((s) => `Set ${trimTo(s.name, 80)}: ${trimTo(s.description, 300)}; lighting: ${trimTo(s.lighting, 120)}`)),+ ...((direction.sets || []).slice(0, 8).map((s) => `Set ${trimTo(s.name, 80)}: ${trimTo(s.description, 300)}; lighting: ${trimTo(s.lighting, 120)}${procedural ? `; image role: ${s.imageRole || 'background'}` : ''}`)),].join('\n').slice(0, 6000);}diff --git a/server/services/musicVideo/castAndSets.js b/server/services/musicVideo/castAndSets.jsindex 83bbe7ef74..87a95a49e5 100644--- a/server/services/musicVideo/castAndSets.js+++ b/server/services/musicVideo/castAndSets.js@@ -13,7 +13,7 @@* processId, // the server process that may dispatch for it* productionRunId, // the production run that started it, if any* route: { mode, model },- * direction, // castAndSetsDirection.js shape+ * direction, // castAndSetsDirection.js shape (`medium`: absent = photographic)* moodImages: [{ kind, filename }],* plan: { [key]: { key, kind, label, prompt, deps, refKeys, moodRefs?, setId?, testIndex? } },* images: { [key]: { status, jobId, imageId, history, failures, error, updatedAt } },@@ -170,8 +170,14 @@ export function dispatchableImageKeys(stage) {.map((item) => item.key);}-export const allCastAndSetsImagesDone = (stage) => Object.keys(stage?.plan || {}).length > 0- && Object.keys(stage.plan).every((key) => stage.images?.[key]?.status === 'done');+// A procedural direction with no planned images (a code-only project) has+// nothing to render: its characters and worlds are code, so the sheet can go+// straight to review.+export const allCastAndSetsImagesDone = (stage) => {+ const keys = Object.keys(stage?.plan || {});+ if (!keys.length) return stage?.direction?.medium === 'procedural';+ return keys.every((key) => stage.images?.[key]?.status === 'done');+};/*** Reserve one key for dispatch in a serialized write, so two advances cannotdiff --git a/server/services/musicVideo/castAndSetsDirection.js b/server/services/musicVideo/castAndSetsDirection.jsindex f565916faf..c51c8efd14 100644--- a/server/services/musicVideo/castAndSetsDirection.js+++ b/server/services/musicVideo/castAndSetsDirection.js@@ -11,6 +11,15 @@* explicitly that the mood board is look/lighting/texture reference only —* the world comes from the song's own references and themes.*+ * The check-in has two media. `photographic` (the legacy default) asks for a+ * human cast: face, hair, wardrobe looks and in-set test frames. `procedural`+ * (a code-first project, or a brief with code tools and no video tool) asks+ * instead how the characters are BUILT in code (construction, shape language,+ * materials, expressions, movement) and how the world behaves (layout, depth,+ * lighting, camera, transitions), and gives every planned image an intentional+ * role (background, texture, decoration, or an explicit cutout). The medium is+ * stored on the direction so a revision never silently switches it.+ ** A regeneration sends the current direction plus the director's notes and* asks for the full revised object. The merge follows the repo's LLM rule:* a key the model left out keeps the current value; a key present with an@@ -28,15 +37,39 @@ export const CAST_SETS_LIMITS = Object.freeze({tests: { min: 2, max: 4 },moodRefs: { min: 2, max: 4 },rules: 6,+ expressions: 8,questions: 4,overlayElements: 4,});+export const CAST_SETS_IMAGE_ROLES = Object.freeze(['background', 'texture', 'decoration', 'cutout']);const TEXT = 1000;const SHORT = 120;const LYRICS_MAX = 6000;const MOOD_ITEMS_MAX = 40;const MOOD_ITEM_TEXT = 280;+// ---- medium ------------------------------------------------------------------++const briefTools = (project) => (Array.isArray(project?.automation?.tools) ? project.automation.tools.filter((t) => typeof t === 'string') : []);++/**+ * The medium the check-in is directed in. A code-first production policy, or a+ * brief that selected code tools and no video tool, is procedural; everything+ * else (an image-only brief included) stays photographic. Tools and policy are+ * read together because either can be saved without the other.+ */+export function castAndSetsMedium(project) {+ if (project?.productionPolicy?.strategy === 'code-first') return 'procedural';+ const tools = briefTools(project);+ return tools.some((t) => t.startsWith('code:')) && !tools.some((t) => t.startsWith('video:')) ? 'procedural' : 'photographic';+}++/** False when the brief names tools and none of them makes images (a code-only project). */+export function castAndSetsAllowsImages(project) {+ const tools = briefTools(project);+ return tools.length === 0 || tools.some((t) => t.startsWith('image:'));+}+// ---- context ---------------------------------------------------------------const fmtTime = (sec) => {@@ -110,11 +143,44 @@ const OUTPUT_SHAPE = `{"questions": ["<a question for the director>"]}`;+const PROCEDURAL_OUTPUT_SHAPE = `{+ "logline": "<one or two sentences: who, where, what happens>",+ "interpretation": "<how the song's references and themes shape this world>",+ "protagonist": {+ "name": "<a name or designation>",+ "description": "<who or what they are in the song: vibe, attitude>",+ "construction": "<how the character is built in code: the parts, proportions and pivots>",+ "shapeLanguage": "<the shapes that define them: round, angular, stacked, ...>",+ "materials": "<fills, gradients, outlines, glow, texture>",+ "palette": "<the exact colors, as hex values>",+ "expressions": ["<expression name: how the face or shape changes>"],+ "movement": "<motion rules: easing, idle loop, how it reacts to the beat>",+ "signature": "<one detail present in every pose>",+ "gesture": "<a recurring gesture tied to a lyric hook, quoting the hook>",+ "rules": ["<continuity rule>"]+ },+ "looks": [{ "name": "<SHORT NAME>", "description": "<a palette or costume variant>", "chapters": "<which parts of the song>" }],+ "world": {+ "layout": "<how the environments are composed>",+ "depth": "<the layers and parallax planes>",+ "lighting": "<how light behaves across the video>",+ "camera": "<camera behavior: moves, framing, speed>",+ "transitions": "<how one environment hands off to the next>"+ },+ "sets": [{ "id": "<short-slug>", "name": "<set name>", "description": "<the environment, concrete and visual>", "lighting": "<its one dominant light>", "imageRole": "<background | texture | decoration | cutout>", "sections": ["<section label it serves>"] }],+ "songMap": [{ "section": 0, "setId": "<short-slug>" }],+ "overlayConcept": { "summary": "<one persistent graphic layer that ties every shot together>", "elements": [{ "name": "<element>", "description": "<what it shows and when it changes>" }] },+ "moodRefs": [0, 1],+ "questions": ["<a question for the director>"]+}`;+/*** Build the direction prompt. `context` is `{ board, moodImages, track }`* (all optional). With `previous` + `notes` it becomes a revision request.+ * `medium` defaults to the previous direction's, else the project's.*/-export function buildCastAndSetsPrompt(project, { moodImages = [], board = null, track = null, previous = null, notes = [] } = {}) {+export function buildCastAndSetsPrompt(project, { moodImages = [], board = null, track = null, previous = null, notes = [], medium = null } = {}) {+ const procedural = (medium || previous?.medium || castAndSetsMedium(project)) === 'procedural';const concept = project?.concept || {};const analysis = project?.audioAnalysis || {};const sections = songSections(project);@@ -127,7 +193,12 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,const sectionLines = sections.map((s) => `${s.index}. ${s.label} ${fmtTime(s.startSec)}–${fmtTime(s.endSec)}`);const bible = musicVideoCreativeContext(concept);- const header = [+ const header = procedural ? [+ `You are the creative director preparing the CAST & SETS check-in for a PROCEDURAL music video of "${project?.name || 'Untitled'}": its characters and environments are authored in code (SVG, Three.js or canvas), not filmed or photographed.`,+ 'Read the lyrics as a story. Interpret the song: its references, themes and subtext. The world of the video (who the protagonist is, where it happens, what the sets are) must come from that interpretation.',+ 'Design the protagonist as a reusable construction: parts, shape language, materials, a fixed palette, a few named expressions and motion rules that every scene will reuse. Design the world as layered environments with a camera and transition language.',+ 'The mood board is reference for LOOK, LIGHTING, COLOR and TEXTURE only. Never copy its literal locations, rooms or props into the sets.',+ ].join('\n') : [`You are the creative director preparing the CAST & SETS check-in for a music video of "${project?.name || 'Untitled'}".`,'Read the lyrics as a story. Interpret the song: its references, themes and subtext, including any real events, ideas or cultural touchstones the words point at. The world of the video (who the protagonist is, where it happens, what the sets are) must come from that interpretation.','The mood board is reference for LOOK, LIGHTING, COLOR and TEXTURE only. Never copy its literal locations, rooms or props into the sets: a kitchen photo on the board does not put the video in a kitchen.',@@ -147,7 +218,16 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,moodLines.length ? `Mood board images (index. caption — per-image analysis):\n${moodLines.join('\n')}` : 'No mood board images.',].filter(Boolean).join('\n');- const rules = [+ const proceduralRules = [+ `- ${CAST_SETS_LIMITS.sets.min}–${CAST_SETS_LIMITS.sets.max} sets; looks are optional palette or costume variants (at most ${CAST_SETS_LIMITS.looks.max}).`,+ '- Never describe photographic people: no skin, pores, realistic hair, wardrobe photography or singing close-ups. A human or photo cutout is allowed ONLY as a set whose imageRole is "cutout", and only when the director guidance asks for one.',+ '- imageRole says what each planned image is FOR: "background" (a full-bleed environment layer), "texture" (a seamless surface), "decoration" (an isolated ornament) or "cutout" (an isolated subject to composite). Default to "background".',+ '- Give every set ONE dominant light color or quality so a cut tells the viewer where we are.',+ '- songMap: one entry per song section index listed above, naming the set that section plays in.',+ `- moodRefs: the ${CAST_SETS_LIMITS.moodRefs.min}–${CAST_SETS_LIMITS.moodRefs.max} mood board image indices that best show the look${moodImages.length ? '' : ' (empty: there are none)'}.`,+ '- questions: up to three things you need the director to decide.',+ ].join('\n');+ const photographicRules = [`- ${CAST_SETS_LIMITS.looks.min}–${CAST_SETS_LIMITS.looks.max} looks, ${CAST_SETS_LIMITS.sets.min}–${CAST_SETS_LIMITS.sets.max} sets, ${CAST_SETS_LIMITS.tests.min}–${CAST_SETS_LIMITS.tests.max} tests.`,'- Give every set ONE dominant light color or quality so a cut tells the viewer where we are.','- songMap: one entry per song section index listed above, naming the set that section plays in.',@@ -156,6 +236,7 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,'- Wet or revealing looks use opaque fabric so the video stays safe to post.','- questions: up to three things you need the director to decide.',].join('\n');+ const rules = procedural ? proceduralRules : photographicRules;const revision = previous ? ['This is a REVISION. The current direction is:',@@ -172,7 +253,7 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,board_,rules,revision,- `Respond with ONLY one JSON object in this shape (replace every <…> with real content; do NOT output the angle-bracket text), no other text:\n${OUTPUT_SHAPE}`,+ `Respond with ONLY one JSON object in this shape (replace every <…> with real content; do NOT output the angle-bracket text), no other text:\n${procedural ? PROCEDURAL_OUTPUT_SHAPE : OUTPUT_SHAPE}`,].filter(Boolean).join('\n\n');}@@ -190,6 +271,20 @@ const protagonistSchema = z.object({signature: text(TEXT).optional(),gesture: text(TEXT).optional(),rules: z.array(text(300)).optional(),+ // Procedural medium: how the character is built and moves in code.+ construction: text(TEXT).optional(),+ shapeLanguage: text(500).optional(),+ materials: text(500).optional(),+ palette: text(300).optional(),+ movement: text(TEXT).optional(),+ expressions: z.array(text(300)).optional(),+}).passthrough();+const worldSchema = z.object({+ layout: text(TEXT).optional(),+ depth: text(500).optional(),+ lighting: text(500).optional(),+ camera: text(500).optional(),+ transitions: text(500).optional(),}).passthrough();const lookSchema = z.object({ name: text(SHORT), description: text(TEXT), chapters: text(300).optional() }).passthrough();const setSchema = z.object({@@ -197,6 +292,7 @@ const setSchema = z.object({name: text(SHORT),description: text(TEXT),lighting: text(300).optional(),+ imageRole: z.string().optional(),sections: z.union([z.array(z.union([z.string(), z.number()])), z.string()]).optional(),}).passthrough();const songMapSchema = z.object({ section: z.union([z.number(), z.string()]), setId: z.string() }).passthrough();@@ -215,6 +311,7 @@ const FIELD_PARSERS = {logline: text(TEXT),interpretation: text(2000),protagonist: protagonistSchema,+ world: worldSchema,looks: z.array(lookSchema),sets: z.array(setSchema),songMap: z.array(songMapSchema),@@ -252,7 +349,12 @@ export function parseCastAndSetsResponse(responseText) {const hasOwn = (obj, key) => obj != null && Object.prototype.hasOwnProperty.call(obj, key);-function normalizeSets(sets, sections) {+const normalizeRole = (role) => {+ const r = String(role || '').trim().toLowerCase();+ return CAST_SETS_IMAGE_ROLES.includes(r) ? r : 'background';+};++function normalizeSets(sets, sections, procedural = false) {const seen = new Set();const labels = new Map(sections.map((s) => [String(s.index), s.label]));return sets.filter((s) => s.name && s.description).slice(0, CAST_SETS_LIMITS.sets.max).map((s, i) => {@@ -265,6 +367,7 @@ function normalizeSets(sets, sections) {name: s.name,description: s.description,lighting: s.lighting || '',+ ...(procedural ? { imageRole: normalizeRole(s.imageRole) } : {}),sections: rawSections.map((x) => (typeof x === 'number' ? labels.get(String(x)) || '' : String(x).trim())).filter(Boolean).slice(0, 12),};});@@ -305,8 +408,9 @@ function normalizeTests(tests, sets, looks) {* `{ direction, missing }` — `missing` lists the required parts still absent,* so a first pass with an unusable answer can be refused.*/-export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moodImageCount = 0 } = {}) {+export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moodImageCount = 0, medium = null } = {}) {const base = previous || {};+ const procedural = (medium || base.medium) === 'procedural';const pick = (key, fallback) => (hasOwn(parsed, key) ? parsed[key] : (hasOwn(base, key) ? base[key] : fallback));const p0 = base.protagonist || {};const p1 = hasOwn(parsed, 'protagonist') ? parsed.protagonist : {};@@ -319,10 +423,22 @@ export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moosignature: pField('signature'),gesture: pField('gesture'),rules: (hasOwn(p1, 'rules') ? p1.rules : (p0.rules || [])).filter(Boolean).slice(0, CAST_SETS_LIMITS.rules),+ ...(procedural ? {+ construction: pField('construction'),+ shapeLanguage: pField('shapeLanguage'),+ materials: pField('materials'),+ palette: pField('palette'),+ movement: pField('movement'),+ expressions: (hasOwn(p1, 'expressions') ? p1.expressions : (p0.expressions || [])).filter(Boolean).slice(0, CAST_SETS_LIMITS.expressions),+ } : {}),};+ const w0 = base.world || {};+ const w1 = hasOwn(parsed, 'world') ? parsed.world : {};+ const wField = (key) => (hasOwn(w1, key) ? w1[key] : (w0[key] ?? ''));+ const world = { layout: wField('layout'), depth: wField('depth'), lighting: wField('lighting'), camera: wField('camera'), transitions: wField('transitions') };const looks = (pick('looks', [])).filter((l) => l.name && l.description).slice(0, CAST_SETS_LIMITS.looks.max).map((l) => ({ name: l.name, description: l.description, chapters: l.chapters || '' }));- const sets = hasOwn(parsed, 'sets') ? normalizeSets(parsed.sets, sections) : (base.sets || []);+ const sets = hasOwn(parsed, 'sets') ? normalizeSets(parsed.sets, sections, procedural) : (base.sets || []);const songMap = normalizeSongMap(pick('songMap', []), sets, sections);const tests = normalizeTests(pick('tests', []), sets, looks);const overlayRaw = pick('overlayConcept', { summary: '', elements: [] }) || {};@@ -333,6 +449,7 @@ export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moo};const moodRefs = [...new Set(pick('moodRefs', []))].filter((i) => i < moodImageCount).slice(0, CAST_SETS_LIMITS.moodRefs.max);const direction = {+ ...(procedural ? { medium: 'procedural', world } : {}),logline: pick('logline', ''),interpretation: pick('interpretation', ''),protagonist,@@ -346,8 +463,8 @@ export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moo};const missing = [!direction.logline && 'logline',- !(protagonist.name && (protagonist.face || protagonist.description)) && 'protagonist',- looks.length < CAST_SETS_LIMITS.looks.min && 'looks',+ !(protagonist.name && (protagonist.face || protagonist.description || protagonist.construction)) && 'protagonist',+ !procedural && looks.length < CAST_SETS_LIMITS.looks.min && 'looks',sets.length < CAST_SETS_LIMITS.sets.min && 'sets',].filter(Boolean);return { direction, missing };diff --git a/server/services/musicVideo/castAndSetsDirection.test.js b/server/services/musicVideo/castAndSetsDirection.test.jsindex 487b7f137f..1c38cbb753 100644--- a/server/services/musicVideo/castAndSetsDirection.test.js+++ b/server/services/musicVideo/castAndSetsDirection.test.js@@ -8,6 +8,8 @@import { describe, it, expect } from 'vitest';import {buildCastAndSetsPrompt,+ castAndSetsAllowsImages,+ castAndSetsMedium,mergeCastAndSetsDirection,parseCastAndSetsResponse,songSections,@@ -91,3 +93,71 @@ describe('Cast & Sets direction', () => {expect(direction.interpretation).toBe('');});});++describe('Cast & Sets procedural medium', () => {+ const procedural = { ...project, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } };+ const PROCEDURAL_ANSWER = {+ logline: 'A paper boat crosses a neon city.',+ protagonist: {+ name: 'Boat', description: 'a folded paper boat', construction: 'three triangles hinged at the keel', shapeLanguage: 'sharp, folded',+ materials: 'flat fills with a soft glow', palette: '#f5f0e6, #ff5a1f', expressions: ['proud: bow lifts', 'tired: bow droops'], movement: 'eases in, bobs on every beat',+ },+ world: { layout: 'a river through stacked streets', depth: 'three parallax planes', camera: 'slow dolly with a beat-synced push', transitions: 'wipe through reflections' },+ sets: [+ { name: 'River', description: 'a neon river', lighting: 'magenta', imageRole: 'Background' },+ { name: 'Bridge', description: 'an iron span', lighting: 'cyan', imageRole: 'decoration' },+ { name: 'Quay', description: 'wet stone', lighting: 'amber', imageRole: 'photo-booth' },+ ],+ looks: [],+ };++ it('resolves the medium from the production policy and the brief tools together', () => {+ expect(castAndSetsMedium(procedural)).toBe('procedural');+ expect(castAndSetsMedium({ automation: { tools: ['image:codex', 'code:render'] } })).toBe('procedural');+ // A video tool, an image-only brief and an untouched project stay photographic.+ expect(castAndSetsMedium({ automation: { tools: ['image:codex', 'code:render', 'video:local'] } })).toBe('photographic');+ expect(castAndSetsMedium({ automation: { tools: ['image:codex'] } })).toBe('photographic');+ expect(castAndSetsMedium(project)).toBe('photographic');+ expect(castAndSetsAllowsImages({ automation: { tools: ['code:render'] } })).toBe(false);+ expect(castAndSetsAllowsImages({ automation: { tools: ['image:codex', 'code:render'] } })).toBe(true);+ expect(castAndSetsAllowsImages(project)).toBe(true);+ });++ it('asks for construction, world and image roles instead of a photographic cast', () => {+ const prompt = buildCastAndSetsPrompt(procedural);+ expect(prompt).toContain('PROCEDURAL music video');+ expect(prompt).toContain('"construction"');+ expect(prompt).toContain('"imageRole"');+ expect(prompt).toContain('"cutout"');+ expect(prompt).not.toMatch(/"face"|"hair"|"tests"/);+ expect(buildCastAndSetsPrompt(project)).toContain('"face"');+ // A revision keeps the medium the saved direction was made in, whatever the project says now.+ expect(buildCastAndSetsPrompt(project, { previous: { medium: 'procedural' }, notes: [{ text: 'bigger sail' }] })).toContain('PROCEDURAL');+ });++ it('merges procedural fields, defaults an unknown image role, and does not require looks', () => {+ const parsed = parseCastAndSetsResponse(JSON.stringify(PROCEDURAL_ANSWER));+ const { direction, missing } = mergeCastAndSetsDirection(null, parsed, { sections, medium: 'procedural' });+ expect(missing).toEqual([]);+ expect(direction).toMatchObject({ medium: 'procedural', looks: [], tests: [] });+ expect(direction.protagonist).toMatchObject({ construction: 'three triangles hinged at the keel', expressions: ['proud: bow lifts', 'tired: bow droops'] });+ expect(direction.world.camera).toBe('slow dolly with a beat-synced push');+ expect(direction.sets.map((s) => s.imageRole)).toEqual(['background', 'decoration', 'background']);++ // Revision: absent keys keep the saved values, a present empty value clears.+ const revision = parseCastAndSetsResponse(JSON.stringify({ protagonist: { movement: '' }, world: { depth: 'two planes' } }));+ const revised = mergeCastAndSetsDirection(direction, revision, { sections }).direction;+ expect(revised.medium).toBe('procedural');+ expect(revised.protagonist).toMatchObject({ movement: '', construction: 'three triangles hinged at the keel' });+ expect(revised.world).toMatchObject({ depth: 'two planes', layout: 'a river through stacked streets' });+ expect(revised.sets).toEqual(direction.sets);+ });++ it('leaves a photographic direction exactly as it was', () => {+ const { direction } = mergeCastAndSetsDirection(null, parseCastAndSetsResponse(JSON.stringify(ANSWER)), { sections });+ expect(direction).not.toHaveProperty('medium');+ expect(direction).not.toHaveProperty('world');+ expect(direction.protagonist).not.toHaveProperty('construction');+ expect(direction.sets[0]).not.toHaveProperty('imageRole');+ });+});diff --git a/server/services/musicVideo/castAndSetsPlan.js b/server/services/musicVideo/castAndSetsPlan.jsindex a030780b1f..807425858f 100644--- a/server/services/musicVideo/castAndSetsPlan.js+++ b/server/services/musicVideo/castAndSetsPlan.js@@ -16,6 +16,12 @@* character, so they render alongside it.* - `test:<n>` — the protagonist in a set: conditioned on that set's plate,* the character sheet and the looks sheet.+ *+ * A `procedural` direction (see castAndSetsDirection.js) plans none of the+ * photographic sheets, expression/looks sheets or tests: the characters are+ * built in code, so the only images are the set plates, each with an+ * intentional `role` (background, texture, decoration or cutout) that shapes+ * its prompt. A code-only project plans no images at all.*/import { trimTo } from '../../lib/textUtils.js';@@ -57,8 +63,9 @@ export function setCoverage(project, direction) {return cover;}-/** The in-set tests to render: the direction's own, topped up to two from the most-used sets. */+/** The in-set tests to render: the direction's own, topped up to two from the most-used sets. A procedural direction has none. */export function plannedTests(project, direction) {+ if (direction?.medium === 'procedural') return [];const tests = (direction?.tests || []).slice(0, 4);if (tests.length >= 2) return tests;const cover = setCoverage(project, direction);@@ -72,6 +79,42 @@ export function plannedTests(project, direction) {return tests;}+const PROCEDURAL_ROLE_PROMPTS = {+ background: (set) => join('Layered illustration background plate for a code-animated music video, flat graphic shading, no characters, no text', set.description),+ texture: (set) => join('Seamless tileable surface texture, flat even light, no objects, no characters, no text', set.description),+ decoration: (set) => join('A single isolated decorative element centered on a plain flat backdrop with generous margin, no text', set.description),+ cutout: (set) => join('A single isolated subject on a plain flat backdrop with clean edges, ready to cut out and composite, no text', set.description),+};++/** The procedural plan: one role-prompted plate per set, no photographic character work. */+function buildProceduralImagePlan(direction, { revisionNotes = {} } = {}) {+ const style = trimTo(direction.look, 500);+ const world = direction.world || {};+ const plan = {};+ for (const set of direction.sets || []) {+ const key = `set:${set.id}`;+ const role = set.imageRole || 'background';+ plan[key] = {+ key,+ kind: 'plate',+ role,+ label: set.name,+ setId: set.id,+ deps: [],+ refKeys: [],+ moodRefs: true,+ prompt: join(+ (PROCEDURAL_ROLE_PROMPTS[role] || PROCEDURAL_ROLE_PROMPTS.background)(set),+ set.lighting && `Lighting: ${set.lighting}`,+ role === 'background' && world.depth && `Depth: ${world.depth}`,+ style && `Look: ${style}`,+ revisionNotes[key] && `Revision: ${revisionNotes[key]}`,+ ),+ };+ }+ return plan;+}+/*** Build the full image plan for a direction: `{ [key]: { key, kind, label,* prompt, deps, refKeys, setId?, testIndex? } }`. `refKeys` name other plan@@ -79,6 +122,7 @@ export function plannedTests(project, direction) {* chosen mood-board images. A revision note for a key is appended to its prompt.*/export function buildCastAndSetsImagePlan(project, direction, { revisionNotes = {} } = {}) {+ if (direction.medium === 'procedural') return buildProceduralImagePlan(direction, { revisionNotes });const p = direction.protagonist || {};const looks = direction.looks || [];const firstLook = looks[0];@@ -252,7 +296,9 @@ export function castAndSetsReferences(project, stage) {const cover = setCoverage(project, direction);const plates = [...(direction.sets || [])].sort((a, b) => (cover.get(b.id) || 0) - (cover.get(a.id) || 0));for (const set of plates) {- push({ id: `${CAST_SETS_REF_PREFIX}set-${set.id}`.slice(0, 64), imageId: images[`set:${set.id}`]?.imageId, role: 'set', label: trimTo(set.name, 120), note: trimTo([set.description, set.lighting].filter(Boolean).join(' — '), 1000) }, true);+ // A procedural texture, decoration or cutout is a loose asset, not a look to condition frames on.+ const conditions = direction.medium !== 'procedural' || (set.imageRole || 'background') === 'background';+ push({ id: `${CAST_SETS_REF_PREFIX}set-${set.id}`.slice(0, 64), imageId: images[`set:${set.id}`]?.imageId, role: 'set', label: trimTo(set.name, 120), note: trimTo([set.description, set.lighting].filter(Boolean).join(' — '), 1000) }, conditions);}push({ id: `${CAST_SETS_REF_PREFIX}looks`, imageId: images.looks?.imageId, role: 'wardrobe', label: 'Looks', note: trimTo((direction.looks || []).map((l) => l.name).join(', '), 1000) }, false);push({ id: `${CAST_SETS_REF_PREFIX}expressions`, imageId: images.expressions?.imageId, role: 'character', label: 'Expression sheet', note: trimTo(p.gesture, 1000) }, false);@@ -276,7 +322,7 @@ export function castAndSetsSubjects(project, stage) {id: `${CAST_SETS_SUBJECT_PREFIX}protagonist`,kind: 'character',name: trimTo(p.name, 120),- description: trimTo([p.description, p.face, p.hair, p.signature].filter(Boolean).join('; '), 1000),+ description: trimTo([p.description, p.construction, p.shapeLanguage, p.materials, p.palette, p.face, p.hair, p.signature].filter(Boolean).join('; '), 1000),role: 'protagonist',});}diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex 1d912a2e4a..8b097c0dcd 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -53,6 +53,8 @@ import {} from './castAndSets.js';import {buildCastAndSetsPrompt,+ castAndSetsAllowsImages,+ castAndSetsMedium,mergeCastAndSetsDirection,moodBoardImageList,parseCastAndSetsResponse,@@ -165,7 +167,11 @@ async function runDirection(projectId, { providerId, model, notes = [], forceKeyif (!provider) return fail(projectId, 'No AI provider is available for the creative direction');if (provider.enabled === false) return fail(projectId, `The ${provider.name || provider.id} provider is disabled`);const previous = stage?.direction || null;- const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes });+ // A revision keeps the medium it was directed in; a fresh pass resolves it+ // from the project's policy and tools, so a saved direction is never+ // silently re-cast into the other medium.+ const medium = (notes.length && previous?.medium) || castAndSetsMedium(project);+ const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes, medium });let text;try {({ text } = await deps.runPrompt({ provider, model: selectedModel, prompt, source: 'music-video-cast-sets' }));@@ -175,7 +181,7 @@ async function runDirection(projectId, { providerId, model, notes = [], forceKeyconst parsed = parseCastAndSetsResponse(text);if (!parsed) return fail(projectId, 'The creative direction answer had no usable JSON');const sections = songSections(project);- const { direction, missing } = mergeCastAndSetsDirection(notes.length ? previous : null, parsed, { sections, moodImageCount: moodImages.length });+ const { direction, missing } = mergeCastAndSetsDirection(notes.length ? previous : null, parsed, { sections, moodImageCount: moodImages.length, medium });if (missing.length) return fail(projectId, `The creative direction answer is missing: ${missing.join(', ')}`);// The photographic look every image prompt carries: the mood board's composed// style, else the project's visual style (never the board's literal places).@@ -192,17 +198,20 @@ async function writePlan(projectId, { direction = null, moodImages = null, forceconst project = await requireProject(projectId);const stage = project.castAndSets;const nextDirection = direction || stage.direction;- const plan = buildCastAndSetsImagePlan(project, nextDirection, { revisionNotes: keyNotesText(stage.keyNotes) });+ // A procedural project whose brief names no image tool is code-only: nothing+ // is rendered, so no image backend is needed (or consulted).+ const codeOnly = nextDirection.medium === 'procedural' && !castAndSetsAllowsImages(project);+ const plan = codeOnly ? {} : buildCastAndSetsImagePlan(project, nextDirection, { revisionNotes: keyNotesText(stage.keyNotes) });const renderKeys = affectedImageKeys(stage.plan || {}, plan, forceKeys);const settings = await deps.getSettings();const run = stage.productionRunId ? (project.productionRuns || []).find((r) => r.id === stage.productionRunId) : null;const preferred = run?.pool?.find((r) => r.kind === 'image') || stage.route || null;- const route = await chooseCastAndSetsRoute(project, { preferred, settings });- if (!route) return fail(projectId, 'No enabled image backend is allowed for the Cast & Sets images — enable Codex (or another image tool in the brief) and resume');+ const route = codeOnly ? (stage.route || null) : await chooseCastAndSetsRoute(project, { preferred, settings });+ if (!route && !codeOnly) return fail(projectId, 'No enabled image backend is allowed for the Cast & Sets images — enable Codex (or another image tool in the brief) and resume');const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsDirection(current, {direction: nextDirection, plan, moodImages, route, renderKeys,}));- console.log(`🎭 Music Video Cast & Sets ${short(projectId)} r${out.stage.revision}: ${renderKeys.length} image(s) to render on ${route.mode}`);+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} r${out.stage.revision}: ${renderKeys.length} image(s) to render${route ? ` on ${route.mode}` : ' (code-only, no image backend)'}`);publish(projectId, out.project);return advance(projectId);}diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.jsindex 40761d856d..b1be797b0c 100644--- a/server/services/musicVideo/castAndSetsService.test.js+++ b/server/services/musicVideo/castAndSetsService.test.js@@ -356,3 +356,103 @@ it('uses project moodboard style images for Cast & Sets without a linked board',const dependent = jobs.find((j) => j.params.referenceImagePaths?.length > 1);expect(dependent.params.referenceImagePaths.at(-1)).toMatch(/style.png$/);});++describe('Cast & Sets procedural check-in', () => {+ const PROCEDURAL = {+ logline: 'A paper boat crosses a neon city.',+ interpretation: 'The song reads as a small thing carried by a big current.',+ protagonist: {+ name: 'Boat', description: 'a folded paper boat', construction: 'three triangles hinged at the keel', shapeLanguage: 'sharp, folded',+ materials: 'flat fills with a soft glow', palette: '#f5f0e6, #ff5a1f', expressions: ['proud: bow lifts'], movement: 'bobs on every beat',+ },+ world: { layout: 'a river through stacked streets', depth: 'three parallax planes', camera: 'slow dolly with a beat-synced push', transitions: 'wipe through reflections' },+ looks: [],+ sets: [+ { id: 'river', name: 'River', description: 'a neon river', lighting: 'magenta', imageRole: 'background', sections: [0] },+ { id: 'bridge', name: 'Bridge', description: 'an iron span', lighting: 'cyan', imageRole: 'decoration', sections: [1] },+ { id: 'quay', name: 'Quay', description: 'wet stone', lighting: 'amber', imageRole: 'texture', sections: [2] },+ ],+ songMap: [{ section: 0, setId: 'river' }, { section: 1, setId: 'bridge' }, { section: 2, setId: 'quay' }],+ overlayConcept: { summary: 'A tide clock.', elements: [] },+ moodRefs: [],+ questions: [],+ };+ const seedProcedural = (tools) => seed({+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ automation: { tools, checkins: { castAndSets: 'review' } },+ });++ beforeEach(() => {+ runPrompt.mockResolvedValue({ text: JSON.stringify(PROCEDURAL) });+ });++ it('directs an image+code project with role-planned plates and no photographic batch, then carries the rules into the planner context', async () => {+ const project = await seedProcedural(['image:codex', 'code:render']);+ await service.startCastAndSets(project.id);+ await runTo(project.id, 'review');++ const prompt = runPrompt.mock.calls[0][0].prompt;+ expect(prompt).toContain('PROCEDURAL music video');+ // Only role-prompted set plates: no character, looks, expression or test photography.+ expect(jobs.map(keyOf).sort()).toEqual(['set:bridge', 'set:quay', 'set:river']);+ const byKey = Object.fromEntries(jobs.map((j) => [keyOf(j), j.params.prompt]));+ expect(byKey['set:river']).toMatch(/background plate/);+ expect(byKey['set:bridge']).toMatch(/isolated decorative element/);+ expect(byKey['set:quay']).toMatch(/Seamless tileable/);+ expect(Object.values(byKey).join(' ')).not.toMatch(/photoreal|person|FRONT/i);++ const reviewing = await current(project.id);+ expect(reviewing.castAndSets.direction).toMatchObject({ medium: 'procedural', world: { camera: 'slow dolly with a beat-synced push' } });+ const artifact = reviewing.devArtifacts.find((a) => a.id === reviewing.castAndSets.artifactId);+ const html = readFileSync(join(ROOT(), artifact.file), 'utf8');+ expect(html).toContain('three triangles hinged at the keel');+ expect(html).toContain('Role: decoration');+ expect(html).not.toContain('Character reference sheet');++ await service.approveCastAndSets(project.id);+ const done = await current(project.id);+ // Only the background plate conditions frame generation; texture and decoration stay loose references.+ expect(done.visualSpec.references.filter((r) => r.id.startsWith('mvr-cs-')).map((r) => [r.id, r.condition]).sort()).toEqual([+ ['mvr-cs-set-bridge', false], ['mvr-cs-set-quay', false], ['mvr-cs-set-river', true],+ ]);+ expect(done.concept.subjects.find((s) => s.id === 'cs-protagonist').description).toContain('three triangles hinged at the keel');++ // The approved motion, camera and construction reach the planner request.+ const { buildScenePlanPrompt } = await import('./planner.js');+ const planPrompt = buildScenePlanPrompt(done, [{ startSec: 0, endSec: 8, sectionIndex: 0, shotIndex: 0, shotCount: 1, sectionLabel: 'Intro', lyricText: '', delivery: [] }]);+ expect(planPrompt).toContain('slow dolly with a beat-synced push');+ expect(planPrompt).toContain('bobs on every beat');+ expect(planPrompt).toContain('image role: decoration');+ });++ it('directs a code-only project without any image backend and still waits for the director', async () => {+ const resolveRoute = vi.fn(async () => null);+ service.__setCastAndSetsDepsForTests({+ resolveProvider: async () => ({ provider: { id: 'example-provider', enabled: true }, selectedModel: 'example-model' }),+ runPrompt, getSettings: async () => ({}), enqueue, resolveRoute,+ loadBoard: async () => null, loadTrack: async () => null,+ });+ const project = await seedProcedural(['code:render']);+ await service.startCastAndSets(project.id);+ await until(async () => (await current(project.id)).castAndSets?.status === 'review', 'the code-only check-in');+ const stage = (await current(project.id)).castAndSets;+ expect(jobs).toEqual([]);+ expect(resolveRoute).not.toHaveBeenCalled();+ expect(stage.plan).toEqual({});+ expect(stage.direction.protagonist.construction).toBe('three triangles hinged at the keel');+ const html = readFileSync(join(ROOT(), (await current(project.id)).devArtifacts[0].file), 'utf8');+ expect(html).toContain('No raster image: drawn in code');+ });++ it('keeps the medium of a saved direction when the project settings change before a revision', async () => {+ const project = await seedProcedural(['image:codex', 'code:render']);+ await service.startCastAndSets(project.id);+ await runTo(project.id, 'review');+ await projects.mutateProjectRecord(project.id, (p) => ({ project: { ...p, productionPolicy: { strategy: 'legacy', maxGeneratedVideoPercent: 100 }, automation: { ...p.automation, tools: ['image:codex'] } } }));+ await service.regenerateCastAndSets(project.id, { notes: [{ text: 'make the camera slower' }] });+ await until(async () => runPrompt.mock.calls.length === 2, 'the revision call');+ expect(runPrompt.mock.calls[1][0].prompt).toContain('PROCEDURAL music video');+ await runTo(project.id, 'review');+ expect((await current(project.id)).castAndSets.direction.medium).toBe('procedural');+ });+});diff --git a/server/services/musicVideo/castAndSetsSheet.js b/server/services/musicVideo/castAndSetsSheet.jsindex 3e25897f12..25f3b53346 100644--- a/server/services/musicVideo/castAndSetsSheet.js+++ b/server/services/musicVideo/castAndSetsSheet.js@@ -34,11 +34,11 @@ const fmtTime = (sec) => {// placeholder so the file can never reach the network.const safeSrc = (src) => (typeof src === 'string' && /^data:image\/(png|jpe?g|webp);base64,[A-Za-z0-9+/=]+$/.test(src) ? src : null);-function figure(src, alt, caption, cls = '') {+function figure(src, alt, caption, cls = '', placeholder = 'Image not rendered') {const ok = safeSrc(src);const media = ok? `<img src="${ok}" alt="${e(alt)}">`- : `<div class="missing" role="img" aria-label="${e(alt)}">Image not rendered</div>`;+ : `<div class="missing" role="img" aria-label="${e(alt)}">${e(placeholder)}</div>`;return `<figure${cls ? ` class="${cls}"` : ''}>${media}${caption ? `<figcaption>${caption}</figcaption>` : ''}</figure>`;}@@ -91,6 +91,11 @@ td.tc{font-family:var(--mono);color:var(--muted);white-space:nowrap;width:64px}@media (max-width:760px){.grid2,.sets,.overlay{grid-template-columns:1fr}.row{grid-template-columns:repeat(2,1fr)}}`;+const PROCEDURAL_QUESTIONS = [+ 'Is the character construction right: shapes, materials, palette and expressions?',+ 'Do the movement, camera and transition rules fit the song?',+ 'Do the environments and their image roles work, or should any be swapped out?',+];const DEFAULT_QUESTIONS = ['Is the protagonist right: face, hair, signature detail and the looks?','Do the sets work, or should any be swapped out?',@@ -107,21 +112,34 @@ export function renderCastAndSetsSheet({revision = 1, notesApplied = [], checkinMode = 'review', status = 'review',}) {const d = direction || {};+ const procedural = d.medium === 'procedural';const p = d.protagonist || {};+ const w = d.world || {};const sets = d.sets || [];const colorOf = new Map(sets.map((s, i) => [s.id, CAST_SETS_SET_COLORS[i % CAST_SETS_SET_COLORS.length]]));const setOfSection = new Map((d.songMap || []).map((m) => [m.section, m.setId]));const tests = plannedTests(project, d);const total = durationSec || (sections.length ? sections[sections.length - 1].endSec : 0);- const facts = [+ const facts = (procedural ? [+ ['Who', p.description],+ ['Construction', p.construction],+ ['Shapes', p.shapeLanguage],+ ['Materials', p.materials],+ ['Palette', p.palette],+ ['Expressions', (p.expressions || []).join('; ')],+ ['Movement', p.movement],+ ['Signature', p.signature],+ ['Gesture', p.gesture],+ ['Rules', (p.rules || []).map((r) => r.replace(/[.;]\s*$/, '')).join('; ')],+ ] : [['Who', p.description],['Face', p.face],['Hair', p.hair],['Signature', p.signature],['Gesture', p.gesture],['Rules', (p.rules || []).map((r) => r.replace(/[.;]\s*$/, '')).join('; ')],- ].filter(([, v]) => v).map(([k, v]) => `<dt>${e(k)}</dt><dd>${e(v)}</dd>`).join('');+ ]).filter(([, v]) => v).map(([k, v]) => `<dt>${e(k)}</dt><dd>${e(v)}</dd>`).join('');const looksCaption = (d.looks || []).map((l, i) => `0${i + 1} ${e(l.name)}${l.chapters ? ` (${e(l.chapters)})` : ''}`).join(' · ');@@ -131,8 +149,9 @@ export function renderCastAndSetsSheet({}).join('');const setFigures = sets.map((s) => {- const caption = `<b>${e(s.name)}</b><span>${e(s.description)}${s.lighting ? ` ${e(s.lighting)}` : ''}</span>${(s.sections || []).length ? `<em>${e(s.sections.join(', '))}</em>` : ''}`;- return figure(images[`set:${s.id}`], s.name, caption, 'set');+ const role = procedural ? `<em>Role: ${e(s.imageRole || 'background')}</em>` : '';+ const caption = `<b>${e(s.name)}</b><span>${e(s.description)}${s.lighting ? ` ${e(s.lighting)}` : ''}</span>${role}${(s.sections || []).length ? `<em>${e(s.sections.join(', '))}</em>` : ''}`;+ return figure(images[`set:${s.id}`], s.name, caption, 'set', procedural ? 'No raster image: drawn in code' : undefined);}).join('');const bar = sections.map((s) => {@@ -149,7 +168,9 @@ export function renderCastAndSetsSheet({const overlay = d.overlayConcept || {};const overlayCards = (overlay.elements || []).map((el) => `<div><h3>${e(el.name)}</h3><p>${e(el.description)}</p></div>`).join('');- const questions = (d.questions && d.questions.length ? d.questions : DEFAULT_QUESTIONS).map((q) => `<li>${e(q)}</li>`).join('');+ const worldFacts = [['Layout', w.layout], ['Depth', w.depth], ['Lighting', w.lighting], ['Camera', w.camera], ['Transitions', w.transitions]]+ .filter(([, v]) => v).map(([k, v]) => `<dt>${e(k)}</dt><dd>${e(v)}</dd>`).join('');+ const questions = (d.questions && d.questions.length ? d.questions : (procedural ? PROCEDURAL_QUESTIONS : DEFAULT_QUESTIONS)).map((q) => `<li>${e(q)}</li>`).join('');const applied = notesApplied.length? `<p class="sub"><b>Revision ${revision}.</b> Notes applied: ${notesApplied.map((n) => `${n.target ? `[${e(n.target)}] ` : ''}${e(n.text)}`).join(' · ')}</p>`: '';@@ -162,17 +183,18 @@ export function renderCastAndSetsSheet({<title>${e(title)} — Cast & Sets</title><style>${STYLE}</style></head><body><div class="wrap">-<div class="hud"><span>Check-in <b>Cast & Sets</b></span><span>Revision <b>${Number(revision) || 1}</b></span>${p.name ? `<span>Protagonist <b>${e(p.name)}</b></span>` : ''}${total ? `<span>Track ${fmtTime(total)}${bpm ? ` · ${Math.round(bpm)} BPM` : ''}</span>` : ''}<span>${sets.length} sets · ${(d.looks || []).length} looks</span></div>+<div class="hud"><span>Check-in <b>Cast & Sets</b></span><span>Revision <b>${Number(revision) || 1}</b></span>${p.name ? `<span>Protagonist <b>${e(p.name)}</b></span>` : ''}${total ? `<span>Track ${fmtTime(total)}${bpm ? ` · ${Math.round(bpm)} BPM` : ''}</span>` : ''}<span>${sets.length} sets · ${procedural ? 'built in code' : `${(d.looks || []).length} looks`}</span></div><h1>${e(title)}</h1><p class="lede">${e(d.logline)}</p>${d.interpretation ? `<p class="sub">${e(d.interpretation)}</p>` : ''}${applied}<section><h2><small>Protagonist</small>${e(p.name || 'Protagonist')}</h2>-<div class="grid2">${figure(images.character, 'Character reference sheet: front, three-quarter, profile, back and face', 'Canonical reference sheet. Every later image of the protagonist uses it as a reference.')}<div><dl class="facts">${facts}</dl></div></div>+${procedural ? `<dl class="facts wide">${facts}</dl></section>+${worldFacts ? `<section><h2><small>World</small>How the environments behave</h2><dl class="facts wide">${worldFacts}</dl></section>` : ''}` : `<div class="grid2">${figure(images.character, 'Character reference sheet: front, three-quarter, profile, back and face', 'Canonical reference sheet. Every later image of the protagonist uses it as a reference.')}<div><dl class="facts">${facts}</dl></div></div>${figure(images.looks, 'Wardrobe looks', looksCaption ? `Wardrobe by chapter: ${looksCaption}` : 'Wardrobe', 'wide')}<div class="grid2">${figure(images.expressions, 'Expression sheet', `Expression range for lip-sync keyframes.${p.gesture ? ` Includes the gesture: ${e(p.gesture)}` : ''}`)}${tests[0] ? figure(images['test:1'], 'First in-set test', e(tests[0].caption || tests[0].action)) : ''}</div></section>-<section><h2><small>In-set tests</small>The protagonist, in the world</h2><div class="row">${testFigures}</div></section>+<section><h2><small>In-set tests</small>The protagonist, in the world</h2><div class="row">${testFigures}</div></section>`}<section><h2><small>Sets</small>${sets.length} sets</h2><p class="sub">Each set has its own light, so a cut says where we are before anything else.</p><div class="sets">${setFigures}</div></section><section><h2><small>Song map</small>Where each set lives in the track</h2>${sections.length ? `<div class="bar">${bar}</div><div class="ticks"><span>0:00</span><span>${fmtTime(total)}</span></div><div class="tablewrap"><table>${rows}</table></div>` : '<p class="sub">The song has not been sectioned yet.</p>'}