Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(music-video): development artifacts and a Cast & Sets check-in stage in the autopilot (#9239)
[._.]/ff9699919b10
diff --git a/client/src/App.jsx b/client/src/App.jsxindex e191380205..ae99c7d911 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -563,6 +563,7 @@ export default function App() {convention. */}<Route path="music-video" element={<MusicVideo />} /><Route path="music-video/:projectId" element={<MusicVideo />} />+ <Route path="music-video/:projectId/dev/:artifactId" element={<MusicVideo />} />{/* 3D — a top-level Create page (moved out of the Media Gen tabs). Therecord id is the URL, per the ID-based deep-linking convention. */}<Route path="3d" element={<Media3D />} />diff --git a/client/src/components/musicVideo/AutomationBriefFields.jsx b/client/src/components/musicVideo/AutomationBriefFields.jsxindex b331fe2222..d2bc7e9bb6 100644--- a/client/src/components/musicVideo/AutomationBriefFields.jsx+++ b/client/src/components/musicVideo/AutomationBriefFields.jsx@@ -57,7 +57,21 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {className={inputClass}/></div>- <div className="max-w-[12rem]">+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),18rem))] gap-3">+ <div>+ <label htmlFor={`${idPrefix}-checkin`} className="block text-xs text-port-text-muted mb-1">Cast & Sets check-in</label>+ <select+ id={`${idPrefix}-checkin`}+ value={draft.castAndSetsCheckin || 'review'}+ onChange={(e) => onChange({ castAndSetsCheckin: e.target.value })}+ className={inputClass}+ >+ <option value="review">Stop for my review</option>+ <option value="auto">Auto-approve</option>+ </select>+ <p className="text-[11px] text-port-text-muted mt-1">Before planning, autopilot builds a cast & sets sheet for your feedback.</p>+ </div>+ <div><label htmlFor={`${idPrefix}-budget`} className="block text-xs text-port-text-muted mb-1">Budget cap (USD)</label><inputid={`${idPrefix}-budget`}@@ -71,6 +85,7 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {className={inputClass}/></div>+ </div></div>);}diff --git a/client/src/components/musicVideo/AutomationPanel.jsx b/client/src/components/musicVideo/AutomationPanel.jsxindex 2ab6b68c81..55aaf26cf1 100644--- a/client/src/components/musicVideo/AutomationPanel.jsx+++ b/client/src/components/musicVideo/AutomationPanel.jsx@@ -11,11 +11,12 @@ const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';/*** The project's automation brief — tools, guidance, budget — shown first on* the board, with a one-click kickoff (analyze the song, import the track's- * lyrics, separate vocals, align words, then plan every shot against the- * brief). `kickoffStep` names the step running now. Edits PATCH through- * `onSave`, which owns the error toast.+ * lyrics, separate vocals, align words, build the Cast & Sets check-in, then+ * plan every shot against the brief). `kickoffStep` names the step running+ * now; `checkin` is the check-in card shown under the brief. Edits PATCH+ * through `onSave`, which owns the error toast.*/-export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason }) {+export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason, checkin = null }) {const [draft, setDraft] = useState(null);const [saving, setSaving] = useState(false);const automation = project.automation || null;@@ -50,6 +51,8 @@ export default function AutomationPanel({ project, onSave, onKickoff, kickoffBus{automation.tools.length} tool{automation.tools.length === 1 ? '' : 's'}{' · '}{automation.budgetUsd != null ? `${formatUsd(automation.budgetUsd)} cap` : 'no budget cap'}+ {' · '}+ {automation.checkins?.castAndSets === 'auto' ? 'check-ins auto-approved' : 'stops for check-ins'}</span><div className="ml-auto flex flex-wrap items-center gap-2"><button type="button" onClick={() => setDraft(automationDraftFrom(automation))} className={actionClass}>Edit brief</button>@@ -57,7 +60,7 @@ export default function AutomationPanel({ project, onSave, onKickoff, kickoffBustype="button"onClick={onKickoff}disabled={kickoffBusy || !!kickoffBlockedReason}- title={kickoffBlockedReason || 'Analyze the song, import its lyrics, separate and align the vocal, then plan every shot against the brief'}+ title={kickoffBlockedReason || 'Analyze the song, import its lyrics, separate and align the vocal, build the Cast & Sets check-in, then plan every shot against the brief'}className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"><Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}@@ -77,6 +80,7 @@ export default function AutomationPanel({ project, onSave, onKickoff, kickoffBus</p>{kickoffStep && <p className="text-xs text-port-accent" role="status">{kickoffStep}</p>}{kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}+ {checkin}</>);} else {diff --git a/client/src/components/musicVideo/CastAndSetsCheckin.jsx b/client/src/components/musicVideo/CastAndSetsCheckin.jsxnew file mode 100644index 0000000000..d43b44c8fd--- /dev/null+++ b/client/src/components/musicVideo/CastAndSetsCheckin.jsx@@ -0,0 +1,80 @@+import { CheckCircle2, Eye, Play, RotateCcw, SkipForward, Users } from 'lucide-react';+import Pill from '../ui/Pill.jsx';++const WORKING = new Set(['directing', 'imaging', 'assembling']);+const buttonClass = 'flex items-center gap-1 rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';++function progress(stage) {+ const images = Object.values(stage.images || {});+ const keys = Object.keys(stage.plan || {});+ const done = images.filter((img) => img.status === 'done').length;+ return keys.length ? `${done} of ${keys.length} reference images` : '';+}++function statusLine(stage) {+ if (stage.interrupted) return 'Interrupted by a restart — resume to continue.';+ switch (stage.status) {+ case 'directing': return 'Reading the song and writing the creative direction…';+ case 'imaging': return `Rendering the cast and sets: ${progress(stage)}…`;+ case 'assembling': return 'Assembling the check-in sheet…';+ case 'review': return 'Waiting for your check-in.';+ case 'approved': return 'Approved — the references now condition the storyboard frames.';+ case 'skipped': return 'Skipped — the autopilot plans without it.';+ case 'failed': return `Stopped: ${stage.stopReason || stage.error || 'unknown error'}`;+ default: return '';+ }+}++/**+ * 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).+ */+export default function CastAndSetsCheckin({ project, busy, onOpenSheet, onApprove, onRegenerate, onResume, onSkip }) {+ const stage = project.castAndSets;+ if (!stage) return null;+ const working = WORKING.has(stage.status) && !stage.interrupted;+ const sheet = stage.artifactId ? (project.devArtifacts || []).find((a) => a.id === stage.artifactId && !a.deleted) : null;+ const openNotes = (sheet?.notes || []).filter((n) => !n.resolvedAt).length;+ const tone = stage.status === 'review' ? 'warning' : stage.status === 'approved' ? 'success' : stage.status === 'failed' ? 'error' : 'muted';+ return (+ <div className={`rounded border p-2 space-y-2 ${stage.status === 'review' ? 'border-port-warning/60' : 'border-port-border'}`} aria-label="Cast & Sets check-in">+ <div className="flex flex-wrap items-center gap-2">+ <Users size={14} className="text-port-accent shrink-0" aria-hidden="true" />+ <span className="text-sm font-medium">Cast & Sets check-in</span>+ <Pill size="xs" tone={tone}>{stage.interrupted ? 'interrupted' : stage.status}</Pill>+ {stage.revision > 1 && <span className="text-[11px] text-port-text-muted">revision {stage.revision}</span>}+ </div>+ <p className={`text-xs ${stage.status === 'review' ? 'text-port-warning' : 'text-port-text-muted'}`} role="status">{statusLine(stage)}</p>+ <div className="flex flex-wrap gap-2">+ {sheet && (+ <button type="button" onClick={() => onOpenSheet(sheet.id)} className={`${buttonClass} border border-port-border`}>+ <Eye size={14} aria-hidden="true" /> Open sheet{openNotes ? ` (${openNotes} note${openNotes === 1 ? '' : 's'})` : ''}+ </button>+ )}+ {stage.status === 'review' && (+ <>+ <button type="button" disabled={busy || !openNotes} onClick={onRegenerate} title={openNotes ? 'Re-render what your notes touch' : 'Add a note on the sheet first'}+ className={`${buttonClass} border border-port-border`}>+ <RotateCcw size={14} aria-hidden="true" /> Regenerate with notes+ </button>+ <button type="button" disabled={busy} onClick={onApprove} className={`${buttonClass} bg-port-accent text-white`}>+ <CheckCircle2 size={14} aria-hidden="true" /> Approve & continue+ </button>+ </>+ )}+ {(stage.interrupted || stage.status === 'failed') && (+ <button type="button" disabled={busy} onClick={onResume} className={`${buttonClass} border border-port-border`}>+ <Play size={14} aria-hidden="true" /> Resume+ </button>+ )}+ {!working && !['approved', 'skipped'].includes(stage.status) && (+ <button type="button" disabled={busy} onClick={onSkip} className={`${buttonClass} text-port-text-muted`}>+ <SkipForward size={14} aria-hidden="true" /> Skip check-in+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/musicVideo/DevArtifactDrawer.jsx b/client/src/components/musicVideo/DevArtifactDrawer.jsxnew file mode 100644index 0000000000..4ceda895fd--- /dev/null+++ b/client/src/components/musicVideo/DevArtifactDrawer.jsx@@ -0,0 +1,211 @@+import { useState } from 'react';+import { CheckCircle2, RotateCcw, Trash2, ExternalLink, MessageSquarePlus } from 'lucide-react';+import Drawer from '../Drawer.jsx';+import Pill from '../ui/Pill.jsx';+import { musicVideoDevArtifactFileUrl } from '../../services/apiMusicVideo.js';+import { timeAgo } from '../../utils/formatters.js';+import { DEV_ARTIFACT_KIND_LABELS, DEV_ARTIFACT_STATUS } from './DevArtifactsPanel.jsx';++const buttonClass = 'flex items-center gap-1 rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';++/** What a Cast & Sets note can point at: the sheet's images, or the direction as a whole. */+function castAndSetsTargets(stage) {+ const direction = stage?.direction || {};+ return [+ { id: '', label: 'General / direction' },+ { id: 'character', label: 'Character sheet' },+ { id: 'expressions', label: 'Expression sheet' },+ { id: 'looks', label: 'Looks' },+ ...(direction.sets || []).map((s) => ({ id: `set:${s.id}`, label: `Set: ${s.name}` })),+ ...Object.values(stage?.plan || {}).filter((p) => p.kind === 'test').map((p) => ({ id: p.key, label: `In-set test: ${p.label}` })),+ ];+}++function Viewer({ projectId, artifact, version }) {+ const entry = (artifact.versions || []).find((v) => v.version === version) || artifact;+ const url = musicVideoDevArtifactFileUrl(projectId, artifact.id, version === artifact.version ? null : version);+ const title = `${artifact.title} v${entry.version || version}`;+ if (entry.mimeType?.startsWith('image/')) return <img src={url} alt={title} className="w-full h-auto rounded border border-port-border" />;+ if (entry.mimeType?.startsWith('video/')) return <video src={url} controls className="w-full rounded border border-port-border" aria-label={title} />;+ // HTML and Markdown: an opaque-origin frame (no allow-same-origin), so a+ // sheet's own script can run but can never reach PortOS. The server's CSP+ // enforces the same sandbox and blocks every network fetch.+ return (+ <iframe+ key={url}+ src={url}+ title={title}+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ className="w-full h-[60vh] lg:h-[calc(100vh-9rem)] rounded border border-port-border bg-white"+ />+ );+}++/**+ * One development artifact, full width: the file (sandboxed), its version+ * history, notes and review actions. For the sheet the Cast & Sets check-in is+ * waiting on, the review actions are the stage's own: "Regenerate with notes"+ * and "Approve & continue". Open state and the viewed version live in the URL+ * (`/music-video/:projectId/dev/:artifactId?v=N`).+ */+export default function DevArtifactDrawer({+ open, onClose, project, artifact, version, onVersionChange, ops, busy, castAndSets,+}) {+ const [noteText, setNoteText] = useState('');+ const [noteTarget, setNoteTarget] = useState('');+ const [confirmDelete, setConfirmDelete] = useState(false);+ if (!open) return null;+ if (!artifact) {+ return (+ <Drawer open onClose={onClose} title="Development file" subtitle={project?.name} size="sm" closeLabel="Close development file">+ <p className="text-sm text-port-text-muted">This file was not found — it may have been deleted.</p>+ </Drawer>+ );+ }+ const stage = project?.castAndSets || null;+ const isStageSheet = stage?.artifactId === artifact.id;+ const stageWorking = isStageSheet && ['directing', 'imaging', 'assembling'].includes(stage.status);+ const shown = (artifact.versions || []).some((v) => v.version === version) ? version : artifact.version;+ const openNotes = (artifact.notes || []).filter((n) => !n.resolvedAt);+ const status = DEV_ARTIFACT_STATUS[artifact.status] || DEV_ARTIFACT_STATUS.pending;+ const targets = isStageSheet ? castAndSetsTargets(stage) : null;+ const idPrefix = `mv-dev-${artifact.id}`;++ const addNote = () => {+ const text = noteText.trim();+ if (!text) return;+ ops.addNote(artifact.id, { text, ...(noteTarget ? { target: noteTarget } : {}) })+ .then((res) => { if (res) setNoteText(''); });+ };++ return (+ <Drawer open onClose={onClose} title={artifact.title} subtitle={`${DEV_ARTIFACT_KIND_LABELS[artifact.kind] || artifact.kind} · ${project?.name || ''}`}+ widthClass="sm:w-[96vw] 2xl:w-[1600px]" closeLabel="Close development file" closeOnEsc={!noteText}>+ <div className="flex flex-col lg:flex-row gap-4 min-w-0">+ <div className="flex-1 min-w-0 space-y-2">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <Pill size="xs" tone={status.tone}>{status.label}</Pill>+ <label htmlFor={`${idPrefix}-version`} className="text-port-text-muted">Version</label>+ <select id={`${idPrefix}-version`} value={shown} onChange={(e) => onVersionChange(Number(e.target.value))}+ className="bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ {[...(artifact.versions || [])].reverse().map((v) => (+ <option key={v.version} value={v.version}>v{v.version}{v.version === artifact.version ? ' (current)' : ''} · {timeAgo(v.createdAt)}</option>+ ))}+ </select>+ <a href={musicVideoDevArtifactFileUrl(project.id, artifact.id, shown === artifact.version ? null : shown)} target="_blank" rel="noreferrer noopener"+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0">+ <ExternalLink size={12} aria-hidden="true" /> Open in a tab+ </a>+ </div>+ <Viewer projectId={project.id} artifact={artifact} version={shown} />+ </div>++ <aside className="lg:w-80 shrink-0 space-y-3 min-w-0" aria-label="Review">+ {isStageSheet && (+ <p className="text-xs text-port-text-muted" role="status">+ {stage.status === 'review' && 'The autopilot is waiting for your check-in.'}+ {stageWorking && 'Regenerating — the new version appears here when it is ready.'}+ {stage.status === 'approved' && 'Approved — these references condition the storyboard frames.'}+ {stage.status === 'failed' && `The check-in stopped: ${stage.stopReason || 'unknown error'}`}+ </p>+ )}+ <div className="flex flex-wrap gap-2">+ {isStageSheet ? (+ <>+ <button type="button" disabled={busy || stageWorking || openNotes.length === 0} onClick={() => castAndSets.regenerate()}+ title={openNotes.length ? 'Re-render only what your open notes touch, as a new version' : 'Add a note first'}+ className={`${buttonClass} border border-port-border`}>+ <RotateCcw size={14} aria-hidden="true" /> Regenerate with notes+ </button>+ {stage.status === 'review' && (+ <button type="button" disabled={busy} onClick={() => castAndSets.approveAndContinue()} className={`${buttonClass} bg-port-accent text-white`}>+ <CheckCircle2 size={14} aria-hidden="true" /> Approve & continue+ </button>+ )}+ </>+ ) : (+ <>+ <button type="button" disabled={busy || artifact.status === 'approved'} onClick={() => ops.review(artifact.id, { status: 'approved' })}+ className={`${buttonClass} bg-port-accent text-white`}>+ <CheckCircle2 size={14} aria-hidden="true" /> Approve+ </button>+ <button type="button" disabled={busy}+ onClick={() => ops.review(artifact.id, { status: 'changes-requested', ...(noteText.trim() ? { note: noteText.trim() } : {}) }).then((res) => { if (res) setNoteText(''); })}+ className={`${buttonClass} border border-port-border`}>+ Request changes+ </button>+ </>+ )}+ </div>++ <div className="space-y-1.5">+ <label htmlFor={`${idPrefix}-note`} className="block text-xs text-port-text-muted">Note</label>+ {targets && (+ <>+ <label htmlFor={`${idPrefix}-target`} className="sr-only">Note is about</label>+ <select id={`${idPrefix}-target`} value={noteTarget} onChange={(e) => setNoteTarget(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ {targets.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}+ </select>+ </>+ )}+ <textarea id={`${idPrefix}-note`} rows={3} maxLength={2000} value={noteText} onChange={(e) => setNoteText(e.target.value)}+ placeholder={targets ? 'What should change? e.g. a different jacket, a wider shot of the set' : 'What should change?'}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm" />+ <button type="button" disabled={busy || !noteText.trim()} onClick={addNote} className={`${buttonClass} border border-port-border`}>+ <MessageSquarePlus size={14} aria-hidden="true" /> Add note+ </button>+ </div>++ <div>+ <h3 className="text-xs uppercase tracking-wide text-port-text-muted mb-1">Notes</h3>+ {(artifact.notes || []).length === 0 && <p className="text-xs text-port-text-muted">No notes yet.</p>}+ <ul className="space-y-1.5">+ {[...(artifact.notes || [])].reverse().map((note) => (+ <li key={note.id} className={`text-xs rounded border border-port-border p-2 ${note.resolvedAt ? 'opacity-60' : ''}`}>+ <div className="flex flex-wrap items-center gap-1.5">+ {note.target && <Pill size="xs" tone="accent">{note.target}</Pill>}+ <span className="text-port-text-muted">v{note.version} · {timeAgo(note.createdAt)}</span>+ <input id={`${idPrefix}-resolved-${note.id}`} type="checkbox" className="ml-auto" checked={!!note.resolvedAt} disabled={busy}+ onChange={(e) => ops.resolveNote(artifact.id, note.id, e.target.checked)} />+ <label htmlFor={`${idPrefix}-resolved-${note.id}`} className="min-h-[44px] sm:min-h-0 flex items-center">Resolved</label>+ </div>+ <p className="mt-1 break-words">{note.text}</p>+ </li>+ ))}+ </ul>+ </div>++ <div>+ <h3 className="text-xs uppercase tracking-wide text-port-text-muted mb-1">Versions</h3>+ <ol className="space-y-1 text-xs">+ {[...(artifact.versions || [])].reverse().map((v) => (+ <li key={v.version}>+ <button type="button" onClick={() => onVersionChange(v.version)}+ className={`min-h-[44px] sm:min-h-0 ${v.version === shown ? 'text-port-accent' : 'text-port-text'}`}>+ v{v.version} · {v.source === 'cast-and-sets' ? 'generated' : v.source} · {timeAgo(v.createdAt)}+ </button>+ </li>+ ))}+ </ol>+ </div>++ <div className="pt-2 border-t border-port-border">+ {confirmDelete ? (+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span>Remove this file from the project?</span>+ <button type="button" disabled={busy} onClick={() => ops.remove(artifact.id).then((res) => { if (res) onClose(); })} className="text-port-error min-h-[44px] sm:min-h-0 px-1">Remove</button>+ <button type="button" onClick={() => setConfirmDelete(false)} className="min-h-[44px] sm:min-h-0 px-1">Cancel</button>+ </div>+ ) : (+ <button type="button" onClick={() => setConfirmDelete(true)} disabled={busy} className="flex items-center gap-1 text-xs text-port-error min-h-[44px] sm:min-h-0">+ <Trash2 size={12} aria-hidden="true" /> Remove+ </button>+ )}+ </div>+ </aside>+ </div>+ </Drawer>+ );+}diff --git a/client/src/components/musicVideo/DevArtifactsPanel.jsx b/client/src/components/musicVideo/DevArtifactsPanel.jsxnew file mode 100644index 0000000000..06123d1a8c--- /dev/null+++ b/client/src/components/musicVideo/DevArtifactsPanel.jsx@@ -0,0 +1,83 @@+import { useState } from 'react';+import { FileText, Film, Image as ImageIcon, LayoutGrid, Users, Upload, FolderOpen } from 'lucide-react';+import Pill from '../ui/Pill.jsx';+import FilePickerButton from '../ui/FilePickerButton.jsx';+import { timeAgo } from '../../utils/formatters.js';++export const DEV_ARTIFACT_KIND_LABELS = {+ 'cast-sets': 'Cast & Sets',+ animatic: 'Animatic',+ treatment: 'Treatment',+ storyboard: 'Storyboard',+ other: 'Other',+};+const KIND_ICONS = { 'cast-sets': Users, animatic: Film, treatment: FileText, storyboard: LayoutGrid, other: ImageIcon };+export const DEV_ARTIFACT_STATUS = {+ pending: { label: 'Pending review', tone: 'warning' },+ approved: { label: 'Approved', tone: 'success' },+ 'changes-requested': { label: 'Changes requested', tone: 'error' },+};+const ACCEPT = '.html,.htm,.md,.mp4,.png,.jpg,.jpeg';++/**+ * The project's development files ("ingredients") — the Cast & Sets sheet,+ * animatics, treatments, storyboards — with their review status. Opening one+ * navigates to its deep link (`/music-video/:projectId/dev/:artifactId`),+ * which shows it in the viewer drawer.+ */+export default function DevArtifactsPanel({ project, busy, onOpen, onUpload }) {+ const artifacts = (project.devArtifacts || [])+ .filter((a) => !a.deleted)+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));+ const [kind, setKind] = useState('other');+ const idPrefix = `mv-dev-${project.id}`;++ const upload = (e) => {+ const file = e.target.files?.[0];+ if (!file) return undefined;+ return onUpload(file, { kind, title: file.name.replace(/\.[^.]+$/, '') });+ };++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-2 min-w-0" aria-labelledby={`${idPrefix}-title`}>+ <div className="flex flex-wrap items-center gap-2">+ <FolderOpen size={16} className="text-port-accent shrink-0" aria-hidden="true" />+ <h3 id={`${idPrefix}-title`} className="text-sm font-medium">Development</h3>+ <span className="text-xs text-port-text-muted">{artifacts.length ? `${artifacts.length} file${artifacts.length === 1 ? '' : 's'}` : 'Check-in sheets, animatics and other working files'}</span>+ <div className="ml-auto flex flex-wrap items-center gap-2">+ <label htmlFor={`${idPrefix}-kind`} className="sr-only">Kind of file to import</label>+ <select id={`${idPrefix}-kind`} value={kind} onChange={(e) => setKind(e.target.value)} disabled={busy}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ {Object.entries(DEV_ARTIFACT_KIND_LABELS).map(([id, label]) => <option key={id} value={id}>{label}</option>)}+ </select>+ <FilePickerButton accept={ACCEPT} onChange={upload} disabled={busy} ariaLabel="Import development file"+ className="flex items-center gap-1 text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1 cursor-pointer">+ <Upload size={14} aria-hidden="true" /> Import+ </FilePickerButton>+ </div>+ </div>+ {artifacts.length > 0 && (+ <ul className="divide-y divide-port-border">+ {artifacts.map((artifact) => {+ const Icon = KIND_ICONS[artifact.kind] || ImageIcon;+ const status = DEV_ARTIFACT_STATUS[artifact.status] || DEV_ARTIFACT_STATUS.pending;+ const open = (artifact.notes || []).filter((n) => !n.resolvedAt).length;+ return (+ <li key={artifact.id}>+ <button type="button" onClick={() => onOpen(artifact.id)}+ className="w-full flex flex-wrap items-center gap-2 py-2 text-left min-h-[44px] hover:bg-port-bg/60 rounded px-1">+ <Icon size={15} className="text-port-text-muted shrink-0" aria-hidden="true" />+ <span className="text-sm min-w-0 flex-1 truncate">{artifact.title}</span>+ <span className="text-[11px] text-port-text-muted">{DEV_ARTIFACT_KIND_LABELS[artifact.kind] || artifact.kind} · v{artifact.version}</span>+ {open > 0 && <Pill size="xs" tone="accent">{open} open note{open === 1 ? '' : 's'}</Pill>}+ <Pill size="xs" tone={status.tone}>{status.label}</Pill>+ <span className="text-[11px] text-port-text-muted hidden sm:inline">{timeAgo(artifact.updatedAt)}</span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ );+}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 416ee50c57..0b5e44d746 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -248,7 +248,9 @@ grep -i "what you want to do" client/src/hooks/README.md| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |-| `useMusicVideoKickoff` | The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans. Returns `{ step, stepLabel, running, run(project) }`. | The Music Video "Analyze & plan" button. |+| `useMusicVideoKickoff` | The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → Cast & Sets check-in → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans; the check-in gates the plan (a sheet waiting for review ends the run until the director approves). Returns `{ step, stepLabel, running, run(project) }`. | The Music Video "Analyze & plan" button. |+| `useMusicVideoCastAndSets` | The Cast & Sets check-in before the plan: applies the project pushed on `music-video:cast-and-sets` / `music-video:dev-artifact` and exposes start / regenerate(notes?) / resume / approve / skip, plus `runToCheckpoint(project)` (start if absent, resolve at review/approved/skipped/failed) for the kickoff. | The Music Video autopilot card and sheet viewer. |+| `useMusicVideoDevArtifacts` | A project's development files ("ingredients"): import a file or a new version, add/resolve notes, approve / request changes, remove; applies the returned project. Returns `{ busy, upload, addNote, resolveNote, review, remove }`. | The Music Video Development section and viewer drawer. || `useMusicVideoVocalSeparation` | "Separate vocals" (demucs) as a `useSseJobSlot`: `start(projectId)` for the button, `run(projectId)` as a promise resolving with the project carrying its new stem (or null on failure/cancel), `stageLabel` for install/separation progress, `onSeparated(projectId, project)` on success. | The Music Video vocal-stem control and the autopilot kickoff. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `useMusicVideoProduction` | Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on `music-video:production` and toasts terminal outcomes. Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`. | The Music Video production panel. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 5ba43290af..216775ed18 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -61,6 +61,8 @@ export { default as useMediaJobProgress } from './useMediaJobProgress.js';export * from './useMediaJobSse.js';export { default as useSceneRenderLifecycle } from './useSceneRenderLifecycle.js';export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.js';+export { default as useMusicVideoCastAndSets } from './useMusicVideoCastAndSets.js';+export { default as useMusicVideoDevArtifacts } from './useMusicVideoDevArtifacts.js';export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';diff --git a/client/src/hooks/useMusicVideoCastAndSets.js b/client/src/hooks/useMusicVideoCastAndSets.jsnew file mode 100644index 0000000000..fd5ef60be7--- /dev/null+++ b/client/src/hooks/useMusicVideoCastAndSets.js@@ -0,0 +1,104 @@+import { useEffect, useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import socket from '../services/socket';+import {+ startMusicVideoCastAndSets,+ regenerateMusicVideoCastAndSets,+ resumeMusicVideoCastAndSets,+ approveMusicVideoCastAndSets,+ skipMusicVideoCastAndSets,+} from '../services/apiMusicVideo.js';++// Where a stage stops needing the server: the autopilot continues past an+// approved or skipped one, and waits for the director at `review` or `failed`.+const CHECKPOINTS = new Set(['review', 'approved', 'skipped', 'failed']);++/**+ * The Cast & Sets check-in (runs before the shot plan). The server does the+ * work — direction, reference images, the sheet — and pushes every step over+ * `music-video:cast-and-sets` (and artifact edits over+ * `music-video:dev-artifact`); this hook applies the project it pushes (no+ * polling) and exposes the director's actions.+ *+ * `runToCheckpoint(project)` is the autopilot kickoff's step: it starts the+ * check-in when there is none and resolves with the project once the stage+ * reaches a checkpoint (`review`, `approved`, `skipped`, `failed`), or null+ * when it could not start.+ *+ * Returns `{ busy, start, regenerate, resume, approve, skip, runToCheckpoint }`.+ */+export default function useMusicVideoCastAndSets({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [busy, setBusy] = useState(false);+ const replaceRef = useRef(replaceProject);+ const waiter = useRef(null);+ useEffect(() => {+ replaceRef.current = replaceProject;+ });++ useEffect(() => {+ if (!projectId) return undefined;+ const onStage = (data) => {+ if (data?.projectId !== projectId || !data.project) return;+ replaceRef.current?.(data.project);+ const w = waiter.current;+ if (w && w.projectId === projectId && CHECKPOINTS.has(data.project.castAndSets?.status)) {+ waiter.current = null;+ w.resolve(data.project);+ }+ };+ const onArtifact = (data) => {+ if (data?.projectId === projectId && data.project) replaceRef.current?.(data.project);+ };+ socket.on('music-video:cast-and-sets', onStage);+ socket.on('music-video:dev-artifact', onArtifact);+ return () => {+ socket.off('music-video:cast-and-sets', onStage);+ socket.off('music-video:dev-artifact', onArtifact);+ // A kickoff waiting on this project ends rather than hanging.+ if (waiter.current?.projectId === projectId) {+ waiter.current.resolve(null);+ waiter.current = null;+ }+ };+ }, [projectId]);++ const call = (request, success) => {+ setBusy(true);+ return request()+ .then((res) => {+ if (res?.project) replaceRef.current?.(res.project);+ if (success) toast.success(success);+ return res;+ })+ .catch((err) => { toast.error(err?.message || 'Cast & Sets request failed'); return null; })+ .finally(() => setBusy(false));+ };++ const start = () => call(() => startMusicVideoCastAndSets(projectId, {}, { silent: true }));+ const regenerate = (notes) => call(() => regenerateMusicVideoCastAndSets(projectId, notes ? { notes } : {}, { silent: true }), 'Regenerating with your notes');+ 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');++ const runToCheckpoint = (target) => {+ if (!target?.id) return Promise.resolve(null);+ const status = target.castAndSets?.status;+ if (CHECKPOINTS.has(status)) return Promise.resolve(target);+ const reached = new Promise((resolve) => { waiter.current = { projectId: target.id, resolve }; });+ // A stage already underway just needs watching; otherwise start one.+ if (status) return reached;+ return startMusicVideoCastAndSets(target.id, {}, { silent: true })+ .then((res) => {+ if (res?.project) replaceRef.current?.(res.project);+ return reached;+ })+ .catch((err) => {+ waiter.current = null;+ toast.error(err?.message || 'Could not start the Cast & Sets check-in');+ return null;+ });+ };++ return { busy, start, regenerate, resume, approve, skip, runToCheckpoint };+}diff --git a/client/src/hooks/useMusicVideoDevArtifacts.js b/client/src/hooks/useMusicVideoDevArtifacts.jsnew file mode 100644index 0000000000..dec06bf498--- /dev/null+++ b/client/src/hooks/useMusicVideoDevArtifacts.js@@ -0,0 +1,46 @@+import { useState } from 'react';+import toast from '../components/ui/Toast';+import {+ uploadMusicVideoDevArtifact,+ addMusicVideoDevArtifactNote,+ resolveMusicVideoDevArtifactNote,+ reviewMusicVideoDevArtifact,+ deleteMusicVideoDevArtifact,+} from '../services/apiMusicVideo.js';++/**+ * A project's development artifacts ("ingredients"): import a file (or a new+ * version of one), notes, review and delete. The list itself is the project's+ * `devArtifacts` field, so every action applies the project the server returns+ * (the socket event covers other tabs).+ *+ * Returns `{ busy, upload(file, fields), addNote(artifactId, body),+ * resolveNote(artifactId, noteId, resolved), review(artifactId, body), remove(artifactId) }`;+ * each resolves with the server response, or null after toasting a failure.+ */+export default function useMusicVideoDevArtifacts({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [busy, setBusy] = useState(false);++ const call = (request, success) => {+ if (!projectId) return Promise.resolve(null);+ setBusy(true);+ return request()+ .then((res) => {+ if (res?.project) replaceProject?.(res.project);+ if (success) toast.success(typeof success === 'function' ? success(res) : success);+ return res;+ })+ .catch((err) => { toast.error(err?.message || 'Development artifact request failed'); return null; })+ .finally(() => setBusy(false));+ };++ return {+ busy,+ upload: (file, fields) => call(() => uploadMusicVideoDevArtifact(projectId, file, fields, { silent: true }), (res) => `Saved ${res?.artifact?.title || 'artifact'} v${res?.artifact?.version || 1}`),+ addNote: (artifactId, body) => call(() => addMusicVideoDevArtifactNote(projectId, artifactId, body, { silent: true })),+ resolveNote: (artifactId, noteId, resolved) => call(() => resolveMusicVideoDevArtifactNote(projectId, artifactId, noteId, resolved, { silent: true })),+ review: (artifactId, body) => call(() => reviewMusicVideoDevArtifact(projectId, artifactId, body, { silent: true }), body.status === 'approved' ? 'Approved' : 'Changes requested'),+ remove: (artifactId) => call(() => deleteMusicVideoDevArtifact(projectId, artifactId, { silent: true }), 'Artifact removed'),+ };+}diff --git a/client/src/hooks/useMusicVideoKickoff.js b/client/src/hooks/useMusicVideoKickoff.jsindex 21be198737..c4bb5148e4 100644--- a/client/src/hooks/useMusicVideoKickoff.js+++ b/client/src/hooks/useMusicVideoKickoff.js@@ -6,6 +6,7 @@ export const MUSIC_VIDEO_KICKOFF_STEPS = Object.freeze({lyrics: 'Importing track lyrics…',vocals: 'Separating vocals…',align: 'Aligning words…',+ castAndSets: 'Building the Cast & Sets check-in…',plan: 'Planning shots…',});@@ -14,21 +15,31 @@ const hasCues = (project) => (project?.lyricCues || []).length > 0;// failed rather than stranding the run half way.const attempt = (step, project) => Promise.resolve().then(() => step(project)).catch(() => null);const allAligned = (project) => hasCues(project) && project.lyricCues.every((cue) => (cue.words || []).length > 0);+const castAndSetsDone = (project) => ['approved', 'skipped'].includes(project?.castAndSets?.status);/*** The Music Video autopilot kickoff ("Analyze & plan"): analyze → import the- * track's lyrics → separate vocals → align words → plan. Each step is skipped- * when its result already exists (a beat map, lyric lines, a vocal stem,- * aligned words), so a re-run only does what is missing. Every step receives- * the freshest project and resolves with the updated one, or null when it- * failed (the step reports its own error). A failed analysis stops the run —- * nothing can be planned without sections — while a failed lyric, vocal or- * alignment step leaves the plan to work with what exists.+ * track's lyrics → separate vocals → align words → Cast & Sets check-in →+ * plan. Each step is skipped when its result already exists (a beat map,+ * lyric lines, a vocal stem, aligned words, an approved or skipped check-in),+ * so a re-run only does what is missing. Every step receives the freshest+ * project and resolves with the updated one, or null when it failed (the step+ * reports its own error). A failed analysis stops the run — nothing can be+ * planned without sections — while a failed lyric, vocal or alignment step+ * leaves the plan to work with what exists.+ *+ * The check-in is a gate: `castAndSets` resolves once the stage reaches a+ * checkpoint, and the run plans only when that checkpoint is approved or+ * skipped. In review mode the stage stops at `review`, so the run ends there+ * ("Waiting for your check-in"); the director approves and runs the kickoff+ * again, which skips every finished step and plans. Auto mode approves itself+ * and the run continues straight to the plan. The step is optional so a caller+ * without it plans directly.** Returns `{ step, stepLabel, running, run(project) }`; `step` names the* running step (a key of MUSIC_VIDEO_KICKOFF_STEPS).*/-export default function useMusicVideoKickoff({ analyze, importLyrics, separateVocals, alignLyrics, plan }) {+export default function useMusicVideoKickoff({ analyze, importLyrics, separateVocals, alignLyrics, castAndSets, plan }) {const [step, setStep] = useState(null);const busy = useRef(false);const mounted = useMounted();@@ -56,6 +67,13 @@ export default function useMusicVideoKickoff({ analyze, importLyrics, separateVoenter('align');project = (await attempt(alignLyrics, project)) || project;}+ if (castAndSets && !castAndSetsDone(project)) {+ enter('castAndSets');+ const checked = await attempt(castAndSets, project);+ // Waiting for the director (review), or the check-in failed: stop here.+ if (!castAndSetsDone(checked)) return;+ project = checked;+ }enter('plan');await attempt(plan, project);} finally {diff --git a/client/src/lib/musicVideoAutomation.js b/client/src/lib/musicVideoAutomation.jsindex b6b9d07fed..9ec78e8ade 100644--- a/client/src/lib/musicVideoAutomation.js+++ b/client/src/lib/musicVideoAutomation.js@@ -15,6 +15,8 @@ export const automationDraftFrom = (automation) => ({tools: automation?.tools ?? DEFAULT_AUTOMATION_TOOLS,guidance: automation?.guidance ?? '',budget: automation?.budgetUsd != null ? String(automation.budgetUsd) : '',+ // The Cast & Sets check-in stops the autopilot for review unless auto-approved.+ castAndSetsCheckin: automation?.checkins?.castAndSets === 'auto' ? 'auto' : 'review',});export const automationFromDraft = (draft) => {@@ -23,5 +25,6 @@ export const automationFromDraft = (draft) => {tools: draft.tools,guidance: draft.guidance.trim(),budgetUsd: Number.isFinite(budget) && budget >= 0 ? budget : null,+ checkins: { castAndSets: draft.castAndSetsCheckin === 'auto' ? 'auto' : 'review' },};};diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 0a54eb50da..1769ffb52f 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -26,6 +26,8 @@ import useFieldDraft from '../hooks/useFieldDraft.js';import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';import useMusicVideoKickoff from '../hooks/useMusicVideoKickoff.js';+import useMusicVideoCastAndSets from '../hooks/useMusicVideoCastAndSets.js';+import useMusicVideoDevArtifacts from '../hooks/useMusicVideoDevArtifacts.js';import useMusicVideoVocalSeparation from '../hooks/useMusicVideoVocalSeparation.js';import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';@@ -64,6 +66,9 @@ import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';import TreatmentPanel from '../components/musicVideo/TreatmentPanel.jsx';import HandoffControls from '../components/musicVideo/HandoffControls.jsx';import ContactSheetDrawer from '../components/musicVideo/ContactSheetDrawer.jsx';+import DevArtifactsPanel from '../components/musicVideo/DevArtifactsPanel.jsx';+import DevArtifactDrawer from '../components/musicVideo/DevArtifactDrawer.jsx';+import CastAndSetsCheckin from '../components/musicVideo/CastAndSetsCheckin.jsx';import GalleryImagePicker from '../components/imageGen/GalleryImagePicker.jsx';import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';@@ -99,7 +104,9 @@ export default function MusicVideo() {// scene board is directly shareable/bookmarkable and reachable from the// media job-completion hooks. selectProject() navigates; the browser URL is// the single source of truth for "which project is open".- const { projectId: routeProjectId } = useParams();+ // A development artifact opens from its own deep link+ // (/music-video/:projectId/dev/:artifactId), the version from `?v=`.+ const { projectId: routeProjectId, artifactId: routeArtifactId } = useParams();const navigate = useNavigate();const [projects, setProjects] = useState([]);const [tracks, setTracks] = useState([]);@@ -175,6 +182,9 @@ export default function MusicVideo() {const revisions = useMusicVideoRevisions({ project: selected, replaceProject, sceneMedia, attachRender: excerpts.attachRender });const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject, submitSections: revisions.submitSections });const production = useMusicVideoProduction({ project: selected, replaceProject });+ // Cast & Sets check-in (before the plan) and the development files it saves.+ const castSets = useMusicVideoCastAndSets({ project: selected, replaceProject });+ const devArtifacts = useMusicVideoDevArtifacts({ project: selected, replaceProject });// Pre-production treatment (#8980): brief, compiled arc, shot direction,// proof checklist and the non-destructive Apply review.const treatment = useMusicVideoTreatment({ project: selected, onProjectPatch: patchProject, replaceProject });@@ -355,8 +365,30 @@ export default function MusicVideo() {return next;}).catch((err) => { toast.error(err?.message || 'Could not align the words — planning without word timings'); return null; }),+ castAndSets: (project) => castSets.runToCheckpoint(project),plan: (project) => handlePlan(project),});+ // Approve & continue: the kickoff resumes past the check-in and plans —+ // unless a server production run owns this board (it continues on its own).+ const continueAfterCheckin = (res) => {+ const next = res?.project;+ if (!next || (next.scenes || []).length) return;+ if ((next.productionRuns || []).some((r) => r.status === 'running')) return;+ kickoff.run(next);+ };+ const approveCastAndSets = () => castSets.approve().then(continueAfterCheckin);+ const skipCastAndSets = () => castSets.skip().then(continueAfterCheckin);+ const openArtifact = (artifactId) => navigate(`/music-video/${encodeURIComponent(selected.id)}/dev/${encodeURIComponent(artifactId)}`);+ const closeArtifact = () => navigate(`/music-video/${encodeURIComponent(selected?.id || routeProjectId)}`);+ const openArtifactRecord = routeArtifactId+ ? (selected?.devArtifacts || []).find((a) => a.id === routeArtifactId && !a.deleted) || null+ : null;+ const artifactVersion = Number(searchParams.get('v')) || openArtifactRecord?.version || null;+ const setArtifactVersion = (version) => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (version && version !== openArtifactRecord?.version) next.set('v', String(version)); else next.delete('v');+ return next;+ });const handleKickoff = () => {if (!selected || analyzing || planning || kickoff.running || autopilotBlockedReason) return;kickoff.run(selected);@@ -671,6 +703,20 @@ export default function MusicVideo() {onSelect={handleClipPickerSelect}/>)}+ {selected && (+ <DevArtifactDrawer+ key={routeArtifactId || 'none'}+ open={!!routeArtifactId}+ onClose={closeArtifact}+ project={selected}+ artifact={openArtifactRecord}+ version={artifactVersion}+ onVersionChange={setArtifactVersion}+ ops={devArtifacts}+ busy={devArtifacts.busy || castSets.busy}+ castAndSets={{ regenerate: () => castSets.regenerate(), approveAndContinue: approveCastAndSets }}+ />+ )}{selected && (<ContactSheetDraweropen={contactSheetOpen}@@ -765,11 +811,30 @@ export default function MusicVideo() {kickoffBusy={analyzing || planning || kickoff.running}kickoffStep={kickoff.stepLabel}kickoffBlockedReason={autopilotBlockedReason}+ checkin={(+ <CastAndSetsCheckin+ project={selected}+ busy={castSets.busy || kickoff.running}+ onOpenSheet={openArtifact}+ onApprove={approveCastAndSets}+ onRegenerate={() => castSets.regenerate()}+ onResume={() => castSets.resume()}+ onSkip={skipCastAndSets}+ />+ )}/><CreativeSetupPanel key={`creative-${selected.id}`} project={selected} onPendingChange={setCreativeSetupPending}onSave={(patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });})} />+ <DevArtifactsPanel+ project={selected}+ busy={devArtifacts.busy}+ onOpen={openArtifact}+ onUpload={(file, fields) => devArtifacts.upload(file, fields).then((res) => {+ if (res?.artifact) openArtifact(res.artifact.id);+ })}+ /><fieldset disabled={creativeSetupPending} className="space-y-3 min-w-0"><div className="bg-port-card border border-port-border rounded-lg p-3"><ProjectToolbardiff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 18571dfa5c..006969ecaa 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -89,7 +89,35 @@ vi.mock('../services/apiMusicVideo.js', () => ({getMusicVideoCodeDocument: vi.fn(async () => ({ html: '<!doctype html><html><body></body></html>', durationSec: 2, fps: 24, width: 1280, height: 720, song: { sections: [] }, timeline: { sections: [] } })),generateMusicVideoCode: vi.fn(),regenerateMusicVideoCodeSection: vi.fn(),+ startMusicVideoCastAndSets: vi.fn(),+ regenerateMusicVideoCastAndSets: vi.fn(),+ resumeMusicVideoCastAndSets: vi.fn(),+ approveMusicVideoCastAndSets: vi.fn(),+ skipMusicVideoCastAndSets: vi.fn(),+ musicVideoDevArtifactFileUrl: (id, artifactId, version) => `/api/music-video/${id}/dev-artifacts/${artifactId}/file${version ? `?version=${version}` : ''}`,+ uploadMusicVideoDevArtifact: vi.fn(),+ addMusicVideoDevArtifactNote: vi.fn(),+ resolveMusicVideoDevArtifactNote: vi.fn(),+ reviewMusicVideoDevArtifact: vi.fn(),+ deleteMusicVideoDevArtifact: vi.fn(),}));+// Server pushes (production runs, the Cast & Sets check-in) arrive over the+// socket; tests deliver them through this registry.+const socketHandlers = vi.hoisted(() => new Map());+vi.mock('../services/socket', () => ({+ default: {+ on: (event, fn) => {+ if (!socketHandlers.has(event)) socketHandlers.set(event, new Set());+ socketHandlers.get(event).add(fn);+ },+ off: (event, fn) => { socketHandlers.get(event)?.delete(fn); },+ emit: () => {},+ connected: true,+ },+}));+const pushSocket = (event, payload) => act(async () => {+ for (const fn of socketHandlers.get(event) || []) fn(payload);+});vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn(), listUniverseNames: vi.fn(() => Promise.resolve([])) }));vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(), uploadGalleryImage: vi.fn() }));@@ -173,6 +201,7 @@ import {renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject,startMusicVideoRevision, resumeMusicVideoRevision, cancelMusicVideoRevision,+ startMusicVideoCastAndSets, approveMusicVideoCastAndSets,} from '../services/apiMusicVideo.js';import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';@@ -1429,6 +1458,8 @@ describe('MusicVideo YouTube audio import (#1945)', () => {tools: ['image:external', 'image:local', 'video:local', 'video:fal', 'code:render'],guidance: 'one long take',budgetUsd: 40,+ // A new brief stops for the Cast & Sets check-in unless told otherwise.+ checkins: { castAndSets: 'review' },});});@@ -1491,7 +1522,8 @@ describe('MusicVideo YouTube audio import (#1945)', () => {});it('autopilot kickoff analyzes the song, tries the track lyrics, then plans the shots against the brief', async () => {- const project = { ...PROJECT_NO_CLIP, trackId: 'track-1', lyricCues: [], scenes: [], automation: { tools: ['image:local'], guidance: 'noir', budgetUsd: null } };+ // A check-in the director already skipped does not stop the run.+ const project = { ...PROJECT_NO_CLIP, trackId: 'track-1', lyricCues: [], scenes: [], castAndSets: { status: 'skipped' }, automation: { tools: ['image:local'], guidance: 'noir', budgetUsd: null } };const analyzed = { ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, status: 'analyzed' };analyzeMusicVideoProject.mockResolvedValue(analyzed);// An instrumental track: nothing to import, so nothing to separate or align.@@ -1506,6 +1538,71 @@ describe('MusicVideo YouTube audio import (#1945)', () => {expect(alignMusicVideoLyrics).not.toHaveBeenCalled();});+ it('autopilot stops at the Cast & Sets check-in in review mode, and Approve & continue plans', async () => {+ const project = { ...PROJECT_ANALYZED, trackId: null, uploadedAudioFilename: 'song.mp3', lyricCues: [], scenes: [], automation: { tools: ['image:codex'], guidance: '', budgetUsd: null, checkins: { castAndSets: 'review' } } };+ const directing = { ...project, castAndSets: { status: 'directing', revision: 1, plan: {}, images: {} } };+ startMusicVideoCastAndSets.mockResolvedValue({ project: directing, stage: directing.castAndSets });+ const sheet = { id: 'mvd-1', kind: 'cast-sets', title: 'Cast & Sets — Nova', status: 'pending', version: 1, mimeType: 'text/html', versions: [{ version: 1, mimeType: 'text/html', createdAt: '2026-01-01T00:00:00Z' }], notes: [] };+ const reviewing = { ...project, devArtifacts: [sheet], castAndSets: { status: 'review', revision: 1, artifactId: 'mvd-1', plan: {}, images: {} } };+ const approved = { ...reviewing, castAndSets: { ...reviewing.castAndSets, status: 'approved' }, devArtifacts: [{ ...sheet, status: 'approved' }] };+ approveMusicVideoCastAndSets.mockResolvedValue({ project: approved, stage: approved.castAndSets });+ planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 2, promptsSeeded: true });+ await openProject(project);++ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(startMusicVideoCastAndSets).toHaveBeenCalledWith(project.id, {}, { silent: true }));+ await pushSocket('music-video:cast-and-sets', { projectId: project.id, project: reviewing, stage: reviewing.castAndSets });+ expect(await screen.findByText('Waiting for your check-in.')).toBeTruthy();+ await settle();+ expect(planMusicVideoProject).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /Approve & continue/ }));+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));+ expect(approveMusicVideoCastAndSets).toHaveBeenCalledTimes(1);+ });++ it('autopilot continues straight to the plan when the check-in auto-approves', async () => {+ const project = { ...PROJECT_ANALYZED, trackId: null, uploadedAudioFilename: 'song.mp3', lyricCues: [], scenes: [], automation: { tools: ['image:codex'], guidance: '', budgetUsd: null, checkins: { castAndSets: 'auto' } } };+ const directing = { ...project, castAndSets: { status: 'directing', revision: 1, plan: {}, images: {} } };+ startMusicVideoCastAndSets.mockResolvedValue({ project: directing, stage: directing.castAndSets });+ const approved = { ...project, castAndSets: { status: 'approved', revision: 1, plan: {}, images: {} } };+ planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 2, promptsSeeded: true });+ await openProject(project);++ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(startMusicVideoCastAndSets).toHaveBeenCalled());+ // Progress pushes don't release the gate; only a checkpoint does.+ await pushSocket('music-video:cast-and-sets', { projectId: project.id, project: { ...directing, castAndSets: { ...directing.castAndSets, status: 'imaging' } } });+ expect(planMusicVideoProject).not.toHaveBeenCalled();+ await pushSocket('music-video:cast-and-sets', { projectId: project.id, project: approved, stage: approved.castAndSets });+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));+ expect(approveMusicVideoCastAndSets).not.toHaveBeenCalled();+ });++ it('opens a development file from its deep link in a sandboxed viewer', async () => {+ const sheet = {+ id: 'mvd-1', kind: 'cast-sets', title: 'Cast & Sets — Nova', status: 'approved', version: 2, mimeType: 'text/html', updatedAt: '2026-01-02T00:00:00Z',+ versions: [{ version: 1, mimeType: 'text/html', source: 'upload', createdAt: '2026-01-01T00:00:00Z' }, { version: 2, mimeType: 'text/html', source: 'upload', createdAt: '2026-01-02T00:00:00Z' }],+ notes: [{ id: 'n1', text: 'Shorter braid', target: null, version: 1, createdAt: '2026-01-01T00:00:00Z', resolvedAt: null }],+ };+ const project = { ...PROJECT_NO_CLIP, devArtifacts: [sheet] };+ listMusicVideoProjects.mockResolvedValue([project]);+ render(+ <MemoryRouter initialEntries={[`/music-video/${project.id}/dev/mvd-1?v=1`]}>+ <Routes>+ <Route path="/music-video/:projectId" element={<MusicVideo />} />+ <Route path="/music-video/:projectId/dev/:artifactId" element={<MusicVideo />} />+ </Routes>+ </MemoryRouter>,+ );+ const frame = await screen.findByTitle('Cast & Sets — Nova v1');+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts');+ expect(frame.getAttribute('src')).toBe(`/api/music-video/${project.id}/dev-artifacts/mvd-1/file?version=1`);+ expect(screen.getByText('Shorter braid')).toBeTruthy();+ // The Development section lists it with its review status.+ expect(screen.getAllByText('Approved').length).toBeGreaterThan(0);+ });+it('blocks relinking the track while a render is in progress for the selected project', async () => {await openProject(PROJECT_WITH_CLIP);fireEvent.click(await screen.findByRole('button', { name: /^Render final$/ }));diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 6057b6682f..0fd64bb779 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -276,3 +276,44 @@ export const reviewMusicVideoTreatmentProof = (id, proofId, body, options = {})request(`/music-video/${encodeURIComponent(id)}/treatment/proofs/${encodeURIComponent(proofId)}/review`, {method: 'POST', body: JSON.stringify(body), ...options,});++// ---- Development artifacts ("ingredients") ----+// Reviewable development files attached to a project: a Cast & Sets sheet, an+// animatic, a treatment, a storyboard. Every write resolves to `{ project, artifact }`.+const devArtifactsPath = (id) => `/music-video/${encodeURIComponent(id)}/dev-artifacts`;+// The served file (sandboxed HTML, Markdown as text, media). `version` null = current.+export const musicVideoDevArtifactFileUrl = (id, artifactId, version = null) =>+ `/api/music-video/${encodeURIComponent(id)}/dev-artifacts/${encodeURIComponent(artifactId)}/file${version ? `?version=${encodeURIComponent(version)}` : ''}`;+// `fields`: { kind, title } for a new artifact, or { artifactId } for a new version.+export const uploadMusicVideoDevArtifact = (id, file, fields = {}, options = {}) => {+ const body = new FormData();+ for (const [key, value] of Object.entries(fields)) {+ if (value != null && value !== '') body.append(key, value);+ }+ body.append('file', file, file.name || 'artifact');+ return request(devArtifactsPath(id), { method: 'POST', body, ...options });+};+export const addMusicVideoDevArtifactNote = (id, artifactId, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/dev-artifacts/${encodeURIComponent(artifactId)}/notes`, { method: 'POST', body: JSON.stringify(body), ...options });+export const resolveMusicVideoDevArtifactNote = (id, artifactId, noteId, resolved, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/dev-artifacts/${encodeURIComponent(artifactId)}/notes/${encodeURIComponent(noteId)}`, { method: 'PATCH', body: JSON.stringify({ resolved }), ...options });+// Body: { status: 'approved' | 'changes-requested' | 'pending', note? }.+export const reviewMusicVideoDevArtifact = (id, artifactId, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/dev-artifacts/${encodeURIComponent(artifactId)}/review`, { method: 'POST', body: JSON.stringify(body), ...options });+export const deleteMusicVideoDevArtifact = (id, artifactId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/dev-artifacts/${encodeURIComponent(artifactId)}`, { method: 'DELETE', ...options });++// ---- Cast & Sets check-in (before the shot plan) ----+// Start / regenerate / resume return at once (`{ project, stage }`); the stage+// advances server-side and reports over the `music-video:cast-and-sets` socket event.+export const startMusicVideoCastAndSets = (id, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/cast-and-sets`, { method: 'POST', body: JSON.stringify(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 });+export const resumeMusicVideoCastAndSets = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/resume`, { method: 'POST', body: '{}', ...options });+export const approveMusicVideoCastAndSets = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/approve`, { method: 'POST', ...options });+export const skipMusicVideoCastAndSets = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/skip`, { method: 'POST', ...options });diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 2024ebc17f..d1938dffdc 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -188,6 +188,7 @@ goal data together; interrupted intents remain retryable after restore.- Generated images — `data/images/*` bytes + `.metadata.json` sidecars; indexed into the `media_assets` table (#1000) keyed `image:<filename>`. Sidecars remain authoritative; the DB row is a derived, queryable mirror. Adapter: `server/services/mediaAssetIndex/`.- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes, tracked in `data/video-history.json`; indexed into `media_assets` keyed `video:<jobId>`. History file remains authoritative.- Game asset manifests — immutable `data/games/{id}/manifests/game-assets-v{N}.json` artifacts reference sprite atlas and music-library bytes by stable path + SHA-256; the `games` DB record owns the current pointer and history. Both halves are backed up: PostgreSQL by the required dump, manifests and referenced media by the rsync snapshot.+- Music Video development artifacts ("ingredients": a Cast & Sets check-in sheet, animatic, treatment, storyboard) — each version is an immutable file under `data/music-video/{projectId}/dev/{artifactId}/v{N}.{html,md,mp4,png,jpg}`; the `musicVideoProject` record owns the metadata (`devArtifacts[]`: kind, title, review status, notes, version history with each version's data-relative path). Versions are never overwritten and deletes are soft, so a clone that carried the metadata keeps valid pointers. The metadata is **wire-local** (stripped by `stripMusicVideoLocalRenderPins`, restored over a newer remote by `mergeProjectRecord`) because the bytes are not in the project's peer-sync asset manifest; both halves are backed up (PostgreSQL dump + rsync snapshot). Adapter: `server/services/musicVideo/devArtifactStore.js`.- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex cf2cb206a4..3d8ceb27de 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), then plans. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/dev/:artifactId`. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/musicVideoAutomation.js b/server/lib/musicVideoAutomation.jsindex a94101c169..99a6a3388d 100644--- a/server/lib/musicVideoAutomation.js+++ b/server/lib/musicVideoAutomation.js@@ -45,12 +45,16 @@ export const MUSIC_VIDEO_AUTOMATION_TOOLS = Object.freeze([export const MUSIC_VIDEO_AUTOMATION_TOOL_IDS = Object.freeze(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => t.id));export const MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX = 8000;+// Check-in gates the autopilot stops at. `review` (the default) waits for the+// director; `auto` approves the step and continues.+export const MUSIC_VIDEO_CHECKIN_MODES = Object.freeze(['review', 'auto']);export const MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD = 100000;/*** Merge a validated automation patch onto the stored brief. Sub-fields merge* (a guidance edit cannot drop the tool list); `tools` replaces its list whole,* de-duplicated in catalog order. `budgetUsd: null` means "no cap".+ * `checkins` merges per gate; an unknown or absent gate is `review`.*/export function normalizeMusicVideoAutomation(patch, current = null) {const merged = { ...(current || {}), ...(patch || {}) };@@ -61,5 +65,8 @@ export function normalizeMusicVideoAutomation(patch, current = null) {guidance: typeof merged.guidance === 'string' ? merged.guidance.slice(0, MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX) : '',budgetUsd: merged.budgetUsd != null && Number.isFinite(budget) && budget >= 0? Math.min(budget, MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD) : null,+ checkins: {+ castAndSets: ({ ...(current?.checkins || {}), ...(patch?.checkins || {}) }).castAndSets === 'auto' ? 'auto' : 'review',+ },};}diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 41f66f0f59..8d32899eac 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -15,6 +15,7 @@ import {MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX,MUSIC_VIDEO_AUTOMATION_TOOL_IDS,+ MUSIC_VIDEO_CHECKIN_MODES,} from './musicVideoAutomation.js';import { MUSCRIPTOR_MODELS } from './muscriptorModels.js';import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';@@ -550,6 +551,75 @@ export const musicVideoAutomationSchema = z.object({tools: z.array(z.enum(MUSIC_VIDEO_AUTOMATION_TOOL_IDS)).max(MUSIC_VIDEO_AUTOMATION_TOOL_IDS.length).optional(),guidance: z.string().max(MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX).optional(),budgetUsd: z.number().min(0).max(MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD).nullable().optional(),+ // Check-in gates: `review` stops the autopilot for the director, `auto`+ // approves and continues. Absent = review.+ checkins: z.object({+ castAndSets: z.enum(MUSIC_VIDEO_CHECKIN_MODES).optional(),+ }).strict().optional(),+}).strict();++// ---- Development artifacts ("ingredients") ----------------------------------+// Reviewable development files attached to a project (a Cast & Sets sheet, an+// animatic, a treatment, a storyboard). Bytes live on disk; see+// services/musicVideo/devArtifacts.js.+export const MUSIC_VIDEO_DEV_ARTIFACT_KINDS = ['cast-sets', 'animatic', 'treatment', 'storyboard', 'other'];+export const MUSIC_VIDEO_DEV_ARTIFACT_STATUSES = ['pending', 'approved', 'changes-requested'];++const devArtifactNoteText = z.string().trim().min(1).max(2000);+const devArtifactNoteTarget = z.string().trim().max(120).nullable().optional();++// The text fields of a multipart import (the file itself is the `file` part).+// `artifactId` adds a version to that artifact; otherwise kind + title create+// one. `notes` is a JSON array of strings or `{ text, target }` objects.+export const musicVideoDevArtifactImportSchema = z.object({+ artifactId: z.string().min(1).max(64).optional(),+ kind: z.enum(MUSIC_VIDEO_DEV_ARTIFACT_KINDS).optional(),+ title: z.string().trim().min(1).max(200).optional(),+ status: z.enum(MUSIC_VIDEO_DEV_ARTIFACT_STATUSES).optional(),+ notes: z.preprocess((v) => {+ if (typeof v !== 'string') return v;+ try { return JSON.parse(v); } catch { return v; }+ }, z.array(z.union([+ devArtifactNoteText,+ z.object({ text: devArtifactNoteText, target: devArtifactNoteTarget }).strict(),+ ])).max(50)).optional(),+}).strict().refine((b) => b.artifactId || b.kind, { message: 'kind is required for a new artifact', path: ['kind'] });++export const musicVideoDevArtifactNoteSchema = z.object({+ text: devArtifactNoteText,+ target: devArtifactNoteTarget,+}).strict();++export const musicVideoDevArtifactNoteUpdateSchema = z.object({+ resolved: z.boolean(),+}).strict();++export const musicVideoDevArtifactReviewSchema = z.object({+ status: z.enum(MUSIC_VIDEO_DEV_ARTIFACT_STATUSES),+ note: z.string().trim().max(2000).optional(),+}).strict();++export const musicVideoDevArtifactFileQuerySchema = z.object({+ version: z.coerce.number().int().min(1).max(1000).optional(),+}).strict();++// ---- Cast & Sets check-in -----------------------------------------------------+// Start / resume take an optional provider pin for the direction call.+export const musicVideoCastAndSetsStartSchema = z.object({+ providerId: z.string().min(1).max(64).optional(),+ model: z.string().min(1).max(200).optional(),+}).strict();++// Regenerate with notes. Omitted notes = the open notes on the sheet. A+// `target` names an image (`character`, `expressions`, `looks`, `set:<id>`,+// `test:<n>`); any other note revises the direction.+export const musicVideoCastAndSetsRegenerateSchema = z.object({+ notes: z.array(z.object({+ text: devArtifactNoteText,+ target: devArtifactNoteTarget,+ }).strict()).min(1).max(50).optional(),+ providerId: z.string().min(1).max(64).optional(),+ model: z.string().min(1).max(200).optional(),}).strict();export const musicVideoProjectCreateSchema = z.object({diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 86c38370f1..451784021f 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -626,7 +626,19 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// import replaces the lines without replacing the markers, leaving them// anchored to the wrong lines, and that edit wins LWW onto the upgraded// peer. Records without either field need no rewrite.- musicVideoProjects: 8,+ // v9 = autopilot check-in gates (`automation.checkins.castAndSets`:+ // `review` | `auto`). A v8 peer's automation normalizer rebuilds the brief+ // from tools/guidance/budget only, so its next brief edit would drop the+ // gate and win LWW back onto the upgraded peer, silently turning an+ // auto-approve setting back into a stop. Gating makes a v8 receiver reject+ // the ahead-version transfer until it upgrades; a record without the gate+ // needs no rewrite (absent = `review`). The Cast & Sets checkpoint+ // (`castAndSets`) and the development artifacts (`devArtifacts`) that ship+ // with it are wire-local like `productionRuns` (lib/syncWire.js): their files+ // live under this install's data/music-video/ and are not in the project's+ // asset manifest, so they are never sent. What an approved check-in writes+ // into ordinary fields (visual-spec references, concept subjects) syncs.+ musicVideoProjects: 9,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex a62d014c88..3296aee1ba 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -50,7 +50,13 @@ export function sanitizeSoftDeleteFields(raw) {*/export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = true } = {}) {if (!record || typeof record !== 'object' || Array.isArray(record)) return record;- const { imageMode: _imageMode, imageModelId: _imageModelId, productionRuns: _productionRuns, ...shared } = record;+ const {+ imageMode: _imageMode, imageModelId: _imageModelId, productionRuns: _productionRuns,+ // Development artifacts and the Cast & Sets checkpoint name files and jobs+ // on this install only (services/musicVideo/devArtifacts.js, castAndSets.js).+ devArtifacts: _devArtifacts, castAndSets: _castAndSets,+ ...shared+ } = record;if (stripVideoBackend && shared.videoSettings&& typeof shared.videoSettings === 'object' && !Array.isArray(shared.videoSettings)) {const { backend: _backend, ...sharedVideoSettings } = shared.videoSettings;diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex d7a0209f5b..0bc2b7d02b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -8,6 +8,8 @@* arranged against the beat grid".*/+import { existsSync } from 'fs';+import { unlink } from 'fs/promises';import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {@@ -42,6 +44,13 @@ import {musicVideoAutoReviewResumeSchema,musicVideoProductionStartSchema,musicVideoProductionResumeSchema,+ musicVideoDevArtifactImportSchema,+ musicVideoDevArtifactNoteSchema,+ musicVideoDevArtifactNoteUpdateSchema,+ musicVideoDevArtifactReviewSchema,+ musicVideoDevArtifactFileQuerySchema,+ musicVideoCastAndSetsStartSchema,+ musicVideoCastAndSetsRegenerateSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -106,6 +115,25 @@ import {reviewProof,} from '../services/musicVideo/treatmentService.js';import { getTrack } from '../services/tracks/index.js';+import {+ listDevArtifacts,+ getDevArtifact,+ importDevArtifact,+ resolveDevArtifactDownload,+ addNote as addDevArtifactNote,+ setNoteResolved as setDevArtifactNoteResolved,+ reviewArtifact as reviewDevArtifact,+ removeDevArtifact,+} from '../services/musicVideo/devArtifactService.js';+import { devArtifactTypeFor } from '../services/musicVideo/devArtifacts.js';+import {+ startCastAndSets,+ regenerateCastAndSets,+ resumeCastAndSets,+ approveCastAndSets,+ skipCastAndSets,+ getCastAndSets,+} from '../services/musicVideo/castAndSetsService.js';const router = Router();@@ -567,6 +595,115 @@ router.post('/:id/production-runs/:runId/cancel', asyncHandler(async (req, res)res.json(await cancelProduction(req.params.id, req.params.runId));}));+// --- Development artifacts ("ingredients") ---+// Reviewable development files attached to the project: list, import/upload+// (HTML, Markdown, MP4, PNG, JPG — a new artifact, or a new version of one),+// serve, notes, review and soft delete. See services/musicVideo/devArtifacts.js.+const DEV_ARTIFACT_MAX_BYTES = 512 * 1024 * 1024;+const devArtifactUpload = uploadSingle('file', {+ limits: { fileSize: DEV_ARTIFACT_MAX_BYTES },+ fileFilter: (_req, file, cb) => {+ const ext = String(file.originalname || '').split('.').pop();+ if (String(file.originalname || '').includes('.') && devArtifactTypeFor(ext)) cb(null, true);+ else cb(new ServerError('Unsupported file type — accepted: HTML, Markdown, MP4, PNG, JPG', { status: 400, code: 'VALIDATION_ERROR' }));+ },+});++// A served artifact never runs with the PortOS origin: HTML is sandboxed by+// its CSP even when opened directly (an opaque origin, no same-origin access),+// may run its own inline script inside that sandbox, and can load nothing+// from the network — images, media and fonts only as data:/blob: URLs.+const DEV_ARTIFACT_HTML_CSP = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:";+const DEV_ARTIFACT_MEDIA_CSP = "sandbox; default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'";++router.get('/:id/dev-artifacts', asyncHandler(async (req, res) => {+ res.json(await listDevArtifacts(req.params.id));+}));++router.post('/:id/dev-artifacts', devArtifactUpload, asyncHandler(async (req, res) => {+ if (!req.file) throw new ServerError('No file uploaded (multipart field "file")', { status: 400, code: 'VALIDATION_ERROR' });+ const input = (() => {+ try {+ return validateRequest(musicVideoDevArtifactImportSchema, req.body || {});+ } catch (err) {+ unlink(req.file.path).catch(() => {});+ throw err;+ }+ })();+ const out = await importDevArtifact(req.params.id, { ...input, tempPath: req.file.path, originalName: req.file.originalname });+ res.status(201).json(out);+}));++router.get('/:id/dev-artifacts/:artifactId', asyncHandler(async (req, res) => {+ res.json(await getDevArtifact(req.params.id, req.params.artifactId));+}));++router.get('/:id/dev-artifacts/:artifactId/file', asyncHandler(async (req, res) => {+ const { version } = validateRequest(musicVideoDevArtifactFileQuerySchema, req.query || {});+ const { path, mimeType } = await resolveDevArtifactDownload(req.params.id, req.params.artifactId, version ?? null);+ if (!existsSync(path)) throw new ServerError('The artifact file is not on this machine', { status: 404, code: 'DEV_ARTIFACT_FILE_MISSING' });+ const isHtml = mimeType === 'text/html';+ res.setHeader('Content-Security-Policy', isHtml ? DEV_ARTIFACT_HTML_CSP : DEV_ARTIFACT_MEDIA_CSP);+ res.setHeader('X-Content-Type-Options', 'nosniff');+ res.setHeader('Referrer-Policy', 'no-referrer');+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');+ res.setHeader('Cache-Control', 'private, no-cache');+ // Markdown is shown as text (a browser would otherwise download it).+ res.type(mimeType === 'text/markdown' ? 'text/plain; charset=utf-8' : (isHtml ? 'text/html; charset=utf-8' : mimeType));+ res.sendFile(path, { dotfiles: 'deny' });+}));++router.post('/:id/dev-artifacts/:artifactId/notes', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoDevArtifactNoteSchema, req.body || {});+ res.status(201).json(await addDevArtifactNote(req.params.id, req.params.artifactId, input));+}));++router.patch('/:id/dev-artifacts/:artifactId/notes/:noteId', asyncHandler(async (req, res) => {+ const { resolved } = validateRequest(musicVideoDevArtifactNoteUpdateSchema, req.body || {});+ res.json(await setDevArtifactNoteResolved(req.params.id, req.params.artifactId, req.params.noteId, resolved));+}));++router.post('/:id/dev-artifacts/:artifactId/review', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoDevArtifactReviewSchema, req.body || {});+ res.json(await reviewDevArtifact(req.params.id, req.params.artifactId, input));+}));++router.delete('/:id/dev-artifacts/:artifactId', asyncHandler(async (req, res) => {+ res.json(await removeDevArtifact(req.params.id, req.params.artifactId));+}));++// --- Cast & Sets check-in (runs before the shot plan) ---+// Start / regenerate / resume write the checkpoint and return at once; the+// direction call and the reference images advance in the background and+// report over `music-video:cast-and-sets`. Only these requests (or a+// production run the director started) begin work — nothing at boot does.+router.get('/:id/cast-and-sets', asyncHandler(async (req, res) => {+ res.json(await getCastAndSets(req.params.id));+}));++router.post('/:id/cast-and-sets', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoCastAndSetsStartSchema, req.body || {});+ res.status(202).json(await startCastAndSets(req.params.id, input));+}));++router.post('/:id/cast-and-sets/regenerate', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoCastAndSetsRegenerateSchema, req.body || {});+ res.status(202).json(await regenerateCastAndSets(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));+}));++router.post('/:id/cast-and-sets/approve', asyncHandler(async (req, res) => {+ res.json(await approveCastAndSets(req.params.id));+}));++router.post('/:id/cast-and-sets/skip', asyncHandler(async (req, res) => {+ res.json(await skipCastAndSets(req.params.id));+}));+// --- Director scene board ---router.post('/:id/scenes', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideoDevArtifacts.test.js b/server/routes/musicVideoDevArtifacts.test.jsnew file mode 100644index 0000000000..97a982ce0b--- /dev/null+++ b/server/routes/musicVideoDevArtifacts.test.js@@ -0,0 +1,140 @@+/**+ * Music Video development artifacts ("ingredients"), through the real router,+ * the real multipart parser, devArtifactService.js / devArtifacts.js and the+ * real file-backed project store: import (new artifact and new version), list,+ * serve under a sandboxing CSP, notes, review, soft delete, and the guards on+ * file type and stored paths.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { existsSync, readdirSync, rmSync } from 'fs';+import { join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-dev-artifact-route-test-');+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const { default: musicVideoRoutes } = await import('./musicVideo.js');+const projects = await import('../services/musicVideo/projects.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++const SHEET_V1 = '<!doctype html><title>Sheet</title><h1>Cast v1</h1><script>document.title = "x"</script>';+const SHEET_V2 = '<!doctype html><title>Sheet</title><h1>Cast v2</h1>';++async function upload(projectId, { name = 'sheet.html', body = SHEET_V1, type = 'text/html', fields = {} } = {}) {+ const form = new FormData();+ for (const [k, v] of Object.entries(fields)) form.append(k, v);+ form.append('file', new Blob([body], { type }), name);+ const encoded = new Request('http://localhost/', { method: 'POST', body: form });+ return request(app).post(`/api/music-video/${projectId}/dev-artifacts`)+ .set('content-type', encoded.headers.get('content-type'))+ .send(Buffer.from(await encoded.arrayBuffer()));+}++const devDir = (projectId) => join(ROOT(), 'music-video', projectId, 'dev');++let project;+beforeEach(async () => {+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });+ rmSync(join(ROOT(), 'music-video'), { recursive: true, force: true });+ project = await projects.createProject({ name: 'Example Video' });+});+afterAll(cleanupTempDataRoots);++describe('music-video development artifacts', () => {+ it('imports a sheet with its review state, versions it, and serves each version sandboxed', async () => {+ const created = await upload(project.id, {+ fields: { kind: 'cast-sets', title: 'Cast & Sets — Example', status: 'approved', notes: JSON.stringify(['Shorter braid', { text: 'Wider framing on the quay', target: 'test:1' }]) },+ });+ expect(created.status).toBe(201);+ const { artifact } = created.body;+ expect(artifact).toMatchObject({ kind: 'cast-sets', title: 'Cast & Sets — Example', status: 'approved', version: 1, mimeType: 'text/html' });+ expect(artifact.notes.map((n) => [n.text, n.target])).toEqual([['Shorter braid', null], ['Wider framing on the quay', 'test:1']]);+ expect(artifact.file).toBe(`music-video/${project.id}/dev/${artifact.id}/v1.html`);++ // Listed, and persisted on the record (not just echoed).+ const listed = await request(app).get(`/api/music-video/${project.id}/dev-artifacts`);+ expect(listed.body.map((a) => a.id)).toEqual([artifact.id]);++ // A new version of the same artifact resets the review to pending.+ const v2 = await upload(project.id, { body: SHEET_V2, fields: { artifactId: artifact.id } });+ expect(v2.status).toBe(201);+ expect(v2.body.artifact).toMatchObject({ id: artifact.id, version: 2, status: 'pending' });+ expect(v2.body.artifact.versions.map((v) => v.version)).toEqual([1, 2]);++ const current = await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/file`);+ expect(current.status).toBe(200);+ expect(current.text).toBe(SHEET_V2);+ const csp = current.headers['content-security-policy'];+ // Its own inline script may run, but only in an opaque origin with no network.+ expect(csp).toMatch(/^sandbox allow-scripts;/);+ expect(csp).not.toMatch(/allow-same-origin/);+ expect(csp).toMatch(/default-src 'none'/);+ expect(current.headers['x-content-type-options']).toBe('nosniff');++ const first = await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/file?version=1`);+ expect(first.text).toBe(SHEET_V1);+ expect((await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/file?version=3`)).status).toBe(404);+ });++ it('adds and resolves notes, approves or requests changes, and soft-deletes', async () => {+ const { body: { artifact } } = await upload(project.id, { fields: { kind: 'storyboard', title: 'Board' } });+ const noted = await request(app).post(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/notes`).send({ text: 'Open on the harbor', target: 'set:harbor' });+ expect(noted.status).toBe(201);+ expect(noted.body.note).toMatchObject({ text: 'Open on the harbor', target: 'set:harbor', version: 1, resolvedAt: null });++ const resolved = await request(app).patch(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/notes/${noted.body.note.id}`).send({ resolved: true });+ expect(resolved.body.note.resolvedAt).toBeTruthy();++ const changes = await request(app).post(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/review`).send({ status: 'changes-requested', note: 'Warmer light' });+ expect(changes.body.artifact.status).toBe('changes-requested');+ expect(changes.body.artifact.notes.at(-1).text).toBe('Warmer light');+ const approved = await request(app).post(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/review`).send({ status: 'approved' });+ expect(approved.body.artifact.status).toBe('approved');+ expect((await projects.getProject(project.id)).devArtifacts[0].status).toBe('approved');++ const removed = await request(app).delete(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}`);+ expect(removed.status).toBe(200);+ expect((await request(app).get(`/api/music-video/${project.id}/dev-artifacts`)).body).toEqual([]);+ expect((await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}`)).status).toBe(404);+ // Soft delete: the bytes stay (a clone may still point at them).+ expect(existsSync(join(devDir(project.id), artifact.id, 'v1.html'))).toBe(true);+ });++ it('serves Markdown as plain text and media under a script-free sandbox', async () => {+ const { body: { artifact } } = await upload(project.id, { name: 'treatment.md', body: '# Treatment\n<b>x</b>', type: 'text/markdown', fields: { kind: 'treatment', title: 'Treatment' } });+ expect(artifact.mimeType).toBe('text/markdown');+ const served = await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/file`);+ expect(served.headers['content-type']).toMatch(/^text\/plain/);+ expect(served.headers['content-security-policy']).toMatch(/^sandbox;/);+ });++ it('refuses an unsupported file type and a new artifact without a kind, storing nothing', async () => {+ const exe = await upload(project.id, { name: 'tool.exe', body: 'MZ', type: 'application/octet-stream', fields: { kind: 'other', title: 'x' } });+ expect(exe.status).toBe(400);+ const noKind = await upload(project.id, { fields: { title: 'x' } });+ expect(noKind.status).toBe(400);+ expect(existsSync(devDir(project.id)) ? readdirSync(devDir(project.id)) : []).toEqual([]);+ expect((await projects.getProject(project.id)).devArtifacts).toBeUndefined();+ });++ it('will not serve a stored path that escapes the music-video folder', async () => {+ const { body: { artifact } } = await upload(project.id, { fields: { kind: 'other', title: 'x' } });+ await projects.mutateProjectRecord(project.id, (current) => ({+ project: {+ ...current,+ devArtifacts: current.devArtifacts.map((a) => ({ ...a, file: '../music-video-projects.json', versions: a.versions.map((v) => ({ ...v, file: '../music-video-projects.json' })) })),+ },+ }));+ const res = await request(app).get(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/file`);+ expect(res.status).toBe(404);+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex b60d7b8ef9..39c5f6a58d 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -149,6 +149,7 @@ import { initFableLoomSceneImageHook } from './fableLoomSceneImageHook.js';import { initFableLoomSceneVideoHook } from './fableLoomSceneVideoHook.js';import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';+import { initMusicVideoCastSetsImageHook } from './musicVideoCastSetsImageHook.js';import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';import { initMusicStudioHook } from './musicStudioHook.js';import { initImageGenQuotaHook } from './imageGenQuota.js';@@ -670,6 +671,10 @@ const initMediaJobDependentHooks = () => {// Music Video scene-video hook — durably files a queued i2v scene clip onto// its project scene's `videoHistoryId` on completion (#1760 Phase 1).initMusicVideoSceneVideoHook();+ // Music Video Cast & Sets hook — files a queued check-in reference image+ // (character sheet, looks, set plates, in-set tests) onto its stage key.+ // It only listens: nothing is generated at boot.+ initMusicVideoCastSetsImageHook();// Creative Director music-bed hook — durably files a queued first-pass// audio render onto its project's `musicBed` field on completion, even if// the requesting client unmounted mid-render (#1928).diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex bd8ca147ba..b22a940149 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -79,6 +79,11 @@ export const CATEGORIES = {'certs': { label: 'TLS Certificates', description: 'HTTPS certificate and private key — purging drops the install back to HTTP', archivable: false, deletable: false },'launch-videos': { label: 'Launch Videos', description: 'App launch-video compositions, plans, captions and rendered deliverables', archivable: true, deletable: false },'composition-proofs': { label: 'Composition Proofs', description: 'Contact-sheet review stills from HTML-composition proof renders — re-rendered from source, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },+ // Development artifacts ("ingredients") of Music Video projects — every+ // version of a Cast & Sets sheet, animatic, treatment or storyboard, one+ // immutable file each, referenced by the project record. Not deletable from+ // here: a purge would strand those references (delete the artifact instead).+ 'music-video': { label: 'Music Video Development Files', description: 'Versioned development artifacts (check-in sheets, animatics, treatments) referenced by Music Video projects', archivable: true, deletable: false },'music-video-compositions': { label: 'Music Video Overlay Scratch', description: 'Typography overlay frames for an in-flight composed music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },'code-animations': { label: 'Code Animations', description: 'Generated animation HTML retained with its job history — the only copy of provider-generated work', archivable: true, deletable: false },'code-animation-exports': { label: 'Code Animation Export Staging', description: 'Animation HTML plus the frame-exact render shim, staged once per MP4 export — safe to purge', archivable: false, deletable: true, purgeScope: 'category' },diff --git a/server/services/musicVideo/castAndSets.js b/server/services/musicVideo/castAndSets.jsnew file mode 100644index 0000000000..83bbe7ef74--- /dev/null+++ b/server/services/musicVideo/castAndSets.js@@ -0,0 +1,245 @@+/**+ * Music Video — Cast & Sets check-in stage: pure record transforms over+ * `project.castAndSets`.+ *+ * The stage runs before the shot plan: a creative-direction call, then the+ * reference images (character sheet first; see castAndSetsPlan.js), then a+ * self-contained check-in sheet saved as a `cast-sets` development artifact.+ * With `automation.checkins.castAndSets === 'review'` (the default) it stops+ * at `review` until the director approves; with `auto` it approves itself.+ *+ * {+ * revision, status, stopReason, error,+ * processId, // the server process that may dispatch for it+ * productionRunId, // the production run that started it, if any+ * route: { mode, model },+ * direction, // castAndSetsDirection.js shape+ * moodImages: [{ kind, filename }],+ * plan: { [key]: { key, kind, label, prompt, deps, refKeys, moodRefs?, setId?, testIndex? } },+ * images: { [key]: { status, jobId, imageId, history, failures, error, updatedAt } },+ * artifactId, artifactVersion, notesApplied,+ * createdAt, updatedAt, approvedAt,+ * }+ *+ * Status: `directing` → `imaging` → `assembling` → `review` → `approved`, or+ * `failed` / `skipped`. A stage in one of the three working states whose+ * `processId` is not this process was interrupted by a restart: completions of+ * jobs already queued still land, but nothing new is dispatched (and no+ * provider is called) until the director resumes it.+ *+ * Peer sync: `castAndSets` is WIRE-LOCAL like `productionRuns` — it names this+ * install's jobs, processes and development files. What an approval produces+ * (visual-spec references, concept subjects) is ordinary project content and+ * syncs as usual.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { trimTo } from '../../lib/textUtils.js';++export const CAST_SETS_STATUSES = Object.freeze(['directing', 'imaging', 'assembling', 'review', 'approved', 'failed', 'skipped']);+export const CAST_SETS_WORKING = Object.freeze(['directing', 'imaging', 'assembling']);+// Settled = the autopilot may continue past the stage.+export const CAST_SETS_SETTLED = Object.freeze(['approved', 'skipped']);+// A key whose render failed this many times in a row stops the stage.+const MAX_IMAGE_FAILURES = 2;+const MAX_HISTORY = 20;+const MAX_REASON = 500;++const stageError = (status, code, message) => new ServerError(message, { status, code });++/** The check-in mode for a project (default: review). */+export const castAndSetsCheckinMode = (project) => (project?.automation?.checkins?.castAndSets === 'auto' ? 'auto' : 'review');++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. */+export const presentCastAndSets = (stage, processId) => (stage+ ? { ...stage, interrupted: CAST_SETS_WORKING.includes(stage.status) && stage.processId !== processId }+ : null);++function requireStage(project) {+ const stage = project?.castAndSets;+ if (!stage) throw stageError(404, 'NOT_FOUND', 'This project has no Cast & Sets check-in yet');+ return stage;+}++function write(project, stage, now) {+ return { project: { ...project, castAndSets: { ...stage, updatedAt: now }, updatedAt: now }, stage: { ...stage, updatedAt: now } };+}++/**+ * Begin (or restart) the stage. Refuses while a working stage is live in+ * this process, and once approved (regenerate instead). Returns `{ project, stage }`.+ */+export function startCastAndSetsOnProject(project, { processId, productionRunId = null }, now = new Date().toISOString()) {+ const current = project?.castAndSets || null;+ if (current && CAST_SETS_WORKING.includes(current.status) && current.processId === processId) {+ throw stageError(409, 'CAST_SETS_IN_PROGRESS', 'The Cast & Sets check-in is already being prepared');+ }+ if (current?.status === 'approved' || current?.status === 'review') {+ throw stageError(409, 'CAST_SETS_EXISTS', 'This project already has a Cast & Sets sheet — regenerate it with notes instead');+ }+ const stage = {+ revision: (current?.revision || 0) + 1,+ status: 'directing',+ stopReason: null,+ error: null,+ processId,+ productionRunId,+ route: current?.route || null,+ direction: current?.direction || null,+ moodImages: current?.moodImages || [],+ plan: current?.plan || {},+ images: current?.images || {},+ artifactId: current?.artifactId || null,+ artifactVersion: current?.artifactVersion || null,+ notesApplied: [],+ createdAt: current?.createdAt || now,+ approvedAt: null,+ };+ return write(project, stage, now);+}++/**+ * Re-open an existing sheet for a revision (Regenerate with notes). The stage+ * goes back to `directing` when the direction itself must change, else+ * straight to `imaging`. Returns `{ project, stage }`.+ */+export function reviseCastAndSetsOnProject(project, { processId, notesApplied = [], redirect }, now = new Date().toISOString()) {+ const stage = requireStage(project);+ if (CAST_SETS_WORKING.includes(stage.status) && stage.processId === processId) {+ throw stageError(409, 'CAST_SETS_IN_PROGRESS', 'The Cast & Sets check-in is already being prepared');+ }+ if (!stage.direction) throw stageError(409, 'CAST_SETS_NO_DIRECTION', 'There is no direction to revise yet — start the check-in first');+ return write(project, {+ ...stage,+ revision: stage.revision + 1,+ status: redirect ? 'directing' : 'imaging',+ stopReason: null,+ error: null,+ processId,+ notesApplied: notesApplied.map((n) => ({ id: n.id || null, target: n.target || null, text: trimTo(n.text, 2000) })),+ approvedAt: null,+ }, now);+}++/** Re-pin an interrupted working stage to this process. Returns `{ project, stage }`. */+export function resumeCastAndSetsOnProject(project, { processId }, now = new Date().toISOString()) {+ const stage = requireStage(project);+ if (!CAST_SETS_WORKING.includes(stage.status) && stage.status !== 'failed') {+ throw stageError(409, 'CAST_SETS_NOT_RESUMABLE', `The Cast & Sets check-in is ${stage.status}`);+ }+ // A failed stage resumes where it stopped: failed keys get another try.+ const images = Object.fromEntries(Object.entries(stage.images || {}).map(([key, img]) => [key,+ img.status === 'failed' || (img.status === 'queued' && !img.jobId) ? { ...img, status: 'pending', failures: 0, error: null } : img]));+ const status = stage.status === 'failed' ? (stage.direction ? 'imaging' : 'directing') : stage.status;+ return write(project, { ...stage, status, images, processId, stopReason: null, error: null }, now);+}++/**+ * Record the direction and its image plan. `renderKeys` are the plan keys to+ * (re)render; every other key keeps its image. Keys no longer in the plan are+ * dropped. Returns `{ project, stage }`.+ */+export function setCastAndSetsDirection(project, { direction, plan, moodImages, route, renderKeys }, now = new Date().toISOString()) {+ const stage = requireStage(project);+ const rerender = new Set(renderKeys);+ const images = {};+ for (const key of Object.keys(plan)) {+ const prev = stage.images?.[key];+ images[key] = !prev || rerender.has(key)+ ? { status: 'pending', jobId: null, imageId: prev?.imageId || null, history: prev?.history || [], failures: 0, error: null, updatedAt: now }+ : prev;+ }+ return write(project, {+ ...stage,+ status: 'imaging',+ direction,+ plan,+ moodImages: moodImages ?? stage.moodImages ?? [],+ route: route ?? stage.route ?? null,+ images,+ }, now);+}++/** Keys whose image may be dispatched now: pending, with every dependency done. */+export function dispatchableImageKeys(stage) {+ const images = stage?.images || {};+ return Object.values(stage?.plan || {})+ .filter((item) => images[item.key]?.status === 'pending' && item.deps.every((d) => images[d]?.status === 'done'))+ .map((item) => item.key);+}++export const allCastAndSetsImagesDone = (stage) => Object.keys(stage?.plan || {}).length > 0+ && Object.keys(stage.plan).every((key) => stage.images?.[key]?.status === 'done');++/**+ * Reserve one key for dispatch in a serialized write, so two advances cannot+ * enqueue it twice. Throws 409 when it is not pending or the stage is not+ * dispatching in this process. Returns `{ project, stage }`.+ */+export function reserveCastAndSetsImage(project, key, { processId }, now = new Date().toISOString()) {+ const stage = requireStage(project);+ if (stage.status !== 'imaging' || stage.processId !== processId) throw stageError(409, 'CAST_SETS_NOT_RUNNING', 'The Cast & Sets check-in is not generating images in this process');+ const img = stage.images?.[key];+ if (!img || img.status !== 'pending') throw stageError(409, 'CAST_SETS_IMAGE_BUSY', `The ${key} image is not waiting to render`);+ return write(project, { ...stage, images: { ...stage.images, [key]: { ...img, status: 'queued', jobId: null, updatedAt: now } } }, now);+}++/** Link the queued job to its key. */+export function linkCastAndSetsJob(project, key, jobId, now = new Date().toISOString()) {+ const stage = requireStage(project);+ const img = stage.images?.[key];+ if (!img) return { project, stage };+ return write(project, { ...stage, images: { ...stage.images, [key]: { ...img, jobId, updatedAt: now } } }, now);+}++/**+ * Settle a key's render. `filename` = it landed; otherwise `error`. A job that+ * is not the key's current one (a superseded render) is ignored. A failure is+ * retried once (back to pending); the second consecutive failure stops the+ * stage `failed`. Returns `{ project, stage, changed }`.+ */+export function settleCastAndSetsImage(project, key, { jobId = null, filename = null, error = null }, now = new Date().toISOString()) {+ const stage = project?.castAndSets;+ const img = stage?.images?.[key];+ if (!img || img.status !== 'queued' || (jobId && img.jobId && img.jobId !== jobId)) return { project, stage, changed: false };+ if (filename) {+ const history = img.imageId && img.imageId !== filename ? [...(img.history || []), img.imageId].slice(-MAX_HISTORY) : (img.history || []);+ const next = { ...img, status: 'done', jobId: jobId || img.jobId, imageId: filename, history, failures: 0, error: null, updatedAt: now };+ return { ...write(project, { ...stage, images: { ...stage.images, [key]: next } }, now), changed: true };+ }+ const failures = (img.failures || 0) + 1;+ const reason = trimTo(String(error || 'The render failed'), MAX_REASON);+ const next = { ...img, status: failures >= MAX_IMAGE_FAILURES ? 'failed' : 'pending', jobId: null, failures, error: reason, updatedAt: now };+ const failed = next.status === 'failed';+ return {+ ...write(project, {+ ...stage,+ images: { ...stage.images, [key]: next },+ ...(failed ? { status: 'failed', stopReason: `The ${stage.plan?.[key]?.label || key} image failed twice: ${reason}` } : {}),+ }, now),+ changed: true,+ };+}++/** Enter a new working/terminal status with an optional reason. */+export function setCastAndSetsStatus(project, status, { reason = null, error = null, extra = {} } = {}, now = new Date().toISOString()) {+ if (!CAST_SETS_STATUSES.includes(status)) throw new Error(`setCastAndSetsStatus: invalid status ${status}`);+ const stage = requireStage(project);+ return write(project, {+ ...stage,+ ...extra,+ status,+ stopReason: reason ? trimTo(String(reason), MAX_REASON) : null,+ error: error ? trimTo(String(error), MAX_REASON) : null,+ ...(status === 'approved' ? { approvedAt: now } : {}),+ }, now);+}++/** Refuse an approval that has nothing to approve. */+export function assertCastAndSetsApprovable(project) {+ const stage = requireStage(project);+ if (stage.status !== 'review') throw stageError(409, 'CAST_SETS_NOT_IN_REVIEW', `The Cast & Sets check-in is ${stage.status}, not waiting for review`);+ return stage;+}diff --git a/server/services/musicVideo/castAndSetsDirection.js b/server/services/musicVideo/castAndSetsDirection.jsnew file mode 100644index 0000000000..f565916faf--- /dev/null+++ b/server/services/musicVideo/castAndSetsDirection.js@@ -0,0 +1,354 @@+/**+ * Music Video — Cast & Sets creative direction (pure): the LLM prompt, the+ * response parser and the absent-vs-empty merge.+ *+ * Before any image is made, one provider call reads the song as a story and+ * returns the production's cast and world: a logline, one protagonist (face,+ * hair, signature prop, a recurring gesture tied to a lyric hook, continuity+ * rules), 1–4 wardrobe looks mapped to chapters, 3–8 sets (one dominant light+ * each) mapped to song sections, 2–4 in-set test frames, an overlay concept,+ * and the 2–4 mood-board images that best show the look. The prompt is told+ * explicitly that the mood board is look/lighting/texture reference only —+ * the world comes from the song's own references and themes.+ *+ * A regeneration sends the current direction plus the director's notes and+ * asks for the full revised object. The merge follows the repo's LLM rule:+ * a key the model left out keeps the current value; a key present with an+ * empty value is an intentional clear (for the optional fields that allow it).+ */++import { z } from 'zod';+import { extractJson } from '../../lib/jsonExtract.js';+import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';+import { trimTo } from '../../lib/textUtils.js';++export const CAST_SETS_LIMITS = Object.freeze({+ looks: { min: 1, max: 4 },+ sets: { min: 3, max: 8 },+ tests: { min: 2, max: 4 },+ moodRefs: { min: 2, max: 4 },+ rules: 6,+ questions: 4,+ overlayElements: 4,+});+const TEXT = 1000;+const SHORT = 120;+const LYRICS_MAX = 6000;+const MOOD_ITEMS_MAX = 40;+const MOOD_ITEM_TEXT = 280;++// ---- context ---------------------------------------------------------------++const fmtTime = (sec) => {+ const s = Math.max(0, Number(sec) || 0);+ return `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;+};++/** The lyric sheet as the model should read it: section headers and delivery directions inline. */+function lyricSheetText(project) {+ const cues = Array.isArray(project?.lyricCues) ? project.lyricCues : [];+ const markers = Array.isArray(project?.lyricMarkers) ? project.lyricMarkers : [];+ const lines = [];+ for (let i = 0; i <= cues.length; i += 1) {+ for (const m of markers.filter((mk) => mk?.line === i)) {+ if (typeof m.label === 'string' && m.label.trim()) lines.push(`[${m.label.trim()}]`);+ }+ const text = typeof cues[i]?.text === 'string' ? cues[i].text.trim() : '';+ if (text) lines.push(text);+ }+ return lines.join('\n').slice(0, LYRICS_MAX);+}++/** The analyzed song sections the song map is keyed by. */+export function songSections(project) {+ const sections = Array.isArray(project?.audioAnalysis?.sections) ? project.audioAnalysis.sections : [];+ return sections+ .filter((s) => typeof s?.startSec === 'number' && typeof s?.endSec === 'number' && s.endSec > s.startSec)+ .map((s, index) => ({ index, label: typeof s.label === 'string' && s.label.trim() ? s.label.trim() : `Section ${index + 1}`, startSec: s.startSec, endSec: s.endSec }));+}++/**+ * The mood board's images with what is known about each (caption, per-item+ * vision analysis). `resolveItem` maps a board item to its local image+ * (`boardItemLocalImage`) — injected so this module stays free of the store.+ */+export function moodBoardImageList(board, resolveItem) {+ const out = [];+ for (const item of Array.isArray(board?.items) ? board.items : []) {+ const asset = typeof resolveItem === 'function' ? resolveItem(item) : null;+ if (!asset?.filename) continue;+ if (out.some((e) => e.kind === asset.kind && e.filename === asset.filename)) continue;+ out.push({+ kind: asset.kind,+ filename: asset.filename,+ caption: trimTo(item.caption, MOOD_ITEM_TEXT),+ analysis: trimTo(item.analysis?.prompt, MOOD_ITEM_TEXT),+ });+ if (out.length >= MOOD_ITEMS_MAX) break;+ }+ return out;+}++const OUTPUT_SHAPE = `{+ "logline": "<one or two sentences: who, where, what happens>",+ "interpretation": "<how the song's references and themes shape this world>",+ "protagonist": {+ "name": "<a name or designation>",+ "description": "<who they are in the song: age, vibe, attitude>",+ "face": "<face: skin, eyes, brows, distinguishing features>",+ "hair": "<hair that reads in silhouette>",+ "signature": "<one signature prop or detail present in every look>",+ "gesture": "<a recurring gesture tied to a lyric hook, quoting the hook>",+ "rules": ["<continuity or safety rule>"]+ },+ "looks": [{ "name": "<SHORT NAME>", "description": "<the complete outfit>", "chapters": "<which parts of the song>" }],+ "sets": [{ "id": "<short-slug>", "name": "<set name>", "description": "<the empty location, concrete and visual>", "lighting": "<its one dominant light>", "sections": ["<section label it serves>"] }],+ "songMap": [{ "section": 0, "setId": "<short-slug>" }],+ "tests": [{ "setId": "<short-slug>", "look": "<SHORT NAME>", "action": "<what the protagonist does in this frame>", "caption": "<the lyric or beat it serves>" }],+ "overlayConcept": { "summary": "<one persistent graphic layer that ties every shot together>", "elements": [{ "name": "<element>", "description": "<what it shows and when it changes>" }] },+ "moodRefs": [0, 1],+ "questions": ["<a question for the director>"]+}`;++/**+ * Build the direction prompt. `context` is `{ board, moodImages, track }`+ * (all optional). With `previous` + `notes` it becomes a revision request.+ */+export function buildCastAndSetsPrompt(project, { moodImages = [], board = null, track = null, previous = null, notes = [] } = {}) {+ const concept = project?.concept || {};+ const analysis = project?.audioAnalysis || {};+ const sections = songSections(project);+ const lyrics = lyricSheetText(project);+ const guidance = trimTo(project?.automation?.guidance, 2000);+ const trackStyle = trimTo(track?.prompt, 1500) || trimTo(concept.style, 1500);+ const boardStyle = trimTo(board?.style?.prompt, 1500) || trimTo(concept.moodBoardStyle, 1500);+ const boardNegative = trimTo(board?.style?.negativePrompt, 600);+ const moodLines = moodImages.map((img, i) => `${i}. ${[img.caption, img.analysis].filter(Boolean).join(' — ') || '(no caption or analysis)'}`);+ const sectionLines = sections.map((s) => `${s.index}. ${s.label} ${fmtTime(s.startSec)}–${fmtTime(s.endSec)}`);+ const bible = musicVideoCreativeContext(concept);++ const header = [+ `You are the creative director preparing the CAST & SETS check-in for a music video of "${project?.name || 'Untitled'}".`,+ 'Read the lyrics as a story. Interpret the song: its references, themes and subtext, including any real events, ideas or cultural touchstones the words point at. The world of the video (who the protagonist is, where it happens, what the sets are) must come from that interpretation.',+ 'The mood board is reference for LOOK, LIGHTING, COLOR and TEXTURE only. Never copy its literal locations, rooms or props into the sets: a kitchen photo on the board does not put the video in a kitchen.',+ ].join('\n');++ const facts = [+ `Duration: ${fmtTime(analysis.durationSec)}${analysis.bpm ? ` · ${Math.round(analysis.bpm)} BPM` : ''}`,+ trackStyle && `Track style prompt: ${trackStyle}`,+ concept.prompt && `Concept: ${trimTo(concept.prompt, 2000)}`,+ guidance && `Director guidance: ${guidance}`,+ bible && bible,+ ].filter(Boolean).join('\n');++ const board_ = [+ boardStyle && `Mood board composed style: ${boardStyle}`,+ boardNegative && `Mood board avoid: ${boardNegative}`,+ moodLines.length ? `Mood board images (index. caption — per-image analysis):\n${moodLines.join('\n')}` : 'No mood board images.',+ ].filter(Boolean).join('\n');++ const rules = [+ `- ${CAST_SETS_LIMITS.looks.min}–${CAST_SETS_LIMITS.looks.max} looks, ${CAST_SETS_LIMITS.sets.min}–${CAST_SETS_LIMITS.sets.max} sets, ${CAST_SETS_LIMITS.tests.min}–${CAST_SETS_LIMITS.tests.max} tests.`,+ '- Give every set ONE dominant light color or quality so a cut tells the viewer where we are.',+ '- songMap: one entry per song section index listed above, naming the set that section plays in.',+ '- tests: in-set frames of the protagonist that prove the cast works in the world; each names a set id and a look name.',+ `- moodRefs: the ${CAST_SETS_LIMITS.moodRefs.min}–${CAST_SETS_LIMITS.moodRefs.max} mood board image indices that best show the look for the character sheet${moodImages.length ? '' : ' (empty: there are none)'}.`,+ '- Wet or revealing looks use opaque fabric so the video stays safe to post.',+ '- questions: up to three things you need the director to decide.',+ ].join('\n');++ const revision = previous ? [+ 'This is a REVISION. The current direction is:',+ JSON.stringify(previous),+ notes.length ? `Director notes to address:\n${notes.map((n) => `- ${n.target ? `[${n.target}] ` : ''}${n.text}`).join('\n')}` : 'No notes: refine it.',+ 'Return the FULL revised JSON object. Change only what the notes ask for and keep every other field exactly as it is.',+ ].join('\n') : '';++ return [+ header,+ facts,+ `Lyrics (section headers and delivery directions in brackets):\n${lyrics || '(instrumental — no lyrics)'}`,+ sectionLines.length ? `Song sections (index. label start–end):\n${sectionLines.join('\n')}` : 'The song has not been sectioned.',+ board_,+ rules,+ revision,+ `Respond with ONLY one JSON object in this shape (replace every <…> with real content; do NOT output the angle-bracket text), no other text:\n${OUTPUT_SHAPE}`,+ ].filter(Boolean).join('\n\n');+}++// ---- parsing ----------------------------------------------------------------++const isPlaceholder = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);+const text = (max) => z.string().transform((s) => (isPlaceholder(s) ? '' : s.trim().slice(0, max)));+const slug = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);++const protagonistSchema = z.object({+ name: text(SHORT).optional(),+ description: text(TEXT).optional(),+ face: text(TEXT).optional(),+ hair: text(TEXT).optional(),+ signature: text(TEXT).optional(),+ gesture: text(TEXT).optional(),+ rules: z.array(text(300)).optional(),+}).passthrough();+const lookSchema = z.object({ name: text(SHORT), description: text(TEXT), chapters: text(300).optional() }).passthrough();+const setSchema = z.object({+ id: z.string().optional(),+ name: text(SHORT),+ description: text(TEXT),+ lighting: text(300).optional(),+ sections: z.union([z.array(z.union([z.string(), z.number()])), z.string()]).optional(),+}).passthrough();+const songMapSchema = z.object({ section: z.union([z.number(), z.string()]), setId: z.string() }).passthrough();+const testSchema = z.object({ setId: z.string(), look: text(SHORT).optional(), action: text(TEXT), caption: text(300).optional() }).passthrough();+const overlaySchema = z.union([+ text(TEXT).transform((summary) => ({ summary, elements: [] })),+ z.object({+ summary: text(TEXT).optional(),+ elements: z.array(z.object({ name: text(SHORT), description: text(TEXT) }).passthrough()).optional(),+ }).passthrough(),+]);++// One lenient parser per field: a field that does not fit its shape counts as+// absent (the merge keeps the current value) rather than failing the answer.+const FIELD_PARSERS = {+ logline: text(TEXT),+ interpretation: text(2000),+ protagonist: protagonistSchema,+ looks: z.array(lookSchema),+ sets: z.array(setSchema),+ songMap: z.array(songMapSchema),+ tests: z.array(testSchema),+ overlayConcept: overlaySchema,+ moodRefs: z.array(z.number().int().min(0)),+ questions: z.array(text(400)),+};++// A real answer (not the echoed schema) carries at least one non-placeholder+// logline or protagonist name — or, on a revision, any other known field.+const realText = (v) => typeof v === 'string' && v.trim() && !isPlaceholder(v);+const looksLikeDirection = (value) => value && typeof value === 'object' && !Array.isArray(value)+ && (realText(value.logline) || realText(value.protagonist?.name)+ || (!('logline' in value) && Object.keys(FIELD_PARSERS).some((k) => k in value)));++/**+ * Parse a provider answer into a PARTIAL direction: only the keys the model+ * returned in a usable shape are present. Returns null when no JSON object+ * could be found at all.+ */+export function parseCastAndSetsResponse(responseText) {+ const { value } = extractJson(responseText, { blockType: 'object', shapePredicate: looksLikeDirection });+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const out = {};+ for (const [key, parser] of Object.entries(FIELD_PARSERS)) {+ if (!(key in value) || value[key] == null) continue;+ const parsed = parser.safeParse(value[key]);+ if (parsed.success) out[key] = parsed.data;+ }+ return out;+}++// ---- merge + normalize ------------------------------------------------------++const hasOwn = (obj, key) => obj != null && Object.prototype.hasOwnProperty.call(obj, key);++function normalizeSets(sets, sections) {+ const seen = new Set();+ const labels = new Map(sections.map((s) => [String(s.index), s.label]));+ return sets.filter((s) => s.name && s.description).slice(0, CAST_SETS_LIMITS.sets.max).map((s, i) => {+ let id = slug(s.id) || slug(s.name) || `set-${i + 1}`;+ while (seen.has(id)) id = `${id}-${i + 1}`;+ seen.add(id);+ const rawSections = Array.isArray(s.sections) ? s.sections : (typeof s.sections === 'string' ? s.sections.split(/[,;]/) : []);+ return {+ id,+ name: s.name,+ description: s.description,+ lighting: s.lighting || '',+ sections: rawSections.map((x) => (typeof x === 'number' ? labels.get(String(x)) || '' : String(x).trim())).filter(Boolean).slice(0, 12),+ };+ });+}++function normalizeSongMap(entries, sets, sections) {+ const setIds = new Set(sets.map((s) => s.id));+ const bySlug = new Map(sets.map((s) => [slug(s.name), s.id]));+ const byLabel = new Map(sections.map((s) => [s.label.toLowerCase(), s.index]));+ const out = new Map();+ for (const entry of entries) {+ const index = typeof entry.section === 'number' ? entry.section : (byLabel.get(String(entry.section).trim().toLowerCase()) ?? Number(entry.section));+ const setId = setIds.has(slug(entry.setId)) ? slug(entry.setId) : bySlug.get(slug(entry.setId));+ if (!Number.isInteger(index) || !sections.some((s) => s.index === index) || !setId) continue;+ if (!out.has(index)) out.set(index, { section: index, setId });+ }+ return [...out.values()].sort((a, b) => a.section - b.section);+}++function normalizeTests(tests, sets, looks) {+ const setIds = new Set(sets.map((s) => s.id));+ return tests+ .map((t) => ({ ...t, setId: slug(t.setId) }))+ .filter((t) => setIds.has(t.setId) && t.action)+ .slice(0, CAST_SETS_LIMITS.tests.max)+ .map((t) => ({+ setId: t.setId,+ look: looks.find((l) => l.name.toLowerCase() === String(t.look || '').toLowerCase())?.name || looks[0]?.name || '',+ action: t.action,+ caption: t.caption || '',+ }));+}++/**+ * Merge a parsed (partial) answer onto the current direction and normalize+ * the result. Absent keys keep `previous`; present keys replace (an empty+ * string/array clears the optional text/list fields). Returns+ * `{ direction, missing }` — `missing` lists the required parts still absent,+ * so a first pass with an unusable answer can be refused.+ */+export function mergeCastAndSetsDirection(previous, parsed, { sections = [], moodImageCount = 0 } = {}) {+ const base = previous || {};+ const pick = (key, fallback) => (hasOwn(parsed, key) ? parsed[key] : (hasOwn(base, key) ? base[key] : fallback));+ const p0 = base.protagonist || {};+ const p1 = hasOwn(parsed, 'protagonist') ? parsed.protagonist : {};+ const pField = (key) => (hasOwn(p1, key) ? p1[key] : (p0[key] ?? ''));+ const protagonist = {+ name: pField('name'),+ description: pField('description'),+ face: pField('face'),+ hair: pField('hair'),+ signature: pField('signature'),+ gesture: pField('gesture'),+ rules: (hasOwn(p1, 'rules') ? p1.rules : (p0.rules || [])).filter(Boolean).slice(0, CAST_SETS_LIMITS.rules),+ };+ const looks = (pick('looks', [])).filter((l) => l.name && l.description).slice(0, CAST_SETS_LIMITS.looks.max)+ .map((l) => ({ name: l.name, description: l.description, chapters: l.chapters || '' }));+ const sets = hasOwn(parsed, 'sets') ? normalizeSets(parsed.sets, sections) : (base.sets || []);+ const songMap = normalizeSongMap(pick('songMap', []), sets, sections);+ const tests = normalizeTests(pick('tests', []), sets, looks);+ const overlayRaw = pick('overlayConcept', { summary: '', elements: [] }) || {};+ const overlayConcept = {+ summary: overlayRaw.summary || '',+ elements: (overlayRaw.elements || []).filter((e) => e.name && e.description).slice(0, CAST_SETS_LIMITS.overlayElements)+ .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 direction = {+ logline: pick('logline', ''),+ interpretation: pick('interpretation', ''),+ protagonist,+ looks,+ sets,+ songMap,+ tests,+ overlayConcept,+ moodRefs,+ questions: (pick('questions', [])).filter(Boolean).slice(0, CAST_SETS_LIMITS.questions),+ };+ const missing = [+ !direction.logline && 'logline',+ !(protagonist.name && (protagonist.face || protagonist.description)) && 'protagonist',+ looks.length < CAST_SETS_LIMITS.looks.min && 'looks',+ sets.length < CAST_SETS_LIMITS.sets.min && 'sets',+ ].filter(Boolean);+ return { direction, missing };+}diff --git a/server/services/musicVideo/castAndSetsDirection.test.js b/server/services/musicVideo/castAndSetsDirection.test.jsnew file mode 100644index 0000000000..487b7f137f--- /dev/null+++ b/server/services/musicVideo/castAndSetsDirection.test.js@@ -0,0 +1,93 @@+/**+ * Cast & Sets creative direction — the parse/merge boundary a provider answer+ * crosses: fenced and echoed answers, lenient per-field parsing, the+ * absent-vs-empty merge rule on a revision, and the refusal of a first pass+ * that lacks the required parts.+ */++import { describe, it, expect } from 'vitest';+import {+ buildCastAndSetsPrompt,+ mergeCastAndSetsDirection,+ parseCastAndSetsResponse,+ songSections,+} from './castAndSetsDirection.js';++const project = {+ name: 'Example Song',+ lyricCues: [{ text: 'line one' }, { text: 'line two' }],+ lyricMarkers: [{ type: 'section', label: 'Verse 1', line: 0 }, { type: 'direction', label: 'Whispered', line: 1 }],+ audioAnalysis: { durationSec: 60, bpm: 128, sections: [{ label: 'Intro', startSec: 0, endSec: 20 }, { label: 'Chorus', startSec: 20, endSec: 60 }] },+ automation: { guidance: 'keep it night-lit' },+ concept: { prompt: 'an escape story', style: 'raw flash' },+};+const sections = songSections(project);++const ANSWER = {+ logline: 'She escapes.',+ protagonist: { name: 'Nova', face: 'weathered', hair: 'grey braid', rules: ['No hats'] },+ looks: [{ name: 'Lab', description: 'grey hoodie' }],+ sets: [+ { name: 'Lab Room', description: 'a lamp room', lighting: 'green', sections: [0] },+ { id: 'Harbor!', name: 'Harbor', description: 'wet stone quay', lighting: 'sodium orange' },+ { name: 'Roof', description: 'rain', lighting: 'red' },+ ],+ songMap: [{ section: 'Chorus', setId: 'roof' }, { section: 0, setId: 'harbor' }, { section: 9, setId: 'roof' }],+ tests: [{ setId: 'lab-room', look: 'Lab', action: 'climbing' }, { setId: 'nowhere', action: 'x' }],+ overlayConcept: 'A falling meter.',+ moodRefs: [2, 7],+};++describe('Cast & Sets direction', () => {+ it('builds a prompt that reads the song and keeps the mood board to look only', () => {+ const prompt = buildCastAndSetsPrompt(project, { moodImages: [{ caption: 'a kitchen', analysis: 'steam and brass' }], board: { style: { prompt: 'green flash' } } });+ expect(prompt).toContain('[Verse 1]\nline one\n[Whispered]\nline two');+ expect(prompt).toContain('Interpret the song');+ expect(prompt).toMatch(/LOOK, LIGHTING, COLOR and TEXTURE only/);+ expect(prompt).toContain('0. a kitchen — steam and brass');+ expect(prompt).toContain('Director guidance: keep it night-lit');+ expect(prompt).toContain('1. Chorus 0:20–1:00');+ expect(prompt).not.toContain('This is a REVISION');+ });++ it('parses a fenced answer after an echoed schema, normalizing ids, the song map and tests', () => {+ const echoed = buildCastAndSetsPrompt(project).split('no other text:\n')[1];+ const parsed = parseCastAndSetsResponse(`${echoed}\n\nSure:\n\`\`\`json\n${JSON.stringify(ANSWER)}\n\`\`\``);+ expect(parsed.logline).toBe('She escapes.');+ const { direction, missing } = mergeCastAndSetsDirection(null, parsed, { sections, moodImageCount: 4 });+ expect(missing).toEqual([]);+ expect(direction.sets.map((s) => s.id)).toEqual(['lab-room', 'harbor', 'roof']);+ expect(direction.sets[0].sections).toEqual(['Intro']);+ // Labels and indices both resolve; an unknown section is dropped.+ expect(direction.songMap).toEqual([{ section: 0, setId: 'harbor' }, { section: 1, setId: 'roof' }]);+ expect(direction.tests).toEqual([{ setId: 'lab-room', look: 'Lab', action: 'climbing', caption: '' }]);+ expect(direction.overlayConcept).toEqual({ summary: 'A falling meter.', elements: [] });+ expect(direction.moodRefs).toEqual([2]);+ });++ it('refuses a first pass missing the protagonist or enough sets', () => {+ const parsed = parseCastAndSetsResponse(JSON.stringify({ logline: 'x', sets: [{ name: 'A', description: 'a' }] }));+ expect(mergeCastAndSetsDirection(null, parsed, { sections }).missing).toEqual(['protagonist', 'looks', 'sets']);+ expect(parseCastAndSetsResponse('no json here')).toBeNull();+ });++ it('on a revision keeps absent keys, applies present ones, and treats an empty value as a clear', () => {+ const { direction: previous } = mergeCastAndSetsDirection(null, parseCastAndSetsResponse(JSON.stringify({ ...ANSWER, questions: ['Is she right?'], interpretation: 'agents' })), { sections, moodImageCount: 4 });+ const revision = parseCastAndSetsResponse(JSON.stringify({+ protagonist: { hair: 'silver crop' },+ questions: [],+ interpretation: '',+ // A malformed field counts as absent rather than failing the answer.+ looks: 'not a list',+ }));+ expect(revision).not.toHaveProperty('looks');+ const { direction, missing } = mergeCastAndSetsDirection(previous, revision, { sections, moodImageCount: 4 });+ expect(missing).toEqual([]);+ expect(direction.protagonist).toMatchObject({ name: 'Nova', hair: 'silver crop', face: 'weathered', rules: ['No hats'] });+ expect(direction.looks).toEqual(previous.looks);+ expect(direction.sets).toEqual(previous.sets);+ expect(direction.logline).toBe('She escapes.');+ expect(direction.questions).toEqual([]);+ expect(direction.interpretation).toBe('');+ });+});diff --git a/server/services/musicVideo/castAndSetsPlan.js b/server/services/musicVideo/castAndSetsPlan.jsnew file mode 100644index 0000000000..a030780b1f--- /dev/null+++ b/server/services/musicVideo/castAndSetsPlan.js@@ -0,0 +1,293 @@+/**+ * Music Video — Cast & Sets image plan (pure): which reference images the+ * check-in needs, the prompt for each, what each one is conditioned on, which+ * ones a revision has to redo, and what the approved result becomes on the+ * project (visual-spec references + concept subjects).+ *+ * The prompts generalize the hand-made check-in's templates:+ * - `character` — the canonical five-view character sheet. First, and every+ * image of the protagonist after it uses it as reference #1.+ * Its own references are the mood-board images the+ * direction picked.+ * - `expressions` — a 2×3 expression sheet including the signature gesture.+ * - `looks` — the wardrobe lookbook, one panel per look.+ * - `set:<id>` — one EMPTY plate per set (no people), conditioned on the+ * mood board for look only; plates do not depend on the+ * character, so they render alongside it.+ * - `test:<n>` — the protagonist in a set: conditioned on that set's plate,+ * the character sheet and the looks sheet.+ */++import { trimTo } from '../../lib/textUtils.js';+import { songSections } from './castAndSetsDirection.js';++export const CAST_SETS_IMAGE_SIZE = Object.freeze({ width: 1536, height: 1024 });+// Mirrors MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES / the visual spec's list cap.+const MAX_CONDITIONING = 4;+const MAX_REFERENCES = 24;+const MAX_SUBJECTS = 24;+export const CAST_SETS_REF_PREFIX = 'mvr-cs-';+export const CAST_SETS_SUBJECT_PREFIX = 'cs-';++// Only the medium is fixed; the look (film stock, light, texture) comes from+// the project's own mood board / style via `direction.look`.+const PHOTO = 'photorealistic, editorial photography';+const sentence = (s) => {+ const t = String(s || '').trim();+ return t && !/[.!?]$/.test(t) ? `${t}.` : t;+};+const join = (...parts) => parts.map(sentence).filter(Boolean).join(' ');++function identity(p) {+ return [p.face && `face: ${p.face}`, p.hair && `hair: ${p.hair}`].filter(Boolean).join('; ');+}++function rulesLine(p) {+ return (p.rules || []).length ? `Rules: ${p.rules.join('; ')}` : '';+}++/** How much of the song each set covers, in seconds (for ordering / conditioning). */+export function setCoverage(project, direction) {+ const sections = songSections(project);+ const bySection = new Map(sections.map((s) => [s.index, s.endSec - s.startSec]));+ const cover = new Map((direction?.sets || []).map((s) => [s.id, 0]));+ for (const entry of direction?.songMap || []) {+ if (cover.has(entry.setId)) cover.set(entry.setId, cover.get(entry.setId) + (bySection.get(entry.section) || 0));+ }+ return cover;+}++/** The in-set tests to render: the direction's own, topped up to two from the most-used sets. */+export function plannedTests(project, direction) {+ const tests = (direction?.tests || []).slice(0, 4);+ if (tests.length >= 2) return tests;+ const cover = setCoverage(project, direction);+ const ranked = [...(direction?.sets || [])].sort((a, b) => (cover.get(b.id) || 0) - (cover.get(a.id) || 0));+ const look = direction?.looks?.[0]?.name || '';+ for (const set of ranked) {+ if (tests.length >= 2) break;+ if (tests.some((t) => t.setId === set.id)) continue;+ tests.push({ setId: set.id, look, action: 'performing the song straight to camera', caption: set.sections?.[0] || set.name });+ }+ return tests;+}++/**+ * Build the full image plan for a direction: `{ [key]: { key, kind, label,+ * prompt, deps, refKeys, setId?, testIndex? } }`. `refKeys` name other plan+ * keys whose image is passed as a reference (in order); `moodRefs` adds the+ * chosen mood-board images. A revision note for a key is appended to its prompt.+ */+export function buildCastAndSetsImagePlan(project, direction, { revisionNotes = {} } = {}) {+ const p = direction.protagonist || {};+ const looks = direction.looks || [];+ const firstLook = looks[0];+ const style = trimTo(direction.look, 500) || trimTo(project?.concept?.style, 500);+ const firstLight = direction.sets?.[0]?.lighting || '';+ const note = (key) => (revisionNotes[key] ? `Revision: ${revisionNotes[key]}` : '');+ const plan = {};++ plan.character = {+ key: 'character',+ kind: 'character',+ label: 'Character sheet',+ deps: [],+ refKeys: [],+ moodRefs: true,+ prompt: join(+ `Photographic character reference sheet of ONE consistent person, ${p.name || 'the protagonist'}: ${p.description || ''}`,+ identity(p),+ p.signature && `Signature detail, always visible: ${p.signature}`,+ firstLook && `Wearing ${firstLook.description}`,+ rulesLine(p),+ 'Five views on a seamless dark grey backdrop: FRONT, 3/4, PROFILE, BACK full-body, plus a FACE close-up, with small typewriter captions',+ style && `Look: ${style}`,+ `${PHOTO}, even studio light, lookbook realism`,+ note('character'),+ ),+ };++ plan.expressions = {+ key: 'expressions',+ kind: 'expressions',+ label: 'Expression sheet',+ deps: ['character'],+ refKeys: ['character'],+ prompt: join(+ 'Photographic expression sheet, 2 rows x 3 columns grid of tight close-ups of the SAME person as the character reference',+ identity(p),+ `Panels: 1) singing full-voice with mouth wide open, eyes closed; 2) whispering close to the lens; 3) sly half-smile, eyes locked on camera; 4) ${p.gesture || 'a signature gesture toward the camera'}; 5) fingertips at parted lips, eyes half-lidded; 6) head tilted back, eyes shut`,+ 'Consistent identity across all panels',+ firstLight && `Light: ${firstLight}`,+ style && `Look: ${style}`,+ `${PHOTO}, thin black gutters between panels, no text`,+ note('expressions'),+ ),+ };++ plan.looks = {+ key: 'looks',+ kind: 'looks',+ label: 'Looks',+ deps: ['character'],+ refKeys: ['character'],+ prompt: join(+ `Fashion lookbook sheet of the SAME person as the character reference, ${looks.length} full-body panels side by side`,+ identity(p),+ rulesLine(p),+ ...looks.map((l, i) => `LOOK 0${i + 1} ${l.name.toUpperCase()}: ${l.description}${p.signature ? `, with ${p.signature}` : ''}`),+ `Seamless dark grey backdrop, typewriter captions ${looks.map((l, i) => `LOOK 0${i + 1} ${l.name.toUpperCase()}`).join(', ')}`,+ style && `Look: ${style}`,+ `${PHOTO}, lookbook realism`,+ note('looks'),+ ),+ };++ for (const set of direction.sets || []) {+ const key = `set:${set.id}`;+ plan[key] = {+ key,+ kind: 'plate',+ label: set.name,+ setId: set.id,+ deps: [],+ refKeys: [],+ moodRefs: true,+ prompt: join(+ 'Empty set plate, no people',+ set.description,+ set.lighting && `Lighting: ${set.lighting}`,+ style && `Look: ${style}`,+ 'Photorealistic music video location still',+ note(key),+ ),+ };+ }++ plannedTests(project, direction).forEach((test, i) => {+ const set = (direction.sets || []).find((s) => s.id === test.setId);+ const look = looks.find((l) => l.name === test.look) || firstLook;+ const key = `test:${i + 1}`;+ plan[key] = {+ key,+ kind: 'test',+ label: test.caption || set?.name || `Test ${i + 1}`,+ setId: test.setId,+ testIndex: i,+ deps: ['character', `set:${test.setId}`, 'looks'].filter((k) => plan[k]),+ refKeys: [`set:${test.setId}`, 'character', 'looks'].filter((k) => plan[k]),+ prompt: join(+ `Photorealistic music video still, wide 16:9. Recreate the ${set?.name || 'set'} from the set plate reference, same camera angle and light`,+ `Place the person from the character sheet in it (${identity(p)})`,+ look && `Wearing ${look.description}`,+ test.action,+ set?.lighting && `Light: ${set.lighting}`,+ style && `Look: ${style}`,+ note(key),+ ),+ };+ });++ return plan;+}++/**+ * The plan keys a revised direction must re-render: a key whose prompt or+ * references changed, plus everything that depends on a re-rendered key.+ * `force` adds keys the director flagged directly.+ */+export function affectedImageKeys(previousPlan, nextPlan, force = []) {+ const out = new Set(force.filter((k) => nextPlan[k]));+ for (const [key, item] of Object.entries(nextPlan)) {+ const before = previousPlan?.[key];+ if (!before || before.prompt !== item.prompt || before.refKeys.join('|') !== item.refKeys.join('|')) out.add(key);+ }+ let grew = true;+ while (grew) {+ grew = false;+ for (const [key, item] of Object.entries(nextPlan)) {+ if (!out.has(key) && item.deps.some((d) => out.has(d))) { out.add(key); grew = true; }+ }+ }+ return [...out];+}++/** Map a note target ('character', 'set:<id>', 'test:2', 'looks', …) to plan keys; null for a direction-level note. */+export function noteImageKeys(target, plan) {+ if (!target) return null;+ const t = String(target).trim().toLowerCase();+ if (plan[t]) return [t];+ if (t === 'protagonist' || t === 'cast') return ['character'];+ if (t === 'wardrobe') return ['looks'];+ if (t === 'expression') return ['expressions'];+ const bySetName = Object.values(plan).find((item) => item.kind === 'plate' && item.label.toLowerCase() === t);+ return bySetName ? [bySetName.key] : null;+}++// ---- applying an approved result ---------------------------------------------++/**+ * The visual-spec references the approved check-in contributes: the character+ * sheet (conditioning) first, then set plates by song coverage (conditioning+ * while the backend's reference cap allows, after any the director flagged+ * themselves), then the looks and expression sheets as unconditioned+ * reference. Replaces any earlier Cast & Sets references; keeps the director's.+ */+export function castAndSetsReferences(project, stage) {+ const existing = (project?.visualSpec?.references || []).filter((r) => !String(r.id || '').startsWith(CAST_SETS_REF_PREFIX));+ let budget = Math.max(0, MAX_CONDITIONING - existing.filter((r) => r.condition).length);+ let room = Math.max(0, MAX_REFERENCES - existing.length);+ const images = stage?.images || {};+ const direction = stage?.direction || {};+ const out = [];+ const push = (ref, wantsCondition) => {+ if (!ref.imageId || room <= 0) return;+ const condition = wantsCondition && budget > 0;+ if (condition) budget -= 1;+ room -= 1;+ out.push({ ...ref, condition, use: 'reference' });+ };+ const p = direction.protagonist || {};+ push({ id: `${CAST_SETS_REF_PREFIX}character`, imageId: images.character?.imageId, role: 'character', label: `${p.name || 'Protagonist'} — character sheet`, note: trimTo([p.face, p.hair, p.signature].filter(Boolean).join('; '), 1000) }, true);+ const cover = setCoverage(project, direction);+ const plates = [...(direction.sets || [])].sort((a, b) => (cover.get(b.id) || 0) - (cover.get(a.id) || 0));+ for (const set of plates) {+ push({ id: `${CAST_SETS_REF_PREFIX}set-${set.id}`.slice(0, 64), imageId: images[`set:${set.id}`]?.imageId, role: 'set', label: trimTo(set.name, 120), note: trimTo([set.description, set.lighting].filter(Boolean).join(' — '), 1000) }, true);+ }+ push({ id: `${CAST_SETS_REF_PREFIX}looks`, imageId: images.looks?.imageId, role: 'wardrobe', label: 'Looks', note: trimTo((direction.looks || []).map((l) => l.name).join(', '), 1000) }, false);+ push({ id: `${CAST_SETS_REF_PREFIX}expressions`, imageId: images.expressions?.imageId, role: 'character', label: 'Expression sheet', note: trimTo(p.gesture, 1000) }, false);+ return [...existing, ...out];+}++/**+ * The concept subjects the check-in seeds: the protagonist and one place per+ * set. A subject the director authored (any id outside the `cs-` namespace)+ * is never replaced, and a Cast & Sets subject whose name matches one of the+ * director's is left out rather than duplicated.+ */+export function castAndSetsSubjects(project, stage) {+ const authored = (project?.concept?.subjects || []).filter((s) => !String(s.id || '').startsWith(CAST_SETS_SUBJECT_PREFIX));+ const taken = new Set(authored.map((s) => `${s.kind}:${String(s.name || '').trim().toLowerCase()}`));+ const direction = stage?.direction || {};+ const p = direction.protagonist || {};+ const ours = [];+ if (p.name) {+ ours.push({+ id: `${CAST_SETS_SUBJECT_PREFIX}protagonist`,+ kind: 'character',+ name: trimTo(p.name, 120),+ description: trimTo([p.description, p.face, p.hair, p.signature].filter(Boolean).join('; '), 1000),+ role: 'protagonist',+ });+ }+ for (const set of direction.sets || []) {+ ours.push({+ id: `${CAST_SETS_SUBJECT_PREFIX}set-${set.id}`.slice(0, 64),+ kind: 'place',+ name: trimTo(set.name, 120),+ description: trimTo([set.description, set.lighting && `Light: ${set.lighting}`].filter(Boolean).join(' '), 1000),+ });+ }+ const fresh = ours.filter((s) => s.name && !taken.has(`${s.kind}:${s.name.toLowerCase()}`));+ return [...authored, ...fresh].slice(0, MAX_SUBJECTS);+}diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsnew file mode 100644index 0000000000..e75f90b71b--- /dev/null+++ b/server/services/musicVideo/castAndSetsService.js@@ -0,0 +1,528 @@+/**+ * Music Video — Cast & Sets check-in orchestrator.+ *+ * Runs the stage whose record transforms live in castAndSets.js:+ *+ * 1. direction — one provider call (castAndSetsDirection.js) through the+ * shared runner, outside the write lock, against a snapshot;+ * 2. images — the reference images of castAndSetsPlan.js, enqueued on+ * the normal image queue with a `musicVideo.castAndSets` tag+ * so the completion hook (musicVideoCastSetsImageHook.js)+ * files each result back here; a key is dispatched only once+ * every image it is conditioned on has landed;+ * 3. sheet — castAndSetsSheet.js, saved as a `cast-sets` development+ * artifact (a new version on every regeneration);+ * 4. check-in — `review` (default) waits for the director; `auto` approves.+ *+ * Approval writes the result into the project: the character sheet and set+ * plates become visual-spec references (conditioning frame generation), the+ * protagonist and sets become concept subjects. A production run waiting on the+ * stage re-bases its creative-setup checksum in the same write and continues.+ *+ * Everything is started by the director (Start / Regenerate / Resume, or a+ * production run they started). Nothing here runs at boot: the image hook only+ * files completions of jobs that were already queued, and a stage pinned to a+ * previous process dispatches nothing until it is resumed.+ */++import { randomUUID } from 'crypto';+import { readFile } from 'fs/promises';+import { extname } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { QUEUEABLE_IMAGE_MODES } from '../../lib/generationModes.js';+import { resolveGalleryImage, resolveImageRef } from '../../lib/pathSafety.js';+import { RENDER_TARGET } from '../../lib/renderTargets.js';+import { trimTo } from '../../lib/textUtils.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';+import {+ allCastAndSetsImagesDone,+ assertCastAndSetsApprovable,+ castAndSetsCheckinMode,+ dispatchableImageKeys,+ linkCastAndSetsJob,+ presentCastAndSets,+ reserveCastAndSetsImage,+ resumeCastAndSetsOnProject,+ reviseCastAndSetsOnProject,+ setCastAndSetsDirection,+ setCastAndSetsStatus,+ settleCastAndSetsImage,+ startCastAndSetsOnProject,+} from './castAndSets.js';+import {+ buildCastAndSetsPrompt,+ mergeCastAndSetsDirection,+ moodBoardImageList,+ parseCastAndSetsResponse,+ songSections,+} from './castAndSetsDirection.js';+import {+ CAST_SETS_IMAGE_SIZE,+ affectedImageKeys,+ buildCastAndSetsImagePlan,+ castAndSetsReferences,+ castAndSetsSubjects,+ noteImageKeys,+} from './castAndSetsPlan.js';+import { renderCastAndSetsSheet } from './castAndSetsSheet.js';+import { findDevArtifact, reviewDevArtifact, resolveDevArtifactNotes } from './devArtifacts.js';+import { rebaseProductionAfterCheckin } from './production.js';++const PROCESS_ID = `proc-${randomUUID()}`;+const short = (id) => String(id || '').slice(3, 11);+const MAX_KEY_NOTES = 8;++// Test seam: provider, queue, settings and mood-board access are swappable.+const defaults = {+ resolveProvider: async (opts) => (await import('../promptRunner.js')).resolveProviderAndModel(opts),+ runPrompt: async (opts) => (await import('../promptRunner.js')).runPromptThroughProvider(opts),+ getSettings: async () => (await import('../settings.js')).getSettings(),+ enqueue: async (job) => (await import('../mediaJobQueue/index.js')).enqueueJob(job),+ loadBoard: async (id) => (await import('../moodBoard/index.js')).getBoard(id),+ boardItemImage: async () => (await import('../moodBoard/logic.js')).boardItemLocalImage,+ loadTrack: async (id) => (await import('../tracks/index.js')).getTrack(id),+ readImage: (path) => readFile(path),+ imageParams: (settings, route, common) => imageJobParams(settings, route, common),+ resolveRoute: null,+};+let deps = { ...defaults };+export function __setCastAndSetsDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }+export const __castAndSetsProcessId = () => PROCESS_ID;++async function requireProject(id) {+ const project = await getProject(id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}++function publish(projectId, project) {+ musicVideoEvents.emit('cast-and-sets', {+ projectId,+ stage: presentCastAndSets(project?.castAndSets, PROCESS_ID),+ project,+ });+}++async function fail(projectId, reason, error = null) {+ const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsStatus(current, 'failed', { reason, error }));+ console.error(`❌ Music Video Cast & Sets ${short(projectId)} failed: ${reason}`);+ publish(projectId, out.project);+ return out;+}++// ---- route choice -------------------------------------------------------------++/**+ * The image route: a production run's pool route when one is given; otherwise+ * Codex when the brief allows it (or names no image tool) and it is enabled,+ * then the brief's other queueable image tools in catalog order, then the+ * install's Music Video render default. Returns `{ mode, model }` or null.+ */+async function chooseCastAndSetsRoute(project, { preferred = null, settings } = {}) {+ if (deps.resolveRoute) return deps.resolveRoute(project, { preferred, settings });+ const { resolveRenderTargetConfig } = await import('../imageGen/cloudProviderConfig.js');+ // A mode is usable when it rides the queue and, for a cloud backend, its+ // opt-in toggle is on (the same resolver the dispatch itself goes through).+ const usable = (mode) => {+ if (!QUEUEABLE_IMAGE_MODES.includes(mode)) return false;+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, { mode });+ return resolved.mode === mode && (!resolved.cloud || resolved.cloud.enabled);+ };+ if (preferred?.mode) return usable(preferred.mode) ? { mode: preferred.mode, model: preferred.model || null } : null;+ const tools = (project?.automation?.tools || []).filter((t) => t.startsWith('image:')).map((t) => t.slice('image:'.length));+ const candidates = tools.length ? tools : ['codex'];+ if (candidates.includes('codex') && usable('codex')) return { mode: 'codex', model: null };+ const listed = candidates.find((mode) => mode !== 'codex' && usable(mode));+ if (listed) return { mode: listed, model: null };+ if (tools.length) return null;+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, {});+ return usable(resolved.mode) ? { mode: resolved.mode, model: null } : null;+}++// ---- direction ------------------------------------------------------------------++async function loadContext(project) {+ const boardId = project?.visualSpec?.moodBoardId;+ const board = boardId ? await deps.loadBoard(boardId).catch(() => null) : null;+ const resolveItem = board ? await deps.boardItemImage() : null;+ const moodImages = board ? moodBoardImageList(board, resolveItem) : [];+ const track = project?.trackId ? await deps.loadTrack(project.trackId).catch(() => null) : null;+ return { board, moodImages, track };+}++/**+ * Run the direction call for the stage's current revision and write the image+ * plan. `notes` (a revision) are sent with the current direction; `forceKeys`+ * are image keys the director flagged directly.+ */+async function runDirection(projectId, { providerId, model, notes = [], forceKeys = [] } = {}) {+ const project = await requireProject(projectId);+ const stage = project.castAndSets;+ const { board, moodImages, track } = await loadContext(project);+ const { provider, selectedModel } = await deps.resolveProvider({ providerId, model }).catch(() => ({ provider: null }));+ if (!provider) return fail(projectId, 'No AI provider is available for the creative direction');+ if (provider.enabled === false) return fail(projectId, `The ${provider.name || provider.id} provider is disabled`);+ const previous = stage?.direction || null;+ const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes });+ let text;+ try {+ ({ text } = await deps.runPrompt({ provider, model: selectedModel, prompt, source: 'music-video-cast-sets' }));+ } catch (err) {+ return fail(projectId, 'The creative direction call failed', err.message);+ }+ const parsed = parseCastAndSetsResponse(text);+ if (!parsed) return fail(projectId, 'The creative direction answer had no usable JSON');+ const sections = songSections(project);+ const { direction, missing } = mergeCastAndSetsDirection(notes.length ? previous : null, parsed, { sections, moodImageCount: moodImages.length });+ if (missing.length) return fail(projectId, `The creative direction answer is missing: ${missing.join(', ')}`);+ // The photographic look every image prompt carries: the mood board's composed+ // style, else the project's visual style (never the board's literal places).+ direction.look = trimTo(board?.style?.prompt, 500) || trimTo(project.concept?.style, 500) || previous?.look || '';+ // The model picks the mood-board references; with none picked, the first+ // images of the board stand in so the character sheet still has a look.+ const picked = direction.moodRefs.length ? direction.moodRefs : moodImages.map((_, i) => i).slice(0, 3);+ const chosen = picked.map((i) => moodImages[i]).filter(Boolean).map(({ kind, filename }) => ({ kind, filename }));+ return writePlan(projectId, { direction, moodImages: chosen, forceKeys });+}++/** (Re)build the plan from the stage's direction + accumulated per-image notes, then dispatch. */+async function writePlan(projectId, { direction = null, moodImages = null, forceKeys = [] } = {}) {+ const project = await requireProject(projectId);+ const stage = project.castAndSets;+ const nextDirection = direction || stage.direction;+ const plan = buildCastAndSetsImagePlan(project, nextDirection, { revisionNotes: keyNotesText(stage.keyNotes) });+ const renderKeys = affectedImageKeys(stage.plan || {}, plan, forceKeys);+ const settings = await deps.getSettings();+ const run = stage.productionRunId ? (project.productionRuns || []).find((r) => r.id === stage.productionRunId) : null;+ const preferred = run?.pool?.find((r) => r.kind === 'image') || stage.route || null;+ const route = await chooseCastAndSetsRoute(project, { preferred, settings });+ if (!route) return fail(projectId, 'No enabled image backend is allowed for the Cast & Sets images — enable Codex (or another image tool in the brief) and resume');+ const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsDirection(current, {+ direction: nextDirection, plan, moodImages, route, renderKeys,+ }));+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} r${out.stage.revision}: ${renderKeys.length} image(s) to render on ${route.mode}`);+ publish(projectId, out.project);+ return advance(projectId);+}++const keyNotesText = (keyNotes = {}) => Object.fromEntries(Object.entries(keyNotes).map(([k, list]) => [k, list.join('; ')]));++// ---- images -----------------------------------------------------------------------++function referencePaths(stage, item) {+ const paths = [];+ for (const key of item.refKeys || []) {+ const id = stage.images?.[key]?.imageId;+ const path = id ? resolveGalleryImage(id, { mustExist: false }) : null;+ if (path) paths.push(path);+ }+ if (item.moodRefs) {+ for (const ref of stage.moodImages || []) {+ if (paths.length >= 4) break;+ const path = ref.kind === 'image-ref' ? resolveImageRef(ref.filename, { mustExist: false }) : resolveGalleryImage(ref.filename, { mustExist: false });+ if (path) paths.push(path);+ }+ }+ return paths.slice(0, 4);+}++/** Job params for one image on the stage's route (cloud provider bag or the local model). */+async function imageJobParams(settings, route, common) {+ const [{ resolveRenderTargetConfig }, { resolveImageCleaners }, { resolveLocalImageModel }] = await Promise.all([+ import('../imageGen/cloudProviderConfig.js'),+ import('../imageGen/index.js'),+ import('../imageGen/prepareParams.js'),+ ]);+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, { mode: route.mode, model: route.model });+ // Never substitute another backend for the one the stage chose.+ if (resolved.mode !== route.mode) throw new ServerError(`The ${route.mode} image backend is not available`, { status: 409, code: 'CAST_SETS_ROUTE_UNAVAILABLE' });+ if (resolved.cloud && !resolved.cloud.enabled) throw resolved.cloud.disabledError;+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, route.mode);+ if (resolved.cloud) return { ...resolved.cloud.jobParams, ...common, cleanC2PA, denoise };+ const { pythonPath, selectedModel } = resolveLocalImageModel(settings, { modelId: route.model || undefined });+ return { ...common, cleanC2PA, denoise, pythonPath, ...(selectedModel?.id ? { modelId: selectedModel.id } : {}) };+}++async function enqueueImage(project, stage, key) {+ const item = stage.plan[key];+ const referenceImagePaths = referencePaths(stage, item);+ const common = {+ prompt: item.prompt,+ width: CAST_SETS_IMAGE_SIZE.width,+ height: CAST_SETS_IMAGE_SIZE.height,+ ...(referenceImagePaths.length ? { referenceImagePaths, referenceImageStrengths: referenceImagePaths.map(() => 1) } : {}),+ // The completion hook files the result by this tag. No `sceneId`, so the+ // scene-frame hook ignores the job.+ musicVideo: { projectId: project.id, castAndSets: { key, revision: stage.revision } },+ };+ const params = await deps.imageParams(await deps.getSettings(), stage.route, common);+ return deps.enqueue({ kind: 'image', params, owner: `music-video-cast-sets:${project.id}` });+}++async function dispatchKey(projectId, key) {+ const reserved = await mutateProjectRecord(projectId, (current) => reserveCastAndSetsImage(current, key, { processId: PROCESS_ID }))+ .catch((err) => ({ error: err }));+ if (reserved.error) {+ if (['CAST_SETS_IMAGE_BUSY', 'CAST_SETS_NOT_RUNNING'].includes(reserved.error.code)) return;+ throw reserved.error;+ }+ const sent = await enqueueImage(reserved.project, reserved.stage, key).catch((err) => ({ error: err }));+ if (sent?.error || !sent?.jobId) {+ const reason = sent?.error?.message || 'The image job was not queued';+ const out = await mutateProjectRecord(projectId, (current) => settleCastAndSetsImage(current, key, { error: reason }));+ console.warn(`⚠️ Music Video Cast & Sets ${short(projectId)} ${key} refused: ${reason}`);+ publish(projectId, out.project);+ return;+ }+ await mutateProjectRecord(projectId, (current) => linkCastAndSetsJob(current, key, sent.jobId));+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} ${key} → ${reserved.stage.route.mode} job ${String(sent.jobId).slice(0, 8)}`);+}++const advancing = new Map();++/**+ * Dispatch every image whose inputs are ready; assemble the sheet once every+ * image is done. Concurrent calls for one project coalesce.+ */+function advance(projectId) {+ const live = advancing.get(projectId);+ if (live) { live.again = true; return live.promise; }+ const entry = { again: false, promise: null };+ entry.promise = (async () => {+ try {+ do {+ entry.again = false;+ await advanceOnce(projectId);+ } while (entry.again);+ } finally {+ advancing.delete(projectId);+ }+ })();+ advancing.set(projectId, entry);+ return entry.promise;+}++async function advanceOnce(projectId) {+ const project = await requireProject(projectId);+ const stage = project.castAndSets;+ if (!stage || stage.processId !== PROCESS_ID || stage.status !== 'imaging') return;+ if (allCastAndSetsImagesDone(stage)) {+ await assemble(projectId);+ return;+ }+ const keys = dispatchableImageKeys(stage);+ for (const key of keys) await dispatchKey(projectId, key);+ if (keys.length) publish(projectId, await requireProject(projectId));+}++function inBackground(label, projectId, fn) {+ Promise.resolve().then(fn).catch(async (err) => {+ console.error(`❌ Music Video Cast & Sets ${short(projectId)} ${label} failed: ${err.message}`);+ await fail(projectId, `${label} failed: ${err.message}`).catch(() => {});+ });+}++// ---- sheet ----------------------------------------------------------------------------++const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };++async function embeddedImages(stage) {+ const out = {};+ for (const [key, img] of Object.entries(stage.images || {})) {+ const path = img.imageId ? resolveGalleryImage(img.imageId, { mustExist: false }) : null;+ const mime = path ? MIME[extname(path).toLowerCase()] : null;+ if (!path || !mime) continue;+ const bytes = await deps.readImage(path).catch(() => null);+ if (bytes) out[key] = `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`;+ }+ return out;+}++/** Build the sheet, save it as the stage's development artifact, then check in. */+async function assemble(projectId) {+ const marked = await mutateProjectRecord(projectId, (current) => setCastAndSetsStatus(current, 'assembling'));+ publish(projectId, marked.project);+ const project = marked.project;+ const stage = marked.stage;+ const mode = castAndSetsCheckinMode(project);+ const html = renderCastAndSetsSheet({+ title: project.name,+ project,+ direction: stage.direction,+ images: await embeddedImages(stage),+ sections: songSections(project),+ durationSec: project.audioAnalysis?.durationSec ?? null,+ bpm: project.audioAnalysis?.bpm ?? null,+ revision: stage.revision,+ notesApplied: stage.notesApplied || [],+ checkinMode: mode,+ status: mode === 'auto' ? 'approved' : 'review',+ });+ const { saveGeneratedDevArtifact } = await import('./devArtifactService.js');+ const existing = stage.artifactId && (project.devArtifacts || []).some((a) => a.id === stage.artifactId && !a.deleted) ? stage.artifactId : null;+ const { artifact } = await saveGeneratedDevArtifact(projectId, {+ artifactId: existing,+ kind: 'cast-sets',+ title: `Cast & Sets — ${stage.direction?.protagonist?.name || project.name}`,+ html,+ source: 'cast-and-sets',+ });+ const out = await mutateProjectRecord(projectId, (current) => setCastAndSetsStatus(current, 'review', {+ extra: { artifactId: artifact.id, artifactVersion: artifact.version },+ }));+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} sheet v${artifact.version} ready (${mode === 'auto' ? 'auto-approve' : 'waiting for check-in'})`);+ if (mode === 'auto') return approveCastAndSets(projectId);+ publish(projectId, out.project);+ return out;+}++// ---- approval ------------------------------------------------------------------------++/**+ * Apply an approved check-in to the project (references, subjects), approve+ * its artifact, and re-base a production run that was waiting on it.+ */+function applyApproval(project, now) {+ const stage = project.castAndSets;+ let next = {+ ...project,+ visualSpec: {+ references: [], palette: [], typography: '', cameraRules: '', moodBoardId: null,+ ...(project.visualSpec || {}),+ references: castAndSetsReferences(project, stage),+ },+ concept: { ...(project.concept || {}), subjects: castAndSetsSubjects(project, stage) },+ };+ if (stage.artifactId && (next.devArtifacts || []).some((a) => a.id === stage.artifactId && !a.deleted)) {+ next = reviewDevArtifact(next, stage.artifactId, { status: 'approved' }, now).project;+ }+ return setCastAndSetsStatus(next, 'approved', {}, now);+}++// Settle the stage and re-base a production run waiting on it, in ONE write,+// so the run never observes the new references without its new basis.+const settleAndRebase = (next, now) => {+ const { project } = rebaseProductionAfterCheckin(next.project, now);+ return { project, stage: project.castAndSets };+};++/** Approve & continue. Returns `{ project, stage }`. */+export async function approveCastAndSets(projectId) {+ const now = new Date().toISOString();+ const out = await mutateProjectRecord(projectId, (current) => {+ assertCastAndSetsApprovable(current);+ return settleAndRebase(applyApproval(current, now), now);+ });+ console.log(`✅ Music Video Cast & Sets ${short(projectId)} approved (r${out.stage.revision})`);+ publish(projectId, out.project);+ return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };+}++/** Skip the check-in (e.g. no image backend): the autopilot continues without it. */+export async function skipCastAndSets(projectId) {+ await requireProject(projectId);+ const now = new Date().toISOString();+ const out = await mutateProjectRecord(projectId, (current) => {+ const base = current.castAndSets ? current : { ...current, castAndSets: { revision: 0, images: {}, plan: {}, createdAt: now } };+ if (base.castAndSets.status === 'approved') throw new ServerError('The Cast & Sets check-in is already approved', { status: 409, code: 'CAST_SETS_EXISTS' });+ // A skip also releases work in flight for it: this process stops dispatching.+ return settleAndRebase(setCastAndSetsStatus(base, 'skipped', { reason: 'Skipped by the director' }, now), now);+ });+ console.log(`⏭️ Music Video Cast & Sets ${short(projectId)} skipped`);+ publish(projectId, out.project);+ return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };+}++// ---- director actions ------------------------------------------------------------------++/** Start the check-in (explicit request). The work continues in the background. */+export async function startCastAndSets(projectId, { providerId, model, productionRunId = null } = {}) {+ const project = await requireProject(projectId);+ if (!Array.isArray(project.audioAnalysis?.sections) || !project.audioAnalysis.sections.length) {+ throw new ServerError('Analyze the song before the Cast & Sets check-in', { status: 409, code: 'NOT_ANALYZED' });+ }+ const out = await mutateProjectRecord(projectId, (current) => startCastAndSetsOnProject(current, { processId: PROCESS_ID, productionRunId }));+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} started (r${out.stage.revision})`);+ publish(projectId, out.project);+ inBackground('The creative direction', projectId, () => runDirection(projectId, { providerId, model }));+ return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };+}++/**+ * Regenerate with notes. `notes` default to the open notes on the stage's+ * sheet. A note aimed at an image (`character`, `looks`, `set:<id>`,+ * `test:<n>`, …) re-renders that image and what depends on it; any other+ * note revises the direction, and only images whose prompt changed re-render.+ * The consumed notes are resolved on the sheet. Returns `{ project, stage }`.+ */+export async function regenerateCastAndSets(projectId, { notes = null, providerId, model } = {}) {+ const project = await requireProject(projectId);+ const stage = project.castAndSets;+ if (!stage?.direction) throw new ServerError('There is no Cast & Sets sheet to regenerate yet', { status: 409, code: 'CAST_SETS_NO_DIRECTION' });+ const artifact = stage.artifactId ? (() => { try { return findDevArtifact(project, stage.artifactId); } catch { return null; } })() : null;+ const source = Array.isArray(notes) ? notes : (artifact?.notes || []).filter((n) => !n.resolvedAt);+ if (!source.length) throw new ServerError('Add a note first — nothing says what to change', { status: 422, code: 'CAST_SETS_NO_NOTES' });+ const imageNotes = {};+ const directionNotes = [];+ for (const note of source) {+ const keys = noteImageKeys(note.target, stage.plan || {});+ if (keys) keys.forEach((k) => { imageNotes[k] = [...(imageNotes[k] || []), note.text]; });+ else directionNotes.push(note);+ }+ const redirect = directionNotes.length > 0;+ const consumed = new Set(source.map((n) => n.id).filter(Boolean));+ const out = await mutateProjectRecord(projectId, (current) => {+ const revised = reviseCastAndSetsOnProject(current, { processId: PROCESS_ID, notesApplied: source, redirect });+ const keyNotes = { ...(revised.stage.keyNotes || {}) };+ for (const [k, list] of Object.entries(imageNotes)) keyNotes[k] = [...(keyNotes[k] || []), ...list].slice(-MAX_KEY_NOTES);+ let next = { ...revised.project, castAndSets: { ...revised.stage, keyNotes } };+ if (artifact && consumed.size) next = resolveDevArtifactNotes(next, artifact.id, (n) => consumed.has(n.id)).project;+ return { project: next, stage: next.castAndSets };+ });+ console.log(`🎭 Music Video Cast & Sets ${short(projectId)} regenerating r${out.stage.revision} (${source.length} note(s)${redirect ? ', new direction' : ''})`);+ publish(projectId, out.project);+ const forceKeys = Object.keys(imageNotes);+ inBackground('The regeneration', projectId, () => (redirect+ ? runDirection(projectId, { providerId, model, notes: directionNotes, forceKeys })+ : writePlan(projectId, { forceKeys })));+ 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 } = {}) {+ const out = await mutateProjectRecord(projectId, (current) => resumeCastAndSetsOnProject(current, { processId: PROCESS_ID }));+ console.log(`▶️ Music Video Cast & Sets ${short(projectId)} resumed (${out.stage.status})`);+ publish(projectId, out.project);+ inBackground('The resume', projectId, () => {+ if (out.stage.status === 'directing') return runDirection(projectId, { providerId, model, notes: out.stage.notesApplied || [] });+ if (out.stage.status === 'assembling') return assemble(projectId);+ return advance(projectId);+ });+ return { project: out.project, stage: presentCastAndSets(out.stage, PROCESS_ID) };+}++/** The stage as the director sees it. */+export async function getCastAndSets(projectId) {+ const project = await requireProject(projectId);+ return { stage: presentCastAndSets(project.castAndSets, PROCESS_ID) };+}++// ---- completion hook entry points ----------------------------------------------------------++/**+ * A tagged image job ended. `filename` = it rendered; otherwise `error`.+ * Settles its key (idempotent) and, when the stage is dispatching in this+ * process, continues. Returns true when the record changed.+ */+export async function onCastAndSetsImageSettled({ projectId, key, jobId = null, filename = null, error = null }) {+ const project = await getProject(projectId);+ if (!project?.castAndSets?.images?.[key]) return false;+ const out = await mutateProjectRecord(projectId, (current) => settleCastAndSetsImage(current, key, { jobId, filename, error }));+ if (!out.changed) return false;+ publish(projectId, out.project);+ if (out.stage?.processId === PROCESS_ID && out.stage.status === 'imaging') {+ advance(projectId).catch((err) => console.error(`❌ Music Video Cast & Sets ${short(projectId)} could not continue: ${err.message}`));+ }+ return true;+}diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.jsnew file mode 100644index 0000000000..aee60146af--- /dev/null+++ b/server/services/musicVideo/castAndSetsService.test.js@@ -0,0 +1,245 @@+/**+ * Music Video Cast & Sets check-in — the whole stage through the real router,+ * castAndSetsService.js and the real file-backed project store, with only the+ * provider call, the image queue and the mood-board store doubled: direction →+ * character sheet first → dependent images conditioned on it → the sheet saved+ * as a `cast-sets` development artifact → the check-in (review or auto) →+ * approval writing references and subjects → a regeneration re-rendering only+ * what a note touched.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-cast-sets-test-');+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const { default: musicVideoRoutes } = await import('../../routes/musicVideo.js');+const projects = await import('./projects.js');+const service = await import('./castAndSetsService.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++const IMAGES = () => join(ROOT(), 'images');+// 1x1 PNG.+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');++const DIRECTION = {+ logline: 'A lighthouse keeper signals a ship only she can see.',+ interpretation: 'The lyrics read as a vigil kept for someone lost at sea.',+ protagonist: {+ name: 'Keeper', description: 'the voice of the song', face: 'weathered, dark eyes', hair: 'long grey braid',+ signature: 'a brass lantern', gesture: 'raising the lantern on "light the way"', rules: ['No hats'],+ },+ looks: [{ name: 'Watch', description: 'oilskin coat, wool sweater', chapters: 'verses' }, { name: 'Storm', description: 'soaked dark sweater', chapters: 'chorus' }],+ sets: [+ { id: 'lab', name: 'Lamp room', description: 'a glass lantern room atop the tower', lighting: 'warm amber', sections: ['Verse'] },+ { id: 'harbor', name: 'Harbor', description: 'a wet stone quay', lighting: 'sodium orange', sections: [0] },+ { id: 'roof', name: 'Cliff', description: 'a rainy cliff edge', lighting: 'cold blue', sections: ['Outro'] },+ ],+ songMap: [{ section: 0, setId: 'harbor' }, { section: 1, setId: 'lab' }, { section: 2, setId: 'roof' }],+ tests: [{ setId: 'lab', look: 'Storm', action: 'trimming the wick', caption: 'the long night' }, { setId: 'harbor', look: 'Watch', action: 'walking the quay', caption: 'opener' }],+ overlayConcept: { summary: 'A tide clock.', elements: [{ name: 'Clock', description: 'turns every chorus' }] },+ moodRefs: [1],+ questions: ['Is she right?'],+};++let jobs;+const enqueue = vi.fn(async ({ params }) => {+ const id = `job-${jobs.length + 1}`;+ jobs.push({ id, params });+ return { jobId: id };+});+const runPrompt = vi.fn();+const board = {+ id: 'mb-1',+ style: { prompt: 'wet skin, raw flash, green light' },+ items: [+ { type: 'image', file: 'board-a.jpg', caption: 'a steamy kitchen', analysis: { prompt: 'flash photo, brass and steam' } },+ { type: 'image', file: 'board-b.jpg', caption: 'neon portrait' },+ { type: 'text', text: 'note' },+ ],+};++const keyOf = (job) => job.params.musicVideo.castAndSets.key;+const current = async (id) => projects.getProject(id);++async function until(check, label) {+ for (let i = 0; i < 200; i += 1) {+ if (await check()) return;+ await new Promise((r) => setTimeout(r, 5));+ }+ throw new Error(`timed out waiting for ${label}`);+}++/** Land every queued job whose key is in `keys` (all when omitted), as the image hook does. */+async function land(projectId, keys = null) {+ const pending = jobs.filter((j) => !j.landed && (!keys || keys.includes(keyOf(j))));+ for (const job of pending) {+ job.landed = true;+ const filename = `${job.id}.png`;+ writeFileSync(join(IMAGES(), filename), PNG);+ await service.onCastAndSetsImageSettled({ projectId, key: keyOf(job), jobId: job.id, filename });+ }+}++/** Land every image as it is queued until the stage reaches `status`. */+async function runTo(projectId, status) {+ for (let i = 0; i < 40; i += 1) {+ await new Promise((r) => setTimeout(r, 10));+ await land(projectId);+ if ((await current(projectId)).castAndSets?.status === status) return;+ }+ throw new Error(`the stage never reached ${status}`);+}++async function seed(overrides = {}) {+ return projects.createProject({+ name: 'Example Song',+ lyricCues: [{ text: 'light the way for me' }, { text: 'the tide is coming in' }],+ visualSpec: { moodBoardId: 'mb-1', references: [{ imageId: 'user-ref.png', role: 'mood', condition: true }] },+ concept: { prompt: 'an escape', subjects: [{ id: 's-band', kind: 'character', name: 'The Band' }] },+ ...overrides,+ }).then(async (p) => projects.setProjectAnalysis(p.id, {+ bpm: 120, beats: [], downbeats: [], durationSec: 30,+ sections: [{ label: 'Intro', startSec: 0, endSec: 8 }, { label: 'Verse', startSec: 8, endSec: 20 }, { label: 'Outro', startSec: 20, endSec: 30 }],+ }));+}++beforeEach(() => {+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });+ rmSync(join(ROOT(), 'music-video'), { recursive: true, force: true });+ mkdirSync(IMAGES(), { recursive: true });+ jobs = [];+ vi.clearAllMocks();+ runPrompt.mockResolvedValue({ text: `Here you go:\n\`\`\`json\n${JSON.stringify(DIRECTION)}\n\`\`\`` });+ service.__setCastAndSetsDepsForTests({+ resolveProvider: async () => ({ provider: { id: 'example-provider', enabled: true }, selectedModel: 'example-model' }),+ runPrompt,+ getSettings: async () => ({}),+ enqueue,+ imageParams: async (_settings, route, common) => ({ mode: route.mode, ...common }),+ resolveRoute: async () => ({ mode: 'codex', model: null }),+ loadBoard: async () => board,+ boardItemImage: async () => (item) => (item.type === 'image' ? { kind: 'image', filename: item.file } : null),+ loadTrack: async () => null,+ });+});+afterAll(cleanupTempDataRoots);++describe('Cast & Sets check-in', () => {+ it('directs, renders the character sheet first, builds the sheet, waits for review, and applies the approval', async () => {+ const project = await seed();+ const started = await request(app).post(`/api/music-video/${project.id}/cast-and-sets`).send({});+ expect(started.status).toBe(202);+ expect(started.body.stage).toMatchObject({ status: 'directing', revision: 1 });++ // The direction prompt interprets the song and treats the board as look only.+ await until(async () => jobs.length >= 4, 'the first images');+ const prompt = runPrompt.mock.calls[0][0].prompt;+ expect(prompt).toContain('light the way for me');+ expect(prompt).toMatch(/LOOK, LIGHTING, COLOR and TEXTURE only/);+ expect(prompt).toContain('0. a steamy kitchen — flash photo, brass and steam');+ expect(runPrompt.mock.calls[0][0].source).toBe('music-video-cast-sets');++ // First pass: the character sheet (conditioned on the mood image the+ // direction picked) and the empty plates, which depend on nothing.+ expect(jobs.map(keyOf).sort()).toEqual(['character', 'set:harbor', 'set:lab', 'set:roof']);+ const character = jobs.find((j) => keyOf(j) === 'character');+ expect(character.params.referenceImagePaths.map((p) => p.split(/[\\/]/).pop())).toEqual(['board-b.jpg']);+ expect(character.params).toMatchObject({ width: 1536, height: 1024, mode: 'codex', musicVideo: { projectId: project.id } });+ expect(character.params.prompt).toMatch(/FRONT, 3\/4, PROFILE, BACK/);++ await land(project.id, ['character']);+ await until(async () => jobs.some((j) => keyOf(j) === 'looks'), 'the looks sheet');+ const looks = jobs.find((j) => keyOf(j) === 'looks');+ expect(looks.params.referenceImagePaths.map((p) => p.split(/[\\/]/).pop())).toEqual([`${character.id}.png`]);+ expect(jobs.some((j) => keyOf(j).startsWith('test:'))).toBe(false);++ await land(project.id);+ await until(async () => jobs.filter((j) => keyOf(j).startsWith('test:')).length === 2, 'the in-set tests');+ const test1 = jobs.find((j) => keyOf(j) === 'test:1');+ const plateLab = jobs.find((j) => keyOf(j) === 'set:lab');+ expect(test1.params.referenceImagePaths.map((p) => p.split(/[\\/]/).pop())).toEqual([`${plateLab.id}.png`, `${character.id}.png`, `${looks.id}.png`]);++ await land(project.id);+ await until(async () => (await current(project.id)).castAndSets?.status === 'review', 'the check-in');+ const reviewing = await current(project.id);+ const artifact = reviewing.devArtifacts.find((a) => a.id === reviewing.castAndSets.artifactId);+ expect(artifact).toMatchObject({ kind: 'cast-sets', status: 'pending', version: 1 });+ const html = readFileSync(join(ROOT(), artifact.file), 'utf8');+ expect(html).toContain('Keeper');+ expect(html).toContain('data:image/png;base64,');+ // Nothing is applied before the director approves.+ expect(reviewing.visualSpec.references.map((r) => r.imageId)).toEqual(['user-ref.png']);++ // Approving the sheet from the artifact viewer is the stage's approval.+ const approved = await request(app).post(`/api/music-video/${project.id}/dev-artifacts/${artifact.id}/review`).send({ status: 'approved' });+ expect(approved.status).toBe(200);+ const done = await current(project.id);+ expect(done.castAndSets.status).toBe('approved');+ expect(done.devArtifacts[0].status).toBe('approved');+ const refs = done.visualSpec.references;+ expect(refs[0]).toMatchObject({ imageId: 'user-ref.png', condition: true });+ expect(refs.find((r) => r.id === 'mvr-cs-character')).toMatchObject({ role: 'character', condition: true });+ // Four conditioning slots: the director's own, the character sheet, then plates by song coverage.+ expect(refs.filter((r) => r.condition).map((r) => r.id)).toEqual([refs[0].id, 'mvr-cs-character', 'mvr-cs-set-lab', 'mvr-cs-set-roof']);+ expect(refs.find((r) => r.id === 'mvr-cs-set-harbor')).toMatchObject({ role: 'set', condition: false });+ expect(refs.find((r) => r.id === 'mvr-cs-looks')).toMatchObject({ role: 'wardrobe', condition: false });+ expect(done.concept.subjects.map((s) => [s.id, s.kind])).toEqual([+ ['s-band', 'character'], ['cs-protagonist', 'character'], ['cs-set-lab', 'place'], ['cs-set-harbor', 'place'], ['cs-set-roof', 'place'],+ ]);+ });++ it('regenerates only the images a note touches (and what depends on them) as a new sheet version', async () => {+ const project = await seed();+ await request(app).post(`/api/music-video/${project.id}/cast-and-sets`).send({});+ await runTo(project.id, 'review');+ const artifactId = (await current(project.id)).castAndSets.artifactId;+ await request(app).post(`/api/music-video/${project.id}/dev-artifacts/${artifactId}/notes`).send({ text: 'Make the braid shorter', target: 'character' });+ const before = jobs.length;++ const regen = await request(app).post(`/api/music-video/${project.id}/cast-and-sets/regenerate`).send({});+ expect(regen.status).toBe(202);+ await until(async () => jobs.length > before, 'the regenerated character');+ // No new direction call: the note names an image.+ expect(runPrompt).toHaveBeenCalledTimes(1);+ expect(jobs.slice(before).map(keyOf)).toEqual(['character']);+ expect(jobs.at(-1).params.prompt).toMatch(/Revision: Make the braid shorter/);+ await runTo(project.id, 'review');+ // Plates were not conditioned on the character, so they kept their images.+ expect(jobs.slice(before).map(keyOf).sort()).toEqual(['character', 'expressions', 'looks', 'test:1', 'test:2']);+ const after = await current(project.id);+ expect(after.castAndSets.revision).toBe(2);+ expect(after.devArtifacts[0]).toMatchObject({ version: 2, status: 'pending' });+ expect(after.devArtifacts[0].notes[0].resolvedAt).toBeTruthy();+ expect(after.castAndSets.images.character.history).toHaveLength(1);+ });++ it('approves itself in auto mode, and fails with a reason when no provider can direct', async () => {+ const auto = await seed({ automation: { tools: ['image:codex'], checkins: { castAndSets: 'auto' } } });+ await request(app).post(`/api/music-video/${auto.id}/cast-and-sets`).send({});+ await runTo(auto.id, 'approved');+ const approved = await current(auto.id);+ expect(approved.devArtifacts[0].status).toBe('approved');+ expect(approved.visualSpec.references.some((r) => r.id === 'mvr-cs-character')).toBe(true);++ service.__setCastAndSetsDepsForTests({ resolveProvider: async () => ({ provider: null }), loadBoard: async () => null, loadTrack: async () => null });+ const bare = await seed();+ await request(app).post(`/api/music-video/${bare.id}/cast-and-sets`).send({});+ await until(async () => (await current(bare.id)).castAndSets?.status === 'failed', 'the failure');+ expect((await current(bare.id)).castAndSets.stopReason).toMatch(/No AI provider/);+ // Skipping releases the autopilot without a sheet.+ const skipped = await request(app).post(`/api/music-video/${bare.id}/cast-and-sets/skip`).send({});+ expect(skipped.body.stage.status).toBe('skipped');+ });+});diff --git a/server/services/musicVideo/castAndSetsSheet.js b/server/services/musicVideo/castAndSetsSheet.jsnew file mode 100644index 0000000000..3e25897f12--- /dev/null+++ b/server/services/musicVideo/castAndSetsSheet.js@@ -0,0 +1,184 @@+/**+ * Music Video — the Cast & Sets check-in sheet (pure HTML generator).+ *+ * One self-contained page the director reviews before the storyboard: the+ * logline, the protagonist's facts beside the canonical character sheet, the+ * looks, the expression sheet, the in-set tests, every set plate with the song+ * sections it serves, a song-map bar colored by set, the overlay concept and+ * the questions that need an answer.+ *+ * Self-contained means no network: every image arrives as a `data:` URI from+ * the caller, the type uses system font stacks (no web fonts), and there is no+ * script. The PortOS viewer serves it into a sandboxed iframe under a CSP that+ * would block any external fetch anyway; the sheet is also meant to be saved+ * and opened on its own.+ */++import { plannedTests } from './castAndSetsPlan.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']);+const NEUTRAL = '#3b4a44';++export function escapeHtml(value) {+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+const e = escapeHtml;++const fmtTime = (sec) => {+ const s = Math.max(0, Number(sec) || 0);+ return `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;+};++// Only `data:image/*` sources are embedded; anything else renders as a+// placeholder so the file can never reach the network.+const safeSrc = (src) => (typeof src === 'string' && /^data:image\/(png|jpe?g|webp);base64,[A-Za-z0-9+/=]+$/.test(src) ? src : null);++function figure(src, alt, caption, cls = '') {+ const ok = safeSrc(src);+ const media = ok+ ? `<img src="${ok}" alt="${e(alt)}">`+ : `<div class="missing" role="img" aria-label="${e(alt)}">Image not rendered</div>`;+ return `<figure${cls ? ` class="${cls}"` : ''}>${media}${caption ? `<figcaption>${caption}</figcaption>` : ''}</figure>`;+}++const STYLE = `+:root{--bg:#0b0f0d;--panel:#131a17;--line:#26312c;--fg:#e7ece9;--muted:#9aa8a1;--accent:#ff5a1f;--green:#b8d63a;+--display:"Impact","Haettenschweiler","Arial Narrow Bold","Arial Narrow",sans-serif;+--body:"Helvetica Neue","Arial Narrow",Arial,sans-serif;--mono:ui-monospace,Menlo,Consolas,monospace;color-scheme:dark}+*{box-sizing:border-box}+body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--body);font-size:16px;line-height:1.55}+.wrap{max-width:1180px;margin:0 auto;padding:28px 20px 80px}+.hud{display:flex;flex-wrap:wrap;gap:8px 20px;font-family:var(--mono);font-size:12px;letter-spacing:.06em;color:var(--muted);text-transform:uppercase;border-bottom:1px solid var(--line);padding-bottom:10px}+.hud b{color:var(--accent);font-weight:500}+h1{font-family:var(--display);font-weight:900;font-size:clamp(48px,10vw,120px);line-height:.9;margin:28px 0 10px;letter-spacing:.01em;overflow-wrap:anywhere}+h2{font-family:var(--display);font-weight:700;font-size:clamp(28px,4.4vw,44px);line-height:1;margin:56px 0 6px;letter-spacing:.02em}+h2 small{display:block;font-family:var(--mono);font-size:12px;letter-spacing:.12em;color:var(--accent);margin-bottom:10px;text-transform:uppercase}+.lede{font-size:clamp(18px,2.2vw,22px);max-width:62ch;margin:0}+.sub{color:var(--muted);max-width:68ch}+.grid2{display:grid;grid-template-columns:1.1fr .9fr;gap:18px;margin-top:22px}+.grid2>*,.row>*,.sets>*,.overlay>*{min-width:0}+figure{margin:0}+figure img,.missing{display:block;width:100%;height:auto;border:1px solid var(--line)}+.missing{aspect-ratio:3/2;display:flex;align-items:center;justify-content:center;color:var(--muted);font-family:var(--mono);font-size:12px;background:var(--panel)}+figcaption{font-family:var(--mono);font-size:12px;color:var(--muted);padding-top:8px}+.facts{display:grid;grid-template-columns:auto 1fr;gap:6px 16px;font-size:15px;margin:0}+.facts dt{font-family:var(--mono);font-size:12px;color:var(--accent);text-transform:uppercase;letter-spacing:.08em;padding-top:3px}+.facts dd{margin:0}+.wide{margin-top:18px}+.row{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-top:18px}+.sets{display:grid;grid-template-columns:repeat(2,1fr);gap:18px;margin-top:20px}+.set figcaption{display:grid;gap:2px}+.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}+.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)}+.ticks{display:flex;justify-content:space-between;font-family:var(--mono);font-size:11px;color:var(--muted);margin-top:4px}+.tablewrap{overflow-x:auto;margin-top:16px}+table{border-collapse:collapse;width:100%;min-width:560px;font-size:14px}+td{border-top:1px solid var(--line);padding:9px 10px 9px 0;vertical-align:top}+td.tc{font-family:var(--mono);color:var(--muted);white-space:nowrap;width:64px}+.dot{display:inline-block;width:9px;height:9px;margin-right:8px;vertical-align:1px}+.overlay{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-top:18px}+.overlay>div{border:1px solid var(--line);background:var(--panel);padding:14px 16px}+.overlay h3{font-family:var(--mono);font-size:12px;letter-spacing:.1em;color:var(--accent);text-transform:uppercase;margin:0 0 6px;font-weight:500}+.overlay p{margin:0;font-size:14.5px}+.ask{border:1px solid var(--accent);padding:18px 20px;margin-top:22px;background:var(--panel)}+.ask ol{margin:8px 0 0;padding-left:20px}+.ask li{margin:6px 0}+@media (max-width:760px){.grid2,.sets,.overlay{grid-template-columns:1fr}.row{grid-template-columns:repeat(2,1fr)}}+`;++const DEFAULT_QUESTIONS = [+ 'Is the protagonist right: face, hair, signature detail and the looks?',+ 'Do the sets work, or should any be swapped out?',+ 'Is the overlay concept right for the on-screen text?',+];++/**+ * Render the sheet. `images` maps plan keys to `data:` URIs (missing = a+ * placeholder). `sections` are the analyzed song sections (songSections()).+ * Returns the HTML document string.+ */+export function renderCastAndSetsSheet({+ title = 'Music Video', project = null, direction, images = {}, sections = [], durationSec = null, bpm = null,+ revision = 1, notesApplied = [], checkinMode = 'review', status = 'review',+}) {+ const d = direction || {};+ const p = d.protagonist || {};+ const sets = d.sets || [];+ const colorOf = new Map(sets.map((s, i) => [s.id, CAST_SETS_SET_COLORS[i % CAST_SETS_SET_COLORS.length]]));+ const setOfSection = new Map((d.songMap || []).map((m) => [m.section, m.setId]));+ const tests = plannedTests(project, d);+ const total = durationSec || (sections.length ? sections[sections.length - 1].endSec : 0);++ const facts = [+ ['Who', p.description],+ ['Face', p.face],+ ['Hair', p.hair],+ ['Signature', p.signature],+ ['Gesture', p.gesture],+ ['Rules', (p.rules || []).map((r) => r.replace(/[.;]\s*$/, '')).join('; ')],+ ].filter(([, v]) => v).map(([k, v]) => `<dt>${e(k)}</dt><dd>${e(v)}</dd>`).join('');++ const looksCaption = (d.looks || []).map((l, i) => `0${i + 1} ${e(l.name)}${l.chapters ? ` (${e(l.chapters)})` : ''}`).join(' · ');++ const testFigures = tests.map((t, i) => {+ const set = sets.find((s) => s.id === t.setId);+ return figure(images[`test:${i + 1}`], `${set?.name || 'Set'} test`, e(t.caption || t.action || set?.name || ''));+ }).join('');++ const setFigures = sets.map((s) => {+ const caption = `<b>${e(s.name)}</b><span>${e(s.description)}${s.lighting ? ` ${e(s.lighting)}` : ''}</span>${(s.sections || []).length ? `<em>${e(s.sections.join(', '))}</em>` : ''}`;+ return figure(images[`set:${s.id}`], s.name, caption, 'set');+ }).join('');++ const bar = sections.map((s) => {+ const setId = setOfSection.get(s.index);+ const color = colorOf.get(setId) || NEUTRAL;+ const setName = sets.find((x) => x.id === setId)?.name || 'Unassigned';+ return `<div class="seg" style="flex:${Math.max(0.01, s.endSec - s.startSec).toFixed(2)};background:${color}" title="${e(s.label)} ${fmtTime(s.startSec)}–${fmtTime(s.endSec)} · ${e(setName)}"><span>${e(s.label)}</span></div>`;+ }).join('');+ const rows = sections.map((s) => {+ const setId = setOfSection.get(s.index);+ const set = sets.find((x) => x.id === setId);+ return `<tr><td class="tc">${fmtTime(s.startSec)}</td><td><span class="dot" style="background:${colorOf.get(setId) || NEUTRAL}"></span>${e(s.label)}</td><td>${set ? e(set.name) : 'Unassigned'}</td></tr>`;+ }).join('');++ const overlay = d.overlayConcept || {};+ const overlayCards = (overlay.elements || []).map((el) => `<div><h3>${e(el.name)}</h3><p>${e(el.description)}</p></div>`).join('');+ const questions = (d.questions && d.questions.length ? d.questions : DEFAULT_QUESTIONS).map((q) => `<li>${e(q)}</li>`).join('');+ const applied = notesApplied.length+ ? `<p class="sub"><b>Revision ${revision}.</b> Notes applied: ${notesApplied.map((n) => `${n.target ? `[${e(n.target)}] ` : ''}${e(n.text)}`).join(' · ')}</p>`+ : '';+ const statusLine = status === 'approved'+ ? '<p class="sub" style="margin:10px 0 0"><b>Approved.</b> These references now condition the storyboard frames.</p>'+ : `<p class="sub" style="margin:10px 0 0">${checkinMode === 'auto' ? 'Auto-approve is on: the autopilot continues to the storyboard.' : 'Add a note on any item in PortOS, then regenerate or approve to continue to the storyboard.'}</p>`;++ return `<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>${e(title)} — Cast & Sets</title>+<style>${STYLE}</style></head>+<body><div class="wrap">+<div class="hud"><span>Check-in <b>Cast & Sets</b></span><span>Revision <b>${Number(revision) || 1}</b></span>${p.name ? `<span>Protagonist <b>${e(p.name)}</b></span>` : ''}${total ? `<span>Track ${fmtTime(total)}${bpm ? ` · ${Math.round(bpm)} BPM` : ''}</span>` : ''}<span>${sets.length} sets · ${(d.looks || []).length} looks</span></div>+<h1>${e(title)}</h1>+<p class="lede">${e(d.logline)}</p>+${d.interpretation ? `<p class="sub">${e(d.interpretation)}</p>` : ''}+${applied}+<section><h2><small>Protagonist</small>${e(p.name || 'Protagonist')}</h2>+<div class="grid2">${figure(images.character, 'Character reference sheet: front, three-quarter, profile, back and face', 'Canonical reference sheet. Every later image of the protagonist uses it as a reference.')}<div><dl class="facts">${facts}</dl></div></div>+${figure(images.looks, 'Wardrobe looks', looksCaption ? `Wardrobe by chapter: ${looksCaption}` : 'Wardrobe', 'wide')}+<div class="grid2">${figure(images.expressions, 'Expression sheet', `Expression range for lip-sync keyframes.${p.gesture ? ` Includes the gesture: ${e(p.gesture)}` : ''}`)}${tests[0] ? figure(images['test:1'], 'First in-set test', e(tests[0].caption || tests[0].action)) : ''}</div>+</section>+<section><h2><small>In-set tests</small>The protagonist, in the world</h2><div class="row">${testFigures}</div></section>+<section><h2><small>Sets</small>${sets.length} sets</h2><p class="sub">Each set has its own light, so a cut says where we are before anything else.</p><div class="sets">${setFigures}</div></section>+<section><h2><small>Song map</small>Where each set lives in the track</h2>+${sections.length ? `<div class="bar">${bar}</div><div class="ticks"><span>0:00</span><span>${fmtTime(total)}</span></div><div class="tablewrap"><table>${rows}</table></div>` : '<p class="sub">The song has not been sectioned yet.</p>'}+</section>+<section><h2><small>Overlay layer</small>What ties every shot together</h2>${overlay.summary ? `<p class="sub">${e(overlay.summary)}</p>` : ''}${overlayCards ? `<div class="overlay">${overlayCards}</div>` : ''}</section>+<div class="ask"><b>What I need from you before the storyboard</b><ol>${questions}</ol>${statusLine}</div>+</div></body></html>+`;+}diff --git a/server/services/musicVideo/castAndSetsSheet.test.js b/server/services/musicVideo/castAndSetsSheet.test.jsnew file mode 100644index 0000000000..90e5548dc0--- /dev/null+++ b/server/services/musicVideo/castAndSetsSheet.test.js@@ -0,0 +1,55 @@+/**+ * The Cast & Sets check-in sheet is a self-contained file the director opens+ * in a sandboxed viewer (or on its own): every section of the hand-made sheet,+ * no network reference of any kind, and no way for direction text or an image+ * source to inject markup.+ */++import { describe, it, expect } from 'vitest';+import { renderCastAndSetsSheet } from './castAndSetsSheet.js';++const PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';++const direction = {+ logline: 'A keeper <signals> & waits.',+ interpretation: 'Read as a vigil kept for someone lost at sea.',+ protagonist: { name: 'Nova', description: 'the voice', face: 'weathered', hair: 'grey braid', signature: 'a lantern', gesture: 'lantern raised', rules: ['No hats'] },+ looks: [{ name: 'Lab', description: 'hoodie', chapters: 'verses' }],+ sets: [+ { id: 'lab', name: 'Lab', description: 'a lamp room', lighting: 'green', sections: ['Verse'] },+ { id: 'roof', name: 'Roof', description: 'rain', lighting: 'red', sections: ['Outro'] },+ { id: 'hall', name: 'Hall', description: 'beacons', lighting: 'red', sections: [] },+ ],+ songMap: [{ section: 0, setId: 'lab' }, { section: 1, setId: 'roof' }],+ tests: [{ setId: 'lab', look: 'Lab', action: 'trimming the wick', caption: 'the long night' }, { setId: 'roof', look: 'Lab', action: 'running', caption: 'outside' }],+ overlayConcept: { summary: 'One meter.', elements: [{ name: 'Meter', description: 'falls' }] },+ questions: ['Is she right?'],+};+const sections = [{ index: 0, label: 'Verse', startSec: 0, endSec: 30 }, { index: 1, label: 'Outro', startSec: 30, endSec: 60 }];++describe('Cast & Sets sheet', () => {+ it('renders every section of the check-in, self-contained', () => {+ const html = renderCastAndSetsSheet({+ title: 'Example Song', direction, sections, durationSec: 60, bpm: 120, revision: 2,+ notesApplied: [{ target: 'character', text: 'No hats' }],+ images: { character: PNG, looks: PNG, expressions: PNG, 'set:lab': PNG, 'set:roof': PNG, 'test:1': PNG, 'test:2': 'https://example.com/x.png' },+ });+ for (const heading of ['Protagonist', 'In-set tests', 'Sets', 'Song map', 'Overlay layer', 'What I need from you']) {+ expect(html).toContain(heading);+ }+ expect(html).toContain('Nova');+ expect(html).toContain('No hats');+ expect(html).toContain('Revision 2');+ // The song map bar: one segment per section, colored by its set.+ expect(html.match(/class="seg"/g)).toHaveLength(2);+ expect(html).toContain('Verse 0:00–0:30 · Lab');+ // Direction text is escaped, never markup.+ expect(html).toContain('A keeper <signals> & waits.');+ // No network reference at all: a non-data image source becomes a placeholder.+ expect(html).not.toMatch(/https?:\/\//);+ expect(html).not.toMatch(/<(script|link|iframe)\b/i);+ expect(html).toContain('Image not rendered');+ // The set with no image yet is a placeholder too.+ expect(html.match(/data:image\/png;base64/g)).toHaveLength(7);+ });+});diff --git a/server/services/musicVideo/devArtifactService.js b/server/services/musicVideo/devArtifactService.jsnew file mode 100644index 0000000000..1ea4aa9e1a--- /dev/null+++ b/server/services/musicVideo/devArtifactService.js@@ -0,0 +1,165 @@+/**+ * Music Video — development artifact workflow: import/upload, generated saves,+ * notes, review and soft delete over the pure transforms in devArtifacts.js+ * and the file store in devArtifactStore.js.+ *+ * Every record write goes through `mutateProjectRecord`, so it runs against the+ * freshest project under the backend's write serialization. A file is written+ * BEFORE its record update (a version number is reserved by reading the record+ * first); when the update is refused the file is removed again, so a failed+ * import leaves nothing behind.+ */++import { extname } from 'path';+import { unlink } from 'fs/promises';+import { ServerError } from '../../lib/errorHandler.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';+import {+ addDevArtifactNote,+ addDevArtifactVersion,+ deleteDevArtifact,+ devArtifactTypeFor,+ devArtifactVersion,+ findDevArtifact,+ liveDevArtifacts,+ newDevArtifactId,+ nextDevArtifactVersion,+ resolveDevArtifactNote,+ reviewDevArtifact,+} from './devArtifacts.js';+import { discardDevArtifactFile, resolveDevArtifactFile, writeDevArtifactFile } from './devArtifactStore.js';++async function requireProject(id) {+ const project = await getProject(id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}++function publish(projectId, project, artifact) {+ musicVideoEvents.emit('dev-artifact', { projectId, artifactId: artifact?.id || null, project });+}++/** Live artifacts, newest activity first. */+export async function listDevArtifacts(projectId) {+ return liveDevArtifacts(await requireProject(projectId));+}++/** One live artifact. */+export async function getDevArtifact(projectId, artifactId) {+ return findDevArtifact(await requireProject(projectId), artifactId);+}++/**+ * Store a file (upload or generated) as a new artifact, or as the next version+ * of `artifactId`. `ext` picks the served media type. Returns `{ project, artifact }`.+ */+async function storeVersion(projectId, {+ artifactId = null, kind, title, ext, buffer = null, tempPath = null, source, status = null, notes = [],+}) {+ const mimeType = devArtifactTypeFor(ext);+ if (!mimeType) throw new ServerError('Unsupported file type — accepted: HTML, Markdown, MP4, PNG, JPG', { status: 400, code: 'VALIDATION_ERROR' });+ const project = await requireProject(projectId);+ if (artifactId) findDevArtifact(project, artifactId);+ const id = artifactId || newDevArtifactId();+ const version = nextDevArtifactVersion(project, artifactId);+ const { file, bytes } = await writeDevArtifactFile({+ projectId, artifactId: id, version, ext: ext === 'jpeg' ? 'jpg' : ext, buffer, tempPath,+ });+ const out = await mutateProjectRecord(projectId, (current) => {+ // A concurrent write took this version number: refuse rather than point+ // two versions at one file.+ if (nextDevArtifactVersion(current, artifactId) !== version) {+ throw new ServerError('Another version of this artifact was saved at the same time — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });+ }+ return addDevArtifactVersion(current, {+ artifactId, id: artifactId ? null : id, kind, title, file, mimeType, bytes, source, status, notes,+ });+ }).catch(async (err) => {+ await discardDevArtifactFile(file);+ throw err;+ });+ console.log(`🗂️ Music Video dev artifact ${out.artifact.id.slice(4, 12)} v${version} saved for ${projectId.slice(0, 11)} (${out.artifact.kind}, ${mimeType})`);+ publish(projectId, out.project, out.artifact);+ return { project: out.project, artifact: out.artifact };+}++/**+ * Import an uploaded file. The temp upload is always removed. `notes` are+ * plain strings (or `{ text, target }`) recorded against the new version.+ */+export async function importDevArtifact(projectId, { tempPath, originalName, artifactId = null, kind, title, status = null, notes = [] }) {+ try {+ const ext = extname(String(originalName || '')).slice(1).toLowerCase();+ return await storeVersion(projectId, {+ artifactId,+ kind,+ title: title || String(originalName || '').replace(/\.[^.]+$/, ''),+ ext,+ tempPath,+ source: 'upload',+ status,+ notes: notes.map((n) => (typeof n === 'string' ? { text: n } : n)),+ });+ } finally {+ await unlink(tempPath).catch(() => {});+ }+}++/** Save generated HTML (e.g. the Cast & Sets sheet) as a new artifact or version. */+export async function saveGeneratedDevArtifact(projectId, { artifactId = null, kind, title, html, status = null, source = 'generated' }) {+ return storeVersion(projectId, {+ artifactId, kind, title, ext: 'html', buffer: Buffer.from(html, 'utf8'), source, status,+ });+}++/**+ * Resolve the file to serve for a version (`version` null = current).+ * Returns `{ path, mimeType, artifact, version }`.+ */+export async function resolveDevArtifactDownload(projectId, artifactId, version = null) {+ const artifact = await getDevArtifact(projectId, artifactId);+ const entry = devArtifactVersion(artifact, version);+ const path = resolveDevArtifactFile(entry.file);+ if (!path) throw new ServerError('Artifact file path is invalid', { status: 404, code: 'NOT_FOUND' });+ return { path, mimeType: entry.mimeType, artifact, version: entry.version };+}++export async function addNote(projectId, artifactId, input) {+ const out = await mutateProjectRecord(projectId, (current) => addDevArtifactNote(current, artifactId, input));+ publish(projectId, out.project, out.artifact);+ return { project: out.project, artifact: out.artifact, note: out.note };+}++export async function setNoteResolved(projectId, artifactId, noteId, resolved) {+ const out = await mutateProjectRecord(projectId, (current) => resolveDevArtifactNote(current, artifactId, noteId, resolved));+ publish(projectId, out.project, out.artifact);+ return { project: out.project, artifact: out.artifact, note: out.note };+}++/**+ * Approve / request changes. Approving the sheet the Cast & Sets stage is+ * waiting on is the stage's own "Approve & continue", so it is delegated there+ * (the stage then applies its references and releases the autopilot).+ */+export async function reviewArtifact(projectId, artifactId, { status, note = null }) {+ const project = await requireProject(projectId);+ findDevArtifact(project, artifactId);+ const stage = project.castAndSets;+ if (status === 'approved' && stage?.artifactId === artifactId && stage.status === 'review') {+ const { approveCastAndSets } = await import('./castAndSetsService.js');+ if (note) await addNote(projectId, artifactId, { text: note });+ const approved = await approveCastAndSets(projectId);+ return { project: approved.project, artifact: findDevArtifact(approved.project, artifactId) };+ }+ const out = await mutateProjectRecord(projectId, (current) => reviewDevArtifact(current, artifactId, { status, note }));+ console.log(`🗂️ Music Video dev artifact ${artifactId.slice(4, 12)} marked ${status}`);+ publish(projectId, out.project, out.artifact);+ return { project: out.project, artifact: out.artifact };+}++export async function removeDevArtifact(projectId, artifactId) {+ const out = await mutateProjectRecord(projectId, (current) => deleteDevArtifact(current, artifactId));+ publish(projectId, out.project, null);+ return { project: out.project };+}diff --git a/server/services/musicVideo/devArtifactStore.js b/server/services/musicVideo/devArtifactStore.jsnew file mode 100644index 0000000000..00693654fe--- /dev/null+++ b/server/services/musicVideo/devArtifactStore.js@@ -0,0 +1,81 @@+/**+ * Music Video — development artifact files on disk.+ *+ * Every version of a development artifact is one immutable file:+ *+ * data/music-video/<projectId>/dev/<artifactId>/v<N>.<ext>+ *+ * The project record holds only the data-relative path (devArtifacts.js), so a+ * version is never overwritten and a clone that carried the metadata over keeps+ * pointing at bytes that still exist. The folder is covered by the rsync+ * snapshot backup like every other `data/` subtree, and is NOT part of the+ * project's peer-sync asset manifest (the metadata is wire-local, see+ * devArtifacts.js).+ *+ * Every path read back from a record is re-resolved and checked to sit inside+ * `data/music-video/`, so a hand-edited record cannot point the file route at+ * an arbitrary file.+ */++import { copyFile, mkdir, stat, unlink, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join, resolve } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/fileUtils.js';+import { isPathInsideDir } from '../../lib/pathSafety.js';++// A project/artifact id is used as a path segment; nothing else may be.+const SEGMENT = /^[A-Za-z0-9_-]{1,100}$/;++/** Root of every music-video development file. */+export const devArtifactRoot = () => join(PATHS.data, 'music-video');++function assertSegment(value, what) {+ if (typeof value !== 'string' || !SEGMENT.test(value)) {+ throw new ServerError(`Invalid ${what}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+}++/** The data-relative path a version will be stored at. */+function devArtifactRelativePath(projectId, artifactId, version, ext) {+ assertSegment(projectId, 'project id');+ assertSegment(artifactId, 'artifact id');+ if (!Number.isInteger(version) || version < 1) throw new ServerError('Invalid version', { status: 400, code: 'VALIDATION_ERROR' });+ if (!/^[a-z0-9]{1,5}$/.test(ext)) throw new ServerError('Invalid extension', { status: 400, code: 'VALIDATION_ERROR' });+ return `music-video/${projectId}/dev/${artifactId}/v${version}.${ext}`;+}++/** Absolute path for a stored data-relative path, or null when it escapes the root. */+export function resolveDevArtifactFile(relativePath) {+ if (typeof relativePath !== 'string' || !relativePath || relativePath.includes('\0')) return null;+ const abs = resolve(PATHS.data, relativePath);+ return isPathInsideDir(devArtifactRoot(), abs) ? abs : null;+}++async function ensureParent(abs) {+ await mkdir(resolve(abs, '..'), { recursive: true });+}++/**+ * Store one version's bytes. `source` is either `{ buffer }` (generated) or+ * `{ tempPath }` (an upload the caller removes). Returns `{ file, bytes }`.+ */+export async function writeDevArtifactFile({ projectId, artifactId, version, ext, buffer = null, tempPath = null }) {+ const file = devArtifactRelativePath(projectId, artifactId, version, ext);+ const abs = resolveDevArtifactFile(file);+ if (!abs) throw new ServerError('Invalid artifact path', { status: 400, code: 'VALIDATION_ERROR' });+ // Versions are immutable: a leftover file from a write whose record update+ // never landed is replaced, but a version the record already names is not+ // reachable here because the version number always advances.+ await ensureParent(abs);+ if (buffer) await writeFile(abs, buffer);+ else await copyFile(tempPath, abs);+ const { size } = await stat(abs);+ return { file, bytes: size };+}++/** Remove a file written for a version whose record update failed. */+export async function discardDevArtifactFile(file) {+ const abs = resolveDevArtifactFile(file);+ if (abs && existsSync(abs)) await unlink(abs).catch(() => {});+}diff --git a/server/services/musicVideo/devArtifacts.js b/server/services/musicVideo/devArtifacts.jsnew file mode 100644index 0000000000..e2639528dc--- /dev/null+++ b/server/services/musicVideo/devArtifacts.js@@ -0,0 +1,219 @@+/**+ * Music Video — development artifacts ("ingredients"): pure record transforms.+ *+ * A project carries a list of reviewable development files — a Cast & Sets+ * check-in sheet, an animatic, a treatment, a storyboard — each with its own+ * review status, notes and version history. The BYTES of every version are an+ * immutable file under `data/music-video/<projectId>/dev/<artifactId>/v<N>.<ext>`+ * (devArtifactStore.js); only the metadata below lives on the project record:+ *+ * {+ * id, kind, title, status, version, file, mimeType, bytes,+ * createdAt, updatedAt, deleted, deletedAt,+ * versions: [{ version, file, mimeType, bytes, source, createdAt }],+ * notes: [{ id, text, target, version, createdAt, resolvedAt }],+ * }+ *+ * `version`/`file`/`mimeType`/`bytes` mirror the newest entry of `versions`, so+ * a reader that only wants "the current sheet" never walks the history. A new+ * version resets the review to `pending` unless the writer names a status+ * (the Cast & Sets stage approves its own sheet in auto mode). Deletion is a+ * soft tombstone; files are never unlinked, so an old version stays viewable+ * from a clone that still points at it.+ *+ * Peer sync: `devArtifacts` is WIRE-LOCAL (lib/syncWire.js), like+ * `productionRuns` — the files it points at exist only on this install (the+ * project's asset manifest does not ship them), so a peer would receive+ * dangling pointers. `mergeProjectRecord` restores the local list over a newer+ * remote copy.+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { trimTo } from '../../lib/textUtils.js';+import { MUSIC_VIDEO_DEV_ARTIFACT_KINDS, MUSIC_VIDEO_DEV_ARTIFACT_STATUSES } from '../../lib/musicVideoValidation.js';++const DEV_ARTIFACT_KINDS = MUSIC_VIDEO_DEV_ARTIFACT_KINDS;+const DEV_ARTIFACT_STATUSES = MUSIC_VIDEO_DEV_ARTIFACT_STATUSES;+// Extension → served media type. The only formats a development file may be.+export const DEV_ARTIFACT_TYPES = Object.freeze({+ html: 'text/html',+ md: 'text/markdown',+ mp4: 'video/mp4',+ png: 'image/png',+ jpg: 'image/jpeg',+});+export const DEV_ARTIFACT_TITLE_MAX = 200;+export const DEV_ARTIFACT_NOTE_MAX = 2000;+export const DEV_ARTIFACT_TARGET_MAX = 120;+const MAX_ARTIFACTS = 100;+const MAX_VERSIONS = 100;+const MAX_NOTES = 500;++const artifactError = (status, code, message) => new ServerError(message, { status, code });++/** Every artifact on a project (tombstones included), tolerating a record with none. */+export const projectDevArtifacts = (project) => (Array.isArray(project?.devArtifacts) ? project.devArtifacts : []);++/** Live (not deleted) artifacts, newest activity first. */+export const liveDevArtifacts = (project) => projectDevArtifacts(project)+ .filter((a) => !a?.deleted)+ .sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));++/** One live artifact, or a 404. */+export function findDevArtifact(project, artifactId) {+ const artifact = projectDevArtifacts(project).find((a) => a?.id === artifactId && !a.deleted);+ if (!artifact) throw artifactError(404, 'NOT_FOUND', 'Development artifact not found');+ return artifact;+}++/** The media type for a filename extension, or null when the format is not accepted. */+export function devArtifactTypeFor(ext) {+ const key = String(ext || '').toLowerCase().replace(/^\./, '');+ return DEV_ARTIFACT_TYPES[key === 'jpeg' ? 'jpg' : key] || null;+}++/** A fresh artifact id (also the per-artifact folder name on disk). */+export const newDevArtifactId = () => `mvd-${randomUUID()}`;++/** The version number the NEXT file of this artifact will carry (1 for a new artifact). */+export const nextDevArtifactVersion = (project, artifactId) => {+ const existing = artifactId ? projectDevArtifacts(project).find((a) => a?.id === artifactId) : null;+ return (existing?.versions || []).reduce((max, v) => Math.max(max, v.version || 0), 0) + 1;+};++function buildNote(input, version, now) {+ const text = trimTo(input?.text, DEV_ARTIFACT_NOTE_MAX);+ if (!text) throw artifactError(422, 'VALIDATION_ERROR', 'A note needs text');+ const target = trimTo(input?.target, DEV_ARTIFACT_TARGET_MAX);+ return {+ id: `mvdn-${randomUUID()}`,+ text,+ target: target || null,+ version,+ createdAt: now,+ resolvedAt: input?.resolved ? now : null,+ };+}++function replaceArtifact(project, next, now) {+ return {+ ...project,+ devArtifacts: projectDevArtifacts(project).map((a) => (a?.id === next.id ? next : a)),+ updatedAt: now,+ };+}++/**+ * Record a new file version. `artifactId` null creates a new artifact (then+ * `kind` and `title` are required); an id adds a version to that artifact.+ * `file` is the data-relative path the store already wrote. Returns+ * `{ project, artifact }`.+ */+export function addDevArtifactVersion(project, {+ artifactId = null, id = null, kind, title, file, mimeType, bytes = null, source = 'upload',+ status = null, notes = [],+}, now = new Date().toISOString()) {+ if (status != null && !DEV_ARTIFACT_STATUSES.includes(status)) throw artifactError(422, 'VALIDATION_ERROR', `Unknown status ${status}`);+ const existing = artifactId ? findDevArtifact(project, artifactId) : null;+ const version = nextDevArtifactVersion(project, existing?.id);+ const entry = {+ version, file, mimeType, bytes: Number.isFinite(bytes) ? bytes : null, source: trimTo(source, 40) || 'upload', createdAt: now,+ };+ if (existing) {+ if ((existing.versions || []).length >= MAX_VERSIONS) throw artifactError(409, 'DEV_ARTIFACT_VERSION_LIMIT', `An artifact keeps at most ${MAX_VERSIONS} versions`);+ const next = {+ ...existing,+ ...(title ? { title: trimTo(title, DEV_ARTIFACT_TITLE_MAX) } : {}),+ version,+ file,+ mimeType,+ bytes: entry.bytes,+ status: status || 'pending',+ versions: [...(existing.versions || []), entry],+ notes: [...(existing.notes || []), ...notes.map((n) => buildNote(n, version, now))].slice(-MAX_NOTES),+ updatedAt: now,+ };+ return { project: replaceArtifact(project, next, now), artifact: next };+ }+ if (!DEV_ARTIFACT_KINDS.includes(kind)) throw artifactError(422, 'VALIDATION_ERROR', `Unknown artifact kind ${kind}`);+ const cleanTitle = trimTo(title, DEV_ARTIFACT_TITLE_MAX);+ if (!cleanTitle) throw artifactError(422, 'VALIDATION_ERROR', 'An artifact needs a title');+ if (liveDevArtifacts(project).length >= MAX_ARTIFACTS) throw artifactError(409, 'DEV_ARTIFACT_LIMIT', `A project keeps at most ${MAX_ARTIFACTS} development artifacts`);+ const artifact = {+ id: id || newDevArtifactId(),+ kind,+ title: cleanTitle,+ status: status || 'pending',+ version,+ file,+ mimeType,+ bytes: entry.bytes,+ versions: [entry],+ notes: notes.map((n) => buildNote(n, version, now)).slice(-MAX_NOTES),+ createdAt: now,+ updatedAt: now,+ deleted: false,+ deletedAt: null,+ };+ return {+ project: { ...project, devArtifacts: [...projectDevArtifacts(project), artifact], updatedAt: now },+ artifact,+ };+}++/** Add a review note (against the artifact's current version). Returns `{ project, artifact, note }`. */+export function addDevArtifactNote(project, artifactId, input, now = new Date().toISOString()) {+ const artifact = findDevArtifact(project, artifactId);+ if ((artifact.notes || []).length >= MAX_NOTES) throw artifactError(409, 'DEV_ARTIFACT_NOTE_LIMIT', `An artifact keeps at most ${MAX_NOTES} notes`);+ const note = buildNote(input, artifact.version, now);+ const next = { ...artifact, notes: [...(artifact.notes || []), note], updatedAt: now };+ return { project: replaceArtifact(project, next, now), artifact: next, note };+}++/** Mark a note resolved (or open again). Returns `{ project, artifact, note }`. */+export function resolveDevArtifactNote(project, artifactId, noteId, resolved, now = new Date().toISOString()) {+ const artifact = findDevArtifact(project, artifactId);+ const current = (artifact.notes || []).find((n) => n.id === noteId);+ if (!current) throw artifactError(404, 'NOT_FOUND', 'Note not found');+ const note = { ...current, resolvedAt: resolved ? (current.resolvedAt || now) : null };+ const next = { ...artifact, notes: artifact.notes.map((n) => (n.id === noteId ? note : n)), updatedAt: now };+ return { project: replaceArtifact(project, next, now), artifact: next, note };+}++/** Resolve every open note matching `predicate` in one write (a regeneration consumed them). */+export function resolveDevArtifactNotes(project, artifactId, predicate = () => true, now = new Date().toISOString()) {+ const artifact = findDevArtifact(project, artifactId);+ const notes = (artifact.notes || []).map((n) => (!n.resolvedAt && predicate(n) ? { ...n, resolvedAt: now } : n));+ const next = { ...artifact, notes, updatedAt: now };+ return { project: replaceArtifact(project, next, now), artifact: next };+}++/**+ * Set the review status. A request for changes may carry the note that says+ * what to change. Returns `{ project, artifact }`.+ */+export function reviewDevArtifact(project, artifactId, { status, note = null }, now = new Date().toISOString()) {+ if (!DEV_ARTIFACT_STATUSES.includes(status)) throw artifactError(422, 'VALIDATION_ERROR', `Unknown status ${status}`);+ const artifact = findDevArtifact(project, artifactId);+ const added = note && trimTo(note, DEV_ARTIFACT_NOTE_MAX) ? [buildNote({ text: note }, artifact.version, now)] : [];+ const next = { ...artifact, status, notes: [...(artifact.notes || []), ...added], updatedAt: now };+ return { project: replaceArtifact(project, next, now), artifact: next };+}++/** Soft-delete an artifact (its files stay on disk). Returns `{ project, artifact }`. */+export function deleteDevArtifact(project, artifactId, now = new Date().toISOString()) {+ const artifact = findDevArtifact(project, artifactId);+ const next = { ...artifact, deleted: true, deletedAt: now, updatedAt: now };+ return { project: replaceArtifact(project, next, now), artifact: next };+}++/** The version entry to serve: `version` null = the current one. */+export function devArtifactVersion(artifact, version = null) {+ const versions = artifact?.versions || [];+ const found = version == null+ ? versions.find((v) => v.version === artifact.version) || versions[versions.length - 1]+ : versions.find((v) => v.version === version);+ if (!found) throw artifactError(404, 'NOT_FOUND', 'Artifact version not found');+ return found;+}diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 929aa9113e..75dbed5c89 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -31,4 +31,13 @@ import { EventEmitter } from 'events';// 'production' → { projectId, runId, run, action, project } — a server-owned// production run advanced (steps, route choices, spend, halts); socket.js// bridges it to `music-video:production`.+//+// The Cast & Sets check-in adds:+// 'cast-and-sets' → { projectId, stage, project } — the check-in stage+// advanced (direction, an image landed, the sheet is ready, approved);+// bridged to `music-video:cast-and-sets`. productionService.js listens so+// a production run waiting on the check-in continues once it settles.+// 'dev-artifact' → { projectId, artifactId, project } — a development+// artifact was added, versioned, noted, reviewed or deleted; bridged to+// `music-video:dev-artifact`.export const musicVideoEvents = new EventEmitter();diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex d457ccc226..4738177f16 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -44,6 +44,7 @@ import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';import { sceneVisualLayer } from '../../lib/musicVideoLayers.js';import { projectAutoReviews } from './autoReview.js';import { projectRevisions } from './revision.js';+import { castAndSetsSettled } from './castAndSets.js';const PRODUCTION_LIMIT_BOUNDS = Object.freeze({maxGenerations: Object.freeze({ min: 1, max: 500 }),@@ -248,6 +249,8 @@ const slotSteps = (run, sceneId, stepKind, revisionId = null) => run.steps/*** Pure: what the run should do next, from the record and the queue alone:+ * `cast-and-sets` — the board is empty and no Cast & Sets check-in exists:+ * start one (it runs before the plan; see castAndSetsService.js);* `plan` — the board is empty: seed it (one planner call, first time only);* `dispatch` — generate `kind` (frame|clip) for `sceneId`;* `review` — every scene holds its media: hand the continuous excerpt@@ -275,6 +278,8 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }const scenes = Array.isArray(project.scenes) ? project.scenes : [];if (!scenes.length) {if (run.planned) return { type: 'halt', status: 'blocked', reason: 'Planning produced no scenes — check the song analysis' };+ const gate = castAndSetsGate(project, run);+ if (gate) return gate;return { type: 'plan' };}const targets = productionTargets(project);@@ -305,6 +310,25 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }};}+/**+ * The Cast & Sets check-in runs before the plan. Returns the step it needs,+ * or null once it is approved or skipped.+ */+function castAndSetsGate(project, run) {+ const stage = project?.castAndSets || null;+ if (castAndSetsSettled(stage)) return null;+ if (!stage) {+ return run.castAndSetsStarted+ ? { type: 'halt', status: 'blocked', reason: 'The Cast & Sets check-in did not start — start it from the Autopilot panel, or skip it' }+ : { type: 'cast-and-sets' };+ }+ if (stage.status === 'review') return { type: 'wait', on: 'checkin' };+ if (stage.status === 'failed') {+ return { type: 'halt', status: 'blocked', reason: `The Cast & Sets check-in failed: ${stage.stopReason || 'unknown error'} — resume or skip it, then resume the run` };+ }+ return { type: 'wait', on: 'cast-and-sets' };+}+// ---- dispatch accounting ------------------------------------------------------/**@@ -437,6 +461,30 @@ export function reconcileProductionSteps(project, runId, jobs = [], nowMs = Date// ---- lifecycle ---------------------------------------------------------------+/** Mark the Cast & Sets check-in as started by this run (so a failed start halts instead of looping). */+export const markProductionCastAndSets = (project, runId, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ castAndSetsStarted: true }), now);++/**+ * An approved (or skipped) Cast & Sets check-in writes the visual spec and+ * concept subjects a run's creative-setup checksum covers. A running run that+ * has not planned yet was waiting on exactly that change, so its basis is+ * re-captured in the same write instead of halting it `needs-replan`.+ * Returns `{ project }`.+ */+export function rebaseProductionAfterCheckin(project, now = new Date().toISOString()) {+ const runs = projectProductionRuns(project);+ if (!runs.some((r) => r.status === 'running' && !r.planned)) return { project };+ const revision = productionBasisRevision(project);+ return {+ project: {+ ...project,+ productionRuns: runs.map((r) => (r.status === 'running' && !r.planned+ ? { ...r, basis: { revision, capturedAt: now }, updatedAt: now } : r)),+ },+ };+}+/** Mark the board as planned by this run (so an empty plan halts instead of looping). */export const markProductionPlanned = (project, runId, now = new Date().toISOString()) =>mutateRun(project, runId, () => ({ planned: true }), now);diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex 50fb94cdd0..f85688eeff 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -31,6 +31,7 @@ import {cancelProductionOnProject,findProductionRun,haltProduction,+ markProductionCastAndSets,markProductionPlanned,normalizeProductionPool,nextProductionStep,@@ -74,6 +75,7 @@ const defaults = {dispatch: async (args) => (await import('./productionDispatch.js')).dispatchProductionStep(args),queue: async () => import('../mediaJobQueue/index.js'),planProject: async (...args) => (await import('./planner.js')).planProject(...args),+ startCastAndSets: async (...args) => (await import('./castAndSetsService.js')).startCastAndSets(...args),autoReview: async () => import('./autoReviewService.js'),releaseRevisionSection: async (...args) => (await import('./revisionService.js')).releaseRevisionSection(...args),};@@ -171,6 +173,22 @@ async function takeSteps(projectId, runId) {return { ...out, action: { type: 'idle' } };}+ if (step.type === 'cast-and-sets') {+ // Marked first, like the plan: a failed start halts instead of looping.+ await mutateProjectRecord(projectId, (current) => markProductionCastAndSets(current, runId));+ const started = await deps.startCastAndSets(projectId, {+ productionRunId: runId,+ ...(run.reviewer?.providerId ? { providerId: run.reviewer.providerId } : {}),+ ...(run.reviewer?.model ? { model: run.reviewer.model } : {}),+ }).catch((err) => ({ error: err }));+ if (started.error) {+ const out = await halt(projectId, runId, { status: 'blocked', reason: `The Cast & Sets check-in could not start: ${started.error.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ console.log(`🎭 Music Video production ${short(runId)} started the Cast & Sets check-in`);+ continue;+ }+if (step.type === 'plan') {// Marked first: a crash mid-plan must not re-plan (and re-pay) on resume.await mutateProjectRecord(projectId, (current) => markProductionPlanned(current, runId));@@ -420,6 +438,15 @@ musicVideoEvents.on('scene-image', guarded('a frame landed', onSceneTake));musicVideoEvents.on('scene-video', guarded('a clip landed', onSceneTake));musicVideoEvents.on('auto-review', guarded('its review advanced', onOwnedReviewAdvanced));+/** The Cast & Sets check-in settled (approved, skipped) or failed: a run waiting on it continues or halts. */+async function onCastAndSetsAdvanced({ projectId, stage } = {}) {+ if (!projectId || !['approved', 'skipped', 'failed'].includes(stage?.status)) return;+ const project = await getProject(projectId);+ const run = project ? projectProductionRuns(project).find(runningHere) : null;+ if (run && !run.planned) await advanceProduction(projectId, run.id);+}+musicVideoEvents.on('cast-and-sets', guarded('its Cast & Sets check-in advanced', onCastAndSetsAdvanced));+// The queue listener is armed on a run's first Start/Resume (never at boot);// the queue module is deferred because only this path needs it.let jobListenersArmed = false;diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 200d1d9326..e2748119a4 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -44,6 +44,7 @@ const queue = {};const dispatch = vi.fn();const planProject = vi.fn();+const startCastAndSets = vi.fn();const startAutoReview = vi.fn();const autoReview = { startAutoReview, resumeAutoReview: vi.fn(), stopAutoReview: vi.fn(async () => {}), cancelAutoReview: vi.fn(async () => {}) };@@ -131,6 +132,7 @@ beforeEach(() => {dispatch,queue: async () => queue,planProject,+ startCastAndSets,autoReview: async () => autoReview,releaseRevisionSection: vi.fn(async () => {}),});@@ -172,7 +174,7 @@ describe('music video production run (#9066)', () => {});it('plans an empty board once, with the directive, before generating', async () => {- seedProject({ scenes: [] });+ seedProject({ scenes: [], castAndSets: { status: 'skipped' } });planProject.mockImplementation(async () => {store.get('mv-example').scenes = [{ sceneId: 'mvs-p', framePrompt: 'x', prompt: 'y', startSec: 0, endSec: 4, takes: [] }];return { scenesAdded: 1 };@@ -182,6 +184,50 @@ describe('music video production run (#9066)', () => {expect(dispatch).toHaveBeenCalledTimes(1);});+ it('runs the Cast & Sets check-in before the plan and waits for the director in review mode', async () => {+ seedProject({ scenes: [], visualSpec: { references: [] } });+ startCastAndSets.mockImplementation(async (projectId, { productionRunId }) => {+ store.get(projectId).castAndSets = { status: 'directing', productionRunId };+ return {};+ });+ planProject.mockImplementation(async () => {+ store.get('mv-example').scenes = [{ sceneId: 'mvs-p', framePrompt: 'x', prompt: 'y', startSec: 0, endSec: 4, takes: [] }];+ return { scenesAdded: 1 };+ });+ await start();+ expect(startCastAndSets).toHaveBeenCalledTimes(1);+ expect(startCastAndSets.mock.calls[0][1]).toMatchObject({ productionRunId: theRun().id });+ expect(planProject).not.toHaveBeenCalled();++ // The sheet is waiting for its check-in: the run waits, it neither plans nor halts.+ store.get('mv-example').castAndSets.status = 'review';+ musicVideoEvents.emit('cast-and-sets', { projectId: 'mv-example', stage: { status: 'review' } });+ await settle();+ expect(planProject).not.toHaveBeenCalled();+ expect(theRun()).toMatchObject({ status: 'running', planned: false, castAndSetsStarted: true });++ // Approval writes new references (a creative-setup change) and re-bases the run in the same write.+ const { rebaseProductionAfterCheckin } = await import('./production.js');+ const project = store.get('mv-example');+ project.castAndSets.status = 'approved';+ project.visualSpec = { references: [{ id: 'mvr-cs-character', imageId: 'sheet.png', role: 'character', condition: true }] };+ store.set('mv-example', rebaseProductionAfterCheckin(project).project);+ musicVideoEvents.emit('cast-and-sets', { projectId: 'mv-example', stage: { status: 'approved' } });+ await settle();+ expect(planProject).toHaveBeenCalledTimes(1);+ expect(theRun().status).toBe('running');+ expect(dispatch).toHaveBeenCalledTimes(1);+ });++ it('halts blocked when the Cast & Sets check-in fails, and never plans past it', async () => {+ seedProject({ scenes: [], castAndSets: { status: 'failed', stopReason: 'no image backend' } });+ await start();+ expect(startCastAndSets).not.toHaveBeenCalled();+ expect(planProject).not.toHaveBeenCalled();+ expect(theRun()).toMatchObject({ status: 'blocked' });+ expect(theRun().stopReason).toMatch(/no image backend/);+ });+it('refuses a route outside the allowed pool before anything is enqueued', async () => {seedProject();const chooseRoute = vi.fn(async () => ({ route: { kind: 'image', mode: 'grok', model: null }, rationale: 'model pick' }));diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex c1ce19a25e..6f62e31082 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -236,6 +236,12 @@ export function cloneProjectRecord(source, {...(Array.isArray(source.autoReviews) ? { autoReviews: [] } : {}),// #9066: a production run executes against the SOURCE's scenes and jobs....(Array.isArray(source.productionRuns) ? { productionRuns: [] } : {}),+ // Development artifacts ride along as-is: every version is an immutable+ // file, so the clone points at the same bytes (devArtifacts.js). The Cast+ // & Sets check-in keeps its direction and images, but its dispatch pin and+ // production link belong to the source — a working stage reads as+ // interrupted on the clone and can be resumed there.+ ...(source.castAndSets ? { castAndSets: { ...source.castAndSets, processId: null, productionRunId: null } } : {}),renderHistoryId: null,// #9010: the source's in-flight render mark is not the clone's.renderingOn: null,@@ -637,6 +643,10 @@ export function mergeProjectRecord(local, remoteRaw) {if (Object.hasOwn(local, 'imageModelId')) remote.imageModelId = local.imageModelId;// #9066: this install's production-run checkpoint survives a newer remote.if (Object.hasOwn(local, 'productionRuns')) remote.productionRuns = local.productionRuns;+ // Development artifacts and the Cast & Sets checkpoint are wire-local too:+ // their files and jobs exist only on this install.+ if (Object.hasOwn(local, 'devArtifacts')) remote.devArtifacts = local.devArtifacts;+ if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;if (local.videoSettings && typeof local.videoSettings === 'object'&& !Array.isArray(local.videoSettings) && Object.hasOwn(local.videoSettings, 'backend')) {const remoteVideoSettings = remote.videoSettings && typeof remote.videoSettings === 'object'diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex a27ef0f6eb..1dc2adc3c3 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -128,6 +128,18 @@ describe('cloneProjectRecord', () => {expect(without).not.toHaveProperty('autoReviews');});+ it('carries development artifacts and the Cast & Sets result to a clone, but not its dispatch pin or production link', () => {+ const artifact = { id: 'mvd-1', kind: 'cast-sets', title: 'Sheet', status: 'approved', version: 2, file: 'music-video/mv-1/dev/mvd-1/v2.html', versions: [], notes: [] };+ const clone = cloneProjectRecord({+ ...baseProject(),+ devArtifacts: [artifact],+ castAndSets: { status: 'imaging', revision: 2, processId: 'proc-a', productionRunId: 'mvpr-1', artifactId: 'mvd-1', images: { character: { status: 'done', imageId: 'c.png' } } },+ }, { id: 'mv-2', now: '2026-01-02T00:00:00.000Z' });+ expect(clone.devArtifacts).toEqual([artifact]);+ expect(clone.castAndSets).toMatchObject({ status: 'imaging', revision: 2, processId: null, productionRunId: null, artifactId: 'mvd-1' });+ expect(cloneProjectRecord(baseProject(), { id: 'mv-3', now: '2026-01-02T00:00:00.000Z' })).not.toHaveProperty('castAndSets');+ });+it('can fork the board without carrying generated media', () => {const source = {...baseProject(),@@ -305,9 +317,13 @@ describe('applyProjectPatch', () => {automation: { tools: ['video:fal', 'image:codex', 'video:fal'], guidance: 'surreal', budgetUsd: 25 },}, { id: 'mv-a', now: 'n' });// De-duplicated, in catalog order (image before video).- expect(created.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'surreal', budgetUsd: 25 });- const edited = applyProjectPatch(created, { automation: { guidance: 'darker' } });- expect(edited.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'darker', budgetUsd: 25 });+ // The Cast & Sets check-in gate defaults to review.+ expect(created.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'surreal', budgetUsd: 25, checkins: { castAndSets: 'review' } });+ const auto = applyProjectPatch(created, { automation: { checkins: { castAndSets: 'auto' } } });+ expect(auto.automation.checkins).toEqual({ castAndSets: 'auto' });+ const edited = applyProjectPatch(auto, { automation: { guidance: 'darker' } });+ // A guidance edit keeps the gate the director chose.+ expect(edited.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'darker', budgetUsd: 25, checkins: { castAndSets: 'auto' } });expect(applyProjectPatch(edited, { automation: { budgetUsd: null } }).automation.budgetUsd).toBeNull();expect(applyProjectPatch(edited, { automation: null }).automation).toBeNull();});@@ -579,6 +595,25 @@ describe('mergeProjectRecord (#1770 LWW)', () => {expect(next.productionRuns).toEqual(runs);});+ it('keeps development artifacts and the Cast & Sets checkpoint install-local (their files and jobs live here)', async () => {+ const { sanitizeRecordForWire } = await import('../../lib/syncWire.js');+ const devArtifacts = [{ id: 'mvd-1', kind: 'cast-sets', file: 'music-video/mv-1/dev/mvd-1/v1.html' }];+ const castAndSets = { status: 'review', processId: 'proc-local' };+ const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'local', devArtifacts, castAndSets };+ const wire = sanitizeRecordForWire('musicVideoProject', local);+ expect(wire).not.toHaveProperty('devArtifacts');+ expect(wire).not.toHaveProperty('castAndSets');++ const foreign = { devArtifacts: [{ id: 'mvd-foreign' }], castAndSets: { status: 'imaging' } };+ const inserted = mergeProjectRecord(null, { id: 'mv-2', updatedAt: '2026-01-02T00:00:00Z', ...foreign }).next;+ expect(inserted).not.toHaveProperty('devArtifacts');+ expect(inserted).not.toHaveProperty('castAndSets');+ const { next } = mergeProjectRecord(local, { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'remote edit', ...foreign });+ expect(next.name).toBe('remote edit');+ expect(next.devArtifacts).toEqual(devArtifacts);+ expect(next.castAndSets).toEqual(castAndSets);+ });+it('remote with a newer updatedAt wins', () => {const local = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00Z', name: 'old' };const remote = { id: 'mv-1', updatedAt: '2026-01-05T00:00:00Z', name: 'new' };diff --git a/server/services/musicVideoCastSetsImageHook.js b/server/services/musicVideoCastSetsImageHook.jsnew file mode 100644index 0000000000..3f5f8a613d--- /dev/null+++ b/server/services/musicVideoCastSetsImageHook.js@@ -0,0 +1,47 @@+/**+ * Music Video Cast & Sets image attach hook.+ *+ * The Cast & Sets check-in (musicVideo/castAndSetsService.js) queues its+ * reference images — character sheet, expressions, looks, set plates, in-set+ * tests — on the normal image queue with a `musicVideo: { projectId,+ * castAndSets: { key, revision } }` tag. This hook files each finished render+ * back onto that key and lets the stage continue (dispatch the images that+ * were waiting on it, or assemble the sheet), independent of any open client.+ * A failed or cancelled job settles its key as failed (the stage retries it+ * once). The scene-frame hook ignores these jobs: their tag has no `sceneId`.+ *+ * Built on the shared completion-hook scaffold (`createMediaJobImageHook`),+ * which owns the idempotent init, per-project serialization and best-effort+ * error handling. Mounted once at server boot; it only listens.+ */++import { createMediaJobImageHook } from './mediaJobImageHook.js';++const settle = async (payload) => (await import('./musicVideo/castAndSetsService.js')).onCastAndSetsImageSettled(payload);++const hook = createMediaJobImageHook({+ label: 'music-video cast & sets image',+ initLog: '🎭 Music Video Cast & Sets image hook initialized',+ tagKey: 'musicVideo',+ identify: (tag) => (tag?.projectId && typeof tag.castAndSets?.key === 'string'+ ? { projectId: tag.projectId, key: tag.castAndSets.key }+ : null),+ serializeKey: ({ projectId }) => projectId,+ describe: ({ projectId, key }) => `${projectId}/${key}`,+ attach: ({ projectId, key, filename, job }) => settle({+ projectId, key, filename, jobId: typeof job.id === 'string' ? job.id : null,+ }).then((changed) => (changed ? { filename } : null)),+ onAttached: ({ projectId, key, filename }) => {+ console.log(`🎭 music-video cast & sets ${projectId.slice(0, 11)}/${key} ← ${filename}`);+ },+ onTerminal: ({ projectId, key, job }, status) => settle({+ projectId, key, jobId: typeof job?.id === 'string' ? job.id : null, error: job?.error || `The render was ${status}`,+ }),+});++export function initMusicVideoCastSetsImageHook() {+ hook.init();+}++// Test-only reset so suites that re-init can do so cleanly.+export const __testing = hook.__testing;diff --git a/server/services/socket.js b/server/services/socket.jsindex 88b0cd1c23..89ae40566b 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -313,6 +313,9 @@ const SIMPLE_BRIDGES = [{ emitter: musicVideoEvents, event: 'scene-video', channel: 'music-video:scene-video' },{ emitter: musicVideoEvents, event: 'auto-review', channel: 'music-video:auto-review' },{ emitter: musicVideoEvents, event: 'production', channel: 'music-video:production' },+ // The Cast & Sets check-in advancing, and a development artifact changing.+ { emitter: musicVideoEvents, event: 'cast-and-sets', channel: 'music-video:cast-and-sets' },+ { emitter: musicVideoEvents, event: 'dev-artifact', channel: 'music-video:dev-artifact' },];let forwardingRegistered = false;