Skip to content

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

feat: reusable code character definitions, previewed sheet and editable direction for procedural Cast & Sets (#9567)

Adam Eivy7615a3d0f29d
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
index 03cc34776c..489b68a05b 100644
--- a/client/src/components/musicVideo/CastAndSetsCheckin.jsx
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.jsx
@@ -1,5 +1,6 @@
import { CheckCircle2, Eye, Play, RotateCcw, SkipForward, Users } from 'lucide-react';
import Pill from '../ui/Pill.jsx';
+import CastAndSetsDirectionEditor from './CastAndSetsDirectionEditor.jsx';
import CastAndSetsReferenceProgress from './CastAndSetsReferenceProgress.jsx';
const WORKING = new Set(['directing', 'imaging', 'assembling']);
@@ -30,9 +31,9 @@ function statusLine(stage) {
* The Cast & Sets check-in's state on the Autopilot card: progress while the
* server works, "Waiting for your check-in" with the sheet one click away,
* and the director's actions (Approve & continue, Regenerate with notes,
- * Resume, Skip).
+ * Edit direction on a procedural sheet, Resume, Skip).
*/
-export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onApprove, onRegenerate, onResume, onSkip }) {
+export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onApprove, onRegenerate, onEditDirection, onResume, onSkip }) {
const stage = project.castAndSets;
if (!stage) return null;
const working = WORKING.has(stage.status) && !stage.interrupted;
@@ -61,6 +62,9 @@ export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onAppro
className={`${buttonClass} border border-port-border`}>
<RotateCcw size={14} aria-hidden="true" /> Regenerate with notes
</button>
+ {onEditDirection && stage.direction?.medium === 'procedural' && (
+ <CastAndSetsDirectionEditor key={stage.revision} project={project} direction={stage.direction} busy={busy} onSave={onEditDirection} />
+ )}
<button type="button" disabled={busy} onClick={onApprove} className={`${buttonClass} bg-port-accent text-white`}>
<CheckCircle2 size={14} aria-hidden="true" /> Approve &amp; continue
</button>
diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
index 2b4e5ebf14..1f74617e08 100644
--- a/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
+++ b/client/src/components/musicVideo/CastAndSetsCheckin.test.jsx
@@ -6,7 +6,7 @@ import useMusicVideoCastAndSets from '../../hooks/useMusicVideoCastAndSets';
const { listeners, api, getMediaJob } = vi.hoisted(() => ({
listeners: new Map(),
- api: { getMusicVideoProject: vi.fn(), startMusicVideoCastAndSets: vi.fn(), regenerateMusicVideoCastAndSets: vi.fn(), resumeMusicVideoCastAndSets: vi.fn(), approveMusicVideoCastAndSets: vi.fn(), skipMusicVideoCastAndSets: vi.fn() },
+ api: { getMusicVideoProject: vi.fn(), startMusicVideoCastAndSets: vi.fn(), regenerateMusicVideoCastAndSets: vi.fn(), editMusicVideoCastAndSetsDirection: vi.fn(), resumeMusicVideoCastAndSets: vi.fn(), approveMusicVideoCastAndSets: vi.fn(), skipMusicVideoCastAndSets: vi.fn() },
getMediaJob: vi.fn(),
}));
vi.mock('../../services/socket', () => ({ default: {
@@ -26,11 +26,11 @@ const plan = {
const project = (images = {}, extra = {}) => ({ id: 'example-project', castAndSets: { revision: 1, status: 'imaging', plan, images, moodImages: [{ kind: 'image-ref', filename: 'mood.png' }], ...extra } });
const done = (filename, prompt) => ({ status: 'done', jobId: `job-${filename}`, imageId: filename, submittedPrompt: prompt, submittedRevision: 1, submittedReferences: [{ kind: 'image-ref', filename: 'mood.png' }] });
let selectProject;
-function Harness({ initial }) {
+function Harness({ initial, locked = true }) {
const [value, setValue] = useState(initial);
selectProject = setValue;
const actions = useMusicVideoCastAndSets({ project: value, replaceProject: setValue });
- return <CastSetsStage board={{ project: value, locked: true, castSets: actions, kickoff: { running: true }, devArtifacts: { busy: false }, openArtifact: vi.fn(), approveCastAndSets: actions.approve, skipCastAndSets: actions.skip }} />;
+ return <CastSetsStage board={{ project: value, locked, castSets: actions, kickoff: { running: locked }, devArtifacts: { busy: false }, openArtifact: vi.fn(), approveCastAndSets: actions.approve, skipCastAndSets: actions.skip }} />;
}
const stage = (next) => emit('music-video:cast-and-sets', { projectId: next.id, project: next });
const card = (name) => within(screen.getByRole('article', { name }));
@@ -131,3 +131,57 @@ describe('Cast & Sets incremental references', () => {
expect([...listeners.values()].every((set) => set.size === 0)).toBe(true);
});
});
+
+describe('Cast & Sets direction editing', () => {
+ const direction = (medium) => ({
+ ...(medium ? { medium } : {}),
+ protagonist: { name: 'Boat', description: 'a paper boat', construction: 'three folds', palette: '#f5f0e6', movement: 'bobs', expressions: ['proud: bow lifts'] },
+ world: { layout: 'a river', camera: 'slow dolly' },
+ sets: [{ id: 'river', name: 'River', description: 'a neon river', imageRole: 'background' }, { id: 'quay', name: 'Quay', description: 'wet stone', imageRole: 'texture' }],
+ });
+ const review = (dir, extra = {}) => ({ id: 'example-project', castAndSets: { revision: 1, status: 'review', plan: {}, images: {}, direction: dir, ...extra } });
+
+ it('offers the editor only for a procedural direction waiting in review', () => {
+ const view = render(<Harness initial={review(direction())} locked={false} />);
+ expect(screen.queryByRole('button', { name: /Edit direction/ })).toBeNull();
+ view.unmount();
+ render(<Harness initial={review(direction('procedural'), { status: 'approved' })} locked={false} />);
+ expect(screen.queryByRole('button', { name: /Edit direction/ })).toBeNull();
+ });
+
+ it('sends only the changed fields, applies the saved project, and keeps the edit across the revision', async () => {
+ api.editMusicVideoCastAndSetsDirection.mockImplementation(async (_id, body) => ({ project: review({
+ ...direction('procedural'),
+ protagonist: { ...direction().protagonist, palette: body.protagonist.palette },
+ sets: direction().sets.map((s) => ({ ...s, imageRole: body.sets?.find((x) => x.id === s.id)?.imageRole || s.imageRole })),
+ }, { revision: 2, status: 'imaging' }) }));
+ render(<Harness initial={review(direction('procedural'))} locked={false} />);
+ fireEvent.click(screen.getByRole('button', { name: /Edit direction/ }));
+ const save = screen.getByRole('button', { name: /Save direction/ });
+ expect(save).toBeDisabled();
+ expect(screen.getByLabelText('Construction').value).toBe('three folds');
+ expect(screen.getByLabelText('Expressions (one per line)').value).toBe('proud: bow lifts');
+
+ fireEvent.change(screen.getByLabelText('Palette'), { target: { value: '#112233, #ddeeff' } });
+ fireEvent.change(screen.getByLabelText('Image role · Quay'), { target: { value: 'cutout' } });
+ expect(save).not.toBeDisabled();
+ await act(async () => { fireEvent.click(save); });
+
+ expect(api.editMusicVideoCastAndSetsDirection).toHaveBeenCalledWith('example-project', {
+ protagonist: { palette: '#112233, #ddeeff' },
+ sets: [{ id: 'quay', imageRole: 'cutout' }],
+ }, { silent: true });
+ // The saved revision replaces the sheet's state; the editor closes and the stage shows the new revision.
+ expect(screen.getByText('revision 2')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Save direction/ })).toBeNull();
+ });
+
+ it('keeps the draft open when the save fails', async () => {
+ api.editMusicVideoCastAndSetsDirection.mockRejectedValue(new Error('Nothing changed'));
+ render(<Harness initial={review(direction('procedural'))} locked={false} />);
+ fireEvent.click(screen.getByRole('button', { name: /Edit direction/ }));
+ fireEvent.change(screen.getByLabelText('Camera'), { target: { value: 'locked off' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Save direction/ })); });
+ expect(screen.getByLabelText('Camera').value).toBe('locked off');
+ });
+});
diff --git a/client/src/components/musicVideo/CastAndSetsDirectionEditor.jsx b/client/src/components/musicVideo/CastAndSetsDirectionEditor.jsx
new file mode 100644
index 0000000000..d77bafe25a
--- /dev/null
+++ b/client/src/components/musicVideo/CastAndSetsDirectionEditor.jsx
@@ -0,0 +1,105 @@
+import { useState } from 'react';
+import { Pencil, Save } from 'lucide-react';
+
+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
+const IMAGE_ROLES = ['background', 'texture', 'decoration', 'cutout'];
+
+// Text fields the director edits directly, with the server's caps (musicVideoCastAndSetsDirectionEditSchema).
+const PROTAGONIST_FIELDS = [
+ ['construction', 'Construction', 1000, true], ['shapeLanguage', 'Shape language', 500], ['materials', 'Materials', 500],
+ ['palette', 'Palette', 300], ['movement', 'Movement', 1000, true],
+];
+const WORLD_FIELDS = [
+ ['layout', 'Layout', 1000, true], ['depth', 'Depth', 500], ['lighting', 'Lighting', 500], ['camera', 'Camera', 500], ['transitions', 'Transitions', 500],
+];
+
+const draftFrom = (direction) => ({
+ protagonist: {
+ ...Object.fromEntries(PROTAGONIST_FIELDS.map(([key]) => [key, direction.protagonist?.[key] || ''])),
+ expressions: (direction.protagonist?.expressions || []).join('\n'),
+ },
+ world: Object.fromEntries(WORLD_FIELDS.map(([key]) => [key, direction.world?.[key] || ''])),
+ roles: Object.fromEntries((direction.sets || []).map((set) => [set.id, set.imageRole || 'background'])),
+});
+
+const lines = (text) => text.split('\n').map((line) => line.trim()).filter(Boolean);
+
+/** Only what the director actually changed, in the PATCH body's shape. */
+function editsFrom(direction, draft) {
+ const base = draftFrom(direction);
+ const pick = (keys, group) => Object.fromEntries(keys.filter((key) => draft[group][key] !== base[group][key]).map((key) => [key, draft[group][key]]));
+ const protagonist = pick(PROTAGONIST_FIELDS.map(([key]) => key), 'protagonist');
+ if (draft.protagonist.expressions !== base.protagonist.expressions) protagonist.expressions = lines(draft.protagonist.expressions);
+ const world = pick(WORLD_FIELDS.map(([key]) => key), 'world');
+ const sets = (direction.sets || []).filter((set) => draft.roles[set.id] !== base.roles[set.id]).map((set) => ({ id: set.id, imageRole: draft.roles[set.id] }));
+ return {
+ ...(Object.keys(protagonist).length ? { protagonist } : {}),
+ ...(Object.keys(world).length ? { world } : {}),
+ ...(sets.length ? { sets } : {}),
+ };
+}
+
+/**
+ * Direct edits to a procedural Cast & Sets direction — how the character is
+ * built and moves, the world's rules and each set's image role — saved through
+ * the check-in's revision path. Only changed fields are sent; the parent keys
+ * this by revision so a saved (or regenerated) direction resets the draft.
+ */
+export default function CastAndSetsDirectionEditor({ project, direction, busy, onSave }) {
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState(() => draftFrom(direction));
+ const edits = editsFrom(direction, draft);
+ const dirty = Object.keys(edits).length > 0;
+ const idFor = (name) => `mv-cs-edit-${project.id}-${name}`;
+ const setField = (group, key, value) => setDraft((d) => ({ ...d, [group]: { ...d[group], [key]: value } }));
+
+ const field = (group, [key, label, max, long]) => {
+ const props = { id: idFor(`${group}-${key}`), maxLength: max, className: inputClass, value: draft[group][key], onChange: (e) => setField(group, key, e.target.value) };
+ return (
+ <div key={`${group}-${key}`} className={long ? 'sm:col-span-2' : ''}>
+ <label htmlFor={props.id} className="text-xs">{label}</label>
+ {long ? <textarea rows={2} {...props} /> : <input type="text" {...props} />}
+ </div>
+ );
+ };
+
+ if (!open) {
+ return (
+ <button type="button" disabled={busy} onClick={() => setOpen(true)} className="flex items-center gap-1 rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 border border-port-border disabled:opacity-50">
+ <Pencil size={14} aria-hidden="true" /> Edit direction
+ </button>
+ );
+ }
+ return (
+ <fieldset disabled={busy} className="w-full min-w-0 space-y-3 rounded border border-port-border p-2">
+ <legend className="px-1 text-xs text-port-text-muted">Edit direction</legend>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {PROTAGONIST_FIELDS.map((f) => field('protagonist', f))}
+ <div className="sm:col-span-2">
+ <label htmlFor={idFor('expressions')} className="text-xs">Expressions (one per line)</label>
+ <textarea id={idFor('expressions')} rows={3} className={inputClass} value={draft.protagonist.expressions} onChange={(e) => setField('protagonist', 'expressions', e.target.value)} />
+ </div>
+ {WORLD_FIELDS.map((f) => field('world', f))}
+ </div>
+ {(direction.sets || []).length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {direction.sets.map((set) => (
+ <div key={set.id}>
+ <label htmlFor={idFor(`role-${set.id}`)} className="text-xs">Image role · {set.name}</label>
+ <select id={idFor(`role-${set.id}`)} className={inputClass} value={draft.roles[set.id]} onChange={(e) => setDraft((d) => ({ ...d, roles: { ...d.roles, [set.id]: e.target.value } }))}>
+ {IMAGE_ROLES.map((role) => <option key={role} value={role}>{role}</option>)}
+ </select>
+ </div>
+ ))}
+ </div>
+ )}
+ <p className="text-xs text-port-text-muted">Saving revises this check-in. Only images whose prompt changes are re-rendered.</p>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={!dirty} onClick={() => onSave(edits).then((res) => { if (res) setOpen(false); })} className="flex items-center gap-1 rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 bg-port-accent text-white disabled:opacity-50">
+ <Save size={14} aria-hidden="true" /> Save direction
+ </button>
+ <button type="button" onClick={() => { setDraft(draftFrom(direction)); setOpen(false); }} className="rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 text-port-text-muted">Cancel</button>
+ </div>
+ </fieldset>
+ );
+}
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsx
index d85d3b56de..dba00d55a1 100644
--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx
+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
-import { normalizeMusicVideoProductionPolicy } from '../../../../server/lib/musicVideoMediumPlan.js';
+import { musicVideoToolPolicyConflict, normalizeMusicVideoProductionPolicy } from '../../../../server/lib/musicVideoMediumPlan.js';
import { formatCount } from '../../utils/formatters.js';
import { Link } from 'react-router';
import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuilder.js';
@@ -19,6 +19,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
const [universe, setUniverse] = useState(null);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
+ const [replanning, setReplanning] = useState(false);
const [error, setError] = useState('');
const [newKind, setNewKind] = useState('character');
const [newName, setNewName] = useState('');
@@ -28,6 +29,9 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
const universeReady = !universeId || (!loading && universe?.id === universeId);
const subjects = editing ? (draft?.subjects || []) : (project.concept?.subjects || []);
const idFor = (name) => `mv-creative-${project.id}-${name}`;
+ // The saved tools and policy disagree (no video tool, yet generated footage is still planned).
+ // Shown, never auto-fixed: approved plans and sheets stay as saved until the director replans.
+ const conflict = musicVideoToolPolicyConflict(project);
useEffect(() => {
onPendingChange(editing);
@@ -69,6 +73,13 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
setDraft((d) => ({ ...d, subjects: [...d.subjects, subject] }));
if (canon) setSelectedCanon((items) => [...items, { subjectId: subject.id, kind, entry: canon }]);
};
+ const replan = () => {
+ setReplanning(true);
+ setError('');
+ return onSave({ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } })
+ .catch((err) => setError(err.message || 'Could not replan the production policy'))
+ .finally(() => setReplanning(false));
+ };
const save = async () => {
if (!universeReady) { setError('Wait for the selected universe to load before saving.'); return; }
const percent = draft.productionPolicy.maxGeneratedVideoPercent;
@@ -160,6 +171,11 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
<div className="flex flex-wrap gap-3"><button type="button" onClick={save} disabled={!universeReady || !!newName.trim() || !!newDescription.trim()} className="bg-port-accent text-white rounded px-3 py-2 text-sm disabled:opacity-50">{saving ? 'Saving…' : 'Save creative setup'}</button><button type="button" onClick={() => setEditing(false)} className="text-sm">Cancel</button></div>
</fieldset>}
{!editing && project.productionPolicy?.strategy === 'code-first' && <p className="text-xs text-port-text-muted">Code-first plan · generated video allowance {formatCount(project.productionPolicy.maxGeneratedVideoPercent, { maximumFractionDigits: 3 })}% of final song time</p>}
+ {!editing && conflict && <div role="status" className="rounded border border-port-warning/60 p-2 space-y-1">
+ <p className="text-xs text-port-warning">{conflict.message}</p>
+ <p className="text-xs text-port-text-muted">Generated video is not dispatched without a video tool. Existing approved plans and check-in sheets stay as saved until you replan.</p>
+ <button type="button" onClick={replan} disabled={replanning} className="text-sm text-port-accent min-h-[44px] disabled:opacity-50">{replanning ? 'Replanning…' : 'Replan as code-first, no generated video'}</button>
+ </div>}
{error && <p role="alert" className="text-sm text-port-error">{error}</p>}
</section>;
}
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
index e69e8a4e68..39cb1fbfaf 100644
--- a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
@@ -102,3 +102,36 @@ it('defaults code-first to zero, offers 20% selective footage, and saves the exp
productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 12.5 },
})));
});
+
+describe('tools / policy conflict', () => {
+ const render_ = (extra, onSave = vi.fn(async () => {})) => {
+ render(<MemoryRouter><CreativeSetupPanel project={{ ...project, ...extra }} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);
+ return onSave;
+ };
+ const noVideo = { automation: { tools: ['image:codex', 'code:render'] } };
+
+ it('warns when no video tool is selected but footage is still planned, and only a deliberate replan saves the new policy', async () => {
+ const onSave = render_({ ...noVideo, productionPolicy: { strategy: 'legacy', maxGeneratedVideoPercent: 100 } });
+ expect(screen.getByRole('status')).toHaveTextContent('No video tool is selected');
+ expect(screen.getByText(/stay as saved until you replan/)).toBeInTheDocument();
+ expect(onSave).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByText('Replan as code-first, no generated video'));
+ await waitFor(() => expect(onSave).toHaveBeenCalledWith({ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } }));
+ });
+
+ it('keeps a failed replan visible and re-enables the action', async () => {
+ render_({ ...noVideo }, vi.fn(async () => { throw new Error('Save rejected'); }));
+ fireEvent.click(screen.getByText('Replan as code-first, no generated video'));
+ await screen.findByText('Save rejected');
+ expect(screen.getByText('Replan as code-first, no generated video')).not.toBeDisabled();
+ });
+
+ it.each([
+ ['a video tool is selected', { automation: { tools: ['image:codex', 'video:fal'] } }],
+ ['the policy already allows no generated video', { ...noVideo, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } }],
+ ['the brief names no tools', {}],
+ ])('shows nothing when %s', (_label, extra) => {
+ render_(extra);
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+});
diff --git a/client/src/components/musicVideo/stages/CastSetsStage.jsx b/client/src/components/musicVideo/stages/CastSetsStage.jsx
index bae1012b45..772c67234d 100644
--- a/client/src/components/musicVideo/stages/CastSetsStage.jsx
+++ b/client/src/components/musicVideo/stages/CastSetsStage.jsx
@@ -17,6 +17,7 @@ export default function CastSetsStage({ board }) {
onOpenSheet={board.openArtifact}
onApprove={board.approveCastAndSets}
onRegenerate={() => castSets.regenerate()}
+ onEditDirection={castSets.editDirection}
onResume={() => castSets.resume()}
onSkip={board.skipCastAndSets}
/>
diff --git a/client/src/hooks/useMusicVideoCastAndSets.js b/client/src/hooks/useMusicVideoCastAndSets.js
index d0ec8c6c2c..1f369b6675 100644
--- a/client/src/hooks/useMusicVideoCastAndSets.js
+++ b/client/src/hooks/useMusicVideoCastAndSets.js
@@ -6,6 +6,7 @@ import {
getMusicVideoProject,
startMusicVideoCastAndSets,
regenerateMusicVideoCastAndSets,
+ editMusicVideoCastAndSetsDirection,
resumeMusicVideoCastAndSets,
approveMusicVideoCastAndSets,
skipMusicVideoCastAndSets,
@@ -27,7 +28,7 @@ const CHECKPOINTS = new Set(['review', 'approved', 'skipped', 'failed']);
* reaches a checkpoint (`review`, `approved`, `skipped`, `failed`), or null
* when it could not start.
*
- * Returns `{ busy, start, regenerate, resume, approve, skip, runToCheckpoint }`.
+ * Returns `{ busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint }`.
*/
export default function useMusicVideoCastAndSets({ project, replaceProject } = {}) {
const projectId = project?.id || null;
@@ -109,6 +110,7 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
const start = () => call(() => startMusicVideoCastAndSets(projectId, {}, { silent: true }));
const regenerate = (notes) => call(() => regenerateMusicVideoCastAndSets(projectId, notes ? { notes } : {}, { silent: true }), 'Regenerating with your notes');
+ const editDirection = (edits) => call(() => editMusicVideoCastAndSetsDirection(projectId, edits, { silent: true }), 'Direction saved — re-rendering what changed');
const resume = () => call(() => resumeMusicVideoCastAndSets(projectId, { silent: true }));
const approve = () => call(() => approveMusicVideoCastAndSets(projectId, { silent: true }), 'Cast & Sets approved');
const skip = () => call(() => skipMusicVideoCastAndSets(projectId, { silent: true }), 'Cast & Sets check-in skipped');
@@ -132,5 +134,5 @@ export default function useMusicVideoCastAndSets({ project, replaceProject } = {
});
};
- return { busy, start, regenerate, resume, approve, skip, runToCheckpoint };
+ return { busy, start, regenerate, editDirection, resume, approve, skip, runToCheckpoint };
}
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 776f73093d..e0fd1d44fc 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -827,7 +827,7 @@ export default function MusicVideo() {
saveVisualSpec,
saveAutomation,
saveCreativeSetup: (patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {
- patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });
+ patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec, productionPolicy: project.productionPolicy });
}),
setCreativeSetupPending,
setStyleReferencesPending,
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index e04b4f75e9..2f0d88fce5 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -366,6 +366,9 @@ export const startMusicVideoCastAndSets = (id, body = {}, options = {}) =>
// Body: { notes?: [{ text, target? }] } — omitted notes = the sheet's open notes.
export const regenerateMusicVideoCastAndSets = (id, body = {}, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/regenerate`, { method: 'POST', body: JSON.stringify(body), ...options });
+// Body: { protagonist?, world?, sets?: [{ id, imageRole }] } — the director's direct edits to a procedural direction.
+export const editMusicVideoCastAndSetsDirection = (id, body, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/direction`, { method: 'PATCH', body: JSON.stringify(body), ...options });
export const resumeMusicVideoCastAndSets = (id, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/resume`, { method: 'POST', body: '{}', ...options });
export const approveMusicVideoCastAndSets = (id, options = {}) =>
diff --git a/server/lib/README.md b/server/lib/README.md
index 0d9893d79e..8bce276f72 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -797,7 +797,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |
-| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
+| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCodeDirectionContext(direction)` renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
| `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. |
| `musicVideoAutonomous.js` | Fully-autonomous Music Video vocabulary: `AUTONOMOUS_STAGES` (brief → lyrics → style → song → analyze → produce), optional `AUTONOMOUS_CHECKPOINT_IDS`, `normalizeAutonomousSettings` / `normalizeAutonomousBrief` / `normalizeAutopilotParams` (the shared run settings, a run's stored brief, and the scheduled task's params), `autonomousMedium` / `autonomousPool` (tool picks → footage vs code, production route pool), `sunoSongFields` + Suno limits/URL helpers, and `pickBrainIdea` / `ideaToPrompt` for the scheduled task. Pure; the client drawer and the run service import it. |
| `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap, `llm: null` clears the direction-LLM pin, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545). Dependency-light; the client create drawer imports it. |
@@ -812,7 +812,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoAspect.js` | `musicVideoAspect(project)` (treatment brief aspect, default 16:9), `MUSIC_VIDEO_FRAME_GEN_SIZES` and `musicVideoFrameGenSize(project)`: the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. `musicVideoAtAspect(project, aspect)` re-frames the project for one render (a vertical social cut) without touching the record. Shared by `productionDispatch.js`, `documentRender.js` and the client board. |
| `musicVideoMotion.js` | `MOTION_CONTINUITY_CLAUSE`: the clause every Music Video motion (i2v) prompt ends with, pinning the reference frame's lighting, time of day and palette. Shared by `handoff.js` and the client board. |
| `musicVideoConditioning.js` | `musicVideoStyleImages`, `musicVideoStylePrompt`, `musicVideoStyleBasis`, and `musicVideoStyleReferenceCapacity` supply bounded moodboard conditioning and text fallback; `musicVideoConditioningReferences(project, scene)` selects the approved character sheet and scene's mapped set plate, with capped project-wide fallback; shared by board and production. |
-| `musicVideoMediumPlan.js` | `normalizeMusicVideoProductionPolicy`, `planMusicVideoMedia`, `summarizeMusicVideoMediumPlan`, and `codeFirstProductionAssets`: pinned shot media, union-of-intervals video allowance, and selected-asset preflight shared by planning and Board review. |
+| `musicVideoMediumPlan.js` | `normalizeMusicVideoProductionPolicy`, `planMusicVideoMedia`, `summarizeMusicVideoMediumPlan`, and `codeFirstProductionAssets`: pinned shot media, union-of-intervals video allowance, and selected-asset preflight shared by planning and Board review. `musicVideoBriefTools`, `musicVideoBriefAllowsVideo` and `musicVideoToolPolicyConflict` read the brief's selected tools against the policy (the setup warning and the video-dispatch refusal). |
| `imageLimits.js` | MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS — browser-safe image generation caps shared with validation. |
diff --git a/server/lib/musicVideoCreativeContext.js b/server/lib/musicVideoCreativeContext.js
index 05d33df45d..b88761659a 100644
--- a/server/lib/musicVideoCreativeContext.js
+++ b/server/lib/musicVideoCreativeContext.js
@@ -66,3 +66,42 @@ export function musicVideoDirectionContext(direction) {
...((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);
}
+
+const CODE_CONTEXT_MAX = 8000;
+
+/**
+ * The approved procedural direction as a code-authoring request needs it: how
+ * each character is built and moves, the world's layout/depth/lighting/camera/
+ * transition rules, and the reusable character definitions (geometry, palette,
+ * expressions, poses, motion) so every scene draws the same figures. '' for a
+ * photographic direction or one with neither rules nor definitions. Whole
+ * characters are included while the budget allows, never a truncated JSON.
+ */
+export function musicVideoCodeDirectionContext(direction) {
+ if (direction?.medium !== 'procedural') return '';
+ const p = direction.protagonist || {};
+ const w = direction.world || {};
+ const rules = (label, pairs) => {
+ const body = pairs.filter(([, v]) => v).map(([k, v]) => `${k}: ${trimTo(v, 300)}`).join('; ');
+ return body ? [`${label} ${body}`] : [];
+ };
+ const head = [
+ 'Approved Cast & Sets direction for code (reuse these exact definitions and rules in every scene; never redesign a character, palette or camera language per scene):',
+ ...rules('Character build:', [['construction', p.construction], ['shape language', p.shapeLanguage], ['materials', p.materials], ['palette', p.palette], ['expressions', (p.expressions || []).join(' | ')], ['movement', p.movement]]),
+ ...rules('World rules:', [['layout', w.layout], ['depth', w.depth], ['lighting', w.lighting], ['camera', w.camera], ['transitions', w.transitions]]),
+ ...(direction.sets || []).slice(0, 8).map((s) => `Set ${trimTo(s.name, 80)} (image role ${s.imageRole || 'background'}): ${trimTo(s.description, 200)}`),
+ ];
+ const lines = [...head];
+ const characters = direction.definitions?.characters || [];
+ if (characters.length) {
+ lines.push('Character definitions (JSON; coordinates are in a 200x200 box, origin top-left; expressions and poses override base parts; motion rules are per-beat):');
+ let budget = CODE_CONTEXT_MAX - lines.join('\n').length;
+ for (const character of characters) {
+ const json = JSON.stringify(character);
+ if (json.length > budget) break;
+ lines.push(json);
+ budget -= json.length + 1;
+ }
+ }
+ return lines.length > 1 ? lines.join('\n') : '';
+}
diff --git a/server/lib/musicVideoCreativeContext.test.js b/server/lib/musicVideoCreativeContext.test.js
new file mode 100644
index 0000000000..333539ea76
--- /dev/null
+++ b/server/lib/musicVideoCreativeContext.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest';
+import { musicVideoCodeDirectionContext } from './musicVideoCreativeContext.js';
+
+const character = (id, partCount) => ({
+ id, name: id, renderer: 'svg', palette: [],
+ parts: Array.from({ length: partCount }, (_, i) => ({ id: `p${i}`, shape: 'circle', x: 10, y: 10, r: 5 })),
+ expressions: [], poses: [], motion: [],
+});
+
+describe('musicVideoCodeDirectionContext', () => {
+ const procedural = (characters) => ({
+ medium: 'procedural',
+ protagonist: { name: 'Boat', movement: 'bobs on every beat' },
+ world: { camera: 'slow dolly' },
+ sets: [{ id: 'river', name: 'River', description: 'a neon river', imageRole: 'texture' }],
+ definitions: { characters },
+ });
+
+ it('carries the rules, the set roles and each definition as parseable JSON', () => {
+ const text = musicVideoCodeDirectionContext(procedural([character('boat', 2)]));
+ expect(text).toContain('movement: bobs on every beat');
+ expect(text).toContain('camera: slow dolly');
+ expect(text).toContain('Set River (image role texture)');
+ const json = text.split('\n').find((line) => line.startsWith('{"id":"boat"'));
+ expect(JSON.parse(json).parts).toHaveLength(2);
+ });
+
+ it('includes whole characters only, never a truncated definition', () => {
+ const text = musicVideoCodeDirectionContext(procedural([character('small', 3), character('huge', 400)]));
+ expect(text.length).toBeLessThanOrEqual(8000);
+ expect(text).toContain('"id":"small"');
+ expect(text).not.toContain('"id":"huge"');
+ });
+
+ it('is empty for a photographic direction or one with no rules and no definitions', () => {
+ expect(musicVideoCodeDirectionContext(null)).toBe('');
+ expect(musicVideoCodeDirectionContext({ protagonist: { name: 'Nova', face: 'weathered' } })).toBe('');
+ expect(musicVideoCodeDirectionContext({ medium: 'procedural' })).toBe('');
+ });
+});
diff --git a/server/lib/musicVideoMediumPlan.js b/server/lib/musicVideoMediumPlan.js
index acbc2e1070..81b98a9aff 100644
--- a/server/lib/musicVideoMediumPlan.js
+++ b/server/lib/musicVideoMediumPlan.js
@@ -23,6 +23,31 @@ export function normalizeMusicVideoProductionPolicy(patch, base = null) {
};
}
+/** The brief's selected render tools (`image:*`, `video:*`, `code:render`); empty when the brief names none. */
+export const musicVideoBriefTools = (project) => (Array.isArray(project?.automation?.tools) ? project.automation.tools.filter((t) => typeof t === 'string') : []);
+
+/** False when the brief names tools and none of them makes video. A brief naming no tools restricts nothing. */
+export function musicVideoBriefAllowsVideo(project) {
+ const tools = musicVideoBriefTools(project);
+ return tools.length === 0 || tools.some((t) => t.startsWith('video:'));
+}
+
+/**
+ * The saved tools and production policy disagree: the brief selected tools but
+ * no video tool, while the policy still plans generated footage (legacy, or
+ * code-first with a non-zero allowance). Describes the mismatch; never edits
+ * anything — an approved plan stays as saved until the director replans.
+ */
+export function musicVideoToolPolicyConflict(project) {
+ if (musicVideoBriefAllowsVideo(project)) return null;
+ const policy = normalizeMusicVideoProductionPolicy(project?.productionPolicy);
+ if (policy.strategy === 'code-first' && policy.maxGeneratedVideoPercent <= 0) return null;
+ return {
+ code: 'NO_VIDEO_TOOL',
+ message: 'No video tool is selected, but the production policy still allows generated footage. Replan as code-first with no generated video, or add a video tool to the brief.',
+ };
+}
+
function unionSeconds(intervals) {
let end = 0;
let total = 0;
diff --git a/server/lib/musicVideoMediumPlan.test.js b/server/lib/musicVideoMediumPlan.test.js
new file mode 100644
index 0000000000..6c0da25563
--- /dev/null
+++ b/server/lib/musicVideoMediumPlan.test.js
@@ -0,0 +1,23 @@
+import { describe, it, expect } from 'vitest';
+import { musicVideoBriefAllowsVideo, musicVideoToolPolicyConflict } from './musicVideoMediumPlan.js';
+
+describe('brief tools vs production policy', () => {
+ const codeFirst = (percent) => ({ strategy: 'code-first', maxGeneratedVideoPercent: percent });
+
+ it('only a brief that names tools and no video tool forbids video', () => {
+ expect(musicVideoBriefAllowsVideo({})).toBe(true);
+ expect(musicVideoBriefAllowsVideo({ automation: { tools: [] } })).toBe(true);
+ expect(musicVideoBriefAllowsVideo({ automation: { tools: ['image:codex', 'video:fal'] } })).toBe(true);
+ expect(musicVideoBriefAllowsVideo({ automation: { tools: ['image:codex', 'code:render'] } })).toBe(false);
+ });
+
+ it('flags a saved pair that plans generated footage with no video tool, and nothing else', () => {
+ const noVideo = ['image:codex', 'code:render'];
+ // Legacy defaults to 100% generated video; a non-zero code-first allowance also contradicts the tools.
+ expect(musicVideoToolPolicyConflict({ automation: { tools: noVideo } })).toMatchObject({ code: 'NO_VIDEO_TOOL' });
+ expect(musicVideoToolPolicyConflict({ automation: { tools: noVideo }, productionPolicy: codeFirst(20) })).toMatchObject({ code: 'NO_VIDEO_TOOL' });
+ expect(musicVideoToolPolicyConflict({ automation: { tools: noVideo }, productionPolicy: codeFirst(0) })).toBeNull();
+ expect(musicVideoToolPolicyConflict({ automation: { tools: ['video:fal'] }, productionPolicy: codeFirst(20) })).toBeNull();
+ expect(musicVideoToolPolicyConflict({ productionPolicy: codeFirst(20) })).toBeNull();
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 0eac7f03e9..87b9affa35 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -888,6 +888,31 @@ export const musicVideoCastAndSetsRegenerateSchema = z.object({
effort: z.enum(EFFORT_LEVELS).optional(),
}).strict();
+// Direct edits to a procedural direction. A present text field replaces the
+// current value (empty clears it); an absent one keeps it.
+const castSetsText = (max) => z.string().max(max);
+export const musicVideoCastAndSetsDirectionEditSchema = z.object({
+ protagonist: z.object({
+ construction: castSetsText(1000).optional(),
+ shapeLanguage: castSetsText(500).optional(),
+ materials: castSetsText(500).optional(),
+ palette: castSetsText(300).optional(),
+ movement: castSetsText(1000).optional(),
+ expressions: z.array(castSetsText(300)).max(8).optional(),
+ }).strict().optional(),
+ world: z.object({
+ layout: castSetsText(1000).optional(),
+ depth: castSetsText(500).optional(),
+ lighting: castSetsText(500).optional(),
+ camera: castSetsText(500).optional(),
+ transitions: castSetsText(500).optional(),
+ }).strict().optional(),
+ sets: z.array(z.object({
+ id: z.string().min(1).max(64),
+ imageRole: z.enum(['background', 'texture', 'decoration', 'cutout']),
+ }).strict()).max(8).optional(),
+}).strict();
+
export const musicVideoProjectCreateSchema = z.object({
productionPolicy: musicVideoProductionPolicySchema.optional(),
name: z.string().min(1).max(200),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 49f41741be..37ee2f188a 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -64,6 +64,7 @@ import {
musicVideoDevArtifactReviewSchema,
musicVideoDevArtifactFileQuerySchema,
musicVideoCastAndSetsStartSchema,
+ musicVideoCastAndSetsDirectionEditSchema,
musicVideoCastAndSetsRegenerateSchema,
musicVideoDocumentDirectoryImportSchema,
musicVideoDocumentFileQuerySchema,
@@ -171,6 +172,7 @@ import {
import { devArtifactTypeFor } from '../services/musicVideo/devArtifacts.js';
import {
startCastAndSets,
+ editCastAndSetsDirection,
regenerateCastAndSets,
resumeCastAndSets,
approveCastAndSets,
@@ -944,6 +946,11 @@ router.post('/:id/cast-and-sets/regenerate', asyncHandler(async (req, res) => {
res.status(202).json(await regenerateCastAndSets(req.params.id, input));
}));
+router.patch('/:id/cast-and-sets/direction', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoCastAndSetsDirectionEditSchema, req.body || {});
+ res.status(202).json(await editCastAndSetsDirection(req.params.id, input));
+}));
+
router.post('/:id/cast-and-sets/resume', asyncHandler(async (req, res) => {
const input = validateRequest(musicVideoCastAndSetsStartSchema, req.body || {});
res.status(202).json(await resumeCastAndSets(req.params.id, input));
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index e3dbd010ef..934b75bd82 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -329,7 +329,7 @@ function promptSong(song) {
* render function per section (or just `onlySectionId` when regenerating).
* The host assembles the page; the model does not return a full HTML document.
*/
-export function buildMusicVideoCodePrompt({ title = '', palette, song, styleLines = [], onlySectionId = null }) {
+export function buildMusicVideoCodePrompt({ title = '', palette, song, styleLines = [], onlySectionId = null, directionContext = '' }) {
const wanted = (song.sections || []).filter((section) => !onlySectionId || section.id === onlySectionId);
const brief = wanted.map((section) => `- ${section.id} [${section.startSec}s, ${section.endSec}s) ${section.label || ''}${section.lyric ? ` — lyric: ${section.lyric}` : ' — instrumental'}`).join('\n');
const scope = onlySectionId
@@ -340,6 +340,7 @@ export function buildMusicVideoCodePrompt({ title = '', palette, song, styleLine
CODE_VIDEO_RULES,
`PALETTE:\n${JSON.stringify(palette)}`,
styleLines.length ? `STYLE SOURCE:\n${styleLines.join('\n')}` : '',
+ directionContext ? `APPROVED CAST & SETS DEFINITIONS AND RULES:\n${directionContext}` : '',
`SONG (song.json):\n${JSON.stringify(promptSong(song))}`,
`SECTIONS:\n${brief}`,
scope,
@@ -366,7 +367,7 @@ export function extractCodeSections(text) {
}
/** Author only bounded drawing functions; the host owns the page and media. */
-export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment, visualSpec, scenes, styleLines = [], onlySectionId = null, sharedStyle = null }) {
+export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment, visualSpec, scenes, styleLines = [], onlySectionId = null, sharedStyle = null, directionContext = '' }) {
const sections = (song.sections || []).filter((section) => !onlySectionId || section.id === onlySectionId);
return [
`Write original Canvas 2D section functions for a mixed-media music-video document titled ${JSON.stringify(trimTo(title, 200))}. The host owns the document, song clock, selected local media and lyric pass. Return code functions only; do not request or generate image/video assets.`,
@@ -374,6 +375,7 @@ export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment,
'env additionally has mediaKind (video, image or null) and visualLayer (footage, still or card). The host has already drawn the selected media at its in/out time. Do not read DOM or load assets in a section function. Use seeded arithmetic from env.frame for visual motion. Keep repeated hooks related but deliberately vary their action.',
'NARRATIVE CLOCK: song.narrativeEvents are resolved absolute startFrame/endFrame bindings. env.events supplies active events with progress and counter value; env.reactiveGain is bounded by the section gain/maxGain and is zero during silence. The host freezes song time, media and graphics for silence, and draws exact event text/counters/motif labels after your function. Use the narrativeFunction, motif and mediumRationale to motivate your graphic actions; do not duplicate event text or infer new onsets. Prefer code/stills/selected media for exact text and graphics. Footage is for actions that need it and must already be selected.',
`SHARED STYLE CONTRACT:\n${JSON.stringify(sharedStyle || { palette, treatment: { brief: treatment?.brief || null, motifs: treatment?.arc?.motifs || [], styleLook: treatment?.styleLook || null }, visualSpec, styleLines })}`,
+ directionContext ? `APPROVED CAST & SETS DEFINITIONS AND RULES:\n${directionContext}` : '',
`SONG AND LYRIC TIMING:\n${JSON.stringify(promptSong(song))}`,
`APPROVED SCENE ASSIGNMENTS AND LOCAL ASSET IDS:\n${JSON.stringify(scenes)}`,
`SECTIONS TO AUTHOR:\n${JSON.stringify(sections)}`,
diff --git a/server/services/musicVideo/castAndSets.js b/server/services/musicVideo/castAndSets.js
index 172ae1ad37..7cc5a31beb 100644
--- a/server/services/musicVideo/castAndSets.js
+++ b/server/services/musicVideo/castAndSets.js
@@ -51,6 +51,9 @@ const stageError = (status, code, message) => new ServerError(message, { status,
/** The check-in mode for a project (default: review). */
export const castAndSetsCheckinMode = (project) => (project?.automation?.checkins?.castAndSets === 'auto' ? 'auto' : 'review');
+/** The direction a code-authoring request may reuse: only an APPROVED stage's. */
+export const approvedCastAndSetsDirection = (project) => (project?.castAndSets?.status === 'approved' ? (project.castAndSets.direction || null) : null);
+
export const castAndSetsSettled = (stage) => CAST_SETS_SETTLED.includes(stage?.status);
/** The stage as the director sees it: `interrupted` when a restart unpinned a working stage. */
diff --git a/server/services/musicVideo/castAndSetsDefinitions.js b/server/services/musicVideo/castAndSetsDefinitions.js
new file mode 100644
index 0000000000..845a8aae6b
--- /dev/null
+++ b/server/services/musicVideo/castAndSetsDefinitions.js
@@ -0,0 +1,323 @@
+/**
+ * Music Video — reusable code character definitions for a procedural Cast & Sets
+ * direction (pure).
+ *
+ * A procedural direction describes a character in prose; a DEFINITION makes it
+ * executable and reviewable: a renderer id, geometry parts in a fixed 200×200
+ * box, a named palette, named expressions and poses (per-part overrides) and
+ * motion rules. The same definition is drawn into the check-in sheet as inline
+ * SVG and handed to the code-authoring request so every scene reuses it.
+ *
+ * Everything here is bounded and sanitized: numbers are finite and clamped,
+ * colors are hex or a palette name, a path may hold only drawing commands. The
+ * preview is built from those validated values alone (no script, no URL, no
+ * font), so it is safe inside the sandboxed sheet and offline.
+ *
+ * Absent-vs-empty: `normalizeDefinitions(undefined)` is `null` (keep the current
+ * value); `{ characters: [] }` is an intentional clear.
+ */
+
+import { trimTo } from '../../lib/textUtils.js';
+
+export const CAST_SETS_DEFINITION_RENDERERS = Object.freeze(['svg', 'canvas2d', 'three']);
+export const CAST_SETS_DEFINITION_SHAPES = Object.freeze(['circle', 'ellipse', 'rect', 'polygon', 'path', 'line']);
+export const CAST_SETS_MOTION_PROPERTIES = Object.freeze(['rotate', 'scale', 'translateX', 'translateY', 'opacity']);
+export const CAST_SETS_MOTION_TRIGGERS = Object.freeze(['idle', 'beat', 'downbeat', 'lyric', 'section']);
+export const CAST_SETS_MOTION_EASINGS = Object.freeze(['linear', 'ease-in-out', 'ease-out', 'bounce', 'step']);
+export const CAST_SETS_DEFINITION_LIMITS = Object.freeze({
+ characters: 4,
+ parts: 20,
+ palette: 12,
+ expressions: 8,
+ poses: 8,
+ motion: 8,
+ points: 16,
+ path: 400,
+ box: 200,
+});
+
+const NAME = 60;
+const NOTE = 200;
+const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
+// A path may hold drawing commands, numbers and separators — nothing else.
+const PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9\s.,+-]+$/;
+
+// Local escape (the sheet imports this module, so it cannot be imported back).
+const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
+const slug = (v) => String(v ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
+const oneOf = (v, list, fallback) => (list.includes(v) ? v : fallback);
+const round = (n) => Math.round(n * 100) / 100;
+const num = (v, min, max) => {
+ const n = typeof v === 'string' && v.trim() ? Number(v) : v;
+ return typeof n === 'number' && Number.isFinite(n) ? round(Math.min(max, Math.max(min, n))) : null;
+};
+const coord = (v) => num(v, 0, CAST_SETS_DEFINITION_LIMITS.box);
+const pair = (v) => {
+ if (!Array.isArray(v) || v.length < 2) return null;
+ const x = coord(v[0]);
+ const y = coord(v[1]);
+ return x == null || y == null ? null : [x, y];
+};
+
+function normalizePalette(raw) {
+ // Either [{ name, hex }] or { name: hex }.
+ const entries = Array.isArray(raw)
+ ? raw.filter(isObject).map((e) => [e.name, e.hex ?? e.color])
+ : (isObject(raw) ? Object.entries(raw) : []);
+ const seen = new Set();
+ const out = [];
+ for (const [name, hex] of entries) {
+ const key = slug(name);
+ if (!key || seen.has(key) || typeof hex !== 'string' || !HEX.test(hex.trim())) continue;
+ seen.add(key);
+ out.push({ name: key, hex: hex.trim().toLowerCase() });
+ if (out.length >= CAST_SETS_DEFINITION_LIMITS.palette) break;
+ }
+ return out;
+}
+
+// A color is `none`, a hex, or the name of a palette entry; anything else is dropped.
+function normalizeColor(v, palette) {
+ if (typeof v !== 'string') return '';
+ const t = v.trim();
+ if (t.toLowerCase() === 'none') return 'none';
+ if (HEX.test(t)) return t.toLowerCase();
+ const key = slug(t);
+ return palette.some((p) => p.name === key) ? key : '';
+}
+
+function normalizePart(raw, palette, index) {
+ if (!isObject(raw)) return null;
+ const shape = oneOf(raw.shape, CAST_SETS_DEFINITION_SHAPES, null);
+ if (!shape) return null;
+ const part = { id: slug(raw.id) || `part-${index + 1}`, shape };
+ const box = CAST_SETS_DEFINITION_LIMITS.box;
+ if (shape === 'circle') {
+ const [x, y, r] = [coord(raw.x), coord(raw.y), num(raw.r, 0, box)];
+ if (x == null || y == null || !r) return null;
+ Object.assign(part, { x, y, r });
+ } else if (shape === 'ellipse') {
+ const [x, y, rx, ry] = [coord(raw.x), coord(raw.y), num(raw.rx, 0, box), num(raw.ry, 0, box)];
+ if (x == null || y == null || !rx || !ry) return null;
+ Object.assign(part, { x, y, rx, ry });
+ } else if (shape === 'rect') {
+ const [x, y, width, height] = [coord(raw.x), coord(raw.y), num(raw.width, 0, box), num(raw.height, 0, box)];
+ if (x == null || y == null || !width || !height) return null;
+ Object.assign(part, { x, y, width, height });
+ const radius = num(raw.radius, 0, box);
+ if (radius) part.radius = radius;
+ } else if (shape === 'line') {
+ const [x, y, x2, y2] = [coord(raw.x), coord(raw.y), coord(raw.x2), coord(raw.y2)];
+ if (x == null || y == null || x2 == null || y2 == null) return null;
+ Object.assign(part, { x, y, x2, y2 });
+ } else if (shape === 'polygon') {
+ const points = (Array.isArray(raw.points) ? raw.points : []).map(pair).filter(Boolean).slice(0, CAST_SETS_DEFINITION_LIMITS.points);
+ if (points.length < 3) return null;
+ part.points = points;
+ } else {
+ const d = trimTo(raw.d, CAST_SETS_DEFINITION_LIMITS.path);
+ if (!d || !PATH.test(d)) return null;
+ part.d = d;
+ }
+ const fill = normalizeColor(raw.fill, palette);
+ const stroke = normalizeColor(raw.stroke, palette);
+ if (fill) part.fill = fill;
+ if (stroke) part.stroke = stroke;
+ const strokeWidth = num(raw.strokeWidth, 0, 40);
+ if (strokeWidth != null) part.strokeWidth = strokeWidth;
+ const opacity = num(raw.opacity, 0, 1);
+ if (opacity != null) part.opacity = opacity;
+ const pivot = pair(raw.pivot);
+ if (pivot) part.pivot = pivot;
+ return part;
+}
+
+// Expressions and poses: per-part overrides of the base geometry.
+function normalizeStates(raw, partIds, palette, max) {
+ const seen = new Set();
+ const out = [];
+ for (const entry of Array.isArray(raw) ? raw : []) {
+ if (!isObject(entry)) continue;
+ const name = trimTo(entry.name, NAME);
+ const key = slug(name);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ const overrides = {};
+ for (const [partId, o] of Object.entries(isObject(entry.overrides) ? entry.overrides : {})) {
+ const id = slug(partId);
+ if (!partIds.has(id) || !isObject(o)) continue;
+ const next = {};
+ const translate = Array.isArray(o.translate) && o.translate.length >= 2 ? [num(o.translate[0], -200, 200), num(o.translate[1], -200, 200)] : null;
+ if (translate && translate.every((n) => n != null)) next.translate = translate;
+ const rotate = num(o.rotate, -360, 360);
+ if (rotate != null) next.rotate = rotate;
+ const scale = num(o.scale, 0, 4);
+ if (scale != null) next.scale = scale;
+ const opacity = num(o.opacity, 0, 1);
+ if (opacity != null) next.opacity = opacity;
+ const fill = normalizeColor(o.fill, palette);
+ if (fill) next.fill = fill;
+ if (o.hidden === true) next.hidden = true;
+ if (Object.keys(next).length) overrides[id] = next;
+ }
+ out.push({ name, overrides });
+ if (out.length >= max) break;
+ }
+ return out;
+}
+
+function normalizeMotion(raw, partIds) {
+ const out = [];
+ for (const entry of Array.isArray(raw) ? raw : []) {
+ if (!isObject(entry)) continue;
+ const name = trimTo(entry.name, NAME);
+ const property = oneOf(entry.property, CAST_SETS_MOTION_PROPERTIES, null);
+ const amplitude = num(entry.amplitude, -360, 360);
+ if (!name || !property || amplitude == null) continue;
+ const target = slug(entry.target);
+ out.push({
+ name,
+ target: partIds.has(target) ? target : 'all',
+ property,
+ amplitude,
+ periodBeats: num(entry.periodBeats, 0.25, 64) ?? 1,
+ easing: oneOf(entry.easing, CAST_SETS_MOTION_EASINGS, 'ease-in-out'),
+ trigger: oneOf(entry.trigger, CAST_SETS_MOTION_TRIGGERS, 'idle'),
+ ...(trimTo(entry.note, NOTE) ? { note: trimTo(entry.note, NOTE) } : {}),
+ });
+ if (out.length >= CAST_SETS_DEFINITION_LIMITS.motion) break;
+ }
+ return out;
+}
+
+function normalizeCharacter(raw, index) {
+ if (!isObject(raw)) return null;
+ const name = trimTo(raw.name, NAME);
+ const palette = normalizePalette(raw.palette);
+ const seen = new Set();
+ const parts = [];
+ for (const [i, p] of (Array.isArray(raw.parts) ? raw.parts : []).entries()) {
+ const part = normalizePart(p, palette, i);
+ if (!part) continue;
+ let id = part.id;
+ while (seen.has(id)) id = `${id}-${i + 1}`;
+ seen.add(id);
+ parts.push({ ...part, id });
+ if (parts.length >= CAST_SETS_DEFINITION_LIMITS.parts) break;
+ }
+ if (!name || !parts.length) return null;
+ const partIds = new Set(parts.map((p) => p.id));
+ return {
+ id: slug(raw.id) || slug(name) || `character-${index + 1}`,
+ name,
+ renderer: oneOf(raw.renderer, CAST_SETS_DEFINITION_RENDERERS, 'svg'),
+ palette,
+ parts,
+ expressions: normalizeStates(raw.expressions, partIds, palette, CAST_SETS_DEFINITION_LIMITS.expressions),
+ poses: normalizeStates(raw.poses, partIds, palette, CAST_SETS_DEFINITION_LIMITS.poses),
+ motion: normalizeMotion(raw.motion, partIds),
+ };
+}
+
+/**
+ * Validate and bound a definitions block. Returns `null` when the input is not
+ * a definitions object at all (the caller keeps the current value),
+ * `{ characters: [] }` for an intentional clear, and `{ characters }` otherwise.
+ * Characters that do not validate are dropped; when every character the input
+ * carried is unusable the whole block counts as unusable (`null`) rather than
+ * as a clear.
+ */
+export function normalizeDefinitions(raw) {
+ if (!isObject(raw) || !Array.isArray(raw.characters)) return null;
+ if (!raw.characters.length) return { characters: [] };
+ const seen = new Set();
+ const characters = [];
+ for (const [i, c] of raw.characters.entries()) {
+ const character = normalizeCharacter(c, i);
+ if (!character) continue;
+ let id = character.id;
+ while (seen.has(id)) id = `${id}-${i + 1}`;
+ seen.add(id);
+ characters.push({ ...character, id });
+ if (characters.length >= CAST_SETS_DEFINITION_LIMITS.characters) break;
+ }
+ return characters.length ? { characters } : null;
+}
+
+// ---- preview ----------------------------------------------------------------
+
+const colorOf = (value, palette, fallback) => {
+ if (value === 'none') return 'none';
+ if (typeof value === 'string' && HEX.test(value)) return value;
+ return palette.find((p) => p.name === value)?.hex || fallback;
+};
+
+// Where a part turns and scales from when it names no pivot: its own center.
+function centerOf(part) {
+ if (part.shape === 'rect') return [part.x + part.width / 2, part.y + part.height / 2];
+ if (part.shape === 'line') return [(part.x + part.x2) / 2, (part.y + part.y2) / 2];
+ if (part.shape === 'polygon') return [round(part.points.reduce((t, [x]) => t + x, 0) / part.points.length), round(part.points.reduce((t, [, y]) => t + y, 0) / part.points.length)];
+ if (part.shape === 'path') return [CAST_SETS_DEFINITION_LIMITS.box / 2, CAST_SETS_DEFINITION_LIMITS.box / 2];
+ return [part.x, part.y];
+}
+
+function partMarkup(part, character, override = {}) {
+ if (override.hidden) return '';
+ const palette = character.palette;
+ const fill = colorOf(override.fill ?? part.fill, palette, part.stroke ? 'none' : '#9aa8a1');
+ const stroke = colorOf(part.stroke, palette, 'none');
+ const attrs = [`fill="${fill}"`, `stroke="${stroke}"`];
+ if (part.strokeWidth != null) attrs.push(`stroke-width="${part.strokeWidth}"`);
+ const opacity = override.opacity ?? part.opacity;
+ if (opacity != null) attrs.push(`opacity="${opacity}"`);
+ const [px, py] = part.pivot || centerOf(part);
+ const [tx, ty] = override.translate || [0, 0];
+ const transforms = [];
+ if (tx || ty) transforms.push(`translate(${tx} ${ty})`);
+ if (override.rotate) transforms.push(`rotate(${override.rotate} ${px} ${py})`);
+ if (override.scale != null && override.scale !== 1) transforms.push(`translate(${px} ${py}) scale(${override.scale}) translate(${-px} ${-py})`);
+ if (transforms.length) attrs.push(`transform="${transforms.join(' ')}"`);
+ const body = {
+ circle: () => `<circle cx="${part.x}" cy="${part.y}" r="${part.r}"`,
+ ellipse: () => `<ellipse cx="${part.x}" cy="${part.y}" rx="${part.rx}" ry="${part.ry}"`,
+ rect: () => `<rect x="${part.x}" y="${part.y}" width="${part.width}" height="${part.height}"${part.radius ? ` rx="${part.radius}"` : ''}`,
+ line: () => `<line x1="${part.x}" y1="${part.y}" x2="${part.x2}" y2="${part.y2}"`,
+ polygon: () => `<polygon points="${part.points.map(([x, y]) => `${x},${y}`).join(' ')}"`,
+ path: () => `<path d="${part.d}"`,
+ }[part.shape]();
+ return `${body} ${attrs.join(' ')}/>`;
+}
+
+/**
+ * One character as an inline `<svg>` string, drawn in the base pose or with a
+ * named expression or pose applied. Input is re-validated, so a hand-edited or
+ * stale record can never smuggle markup into the sheet.
+ */
+export function renderCharacterSvg(character, stateName = null, { size = 160 } = {}) {
+ const safe = normalizeDefinitions({ characters: [character] })?.characters?.[0];
+ if (!safe) return '';
+ const key = slug(stateName);
+ const state = key ? [...safe.expressions, ...safe.poses].find((s) => slug(s.name) === key) : null;
+ const parts = safe.parts.map((part) => partMarkup(part, safe, state?.overrides?.[part.id])).join('');
+ const label = `${safe.name}${state ? `: ${state.name}` : ''}`;
+ return `<svg viewBox="0 0 ${CAST_SETS_DEFINITION_LIMITS.box} ${CAST_SETS_DEFINITION_LIMITS.box}" width="${size}" height="${size}" role="img" aria-label="${escapeHtml(label)}">${parts}</svg>`;
+}
+
+/** The sheet's "Character design" section for a direction's definitions ('' when it has none). */
+export function renderDefinitionsSection(definitions) {
+ const characters = normalizeDefinitions(definitions)?.characters || [];
+ if (!characters.length) return '';
+ const e = escapeHtml;
+ const cards = characters.map((c) => {
+ const states = [{ name: 'Base', label: 'Base pose' }, ...c.expressions.map((s) => ({ name: s.name, label: s.name })), ...c.poses.map((s) => ({ name: s.name, label: `${s.name} (pose)` }))];
+ const tiles = states.map((s) => `<figure class="def-tile">${renderCharacterSvg(c, s.name === 'Base' ? null : s.name)}<figcaption>${e(s.label)}</figcaption></figure>`).join('');
+ const swatches = c.palette.map((p) => `<span class="swatch"><i style="background:${p.hex}"></i>${e(p.name)} <code>${p.hex}</code></span>`).join('');
+ const motion = c.motion.map((m) => `<tr><td>${e(m.name)}</td><td>${e(m.target)}</td><td>${e(m.property)} ±${m.amplitude}</td><td>${m.periodBeats} beat${m.periodBeats === 1 ? '' : 's'}, ${e(m.easing)}, on ${e(m.trigger)}${m.note ? ` — ${e(m.note)}` : ''}</td></tr>`).join('');
+ return `<div class="def"><h3>${e(c.name)} <span>${e(c.renderer)} · ${c.parts.length} part${c.parts.length === 1 ? '' : 's'}</span></h3>
+<div class="def-tiles">${tiles}</div>
+${swatches ? `<div class="swatches">${swatches}</div>` : ''}
+${motion ? `<div class="tablewrap"><table><tr><td><b>Motion</b></td><td><b>Target</b></td><td><b>Change</b></td><td><b>Timing</b></td></tr>${motion}</table></div>` : ''}</div>`;
+ }).join('');
+ return `<section><h2><small>Character design</small>Reusable code definitions</h2><p class="sub">Every scene reuses these exact parts, palette, expressions and motion rules.</p>${cards}</section>`;
+}
diff --git a/server/services/musicVideo/castAndSetsDefinitions.test.js b/server/services/musicVideo/castAndSetsDefinitions.test.js
new file mode 100644
index 0000000000..a527d6c15d
--- /dev/null
+++ b/server/services/musicVideo/castAndSetsDefinitions.test.js
@@ -0,0 +1,84 @@
+/**
+ * Character definitions — the sanitizing boundary between a provider answer (or
+ * a stored, possibly hand-edited record) and the inline SVG the sheet embeds.
+ * The security-relevant contract: nothing but validated numbers, hex colors and
+ * drawing commands ever reaches the markup.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { normalizeDefinitions, renderCharacterSvg, renderDefinitionsSection } from './castAndSetsDefinitions.js';
+
+const character = () => ({
+ id: 'Boat',
+ name: 'Paper boat',
+ renderer: 'svg',
+ palette: [{ name: 'Cream', hex: '#F5F0E6' }, { name: 'Ember', hex: '#ff5a1f' }],
+ parts: [
+ { id: 'hull', shape: 'polygon', points: [[40, 120], [160, 120], [130, 160], [70, 160]], fill: 'cream', stroke: 'ember', strokeWidth: 3 },
+ { id: 'sail', shape: 'path', d: 'M100 40 L100 120 L150 120 Z', fill: 'ember', pivot: [100, 120] },
+ { id: 'eye', shape: 'circle', x: 90, y: 135, r: 5, fill: '#000' },
+ ],
+ expressions: [{ name: 'Proud', overrides: { sail: { rotate: -10, scale: 1.1 }, eye: { hidden: true }, ghost: { rotate: 3 } } }],
+ poses: [{ name: 'Lean', overrides: { hull: { translate: [4, 0], rotate: 6 } } }],
+ motion: [{ name: 'Bob', target: 'hull', property: 'translateY', amplitude: 4, periodBeats: 1, easing: 'ease-in-out', trigger: 'beat' }],
+});
+
+describe('normalizeDefinitions', () => {
+ it('bounds and canonicalizes a character, dropping what does not validate', () => {
+ const raw = character();
+ raw.parts.push({ id: 'bad', shape: 'path', d: 'M0 0 <script>alert(1)</script>' }, { id: 'huge', shape: 'circle', x: 9999, y: -4, r: 'NaN' }, { shape: 'blob' });
+ const { characters } = normalizeDefinitions({ characters: [raw] });
+ const [c] = characters;
+ expect(c.id).toBe('boat');
+ expect(c.palette).toEqual([{ name: 'cream', hex: '#f5f0e6' }, { name: 'ember', hex: '#ff5a1f' }]);
+ expect(c.parts.map((p) => p.id)).toEqual(['hull', 'sail', 'eye']);
+ expect(c.parts[0]).toMatchObject({ fill: 'cream', stroke: 'ember' });
+ // An override naming no part is dropped; the rest survive.
+ expect(c.expressions[0].overrides).toEqual({ sail: { rotate: -10, scale: 1.1 }, eye: { hidden: true } });
+ expect(c.motion[0]).toMatchObject({ target: 'hull', property: 'translateY', trigger: 'beat' });
+ });
+
+ it('separates absent, unusable and intentionally empty', () => {
+ expect(normalizeDefinitions(undefined)).toBeNull();
+ expect(normalizeDefinitions('nope')).toBeNull();
+ expect(normalizeDefinitions({ characters: [{ name: 'No parts' }, 'x'] })).toBeNull();
+ expect(normalizeDefinitions({ characters: [] })).toEqual({ characters: [] });
+ });
+
+ it('is idempotent, so a stored record re-validates to itself', () => {
+ const once = normalizeDefinitions({ characters: [character()] });
+ expect(normalizeDefinitions(once)).toEqual(once);
+ });
+});
+
+describe('renderCharacterSvg / renderDefinitionsSection', () => {
+ it('draws the base pose and applies a named expression to the right part', () => {
+ const base = renderCharacterSvg(character());
+ const proud = renderCharacterSvg(character(), 'proud');
+ expect(base).toContain('<svg viewBox="0 0 200 200"');
+ expect(base).toContain('fill="#f5f0e6"');
+ expect(base).not.toContain('rotate(-10');
+ expect(proud).toContain('rotate(-10 100 120)');
+ // The hidden part is not drawn in that expression.
+ expect(base).toContain('<circle');
+ expect(proud).not.toContain('<circle');
+ });
+
+ it('never emits script, URLs or injected markup, even from a hand-edited record', () => {
+ const hostile = character();
+ hostile.name = '"><script>alert(1)</script>';
+ hostile.parts[1].d = 'M0 0 L1 1" onload="alert(1)';
+ hostile.parts[2].fill = 'url(http://example.com/x)';
+ hostile.motion[0].note = '<img src=x onerror=alert(1)>';
+ const html = renderDefinitionsSection({ characters: [hostile] });
+ expect(html).toContain('<svg');
+ // Free text is escaped; the unusable path and fill never reach the markup.
+ expect(html).toContain('&lt;img src=x onerror=alert(1)&gt;');
+ expect(html).not.toMatch(/<script|<img|onload|http|url\(/i);
+ });
+
+ it('renders nothing for a direction without definitions', () => {
+ expect(renderDefinitionsSection(undefined)).toBe('');
+ expect(renderDefinitionsSection({ characters: [] })).toBe('');
+ });
+});
diff --git a/server/services/musicVideo/castAndSetsDirection.js b/server/services/musicVideo/castAndSetsDirection.js
index 711333e35b..bc9f9dca59 100644
--- a/server/services/musicVideo/castAndSetsDirection.js
+++ b/server/services/musicVideo/castAndSetsDirection.js
@@ -18,7 +18,10 @@
* 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.
+ * stored on the direction so a revision never silently switches it. A procedural
+ * direction may also carry `definitions`: a bounded, validated code definition
+ * per reusable character (castAndSetsDefinitions.js) that the sheet previews and
+ * the code-authoring request reuses.
*
* 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:
@@ -27,9 +30,12 @@
*/
import { z } from 'zod';
+import { ServerError } from '../../lib/errorHandler.js';
import { extractJson } from '../../lib/jsonExtract.js';
import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
+import { musicVideoBriefTools as briefTools } from '../../lib/musicVideoMediumPlan.js';
import { trimTo } from '../../lib/textUtils.js';
+import { CAST_SETS_DEFINITION_LIMITS, normalizeDefinitions } from './castAndSetsDefinitions.js';
export const CAST_SETS_LIMITS = Object.freeze({
looks: { min: 1, max: 4 },
@@ -50,8 +56,6 @@ 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
@@ -170,6 +174,18 @@ const PROCEDURAL_OUTPUT_SHAPE = `{
"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>" }] },
+ "definitions": {
+ "characters": [{
+ "id": "<short-slug>",
+ "name": "<character name>",
+ "renderer": "svg | canvas2d | three",
+ "palette": [{ "name": "<color-name>", "hex": "#rrggbb" }],
+ "parts": [{ "id": "<part-slug>", "shape": "circle | ellipse | rect | polygon | path | line", "x": 100, "y": 100, "r": 40, "fill": "<palette color name or #hex>", "stroke": "<palette color name or #hex>", "strokeWidth": 2, "pivot": [100, 100] }],
+ "expressions": [{ "name": "<expression name>", "overrides": { "<part-slug>": { "translate": [0, 0], "rotate": 0, "scale": 1, "fill": "<palette color name or #hex>", "hidden": false } } }],
+ "poses": [{ "name": "<pose name>", "overrides": { "<part-slug>": { "rotate": 0 } } }],
+ "motion": [{ "name": "<motion name>", "target": "<part-slug or all>", "property": "rotate | scale | translateX | translateY | opacity", "amplitude": 4, "periodBeats": 1, "easing": "linear | ease-in-out | ease-out | bounce | step", "trigger": "idle | beat | downbeat | lyric | section" }]
+ }]
+ },
"moodRefs": [0, 1],
"questions": ["<a question for the director>"]
}`;
@@ -225,6 +241,7 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,
'- 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.',
+ `- definitions: one reusable code definition per recurring character (at most ${CAST_SETS_DEFINITION_LIMITS.characters}). Draw it in a 200×200 box (origin top-left, y down) from at most ${CAST_SETS_DEFINITION_LIMITS.parts} simple parts; fills and strokes name a palette entry or a #hex. Expressions and poses are per-part overrides of the base parts; motion rules say what moves, by how much, over how many beats. Keep the definition consistent with the prose above.`,
`- 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');
@@ -287,6 +304,16 @@ const worldSchema = z.object({
camera: text(500).optional(),
transitions: text(500).optional(),
}).passthrough();
+// Unusable definitions (not an object, or no character survives validation) count as
+// absent so the merge keeps the current ones; `{ characters: [] }` is a deliberate clear.
+const definitionsSchema = z.unknown().transform((value, ctx) => {
+ const normalized = normalizeDefinitions(value);
+ if (!normalized) {
+ ctx.addIssue({ code: 'custom', message: 'no usable character definitions' });
+ return z.NEVER;
+ }
+ return normalized;
+});
const lookSchema = z.object({ name: text(SHORT), description: text(TEXT), chapters: text(300).optional() }).passthrough();
const setSchema = z.object({
id: z.string().optional(),
@@ -313,6 +340,7 @@ const FIELD_PARSERS = {
interpretation: text(2000),
protagonist: protagonistSchema,
world: worldSchema,
+ definitions: definitionsSchema,
looks: z.array(lookSchema),
sets: z.array(setSchema),
songMap: z.array(songMapSchema),
@@ -449,8 +477,9 @@ export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moo
.map((e) => ({ name: e.name, description: e.description })),
};
const moodRefs = [...new Set(pick('moodRefs', []))].filter((i) => i < moodImageCount).slice(0, CAST_SETS_LIMITS.moodRefs.max);
+ const definitions = hasOwn(parsed, 'definitions') ? parsed.definitions : (base.definitions || { characters: [] });
const direction = {
- ...(procedural ? { medium: 'procedural', world } : {}),
+ ...(procedural ? { medium: 'procedural', world, definitions } : {}),
logline: pick('logline', ''),
interpretation: pick('interpretation', ''),
protagonist,
@@ -470,3 +499,59 @@ export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moo
].filter(Boolean);
return { direction, missing };
}
+
+// ---- director edits -----------------------------------------------------------
+
+// The procedural fields the director can edit directly, with the caps the
+// provider answer is held to.
+export const CAST_SETS_EDITABLE_PROTAGONIST = Object.freeze({ construction: TEXT, shapeLanguage: 500, materials: 500, palette: 300, movement: TEXT });
+export const CAST_SETS_EDITABLE_WORLD = Object.freeze({ layout: TEXT, depth: 500, lighting: 500, camera: 500, transitions: 500 });
+
+const pickText = (source, caps) => Object.fromEntries(
+ Object.entries(caps).filter(([key]) => typeof source?.[key] === 'string').map(([key, max]) => [key, source[key].trim().slice(0, max)]),
+);
+
+/**
+ * Apply the director's direct edits to a procedural direction. `edits` is
+ * `{ protagonist?, world?, sets? }`: a text field that is present replaces the
+ * current value (an empty string clears it), one that is absent keeps it;
+ * `protagonist.expressions` replaces the whole list; `sets` is
+ * `[{ id, imageRole }]`. The result goes through the same merge + normalize as
+ * a provider answer, so it can never be shaped differently from one. Returns
+ * `{ direction, changed }` (`changed` names the fields that actually changed, for
+ * the revision record); throws 409 for a photographic direction and 422 for an
+ * unknown set or an edit that would leave the direction unusable.
+ */
+export function applyCastAndSetsDirectionEdits(previous, edits, { sections = [] } = {}) {
+ if (previous?.medium !== 'procedural') {
+ throw new ServerError('Only a procedural direction has editable construction and world rules', { status: 409, code: 'CAST_SETS_NOT_PROCEDURAL' });
+ }
+ const parsed = {};
+ if (edits?.protagonist) {
+ const protagonist = pickText(edits.protagonist, CAST_SETS_EDITABLE_PROTAGONIST);
+ if (Array.isArray(edits.protagonist.expressions)) {
+ protagonist.expressions = edits.protagonist.expressions.map((x) => String(x).trim().slice(0, 300)).filter(Boolean);
+ }
+ parsed.protagonist = protagonist;
+ }
+ if (edits?.world) {
+ parsed.world = pickText(edits.world, CAST_SETS_EDITABLE_WORLD);
+ }
+ if (Array.isArray(edits?.sets) && edits.sets.length) {
+ const roles = new Map(edits.sets.map((s) => [s.id, s.imageRole]));
+ const unknown = [...roles.keys()].filter((id) => !(previous.sets || []).some((s) => s.id === id));
+ if (unknown.length) throw new ServerError(`Unknown set: ${unknown.join(', ')}`, { status: 422, code: 'CAST_SETS_UNKNOWN_SET' });
+ parsed.sets = previous.sets.map((s) => (roles.has(s.id) ? { ...s, imageRole: roles.get(s.id) } : s));
+ }
+ // The mood-board indices were validated against the board when it was directed.
+ const { direction, missing } = mergeCastAndSetsDirection(previous, parsed, { sections, moodImageCount: Number.POSITIVE_INFINITY, medium: 'procedural' });
+ if (missing.length) throw new ServerError(`That edit would leave the direction without: ${missing.join(', ')}`, { status: 422, code: 'CAST_SETS_EDIT_INVALID' });
+ const differs = (a, b) => JSON.stringify(a ?? '') !== JSON.stringify(b ?? '');
+ const changed = [
+ ...Object.keys(CAST_SETS_EDITABLE_PROTAGONIST).filter((key) => differs(previous.protagonist?.[key], direction.protagonist[key])),
+ ...(differs(previous.protagonist?.expressions, direction.protagonist.expressions) ? ['expressions'] : []),
+ ...Object.keys(CAST_SETS_EDITABLE_WORLD).filter((key) => differs(previous.world?.[key], direction.world[key])).map((key) => `world ${key}`),
+ ...direction.sets.filter((set) => differs(previous.sets.find((s) => s.id === set.id)?.imageRole, set.imageRole)).map((set) => `${set.name} image role`),
+ ];
+ return { direction: { ...direction, look: previous.look || '' }, changed };
+}
diff --git a/server/services/musicVideo/castAndSetsDirection.test.js b/server/services/musicVideo/castAndSetsDirection.test.js
index 69d18e3321..b375accdd0 100644
--- a/server/services/musicVideo/castAndSetsDirection.test.js
+++ b/server/services/musicVideo/castAndSetsDirection.test.js
@@ -7,6 +7,7 @@
import { describe, it, expect } from 'vitest';
import {
+ applyCastAndSetsDirectionEdits,
buildCastAndSetsPrompt,
castAndSetsAllowsImages,
castAndSetsMedium,
@@ -94,23 +95,23 @@ describe('Cast & Sets direction', () => {
});
});
+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: [],
+};
+
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');
@@ -163,3 +164,57 @@ describe('Cast & Sets procedural medium', () => {
expect(direction.sets[0]).not.toHaveProperty('imageRole');
});
});
+
+describe('Cast & Sets reusable definitions', () => {
+ const DEFINITIONS = { characters: [{
+ name: 'Boat', palette: [{ name: 'cream', hex: '#f5f0e6' }],
+ parts: [{ id: 'hull', shape: 'rect', x: 40, y: 100, width: 120, height: 40, fill: 'cream' }],
+ expressions: [{ name: 'proud', overrides: { hull: { rotate: -4 } } }],
+ }] };
+ const direct = (extra) => mergeCastAndSetsDirection(null, parseCastAndSetsResponse(JSON.stringify({ ...PROCEDURAL_ANSWER, ...extra })), { sections, medium: 'procedural' }).direction;
+
+ it('asks for definitions and keeps them through a revision (absent keeps, empty clears, unusable keeps)', () => {
+ expect(buildCastAndSetsPrompt({ ...project, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } })).toContain('"definitions"');
+ const direction = direct({ definitions: DEFINITIONS });
+ expect(direction.definitions.characters[0]).toMatchObject({ id: 'boat', renderer: 'svg' });
+
+ const revise = (answer) => mergeCastAndSetsDirection(direction, parseCastAndSetsResponse(JSON.stringify(answer)), { sections }).direction;
+ expect(revise({ protagonist: { movement: 'slower' } }).definitions).toEqual(direction.definitions);
+ expect(revise({ definitions: { characters: [{ name: 'Broken', parts: [{ shape: 'path', d: '<bad>' }] }] } }).definitions).toEqual(direction.definitions);
+ expect(revise({ definitions: { characters: [] } }).definitions).toEqual({ characters: [] });
+ });
+
+ it('gives a photographic direction no definitions', () => {
+ const { direction } = mergeCastAndSetsDirection(null, parseCastAndSetsResponse(JSON.stringify({ ...ANSWER, definitions: DEFINITIONS })), { sections });
+ expect(direction).not.toHaveProperty('definitions');
+ });
+});
+
+describe('Cast & Sets direct edits', () => {
+ const saved = mergeCastAndSetsDirection(null, parseCastAndSetsResponse(JSON.stringify(PROCEDURAL_ANSWER)), { sections, medium: 'procedural' }).direction;
+ const direction = { ...saved, look: 'flat fills', moodRefs: [0, 2] };
+
+ it('replaces present fields, keeps absent ones, clears on empty, and reports what changed', () => {
+ const edited = applyCastAndSetsDirectionEdits(direction, {
+ protagonist: { palette: '#112233, #445566', movement: '', expressions: ['calm: bow level'] },
+ world: { camera: 'locked off' },
+ sets: [{ id: direction.sets[0].id, imageRole: 'texture' }],
+ }, { sections });
+ expect(edited.direction.protagonist).toMatchObject({ palette: '#112233, #445566', movement: '', expressions: ['calm: bow level'], construction: direction.protagonist.construction });
+ expect(edited.direction.world).toMatchObject({ camera: 'locked off', layout: direction.world.layout });
+ expect(edited.direction.sets[0].imageRole).toBe('texture');
+ expect(edited.direction.sets.slice(1)).toEqual(direction.sets.slice(1));
+ // The mood-board picks and photographic look are not touched by an edit.
+ expect(edited.direction).toMatchObject({ look: 'flat fills', moodRefs: [0, 2], songMap: direction.songMap });
+ expect(edited.changed).toEqual(['palette', 'movement', 'expressions', 'world camera', `${direction.sets[0].name} image role`]);
+ // Re-saving the same values is no change at all.
+ expect(applyCastAndSetsDirectionEdits(direction, { world: { camera: direction.world.camera } }, { sections }).changed).toEqual([]);
+ });
+
+ it('refuses a photographic direction, an unknown set, and an edit that empties the protagonist', () => {
+ expect(() => applyCastAndSetsDirectionEdits({ ...direction, medium: undefined }, { world: { camera: 'x' } })).toThrow(/procedural/);
+ expect(() => applyCastAndSetsDirectionEdits(direction, { sets: [{ id: 'nowhere', imageRole: 'cutout' }] })).toThrow(/Unknown set/);
+ const bare = { ...direction, protagonist: { ...direction.protagonist, description: '' } };
+ expect(() => applyCastAndSetsDirectionEdits(bare, { protagonist: { construction: '' } })).toThrow(/protagonist/);
+ });
+});
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 1ea9862045..a49ba6006c 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -53,6 +53,7 @@ import {
startCastAndSetsOnProject,
} from './castAndSets.js';
import {
+ applyCastAndSetsDirectionEdits,
buildCastAndSetsPrompt,
castAndSetsAllowsImages,
castAndSetsMedium,
@@ -611,6 +612,37 @@ export async function regenerateCastAndSets(projectId, { notes = null, providerI
return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };
}
+/**
+ * Save the director's direct edits to a procedural direction (construction,
+ * palette, expressions, movement, world rules, per-set image role) through the
+ * revision path: the stage re-opens as a new revision, the edited direction is
+ * persisted in the same write, and only images whose prompt changed re-render
+ * before the sheet is re-assembled. No direction (text) provider call is made;
+ * a changed image prompt is the director's save acting on the image queue.
+ * Returns `{ project, stage }`.
+ */
+export async function editCastAndSetsDirection(projectId, edits) {
+ const project = await requireProject(projectId);
+ const sections = songSections(project);
+ let changed = [];
+ const out = await mutateProjectRecord(projectId, (current) => {
+ const stage = current.castAndSets;
+ if (!stage?.direction) throw new ServerError('There is no Cast & Sets direction to edit yet', { status: 409, code: 'CAST_SETS_NO_DIRECTION' });
+ assertCastAndSetsApprovable(current);
+ const edited = applyCastAndSetsDirectionEdits(stage.direction, edits, { sections });
+ if (!edited.changed.length) throw new ServerError('Nothing changed — edit a field first', { status: 422, code: 'CAST_SETS_NO_EDITS' });
+ changed = edited.changed;
+ const notesApplied = [{ id: null, target: 'direction', text: `Edited by the director: ${changed.join(', ')}` }];
+ const revised = reviseCastAndSetsOnProject(current, { processId: PROCESS_ID, notesApplied, redirect: false });
+ const next = { ...revised.project, castAndSets: { ...revised.stage, direction: edited.direction } };
+ return { project: next, stage: next.castAndSets };
+ });
+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} direction edited r${out.stage.revision} (${changed.length} field(s))`);
+ publish(projectId, out.project);
+ inBackground('The direction edit', projectId, () => writePlan(projectId));
+ return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };
+}
+
/** Resume an interrupted (restart) or failed stage in this process. */
export async function resumeCastAndSets(projectId, { providerId, model, effort } = {}) {
const out = await mutateProjectRecord(projectId, (current) => resumeCastAndSetsOnProject(current, { processId: PROCESS_ID }));
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index b9afcef348..21573fee98 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -532,4 +532,71 @@ describe('Cast & Sets procedural check-in', () => {
await runTo(project.id, 'review');
expect((await current(project.id)).castAndSets.direction.medium).toBe('procedural');
});
+
+ it('previews the reusable definitions on the sheet, saves the director\'s direction edits through a revision, and persists them', async () => {
+ const definitions = { characters: [{
+ id: 'boat', name: 'Paper boat', renderer: 'svg', palette: [{ name: 'cream', hex: '#f5f0e6' }],
+ parts: [{ id: 'hull', shape: 'rect', x: 40, y: 100, width: 120, height: 40, fill: 'cream' }],
+ expressions: [{ name: 'proud', overrides: { hull: { rotate: -4 } } }],
+ }] };
+ runPrompt.mockResolvedValue({ text: JSON.stringify({ ...PROCEDURAL, definitions }) });
+ const project = await seedProcedural(['image:codex', 'code:render']);
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ const reviewing = await current(project.id);
+ const sheet = () => readFileSync(join(ROOT(), (reviewing.devArtifacts.find((a) => a.id === reviewing.castAndSets.artifactId)).file), 'utf8');
+ expect(reviewing.castAndSets.direction.definitions.characters[0]).toMatchObject({ id: 'boat', parts: [{ id: 'hull', shape: 'rect' }] });
+ expect(sheet()).toContain('Reusable code definitions');
+ const landed = jobs.length;
+
+ // Edit palette, camera and a plate's role. No direction (text) call; only the plate whose prompt changed re-renders.
+ const edit = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({
+ protagonist: { palette: '#112233, #ddeeff', expressions: ['calm: bow level'] },
+ world: { camera: 'locked off, no push' },
+ sets: [{ id: 'river', imageRole: 'texture' }],
+ });
+ expect(edit.status).toBe(202);
+ expect(edit.body.stage.revision).toBe(2);
+ await until(async () => jobs.length > landed, 'the re-rendered plate');
+ await runTo(project.id, 'review');
+ expect(runPrompt).toHaveBeenCalledTimes(1);
+ expect(jobs.slice(landed).map(keyOf)).toEqual(['set:river']);
+
+ // The edit survives a reload and reaches the planner request and the sheet.
+ const after = await current(project.id);
+ expect(after.castAndSets.direction).toMatchObject({
+ protagonist: { palette: '#112233, #ddeeff', expressions: ['calm: bow level'], construction: 'three triangles hinged at the keel' },
+ world: { camera: 'locked off, no push', layout: 'a river through stacked streets' },
+ definitions,
+ });
+ expect(after.castAndSets.direction.sets.find((x) => x.id === 'river').imageRole).toBe('texture');
+ expect(after.castAndSets.notesApplied[0].text).toMatch(/^Edited by the director: palette, expressions, world camera, River image role/);
+ const { buildScenePlanPrompt } = await import('./planner.js');
+ const planPrompt = buildScenePlanPrompt(after, [{ startSec: 0, endSec: 8, sectionIndex: 0, shotIndex: 0, shotCount: 1, sectionLabel: 'Intro', lyricText: '', delivery: [] }]);
+ expect(planPrompt).toContain('locked off, no push');
+ expect(planPrompt).toContain('#112233, #ddeeff');
+
+ // Nothing changed / unknown set / not in review are refused, leaving the direction as saved.
+ const same = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({ world: { camera: 'locked off, no push' } });
+ expect(same.status).toBe(422);
+ const unknown = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({ sets: [{ id: 'nowhere', imageRole: 'cutout' }] });
+ expect(unknown.status).toBe(422);
+ const invalid = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({ sets: [{ id: 'river', imageRole: 'wallpaper' }] });
+ expect(invalid.status).toBe(400);
+ await service.approveCastAndSets(project.id);
+ const approved = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({ world: { camera: 'x' } });
+ expect(approved.status).toBe(409);
+ expect((await current(project.id)).castAndSets.direction.world.camera).toBe('locked off, no push');
+ expect(sheet()).toContain('Reusable code definitions');
+ });
+
+ it('refuses to edit a photographic direction', async () => {
+ runPrompt.mockResolvedValue({ text: JSON.stringify(DIRECTION) });
+ const project = await seed();
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ const res = await request(app).patch(`/api/music-video/${project.id}/cast-and-sets/direction`).send({ world: { camera: 'x' } });
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('CAST_SETS_NOT_PROCEDURAL');
+ });
});
diff --git a/server/services/musicVideo/castAndSetsSheet.js b/server/services/musicVideo/castAndSetsSheet.js
index 25f3b53346..2433eece72 100644
--- a/server/services/musicVideo/castAndSetsSheet.js
+++ b/server/services/musicVideo/castAndSetsSheet.js
@@ -15,6 +15,7 @@
*/
import { plannedTests } from './castAndSetsPlan.js';
+import { renderDefinitionsSection } from './castAndSetsDefinitions.js';
// One color per set (song-map bar + dots), in set order.
export const CAST_SETS_SET_COLORS = Object.freeze(['#b8d63a', '#2fae8f', '#8a5cff', '#e0342b', '#18c7d6', '#3d7bff', '#f0a13a', '#ff5a1f']);
@@ -72,6 +73,13 @@ figcaption{font-family:var(--mono);font-size:12px;color:var(--muted);padding-top
.set figcaption b{font-family:var(--body);font-size:17px;color:var(--fg);font-weight:600}
.set figcaption span{font-family:var(--body);font-size:14px;color:var(--muted)}
.set figcaption em{font-style:normal;color:var(--green);font-size:11px;letter-spacing:.08em;text-transform:uppercase}
+.def{border:1px solid var(--line);background:var(--panel);padding:16px;margin-top:18px}
+.def h3{font-family:var(--display);font-size:24px;margin:0 0 10px;font-weight:700}
+.def h3 span{font-family:var(--mono);font-size:12px;color:var(--muted);letter-spacing:.08em;margin-left:8px}
+.def-tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:12px}
+.def-tile svg{display:block;width:100%;height:auto;background:#0b0f0d;border:1px solid var(--line)}
+.swatches{display:flex;flex-wrap:wrap;gap:6px 16px;margin-top:12px;font-family:var(--mono);font-size:12px;color:var(--muted)}
+.swatch i{display:inline-block;width:12px;height:12px;margin-right:6px;vertical-align:-2px;border:1px solid var(--line)}
.bar{display:flex;height:44px;border:1px solid var(--line);margin-top:20px;overflow:hidden}
.seg{position:relative;border-right:1px solid var(--bg);min-width:0}
.seg span{position:absolute;left:4px;bottom:3px;font-family:var(--mono);font-size:10px;color:#0b0f0d;white-space:nowrap;overflow:hidden;max-width:calc(100% - 6px)}
@@ -190,6 +198,7 @@ ${d.interpretation ? `<p class="sub">${e(d.interpretation)}</p>` : ''}
${applied}
<section><h2><small>Protagonist</small>${e(p.name || 'Protagonist')}</h2>
${procedural ? `<dl class="facts wide">${facts}</dl></section>
+${renderDefinitionsSection(d.definitions)}
${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>
diff --git a/server/services/musicVideo/castAndSetsSheet.test.js b/server/services/musicVideo/castAndSetsSheet.test.js
index 90e5548dc0..fae73eb584 100644
--- a/server/services/musicVideo/castAndSetsSheet.test.js
+++ b/server/services/musicVideo/castAndSetsSheet.test.js
@@ -52,4 +52,27 @@ describe('Cast & Sets sheet', () => {
// The set with no image yet is a placeholder too.
expect(html.match(/data:image\/png;base64/g)).toHaveLength(7);
});
+
+ it('previews the reusable character definitions as inline SVG, still with no network or script', () => {
+ const procedural = {
+ ...direction, medium: 'procedural', looks: [], tests: [],
+ protagonist: { name: 'Boat', description: 'a paper boat', construction: 'three folds' },
+ definitions: { characters: [{
+ id: 'boat', name: 'Paper boat', renderer: 'svg', palette: [{ name: 'cream', hex: '#f5f0e6' }],
+ parts: [{ id: 'hull', shape: 'rect', x: 40, y: 100, width: 120, height: 40, fill: 'cream' }],
+ expressions: [{ name: 'proud', overrides: { hull: { rotate: -5 } } }], poses: [],
+ motion: [{ name: 'Bob', target: 'hull', property: 'translateY', amplitude: 4, periodBeats: 1, easing: 'ease-in-out', trigger: 'beat' }],
+ }] },
+ };
+ const html = renderCastAndSetsSheet({ title: 'Example Song', direction: procedural, sections });
+ expect(html).toContain('Reusable code definitions');
+ // Base pose + the named expression, each its own drawing; palette and motion listed.
+ expect(html.match(/<svg viewBox="0 0 200 200"/g)).toHaveLength(2);
+ expect(html).toContain('rotate(-5 100 120)');
+ expect(html).toContain('Bob');
+ expect(html).not.toMatch(/https?:\/\//);
+ expect(html).not.toMatch(/<(script|link|iframe|image|use)\b/i);
+ // A procedural direction without definitions shows no empty section.
+ expect(renderCastAndSetsSheet({ title: 'Example Song', direction: { ...procedural, definitions: { characters: [] } }, sections })).not.toContain('Character design');
+ });
});
diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.js
index 4eb8fb7698..0d5adb2999 100644
--- a/server/services/musicVideo/codeGeneration.js
+++ b/server/services/musicVideo/codeGeneration.js
@@ -11,8 +11,10 @@ import { ServerError } from '../../lib/errorHandler.js';
import { PATHS } from '../../lib/paths.js';
import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';
import { universeStyleLines } from '../../lib/styleSourcePrompt.js';
+import { musicVideoCodeDirectionContext } from '../../lib/musicVideoCreativeContext.js';
import { buildMusicVideoCodePrompt, extractCodeSections } from '../codeAnimation/prompt.js';
import { normalizeComposition } from './composition.js';
+import { approvedCastAndSetsDirection } from './castAndSets.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoLlmRouteLabel } from '../../lib/musicVideoAutomation.js';
import { effortArg, resolveMusicVideoLlm } from './llmRoute.js';
@@ -31,6 +33,9 @@ export async function styleLinesFor(project) {
}
}
+/** The approved procedural direction's definitions and rules, for a code-authoring request. */
+export const castAndSetsCodeContext = (project) => musicVideoCodeDirectionContext(approvedCastAndSetsDirection(project));
+
function acceptSources(parsed, ids) {
const wanted = new Set(ids);
const accepted = [];
@@ -109,6 +114,7 @@ export async function generateMusicVideoCode(projectId, { providerId, model, eff
palette,
song,
styleLines: await styleLinesFor(project),
+ directionContext: castAndSetsCodeContext(project),
});
const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });
const parsed = extractCodeSections(run.text);
@@ -136,6 +142,7 @@ export async function regenerateMusicVideoCodeSection(projectId, sectionId, { pr
song,
styleLines: await styleLinesFor(project),
onlySectionId: sectionId,
+ directionContext: castAndSetsCodeContext(project),
});
const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });
const sections = acceptSources(extractCodeSections(run.text), [sectionId]);
diff --git a/server/services/musicVideo/codeGeneration.test.js b/server/services/musicVideo/codeGeneration.test.js
index dddb902a83..f47aea49fd 100644
--- a/server/services/musicVideo/codeGeneration.test.js
+++ b/server/services/musicVideo/codeGeneration.test.js
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const fixtureSectionSource = (color) => `function render(ctx, env) {\n ctx.fillStyle = ${JSON.stringify(color)};\n ctx.fillRect(env.safe.x, env.safe.y, 12 + (env.frame % 3), 12);\n}`;
-const h = vi.hoisted(() => ({ project: null, calls: 0, response: '' }));
+const h = vi.hoisted(() => ({ project: null, calls: 0, response: '', prompts: [] }));
vi.mock('../promptRunner.js', () => ({
assertProvider: () => {},
@@ -9,8 +9,9 @@ vi.mock('../promptRunner.js', () => ({
provider: { id: providerId || 'stub-provider' },
selectedModel: model || 'fixture-model',
})),
- runPromptThroughProvider: vi.fn(async () => {
+ runPromptThroughProvider: vi.fn(async ({ prompt }) => {
h.calls += 1;
+ h.prompts.push(prompt);
return { text: h.response };
}),
}));
@@ -52,6 +53,7 @@ beforeEach(() => {
h.project = base();
h.calls = 0;
h.response = '';
+ h.prompts = [];
});
describe('music video code generation (#9076)', () => {
@@ -92,4 +94,49 @@ describe('music video code generation (#9076)', () => {
expect(stored.b).toBe(fixtureSectionSource('#222222'));
expect(h.calls).toBe(1);
});
+
+ describe('approved procedural Cast & Sets direction', () => {
+ const direction = () => ({
+ medium: 'procedural',
+ protagonist: { name: 'Boat', description: 'a folded paper boat', construction: 'three triangles hinged at the keel', palette: '#f5f0e6, #ff5a1f', movement: 'bobs on every beat' },
+ world: { layout: 'a river through stacked streets', camera: 'slow dolly with a beat-synced push', transitions: 'wipe through reflections' },
+ sets: [{ id: 'river', name: 'River', description: 'a neon river', lighting: 'magenta', imageRole: 'background' }],
+ definitions: { characters: [{
+ id: 'boat', name: 'Boat', renderer: 'svg', palette: [{ name: 'cream', hex: '#f5f0e6' }],
+ parts: [{ id: 'hull', shape: 'rect', x: 40, y: 100, width: 120, height: 40, fill: 'cream' }],
+ expressions: [{ name: 'proud', overrides: { hull: { rotate: -4 } } }], poses: [],
+ motion: [{ name: 'Bob', target: 'hull', property: 'translateY', amplitude: 4, periodBeats: 1, easing: 'ease-in-out', trigger: 'beat' }],
+ }] },
+ });
+ const response = () => JSON.stringify({ sections: [{ id: 'a', source: fixtureSectionSource('#555555') }, { id: 'b', source: fixtureSectionSource('#666666') }] });
+
+ it('sends the approved definitions and motion/camera rules with both the full and the one-section request', async () => {
+ h.project = { ...base(), castAndSets: { status: 'approved', direction: direction() } };
+ h.response = response();
+ await generateMusicVideoCode('mv-code', { providerId: 'stub-provider' });
+ await regenerateMusicVideoCodeSection('mv-code', 'a', { providerId: 'stub-provider' });
+ expect(h.prompts).toHaveLength(2);
+ for (const prompt of h.prompts) {
+ expect(prompt).toContain('APPROVED CAST & SETS DEFINITIONS AND RULES');
+ expect(prompt).toContain('camera: slow dolly with a beat-synced push');
+ expect(prompt).toContain('movement: bobs on every beat');
+ expect(prompt).toContain('"parts":[{"id":"hull","shape":"rect"');
+ expect(prompt).toContain('"motion":[{"name":"Bob"');
+ }
+ });
+
+ it('does not send an unapproved, skipped or photographic direction to the code author', async () => {
+ h.response = response();
+ for (const castAndSets of [
+ { status: 'review', direction: direction() },
+ { status: 'skipped', direction: direction() },
+ { status: 'approved', direction: { ...direction(), medium: undefined } },
+ ]) {
+ h.project = { ...base(), castAndSets };
+ await generateMusicVideoCode('mv-code', { providerId: 'stub-provider' });
+ }
+ expect(h.prompts).toHaveLength(3);
+ for (const prompt of h.prompts) expect(prompt).not.toContain('APPROVED CAST & SETS');
+ });
+ });
});
diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.js
index 9ae30581b3..51b4d63118 100644
--- a/server/services/musicVideo/documentGeneration.js
+++ b/server/services/musicVideo/documentGeneration.js
@@ -8,7 +8,7 @@ import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';
import { summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';
import { buildMixedMediaDocumentPrompt, extractCodeSections } from '../codeAnimation/prompt.js';
import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';
-import { runModel, styleLinesFor } from './codeGeneration.js';
+import { castAndSetsCodeContext, runModel, styleLinesFor } from './codeGeneration.js';
import { getProject } from './projects.js';
import { buildDocumentData, documentAspect, documentRenderClock, documentSongDuration, DOCUMENT_FRAME_SIZES, resolveSceneMedia } from './documentRender.js';
import { acceptGeneratedDocument, readDocumentFiles, stageGeneratedDocument } from './compositionDocument.js';
@@ -191,7 +191,7 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =
const prompt = buildMixedMediaDocumentPrompt({
title: project.name, song: { ...context.song, sections: context.song.sections.filter((section) => ids.includes(section.id)) }, palette: context.palette, treatment: project.treatment,
visualSpec: project.visualSpec, scenes: context.scenes, styleLines: sharedStyle.styleLines,
- onlySectionId: sectionId, sharedStyle,
+ onlySectionId: sectionId, sharedStyle, directionContext: castAndSetsCodeContext(project),
});
const directedPrompt = feedback ? `${prompt}\n\nReview findings for this section (retain the approved medium and selected assets; never invent a footage fallback):\n${feedback.slice(0, 8000)}` : prompt;
const run = await runModel({ providerId, model, effort, automation: project.automation, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });
diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.js
index d5f7ecf32c..bc4d4a8e70 100644
--- a/server/services/musicVideo/documentGeneration.test.js
+++ b/server/services/musicVideo/documentGeneration.test.js
@@ -218,3 +218,23 @@ it('checks production authorization before provider submission and again before
await expect(acceptMixedMediaDocument(id, staged.directory, { verifyCurrent: blocked })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });
expect((await projects.getProject(id)).composition.documentDraft.directory).toBe(staged.directory);
});
+
+it('hands the approved procedural definitions and rules to the document author, and nothing from an unapproved check-in', async () => {
+ const id = await fixture();
+ const castAndSets = (status) => ({ status, direction: {
+ medium: 'procedural',
+ protagonist: { name: 'Kite', description: 'a paper kite', movement: 'sways on the downbeat' },
+ world: { camera: 'locked wide, slow push' },
+ definitions: { characters: [{ id: 'kite', name: 'Kite', renderer: 'svg', palette: [], parts: [{ id: 'sail', shape: 'polygon', points: [[100, 20], [160, 100], [100, 180], [40, 100]], fill: '#ff7700' }], expressions: [], poses: [], motion: [] }] },
+ } });
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, castAndSets: castAndSets('review') } }));
+ await generateMixedMediaDocument(id);
+ expect(h.prompt).not.toContain('APPROVED CAST & SETS');
+
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, castAndSets: castAndSets('approved') } }));
+ await generateMixedMediaDocument(id);
+ expect(h.prompt).toContain('APPROVED CAST & SETS DEFINITIONS AND RULES');
+ expect(h.prompt).toContain('camera: locked wide, slow push');
+ expect(h.prompt).toContain('movement: sways on the downbeat');
+ expect(h.prompt).toContain('"shape":"polygon"');
+});
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index afc2d6bba0..4e386715a6 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -8,6 +8,7 @@ import { unlink } from 'fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';
import { asFableLoomRenderSettings } from '../../lib/fableLoomProduction.js';
+import { musicVideoBriefAllowsVideo } from '../../lib/musicVideoMediumPlan.js';
import { isFullDecode } from '../../lib/videoDraftDecoders.js';
import { isDefaultVideoStreamingMode } from '../../lib/videoStreamingMode.js';
import { isDefaultI2vReferenceMode } from '../../lib/videoReferenceModes.js';
@@ -215,6 +216,11 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
import('../musicVideo/projects.js'), import('../../lib/musicVideoActionContract.js'),
]);
const project = await getProject(body.musicVideo.projectId);
+ // A brief that names tools and no video tool never dispatches generated footage;
+ // an approved plan or sheet stays as saved until the director replans.
+ if (project && !musicVideoBriefAllowsVideo(project)) {
+ throw new ServerError('No video tool is selected in this project\'s brief, so generated footage is not dispatched. Add a video tool, or replan the project without generated video.', { status: 409, code: 'MUSIC_VIDEO_NO_VIDEO_TOOL' });
+ }
const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
assertShotActionContract(scene);
params.prompt = withShotActionPrompt(params.prompt, project, scene, { offsetSec: performance?.shotInstruction?.edit?.inSec || 0 });
diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.js
index c00a3dbb05..c7bd8a6115 100644
--- a/server/services/videoGen/submitJob.test.js
+++ b/server/services/videoGen/submitJob.test.js
@@ -264,6 +264,22 @@ describe('submitVideoGenJob', () => {
expect(mocks.assertRevisionOpen).not.toHaveBeenCalled();
});
+ it('refuses generated footage when the brief names tools and none makes video, and queues once a video tool is selected', async () => {
+ const prepared = falPrepared();
+ mocks.prepareVideoGenParams.mockResolvedValue(prepared);
+ mocks.getMusicVideoProject.mockResolvedValue({ id: 'mv-1', scenes: [], automation: { tools: ['image:codex', 'code:render'] }, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } });
+ await expect(submitVideoGenJob({ prompt: 'selected shot', backend: 'fal', musicVideo }, {})).rejects.toMatchObject({ status: 409, code: 'MUSIC_VIDEO_NO_VIDEO_TOOL' });
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
+ expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);
+
+ // A brief naming no tools restricts nothing; one naming a video tool dispatches.
+ for (const automation of [undefined, { tools: [] }, { tools: ['image:codex', 'video:fal'] }]) {
+ mocks.enqueueJob.mockReturnValue(queued);
+ mocks.getMusicVideoProject.mockResolvedValue({ id: 'mv-1', scenes: [{ sceneId: 'mvs-1' }], automation });
+ await expect(submitVideoGenJob({ prompt: 'selected shot', backend: 'fal', musicVideo }, {})).resolves.toMatchObject({ jobId: 'job-123' });
+ }
+ });
+
it('checks the current production policy after video preparation, before queueing', async () => {
const changed = Object.assign(new Error('The approved plan changed'), { status: 409, code: 'PRODUCTION_BASIS_CHANGED' });
const prepared = falPrepared();