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: review music-video art, choreography and animated evidence before production
[._.]/ Adam Eivy4bd8538c3daf
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsxnew file mode 100644index 0000000000..761dc71a82--- /dev/null+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx@@ -0,0 +1,168 @@+import { useState } from 'react';++const EMPTY = { cast: '', environments: '', visualLanguage: '', motionLanguage: '', guideArtifactId: null,+ lyricsMode: 'vocal', timingStatus: 'provisional', timingNotes: '', storyboard: [] };+const fieldClass = 'mt-1 w-full rounded border border-port-border bg-port-bg p-2 text-sm';+const buttonClass = 'min-h-[44px] rounded border border-port-border px-3 py-2 text-sm disabled:opacity-50';+const labels = { art: 'Art direction', storyboard: 'Lyric-timed storyboard', proof: 'Animated proof' };++/** Editable planning content and explicit operator decisions for every render mode. */+export default function ProductionReviewPanel({ project, review, onOpenArtifact }) {+ const fieldId = key => `mv-review-${project.id}-${key}`;+ const saved = project.productionReview?.draft || EMPTY;+ const [local, setLocal] = useState(null);+ const draft = local || saved;+ const dirty = !!local && JSON.stringify(local) !== JSON.stringify(saved);+ const [password, setPassword] = useState('');+ const [feedback, setFeedback] = useState({ stage: 'art', target: '', text: '', decision: 'request-changes' });+ const [resolutions, setResolutions] = useState({});+ const [importError, setImportError] = useState(null);+ const [watched, setWatched] = useState(null);+ const [startSec, setStartSec] = useState(project.productionReview?.proof?.startSec || 0);+ const [endSec, setEndSec] = useState(project.productionReview?.proof?.endSec || Math.min(20, project.audioAnalysis?.durationSec || 20));+ const ready = review.readiness;+ const set = (key, value) => setLocal({ ...draft, [key]: value });+ const shots = [...draft.storyboard, ...(project.scenes || []).filter(scene => !draft.storyboard.some(s => s.sceneId === scene.sceneId)).map(scene => ({+ id: scene.sceneId, sceneId: scene.sceneId, lyricCueIds: [], action: '', staging: '', camera: '', transition: '',+ }))];+ const shotKey = shot => shot.id || shot.sceneId;+ const setShot = (shot, key, value) => set('storyboard', shots.map(s => shotKey(s) === shotKey(shot) ? { ...s, [key]: value } : s));+ const blocked = dirty || review.busy || !ready;+ const prototype = project.excerpts?.find(e => e.id === project.productionReview?.prototype?.excerptId);+ const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);+ const approve = stage => { const secret = password; setPassword(''); return review.approve(stage, secret); };++ return <section id="mv-production-review" aria-label="Production review" className="rounded-lg border border-port-border bg-port-card p-3 space-y-3">+ <h3 className="font-medium">Production review</h3>+ <p className="text-sm text-port-text-muted">Every medium needs visual direction, a timed storyboard and a watched animated proof. Drafts and technical renders do not count as approval.</p>+ {review.error && <p role="alert" className="text-port-error">{review.error}</p>}+ <ol className="grid gap-2 sm:grid-cols-3">+ {Object.entries(labels).map(([key, label]) => <li key={key} className="rounded border border-port-border p-2">+ <strong className="text-sm">{label}</strong>+ <p role="status" className="text-xs">{ready?.[key].approved ? 'Approved for this revision' : 'Human review required'}</p>+ {(ready?.[key].problems || []).map(problem => <p key={problem} className="mt-1 text-xs text-port-text-muted">{problem}</p>)}+ <button type="button" className={`${buttonClass} mt-2`} onClick={() => approve(key)}+ disabled={blocked || !password || ready?.[key].approved || !!ready?.[key].problems.length+ || (key === 'proof' && watched !== ready?.basis.proof)}>+ Approve {label.toLowerCase()}+ </button>+ </li>)}+ </ol>+ <label htmlFor={fieldId('password')} className="block text-sm">Instance password for this approval+ <input id={fieldId('password')} type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} className={fieldClass} />+ </label>+ <p className="text-xs text-port-text-muted">Enter it yourself. API tokens cannot approve. Password-free installs can prepare drafts; set an instance password in Settings → Security before approval.</p>+ <details>+ <summary className="cursor-pointer min-h-[44px] py-2 text-sm">Review feedback and revision history</summary>+ <p className="text-sm">Name a cast member, environment, shot, artifact or frame time. Structure acceptance records agreement on organization only; it never approves the art or authorizes production.</p>+ <label htmlFor={fieldId('feedback-stage')} className="block text-sm">Feedback stage<select id={fieldId('feedback-stage')} className={fieldClass} value={feedback.stage} onChange={e => setFeedback({ ...feedback, stage: e.target.value })}>+ {Object.entries(labels).map(([key, label]) => <option key={key} value={key}>{label}</option>)}+ </select></label>+ <label htmlFor={fieldId('feedback-target')} className="block text-sm">Feedback target<input id={fieldId('feedback-target')} className={fieldClass} value={feedback.target} placeholder="Cast: operator; shot: chorus; frame: 12.5s" onChange={e => setFeedback({ ...feedback, target: e.target.value })} /></label>+ <label htmlFor={fieldId('feedback-text')} className="block text-sm">Requested change<textarea id={fieldId('feedback-text')} className={fieldClass} rows={3} value={feedback.text} onChange={e => setFeedback({ ...feedback, text: e.target.value })} /></label>+ <label htmlFor={fieldId('feedback-decision')} className="block text-sm">Review decision<select id={fieldId('feedback-decision')} className={fieldClass} value={feedback.decision} onChange={e => setFeedback({ ...feedback, decision: e.target.value })}>+ <option value="request-changes">Request changes — blocks affected approvals</option><option value="comment">Comment</option><option value="structure-accepted">Accept structure only — art remains unapproved</option>+ </select></label>+ <button type="button" className={buttonClass} disabled={blocked || !feedback.target.trim() || !feedback.text.trim()} onClick={async () => {+ if (await review.feedback(feedback)) setFeedback({ ...feedback, text: '' });+ }}>Save revision feedback</button>+ <ul className="mt-3 space-y-3">{(project.productionReview?.feedback || []).map(item => <li key={item.id} className="rounded border border-port-border p-2">+ <p className="text-sm"><strong>{item.target}</strong> · {item.decision} · {item.resolvedAt ? 'Resolved' : 'Open'}</p>+ <p className="text-sm whitespace-pre-wrap">{item.text}</p>+ <p className="text-xs text-port-text-muted">Reviewed revision {item.basis.slice(0, 12)}{ready?.basis[item.stage] !== item.basis ? ' · content has changed since review' : ' · current revision'}</p>+ <details><summary className="cursor-pointer py-2 text-sm">Original reviewed content</summary><pre className="max-h-60 overflow-auto whitespace-pre-wrap text-xs">{JSON.stringify(project.productionReview.reviewedRevisions?.[item.basis]?.draft, null, 2)}</pre></details>+ {item.resolvedAt ? <p className="text-sm">Resolution: {item.resolution}</p> : <>+ <label htmlFor={fieldId(`resolution-${item.id}`)} className="block text-sm">Resolution for {item.target}<textarea id={fieldId(`resolution-${item.id}`)} className={fieldClass} value={resolutions[item.id] || ''} onChange={e => setResolutions({ ...resolutions, [item.id]: e.target.value })} /></label>+ <button type="button" className={buttonClass} disabled={blocked || !password || !resolutions[item.id]?.trim()} onClick={async () => {+ const secret = password; setPassword(''); await review.resolveFeedback(item.id, resolutions[item.id], secret);+ }}>Resolve feedback after review</button>+ </>}+ </li>)}</ul>+ </details>+ <details>+ <summary className="cursor-pointer min-h-[44px] py-2 text-sm">Edit visual guide and storyboard</summary>+ <div className="space-y-3">+ <label htmlFor={fieldId('import')} className="block text-sm">Import planning JSON as an unapproved draft+ <input id={fieldId('import')} type="file" accept=".json,application/json" disabled={dirty || review.busy} className={fieldClass}+ onChange={async e => {+ const file = e.target.files?.[0]; e.target.value = ''; setImportError(null);+ if (!file) return;+ try { if (await review.importPlanning(await file.text())) setLocal(null); }+ catch (error) { setImportError(error.message); }+ }} />+ </label>+ {importError && <p role="alert">{importError}</p>}+ {draft.sourceArtifactId && <button type="button" className={buttonClass} onClick={() => onOpenArtifact(draft.sourceArtifactId)}>Read preserved original planning draft</button>}+ <button type="button" className={buttonClass} disabled={dirty || review.busy} onClick={review.prepare}>Prepare planning draft with autopilot</button>+ <p className="text-xs text-port-text-muted">Uses the saved authoring provider and allowed tools. Builds Cast & Sets first, then pauses for art approval before planning shots. Existing edits are retained.</p>+ <div className="grid gap-3 sm:grid-cols-2">+ {Object.entries({ cast: 'Cast guide', environments: 'Environment guide', visualLanguage: 'Visual language and mood board', motionLanguage: 'Motion language and choreography' }).map(([key, label]) =>+ <label key={key} htmlFor={fieldId(key)} className="text-sm">{label}<textarea id={fieldId(key)} rows={4} value={draft[key]} onChange={e => set(key, e.target.value)} className={fieldClass} /></label>)}+ </div>+ <label htmlFor={fieldId('implementation')} className="block text-sm">Implementation and feasibility for {project.composition?.mode || 'composed'} rendering+ <textarea id={fieldId('implementation')} rows={5} value={draft.implementationPlan || ''} onChange={e => set('implementationPlan', e.target.value)} className={fieldClass}+ placeholder="Scene graph and layers; vector/mesh construction; rig joints and pose limits; procedural materials; camera and transition mechanics; typography; frame rate, geometry and draw-call budgets." />+ </label>+ <p className="text-xs text-port-text-muted">Concept references establish intent. Document how this renderer can build and animate the look; a raster reference is not code-rendered evidence. Changing the plan invalidates prior art approval.</p>+ <label htmlFor={fieldId('guide')} className="block text-sm">Visual cast and environment sheet+ <select id={fieldId('guide')} value={draft.guideArtifactId || ''} onChange={e => set('guideArtifactId', e.target.value || null)} className={fieldClass}>+ <option value="">Choose a Development artifact</option>+ {(project.devArtifacts || []).filter(a => !a.deleted).map(a => <option key={a.id} value={a.id}>{a.title}</option>)}+ </select>+ </label>+ {draft.guideArtifactId && <button type="button" className={buttonClass} onClick={() => onOpenArtifact(draft.guideArtifactId)}>Review visual sheet</button>}+ <label htmlFor={fieldId('song-content')} className="block text-sm">Song content+ <select id={fieldId('song-content')} value={draft.lyricsMode} onChange={e => set('lyricsMode', e.target.value)} className={fieldClass}>+ <option value="vocal">Vocal song — aligned lyrics required</option><option value="instrumental">Instrumental — explicit exception</option>+ </select>+ </label>+ <label htmlFor={fieldId('alignment-status')} className="block text-sm">Alignment status+ <select id={fieldId('alignment-status')} value={draft.timingStatus} onChange={e => set('timingStatus', e.target.value)} className={fieldClass}>+ <option value="provisional">Provisional — needs listening and correction</option><option value="verified">Verified against the current master vocal</option>+ </select>+ </label>+ <label htmlFor={fieldId('alignment-notes')} className="block text-sm">Alignment notes / instrumental rationale<textarea id={fieldId('alignment-notes')} rows={2} value={draft.timingNotes} onChange={e => set('timingNotes', e.target.value)} className={fieldClass} /></label>+ {shots.map(shot => {+ const scene = project.scenes?.find(s => s.sceneId === shot.sceneId);+ return <details key={shotKey(shot)} className="rounded border border-port-border p-2">+ <summary className="cursor-pointer min-h-[44px] text-sm">{scene?.label || shot.id || 'Unbound shot'} — {scene ? 'edit choreography' : 'bind to a Board scene'}</summary>+ <label htmlFor={fieldId(`scene-${shotKey(shot)}`)} className="block text-sm">Board scene+ <select id={fieldId(`scene-${shotKey(shot)}`)} value={shot.sceneId || ''} onChange={e => setShot(shot, 'sceneId', e.target.value || null)} className={fieldClass}>+ <option value="">Unbound draft — no scene selected</option>+ {(project.scenes || []).map(s => <option key={s.sceneId} value={s.sceneId}>{s.label || s.sceneId}</option>)}+ </select>+ </label>+ {!scene && <button type="button" className={buttonClass} disabled={dirty || review.busy || !shot.id} onClick={() => review.bindShot(shot.id)}>Create Board scene from this draft shot</button>}+ <p className="text-xs text-port-text-muted">Review exact start/end in Board. Imported timings remain provisional.</p>+ {['action', 'staging', 'camera', 'transition'].map(key => <label key={key} htmlFor={fieldId(`${shotKey(shot)}-${key}`)} className="block text-sm capitalize">{key}+ <textarea id={fieldId(`${shotKey(shot)}-${key}`)} rows={2} value={shot[key]} onChange={e => setShot(shot, key, e.target.value)} className={fieldClass} />+ </label>)}+ <fieldset><legend className="text-sm">Lyric anchors</legend>+ {(project.lyricCues || []).filter(c => c.startSec < scene?.endSec && c.endSec > scene?.startSec).map(cue =>+ <label key={cue.id} htmlFor={fieldId(`${shotKey(shot)}-${cue.id}`)} className="flex gap-2 py-2 text-sm"><input id={fieldId(`${shotKey(shot)}-${cue.id}`)} type="checkbox" checked={shot.lyricCueIds.includes(cue.id)}+ onChange={e => setShot(shot, 'lyricCueIds', e.target.checked ? [...shot.lyricCueIds, cue.id] : shot.lyricCueIds.filter(id => id !== cue.id))} />{cue.text}</label>)}+ </fieldset>+ </details>;+ })}+ <button type="button" className={buttonClass} disabled={!dirty || review.busy} onClick={async () => { if (await review.save(draft)) setLocal(null); }}>Save planning edits</button>+ {dirty && <p role="status" className="text-sm">Save edits before preparing, approving or rendering.</p>}+ </div>+ </details>+ <details open={ready?.storyboard.approved && !ready?.proof.approved}>+ <summary className="cursor-pointer min-h-[44px] py-2 text-sm">Animated chorus proof</summary>+ <p className="text-sm">Author the approved storyboard in Compose, then render a 10–45 second chorus with its entry and exit. Watch with sound; check lyric timing, readable type, purposeful action, camera movement and transitions.</p>+ <div className="flex flex-wrap items-end gap-2">+ <label htmlFor={fieldId('proof-start')} className="text-sm">Proof start (seconds)<input id={fieldId('proof-start')} type="number" min="0" step="0.01" value={startSec} onChange={e => setStartSec(Number(e.target.value))} className={fieldClass} /></label>+ <label htmlFor={fieldId('proof-end')} className="text-sm">Proof end (seconds)<input id={fieldId('proof-end')} type="number" min="0" step="0.01" value={endSec} onChange={e => setEndSec(Number(e.target.value))} className={fieldClass} /></label>+ <button type="button" className={buttonClass} disabled={blocked || review.proof.active} onClick={() => review.renderProof({ startSec, endSec, kind: 'prototype' })}>Render feasibility prototype — unapproved</button>+ <button type="button" className={buttonClass} disabled={blocked || !ready?.storyboard.approved || review.proof.active} onClick={() => review.renderProof({ startSec, endSec })}>Render animated proof</button>+ </div>+ {review.proof.active && <p role="status">Rendering proof…</p>}+ <p className="text-xs text-port-text-muted">A feasibility prototype uses the current authored composition and master audio without approving the look or authorizing production. It can be made before art approval; it never becomes approved proof automatically.</p>+ {prototype?.status === 'complete' && prototype.filename && <figure><video controls className="mt-2 w-full rounded" aria-label="Unapproved feasibility prototype" src={`/data/videos/${encodeURIComponent(prototype.filename)}`} /><figcaption className="text-sm">Unapproved feasibility prototype — separate from production proof</figcaption></figure>}+ {excerpt?.status === 'complete' && excerpt.filename && <video controls className="mt-2 w-full rounded" aria-label="Animated proof with master audio" src={`/data/videos/${encodeURIComponent(excerpt.filename)}`} />}+ <label htmlFor={fieldId('watched')} className="flex gap-2 py-2 text-sm"><input id={fieldId('watched')} type="checkbox" checked={!!ready && watched === ready.basis.proof}+ disabled={!ready || !!ready.proof.problems.length} onChange={e => setWatched(e.target.checked ? ready.basis.proof : null)} />I watched this revision with audio and checked the approved visual direction, motion and lyric timing.</label>+ </details>+ </section>;+}diff --git a/client/src/components/musicVideo/ProjectActionGroups.jsx b/client/src/components/musicVideo/ProjectActionGroups.jsxindex bc7aa410f5..252a321a4c 100644--- a/client/src/components/musicVideo/ProjectActionGroups.jsx+++ b/client/src/components/musicVideo/ProjectActionGroups.jsx@@ -161,7 +161,7 @@ export function RenderStyleSelect({ project, onRenderStyle }) {}/** Render the complete video, or cancel the render in flight for this project. */-export function RenderFinalButton({ project, renderJob }) {+export function RenderFinalButton({ project, renderJob, readiness }) {const scenes = project.scenes || [];const sceneCount = scenes.length;const mode = project.composition?.mode || 'concat';@@ -191,8 +191,8 @@ export function RenderFinalButton({ project, renderJob }) {);}return (- <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || (documentMode ? !!documentBlocked : codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}- title={renderJob.active+ <button onClick={() => renderJob.start(project.id)} disabled={!readiness?.readyForProduction || renderJob.active || (documentMode ? !!documentBlocked : codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}+ title={!readiness?.readyForProduction ? 'Approve the current visual guide, timed storyboard and animated proof first' : renderJob.active? 'Wait for the other project render to finish, or return to it to cancel': documentMode? (documentBlocked || 'Render the composition document over the song')diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsxindex 6aa984e8f4..40fb2bfbc3 100644--- a/client/src/components/musicVideo/PublishPostingPanel.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx@@ -1,5 +1,5 @@import { useState } from 'react';-import { Send, ExternalLink, X as XIcon, LogIn, Link as LinkIcon } from 'lucide-react';+import { ExternalLink, X as XIcon, LogIn, Link as LinkIcon } from 'lucide-react';// Where the release goes, in posting order: the full video first so every// other post can link to it.@@ -125,6 +125,7 @@ function TargetRow({ project, kit, entry, publishing }) {const { target, label, note } = entry;const idFor = (key) => `mv-post-${project.id}-${target}-${key}`;const [options, setOptions] = useState({});+ const [password, setPassword] = useState('');const setOption = (key, value) => setOptions((prev) => ({ ...prev, [key]: value }));const draft = publishing.drafts[target];const busy = publishing.busy[target];@@ -136,6 +137,10 @@ function TargetRow({ project, kit, entry, publishing }) {return (<li className="rounded border border-port-border p-2 space-y-2">+ <p className="text-xs text-port-text-muted">Preparing a draft may upload files and save platform metadata. This is separate from production and never publishes.</p>+ <label htmlFor={idFor('password')} className="block text-xs">Instance password to prepare {label}+ <input id={idFor('password')} type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} className={inputCls} />+ </label><div className="flex flex-wrap items-start justify-between gap-2"><div className="min-w-0"><div className="text-xs font-medium">{label}{account && <span className="font-normal text-port-text-muted"> as @{account}</span>}</div>@@ -146,7 +151,7 @@ function TargetRow({ project, kit, entry, publishing }) {</a>)}</div>- <button type="button" onClick={() => publishing.prepare(target, clean)} disabled={!!busy}+ <button type="button" onClick={() => { publishing.prepare(target, { ...clean, password }); setPassword(''); }} disabled={!!busy || !password}className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">{busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}</button>@@ -170,10 +175,7 @@ function TargetRow({ project, kit, entry, publishing }) {))}</dl><div className="flex flex-wrap gap-2">- <button type="button" onClick={() => publishing.submit(target)} disabled={!!busy}- className="flex items-center gap-1 bg-port-accent text-white disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">- <Send size={13} /> {busy === 'submit' ? 'Posting…' : `Post to ${label}`}- </button>+ <p className="text-sm">Review and publish yourself in the destination platform's open browser tab. PortOS cannot submit this draft. Record the resulting link below.</p><button type="button" onClick={() => publishing.discard(target)} disabled={!!busy}className="flex items-center gap-1 border border-port-border disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0"><XIcon size={13} /> Discard@@ -188,8 +190,7 @@ function TargetRow({ project, kit, entry, publishing }) {/*** Posting (#9282): each platform's post is filled in the PortOS Browser (in* a new tab, with the director's signed-in sessions) and shown back here as- * a screenshot and summary. Nothing is posted until the director presses- * Post for that draft.+ * a screenshot and summary. Publication is performed manually on the platform.*/export default function PublishPostingPanel({ project, publishing }) {const kit = project?.publishKit || {};@@ -198,9 +199,9 @@ export default function PublishPostingPanel({ project, publishing }) {const targets = PUBLISH_TARGETS.filter((entry) => publishing.enabledTargets?.includes(entry.target));return (<section aria-label="Post the release" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">- <h3 className="text-sm font-medium flex items-center gap-1.5"><Send size={14} /> Post the release</h3>- <p className="text-port-text-muted">Sign in to each platform in the PortOS Browser first. Fill draft opens a new tab there and fills the post from the kit and copy above; nothing is posted until you review it and press Post.</p>- {!targets.length && <p className="text-port-text-muted">Turn on the platforms you use under Where you post to fill and post drafts here.</p>}+ <h3 className="text-sm font-medium flex items-center gap-1.5"><ExternalLink size={14} /> Publish manually</h3>+ <p className="text-port-text-muted">Sign in to each platform in the PortOS Browser first. Fill draft opens a new tab there and fills the post from the kit and copy above; review and publish yourself on the platform. PortOS cannot submit posts.</p>+ {!targets.length && <p className="text-port-text-muted">Turn on the platforms you use under Where you post to prepare drafts. Final publication happens on each platform.</p>}<ul className="space-y-2">{targets.map((entry) => <TargetRow key={`${project.id}-${entry.target}`} project={project} kit={kit} entry={entry} publishing={publishing} />)}</ul>diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsxindex 2c83ba68b9..f417ff4683 100644--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx@@ -31,19 +31,20 @@ describe('PublishPostingPanel (#9282)', () => {const reddit = row('Reddit');fireEvent.change(within(reddit).getByLabelText('Subreddit'), { target: { value: 'SunoAI' } });fireEvent.change(within(reddit).getByLabelText('Post type'), { target: { value: 'link' } });+ fireEvent.change(within(reddit).getByLabelText('Instance password to prepare Reddit'), { target: { value: 'synthetic-password' } });fireEvent.click(within(reddit).getByRole('button', { name: 'Fill draft' }));- expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link' });+ expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link', password: 'synthetic-password' });});- it('shows the filled draft and posts only when Post is pressed', () => {+ it('shows the filled draft and requires manual platform publication', () => {const publishing = hook({ drafts: { stackerNews: { draftId: 'd1', summary: { title: 'Song', territory: 'art' }, screenshot: 'data:image/jpeg;base64,AA' } } });render(<PublishPostingPanel project={project()} publishing={publishing} />);const sn = row('Stacker News');expect(within(sn).getByAltText('Stacker News draft as filled')).toBeInTheDocument();expect(within(sn).getByText('Song')).toBeInTheDocument();expect(publishing.submit).not.toHaveBeenCalled();- fireEvent.click(within(sn).getByRole('button', { name: /Post to Stacker News/ }));- expect(publishing.submit).toHaveBeenCalledWith('stackerNews');+ expect(within(sn).queryByRole('button', { name: /Post to Stacker News/ })).toBeNull();+ expect(within(sn).getByText(/PortOS cannot submit this draft/)).toBeInTheDocument();fireEvent.click(within(sn).getByRole('button', { name: /Discard/ }));expect(publishing.discard).toHaveBeenCalledWith('stackerNews');});diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsxindex 68a24b48e4..26b34b4505 100644--- a/client/src/components/musicVideo/stages/ReviewStage.jsx+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx@@ -21,7 +21,7 @@ export default function ReviewStage({ board }) {<section id="mv-final-video" aria-label="Final render" className="rounded-lg border border-port-border bg-port-card p-3"><div className="flex flex-wrap items-center justify-between gap-2"><h3 className="text-sm font-medium">Final render</h3>- <RenderFinalButton project={project} renderJob={renderJob} />+ <RenderFinalButton project={project} renderJob={renderJob} readiness={board.productionReadiness} /></div><RenderStatusPanelrendering={renderBound}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex cf1f73af7c..6eb27729c0 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -288,3 +288,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useGraphNodeDetail` | Selection-keyed graph record loading with render-time identity gating and late-response disposal. | Brain and CoS graph detail panels. || `useModelLifecycle` | Targeted 3D model lifecycle reads, cancellation and bounded transient recovery. | Image-to-3D and procedural model views. |++| `useMusicVideoProductionReview` | Server-authoritative art/storyboard/proof approvals and SSE proof rendering, with stale-readiness suppression. | Music Video production review. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 50dfc9e7fb..03dd7e22fd 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -269,3 +269,5 @@ export * from './useFableLoomRun.js';export { default as useGraphNodeDetail } from './useGraphNodeDetail.js';export * from './useModelLifecycle.js';++export { default as useMusicVideoProductionReview } from './useMusicVideoProductionReview.js';diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.jsnew file mode 100644index 0000000000..33e9abde04--- /dev/null+++ b/client/src/hooks/useMusicVideoProductionReview.js@@ -0,0 +1,63 @@+import { useEffect, useRef, useState } from 'react';+import { getMusicVideoProductionReview, saveMusicVideoProductionDraft, prepareMusicVideoProductionReview,+ approveMusicVideoProductionReview, renderMusicVideoProductionProof, musicVideoExcerptRenderEventsUrl,+ cancelMusicVideoExcerptRender, importMusicVideoProductionPlanning, bindMusicVideoProductionShot, addMusicVideoProductionFeedback, resolveMusicVideoProductionFeedback } from '../services/apiMusicVideo.js';+import useSseJobSlot from './useSseJobSlot.js';++/** Server-authoritative approvals; changing any project input hides stale readiness immediately. */+export default function useMusicVideoProductionReview({ project, replaceProject }) {+ const latest = useRef(project);+ latest.current = project;+ const seenProofJobs = useRef(new Set());+ const [state, setState] = useState(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(null);+ useEffect(() => {+ let active = true;+ if (project?.id) getMusicVideoProductionReview(project.id, { silent: true })+ .then(result => { if (active) setState({ owner: project, readiness: result.readiness }); })+ .catch(err => { if (active) setError(err.message); });+ return () => { active = false; };+ }, [project]);+ const refresh = async id => {+ const owner = latest.current;+ if (owner?.id !== id) return;+ const result = await getMusicVideoProductionReview(id, { silent: true });+ if (latest.current === owner) replaceProject(result.project);+ };+ const proof = useSseJobSlot({+ startRequest: ({ id, window }) => renderMusicVideoProductionProof(id, window, { silent: true }),+ eventsUrl: musicVideoExcerptRenderEventsUrl, cancelRequest: cancelMusicVideoExcerptRender,+ readPercent: frame => Number.isFinite(frame.progress) ? frame.progress * 100 : undefined,+ onKickoffSuccess: (job, { id }) => { seenProofJobs.current.add(job); refresh(id).catch(err => setError(err.message)); },+ onComplete: (_frame, id) => { refresh(id).catch(err => setError(err.message)); },+ errorFallback: 'The proof render failed',+ });+ useEffect(() => {+ const refs = [project?.productionReview?.proof?.excerptId, project?.productionReview?.prototype?.excerptId];+ const excerpt = project?.excerpts?.find(e => refs.includes(e.id) && e.status === 'rendering' && e.jobId);+ if (excerpt && !seenProofJobs.current.has(excerpt.jobId) && proof.attach(excerpt.jobId, project.id)) seenProofJobs.current.add(excerpt.jobId);+ }, [project, proof.active]);+ const call = async operation => {+ if (!project || busy) return null;+ const owner = project;+ setBusy(true); setError(null);+ try {+ const result = await operation();+ if (latest.current === owner) replaceProject(result.project);+ return result;+ } catch (err) { if (latest.current === owner) setError(err.message); return null; }+ finally { setBusy(false); }+ };+ return { readiness: state?.owner === project ? state.readiness : null, busy, error, proof,+ feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: state?.readiness.basis[body.stage] }, { silent: true })),+ resolveFeedback: (feedbackId, resolution, password) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution, password }, { silent: true })),+ importPlanning: source => call(() => importMusicVideoProductionPlanning(project.id, source, { silent: true })),+ bindShot: shotId => call(() => bindMusicVideoProductionShot(project.id, shotId, { silent: true })),+ save: draft => call(() => saveMusicVideoProductionDraft(project.id, draft, { silent: true })),+ prepare: () => call(() => prepareMusicVideoProductionReview(project.id, {}, { silent: true })),+ approve: (stage, password) => call(() => approveMusicVideoProductionReview(project.id,+ { stage, password, basis: state?.readiness.basis[stage] }, { silent: true })),+ renderProof: window => proof.start({ id: project.id, window }, project.id),+ };+}diff --git a/client/src/lib/musicVideoStages.js b/client/src/lib/musicVideoStages.jsindex 03849d4dcf..24509a0c8c 100644--- a/client/src/lib/musicVideoStages.js+++ b/client/src/lib/musicVideoStages.js@@ -80,7 +80,7 @@ const composeDone = (project, mode) => {* `todo` — plus `current`, the first stage that is not done. A live production* run owns the project, so it pins `current` to Produce.*/-export function deriveStages(project) {+export function deriveStages(project, readiness = project?.productionReadiness) {const scenes = project?.scenes || [];const mode = project?.composition?.mode || 'concat';const cast = project?.castAndSets || null;@@ -89,18 +89,17 @@ export function deriveStages(project) {const layered = isLayeredComposition(project);// Code and document renders draw the picture themselves; scene footage is optional there.const footageOptional = mode === 'code' || mode === 'document';- const planned = scenes.length > 0;- const castApplies = !!cast || !!project?.automation;+ const planned = !!readiness?.storyboard.approved;const castStopped = !!cast && (cast.interrupted || cast.status === 'failed');- const castDone = !castApplies || cast?.status === 'approved' || cast?.status === 'skipped' || (!cast && planned);+ const castDone = !!readiness?.art.approved;const produceDone = planned && (footageOptional || scenes.every((scene) => sceneRenderReady(scene, { layered })));const done = {setup: projectHasAudio(project) && !!project?.audioAnalysis,'cast-sets': castDone,board: planned,- produce: produceDone,- compose: composeDone(project || {}, mode),+ produce: produceDone && !!readiness?.proof.approved,+ compose: !!readiness?.proof.approved && composeDone(project || {}, mode),review: !!project?.renderHistoryId,// #9281/#9282: a release is published once any platform post is recorded.publish: Object.keys(project?.publishKit?.posts || {}).length > 0,@@ -131,14 +130,18 @@ export function deriveStages(project) {export function deriveNextAction(project, {renderActive = false, renderProgress = 0, renderPending = false, renderBlockedByOther = false,kickoffRunning = false, kickoffStep = '', kickoffBlockedReason = null,- planning = false, analyzing = false,+ planning = false, analyzing = false, readiness = project?.productionReadiness,} = {}) {if (!project) return null;- const { current } = deriveStages(project);+ const { current } = deriveStages(project, readiness);const run = currentProductionRun(project);const cast = project.castAndSets || null;const scenes = project.scenes || [];+ if (projectHasAudio(project) && project.audioAnalysis && !CAST_WORKING.has(cast?.status) && !readiness?.readyForProduction && run?.status !== 'running' && !renderActive && !kickoffRunning) {+ return { id: 'review-production', kind: 'goto', stage: !readiness?.art.approved ? 'cast-sets' : !readiness?.storyboard.approved ? 'board' : 'review',+ anchor: 'mv-production-review', label: !readiness?.art.approved ? 'Review art direction' : !readiness?.storyboard.approved ? 'Review timed storyboard' : 'Review animated proof' };+ }if (run && RESUMABLE_RUN_STATUSES.has(run.status)) {if (run.status === 'running' && !run.interrupted) return { id: 'stop-production', kind: 'run', label: 'Stop production', runId: run.id };return {diff --git a/client/src/lib/musicVideoStages.test.js b/client/src/lib/musicVideoStages.test.jsindex 64d878d938..4441beff21 100644--- a/client/src/lib/musicVideoStages.test.js+++ b/client/src/lib/musicVideoStages.test.js@@ -3,6 +3,7 @@ import {MUSIC_VIDEO_STAGES, currentProductionRun, deriveNextAction, deriveStages, projectSpend, resolvePreviewSource, resolveStageParam,} from './musicVideoStages.js';+const APPROVED = { art: { approved: true }, storyboard: { approved: true }, proof: { approved: true }, readyForProduction: true };const ANALYSIS = { bpm: 120, durationSec: 30, sections: [] };const scene = (over = {}) => ({ sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img', videoHistoryId: 'vid', ...over });const run = (over = {}) => ({@@ -28,7 +29,7 @@ describe('deriveStages / deriveNextAction', () => {const waiting = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, automation: {}, castAndSets: { status: 'review' }, scenes: [] };expect(deriveStages(waiting).current).toBe('cast-sets');expect(stateOf(waiting)).toMatchObject({ setup: 'done', 'cast-sets': 'active', board: 'todo' });- expect(deriveNextAction(waiting)).toMatchObject({ id: 'approve-cast-sets', kind: 'run' });+ expect(deriveNextAction(waiting)).toMatchObject({ id: 'review-production', kind: 'goto', stage: 'cast-sets' });const interrupted = { ...waiting, castAndSets: { status: 'imaging', interrupted: true } };expect(stateOf(interrupted)['cast-sets']).toBe('blocked');@@ -54,7 +55,7 @@ describe('deriveStages / deriveNextAction', () => {});it('walks Board → Produce → Compose → Review, then reports a finished project', () => {- const planned = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };+ const planned = { productionReadiness: APPROVED, id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };expect(deriveStages(planned).current).toBe('produce');expect(deriveNextAction(planned)).toMatchObject({ id: 'goto-produce', kind: 'goto', stage: 'produce' });@@ -78,7 +79,7 @@ describe('deriveStages / deriveNextAction', () => {});it('does not require scene footage for code-rendered or document projects', () => {- const bare = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };+ const bare = { productionReadiness: APPROVED, id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };expect(stateOf({ ...bare, composition: { mode: 'code' } }).produce).toBe('done');const doc = { ...bare, composition: { mode: 'document' } };expect(deriveStages(doc).current).toBe('compose');@@ -86,11 +87,19 @@ describe('deriveStages / deriveNextAction', () => {expect(deriveStages({ ...doc, composition: { mode: 'document', document: { directory: 'd' } } }).current).toBe('review');});- it('treats the check-in as not applicable to a hands-on project', () => {- expect(stateOf({ id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [] })['cast-sets']).toBe('done');+ it('requires art review for hands-on projects too', () => {+ expect(stateOf({ id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [] })['cast-sets']).toBe('active');});});+it('never promotes placeholder scenes or imported schematic documents to final production', () => {+ const project = { id: 'example', trackId: 'song', audioAnalysis: ANALYSIS, scenes: [scene()], composition: { mode: 'document', document: { directory: 'draft' } } };+ expect(stateOf(project)).toMatchObject({ 'cast-sets': 'active', board: 'todo', produce: 'todo', compose: 'todo' });+ expect(deriveNextAction(project)).toMatchObject({ id: 'review-production', stage: 'cast-sets' });+ const planned = { ...project, productionReadiness: { ...APPROVED, proof: { approved: false }, readyForProduction: false } };+ expect(deriveNextAction(planned)).toMatchObject({ id: 'review-production', stage: 'review' });+});+describe('projectSpend', () => {it('sums every run and takes the live run\'s cap, falling back to the brief budget', () => {const project = {diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 4da14dc84f..63ba4564af 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -1,3 +1,5 @@+import ProductionReviewPanel from '../components/musicVideo/ProductionReviewPanel.jsx';+import useMusicVideoProductionReview from '../hooks/useMusicVideoProductionReview.js';import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router';import { Plus, Film, Copy, Trash2, Wand2 } from 'lucide-react';@@ -143,13 +145,15 @@ export default function MusicVideo() {// unknown one) the tab is the stage the project was in when it was opened,// pinned so a stage completing mid-session doesn't move the user off the tab// they are working in — the header's next action tracks the project instead.- const progress = useMemo(() => deriveStages(selected), [selected]);+ const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));+ const productionReview = useMusicVideoProductionReview({ project: selected, replaceProject });+ const progress = useMemo(() => deriveStages(selected, productionReview.readiness), [selected, productionReview.readiness]);const [openedStage, setOpenedStage] = useState({ id: null, stage: null });if (selected && openedStage.id !== selected.id) setOpenedStage({ id: selected.id, stage: progress.current });const pinnedStage = openedStage.id === selected?.id ? openedStage.stage : null;const activeStage = resolveStageParam(routeStage) || pinnedStage || progress.current;- const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));+// Functional merges keyed on the captured projectId/sceneId so an async result// that resolves after the user edited the board can't clobber those edits with// a stale project snapshot. `patch` may be a function of the current record@@ -761,6 +765,7 @@ export default function MusicVideo() {const audioFilename = projectAudioFilename(selected);const audioUrl = audioFilename ? trackAudioUrl(audioFilename) : null;const nextAction = selected ? deriveNextAction(selected, {+ readiness: productionReview.readiness,renderActive: renderTargetsSelected,renderProgress: renderJob.progress,renderPending: renderJob.pending,@@ -791,6 +796,7 @@ export default function MusicVideo() {// use, so a panel moving between tabs never changes a signature here.const board = selected ? {project: selected,+ productionReadiness: productionReview.readiness,locked: creativeSetupPending || styleReferencesPending || compositionSavePending > 0,busy: { analyzing, planning, arranging, cloning },tracks,@@ -1082,6 +1088,7 @@ export default function MusicVideo() {><div className="space-y-3 min-w-0"><AutonomousRunPanel key={`autonomous-${selected.id}`} project={selected} auto={autonomous} selectedStage={runStage} onSelectStage={setRunStage} />+ <ProductionReviewPanel key={`production-review-${selected.id}`} project={selected} review={productionReview} onOpenArtifact={openArtifact} /><StageView key={selected.id} board={board} /></div></MusicVideoLayout>diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 2234bc1b89..8639b94ad1 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -35,6 +35,13 @@ const { sseState, ytSseStates, getYtSseState } = vi.hoisted(() => {};});+// This page suite exercises existing controls with production approvals already granted.+// ProductionReviewPanel and route integration suites exercise the real approval refusals.+vi.mock('../hooks/useMusicVideoProductionReview.js', () => ({ default: () => ({+ readiness: { readyForProduction: true, basis: {}, art: { approved: true, problems: [] }, storyboard: { approved: true, problems: [] }, proof: { approved: true, problems: [] } },+ busy: false, error: null, proof: { active: false }, save: vi.fn(), prepare: vi.fn(), approve: vi.fn(), renderProof: vi.fn(),+}) }));+vi.mock('../services/apiMusicVideo.js', () => ({listMusicVideoProjects: vi.fn(async () => []),createMusicVideoProject: vi.fn(),@@ -929,7 +936,7 @@ describe('MusicVideo project video renderer', () => {expect(await screen.findByText(/Split the scene on a lyric or phrase boundary/)).toBeTruthy();fireEvent.click(await screen.findByRole('button', { name: /Split on lyric boundaries/ }));await waitFor(() => expect(splitMusicVideoScene).toHaveBeenCalledWith('mv-2', 's1', 'fal', expect.anything()));- expect(await screen.findByText('Verse · 2/2')).toBeTruthy();+ expect(await screen.findByText('Verse · 2/2', { selector: ':not(option)' })).toBeTruthy();expect(screen.queryByRole('button', { name: /Split on lyric boundaries/ })).toBeNull();});@@ -1680,8 +1687,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {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 });- // The check-in lives on the Cast & Sets tab; the header offers its approval.- expect(screen.getByRole('button', { name: 'Approve cast & sets' })).toBeEnabled();+ // Existing Cast & Sets controls still apply references; Production review separately authorizes work.await openStage('cast-sets');expect(await screen.findByText('Waiting for your check-in.')).toBeTruthy();await settle();@@ -2163,7 +2169,7 @@ describe('MusicVideo stage tabs (#9243)', () => {await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));});- it('approves the Cast & Sets check-in it is waiting on, from any tab', async () => {+ it('keeps the Cast & Sets reference check-in available from its tab', async () => {const waiting = {...PROJECT_ANALYZED, scenes: [], lyricCues: [], automation: { tools: ['image:local'], guidance: '', budgetUsd: null },castAndSets: { status: 'review', revision: 1, plan: {}, images: {} },@@ -2173,7 +2179,8 @@ describe('MusicVideo stage tabs (#9243)', () => {importMusicVideoTrackLyrics.mockResolvedValue({ project: approved, imported: 0, markers: 0 });planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 1, promptsSeeded: false });await openProject(waiting, 'setup');- fireEvent.click(screen.getByRole('button', { name: 'Approve cast & sets' }));+ await openStage('cast-sets');+ fireEvent.click(screen.getByRole('button', { name: /Approve & continue/ }));await waitFor(() => expect(approveMusicVideoCastAndSets).toHaveBeenCalledTimes(1));await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalled());});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 2f0d88fce5..7ecebe0726 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -432,3 +432,15 @@ export const previewMusicVideoAudioTiming = (id, data, options = {}) => request(export const applyMusicVideoAudioTiming = (id, data, options = {}) => request(`/music-video/${encodeURIComponent(id)}/audio-timing/apply`, {method: 'POST', body: JSON.stringify(data), ...options,});++// Human-reviewed production planning and proof. These never accept approval state in a project PATCH.+export const getMusicVideoProductionReview = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review`, options);+export const saveMusicVideoProductionDraft = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review`, { method: 'PUT', body: JSON.stringify(body), ...options });+export const prepareMusicVideoProductionReview = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/prepare`, { method: 'POST', body: JSON.stringify(body), ...options });+export const approveMusicVideoProductionReview = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/approve`, { method: 'POST', body: JSON.stringify(body), ...options });+export const renderMusicVideoProductionProof = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/proof`, { method: 'POST', body: JSON.stringify(body), ...options });+export const importMusicVideoProductionPlanning = (id, source, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/import`, { method: 'POST', body: JSON.stringify({ source }), ...options });+export const bindMusicVideoProductionShot = (id, shotId, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/shots/${encodeURIComponent(shotId)}/bind`, { method: 'POST', ...options });++export const addMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback`, { method: 'POST', body: JSON.stringify(body), ...options });+export const resolveMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback/resolve`, { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdindex 3c47c62117..ba8a222f43 100644--- a/docs/features/music-video-autonomous.md+++ b/docs/features/music-video-autonomous.md@@ -1,6 +1,6 @@# Autonomous Music Video-One prompt in, a finished music video out. The Music Video page's **Autonomous** entry point (and the `music-video-autopilot` scheduled task) starts a server-owned run that does everything the hand-driven flow asks you to set up first: it writes the creative brief, the lyrics and a mood board, makes the song (in Suno, or on this machine), and produces the video with the tools you allowed. Approval checkpoints are optional; with none chosen the run is fully unattended.+One prompt in, a finished music video out. The Music Video page's **Autonomous** entry point (and the `music-video-autopilot` scheduled task) starts a server-owned run that does everything the hand-driven flow asks you to set up first: it writes the creative brief, the lyrics and a mood board, makes the song (in Suno, or on this machine), and produces the video with the tools you allowed. Song-writing checkpoints are optional. Production always pauses for revision-bound human review of the visual guide, lyric-timed storyboard and animated proof.## Pipeline@@ -16,7 +16,7 @@ brief → lyrics → style → song → analyze → produce| `song` | The PortOS Browser drives the Suno web UI (custom mode: lyrics, style, title), only M4A is selected in Suno's Download UI and the completed audio is validated and imported directly into the music library, a Track is created, the take is recorded with `source: 'suno'`, and the project is linked to it. | Suno credits || `song` (local) | `songSource: 'local'` renders the song with the on-device Music Designer engines instead (see [Local song source](#local-song-source)). | free (GPU time) || `analyze` | The usual offline beat / tempo / section analysis. | free |-| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored and rendered directly. | per tool |+| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored after storyboard approval, renders a review proof, then waits for human proof approval before the final render. | per tool |State lives on the project as `autonomousRun` — install-local like `productionRuns` (stripped from the peer wire, not carried into a clone). Each stage settles in one serialized project write, so a crash resumes at the stage that did not settle. After a server restart a run is shown **interrupted** and nothing advances until you resume it (no cold-bootstrap provider calls).@@ -31,6 +31,22 @@ State lives on the project as `autonomousRun` — install-local like `productionApproving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{ lyrics }` or `{ style }`).+## Production review++The **Production review** panel is shared by the manual and autopilot paths. Prepare or import an unapproved planning draft, attach an actual visual sheet, and edit cast, environment, visual and motion direction. The implementation field records scene layers, geometry, rig/pose limits, materials, typography, camera/transition mechanics and performance constraints for the selected renderer. Static concept references communicate intent; they are never animated proof.++Imported storyboard shots may remain unbound. Bind each to an existing Board scene or explicitly create its scene; an import never invents approval or verifies provisional timings. Vocal songs require bounded positive-duration word timings checked against the current master. An instrumental exception requires a rationale and cannot mask existing lyric cues.++Art, storyboard and proof decisions bind to exact content. Changes invalidate affected downstream approvals. Targeted comments and requests for changes retain the original reviewed draft and scene snapshot; unresolved requests block the affected stage. Accepting structure records organizational agreement only. Regeneration receives unresolved feedback, and a human must resolve it and approve the revised content.++Use **Render feasibility prototype — unapproved** to test a current authored composition before committing to its art direction. This makes a local 1–45 second excerpt and never grants production approval. After art and storyboard approval, render a 10–45 second representative chorus proof, watch with audio and approve that revision. Autopilot pauses at the same boundaries; queued provider work and final renders recheck approval before dispatch.++Approval and feedback resolution require the operator to re-enter the existing instance password. Agent bearer credentials cannot authorize those operations. Password-free installs can draft and prototype; setting a password is required before production approval. This separates delegated agent credentials from operator authority; it does not defend against someone who controls the host or knows the password.++External draft preparation also requires operator reauthentication. PortOS never submits a final post: review and publish on the destination platform, then record the resulting link. Existing projects and assets remain intact, but an older project's final render now requires the same production review.++The local browser acceptance test (`server/routes/musicVideoProductionReview.browser.test.js`) exercises the real React controls, approval routes, native code renderer, ffmpeg output and video playback with synthetic data. It requires Chrome, ffmpeg and installed client dependencies; server-only CI skips this cross-workspace check. API and orchestration tests run independently of those visual-test prerequisites.+## Local song source`songSource: 'local'` makes the song with the Music Designer engines (ACE-Step, MiniMax, …) through the same audio media-job lane the Music studio uses — no browser, no Suno account. The request goes through `queueMusicGeneration` (`server/services/musicGeneration.js`, the pipeline behind `POST /api/music/generate`), called in-process.diff --git a/scripts/vitestCiPool.js b/scripts/vitestCiPool.jsindex fea2b53610..9494cc8247 100644--- a/scripts/vitestCiPool.js+++ b/scripts/vitestCiPool.js@@ -20,6 +20,7 @@ export function vitestCiPool({ maxWorkers = 4 } = {}) {export const EXCLUSIVE_CAPTURE_TESTS = ['services/htmlComposition/index.test.js','services/musicVideo/documentRender.browser.test.js',+ 'routes/musicVideoProductionReview.browser.test.js',];// Cutover's real subprocess proof has a four-second test budget. A retaineddiff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 0fe935ba78..0a9466ac09 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -968,6 +968,32 @@ export const musicVideoProjectCloneSchema = z.object({variant: z.enum(['revision', 'video-generation']).optional(),}).strict();+// Review content is editable; approval records are server-owned and never PATCHable.+export const musicVideoProductionDraftSchema = z.object({+ cast: z.string().max(12000), environments: z.string().max(12000),+ visualLanguage: z.string().max(12000), motionLanguage: z.string().max(12000),+ implementationPlan: z.string().max(16000).optional(),+ guideArtifactId: z.string().max(64).nullable(),+ sourceArtifactId: z.string().max(64).nullable().optional(),+ lyricsMode: z.enum(['vocal', 'instrumental']), timingStatus: z.enum(['provisional', 'verified']),+ timingNotes: z.string().max(4000),+ storyboard: z.array(z.object({+ id: z.string().max(64).optional(), startSec: timedSec, endSec: timedSec,+ sceneId: z.string().max(64).nullable(), lyricCueIds: z.array(z.string().max(64)).max(2000),+ action: z.string().max(4000), staging: z.string().max(4000),+ camera: z.string().max(4000), transition: z.string().max(4000),+ }).strict()).max(2000),+}).strict();+export const musicVideoProductionImportSchema = z.object({ source: z.string().min(2).max(250000) }).strict();+export const musicVideoProductionApprovalSchema = z.object({+ stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),+ password: z.string().min(1).max(1024),+}).strict();+export const musicVideoProductionProofSchema = z.object({+ kind: z.enum(['proof', 'prototype']).optional(),+ startSec: z.number().min(0), endSec: z.number().positive(),+}).strict();+// A scene on the director board. `startSec`/`endSec` place it on the timeline;// `prompt` drives the shot's video; `framePrompt`/`referenceImageId` are the// reference-frame inputs the i2v generation (Phase 1b) will consume.@@ -1156,3 +1182,12 @@ export const musicVideoAudioTimingPreviewSchema = z.object({export const musicVideoAudioTimingApplySchema = musicVideoAudioTimingPreviewSchema.extend({basis: z.string().regex(/^[a-f0-9]{32}$/),});++export const musicVideoProductionFeedbackSchema = z.object({+ stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),+ target: z.string().trim().min(1).max(300), text: z.string().trim().min(1).max(8000),+ decision: z.enum(['comment', 'structure-accepted', 'request-changes']),+}).strict();+export const musicVideoProductionFeedbackResolutionSchema = z.object({+ feedbackId: z.string().min(1).max(128), resolution: z.string().trim().min(1).max(8000), password: z.string().min(1).max(1024),+}).strict();diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 8bdbf0c2f2..20fd244ac0 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -54,7 +54,7 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = truimageMode: _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,+ devArtifacts: _devArtifacts, castAndSets: _castAndSets, productionReview: _productionReview,// A fully-autonomous run names this install's providers, Suno songs and// production run (services/musicVideo/autonomousService.js).autonomousRun: _autonomousRun,diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 37ee2f188a..acd62da3fc 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -11,6 +11,8 @@import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { Router } from 'express';+import { musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema } from '../lib/musicVideoValidation.js';+import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionOperator, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback } from '../services/musicVideo/productionReviewService.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {validateRequest,@@ -470,6 +472,40 @@ router.post('/:id/render', asyncHandler(async (req, res) => {res.json(await renderMusicVideo(req.params.id));}));+router.post('/:id/production-review/feedback', asyncHandler(async (req, res) => {+ res.json(await addProductionFeedback(req.params.id, validateRequest(musicVideoProductionFeedbackSchema, req.body)));+}));+router.post('/:id/production-review/feedback/resolve', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoProductionFeedbackResolutionSchema, req.body);+ await requireProductionOperator(req);+ res.json(await closeProductionFeedback(req.params.id, { feedbackId: input.feedbackId, resolution: input.resolution }));+}));+router.get('/:id/production-review', asyncHandler(async (req, res) => {+ res.json(await getProductionReview(req.params.id));+}));+router.post('/:id/production-review/import', asyncHandler(async (req, res) => {+ const { source } = validateRequest(musicVideoProductionImportSchema, req.body);+ res.json(await importProductionPlanning(req.params.id, source));+}));+router.post('/:id/production-review/shots/:shotId/bind', asyncHandler(async (req, res) => {+ res.json(await bindProductionShot(req.params.id, req.params.shotId));+}));+router.put('/:id/production-review', asyncHandler(async (req, res) => {+ res.json(await saveProductionDraft(req.params.id, validateRequest(musicVideoProductionDraftSchema, req.body)));+}));+router.post('/:id/production-review/prepare', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoCastAndSetsStartSchema, req.body || {});+ res.json(await prepareProductionReview(req.params.id, input));+}));+router.post('/:id/production-review/approve', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoProductionApprovalSchema, req.body);+ await requireProductionOperator(req);+ res.json(await approveProductionReview(req.params.id, { stage: input.stage, basis: input.basis }));+}));+router.post('/:id/production-review/proof', asyncHandler(async (req, res) => {+ res.status(202).json(await renderProductionProof(req.params.id, validateRequest(musicVideoProductionProofSchema, req.body)));+}));+// SSE progress stream for a render job. Two-segment path — distinct from the// one-segment GET /:id project read, so it can't shadow it.router.get('/render/:jobId/events', (req, res) => {@@ -680,7 +716,9 @@ router.put('/:id/publish/posts/:target', asyncHandler(async (req, res) => {router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);- const options = validateRequest(musicVideoPublishPrepareSchema, req.body || {});+ await requireProductionOperator(req);+ const { password: _password, ...body } = req.body || {};+ const options = validateRequest(musicVideoPublishPrepareSchema, body);res.json(await preparePublishDraft(req.params.id, target, options));}));diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.jsindex 737f1aa5d5..38210742ae 100644--- a/server/routes/musicVideoAutonomous.test.js+++ b/server/routes/musicVideoAutonomous.test.js@@ -22,6 +22,15 @@ import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots, sweepStrayTempRconst ROOT = () => lazyTempDataRoot('mv-autonomous-route-test-');vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+// Preparing a visual guide may call a provider. Keep that authoring boundary+// inert; persisted review readiness and the HTTP approval transitions are real.+vi.mock('../services/musicVideo/productionReviewService.js', async load => ({+ ...await load(), prepareProductionReview: vi.fn(async () => {}),+}));+vi.mock('../services/auth.js', () => ({+ isAuthEnabled: async () => true,+ verifyPassword: async password => password === 'synthetic-operator-password',+}));const { default: musicVideoRoutes } = await import('./musicVideo.js');const projects = await import('../services/musicVideo/projects.js');@@ -87,6 +96,30 @@ beforeEach(() => {const get = async (id) => (await request(app).get(`/api/music-video/${id}/autonomous`)).body.run;+async function approveSyntheticStoryboard(id) {+ await projects.setProjectAnalysis(id, { durationSec: 20, bpm: 120, beats: [0, 1], downbeats: [0],+ sections: [{ startSec: 0, endSec: 20, label: 'Chorus' }] });+ await projects.updateProject(id, { lyricCues: [{ id: 'line', text: 'Rain on glass', startSec: 1, endSec: 4,+ words: [{ w: 'Rain', conf: 'matched', startSec: 1, endSec: 2 }, { w: 'on', conf: 'matched', startSec: 2, endSec: 3 }, { w: 'glass', conf: 'matched', startSec: 3, endSec: 4 }] }] });+ const scene = await projects.addProjectScene(id, { label: 'Chorus', startSec: 0, endSec: 20, prompt: 'Paper figure in the rain' });+ const { saveGeneratedDevArtifact } = await import('../services/musicVideo/devArtifactService.js');+ const { artifact } = await saveGeneratedDevArtifact(id, { kind: 'cast-sets', title: 'Synthetic visual guide', html: '<html><body>Paper figure, painted rain</body></html>' });+ const base = `/api/music-video/${id}/production-review`;+ const saved = await request(app).put(base).send({ cast: 'Paper figure', environments: 'Painted street',+ visualLanguage: 'Ink and cream', motionLanguage: 'Slow camera orbit', guideArtifactId: artifact.id,+ lyricsMode: 'vocal', timingStatus: 'verified', timingNotes: 'Synthetic fixture onsets checked.',+ storyboard: [{ sceneId: scene.sceneId, lyricCueIds: ['line'], action: 'Step into rain', staging: 'Wide street', camera: 'Orbit', transition: 'Fade' }],+ });+ expect(saved.status).toBe(200);+ for (const stage of ['art', 'storyboard']) {+ const current = await request(app).get(base);+ const approved = await request(app).post(`${base}/approve`).send({ stage,+ basis: current.body.readiness.basis[stage], password: 'synthetic-operator-password' });+ expect(approved.status, JSON.stringify(approved.body)).toBe(200);+ }+}++describe('POST /api/music-video/autonomous', () => {it('validates at the door: a blank prompt, an unknown tool and an unknown field are 400s', async () => {for (const body of [{ prompt: ' ' }, { prompt: 'p', tools: ['image:nope'] }, { prompt: 'p', surprise: true }, {}]) {@@ -95,7 +128,7 @@ describe('POST /api/music-video/autonomous', () => {}});- it('accepts a prompt, persists the run on the real project record and runs through to production', async () => {+ it('persists the review pause and only hands off production after current approvals over HTTP', async () => {const res = await begin({ prompt: 'a courier crosses a rainy city', tools: ['image:local'] });expect(res.status).toBe(202);const id = res.body.project.id;@@ -103,10 +136,20 @@ describe('POST /api/music-video/autonomous', () => {await settle();const run = await get(id);- expect(run.output.productionRunId).toBe('mvpr-1');- expect(startProduction).toHaveBeenCalledTimes(1);- expect(run).toMatchObject({ status: 'running', stage: 'produce', interrupted: false });- expect(Object.values(run.stages).map((s) => s.status)).toEqual(['done', 'done', 'done', 'done', 'done', 'running']);+ expect(run.output.productionRunId).toBeUndefined();+ expect(startProduction).not.toHaveBeenCalled();+ expect(run).toMatchObject({ status: 'needs-human', stage: 'produce', errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED', interrupted: false });+ expect(Object.values(run.stages).map((s) => s.status)).toEqual(['done', 'done', 'done', 'done', 'done', 'failed']);+ // Resume alone is not approval and cannot hand off production.+ expect((await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({})).status).toBe(200);+ await settle();+ expect((await get(id)).status).toBe('needs-human');+ expect(startProduction).not.toHaveBeenCalled();+ await approveSyntheticStoryboard(id);+ expect((await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({})).status).toBe(200);+ await settle();+ expect((await get(id))).toMatchObject({ status: 'running', stage: 'produce', output: { productionRunId: 'mvpr-1' } });+ expect(startProduction).toHaveBeenCalledOnce();const stored = await projects.getProject(id);expect(stored.autonomousRun.output).toMatchObject({ moodBoardId: 'board-1', trackId: 'track-1' });expect(stored.name).toBe('Neon Rain');@@ -124,8 +167,8 @@ describe('POST /api/music-video/autonomous', () => {const ok = await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({ lyrics: '[verse]\nedited' });expect(ok.status).toBe(200);await settle();- expect((await get(id)).output.lyrics).toBe('[verse]\nedited');- expect(startProduction).toHaveBeenCalledTimes(1);+ expect((await get(id))).toMatchObject({ status: 'needs-human', errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED', output: { lyrics: '[verse]\nedited' } });+ expect(startProduction).not.toHaveBeenCalled();});it('cancels a live run, and refuses to cancel or resume one that is finished or absent', async () => {@@ -157,8 +200,8 @@ describe('background workflow ownership', () => {held.resolve();await settling;- expect(startProduction).toHaveBeenCalledTimes(1);- expect((await get(id)).output.productionRunId).toBe('mvpr-1');+ expect(startProduction).not.toHaveBeenCalled();+ expect((await get(id))).toMatchObject({ status: 'needs-human', errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED' });});it('a canceled run releases its held stage before teardown', async () => {diff --git a/server/routes/musicVideoProductionReview.browser.test.js b/server/routes/musicVideoProductionReview.browser.test.jsnew file mode 100644index 0000000000..68d71e4e85--- /dev/null+++ b/server/routes/musicVideoProductionReview.browser.test.js@@ -0,0 +1,135 @@+/** Actual review controls + router/file store + Chrome/ffmpeg proof. No provider or live data. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { existsSync } from 'node:fs';+import { mkdir, writeFile, copyFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { execFileSync, spawn } from 'node:child_process';+import { chromium } from 'playwright-core';+import { createRequire } from 'node:module';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-review-browser-') }));+vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: async () => 'synthetic-instance' }));+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyPassword: async p => p === 'synthetic-password' }));+let endpoint;+vi.mock('../services/browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));+const { PATHS } = await import('../lib/paths.js');+const { findFfmpeg } = await import('../lib/ffmpeg.js');+const { _testChromeCaptureArgs, _waitForTestChrome, _cleanupTestBrowser } = await import('../services/htmlComposition/testBrowserCleanup.js');+const { default: router } = await import('./musicVideo.js');+const store = await import('../services/musicVideo/projects.js');+const { saveGeneratedDevArtifact } = await import('../services/musicVideo/devArtifactService.js');+const chrome = [process.env.CHROME_PATH, chromium.executablePath(), '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome'].find(p => p && existsSync(p));+const ffmpeg = await findFfmpeg();+// Server-only CI intentionally does not install the client workspace. This+// cross-workspace visual test runs when all three local QA prerequisites exist.+const client = resolve(import.meta.dirname, '../../client');+const requireClient = createRequire(join(client, 'package.json'));+let clientBundler;+try {+ clientBundler = ['vite', '@vitejs/plugin-react', '@tailwindcss/postcss'].map(name => requireClient.resolve(name));+} catch (error) {+ if (error.code !== 'MODULE_NOT_FOUND') throw error;+}++let browser, proc, server;+afterAll(async () => {+ await _cleanupTestBrowser({ browser, proc, cleanup: () => {} });+ if (server) await new Promise(resolve => server.close(resolve));+ cleanupTempDataRoots();+});++describe.skipIf(!chrome || !ffmpeg || !clientBundler)('production review in a real browser (Chrome, ffmpeg and client dependencies required)', () => {+ it('reviews, requests targeted revisions, renders and watches real animated evidence before approval', async () => {+ await mkdir(PATHS.music, { recursive: true });+ await mkdir(PATHS.videos, { recursive: true });+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=10', join(PATHS.music, 'synthetic-master.wav')]);+ const p = await store.createProject({ name: 'Example paper doorway', uploadedAudioFilename: 'synthetic-master.wav', composition: { mode: 'code' } });+ await store.setProjectAnalysis(p.id, { durationSec: 10, bpm: 120, beats: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], downbeats: [0, 4, 8], sections: [{ id: 'chorus', label: 'Chorus', startSec: 0, endSec: 10 }] });+ await store.updateProject(p.id, { lyricCues: [{ id: 'line', text: 'Open the doorway', startSec: 1, endSec: 7, words: [{ conf: 'matched', w: 'Open', startSec: 1, endSec: 3 }, { conf: 'matched', w: 'the', startSec: 3, endSec: 4 }, { conf: 'matched', w: 'doorway', startSec: 4, endSec: 7 }] }] });+ const scene = await store.addProjectScene(p.id, { label: 'Chorus', startSec: 0, endSec: 10, prompt: 'A paper doorway opens onto a copper sky.' });+ const { buildCodeTimeline } = await import('../services/musicVideo/codeTimeline.js');+ const sectionId = buildCodeTimeline(await store.getProject(p.id)).sections[0].id;+ await store.updateProject(p.id, { composition: { mode: 'code', codeVideo: { sections: [{ id: sectionId, source: `function render(ctx, env) {+ const w=env.width,h=env.height,t=env.t||0;+ ctx.fillStyle='#151e35';ctx.fillRect(0,0,w,h);+ for(let i=0;i<9;i++){ctx.fillStyle=i%2?'#25314b':'#1d2940';ctx.fillRect(i*w/9,0,w/11,h);}+ const x=w*.34,y=h*.12,dw=w*.32,dh=h*.72;+ ctx.fillStyle='#d59655';ctx.fillRect(x,y,dw,dh);+ ctx.fillStyle='#f1dbb0';ctx.fillRect(x+12,y+12,dw-24,dh-24);+ ctx.fillStyle='#28354b';ctx.fillRect(x+12,y+12,(dw-24)*(1-Math.min(1,t/8)),dh-24);+ ctx.strokeStyle='#b68e60';ctx.lineWidth=4;ctx.strokeRect(x-8,y-8,dw+16,dh+16);+ ctx.fillStyle='#0b1425';ctx.beginPath();ctx.ellipse(w*.52,h*.88,w*.24,h*.05,0,0,Math.PI*2);ctx.fill();+ const fx=w*(.21+.035*t);ctx.fillStyle='#ddc49e';ctx.beginPath();ctx.arc(fx,h*.48,h*.028,0,Math.PI*2);ctx.fill();+ ctx.fillStyle='#a46742';ctx.fillRect(fx-h*.025,h*.51,h*.05,h*.12);+ ctx.strokeStyle='#ddc49e';ctx.lineWidth=h*.012;ctx.beginPath();ctx.moveTo(fx,h*.53);ctx.lineTo(fx+h*.07,h*.48+Math.sin(t)*h*.015);ctx.stroke();+ ctx.strokeStyle='#1a2234';ctx.lineWidth=h*.015;ctx.beginPath();ctx.moveTo(fx-h*.016,h*.63);ctx.lineTo(fx-h*.025,h*.75);ctx.moveTo(fx+h*.016,h*.63);ctx.lineTo(fx+h*.025,h*.75);ctx.stroke();+ ctx.fillStyle='#f1dbb0';ctx.font='600 '+Math.round(h*.025)+'px sans-serif';ctx.fillText('CHORUS / THE THRESHOLD',w*.05,h*.08);+ }` }] } } });+ const { artifact } = await saveGeneratedDevArtifact(p.id, { kind: 'cast-sets', title: 'Static concept reference — paper doorway', html: '<html><body><h1>Static concept reference</h1><svg viewBox="0 0 600 300"><rect width="600" height="300" fill="#151e35"/><rect x="200" y="30" width="160" height="220" fill="#d59655"/></svg></body></html>' });+ const draft = { cast: 'Small paper operator in a copper vest.', environments: 'Indigo archive, layered door and warm sky.', visualLanguage: 'Cream paper, copper light, readable negative space.', motionLanguage: 'Operator reaches toward door; doorway opens through chorus.', guideArtifactId: artifact.id, lyricsMode: 'vocal', timingStatus: 'verified', timingNotes: 'Synthetic fixture word timings verified.', storyboard: [{ sceneId: scene.sceneId, lyricCueIds: ['line'], action: 'Open the door', staging: 'Operator left, door center', camera: 'Hold wide with layered depth', transition: 'Hold open doorway' }] };+ const { saveProductionDraft } = await import('../services/musicVideo/productionReviewService.js');+ await saveProductionDraft(p.id, draft);++ const ui = join(PATHS.data, 'review-ui'); await mkdir(ui, { recursive: true });+ const entry = `import React,{useEffect,useState} from 'react';import{createRoot}from'react-dom/client';import Panel from './src/components/musicVideo/ProductionReviewPanel.jsx';import useReview from './src/hooks/useMusicVideoProductionReview.js';function App(){const[p,setP]=useState(null);useEffect(()=>{fetch('/api/music-video/${p.id}/production-review').then(r=>r.json()).then(r=>setP(r.project))},[]);const review=useReview({project:p,replaceProject:setP});return p?<main style={{maxWidth:1100,margin:'auto',padding:24}}><h1>Music video production review</h1><Panel project={p} review={review} onOpenArtifact={id=>window.open('/api/music-video/${p.id}/dev-artifacts/'+id+'/file')}/></main>:null}createRoot(document.getElementById('root')).render(<App/>);`;+ const { build } = await import(clientBundler[0]);+ const { default: react } = await import(clientBundler[1]);+ const { default: tailwind } = await import(clientBundler[2]);+ const { symlink } = await import('node:fs/promises');+ await symlink(join(client, 'node_modules'), join(ui, 'node_modules'), 'dir');+ await writeFile(join(ui, 'entry.jsx'), `import ${JSON.stringify(join(client, 'src/index.css'))};\n` + entry.replaceAll("'./src/", `'${client}/src/`));+ await writeFile(join(ui, 'index.html'), '<html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="root"></div><script type="module" src="/entry.jsx"></script></body></html>');+ await build({ configFile: false, root: ui, plugins: [react()], css: { postcss: { plugins: [tailwind({ base: client })] } }, build: { outDir: join(ui, 'dist'), emptyOutDir: true }, logLevel: 'warn' });+ const app = express(); app.use(express.json()); app.use('/api/music-video', router); app.use('/data/videos', express.static(PATHS.videos)); app.use('/fonts', express.static(join(client, 'public/fonts'))); app.use(express.static(join(ui, 'dist'))); app.use(errorMiddleware);+ server = await new Promise(resolve => { const listener = app.listen(0, '127.0.0.1', () => resolve(listener)); });+ proc = spawn(chrome, _testChromeCaptureArgs(join(PATHS.data, 'test-chrome')), { stdio: ['ignore', 'ignore', 'pipe'] });+ endpoint = new URL(await _waitForTestChrome(proc)).origin.replace('ws:', 'http:');+ browser = await chromium.connectOverCDP(endpoint);+ const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });+ const errors = []; page.on('pageerror', e => errors.push(e.message));+ await page.goto(`http://127.0.0.1:${server.address().port}`);+ const password = page.getByLabel('Instance password for this approval');+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve art direction', exact: true }).click();+ await page.getByText('Review feedback and revision history', { exact: true }).click();+ await page.getByLabel('Feedback stage').selectOption('storyboard');+ await page.getByLabel('Feedback target').fill('shot: chorus / operator');+ await page.getByLabel('Requested change').fill('Move the operator behind the threshold at the exit.');+ await page.getByRole('button', { name: 'Save revision feedback' }).click();+ await page.getByText('Move the operator behind the threshold at the exit.', { exact: true }).waitFor();+ expect(await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).isDisabled()).toBe(true);+ await page.getByLabel('Resolution for shot: chorus / operator').fill('Reviewed the updated staging in the storyboard.');+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Resolve feedback after review' }).click();+ await page.getByText('Resolution: Reviewed the updated staging in the storyboard.', { exact: true }).waitFor();+ const beforeBoard = await page.evaluate(async id => (await fetch('/api/music-video/' + id + '/production-review')).json(), p.id);+ expect(beforeBoard.readiness.storyboard.problems).toEqual([]);+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).click();+ await page.getByRole('button', { name: 'Render animated proof' }).click();+ await page.locator('video').waitFor({ timeout: 120000 });+ await page.locator('video').evaluate(async video => { await video.play(); await new Promise(r => setTimeout(r, 400)); video.pause(); });+ expect(await page.locator('video').evaluate(v => v.videoWidth)).toBeGreaterThan(0);+ await page.getByLabel('I watched this revision with audio and checked the approved visual direction, motion and lyric timing.').check();+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve animated proof' }).click();+ await page.waitForFunction(() => [...document.querySelectorAll('[role=status]')].filter(el => el.textContent === 'Approved for this revision').length === 3);+ const result = await store.getProject(p.id);+ expect(result.productionReview.feedback[0].resolvedAt).toBeTruthy();+ expect(errors).toEqual([]);+ const proofFile = join(PATHS.videos, result.excerpts.find(e => e.id === result.productionReview.proof.excerptId).filename);+ const frame = at => execFileSync(ffmpeg, ['-v', 'error', '-ss', String(at), '-i', proofFile, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);+ const middle = frame(5);+ expect([...middle].filter((_, i) => i % 3 === 0 && middle[i] > middle[i + 2] + 40).length).toBeGreaterThan(150); // warm doorway occupies the stage, not the host's fallback dot+ expect(frame(2).equals(frame(7))).toBe(false); // actual authored motion changes the scene+ if (process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR) {+ await mkdir(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, { recursive: true });+ await page.screenshot({ path: join(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, 'review-desktop.png'), fullPage: true });+ await page.setViewportSize({ width: 390, height: 844 });+ await page.screenshot({ path: join(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, 'review-mobile.png'), fullPage: true });+ const excerpt = result.excerpts.find(e => e.id === result.productionReview.proof.excerptId);+ await copyFile(join(PATHS.videos, excerpt.filename), join(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, 'synthetic-chorus-proof.mp4'));+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-ss', '5', '-i', join(PATHS.videos, excerpt.filename), '-frames:v', '1', join(process.env.MUSIC_VIDEO_REVIEW_EVIDENCE_DIR, 'proof-frame.png')]);+ }+ }, 180000);+});diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.jsnew file mode 100644index 0000000000..302a6a5dbb--- /dev/null+++ b/server/routes/musicVideoProductionReview.test.js@@ -0,0 +1,170 @@+import { beforeEach, afterAll, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-production-review-');+vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: ROOT }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+const auth = vi.hoisted(() => ({ enabled: true }));+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => auth.enabled, verifyPassword: async password => password === 'synthetic-operator-password' }));+vi.mock('../services/musicVideo/excerptRender.js', async original => ({ ...await original(),+ startExcerptRender: vi.fn(async (id, window, options) => {+ const store = await import('../services/musicVideo/projects.js');+ const project = await store.getProject(id);+ options.verifyCurrent(project);+ await store.mutateProjectRecord(id, current => ({ project: { ...current,+ excerpts: [...(current.excerpts || []), { id: 'proof-fixture', ...window, status: 'complete', filename: 'synthetic-proof.mp4' }] } }));+ return { jobId: 'proof-job', excerptId: 'proof-fixture' };+ }),+}));++const { default: router } = await import('./musicVideo.js');+const store = await import('../services/musicVideo/projects.js');+const { saveGeneratedDevArtifact } = await import('../services/musicVideo/devArtifactService.js');+const { assertProductionApproval } = await import('../services/musicVideo/productionReview.js');+const app = express();+app.use(express.json()); app.use('/api/music-video', router); app.use(errorMiddleware);+let project, base, draft;+const read = () => request(app).get(`${base}/production-review`);+const save = body => request(app).put(`${base}/production-review`).send(body);+async function approve(stage, extra = {}) {+ const status = await read();+ return request(app).post(`${base}/production-review/approve`).send({ stage,+ basis: status.body.readiness.basis[stage], password: 'synthetic-operator-password', ...extra });+}++beforeEach(async () => {+ auth.enabled = true;+ project = await store.createProject({ name: 'Example animation', uploadedAudioFilename: 'synthetic-song.wav', composition: { mode: 'code' } });+ base = `/api/music-video/${project.id}`;+ await store.setProjectAnalysis(project.id, { durationSec: 20, bpm: 120, beats: [0, 1], downbeats: [0], sections: [{ startSec: 0, endSec: 20, label: 'Chorus' }] });+ await store.updateProject(project.id, { lyricCues: [{ id: 'line-a', text: 'Example chorus', startSec: 1, endSec: 3,+ words: [{ w: 'Example', startSec: 1, endSec: 2, conf: 'matched' }, { w: 'chorus', startSec: 2, endSec: 3, conf: 'matched' }] }] });+ const scene = await store.addProjectScene(project.id, { label: 'Chorus', startSec: 0, endSec: 20, prompt: 'A paper figure opens a painted doorway.' });+ const { artifact } = await saveGeneratedDevArtifact(project.id, { kind: 'cast-sets', title: 'Example visual sheet', html: '<html><body><svg><circle r="30" cx="40" cy="40"/></svg></body></html>' });+ draft = { cast: 'Paper figure with an angular silhouette.', environments: 'Layered painted doorway.',+ visualLanguage: 'Indigo and cream; bold readable type with open lyric space.', motionLanguage: 'The camera follows the opening doorway; the chorus expands the room.',+ guideArtifactId: artifact.id, lyricsMode: 'vocal', timingStatus: 'verified', timingNotes: 'Synthetic word onsets were checked against the fixture master.',+ storyboard: [{ sceneId: scene.sceneId, lyricCueIds: ['line-a'], action: 'Open the doorway', staging: 'Figure foreground, doorway behind', camera: 'Dolly through doorway', transition: 'Match doorway to next frame' }] };+ expect((await save(draft)).status).toBe(200);+});+afterAll(cleanupTempDataRoots);++describe('human-reviewed Music Video workflow', () => {+ it('refuses API credentials, password-free approval, stale revisions and final-render bypasses', async () => {+ const status = await read();+ const body = { stage: 'art', basis: status.body.readiness.basis.art, password: 'synthetic-operator-password' };+ expect((await request(app).post(`${base}/production-review/approve`).set('authorization', 'Bearer synthetic-agent').send(body)).status).toBe(403);+ expect((await approve('art', { password: 'wrong' })).status).toBe(403);+ auth.enabled = false;+ expect((await approve('art')).body.code).toBe('OPERATOR_PASSWORD_REQUIRED');+ auth.enabled = true;+ await save({ ...draft, motionLanguage: 'A different motion direction' });+ expect((await request(app).post(`${base}/production-review/approve`).send(body)).status).toBe(409);+ expect((await request(app).patch(base).send({ productionReview: { approvals: { proof: true } } })).status).toBe(400);+ expect((await request(app).post(`${base}/render`).send({ approved: true })).body.code).toBe('MUSIC_VIDEO_APPROVAL_REQUIRED');+ expect((await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 })).status).toBe(409);+ });++ it('allows explicitly unapproved feasibility renders before art without granting proof approval', async () => {+ const rendered = await request(app).post(`${base}/production-review/proof`).send({ kind: 'prototype', startSec: 0, endSec: 20 });+ expect(rendered.status).toBe(202);+ const status = await read();+ expect(status.body.project.productionReview.prototype.excerptId).toBeTruthy();+ expect(status.body.project.productionReview.proof).toBeUndefined();+ expect(status.body.readiness.readyForProduction).toBe(false);+ expect((await approve('proof')).status).toBe(409);+ });++ it('reviews art, aligned storyboard and rendered proof, then invalidates revisions and fork approvals', async () => {+ expect((await approve('art')).status).toBe(200);+ expect((await approve('storyboard')).status).toBe(200);+ expect((await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 })).status).toBe(202);+ expect((await approve('proof')).status).toBe(200);+ const accepted = await store.getProject(project.id);+ expect(() => assertProductionApproval(accepted)).not.toThrow();+ const fork = await store.cloneProject(project.id, { variant: 'video-generation' });+ expect(fork.productionReview.approvals).toEqual({});+ expect(fork.productionReview.draft.cast).toBe('');+ expect(fork.productionReview.draft.storyboard[0].sceneId).toBe(fork.scenes[0].sceneId);+ expect(() => assertProductionApproval(fork)).toThrow();+ expect(() => assertProductionApproval(accepted)).not.toThrow();+ await save({ ...draft, visualLanguage: 'New orange direction' });+ expect((await read()).body.readiness.readyForProduction).toBe(false);+ expect((await request(app).post(`${base}/render`).send({})).status).toBe(409);+ });++ it('distinguishes provisional/zero-length/missing lyrics from an explicit instrumental', async () => {+ await approve('art');+ await save({ ...draft, timingStatus: 'provisional' });+ expect((await approve('storyboard')).status).toBe(409);+ await store.updateProject(project.id, { lyricCues: [{ id: 'line-a', text: 'Example', startSec: 1, endSec: 2, words: [{ w: 'Example', startSec: 1, endSec: 1, conf: 'interpolated' }] }] });+ await save(draft);+ expect((await approve('storyboard')).status).toBe(409);+ await save({ ...draft, lyricsMode: 'instrumental' });+ expect((await approve('storyboard')).status).toBe(409);+ await store.updateProject(project.id, { lyricCues: [] });+ await save({ ...draft, storyboard: draft.storyboard.map(s => ({ ...s, lyricCueIds: [] })) });+ expect((await approve('storyboard')).status).toBe(409);+ await save({ ...draft, lyricsMode: 'instrumental', timingNotes: 'This synthetic master contains only instruments.', storyboard: draft.storyboard.map(s => ({ ...s, lyricCueIds: [] })) });+ expect((await approve('storyboard')).status).toBe(200);+ });++ it('imports unbound planning without authorizing it, preserves source and binds only on explicit request', async () => {+ const source = JSON.stringify({ cast: [{ id: 'paper-figure' }], environments: [{ id: 'doorway' }],+ visualLanguage: { palette: ['indigo'] }, motionLanguage: { camera: 'dolly' }, productionAuthorized: true,+ storyboard: [{ id: 'shot-a', sceneId: null, startSec: 0, endSec: 20, action: 'Open doorway', staging: 'Foreground', camera: 'Dolly', transition: 'Match cut' }] });+ const imported = await request(app).post(`${base}/production-review/import`).send({ source });+ expect(imported.status).toBe(200);+ expect(imported.body.project.productionReview.approvals).toEqual({});+ expect(imported.body.project.productionReview.draft.storyboard[0].sceneId).toBeNull();+ expect(imported.body.project.productionReview.draft.timingStatus).toBe('provisional');+ const preserved = await request(app).get(`${base}/dev-artifacts/${imported.body.project.productionReview.draft.sourceArtifactId}/file`);+ expect(preserved.status).toBe(200);+ const bound = await request(app).post(`${base}/production-review/shots/shot-a/bind`).send({});+ expect(bound.status).toBe(200);+ expect(bound.body.project.productionReview.draft.storyboard[0].sceneId).toBeTruthy();+ expect((await request(app).post(`${base}/production-review/shots/shot-a/bind`).send({})).status).toBe(409);+ expect(bound.body.readiness.readyForProduction).toBe(false);+ });++ it('retains targeted feedback across revisions and imports without granting production approval', async () => {+ const comment = async (stage, decision, text) => {+ const status = await read();+ return request(app).post(`${base}/production-review/feedback`).send({ stage, decision, text,+ target: 'cast: example-figure / frame: 2.5s', basis: status.body.readiness.basis[stage] });+ };+ await comment('art', 'structure-accepted', 'The sheet structure works; the silhouette needs revision.');+ expect((await read()).body.readiness.art.approved).toBe(false);+ await approve('art'); await approve('storyboard');+ const feedback = await comment('proof', 'request-changes', 'Keep the figure behind the doorway during the camera move.');+ const entry = feedback.body.project.productionReview.feedback.at(-1);+ expect(feedback.body.readiness.art.approved).toBe(true);+ expect(feedback.body.readiness.storyboard.approved).toBe(true);+ expect(feedback.body.readiness.proof.problems.join(' ')).toContain('Keep the figure');+ await save({ ...draft, storyboard: draft.storyboard.map(shot => ({ ...shot, staging: 'Figure behind doorway' })) });+ const revised = await read();+ expect(revised.body.project.productionReview.reviewedRevisions[entry.basis].draft.storyboard[0].staging).toBe('Figure foreground, doorway behind');+ expect(revised.body.project.productionReview.feedback.at(-1).resolvedAt).toBeUndefined();+ expect(revised.body.readiness.art.approved).toBe(true);+ expect(revised.body.readiness.storyboard.approved).toBe(false);+ const resolution = { feedbackId: entry.id, resolution: 'Reviewed the revised staging.', password: 'synthetic-operator-password' };+ expect((await request(app).post(`${base}/production-review/feedback/resolve`).set('authorization', 'Bearer synthetic-agent').send(resolution)).status).toBe(403);+ expect((await request(app).post(`${base}/production-review/feedback/resolve`).send(resolution)).status).toBe(200);+ expect((await read()).body.readiness.readyForProduction).toBe(false);+ await request(app).post(`${base}/production-review/import`).send({ source: JSON.stringify({ cast: 'Another proposal', storyboard: [] }) });+ const imported = await read();+ expect(imported.body.project.productionReview.feedback).toHaveLength(2);+ expect(imported.body.project.productionReview.feedback.at(-1).resolution).toBe(resolution.resolution);+ expect(imported.body.project.productionReview.reviewedRevisions[entry.basis]).toBeTruthy();+ });++ it('never submits an external post, including forged approval and agent credentials', async () => {+ const result = await request(app).post(`${base}/publish/drafts/any-draft/submit`).set('authorization', 'Bearer synthetic-agent').send({ approved: true, password: 'synthetic-operator-password' });+ expect(result.status).toBe(403);+ expect(result.body.code).toBe('PUBLISH_MANUAL_REQUIRED');+ expect((await request(app).post(`${base}/publish/youtube/prepare`).send({ approved: true })).status).toBe(403);+ });+});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex ea1c9c7161..ff3c137001 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -1277,6 +1277,10 @@ async function runJobLifecycle(job, markDispatched) {cancelRequested: job.params?.remoteMedia?.cancelRequested === true,};}+ if (job.params?.musicVideo?.sceneId && !(job.cancelRequested && isRemoteMediaJob(job))) {+ const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');+ await assertMusicVideoSceneReview(job.params.musicVideo);+ }// Remote recovery must still reach its adapter to cancel an existing render.// Local cancellation before dispatch owns no provider process to stop.if (job.cancelRequested && !isRemoteMediaJob(job)) {@@ -1354,6 +1358,10 @@ export function assertMediaQueueRoom(count = 1) {// entry, no SSE entry, no snapshot write. The check and the push below run in// one synchronous stretch, so concurrent submissions cannot overshoot it.export async function enqueueJob({ kind, params, owner = null }) {+ if (params?.musicVideo?.sceneId) {+ const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');+ await assertMusicVideoSceneReview(params.musicVideo);+ }if (!JOB_KINDS.includes(kind)) {throw new Error(`enqueueJob: invalid kind '${kind}'`);}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex c79a1ae210..663868cb9f 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -1,3 +1,4 @@+vi.mock('../musicVideo/productionReviewService.js', () => ({ assertMusicVideoSceneReview: vi.fn(async () => {}) }));import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';import { tmpdir } from 'os';@@ -245,6 +246,19 @@ afterAll(async () => {});describe('mediaJobQueue', () => {+ it('rejects an unreviewed music-video scene before queue admission and rechecks delayed dispatch', async () => {+ const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');+ const request = { kind: 'video', params: { prompt: 'Synthetic scene', musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' } } };+ assertMusicVideoSceneReview.mockRejectedValueOnce(new Error('Storyboard approval required'));+ await expect(mediaJobQueue.enqueueJob(request)).rejects.toThrow('Storyboard approval required');+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ assertMusicVideoSceneReview.mockResolvedValueOnce().mockRejectedValueOnce(new Error('Proof changed while queued'));+ const { jobId } = await mediaJobQueue.enqueueJob(request);+ await waitFor(() => mediaJobQueue.getJob(jobId).status === 'failed');+ expect(mediaJobQueue.getJob(jobId).error).toContain('Proof changed while queued');+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ });+it('invalidates snapshots after enqueue and cancellation so idle clients see changes', async () => {const changed = vi.fn();mediaJobQueue.mediaJobEvents.on('changed', changed);diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex fd6ad3c011..ccf48cdec2 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -1,3 +1,5 @@+import { prepareProductionReview, renderProductionProof } from './productionReviewService.js';+import { assertProductionApproval, productionReadiness, productionProofNeedsRender, productionProofWindow } from './productionReview.js';/*** Fully-autonomous Music Video — the run orchestrator.*@@ -257,12 +259,23 @@ const STAGES = {async produce({ project, run }) {const medium = autonomousMedium(run.brief.tools);- if (medium === 'code') {+ if (medium === 'code' && !['code', 'document'].includes(project.composition?.mode)) {await deps.updateProject(project.id, { composition: { mode: 'code' } });+ }+ await prepareProductionReview(project.id);+ project = await getProject(project.id);+ assertProductionApproval(project, 'storyboard');+ if (medium === 'code') {const authoring = run.brief.authoring || (run.brief.llm ? { providerId: run.brief.llm.providerId, model: run.brief.llm.model, effort: run.brief.llm.effort } : {});- await deps.generateCode(project.id, {+ if (project.composition?.mode === 'code' && !project.composition?.codeVideo?.sections?.length) await deps.generateCode(project.id, {providerId: authoring.providerId, model: authoring.model || undefined, ...(authoring.effort ? { effort: authoring.effort } : {}),});+ project = await getProject(project.id);+ const readiness = productionReadiness(project);+ if (productionProofNeedsRender(project, readiness.basis.proof)) {+ await renderProductionProof(project.id, productionProofWindow(project));+ }+ assertProductionApproval(await getProject(project.id));const render = await deps.renderVideo(project.id);return { output: { renderJobId: render?.jobId || null } };}@@ -311,7 +324,7 @@ async function advance(projectId) {const latest = projectAutonomousRun(await getProject(projectId));if (latest?.status !== 'running' || latest.processId !== PROCESS_ID) return;await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'failed', error: trimTo(err.message, 500), step: null }));- await park(projectId, isLoginRequired(err) ? 'needs-human' : 'failed', { error: trimTo(err.message, 500), errorCode: err.code || null });+ await park(projectId, isLoginRequired(err) || err.code === 'MUSIC_VIDEO_APPROVAL_REQUIRED' ? 'needs-human' : 'failed', { error: trimTo(err.message, 500), errorCode: err.code || null });return;}const finishedAt = new Date().toISOString();diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex c2562440b2..59d9c92342 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -1,3 +1,20 @@+// Existing engine cases isolate the creative review boundary; explicit approval-flow+// cases below switch to the real model and verify pause/resume without providers.+const creativeReview = vi.hoisted(() => ({ real: false }));+vi.mock('./productionReview.js', async (load) => {+ const actual = await load();+ return { ...actual,+ assertProductionApproval: (...args) => creativeReview.real ? actual.assertProductionApproval(...args) : undefined,+ productionReadiness: (...args) => creativeReview.real ? actual.productionReadiness(...args) : {+ art: { approved: true }, storyboard: { approved: true }, proof: { approved: true }, basis: { proof: 'test-proof' }, readyForProduction: true,+ },+ };+});+vi.mock('./productionReviewService.js', () => ({+ prepareProductionReview: vi.fn(async () => {}),+ renderProductionProof: vi.fn(async () => ({ jobId: 'proof-example' })),+ attachProductionPilotProof: vi.fn(async () => {}),+}));/*** Fully-autonomous Music Video run — orchestration contract. The project store* is an in-memory double with the real store's serialized read-modify-write;@@ -41,11 +58,12 @@ let doubles;const stub = (name, impl) => vi.fn(async (...args) => { calls.push(name); return impl(...args); });beforeEach(() => {+ creativeReview.real = false;store.clear();calls = [];doubles = {createProject: stub('createProject', async (input) => {- const project = { id: 'mv-auto', ...input };+ const project = { id: 'mv-auto', productionReview: { proof: { basis: 'test-proof', excerptId: 'test-proof' } }, excerpts: [{ id: 'test-proof', status: 'complete', filename: 'test-proof.mp4' }], ...input };store.set(project.id, clone(project));return project;}),@@ -422,3 +440,75 @@ describe('events and process pinning', () => {expect(calls.length).toBe(before);});});++it('parks standalone code at real human gates and replaces a stale proof before final rendering', async () => {+ creativeReview.real = true;+ const { approveProductionStage, productionReviewBasis } = await vi.importActual('./productionReview.js');+ const { renderProductionProof } = await import('./productionReviewService.js');+ let proofNumber = 0;+ doubles.analyzeSong.mockImplementation(async () => {+ Object.assign(store.get('mv-auto'), {+ audioAnalysis: { durationSec: 20, sections: [{ id: 'chorus', label: 'Chorus', startSec: 18, endSec: 20 }] },+ scenes: [{ sceneId: 'shot', startSec: 0, endSec: 20, label: 'Chorus' }],+ devArtifacts: [{ id: 'guide', version: 1, file: 'guide.html', mimeType: 'text/html' }],+ productionReview: { draft: {+ cast: 'Paper dancer', environments: 'Theatre', visualLanguage: 'Ink silhouettes', motionLanguage: 'Slow orbit',+ guideArtifactId: 'guide', lyricsMode: 'instrumental', timingNotes: 'Synthetic instrumental master checked.',+ storyboard: [{ sceneId: 'shot', lyricCueIds: [], action: 'Dancer unfolds', staging: 'Wide theatre', camera: 'Orbit', transition: 'Fade' }],+ } },+ });+ });+ doubles.generateCode.mockImplementation(async () => {+ const project = store.get('mv-auto');+ project.composition.codeVideo = { sections: [{ id: 'chorus', source: 'function render() {}' }] };+ });+ renderProductionProof.mockImplementation(async (_id, window) => {+ const project = store.get('mv-auto');+ const id = `proof-${++proofNumber}`;+ project.excerpts = [{ id, status: 'complete', filename: `${id}.mp4` }];+ project.productionReview.proof = { ...window, excerptId: id };+ project.productionReview.proof.basis = productionReviewBasis(project).proof;+ return { jobId: id };+ });+ const approve = stage => {+ const project = store.get('mv-auto');+ store.set(project.id, approveProductionStage(project, { stage, basis: productionReviewBasis(project)[stage] }));+ };+ await service.startAutonomousVideo({ prompt: 'Synthetic animation', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' } });+ await settled('needs-human');+ expect(doubles.generateCode).not.toHaveBeenCalled();+ expect(doubles.renderVideo).not.toHaveBeenCalled();+ approve('art');+ approve('storyboard');+ await service.resumeAutonomousVideo('mv-auto');+ await settled('needs-human');+ expect(doubles.generateCode).toHaveBeenCalledOnce();+ expect(renderProductionProof).toHaveBeenCalledOnce();+ expect(renderProductionProof).toHaveBeenLastCalledWith('mv-auto', { startSec: 0, endSec: 20 });+ expect(doubles.renderVideo).not.toHaveBeenCalled();+ store.get('mv-auto').excerpts[0].status = 'rendering';+ await service.resumeAutonomousVideo('mv-auto');+ await settled('needs-human');+ expect(renderProductionProof).toHaveBeenCalledOnce();+ for (const status of ['error', 'canceled']) {+ store.get('mv-auto').excerpts[0].status = status;+ store.get('mv-auto').excerpts[0].filename = null;+ const callsBefore = renderProductionProof.mock.calls.length;+ await service.resumeAutonomousVideo('mv-auto');+ await settled('needs-human');+ expect(renderProductionProof).toHaveBeenCalledTimes(callsBefore + 1);+ expect(doubles.renderVideo).not.toHaveBeenCalled();+ }+ approve('proof');+ store.get('mv-auto').composition.codeVideo.sections[0].source = 'function render() { /* revision */ }';+ await service.resumeAutonomousVideo('mv-auto');+ await settled('needs-human');+ expect(renderProductionProof).toHaveBeenCalledTimes(4);+ expect(doubles.renderVideo).not.toHaveBeenCalled();+ approve('proof');+ await service.resumeAutonomousVideo('mv-auto');+ await settled('completed');+ expect(doubles.renderVideo).toHaveBeenCalledOnce();+ expect(doubles.generateCode).toHaveBeenCalledOnce();+ expect(doubles.startProduction).not.toHaveBeenCalled();+});diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.jsindex a49ba6006c..bfd1dd7f99 100644--- a/server/services/musicVideo/castAndSetsService.js+++ b/server/services/musicVideo/castAndSetsService.js@@ -1,3 +1,4 @@+import { productionFeedbackContext } from './productionReview.js';import { withMusicVideoStyle } from './styleReferences.js';/*** Music Video — Cast & Sets check-in orchestrator.@@ -177,7 +178,7 @@ async function runDirection(projectId, { providerId, model, effort, notes = [],// silently re-cast into the other medium.// A saved direction without a medium predates the procedural one: photographic.const medium = notes.length && previous ? (previous.medium || 'photographic') : castAndSetsMedium(project);- const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes, medium });+ const prompt = buildCastAndSetsPrompt(project, { moodImages, board, track, previous: notes.length ? previous : null, notes, medium }) + productionFeedbackContext(project);let text;try {({ text } = await deps.runPrompt({ provider, model: selectedModel, ...effortArg(route), prompt, source: 'music-video-cast-sets' }));@@ -584,7 +585,9 @@ export async function regenerateCastAndSets(projectId, { notes = null, providerIconst 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);+ const reviewNotes = (project.productionReview?.feedback || []).filter(n => n.stage === 'art' && !n.resolvedAt)+ .map(n => ({ target: `production-review:${n.target}`, text: n.text }));+ const source = [...(Array.isArray(notes) ? notes : (artifact?.notes || []).filter((n) => !n.resolvedAt)), ...reviewNotes];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 = [];diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.jsindex c2389e10fd..1aec8a6e30 100644--- a/server/services/musicVideo/castAndSetsService.test.js+++ b/server/services/musicVideo/castAndSetsService.test.js@@ -628,3 +628,25 @@ describe('Cast & Sets procedural check-in', () => {expect(res.body.code).toBe('CAST_SETS_NOT_PROCEDURAL');});});+++it('carries unresolved targeted production feedback into regeneration without resolving the human decision', async () => {+ const project = await seed();+ await service.startCastAndSets(project.id);+ await runTo(project.id, 'review');+ await projects.mutateProjectRecord(project.id, current => ({ project: { ...current,+ productionReview: { feedback: [+ { id: 'feedback-open', stage: 'art', target: 'cast:keeper', text: 'Use a wider composition and a stronger silhouette', decision: 'request-changes' },+ { id: 'feedback-closed', stage: 'art', target: 'environment:harbor', text: 'Obsolete resolved direction', decision: 'comment', resolvedAt: '2026-01-01T00:00:00.000Z' },+ ] },+ } }));+ await service.regenerateCastAndSets(project.id);+ await runTo(project.id, 'review');+ expect(runPrompt).toHaveBeenCalledTimes(2);+ const prompt = runPrompt.mock.calls[1][0].prompt;+ expect(prompt).toContain('cast:keeper');+ expect(prompt).toContain('Use a wider composition and a stronger silhouette');+ expect(prompt).not.toContain('Obsolete resolved direction');+ const revised = await current(project.id);+ expect(revised.productionReview.feedback[0].resolvedAt).toBeUndefined();+});diff --git a/server/services/musicVideo/codeComposition.js b/server/services/musicVideo/codeComposition.jsindex 3e0d90737e..593e665737 100644--- a/server/services/musicVideo/codeComposition.js+++ b/server/services/musicVideo/codeComposition.js@@ -7,10 +7,27 @@* after fetch/WebSocket are disabled.*/+import { parseExpression } from '@babel/parser';+import { ServerError } from '../../lib/errorHandler.js';+import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';import { codeRuntimeSource } from './codeFrame.js';const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');+// Compile at document construction, never through browser eval. The wrapper+// retains legacy statement-body sources, but cannot escape into page-level code.+function staticSectionFunction(source) {+ if (!isDeterministicCodeSource(source)) throw new ServerError('A section must be deterministic and offline', { status: 422, code: 'NONDETERMINISTIC_SECTION' });+ if (/<\/script|<!--|-->/i.test(source)) throw new ServerError('Escape HTML script delimiters inside section source with JavaScript string escapes', { status: 422, code: 'INVALID_SECTION_SOURCE' });+ const wrapped = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;+ const literal = `function (ctx, env) {\n${wrapped}\nreturn typeof render === 'function' ? render(ctx, env) : undefined;\n}`;+ let expression;+ try { expression = parseExpression(`(${literal})`, { sourceType: 'script' }); }+ catch { throw new ServerError('A section function has invalid JavaScript', { status: 422, code: 'INVALID_SECTION_SOURCE' }); }+ if (expression.type !== 'FunctionExpression') throw new ServerError('A section must remain inside its render function', { status: 422, code: 'INVALID_SECTION_SOURCE' });+ return literal;+}+/*** @param {object} input* @param {object} input.song song.json document@@ -21,6 +38,8 @@ const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');*/export function buildCodeDocument({ song, palette, sources, width, height, fps, windowStart = 0, windowDuration = null }) {const durationSec = windowDuration == null ? song.durationSec : windowDuration;+ const functions = [...new Set(Object.values(sources || {}))]+ .map(source => `[${scriptJson(source)}, ${staticSectionFunction(source)}]`).join(',\n');const html = `<!doctype html><html><head><meta charset="utf-8"><style>html, body { margin: 0; background: #000; overflow: hidden; }canvas { display: block; width: 100vw; height: 100vh; object-fit: contain; background: #000; }@@ -29,6 +48,7 @@ ${codeRuntimeSource()}const SONG = ${scriptJson(song)};const PALETTE = ${scriptJson(palette)};const SOURCES = ${scriptJson(sources || {})};+const SECTION_FUNCTIONS = new Map([${functions}]);const WINDOW_START = ${Number(windowStart) || 0};function disableNetwork() {const block = (name) => function blocked() { throw new Error(name + ' is disabled in a code-rendered video'); };@@ -47,7 +67,7 @@ globalThis.portosComposition = {song: SONG,seek(t) {const time = WINDOW_START + (Number(t) || 0);- drawCodeFrame({ ctx, song: SONG, palette: PALETTE, sources: SOURCES, t: time, width: ${width}, height: ${height}, fps: ${fps} });+ drawCodeFrame({ ctx, song: SONG, palette: PALETTE, sources: SOURCES, compile: source => SECTION_FUNCTIONS.get(source), t: time, width: ${width}, height: ${height}, fps: ${fps} });}};addEventListener('message', (event) => {diff --git a/server/services/musicVideo/codeFrame.js b/server/services/musicVideo/codeFrame.jsindex 9e67a60970..4b467edb9e 100644--- a/server/services/musicVideo/codeFrame.js+++ b/server/services/musicVideo/codeFrame.js@@ -76,21 +76,15 @@ export function drawCodeFrame({ ctx, song, palette, sources, t, width, height, f}),}));const env = { t: time, localT, frame, width, height, song, palette, section, safe, karaoke };- // The page uses this when the caller does not pass its own compiler.- // It stays inside this function so the embedded page has it too.- function defaultCompile(source) {- const wrapped = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;- return new Function('ctx', 'env', `${wrapped}\nreturn typeof render === 'function' ? render(ctx, env) : undefined;`);- }const source = sources && sources[section.id];if (typeof source === 'string' && source) {const restore = lockClock();try {if (!drawCodeFrame.compiled) drawCodeFrame.compiled = new Map();- const key = `${typeof compile === 'function' ? 'custom' : 'page'}:${source}`;+ const key = source;let fn = drawCodeFrame.compiled.get(key);if (!fn) {- fn = (typeof compile === 'function' ? compile : defaultCompile)(source);+ fn = compile(source);drawCodeFrame.compiled.set(key, fn);}fn(ctx, env);@@ -212,7 +206,7 @@ function createSoftwareCanvas(width, height) {}// Section source under test runs in a context with no process, require, or-// network. The page compiler is the browser's, after network globals are removed.+// network. Browser pages instead provide statically declared section functions.function sandboxCompile(source) {const wrapped = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;const sandbox = {diff --git a/server/services/musicVideo/codeFrame.test.js b/server/services/musicVideo/codeFrame.test.jsindex cdea8b9c66..b47dc97df8 100644--- a/server/services/musicVideo/codeFrame.test.js+++ b/server/services/musicVideo/codeFrame.test.js@@ -94,3 +94,42 @@ describe('code frame contract (#9076)', () => {expect(doc.html).toContain('mv-code:seek');});});++it('executes authored functions and legacy statement bodies with runtime string compilation disabled', async () => {+ const { runInNewContext } = await import('node:vm');+ const song = { durationSec: 2, sections: [+ { id: 'first', startSec: 0, endSec: 1 }, { id: 'second', startSec: 1, endSec: 2 },+ ], lyrics: [] };+ const { html } = buildCodeDocument({ song, palette: { background: '#000000', accent: '#ffffff' },+ sources: {+ first: "function render(ctx, env) { ctx.fillStyle = '#123456'; ctx.fillRect(0, 0, env.width, env.height); }",+ second: "ctx.fillStyle = '#abcdef'; ctx.fillRect(0, 0, env.width, env.height);",+ }, width: 32, height: 18, fps: 24 });+ const painted = [];+ const ctx = { fillRect() { painted.push(this.fillStyle); } };+ const sandbox = {+ document: { getElementById: () => ({ getContext: () => ctx }) },+ addEventListener() {}, parent: { postMessage() {} },+ };+ const script = html.slice(html.indexOf('<script>') + 8, html.lastIndexOf('</script>'));+ runInNewContext(script, sandbox, { contextCodeGeneration: { strings: false, wasm: false }, timeout: 1000 });+ expect(painted.at(-1)).toBe('#123456');+ sandbox.portosComposition.seek(1.25);+ expect(painted.at(-1)).toBe('#abcdef');+ sandbox.portosComposition.seek(0);+ expect(painted.at(-1)).toBe('#123456');+ expect(html).not.toContain('new Function');+});++it('rejects section source that would escape the static function/script or use a network call', () => {+ const input = { song: { durationSec: 1 }, palette: {}, width: 32, height: 18, fps: 24 };+ for (const source of [+ "function render(ctx, env) {} }; globalThis.compromised = true; (function () {",+ "function render(ctx, env) { ctx.fillText('</ScRiPt><script>bad()', 0, 0); }",+ "function render(ctx, env) { /* <!-- */ }",+ ]) {+ expect(() => buildCodeDocument({ ...input, sources: { section: source } })).toThrow(expect.objectContaining({ code: 'INVALID_SECTION_SOURCE' }));+ }+ expect(() => buildCodeDocument({ ...input, sources: { section: "fetch('https://example.com')" } }))+ .toThrow(expect.objectContaining({ code: 'NONDETERMINISTIC_SECTION' }));+});diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.jsindex 0d5adb2999..bebc21a3a0 100644--- a/server/services/musicVideo/codeGeneration.js+++ b/server/services/musicVideo/codeGeneration.js@@ -1,3 +1,4 @@+import { assertProductionApproval, productionReviewBasis, productionFeedbackContext } from './productionReview.js';/*** User-triggered code-video generation (#9076).*@@ -34,7 +35,11 @@ export async function styleLinesFor(project) {}/** The approved procedural direction's definitions and rules, for a code-authoring request. */-export const castAndSetsCodeContext = (project) => musicVideoCodeDirectionContext(approvedCastAndSetsDirection(project));+export const castAndSetsCodeContext = (project) => [+ productionFeedbackContext(project),+ musicVideoCodeDirectionContext(approvedCastAndSetsDirection(project)),+ project.productionReview?.draft && `HUMAN-REVIEWED VISUAL/MOTION GUIDE AND SHOT CHOREOGRAPHY:\n${JSON.stringify(project.productionReview.draft)}`,+].filter(Boolean).join('\n\n');function acceptSources(parsed, ids) {const wanted = new Set(ids);@@ -85,14 +90,16 @@ function storeCodeVideo(project, { providerId, model, sections, timelineIds }) {return normalizeComposition({ ...(project.composition || {}), mode: 'code', codeVideo });}-async function writeComposition(projectId, run, sections, timelineIds) {- const { project } = await mutateProjectRecord(projectId, (current) => ({- project: {+async function writeComposition(projectId, run, sections, timelineIds, authoringBasis) {+ const { project } = await mutateProjectRecord(projectId, (current) => {+ assertProductionApproval(current, 'storyboard');+ if (productionReviewBasis(current).storyboard !== authoringBasis) throw new ServerError('The approved storyboard changed during authoring.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ return { project: {...current,composition: storeCodeVideo(current, { providerId: run.providerId, model: run.model, sections, timelineIds }),updatedAt: new Date().toISOString(),- },- }));+ } };+ });return project;}@@ -103,6 +110,7 @@ async function writeComposition(projectId, run, sections, timelineIds) {export async function generateMusicVideoCode(projectId, { providerId, model, effort } = {}) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ assertProductionApproval(project, 'storyboard');const timeline = buildCodeTimeline(project);if (!timeline.sections.length) {throw new ServerError('Code-rendered video needs a song duration — analyze the track or time a scene or lyric line', { status: 422, code: 'NO_TIMELINE' });@@ -116,13 +124,17 @@ export async function generateMusicVideoCode(projectId, { providerId, model, effstyleLines: await styleLinesFor(project),directionContext: castAndSetsCodeContext(project),});- const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt, beforeSubmit: async () => {+ const current = await getProject(projectId);+ assertProductionApproval(current, 'storyboard');+ if (productionReviewBasis(current).storyboard !== productionReviewBasis(project).storyboard) throw new ServerError('The approved storyboard changed before authoring.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ } });const parsed = extractCodeSections(run.text);const sections = acceptSources(parsed, timeline.sections.map((section) => section.id));if (!sections.length) {throw new ServerError('The model did not return a section function', { status: 422, code: 'NO_SECTION_SOURCE' });}- const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id));+ const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id), productionReviewBasis(project).storyboard);console.log(`✅ Music-video code stored sections=${sections.length}`);return { project: updated, providerId: run.providerId, model: run.model };}@@ -131,6 +143,7 @@ export async function generateMusicVideoCode(projectId, { providerId, model, effexport async function regenerateMusicVideoCodeSection(projectId, sectionId, { providerId, model, effort } = {}) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ assertProductionApproval(project, 'storyboard');const timeline = buildCodeTimeline(project);if (!timeline.sections.some((section) => section.id === sectionId)) {throw new ServerError('That section is not on the code timeline', { status: 404, code: 'SECTION_NOT_FOUND' });@@ -144,12 +157,16 @@ export async function regenerateMusicVideoCodeSection(projectId, sectionId, { pronlySectionId: sectionId,directionContext: castAndSetsCodeContext(project),});- const run = await runModel({ providerId, model, effort, automation: project.automation, prompt });+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt, beforeSubmit: async () => {+ const current = await getProject(projectId);+ assertProductionApproval(current, 'storyboard');+ if (productionReviewBasis(current).storyboard !== productionReviewBasis(project).storyboard) throw new ServerError('The approved storyboard changed before authoring.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ } });const sections = acceptSources(extractCodeSections(run.text), [sectionId]);if (!sections.length) {throw new ServerError('The model did not return that section', { status: 422, code: 'NO_SECTION_SOURCE' });}- const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id));+ const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id), productionReviewBasis(project).storyboard);console.log(`✅ Music-video code replaced section=${sectionId}`);return { project: updated, providerId: run.providerId, model: run.model, sectionId };}diff --git a/server/services/musicVideo/codeGeneration.test.js b/server/services/musicVideo/codeGeneration.test.jsindex f47aea49fd..ae46fd484a 100644--- a/server/services/musicVideo/codeGeneration.test.js+++ b/server/services/musicVideo/codeGeneration.test.js@@ -1,7 +1,9 @@+// Creative approval behavior is covered through production review routes and orchestration.+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));import { beforeEach, describe, expect, it, vi } from 'vitest';const fixtureSectionSource = (color) => `function render(ctx, env) {\n ctx.fillStyle = ${JSON.stringify(color)};\n ctx.fillRect(env.safe.x, env.safe.y, 12 + (env.frame % 3), 12);\n}`;-const h = vi.hoisted(() => ({ project: null, calls: 0, response: '', prompts: [] }));+const h = vi.hoisted(() => ({ project: null, calls: 0, response: '', prompts: [], beforeExecute: null }));vi.mock('../promptRunner.js', () => ({assertProvider: () => {},@@ -9,7 +11,9 @@ vi.mock('../promptRunner.js', () => ({provider: { id: providerId || 'stub-provider' },selectedModel: model || 'fixture-model',})),- runPromptThroughProvider: vi.fn(async ({ prompt }) => {+ runPromptThroughProvider: vi.fn(async ({ prompt, beforeExecute }) => {+ await h.beforeExecute?.();+ await beforeExecute?.({ provider: { id: 'stub-provider' }, model: 'fixture-model' });h.calls += 1;h.prompts.push(prompt);return { text: h.response };@@ -51,6 +55,7 @@ const base = () => ({beforeEach(() => {h.project = base();+ h.beforeExecute = null;h.calls = 0;h.response = '';h.prompts = [];@@ -140,3 +145,12 @@ describe('music video code generation (#9076)', () => {});});});+++it('refuses standalone authoring when a lyric changes during provider preparation, before spending', async () => {+ h.beforeExecute = () => {+ h.project = { ...h.project, lyricCues: [{ ...h.project.lyricCues[0], text: 'changed lyric' }] };+ };+ await expect(generateMusicVideoCode('mv-code')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_REVIEW_STALE' });+ expect(h.calls).toBe(0);+});diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.jsindex 51b4d63118..f61d85ad02 100644--- a/server/services/musicVideo/documentGeneration.js+++ b/server/services/musicVideo/documentGeneration.js@@ -1,3 +1,4 @@+import { assertProductionApproval } from './productionReview.js';/** User-triggered mixed-media document authoring. No provider runs on read or boot. */import { createHash } from 'node:crypto';import { readFile } from 'node:fs/promises';@@ -49,6 +50,7 @@ function basisFor(project, includeEvents = true) {// a section means. A new candidate cannot publish across such an edit.const input = {name: project.name || null,+ productionDraft: project.productionReview?.draft || null,treatment: project.treatment || null,productionPolicy: project.productionPolicy || null,visualSpec: project.visualSpec || null,@@ -167,6 +169,7 @@ async function priorManifest(project) {async function runAuthoring(projectId, { providerId, model, effort, sectionId = null, eventRevision = false, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);if (!project) throw fail('Project not found', 'NOT_FOUND', 404);+ assertProductionApproval(project, 'storyboard');const context = await authoringContext(project);let prior = null;if (sectionId || eventRevision) {@@ -194,7 +197,13 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =onlySectionId: sectionId, sharedStyle, directionContext: castAndSetsCodeContext(project),});const directedPrompt = feedback ? `${prompt}\n\nReview findings for this section (retain the approved medium and selected assets; never invent a footage fallback):\n${feedback.slice(0, 8000)}` : prompt;- const run = await runModel({ providerId, model, effort, automation: project.automation, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });+ const run = await runModel({ providerId, model, effort, automation: project.automation, prompt: directedPrompt, source: 'music-video-document', beforeSubmit: async (submission) => {+ const current = await getProject(projectId);+ assertProductionApproval(current, 'storyboard');+ verifyCurrent(current);+ if (basisFor(current) !== context.basis) throw fail('The approved plan changed before authoring', 'COMPOSITION_DRAFT_STALE', 409);+ await beforeSubmit?.(submission);+ } });const updated = acceptedSections(run.text, ids);const merged = new Map((prior?.manifest.sections || []).map((section) => [section.id, section.source]));for (const [id, source] of updated) merged.set(id, source);@@ -211,6 +220,7 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =const draft = project.composition?.documentDraft?.directory || null;const result = await stageGeneratedDocument(projectId, generatedFiles(manifest), {verifyCurrent: (current) => {+ assertProductionApproval(current, 'storyboard');verifyCurrent(current);if (basisFor(current) !== context.basis || (current.composition?.document?.directory || null) !== active|| (current.composition?.documentDraft?.directory || null) !== draft) {diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.jsindex bc4d4a8e70..801972666c 100644--- a/server/services/musicVideo/documentGeneration.test.js+++ b/server/services/musicVideo/documentGeneration.test.js@@ -1,9 +1,11 @@+// Creative approval behavior is covered through production review routes and orchestration.+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdir, readFile, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';-const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '', onSubmit: null, provider: { id: 'stub-provider' }, args: null }));+const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '', onSubmit: null, onPrepare: null, provider: { id: 'stub-provider' }, args: null }));vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {dataRoot: () => lazyTempDataRoot('portos-mv-document-author-'),}));@@ -12,6 +14,7 @@ vi.mock('../promptRunner.js', () => ({resolveProviderAndModel: async () => ({ provider: h.provider, selectedModel: 'fixture-model' }),runPromptThroughProvider: async ({ prompt, beforeExecute, ...args }) => {h.args = args;+ await h.onPrepare?.();if (beforeExecute) await beforeExecute({ provider: { id: 'stub-provider' }, model: 'fixture-model' });h.calls += 1; h.prompt = prompt;if (h.onSubmit) await h.onSubmit();@@ -29,7 +32,7 @@ const response = (colors) => JSON.stringify({ sections: Object.entries(colors).mconst manifestAt = async (document) => JSON.parse(await readFile(join(PATHS.data, document.directory, 'manifest.json'), 'utf8'));afterAll(() => cleanupTempDataRoots());-beforeEach(() => { h.provider = { id: 'stub-provider' }; h.args = null; h.onSubmit = null; h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });+beforeEach(() => { h.provider = { id: 'stub-provider' }; h.args = null; h.onSubmit = null; h.onPrepare = null; h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });async function fixture() {await mkdir(PATHS.images, { recursive: true });@@ -213,7 +216,7 @@ it('checks production authorization before provider submission and again beforeawait expect(generateMixedMediaDocument(id, { verifyCurrent: () => { if (!active) blocked(); } })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });expect(h.calls).toBe(1);expect((await projects.getProject(id)).composition?.documentDraft).toBeUndefined();- h.onSubmit = null;+ h.onSubmit = null; h.onPrepare = null;const staged = (await generateMixedMediaDocument(id)).document;await expect(acceptMixedMediaDocument(id, staged.directory, { verifyCurrent: blocked })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });expect((await projects.getProject(id)).composition.documentDraft.directory).toBe(staged.directory);@@ -238,3 +241,13 @@ it('hands the approved procedural definitions and rules to the document author,expect(h.prompt).toContain('movement: sways on the downbeat');expect(h.prompt).toContain('"shape":"polygon"');});+++it('refuses a changed production draft after provider preparation and before paid authoring', async () => {+ const id = await fixture();+ h.onPrepare = () => projects.mutateProjectRecord(id, project => ({ project: { ...project,+ productionReview: { draft: { motionLanguage: 'Revised choreography' } },+ } }));+ await expect(generateMixedMediaDocument(id)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });+ expect(h.calls).toBe(0);+});diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.jsindex b8950599b0..71115dc50e 100644--- a/server/services/musicVideo/documentRender.browser.test.js+++ b/server/services/musicVideo/documentRender.browser.test.js@@ -14,6 +14,9 @@ import { chromium } from 'playwright-core';import sharp from 'sharp';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';+// This suite measures encoder pixels; the actual operator boundary is exercised in musicVideoProductionReview.browser.test.js.+vi.mock('./productionReview.js', async original => ({ ...await original(), assertProductionApproval: () => {} }));+const author = vi.hoisted(() => ({ calls: 0, response: null }));vi.mock('../promptRunner.js', () => ({assertProvider: () => {},diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex af20a44beb..38954ea900 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -48,6 +48,7 @@ import { codeFirstProductionAssets, normalizeMusicVideoProductionPolicy, summariimport { projectAutoReviews } from './autoReview.js';import { projectRevisions } from './revision.js';import { castAndSetsSettled } from './castAndSets.js';+import { assertProductionApproval } from './productionReview.js';import { currentPilotPass, pilotClass, pilotInputBasis, pilotRepair, selectProductionPilots } from './productionPilot.js';const PRODUCTION_LIMIT_BOUNDS = Object.freeze({@@ -207,7 +208,7 @@ export function startProductionOnProject(project, {if (!authoring?.providerId || !authoring?.model) throw productionError(422, 'PRODUCTION_AUTHORING_REQUIRED', 'Select a separate code-authoring provider and model');}if (!codeFirst && project?.composition?.mode === 'code') {- throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'A code-rendered project generates no footage — render it directly');+ throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'Use Code authoring and Production review for a standalone code project: approve the storyboard, author the animation, then approve its chorus proof before rendering. Asset autopilot requires document composition.');}if (!Array.isArray(project?.audioAnalysis?.sections) || !project.audioAnalysis.sections.length) {throw productionError(409, 'NOT_ANALYZED', 'Analyze the song before starting production');@@ -254,6 +255,7 @@ export function startProductionOnProject(project, {export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kind, processId }) {const run = findProductionRun(project, runId);const step = run.steps.find((entry) => entry.key === stepKey);+ if (step?.kind !== 'checkin') assertProductionApproval(project, 'storyboard');if (run.status !== 'running' || run.processId !== processId || !step || step.status !== 'reserved' || step.sceneId !== sceneId|| JOB_KIND[step.kind] !== kind) {throw productionError(409, 'PRODUCTION_STEP_CLOSED', 'The production step was stopped or changed before submission');@@ -266,6 +268,8 @@ export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kin&& !run.pilot.scenes.every((pilot) => currentPilotPass(project, pilot))))) {throw productionError(409, 'PRODUCTION_PILOT_REQUIRED', 'The pilot evidence changed before bulk submission');}+ if (['image', 'video'].includes(kind) && run.pilot?.scenes?.length+ && !run.pilot.scenes.some(pilot => pilot.sceneId === sceneId)) assertProductionApproval(project);assertProductionPilotRoute(project, run, sceneId, step.kind, step.route);if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {const plan = summarizeMusicVideoMediumPlan(project);diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsnew file mode 100644index 0000000000..58c7dc3f2b--- /dev/null+++ b/server/services/musicVideo/productionReview.js@@ -0,0 +1,166 @@+/** Revision-bound creative approvals. Technical renders never imply approval. */+import { randomUUID } from 'node:crypto';+import { canonicalSnapshotChecksum as hash } from '../../lib/snapshotChecksum.js';+import { ServerError } from '../../lib/errorHandler.js';++import { isNonBlankStr as text } from '../../lib/textUtils.js';+const artifact = (project, id) => (project.devArtifacts || []).find(a => a.id === id && !a.deleted);+const artifactBasis = a => a ? { id: a.id, version: a.version, file: a.file } : null;+const source = p => ({ trackId: p.trackId, uploadedAudioFilename: p.uploadedAudioFilename,+ duration: p.audioAnalysis?.durationSec, beats: p.audioAnalysis?.beats, sections: p.audioAnalysis?.sections,+ lyrics: p.lyricCues, markers: p.lyricMarkers, phrases: p.phrases });+export const productionAlignmentBasis = project => hash(source(project));++export function productionReviewBasis(project) {+ const draft = project.productionReview?.draft || {};+ const art = hash({ projectId: project.id, mode: project.composition?.mode, policy: project.productionPolicy,+ concept: project.concept, visualSpec: project.visualSpec, styleReferences: project.styleReferences,+ direction: project.castAndSets?.direction,+ cast: draft.cast, environments: draft.environments, visualLanguage: draft.visualLanguage,+ motionLanguage: draft.motionLanguage, implementationPlan: draft.implementationPlan, guide: artifactBasis(artifact(project, draft.guideArtifactId)) });+ const storyboard = hash({ art, source: source(project), lyricsMode: draft.lyricsMode,+ timingStatus: draft.timingStatus, timingNotes: draft.timingNotes, storyboard: draft.storyboard,+ scenes: (project.scenes || []).map(({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt }) =>+ ({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt })), treatment: project.treatment });+ const window = project.productionReview?.proof;+ const proof = hash({ storyboard, composition: project.composition,+ window: window && { startSec: window.startSec, endSec: window.endSec },+ scenes: (project.scenes || []).filter(s => !window || s.startSec < window.endSec && s.endSec > window.startSec)+ .map(({ sceneId, referenceImageId, videoHistoryId, performanceEdit, direction, visualLayer }) =>+ ({ sceneId, referenceImageId, videoHistoryId, performanceEdit, direction, visualLayer })),+ soundBed: project.soundBed, videoSettings: project.videoSettings });+ return { art, storyboard, proof };+}++export function productionReadiness(project) {+ const review = project.productionReview || {};+ const draft = review.draft || {};+ const basis = productionReviewBasis(project);+ const unresolved = stage => (review.feedback || []).filter(f => f.stage === stage && f.decision === 'request-changes' && !f.resolvedAt);+ const artProblems = unresolved('art').map(f => `Resolve art feedback for ${f.target}: ${f.text}`);+ for (const [key, label] of [['cast', 'Cast guide'], ['environments', 'Environment guide'],+ ['visualLanguage', 'Visual guide and mood board'], ['motionLanguage', 'Motion guide']]) {+ if (!text(draft[key])) artProblems.push(`${label} needs editable direction.`);+ }+ if (!['text/html', 'image/png', 'image/jpeg'].includes(artifact(project, draft.guideArtifactId)?.mimeType)) artProblems.push('Attach a visual cast/environment sheet from Development artifacts.');+ const artApproved = !artProblems.length && review.approvals?.art?.basis === basis.art;+ const boardProblems = unresolved('storyboard').map(f => `Resolve storyboard feedback for ${f.target}: ${f.text}`);+ if (!artApproved) boardProblems.push('Review and approve the current art direction first.');+ const duration = project.audioAnalysis?.durationSec;+ if (!(duration > 0)) boardProblems.push('Analyze the current master song.');+ const cues = (project.lyricCues || []).filter(c => text(c.text));+ if (draft.lyricsMode === 'instrumental') {+ if (cues.length) boardProblems.push('This song has lyrics. Remove the instrumental exception or correct the song data.');+ if (!text(draft.timingNotes)) boardProblems.push('Explain and confirm the instrumental exception.');+ } else {+ if (!cues.length) boardProblems.push('Import lyrics and align them to the current vocal; missing lyrics are not an instrumental.');+ if (draft.timingStatus !== 'verified' || review.alignmentBasis !== productionAlignmentBasis(project)) boardProblems.push('Lyric alignment is provisional or changed. Listen and verify the current word timings.');+ if (!text(draft.timingNotes)) boardProblems.push('Record how the vocal timings were checked.');+ if (cues.some(c => !(Number.isFinite(c.startSec) && c.endSec > c.startSec && c.endSec <= duration)+ || !c.words?.length || c.words.some(w => !(Number.isFinite(w.startSec) && w.endSec > w.startSec)+ || w.startSec < c.startSec || w.endSec > c.endSec))) {+ boardProblems.push('Every lyric line needs bounded, positive-duration word timings; repair zero-length or missing words.');+ }+ }+ const scenes = project.scenes || [];+ if (draft.storyboard?.some(shot => !shot.sceneId || !scenes.some(s => s.sceneId === shot.sceneId))) boardProblems.push('Bind every draft shot to a real Board scene.');+ if (new Set((draft.storyboard || []).map(s => s.sceneId)).size !== draft.storyboard?.length) boardProblems.push('Each storyboard shot must bind to its own Board scene.');+ if (!scenes.length) boardProblems.push('Create a timed shot storyboard.');+ const timedScenes = scenes.filter(s => Number.isFinite(s.startSec) && s.endSec > s.startSec).sort((a, b) => a.startSec - b.startSec);+ if (timedScenes.length && (timedScenes[0].startSec > 1 / 24+ || Math.abs(timedScenes.at(-1).endSec - duration) > 1 / 24+ || timedScenes.some((s, i) => i > 0 && Math.abs(s.startSec - timedScenes[i - 1].endSec) > 1 / 24))) {+ boardProblems.push('Storyboard shots must cover the master without unintended gaps or overlaps.');+ }+ for (const scene of scenes) {+ const shot = draft.storyboard?.find(s => s.sceneId === scene.sceneId);+ if (!(Number.isFinite(scene.startSec) && scene.endSec > scene.startSec && scene.endSec <= duration)+ || !shot || ['action', 'staging', 'camera', 'transition'].some(key => !text(shot[key]))) {+ boardProblems.push(`Complete timing, action, staging, camera and transition for ${scene.label || 'each shot'}.`);+ }+ const overlapping = cues.filter(c => c.startSec < scene.endSec && c.endSec > scene.startSec);+ if (overlapping.some(c => !shot?.lyricCueIds?.includes(c.id))+ || shot?.lyricCueIds?.some(id => !cues.some(c => c.id === id))) boardProblems.push(`Review lyric anchors for ${scene.label || 'each shot'}.`);+ }+ const storyboardApproved = !boardProblems.length && review.approvals?.storyboard?.basis === basis.storyboard;+ const proof = review.proof;+ const excerpt = (project.excerpts || []).find(e => e.id === proof?.excerptId);+ const proofProblems = unresolved('proof').map(f => `Resolve proof feedback for ${f.target}: ${f.text}`);+ if (!storyboardApproved) proofProblems.push('Approve the current lyric-timed storyboard before the animated proof.');+ if (!proof || proof.basis !== basis.proof || excerpt?.status !== 'complete' || !excerpt?.filename) {+ proofProblems.push('Render and watch a current animated chorus proof with the master song.');+ }+ const proofApproved = !proofProblems.length && review.approvals?.proof?.basis === hash({ basis: basis.proof, excerptId: excerpt.id, filename: excerpt.filename });+ return { basis, art: { approved: artApproved, problems: [...new Set(artProblems)] },+ storyboard: { approved: storyboardApproved, problems: [...new Set(boardProblems)] },+ proof: { approved: proofApproved, problems: proofProblems, excerptId: excerpt?.id || null },+ readyForProduction: proofApproved };+}++export function assertProductionApproval(project, stage = 'proof') {+ const readiness = productionReadiness(project);+ if (!readiness[stage].approved) throw new ServerError(+ readiness[stage].problems[0] || `A human must approve the current ${stage === 'art' ? 'art direction' : stage} in Production review.`,+ { status: 409, code: 'MUSIC_VIDEO_APPROVAL_REQUIRED', context: { stage, readiness } });+}++export function approveProductionStage(project, { stage, basis }) {+ const readiness = productionReadiness(project);+ const expected = stage === 'proof'+ ? hash({ basis: readiness.basis.proof, excerptId: project.productionReview?.proof?.excerptId,+ filename: project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId)?.filename })+ : readiness.basis[stage];+ if (basis !== readiness.basis[stage]) throw new ServerError('This revision changed while you were reviewing it. Review it again.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ if (readiness[stage].problems.length) throw new ServerError(readiness[stage].problems.join(' '), { status: 409, code: 'MUSIC_VIDEO_REVIEW_INCOMPLETE' });+ return { ...project, productionReview: { ...project.productionReview,+ reviewedRevisions: { ...project.productionReview?.reviewedRevisions, [basis]: { draft: structuredClone(project.productionReview?.draft || {}), scenes: structuredClone(project.scenes || []), proof: structuredClone(project.productionReview?.proof || null), capturedAt: new Date().toISOString() } },+ approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString() } } } };+}++/** Comments retain the exact reviewed draft, even after a replacement import. */+export function recordProductionFeedback(project, input) {+ const review = project.productionReview || {};+ const basis = productionReviewBasis(project)[input.stage];+ if (input.basis !== basis) throw new ServerError('This revision changed. Review the current revision before commenting.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ const snapshots = { ...review.reviewedRevisions };+ if (!snapshots[basis]) snapshots[basis] = { draft: structuredClone(review.draft || {}),+ scenes: structuredClone(project.scenes || []), capturedAt: new Date().toISOString() };+ const entry = { id: randomUUID(), stage: input.stage, target: input.target, text: input.text,+ decision: input.decision, basis, createdAt: new Date().toISOString() };+ const approvals = { ...review.approvals };+ if (input.decision === 'request-changes') {+ for (const stage of ['art', 'storyboard', 'proof'].slice(['art', 'storyboard', 'proof'].indexOf(input.stage))) delete approvals[stage];+ }+ return { ...project, productionReview: { ...review, approvals, reviewedRevisions: snapshots,+ feedback: [...(review.feedback || []), entry] } };+}++export function resolveProductionFeedback(project, { feedbackId, resolution }) {+ const review = project.productionReview || {};+ const entry = review.feedback?.find(f => f.id === feedbackId);+ if (!entry || entry.resolvedAt) throw new ServerError('Open feedback not found.', { status: 409, code: 'MUSIC_VIDEO_FEEDBACK_CLOSED' });+ return { ...project, productionReview: { ...review, feedback: review.feedback.map(f => f.id === feedbackId+ ? { ...f, resolution, resolvedAt: new Date().toISOString(), resolvedBasis: productionReviewBasis(project)[f.stage] } : f) } };+}++export function productionFeedbackContext(project) {+ const feedback = (project.productionReview?.feedback || []).filter(f => !f.resolvedAt);+ return feedback.length ? `\nUNRESOLVED REVIEW FEEDBACK (retain until a human resolves it):\n${feedback.map(f => `${f.stage} / ${f.target} / ${f.decision}: ${f.text}`).join('\n')}` : '';+}+++/** A live capture keeps its slot; failed, canceled or missing evidence is retryable on explicit Resume. */+export function productionProofNeedsRender(project, basis) {+ const proof = project.productionReview?.proof;+ const excerpt = project.excerpts?.find(e => e.id === proof?.excerptId);+ if (excerpt?.status === 'rendering') return false;+ return !proof || proof.basis !== basis || excerpt?.status !== 'complete' || !excerpt.filename;+}++/** Keep the chorus in frame even when it starts near the end of the master. */+export function productionProofWindow(project) {+ const duration = project.audioAnalysis.durationSec;+ const chorus = project.audioAnalysis.sections?.find(s => /chorus|hook/i.test(s.label || s.type || ''));+ const startSec = Math.min(Math.max(0, chorus?.startSec || 0), Math.max(0, duration - 20));+ return { startSec, endSec: Math.min(startSec + 20, duration) };+}diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.jsnew file mode 100644index 0000000000..06b56182e0--- /dev/null+++ b/server/services/musicVideo/productionReviewService.js@@ -0,0 +1,211 @@+import { randomUUID } from 'node:crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';+import { productionReadiness, productionReviewBasis, productionAlignmentBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback } from './productionReview.js';++const reviewProcessId = randomUUID();++async function requireProject(id) {+ const project = await getProject(id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}++const present = project => ({ project, readiness: productionReadiness(project) });+function changed(project) {+ // Reuse the existing project-bearing development-artifact notification.+ musicVideoEvents.emit('dev-artifact', { projectId: project.id, artifactId: null, project });+ return present(project);+}++export const getProductionReview = async id => present(await requireProject(id));++export async function assertMusicVideoSceneReview(tag) {+ if (!tag?.projectId || !tag.sceneId) return;+ const project = await requireProject(tag.projectId);+ assertProductionApproval(project, 'storyboard');+ if (tag.productionRunId) {+ const run = project.productionRuns?.find(r => r.id === tag.productionRunId);+ if (!run?.pilot?.scenes?.some(scene => scene.sceneId === tag.sceneId)) assertProductionApproval(project, 'proof');+ }+}++/** Preserve the original handoff verbatim in an immutable artifact, never its approvals. */+export async function importProductionPlanning(id, source) {+ let input;+ try { input = JSON.parse(source); } catch { throw new ServerError('Choose a valid planning JSON document.', { status: 422, code: 'VALIDATION_ERROR' }); }+ if (!input || Array.isArray(input) || typeof input !== 'object') throw new ServerError('The planning document must be an object.', { status: 422, code: 'VALIDATION_ERROR' });+ const { musicVideoProductionDraftSchema } = await import('../../lib/musicVideoValidation.js');+ const prose = value => value == null ? '' : typeof value === 'string' ? value : JSON.stringify(value, null, 2);+ const draft = musicVideoProductionDraftSchema.parse({+ cast: prose(input.cast), environments: prose(input.environments), visualLanguage: prose(input.visualLanguage),+ motionLanguage: prose(input.motionLanguage), implementationPlan: prose(input.implementationPlan || input.feasibility), guideArtifactId: null, lyricsMode: 'vocal',+ timingStatus: 'provisional', timingNotes: prose(input.timing),+ storyboard: (Array.isArray(input.storyboard) ? input.storyboard : []).map((shot, index) => ({+ id: shot.id || `draft-${index + 1}`, sceneId: shot.sceneId || null,+ startSec: shot.startSec, endSec: shot.endSec, lyricCueIds: shot.lyricCueIds || [],+ action: prose(shot.action), staging: prose(shot.staging), camera: prose(shot.camera), transition: prose(shot.transition),+ })),+ });+ const { saveGeneratedDevArtifact } = await import('./devArtifactService.js');+ const { escapeHtml } = await import('./castAndSetsSheet.js');+ const { artifact } = await saveGeneratedDevArtifact(id, { kind: 'other', title: 'Original planning import — unapproved',+ html: `<!doctype html><html><head><meta charset="utf-8"><title>Original planning import</title></head><body><h1>Original planning import — unapproved</h1><pre style="white-space:pre-wrap">${escapeHtml(source)}</pre></body></html>`, source: 'planning-import' });+ const { project } = await mutateProjectRecord(id, current => ({ project: { ...current,+ productionReview: { ...current.productionReview, draft: { ...draft, sourceArtifactId: artifact.id }, approvals: {}, proof: null } } }));+ return changed(project);+}++/** Explicitly create and bind an unbound draft shot, under the project write lock. */+export async function bindProductionShot(id, shotId) {+ const { addScene } = await import('./projectsLogic.js');+ const { project } = await mutateProjectRecord(id, current => {+ const draft = current.productionReview?.draft;+ const shot = draft?.storyboard.find(s => s.id === shotId);+ if (!shot) throw new ServerError('Draft shot not found', { status: 404, code: 'NOT_FOUND' });+ if (shot.sceneId) throw new ServerError('This draft shot is already bound. Edit its existing Board scene.', { status: 409, code: 'SHOT_ALREADY_BOUND' });+ const out = addScene(current, { label: shot.id, startSec: shot.startSec ?? null, endSec: shot.endSec ?? null,+ visualIntent: shot.action, prompt: [shot.action, shot.camera, shot.transition].join('\n'), framePrompt: shot.staging });+ out.project.productionReview = { ...current.productionReview, draft: { ...draft,+ storyboard: draft.storyboard.map(s => s === shot ? { ...s, sceneId: out.scene.sceneId } : s) } };+ return { project: out.project };+ });+ return changed(project);+}++/** The existing password is reverified; agent session tokens are not approval authority.+ * This protects against delegated agents, not an adversary controlling the host or password.+ * No password is persisted and password-free installs fail closed for approvals.+ */+export async function requireProductionOperator(req) {+ const { isAuthEnabled, verifyPassword } = await import('../auth.js');+ if (!await isAuthEnabled()) throw new ServerError('Set an instance password in Settings > Security before approving production. Draft editing remains available.', { status: 403, code: 'OPERATOR_PASSWORD_REQUIRED' });+ if (req.headers?.authorization || !await verifyPassword(req.body?.password)) {+ throw new ServerError('Enter the instance password yourself to approve this revision. Agent/API credentials cannot approve it.', { status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ }+}++export async function saveProductionDraft(id, draft) {+ const { project } = await mutateProjectRecord(id, current => ({ project: { ...current,+ productionReview: { ...current.productionReview, draft,+ alignmentBasis: draft.timingStatus === 'verified'+ ? (current.productionReview?.draft?.timingStatus !== 'verified' ? productionAlignmentBasis(current) : current.productionReview?.alignmentBasis)+ : null } } }));+ return changed(project);+}++export async function approveProductionReview(id, input) {+ const { project } = await mutateProjectRecord(id, current => ({ project: approveProductionStage(current, input) }));+ return changed(project);+}++/** Prepare ordinary editable artifacts; never mark any stage approved. */+export async function prepareProductionReview(id, options = {}) {+ let project = await requireProject(id);+ const stage = project.castAndSets;+ const hasManualGuide = !productionReadiness(project).art.problems.length;+ if (!hasManualGuide && (!stage?.direction || !stage.artifactId)) {+ if (!stage || ['failed', 'skipped'].includes(stage.status)) {+ const { startCastAndSets } = await import('./castAndSetsService.js');+ await startCastAndSets(id, options);+ }+ return present(await requireProject(id));+ }+ // Applying references does not grant production approval. That lives only in+ // productionReview.approvals and requires the operator route.+ if (!hasManualGuide && stage?.status === 'review') {+ const { approveCastAndSets } = await import('./castAndSetsService.js');+ await approveCastAndSets(id);+ project = await requireProject(id);+ }+ const d = stage?.direction || {};+ const describe = value => typeof value === 'string' ? value : JSON.stringify(value || {}, null, 2);+ // Merge against the latest draft while holding the write lock: a guide job+ // may finish while the operator is editing its text.+ await mutateProjectRecord(id, current => {+ const prior = current.productionReview?.draft || {};+ const draft = { lyricsMode: 'vocal', timingStatus: 'provisional', timingNotes: '', storyboard: [], ...prior,+ cast: prior.cast || describe(d.protagonist), environments: prior.environments || describe(d.sets),+ visualLanguage: prior.visualLanguage || describe({ look: d.look, palette: d.protagonist?.palette, world: d.world }),+ motionLanguage: prior.motionLanguage || describe({ movement: d.protagonist?.movement, camera: d.world?.camera, transitions: d.world?.transitions }),+ guideArtifactId: prior.guideArtifactId || stage?.artifactId };+ return { project: { ...current, productionReview: { ...current.productionReview, draft } } };+ });+ project = await requireProject(id);+ if (!productionReadiness(project).art.approved) return present(project);+ if (!project.scenes?.length) {+ const { planProject } = await import('./planner.js');+ await planProject(id, { ...options, seedPrompts: true });+ project = await requireProject(id);+ }+ const { project: planned } = await mutateProjectRecord(id, current => {+ const latest = current.productionReview.draft;+ const storyboard = [...latest.storyboard, ...current.scenes.filter(scene => !latest.storyboard.some(shot => shot.sceneId === scene.sceneId)).map(scene => ({+ sceneId: scene.sceneId,+ lyricCueIds: (current.lyricCues || []).filter(c => c.startSec < scene.endSec && c.endSec > scene.startSec).map(c => c.id),+ action: scene.visualIntent || scene.prompt || '', staging: scene.framePrompt || '',+ camera: scene.direction?.camera || d.world?.camera || '', transition: d.world?.transitions || '',+ }))];+ return { project: { ...current, productionReview: { ...current.productionReview, draft: { ...latest, storyboard } } } };+ });+ return changed(planned);+}++export async function renderProductionProof(id, { startSec, endSec, kind = 'proof' }) {+ let project = await requireProject(id);+ if (kind === 'proof') assertProductionApproval(project, 'storyboard');+ const minDuration = kind === 'prototype' ? 1 : 10;+ if (!(endSec - startSec >= minDuration && endSec - startSec <= 45 && endSec <= project.audioAnalysis?.durationSec)) throw new ServerError(`Choose a ${minDuration}–45 second window within the current master song.`, { status: 422, code: 'PROOF_WINDOW_REQUIRED' });+ const requestId = randomUUID();+ let previous;+ ({ project } = await mutateProjectRecord(id, current => {+ for (const key of ['proof', 'prototype']) {+ const evidence = current.productionReview?.[key];+ if ((evidence?.requestId && evidence.requestOwner === reviewProcessId) || current.excerpts?.some(e => e.id === evidence?.excerptId && e.status === 'rendering')) throw new ServerError('An evidence render is already starting or running.', { status: 409, code: 'EXCERPT_RENDER_IN_PROGRESS' });+ }+ previous = current.productionReview?.[kind] || null;+ return { project: { ...current, productionReview: { ...current.productionReview, [kind]: { startSec, endSec, excerptId: null, requestId, requestOwner: reviewProcessId } } } };+ }));+ const basis = productionReviewBasis(project).proof;+ const { startExcerptRender } = await import('./excerptRender.js');+ let result;+ try {+ result = await startExcerptRender(id, { startSec, endSec }, { verifyCurrent: current => {+ if (kind === 'proof') assertProductionApproval(current, 'storyboard');+ if (productionReviewBasis(current).proof !== basis) throw new ServerError('The proof inputs changed', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ } });+ } catch (error) {+ await mutateProjectRecord(id, current => ({ project: current.productionReview?.[kind]?.requestId === requestId+ ? { ...current, productionReview: { ...current.productionReview, [kind]: previous } } : current }));+ throw error;+ }+ const { project: next } = await mutateProjectRecord(id, current => ({ project: { ...current,+ productionReview: { ...current.productionReview, [kind]: { startSec, endSec, excerptId: result.excerptId, basis } } } }));+ return { ...changed(next), ...result };+}++/** An existing, dependency-checked asset pilot becomes a human review candidate. */+export async function attachProductionPilotProof(id, excerptId) {+ const { musicVideoDependencyChanges } = await import('../../lib/musicVideoDependencies.js');+ const { project } = await mutateProjectRecord(id, current => {+ const excerpt = current.excerpts?.find(e => e.id === excerptId);+ if (excerpt?.status !== 'complete' || !excerpt.filename || musicVideoDependencyChanges(current, excerpt.dependencies).length) {+ throw new ServerError('The pilot evidence is missing or stale. Render it again.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });+ }+ const next = { ...current, productionReview: { ...current.productionReview,+ proof: { excerptId, startSec: excerpt.startSec, endSec: excerpt.endSec } } };+ next.productionReview.proof.basis = productionReviewBasis(next).proof;+ return { project: next };+ });+ return changed(project);+}++export async function addProductionFeedback(id, input) {+ const { project } = await mutateProjectRecord(id, current => ({ project: recordProductionFeedback(current, input) }));+ return changed(project);+}+export async function closeProductionFeedback(id, input) {+ const { project } = await mutateProjectRecord(id, current => ({ project: resolveProductionFeedback(current, input) }));+ return changed(project);+}diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex c8bfcac273..294a1f1e2c 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -1,3 +1,5 @@+import { prepareProductionReview, renderProductionProof, attachProductionPilotProof } from './productionReviewService.js';+import { productionReadiness, productionProofNeedsRender, productionProofWindow } from './productionReview.js';import { currentPlateEvidence, plateRequirementBasis, selectedPlatePasses } from '../../lib/musicVideoPlateEvidence.js';import { ensureSceneTakes, selectSceneTake } from './takes.js';/**@@ -412,7 +414,29 @@ async function takeSteps(projectId, runId) {for (let i = 0; i < MAX_STEPS_PER_ADVANCE; i += 1) {const project = await requireProject(projectId);const run = findProductionRun(project, runId);+ if (run.status !== 'running' || run.processId !== PROCESS_ID) return { project, run, action: { type: 'idle' } };+ const readiness = productionReadiness(project);+ if (!readiness.storyboard.approved) {+ await prepareProductionReview(projectId);+ return halt(projectId, runId, { status: 'blocked', reason: 'Production review needs human approval of the current visual guide and lyric-timed storyboard.' });+ }const step = nextProductionStep(project, run, { jobs: await liveJobs(), processId: PROCESS_ID });+ if (!readiness.proof.approved && run.pilot?.scenes?.length+ && run.pilot.scenes.every(pilot => currentPilotPass(project, pilot)) && step.type === 'dispatch') {+ if (productionProofNeedsRender(project, readiness.basis.proof)) {+ const pilot = run.pilot.scenes[0];+ const reviewed = project.autoReviews.find(review => review.id === pilot.reviewRunId);+ await attachProductionPilotProof(projectId, reviewed.attempts.at(-1).excerptId);+ }+ return halt(projectId, runId, { status: 'blocked', reason: 'Watch and approve the rendered pilot in Production review before bulk generation.' });+ }+ if (step.type === 'review' && !readiness.proof.approved) {+ if (productionProofNeedsRender(project, readiness.basis.proof)) {+ await renderProductionProof(projectId, productionProofWindow(project));+ }+ return halt(projectId, runId, { status: 'blocked', reason: 'Watch and approve the animated proof in Production review before the full film.' });+ }+if (step.type === 'idle' || step.type === 'wait') return { project, run, action: step };if (step.type === 'plan-pilots') {diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 146ef1590a..13af1426ad 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -1,3 +1,20 @@+// Existing engine cases isolate the creative review boundary; explicit approval-flow+// cases below switch to the real model and verify pause/resume without providers.+const creativeReview = vi.hoisted(() => ({ real: false }));+vi.mock('./productionReview.js', async (load) => {+ const actual = await load();+ return { ...actual,+ assertProductionApproval: (...args) => creativeReview.real ? actual.assertProductionApproval(...args) : undefined,+ productionReadiness: (...args) => creativeReview.real ? actual.productionReadiness(...args) : {+ art: { approved: true }, storyboard: { approved: true }, proof: { approved: true }, basis: { proof: 'test-proof' }, readyForProduction: true,+ },+ };+});+vi.mock('./productionReviewService.js', () => ({+ prepareProductionReview: vi.fn(async () => {}),+ renderProductionProof: vi.fn(async () => ({ jobId: 'proof-example' })),+ attachProductionPilotProof: vi.fn(async () => {}),+}));import { startProductionOnProject, markProductionPlanned, reserveProductionStep } from './production.js';import { plateReviewEvidence } from '../../lib/musicVideoPlateEvidence.js';import { plateRequirements } from '../../lib/musicVideoPlateEvidence.js';@@ -124,6 +141,7 @@ async function start(input = {}) {}beforeEach(() => {+ creativeReview.real = false;store.clear();jobs = [];nextJobId = 0;@@ -1203,3 +1221,80 @@ describe('budgeted production pilots (#9351)', () => {expect(deferred.run).toMatchObject({ status: 'limit-reached', usage: { reviews: 0 }, attempts: [{ review: null }] });});});++it('blocks unreviewed production, resumes an approved board, and refuses a revocation before queue submission', async () => {+ creativeReview.real = true;+ const { approveProductionStage, productionReviewBasis } = await vi.importActual('./productionReview.js');+ const seeded = seedProject({+ devArtifacts: [{ id: 'guide', version: 1, file: 'guide.html', mimeType: 'text/html' }],+ });+ seeded.productionReview = { draft: {+ cast: 'Paper dancer', environments: 'Theatre', visualLanguage: 'Ink silhouettes', motionLanguage: 'Slow orbit',+ guideArtifactId: 'guide', lyricsMode: 'instrumental', timingNotes: 'Synthetic instrumental master checked.',+ storyboard: seeded.scenes.map(scene => ({ sceneId: scene.sceneId, lyricCueIds: [], action: 'Dancer unfolds', staging: 'Wide theatre', camera: 'Orbit', transition: 'Fade' })),+ } };+ await start();+ expect(theRun().status).toBe('blocked');+ expect(dispatch).not.toHaveBeenCalled();+ for (const stage of ['art', 'storyboard']) {+ const project = current();+ store.set(project.id, approveProductionStage(project, { stage, basis: productionReviewBasis(project)[stage] }));+ }+ dispatch.mockImplementation(async ({ tag }) => {+ const project = store.get('mv-example');+ delete project.productionReview.approvals.art;+ await service.assertProductionSubmission(project.id, tag.productionRunId, tag.productionStepKey, {+ sceneId: tag.sceneId, kind: 'image',+ });+ return enqueueing({ stepKind: 'frame', tag });+ });+ await service.resumeProduction('mv-example', theRun().id);+ await settle();+ expect(dispatch).toHaveBeenCalledOnce();+ expect(jobs).toHaveLength(0);+ expect(theRun().status).toBe('blocked');+ expect(theRun().steps[0]).toMatchObject({ status: 'refused', errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED' });+});++it('retries canceled proof evidence on Resume and keeps a late chorus window inside the master', async () => {+ creativeReview.real = true;+ const { approveProductionStage, productionReviewBasis } = await vi.importActual('./productionReview.js');+ const { renderProductionProof } = await import('./productionReviewService.js');+ let proofNumber = 0;+ renderProductionProof.mockImplementation(async (id, window) => {+ const project = store.get(id);+ const excerptId = `proof-${++proofNumber}`;+ project.excerpts = [{ id: excerptId, status: 'rendering', filename: null }];+ project.productionReview.proof = { ...window, excerptId };+ project.productionReview.proof.basis = productionReviewBasis(project).proof;+ });+ const seeded = seedProject({+ composition: { mode: 'document' },+ scenes: [{ sceneId: 'card', startSec: 0, endSec: 100, visualLayer: 'card' }],+ audioAnalysis: { durationSec: 100, sections: [{ label: 'Chorus', startSec: 95, endSec: 100 }] },+ devArtifacts: [{ id: 'guide', version: 1, file: 'guide.html', mimeType: 'text/html' }],+ });+ seeded.productionReview = { draft: {+ cast: 'Paper figure', environments: 'Theatre', visualLanguage: 'Ink silhouettes', motionLanguage: 'Slow orbit',+ guideArtifactId: 'guide', lyricsMode: 'instrumental', timingNotes: 'Synthetic instrumental master checked.',+ storyboard: [{ sceneId: 'card', lyricCueIds: [], action: 'Figure unfolds', staging: 'Wide theatre', camera: 'Orbit', transition: 'Fade' }],+ } };+ for (const stage of ['art', 'storyboard']) {+ const project = current();+ store.set(project.id, approveProductionStage(project, { stage, basis: productionReviewBasis(project)[stage] }));+ }+ await start();+ expect(theRun().status).toBe('blocked');+ expect(renderProductionProof).toHaveBeenCalledOnce();+ expect(renderProductionProof).toHaveBeenLastCalledWith('mv-example', { startSec: 80, endSec: 100 });+ await service.resumeProduction('mv-example', theRun().id);+ await settle();+ expect(renderProductionProof).toHaveBeenCalledOnce();+ store.get('mv-example').excerpts[0].status = 'canceled';+ await service.resumeProduction('mv-example', theRun().id);+ await settle();+ expect(renderProductionProof).toHaveBeenCalledTimes(2);+ expect(dispatch).not.toHaveBeenCalled();+ expect(startAutoReview).not.toHaveBeenCalled();+ expect(theRun().status).toBe('blocked');+});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex ecd6a4f4eb..10dfa1479b 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -269,6 +269,10 @@ export function cloneProjectRecord(source, {// & 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.+ productionReview: source.productionReview ? { feedback: source.productionReview.feedback || [], reviewedRevisions: source.productionReview.reviewedRevisions || {}, draft: { ...source.productionReview.draft, timingStatus: 'provisional',+ storyboard: (source.productionReview.draft?.storyboard || []).map(shot => ({ ...shot, sceneId: sceneIdMap.get(shot.sceneId) || shot.sceneId })),+ ...(videoVariant ? { cast: '', environments: '', visualLanguage: '', motionLanguage: '', guideArtifactId: null } : {}),+ }, approvals: {}, proof: null } : null,...(source.castAndSets ? { castAndSets: { ...source.castAndSets, processId: null, productionRunId: null } } : {}),renderHistoryId: null,renderDependencies: null,@@ -709,6 +713,8 @@ export function mergeProjectRecord(local, remoteRaw) {// 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;+ delete remote.productionReview;+ if (Object.hasOwn(local, 'productionReview')) remote.productionReview = local.productionReview;if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;if (Object.hasOwn(local, 'autonomousRun')) remote.autonomousRun = local.autonomousRun;// The composition document's files live only on this install as welldiff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex 8d2d0499d8..0440c0a2f0 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -1,18 +1,9 @@/**- * Music Video publishing (#9282): fill a platform's post in the PortOS Browser,- * show the director what it will post, and post only when they press Post.- *- * `prepare` opens a NEW tab, runs the platform adapter's fill (never its- * submit), screenshots the filled draft and parks it under a draft id.- * `submit` requires that same live draft: a missing, expired or closed draft- * is a 409 and nothing is posted. One browser operation runs at a time,- * because keyboard input goes to whichever tab has focus. A logged-out- * platform returns PUBLISH_LOGIN_REQUIRED; login, CAPTCHAs and 2FA are the- * director's to do in the PortOS Browser.- *- * Posting results persist to `project.publishKit.posts[target] = { url, postedAt }`;- * the director can add reception and notes, or record a post made by hand (#9287).- * Only platforms the director turned on can be prepared.+ * Prepare external platform drafts for manual review and publication.+ * The authenticated operator route requires fresh password verification.+ * PortOS never submits a draft; the operator publishes in the destination+ * platform and records its URL. Adapter preparation runs in a serialized,+ * dedicated browser tab. Existing drafts can be discarded or replaced.*/import { randomUUID } from 'crypto';import { existsSync } from 'fs';@@ -108,7 +99,7 @@ export async function preparePublishDraft(projectId, target, options = {}, depsdraft.timer.unref?.();drafts.set(id, draft);console.log(`📝 ${adapter.label} draft filled for music-video ${projectId.slice(0, 8)} [${id.slice(6, 14)}]`);- return { draftId: id, target, summary, screenshot: shot ? `data:image/jpeg;base64,${shot.toString('base64')}` : null };+ return { draftId: id, target, summary, manualPublication: true, screenshot: shot ? `data:image/jpeg;base64,${shot.toString('base64')}` : null };} catch (err) {await page.close().catch(() => {});await browser.close().catch(() => {});@@ -117,23 +108,12 @@ export async function preparePublishDraft(projectId, target, options = {}, deps});}-/** Post a draft the director reviewed. Resolves `{ project, post }`. */-export async function submitPublishDraft(projectId, draftId, deps = {}) {- const draft = drafts.get(draftId);- if (!draft || draft.projectId !== projectId) throw draftError('That draft is gone (posted, discarded or expired) — fill it again');- if (draft.page.isClosed?.()) { await closeDraft(draft); throw draftError('The draft tab was closed — fill it again'); }- const adapter = (deps.adapters || PUBLISH_ADAPTERS)[draft.target];- return serialize(async () => {- await draft.page.bringToFront();- const { url = null } = await adapter.submit(draft.page, draft.payload) || {};- await closeDraft(draft);- const post = { url, postedAt: new Date().toISOString() };- console.log(`🚀 Posted music-video ${projectId.slice(0, 8)} to ${adapter.label}${url ? `: ${url}` : ''}`);- const { project } = await mutateProjectRecord(projectId, (current) => {- const kit = current.publishKit && typeof current.publishKit === 'object' ? current.publishKit : {};- return { project: { ...current, publishKit: { ...kit, posts: { ...(kit.posts || {}), [draft.target]: post } } } };- });- return { project, post };+/** Final publication is deliberately unavailable to agents and API callers.+ * The operator reviews and publishes in the destination platform itself.+ */+export async function submitPublishDraft() {+ throw new ServerError('Publish manually in the destination platform, then record the post link in PortOS.', {+ status: 403, code: 'PUBLISH_MANUAL_REQUIRED',});}diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.jsindex 867c046d2d..d177f00446 100644--- a/server/services/musicVideo/publish/index.test.js+++ b/server/services/musicVideo/publish/index.test.js@@ -1,7 +1,7 @@/*** Posting state machine (#9282) with a fake browser and adapters: prepare- * fills a draft in a new tab and returns its screenshot, submit posts only a- * live draft and records the link, discard and re-prepare close the old tab.+ * fills a draft in a new tab and returns its screenshot. Submit always refuses;+ * manual links persist, and discard/re-prepare close the old tab.*/import { afterAll, describe, expect, it, vi } from 'vitest';import { mkdir, writeFile } from 'node:fs/promises';@@ -51,7 +51,7 @@ async function readyProject() {}describe('publish drafts (#9282)', () => {- it('fills a draft, then posts it only on submit and records the link', async () => {+ it('fills a reviewable draft but never submits it; records a manually published link', async () => {const id = await readyProject();const { connect, pages } = fakeBrowser();const adapters = { stackerNews: adapter() };@@ -60,11 +60,12 @@ describe('publish drafts (#9282)', () => {expect(draft.screenshot).toMatch(/^data:image\/jpeg;base64,/);expect(adapters.stackerNews.submit).not.toHaveBeenCalled();- const { project, post } = await submitPublishDraft(id, draft.draftId, { adapters });+ await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ status: 403, code: 'PUBLISH_MANUAL_REQUIRED' });+ expect(adapters.stackerNews.submit).not.toHaveBeenCalled();+ expect(pages[0].closed).toBe(false);+ const { project, post } = await recordPublishPost(id, 'stackerNews', { url: 'https://stacker.news/items/1' });expect(post.url).toBe('https://stacker.news/items/1');- expect(project.publishKit.posts.stackerNews.url).toBe('https://stacker.news/items/1');- expect(pages[0].closed).toBe(true);- await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DRAFT_MISSING' });+ expect(project.publishKit.posts.stackerNews.url).toBe(post.url);});it('closes the earlier draft when the same target is filled again, and discards on request', async () => {@@ -74,7 +75,7 @@ describe('publish drafts (#9282)', () => {const first = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });const second = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });expect(pages[0].closed).toBe(true);- await expect(submitPublishDraft(id, first.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_DRAFT_MISSING' });+ await expect(submitPublishDraft(id, first.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_MANUAL_REQUIRED' });expect(await discardPublishDraft(id, second.draftId)).toBe(true);expect(pages[1].closed).toBe(true);expect(await discardPublishDraft(id, second.draftId)).toBe(false);@@ -86,7 +87,7 @@ describe('publish drafts (#9282)', () => {const adapters = { stackerNews: adapter() };const draft = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });pages[0].closed = true;- await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_DRAFT_MISSING' });+ await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_MANUAL_REQUIRED' });expect(adapters.stackerNews.submit).not.toHaveBeenCalled();});diff --git a/server/services/musicVideo/render.code.test.js b/server/services/musicVideo/render.code.test.jsindex 64824ce66e..3e4a759f38 100644--- a/server/services/musicVideo/render.code.test.js+++ b/server/services/musicVideo/render.code.test.js@@ -1,50 +1,10 @@-import { describe, expect, it, vi } from 'vitest';+import { expect, it, vi } from 'vitest';-vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));-vi.mock('../../lib/ffmpeg.js', () => ({- findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),- safeUnder: (root, name) => (name ? `${root}/${name}` : null),- generateThumbnail: vi.fn(async () => 'thumb.jpg'),- probeVideoDuration: vi.fn(async () => 30),- probeVideoGeometry: vi.fn(async () => null),-}));-vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(), saveHistory: vi.fn(async () => {}), mutateVideoHistory: vi.fn() }));-vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));-vi.mock('./projects.js', () => ({ getProject: vi.fn(), updateProject: vi.fn(async () => ({})), listProjects: vi.fn(async () => []), mutateProjectRecord: vi.fn() }));-vi.mock('./compositionRender.js', () => ({- renderTypographyOverlays: vi.fn(),- removeCompositionScratch: vi.fn(),- sweepCompositionScratch: vi.fn(),- renderSongComposition: vi.fn(async () => ({ generationId: 'song-job' })),-}));+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));+vi.mock('./projects.js', () => ({ getProject: vi.fn(async () => ({ id: 'reviewed-project' })), updateProject: vi.fn() }));+const { renderMusicVideo } = await import('./render.js');-import { getProject } from './projects.js';-import { getTrack } from '../tracks/index.js';-import { renderSongComposition } from './compositionRender.js';-import { renderMusicVideo } from './render.js';--describe('renderMusicVideo code composition', () => {- it('passes the composition directory and excerpt in-point to the song renderer', async () => {- getProject.mockResolvedValue({ id: 'p1', trackId: 't1', audioAnalysis: { durationSec: 180 } });- getTrack.mockResolvedValue({ audioFilename: 'song.wav' });- const result = await renderMusicVideo('p1', { codeDirectory: 'compositions/song', startSec: 60 });- expect(result).toEqual({ generationId: 'song-job' });- expect(renderSongComposition).toHaveBeenCalledWith(expect.objectContaining({- directory: 'compositions/song',- audioPath: expect.stringContaining('song.wav'),- startSec: 60,- project: expect.objectContaining({ id: 'p1' }),- }));- });-- it('keeps a second code render off the project while the first is in flight', async () => {- getProject.mockResolvedValue({ id: 'p2', uploadedAudioFilename: 'take.wav', audioAnalysis: { durationSec: 90 } });- let release;- renderSongComposition.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));- const first = renderMusicVideo('p2', { codeDirectory: 'compositions/song' });- await vi.waitFor(() => expect(renderSongComposition).toHaveBeenCalled());- await expect(renderMusicVideo('p2', { codeDirectory: 'compositions/song' })).rejects.toMatchObject({ status: 409, code: 'RENDER_IN_PROGRESS' });- release({ generationId: 'done' });- await first;- });+it('refuses an unbound directory override instead of rendering different content under a project approval', async () => {+ await expect(renderMusicVideo('reviewed-project', { codeDirectory: 'compositions/unreviewed' }))+ .rejects.toMatchObject({ code: 'MUSIC_VIDEO_UNREVIEWED_DIRECTORY' });});diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.jsindex 8591b574a5..16ef060641 100644--- a/server/services/musicVideo/render.document.test.js+++ b/server/services/musicVideo/render.document.test.js@@ -1,3 +1,5 @@+// Engine mechanics are isolated from the review contract, covered in route/orchestration suites.+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));/*** Render planning for the composition-document render style: a `document`* project takes the seeked path with its document folder, a full render and a@@ -123,3 +125,20 @@ describe('composition-document render plan', () => {expect(encodeDocumentComposition).not.toHaveBeenCalled();});});+++it('rejects a changed film between preparing its reviewed plan and starting the encoder', async () => {+ const id = await documentProject();+ await importDocumentTemplate(id);+ encodeDocumentComposition.mockClear();+ let changed = false;+ await renderMusicVideo(id, { verifyCurrent: async () => {+ if (changed) return;+ changed = true;+ await projects.mutateProjectRecord(id, project => ({ project: { ...project,+ composition: { ...project.composition, posterSec: 2 },+ } }));+ } });+ await vi.waitFor(async () => expect((await projects.getProject(id)).status).toBe('failed'));+ expect(encodeDocumentComposition).not.toHaveBeenCalled();+});diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 49589fa813..75c43426a8 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -1,3 +1,4 @@+import { assertProductionApproval, productionReviewBasis } from './productionReview.js';import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';/*** Music Video — render pipeline (#1760, Phase 2).@@ -41,7 +42,7 @@ import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayeimport { renderableCues, sectionCardCues } from './composition.js';import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';import { encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';-import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';+import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';import { captureMusicVideoEvidence, musicVideoTakeChanges } from '../../lib/musicVideoDependencies.js';import { assertCurrentPerformanceTakes } from './performanceShot.js';@@ -625,28 +626,6 @@ export async function planMusicVideoRender(project) {return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };}-// An existing HTML composition directory is rendered through the music-video-// owner (#9075). The caller names the directory; excerpts pass the master's-// in-point as startSec. This is not the code-rendered project mode below.-async function renderMusicVideoCode(projectId, { codeDirectory, startSec = 0 }) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const existingJob = projectRenders.get(projectId);- if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {- throw new ServerError('Render already in progress for this project', {- status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId: existingJob === PENDING ? null : existingJob },- });- }- projectRenders.set(projectId, PENDING);- const jobId = randomUUID();- try {- const audioPath = await resolveMasterAudioPath(project);- return await renderSongComposition({ project, directory: codeDirectory, jobId, audioPath, startSec });- } finally {- if (projectRenders.get(projectId) === PENDING) projectRenders.delete(projectId);- }-}-// Code-rendered mode (#9076) and the composition-document mode seek a// composition instead of concatenating footage. They share this module's job// map so the existing SSE and cancel routes apply. Code mode never asks a@@ -693,7 +672,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);const renderingOn = await ensureInstanceId();- if (options.verifyCurrent) options.verifyCurrent(await getProject(projectId));+ await assertCurrentRenderApproval(projectId, project, options);const jobId = randomUUID();const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;const outputPath = join(PATHS.videos, filename);@@ -720,7 +699,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =closeJobAfterDelay(jobs, jobId);};Promise.resolve().then(async () => {- if (options.verifyCurrent) options.verifyCurrent(await getProject(projectId));+ await assertCurrentRenderApproval(projectId, project, options);if (signal.aborted) throw Object.assign(new Error('Render cancelled'), { code: 'CANCELED' });return renderer.encode({plan, project, projectId, jobId, audioPath, soundBed, outputPath, signal,@@ -771,13 +750,22 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =return { jobId };}-export async function renderMusicVideo(projectId, options = {}) {- if (typeof options?.codeDirectory === 'string' && options.codeDirectory) {- return renderMusicVideoCode(projectId, options);+async function assertCurrentRenderApproval(projectId, preparedProject, options) {+ const current = await getProject(projectId);+ assertProductionApproval(current);+ if (productionReviewBasis(current).proof !== productionReviewBasis(preparedProject).proof) {+ throw new ServerError('The reviewed film changed during render preparation.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });}+ await options.verifyCurrent?.(current);+}++export async function renderMusicVideo(projectId, options = {}) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });-+ assertProductionApproval(project);+ if (typeof options?.codeDirectory === 'string' && options.codeDirectory) {+ throw new ServerError('Import and select the composition document, then approve its animated proof before rendering.', { status: 409, code: 'MUSIC_VIDEO_UNREVIEWED_DIRECTORY' });+ }const existingJob = projectRenders.get(projectId);if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {throw new ServerError('Render already in progress for this project', {@@ -812,6 +800,7 @@ export async function renderMusicVideo(projectId, options = {}) {.sort((a, b) => a.startSec - b.startSec);const composition = cues.length > 0 ? project.composition : null;+ await assertCurrentRenderApproval(projectId, project, options);const job = { id: jobId, projectId, status: 'running', clients: [], process: null, totalDuration };jobs.set(jobId, job);projectRenders.set(projectId, jobId);@@ -982,7 +971,8 @@ export async function renderMusicVideo(projectId, options = {}) {renderTypographyOverlays({jobId, cues, style: { ...composition.style, graphicLanguage: project.treatment?.brief?.graphicLanguage }, width: canonW, height: canonH, fps, durationSec: totalDuration, signal,onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: 0.5 * fraction }),- }).then((overlays) => {+ }).then(async (overlays) => {+ await assertCurrentRenderApproval(projectId, project, options);signal.throwIfAborted();// Capture is over: from here a cancel kills the encode (job.process).job.overlayAbort = null;diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.jsindex 61239f871e..fe72523571 100644--- a/server/services/musicVideo/render.terminal.test.js+++ b/server/services/musicVideo/render.terminal.test.js@@ -1,3 +1,5 @@+// Engine mechanics are isolated from the review contract, covered in route/orchestration suites.+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));import { describe, it, expect, vi, beforeEach } from 'vitest';// #2386 — exactly-once terminal handling for the music-video renderer thatdiff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex fd241527f4..250a267079 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -1,3 +1,5 @@+// Creative approval behavior is covered through production review routes and orchestration.+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));import { productionPilotRenderProject } from './productionPilot.js';import { describe, it, expect, vi, beforeEach } from 'vitest';