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: opt-in automatic draft review/retries with spend limits and an explicit sound-design bed for music videos (#8988)
[._.]/ Adam Eivy9eec8bb6292c
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsxnew file mode 100644index 0000000000..6b05082571--- /dev/null+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx@@ -0,0 +1,187 @@+import { useState } from 'react';+import { Bot, Play, Pause, X } from 'lucide-react';+import useProviderModels from '../../hooks/useProviderModels.js';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import { formatTimecode } from '../../utils/formatters.js';++const STATUS_LABELS = {+ running: 'Running', stopped: 'Paused', 'limit-reached': 'Stopped at a limit', passed: 'Passed',+ 'needs-human': 'Needs you', failed: 'Failed', canceled: 'Cancelled',+};+const STATUS_TONES = {+ running: 'text-port-accent', stopped: 'text-port-warning', 'limit-reached': 'text-port-warning', passed: 'text-port-success',+ 'needs-human': 'text-port-warning', failed: 'text-port-error', canceled: 'text-port-text-muted',+};+const CHECK_TONES = { pass: 'bg-port-success/20 text-port-success', fail: 'bg-port-error/20 text-port-error', unverified: 'bg-port-border text-port-text-muted' };+const CHECK_LABELS = { composition: 'Composition', continuity: 'Continuity', motion: 'Motion', audioSync: 'Audio sync' };+const ACTION_LABELS = {+ wait: (a) => (a.on === 'generation' ? 'Waiting for the revised sections to generate…' : 'Rendering the draft…'),+ reviewing: () => 'Reviewing the draft (frames + continuous excerpt)…',+ generate: (a) => `Generating ${a.sections?.length || 0} revised section${a.sections?.length === 1 ? '' : 's'}…`,+};+const ACTIVE = new Set(['running', 'stopped', 'limit-reached']);+const inputCls = 'w-20 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';++/** The latest run worth showing: the live one, else the most recent. */+export const currentAutoReview = (project) => {+ const runs = Array.isArray(project?.autoReviews) ? project.autoReviews : [];+ return runs.find((r) => ACTIVE.has(r.status)) || runs[runs.length - 1] || null;+};++function LimitInputs({ idFor, attempts, generations, onAttempts, onGenerations, disabled }) {+ return (+ <>+ <div>+ <label htmlFor={idFor('attempts')} className="block text-[10px] text-port-text-muted">Max reviews</label>+ <input id={idFor('attempts')} type="number" min={1} max={10} step={1} value={attempts} disabled={disabled}+ onChange={(e) => onAttempts(Number(e.target.value))} className={inputCls} />+ </div>+ <div>+ <label htmlFor={idFor('generations')} className="block text-[10px] text-port-text-muted">Max paid generations</label>+ <input id={idFor('generations')} type="number" min={0} max={100} step={1} value={generations} disabled={disabled}+ onChange={(e) => onGenerations(Number(e.target.value))} className={inputCls} />+ </div>+ </>+ );+}++function AttemptRow({ attempt }) {+ const { review } = attempt;+ return (+ <li className="rounded border border-port-border p-1.5 space-y-1">+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="font-medium">Attempt {attempt.n}</span>+ {review ? <span className="uppercase text-[10px] text-port-text-muted">{review.verdict}</span> : <span className="text-port-text-muted">not reviewed yet</span>}+ {review && Object.entries(CHECK_LABELS).map(([key, label]) => (+ <span key={key} className={`px-1.5 py-0.5 rounded text-[10px] ${CHECK_TONES[review.checks?.[key]] || CHECK_TONES.unverified}`}>+ {label}: {review.checks?.[key] || 'unverified'}+ </span>+ ))}+ </div>+ {review?.evidence && (+ <p className="text-[10px] text-port-text-muted">+ Evidence: {review.evidence.boundaryFrames ? 'cut/cue sheet + ' : ''}{review.evidence.continuousFrames || 0} continuous frames+ {review.evidence.continuous ? ' + continuous-excerpt analysis' : ` — continuous analysis unavailable (${review.evidence.continuousError || 'not run'})`}+ </p>+ )}+ {review?.summary && <p className="text-port-text-muted">{review.summary}</p>}+ {review?.findings?.length > 0 && (+ <ul className="space-y-0.5">+ {review.findings.map((f, i) => (+ <li key={`${f.atSec}-${i}`} className="flex flex-wrap gap-1.5">+ {/* Blocking findings are also flagged notes on that draft, where they seek the player. */}+ <span className="font-mono text-port-accent">{formatTimecode(f.atSec)}</span>+ <span className={f.severity === 'blocking' ? 'text-port-error' : 'text-port-text-muted'}>{f.note}</span>+ </li>+ ))}+ </ul>+ )}+ </li>+ );+}++/**+ * Opt-in automatic review/retries (#8988). Nothing runs until the director+ * starts a run over the draft window with their own limits: how many drafts+ * may be reviewed (each review is one call to the chosen vision model) and how+ * many PAID scene generations the run's revisions may spend. The review sees+ * the cut/cue contact sheet plus frames across the whole continuous excerpt,+ * and the excerpt file itself is analysed for frozen footage and audio/picture+ * parity — a frame-only look can never pass motion or audio sync.+ */+export default function AutoReviewPanel({ project, startSec, endSec, rangeValid, rendering, autoReview }) {+ const run = currentAutoReview(project);+ const [attempts, setAttempts] = useState(3);+ const [generations, setGenerations] = useState(4);+ const [raiseAttempts, setRaiseAttempts] = useState(null);+ const [raiseGenerations, setRaiseGenerations] = useState(null);+ const {+ providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });+ const idFor = (s) => `mv-auto-review-${project?.id}-${s}`;+ const active = run && ACTIVE.has(run.status);+ const limitsValid = Number.isInteger(attempts) && attempts >= 1 && attempts <= 10+ && Number.isInteger(generations) && generations >= 0 && generations <= 100;+ const busy = autoReview.busy;+ const actionLabel = run?.status === 'running' && autoReview.action && ACTION_LABELS[autoReview.action.type]?.(autoReview.action);++ const resume = () => {+ const limits = {};+ if (raiseAttempts != null) limits.maxAttempts = raiseAttempts;+ if (raiseGenerations != null) limits.maxGenerations = raiseGenerations;+ autoReview.resume(run.id, Object.keys(limits).length ? limits : undefined).then(() => {+ setRaiseAttempts(null);+ setRaiseGenerations(null);+ });+ };++ return (+ <div className="rounded border border-port-border p-2 space-y-2 text-xs" aria-label="Automatic review">+ <span className="font-medium flex items-center gap-1"><Bot size={12} /> Auto-review (opt-in)</span>+ {!active && (+ <div className="space-y-2">+ <p className="text-port-text-muted">+ Renders the window above, has a vision model review it, and regenerates only the sections it flags — until the draft passes or a limit is hit.+ Regeneration is paid work; the run never exceeds the limits you set.+ </p>+ <div className="flex flex-wrap items-end gap-2">+ <LimitInputs idFor={idFor} attempts={attempts} generations={generations} onAttempts={setAttempts} onGenerations={setGenerations} disabled={busy} />+ {providers.length > 0 && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ label="Reviewer (vision)"+ disabled={busy}+ modelDisabled={availableModels.length === 0}+ compact+ alwaysShowModel+ emptyProviderOption="Active provider (default)"+ emptyModelOption="Default model"+ />+ )}+ <button type="button" disabled={busy || rendering || !rangeValid || !limitsValid}+ onClick={() => autoReview.start(startSec, endSec, { maxAttempts: attempts, maxGenerations: generations }, { providerId: selectedProviderId, model: selectedModel })}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 min-h-[44px] sm:min-h-0">+ <Play size={12} /> Start auto-review+ </button>+ </div>+ </div>+ )}+ {run && (+ <div className="space-y-1.5">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span>+ <span className={STATUS_TONES[run.status]}>{STATUS_LABELS[run.status] || run.status}</span>+ <span className="text-port-text-muted"> · {formatTimecode(run.startSec)}–{formatTimecode(run.endSec)} · reviews {run.usage.reviews}/{run.limits.maxAttempts} · paid generations {run.usage.generations}/{run.limits.maxGenerations}</span>+ </span>+ {active && (+ <div className="flex items-center gap-2">+ {run.status === 'running'+ ? <button type="button" disabled={busy} onClick={() => autoReview.stop(run.id)} className="flex items-center gap-1 text-port-warning disabled:opacity-50 min-h-[44px] sm:min-h-0"><Pause size={12} /> Pause</button>+ : <button type="button" disabled={busy} onClick={resume} className="flex items-center gap-1 text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0"><Play size={12} /> Resume</button>}+ <button type="button" disabled={busy} onClick={() => autoReview.cancel(run.id)} className="flex items-center gap-1 text-port-error disabled:opacity-50 min-h-[44px] sm:min-h-0"><X size={12} /> Cancel run</button>+ </div>+ )}+ </div>+ {actionLabel && <p className="text-port-text-muted">{actionLabel}</p>}+ {run.stopReason && run.status !== 'running' && <p role="status" className={STATUS_TONES[run.status]}>{run.stopReason}</p>}+ {run.status === 'limit-reached' && (+ <div className="flex flex-wrap items-end gap-2">+ <LimitInputs idFor={(s) => idFor(`raise-${s}`)}+ attempts={raiseAttempts ?? run.limits.maxAttempts} generations={raiseGenerations ?? run.limits.maxGenerations}+ onAttempts={setRaiseAttempts} onGenerations={setRaiseGenerations} disabled={busy} />+ <span className="text-port-text-muted">Raise a limit, then Resume.</span>+ </div>+ )}+ <ul className="space-y-1">+ {run.attempts.map((attempt) => <AttemptRow key={attempt.n} attempt={attempt} />)}+ </ul>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/AutoReviewPanel.test.jsx b/client/src/components/musicVideo/AutoReviewPanel.test.jsxnew file mode 100644index 0000000000..2e0fc2062a--- /dev/null+++ b/client/src/components/musicVideo/AutoReviewPanel.test.jsx@@ -0,0 +1,95 @@+/**+ * Auto-review panel (#8988) rendered with the real useMusicVideoAutoReview+ * hook over a mocked API and socket: a run starts only with the director's+ * explicit limits, the board submits exactly the sections a run hands out for+ * its own project, and a run stopped at a limit resumes only with the limits+ * the director raised.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { useState } from 'react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';++const listeners = vi.hoisted(() => new Map());+vi.mock('../../services/socket', () => ({+ default: {+ on: (ev, fn) => listeners.set(ev, fn),+ off: (ev) => listeners.delete(ev),+ },+}));+vi.mock('../../services/apiMusicVideo.js', () => ({+ startMusicVideoAutoReview: vi.fn(),+ resumeMusicVideoAutoReview: vi.fn(),+ stopMusicVideoAutoReview: vi.fn(),+ cancelMusicVideoAutoReview: vi.fn(),+}));+vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({+ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],+ setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(),+ }),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));++import * as api from '../../services/apiMusicVideo.js';+import useMusicVideoAutoReview from '../../hooks/useMusicVideoAutoReview.js';+import AutoReviewPanel from './AutoReviewPanel.jsx';++const baseProject = { id: 'mv-1', scenes: [{ sceneId: 's2', order: 0 }], autoReviews: [] };+const limitRun = {+ id: 'mvar-1', status: 'limit-reached', startSec: 0, endSec: 10, stopReason: 'Reached the 1-review attempt limit',+ limits: { maxAttempts: 1, maxGenerations: 2 }, usage: { reviews: 1, generations: 1 },+ attempts: [{ n: 1, excerptId: 'mve-1', review: null, revisionId: null }],+};++function Harness({ initial, submitSections }) {+ const [project, setProject] = useState(initial);+ const autoReview = useMusicVideoAutoReview({ project, replaceProject: setProject, submitSections });+ return <AutoReviewPanel project={project} startSec={0} endSec={10} rangeValid rendering={false} autoReview={autoReview} />;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('AutoReviewPanel (#8988)', () => {+ it('starts a run with the limits the director set, and refuses to start without valid ones', async () => {+ api.startMusicVideoAutoReview.mockResolvedValue({ project: baseProject, run: { id: 'mvar-1', status: 'running' } });+ render(<Harness initial={baseProject} submitSections={vi.fn()} />);+ const start = screen.getByRole('button', { name: /start auto-review/i });++ fireEvent.change(screen.getByLabelText('Max reviews'), { target: { value: '0' } });+ expect(start).toBeDisabled();++ fireEvent.change(screen.getByLabelText('Max reviews'), { target: { value: '2' } });+ fireEvent.change(screen.getByLabelText('Max paid generations'), { target: { value: '5' } });+ fireEvent.click(start);+ await waitFor(() => expect(api.startMusicVideoAutoReview).toHaveBeenCalledWith(+ 'mv-1', { startSec: 0, endSec: 10, limits: { maxAttempts: 2, maxGenerations: 5 } }, { silent: true },+ ));+ });++ it('submits exactly the sections a run hands out for THIS project', async () => {+ const submitSections = vi.fn(async () => 1);+ render(<Harness initial={baseProject} submitSections={submitSections} />);+ const running = { ...limitRun, status: 'running', stopReason: null };+ const project = { ...baseProject, autoReviews: [running] };+ const handout = { type: 'generate', revisionId: 'mvr-1', sections: [{ sceneId: 's2', kind: 'video' }] };++ act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-other', run: running, project, action: handout }));+ expect(submitSections).not.toHaveBeenCalled();++ act(() => listeners.get('music-video:auto-review')({ projectId: 'mv-1', run: running, project, action: handout }));+ expect(submitSections).toHaveBeenCalledWith(project, handout.sections, 'mvr-1');+ expect(await screen.findByText(/Generating 1 revised section/)).toBeInTheDocument();+ });++ it('a run stopped at a limit resumes with the raised limit only', async () => {+ api.resumeMusicVideoAutoReview.mockResolvedValue({ project: baseProject, run: { ...limitRun, status: 'running' } });+ render(<Harness initial={{ ...baseProject, autoReviews: [limitRun] }} submitSections={vi.fn()} />);+ expect(screen.getByText('Reached the 1-review attempt limit')).toBeInTheDocument();++ fireEvent.change(screen.getAllByLabelText('Max reviews')[0], { target: { value: '3' } });+ fireEvent.click(screen.getByRole('button', { name: /resume/i }));+ await waitFor(() => expect(api.resumeMusicVideoAutoReview).toHaveBeenCalledWith('mv-1', 'mvar-1', { limits: { maxAttempts: 3 } }, { silent: true }));+ });+});diff --git a/client/src/components/musicVideo/ExcerptPanel.jsx b/client/src/components/musicVideo/ExcerptPanel.jsxindex d80ac96088..761939ef01 100644--- a/client/src/components/musicVideo/ExcerptPanel.jsx+++ b/client/src/components/musicVideo/ExcerptPanel.jsx@@ -1,6 +1,7 @@import { useRef, useState } from 'react';import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard, RotateCcw } from 'lucide-react';import RevisionPanel, { currentRevision } from './RevisionPanel.jsx';+import AutoReviewPanel from './AutoReviewPanel.jsx';const VERDICT_STYLES = {flagged: 'bg-port-error/20 text-port-error',@@ -133,7 +134,7 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot* start) — a frame check alone can't prove motion/audio sync, so the video* plays alongside the sheet rather than replacing it.*/-export default function ExcerptPanel({ project, rendering, progress, excerpts, revision = null, ...actions }) {+export default function ExcerptPanel({ project, rendering, progress, excerpts, revision = null, autoReview = null, ...actions }) {const activeRevision = currentRevision(project);const canRevise = !!revision && !revision.busy && !rendering&& !(activeRevision && (activeRevision.status === 'open' || activeRevision.status === 'rendering'));@@ -178,6 +179,10 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, rgenScenes={revision.genScenes} genVideoScenes={revision.genVideoScenes}onResume={revision.resume} onCancel={revision.cancel} />)}+ {autoReview && (+ <AutoReviewPanel project={project} startSec={startSec} endSec={endSec} rangeValid={valid}+ rendering={rendering} autoReview={autoReview} />+ )}{excerpts.length > 0 && (<ul className="space-y-2">{[...excerpts].reverse().map((excerpt) => (diff --git a/client/src/components/musicVideo/SoundBedControl.jsx b/client/src/components/musicVideo/SoundBedControl.jsxnew file mode 100644index 0000000000..f5a1bf0253--- /dev/null+++ b/client/src/components/musicVideo/SoundBedControl.jsx@@ -0,0 +1,61 @@+import { useState } from 'react';+import { Waves } from 'lucide-react';+import toast from '../ui/Toast';+import { updateMusicVideoProject } from '../../services/apiMusicVideo.js';++const DEFAULT_VOLUME = 0.3;++/**+ * Optional sound-design bed (#8988). The song is the video's sole audio by+ * default; a director may explicitly pick one library track (ambience,+ * risers, texture) to mix UNDER it at a chosen level. The render trims the bed+ * to the song, so it can never extend or replace the master. "None" returns+ * the soundtrack to the song alone.+ */+export default function SoundBedControl({ project, tracks, disabled, onUpdated }) {+ const [busy, setBusy] = useState(false);+ const bed = project.soundBed || null;+ const [volume, setVolume] = useState(bed?.volume ?? DEFAULT_VOLUME);+ const selectId = `mv-sound-bed-${project.id}`;+ const volumeId = `mv-sound-bed-volume-${project.id}`;+ const candidates = tracks.filter((t) => t.id !== project.trackId);++ const save = (soundBed) => {+ setBusy(true);+ updateMusicVideoProject(project.id, { soundBed }, { silent: true })+ .then((updated) => {+ onUpdated(updated);+ toast.success(soundBed ? 'Sound-design bed set — mixed under the song' : 'Sound-design bed removed — the song is the only audio');+ })+ .catch((err) => toast.error(err?.message || 'Failed to update the sound-design bed'))+ .finally(() => setBusy(false));+ };++ // Save the level once the slider is released, not on every step of a drag.+ const commitVolume = () => {+ if (bed && volume !== bed.volume) save({ trackId: bed.trackId, volume });+ };+ const off = busy || disabled;+ return (+ <div className="mt-2 flex flex-wrap items-end gap-2 text-xs">+ <div>+ <label htmlFor={selectId} className="text-[10px] text-port-text-muted flex items-center gap-1"><Waves size={11} /> Sound-design bed</label>+ <select id={selectId} value={bed?.trackId || ''} disabled={off}+ onChange={(e) => save(e.target.value ? { trackId: e.target.value, volume } : null)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-1 disabled:opacity-50 max-w-[16rem]">+ <option value="">None — the song is the only audio</option>+ {candidates.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}+ </select>+ </div>+ {bed && (+ <div>+ <label htmlFor={volumeId} className="block text-[10px] text-port-text-muted">Bed level ({Math.round(volume * 100)}%)</label>+ <input id={volumeId} type="range" min={0.05} max={1} step={0.05} value={volume} disabled={off}+ onChange={(e) => setVolume(Number(e.target.value))}+ onPointerUp={commitVolume} onKeyUp={commitVolume}+ className="w-32" />+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsxindex 611dd0e4c5..5fa950e33c 100644--- a/client/src/components/musicVideo/TrackPanel.jsx+++ b/client/src/components/musicVideo/TrackPanel.jsx@@ -4,6 +4,7 @@ import MidiVisualization from '../songs/MidiVisualization.jsx';import { trackAudioUrl } from '../../services/apiTracks.js';import YoutubeImportControls from './YoutubeImportControls.jsx';import VocalStemControl from './VocalStemControl.jsx';+import SoundBedControl from './SoundBedControl.jsx';import { trackSourceLabel } from '../../lib/trackProvenance.js';/**@@ -12,7 +13,8 @@ import { trackSourceLabel } from '../../lib/trackProvenance.js';* download the resolved master file. Relinking is blocked while a render or a* MIDI transcription is bound to this project — both already resolved the* project's audio at kickoff. An optional vocal stem (#8977) conditions- * lip-sync performance shots in place of the mix.+ * lip-sync performance shots in place of the mix, and an optional+ * sound-design bed (#8988) mixes under the song only when explicitly chosen.*/export default function TrackPanel({project, tracks, trackName, audioFilename, youtube,@@ -62,6 +64,8 @@ export default function TrackPanel({hasAudio={Boolean(project.trackId || project.uploadedAudioFilename)}onUpdated={onProjectUpdated}/>+ {/* #8988: an optional, explicitly chosen bed mixed under the song. */}+ <SoundBedControl key={project.id} project={project} tracks={tracks} disabled={renderBound} onUpdated={onProjectUpdated} />{/* Preview + download the project's master audio track. Both act onthe resolved data/music/ file (linked track or uploaded audio). */}{audioUrl && (diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 9896f2b7ef..47a4f62928 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -248,7 +248,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |-| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId) }`. | The Music Video excerpt panel. |+| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId), submitSections(project, refs, revisionId) }`. | The Music Video excerpt panel. |+| `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and submits the revised sections a run hands out through `submitSections` while the board is open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. || `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. || `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. || `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 3adf19176e..7c796d7540 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -59,6 +59,7 @@ export * from './useKeyboardShortcuts.js';export { default as useMediaJobProgress } from './useMediaJobProgress.js';export * from './useMediaJobSse.js';export { default as useSceneRenderLifecycle } from './useSceneRenderLifecycle.js';+export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.js';export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';diff --git a/client/src/hooks/useMusicVideoAutoReview.js b/client/src/hooks/useMusicVideoAutoReview.jsnew file mode 100644index 0000000000..c3389b301a--- /dev/null+++ b/client/src/hooks/useMusicVideoAutoReview.js@@ -0,0 +1,87 @@+import { useEffect, useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import socket from '../services/socket';+import {+ startMusicVideoAutoReview,+ resumeMusicVideoAutoReview,+ stopMusicVideoAutoReview,+ cancelMusicVideoAutoReview,+} from '../services/apiMusicVideo.js';++const OUTCOME_TOASTS = {+ passed: (run) => toast.success(`Auto-review passed after ${run.attempts.length} attempt${run.attempts.length === 1 ? '' : 's'}`),+ 'needs-human': (run) => toast.info(`Auto-review needs you: ${run.stopReason || 'watch the latest draft'}`),+ 'limit-reached': (run) => toast.info(`Auto-review stopped at its limit: ${run.stopReason || ''}`),+ failed: (run) => toast.error(`Auto-review failed: ${run.stopReason || run.error || 'unknown error'}`),+};++/**+ * Opt-in automatic review/retries (#8988). A run is started only by the+ * director, with explicit limits on reviews (`maxAttempts`) and paid+ * generations (`maxGenerations`); the server then renders the draft window,+ * reviews it, and revises only the flagged sections, reporting each step over+ * the `music-video:auto-review` socket event. This hook applies the pushed+ * project, and — while the board is open — submits the sections a run hands+ * out through the board's normal scene lanes (`submitSections`, from+ * `useMusicVideoRevisions`), tagged with the run's revision so the server's+ * enqueue guard charges them against the spend limit.+ *+ * Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`+ * — `action` is the latest step the server reported for this project's run.+ */+export default function useMusicVideoAutoReview({ project, replaceProject, submitSections } = {}) {+ const projectId = project?.id || null;+ const [busy, setBusy] = useState(false);+ const [action, setAction] = useState(null);+ const handlers = useRef({ replaceProject, submitSections });+ const lastStatus = useRef(new Map());+ useEffect(() => {+ handlers.current = { replaceProject, submitSections };+ });++ useEffect(() => {+ if (!projectId) return undefined;+ setAction(null);+ const onAutoReview = (data) => {+ if (data?.projectId !== projectId) return;+ const { replaceProject: replace, submitSections: submit } = handlers.current;+ if (data.project) replace?.(data.project);+ setAction(data.action || null);+ if (data.action?.type === 'generate' && data.action.sections?.length && submit) {+ submit(data.project, data.action.sections, data.action.revisionId).then((n) => {+ if (n) toast.info(`Auto-review: generating ${n} revised section${n === 1 ? '' : 's'}`);+ });+ }+ const run = data.run;+ if (run?.id && lastStatus.current.get(run.id) !== run.status) {+ const seen = lastStatus.current.has(run.id);+ lastStatus.current.set(run.id, run.status);+ if (seen || run.status !== 'running') OUTCOME_TOASTS[run.status]?.(run);+ }+ };+ socket.on('music-video:auto-review', onAutoReview);+ return () => socket.off('music-video:auto-review', onAutoReview);+ }, [projectId]);++ const call = (request) => {+ setBusy(true);+ return request()+ .then((res) => {+ if (res?.project) handlers.current.replaceProject?.(res.project);+ if (res?.run) lastStatus.current.set(res.run.id, res.run.status);+ return res;+ })+ .catch((err) => { toast.error(err?.message || 'Auto-review request failed'); return null; })+ .finally(() => setBusy(false));+ };++ const start = (startSec, endSec, limits, { providerId = null, model = null } = {}) =>+ call(() => startMusicVideoAutoReview(projectId, {+ startSec, endSec, limits, ...(providerId ? { providerId } : {}), ...(model ? { model } : {}),+ }, { silent: true }));+ const resume = (runId, limits) => call(() => resumeMusicVideoAutoReview(projectId, runId, limits ? { limits } : {}, { silent: true }));+ const stop = (runId) => call(() => stopMusicVideoAutoReview(projectId, runId, { silent: true }));+ const cancel = (runId) => call(() => cancelMusicVideoAutoReview(projectId, runId, { silent: true }));++ return { busy, action, start, resume, stop, cancel };+}diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.jsindex 3255b2ebc7..2bffa07eb3 100644--- a/client/src/hooks/useMusicVideoRevisions.js+++ b/client/src/hooks/useMusicVideoRevisions.js@@ -38,6 +38,10 @@ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;* `replaceProject(project)` swaps the local record whole; `sceneMedia` is the* `useMusicVideoSceneMedia` result; `attachRender(jobId, projectId)` is* `useMusicVideoExcerpts().attachRender`.+ *+ * `submitSections(project, refs, revisionId)` exposes the same tagged+ * submission for an auto-review run's hand-outs (#8988); resolves to the+ * number of sections that reached the queue.*/export default function useMusicVideoRevisions({ project, replaceProject, sceneMedia, attachRender } = {}) {const projectId = project?.id || null;@@ -111,5 +115,7 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneMreturn res;}));- return { busy, revise, resume, cancel };+ // Also used by an opt-in auto-review run (#8988), which hands its revised+ // sections to the open board over the `music-video:auto-review` event.+ return { busy, revise, resume, cancel, submitSections: generateSections };}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 721e9232e8..cafb6e9127 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -25,6 +25,7 @@ import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';+import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';@@ -134,6 +135,7 @@ export default function MusicVideo() {// Selective section revision (#8987): regenerate only a draft's flagged// sections, resumable from the server's checkpoint.const revisions = useMusicVideoRevisions({ project: selected, replaceProject, sceneMedia, attachRender: excerpts.attachRender });+ const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject, submitSections: revisions.submitSections });// Pre-production treatment (#8980): brief, compiled arc, shot direction,// proof checklist and the non-destructive Apply review.const treatment = useMusicVideoTreatment({ project: selected, onProjectPatch: patchProject, replaceProject });@@ -718,6 +720,7 @@ export default function MusicVideo() {editNote={excerpts.editNote}deleteNote={excerpts.deleteNote}revision={{ ...revisions, genScenes: sceneMedia.genScenes, genVideoScenes: sceneMedia.genVideoScenes }}+ autoReview={autoReview}/><LyricsPanelproject={selected}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 1769a13020..04c36f4b1e 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -191,6 +191,20 @@ export const releaseMusicVideoRevisionSection = (id, revisionId, sceneId, optionmethod: 'POST', body: JSON.stringify({ sceneId }), ...options,});+// ---- Opt-in automatic review/retries (#8988) ----+// Start body: { startSec, endSec, limits: { maxAttempts, maxGenerations }, providerId?, model? }+// → { project, run }. The run then advances server-side and reports over the+// `music-video:auto-review` socket event.+export const startMusicVideoAutoReview = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/auto-reviews`, { method: 'POST', body: JSON.stringify(body), ...options });+// Body: { limits?: { maxAttempts?, maxGenerations? } } — optionally RAISES the limits.+export const resumeMusicVideoAutoReview = (id, runId, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/auto-reviews/${encodeURIComponent(runId)}/resume`, { method: 'POST', body: JSON.stringify(body), ...options });+export const stopMusicVideoAutoReview = (id, runId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/auto-reviews/${encodeURIComponent(runId)}/stop`, { method: 'POST', ...options });+export const cancelMusicVideoAutoReview = (id, runId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/auto-reviews/${encodeURIComponent(runId)}/cancel`, { method: 'POST', ...options });+// ---- Pre-production treatment (#8980) ----// A structured brief, a compiled whole-song arc, per-shot direction keyed to the// board's scene ids and a proof checklist. Every write names the treatmentdiff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 2d73379f3e..c94f83918a 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached) — Grok video is cutaway-only. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached) — Grok video is cutaway-only. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync); the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 82a558ae9b..2b519d0e64 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -382,6 +382,28 @@ export const musicVideoRevisionStartSchema = z.object({sceneIds: z.array(z.string().min(1).max(200)).min(1).max(500).optional(),}).strict();+// ---- Opt-in automatic review/retries (#8988) --------------------------------+// Every limit is required: a run never picks its own budget. `maxAttempts`+// bounds the reviews (provider calls); `maxGenerations` is the spend limit on+// paid scene-generation jobs. See services/musicVideo/autoReview.js.+export const musicVideoAutoReviewLimitsSchema = z.object({+ maxAttempts: z.number().int().min(1).max(10),+ maxGenerations: z.number().int().min(0).max(100),+}).strict();++export const musicVideoAutoReviewStartSchema = z.object({+ startSec: z.number().min(0).max(36000),+ endSec: z.number().min(0).max(36000),+ limits: musicVideoAutoReviewLimitsSchema,+ providerId: z.string().min(1).max(200).nullable().optional(),+ model: z.string().min(1).max(200).nullable().optional(),+}).strict().refine((r) => r.endSec > r.startSec, { message: 'endSec must be greater than startSec' });++// Resume may RAISE either limit (never below what the run already used).+export const musicVideoAutoReviewResumeSchema = z.object({+ limits: musicVideoAutoReviewLimitsSchema.partial().optional(),+}).strict();+// A generation kickoff that failed before reaching the queue (#9011) — names// the rejected section whose claim should clear so the next resume can hand// it out again immediately instead of waiting out GENERATION_CLAIM_LEASE_MS.@@ -389,6 +411,14 @@ export const musicVideoRevisionReleaseSchema = z.object({sceneId: z.string().min(1).max(200),}).strict();+// Optional sound-design bed (#8988): one explicitly chosen music-library track+// mixed UNDER the song. null (or omitted) keeps the song as the sole audio+// master. See services/musicVideo/soundBed.js.+export const musicVideoSoundBedSchema = z.object({+ trackId: z.string().min(1).max(64),+ volume: z.number().min(0.05).max(1).optional(),+}).strict();+export const musicVideoProjectCreateSchema = z.object({name: z.string().min(1).max(200),mode: z.enum(MUSIC_VIDEO_MODES).optional(),@@ -416,6 +446,7 @@ export const musicVideoProjectUpdateSchema = z.object({phrases: phraseList.optional(),pacing: musicVideoPacingSchema.nullable().optional(),composition: musicVideoCompositionSchema.nullable().optional(),+ soundBed: musicVideoSoundBedSchema.nullable().optional(),}).strict();// Fork a project into its next editable version. The server derives lineage anddiff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 632e0e748a..2682873c5d 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -68,7 +68,7 @@ async function enqueueLoggedImage(req, job) {// service's closure.if (job.params?.musicVideo?.revisionId) {const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');- await assertRevisionOpen(job.params.musicVideo.projectId, job.params.musicVideo.revisionId);+ await assertRevisionOpen(job.params.musicVideo.projectId, job.params.musicVideo.revisionId, { sceneId: job.params.musicVideo.sceneId, kind: 'image' });}const queued = await enqueueJob(job);try {@@ -675,7 +675,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// tag carries no revisionId.if (params.musicVideo?.revisionId) {const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');- await assertRevisionOpen(params.musicVideo.projectId, params.musicVideo.revisionId);+ await assertRevisionOpen(params.musicVideo.projectId, params.musicVideo.revisionId, { sceneId: params.musicVideo.sceneId, kind: 'image' });}const result = await imageGen.generateImage(params);if (params.fableLoom && result?.filename) {diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 03c66b2405..c911eaa6d9 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -35,6 +35,8 @@ import {musicVideoExcerptNoteUpdateSchema,musicVideoRevisionStartSchema,musicVideoRevisionReleaseSchema,+ musicVideoAutoReviewStartSchema,+ musicVideoAutoReviewResumeSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -78,6 +80,9 @@ import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from 'import {startRevision, resumeRevision, cancelRevision, releaseRevisionSection,} from '../services/musicVideo/revisionService.js';+import {+ startAutoReview, resumeAutoReview, stopAutoReview, cancelAutoReview,+} from '../services/musicVideo/autoReviewService.js';import { planProject } from '../services/musicVideo/planner.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import {@@ -431,6 +436,29 @@ router.post('/:id/revisions/:revisionId/release', asyncHandler(async (req, res)res.json(await releaseRevisionSection(req.params.id, req.params.revisionId, input.sceneId));}));+// --- Opt-in automatic review/retries (#8988) ---+// Start/resume write the checkpoint and return at once; the run advances in+// the background (render → review → revise → generate → re-render) and+// reports over the `music-video:auto-review` socket event. Only these+// explicit requests start or resume a run — nothing at boot does.+router.post('/:id/auto-reviews', asyncHandler(async (req, res) => {+ const { providerId, model, ...input } = validateRequest(musicVideoAutoReviewStartSchema, req.body || {});+ res.status(201).json(await startAutoReview(req.params.id, { ...input, reviewer: { providerId, model } }));+}));++router.post('/:id/auto-reviews/:runId/resume', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoAutoReviewResumeSchema, req.body || {});+ res.json(await resumeAutoReview(req.params.id, req.params.runId, input));+}));++router.post('/:id/auto-reviews/:runId/stop', asyncHandler(async (req, res) => {+ res.json(await stopAutoReview(req.params.id, req.params.runId));+}));++router.post('/:id/auto-reviews/:runId/cancel', asyncHandler(async (req, res) => {+ res.json(await cancelAutoReview(req.params.id, req.params.runId));+}));+// --- Director scene board ---router.post('/:id/scenes', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex a346fa9120..6560ed8403 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -236,6 +236,17 @@ describe('musicVideo routes', () => {expect(svc.updateProject).toHaveBeenCalledWith('mv-1', { composition });});+ it('PATCH /:id takes an explicit sound-design bed, refuses a bed louder than the song, and clears it with null (#8988)', async () => {+ const loud = await request(app).patch('/api/music-video/mv-1').send({ soundBed: { trackId: 'trk-rain', volume: 1.5 } });+ expect(loud.status).toBe(400);+ expect(svc.updateProject).not.toHaveBeenCalled();+ const ok = await request(app).patch('/api/music-video/mv-1').send({ soundBed: { trackId: 'trk-rain', volume: 0.25 } });+ expect(ok.status).toBe(200);+ const cleared = await request(app).patch('/api/music-video/mv-1').send({ soundBed: null });+ expect(cleared.status).toBe(200);+ expect(svc.updateProject).toHaveBeenLastCalledWith('mv-1', { soundBed: null });+ });+describe('POST /:id/lyrics/import (#8964)', () => {it('replaces the cue list with the parsed LRC and reports the detected format', async () => {svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [{ id: 'lc-old', text: 'old', startSec: 1, endSec: 2 }] });diff --git a/server/routes/musicVideoAutoReview.test.js b/server/routes/musicVideoAutoReview.test.jsnew file mode 100644index 0000000000..41e0a7d4b6--- /dev/null+++ b/server/routes/musicVideoAutoReview.test.js@@ -0,0 +1,294 @@+/**+ * Music Video opt-in automatic review/retries (#8988), through the real+ * router, autoReviewService.js, revisionService.js, excerptRender.js and the+ * real file-backed project store. Only the process boundaries are doubled:+ * the ffmpeg/ffprobe children (a fake encode the test finishes, and canned+ * analysis output), the render prep that needs a real ffmpeg + song, the+ * media-job queue, and the reviewer's provider call (an injected verdict+ * sequence whose call count is the review spend).+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { dirname, join } from 'path';+import { promisify } from 'util';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-auto-review-route-test-');+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));++const h = vi.hoisted(() => {+ const procs = [];+ const makeEmitter = () => {+ const listeners = {};+ return {+ on(ev, fn) { (listeners[ev] ||= []).push(fn); return this; },+ emit(ev, ...args) { for (const fn of listeners[ev] || []) fn(...args); },+ };+ };+ const spawn = (_cmd, args) => {+ const p = makeEmitter();+ p.args = args;+ p.stderr = makeEmitter();+ p.kill = () => {};+ procs.push(p);+ return p;+ };+ return {+ procs, spawn, jobs: [], verdicts: [], review: null, analysisAvailable: true, freezeStderr: '',+ };+});++vi.mock('../lib/childProcess.js', async (importOriginal) => {+ const real = await importOriginal();+ // The continuous-excerpt analysis: ffprobe stream lengths + ffmpeg freezedetect.+ const execFile = Object.assign(() => { throw new Error('execFile is only used promisified here'); }, {+ [promisify.custom]: async (bin) => (bin === 'ffprobe'+ ? { stdout: 'video,20.000000\naudio,20.010000\n', stderr: '' }+ : { stdout: '', stderr: h.freezeStderr }),+ });+ return { ...real, spawn: h.spawn, execFile };+});+vi.mock('../lib/ffmpeg.js', async (importOriginal) => {+ const real = await importOriginal();+ const { writeFileSync: write, mkdirSync: mkdir } = await import('fs');+ const { join: joinPath } = await import('path');+ const { PATHS } = await import('../lib/fileUtils.js');+ return {+ ...real,+ findFfmpeg: vi.fn(async () => (h.analysisAvailable ? 'ffmpeg' : null)),+ findFfprobe: vi.fn(async () => (h.analysisAvailable ? 'ffprobe' : null)),+ // Real frame files, so the reviewer sees a non-empty continuous strip.+ extractEvaluationFrames: vi.fn(async (_path, id, count) => {+ mkdir(PATHS.videoThumbnails, { recursive: true });+ return Array.from({ length: count }, (_, i) => {+ const name = `${id}-f${i + 1}.jpg`;+ write(joinPath(PATHS.videoThumbnails, name), 'jpg');+ return name;+ });+ }),+ };+});+vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));+vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-test') }));+vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.emit('close', null, 'SIGTERM')) }));+vi.mock('../services/htmlComposition/encode.js', () => ({ encodeFileContactSheetAtTimes: vi.fn(async () => {}) }));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ listJobs: vi.fn(({ kind } = {}) => h.jobs.filter((j) => !kind || j.kind === kind)),+ enqueueJob: vi.fn(),+ cancelJob: vi.fn(async () => {}),+}));+vi.mock('../services/promptRunner.js', () => ({+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'reviewer', name: 'Reviewer', type: 'api' }, selectedModel: 'vision-1' })),+ assertVisionRunUsedImages: vi.fn((_result, provider) => provider),+ runPromptThroughProvider: vi.fn(async () => ({ text: JSON.stringify(h.verdicts.shift()) })),+}));+// Three 10s sections: footage s1, footage s2, still s3 (a composed render).+const CLIPS = [+ { sceneId: 's1', videoPath: '/v/a.mp4', width: 640, height: 360, fps: 24, inSec: 0, outSec: 10, duration: 10, sourceSec: 10, loop: true },+ { sceneId: 's2', videoPath: '/v/b.mp4', width: 640, height: 360, fps: 24, inSec: 0, outSec: 10, duration: 10, sourceSec: 10, loop: true },+ { sceneId: 's3', layer: 'still', imagePath: '/i/c.png', move: 'hold', inSec: 0, outSec: 10, duration: 10, sourceSec: 10 },+];+vi.mock('../services/musicVideo/render.js', async (importOriginal) => ({+ ...(await importOriginal()),+ planMusicVideoRender: vi.fn(async () => ({ ffmpeg: 'ffmpeg', audioPath: '/a/song.wav', composed: true, clips: CLIPS, audioDurationSec: 30, soundBed: null })),+}));++const { default: musicVideoRoutes } = await import('./musicVideo.js');+const projects = await import('../services/musicVideo/projects.js');+const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');+const { musicVideoEvents } = await import('../services/musicVideo/events.js');+const { runPromptThroughProvider } = await import('../services/promptRunner.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++const base = (id) => `/api/music-video/${id}`;+const scene = (sceneId, order, media) => ({ sceneId, order, prompt: `shot ${sceneId}`, takes: [], ...media });+const PASS = { checks: { composition: 'pass', continuity: 'pass', motion: 'pass' }, findings: [], summary: 'Reads well.' };+// A blocking problem at excerpt time 8s — inside s2 (song time 13s of the [5, 25) window).+const FAIL_S2 = {+ checks: { composition: 'fail', continuity: 'pass', motion: 'pass' },+ findings: [{ atSec: 8, check: 'composition', severity: 'blocking', note: 'The subject\'s hands warp.' }],+ summary: 'One shot is broken.',+};++const project = async () => {+ const created = await projects.createProject({ name: 'Example Video' });+ return projects.updateProject(created.id, {+ scenes: [+ scene('s1', 0, { referenceImageId: 'f1.png', videoHistoryId: 'clip-1' }),+ scene('s2', 1, { referenceImageId: 'f2.png', videoHistoryId: 'clip-2' }),+ scene('s3', 2, { referenceImageId: 'still-3.png', visualLayer: 'still' }),+ ],+ });+};++const settled = (projectId, check) => vi.waitFor(async () => {+ const p = await projects.getProject(projectId);+ check(p);+ return p;+}, { timeout: 5000, interval: 20 });+const run = (p) => p.autoReviews[p.autoReviews.length - 1];++// Finish the in-flight draft encode: the fake ffmpeg "writes" its output and exits 0.+async function finishDraft(projectId, renders) {+ await vi.waitFor(() => expect(h.procs).toHaveLength(renders), { timeout: 5000, interval: 20 });+ const proc = h.procs[renders - 1];+ const outputPath = proc.args[proc.args.length - 1];+ mkdirSync(dirname(outputPath), { recursive: true });+ writeFileSync(outputPath, 'mp4');+ proc.emit('spawn');+ proc.emit('close', 0, null);+ await settled(projectId, (p) => expect(p.excerpts.filter((e) => e.status === 'complete')).toHaveLength(renders));+}++// What the scene-video completion hook does when a regenerated clip lands.+async function landTake(projectId, sceneId, assetId) {+ await projects.appendSceneTakes(projectId, sceneId, [{ kind: 'video', assetId, source: 'generated', provider: 'portos', jobId: `job-${assetId}` }]);+ musicVideoEvents.emit('scene-video', { projectId, sceneId, videoHistoryId: assetId });+}++const start = (projectId, limits) => request(app).post(`${base(projectId)}/auto-reviews`).send({ startSec: 5, endSec: 25, limits });++beforeEach(() => {+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });+ h.procs.length = 0;+ h.jobs.length = 0;+ h.verdicts.length = 0;+ h.analysisAvailable = true;+ h.freezeStderr = '';+ vi.clearAllMocks();+});+afterAll(cleanupTempDataRoots);++describe('opt-in automatic review/retries (#8988)', () => {+ it('requires explicit limits — a run never picks its own budget', async () => {+ const p = await project();+ const r = await request(app).post(`${base(p.id)}/auto-reviews`).send({ startSec: 5, endSec: 25 });+ expect(r.status).toBe(400);+ expect(h.procs).toHaveLength(0);+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('reviews, revises only the flagged section, enforces the spend limit at enqueue, and passes the re-rendered draft', async () => {+ const p = await project();+ h.verdicts.push(FAIL_S2, PASS);+ const r = await start(p.id, { maxAttempts: 2, maxGenerations: 1 });+ expect(r.status).toBe(201);+ expect(r.body.run).toMatchObject({ status: 'running', limits: { maxAttempts: 2, maxGenerations: 1 } });++ await finishDraft(p.id, 1);+ // Attempt 1 reviewed: its finding became a flagged, timecoded note and a+ // revision rejected s2 only.+ let current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());+ const attempt1 = run(current).attempts[0];+ expect(attempt1.review).toMatchObject({ verdict: 'revise', checks: { composition: 'fail', audioSync: 'pass', motion: 'pass' } });+ expect(attempt1.review.evidence).toMatchObject({ continuous: true, continuousFrames: 12 });+ const draft = current.excerpts.find((e) => e.id === attempt1.excerptId);+ expect(draft.notes).toEqual([expect.objectContaining({ atSec: 8, verdict: 'flagged', note: expect.stringMatching(/^\[auto-review\] .*hands warp/) })]);+ const revision = current.revisions.find((rv) => rv.id === attempt1.revisionId);+ expect(revision.sections.filter((s) => s.verdict === 'rejected').map((s) => s.sceneId)).toEqual(['s2']);++ // The board submits s2: the enqueue guard charges it. A double submit+ // while its job is live, and any further paid job past the run's spend+ // limit, are refused BEFORE they reach the queue.+ const s2 = { sceneId: 's2', kind: 'video' };+ await assertRevisionOpen(p.id, revision.id, s2);+ h.jobs.push({ id: 'job-s2', kind: 'video', status: 'running', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: p.id, sceneId: 's2', revisionId: revision.id } } });+ await expect(assertRevisionOpen(p.id, revision.id, s2)).rejects.toMatchObject({ code: 'AUTO_REVIEW_SECTION_IN_FLIGHT' });+ await expect(assertRevisionOpen(p.id, revision.id, { sceneId: 's1', kind: 'video' })).rejects.toMatchObject({ code: 'AUTO_REVIEW_SPEND_LIMIT' });+ h.jobs[0].status = 'completed';+ current = await projects.getProject(p.id);+ expect(run(current).usage).toEqual({ reviews: 1, generations: 1 });++ // The new take lands → the run re-renders the window and reviews attempt 2.+ await landTake(p.id, 's2', 'clip-2b');+ await finishDraft(p.id, 2);+ current = await settled(p.id, (x) => expect(run(x).status).toBe('passed'));+ expect(run(current).attempts).toHaveLength(2);+ expect(run(current).attempts[1].review.verdict).toBe('pass');+ expect(run(current).usage).toEqual({ reviews: 2, generations: 1 });+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(2);+ expect(current.scenes[0].videoHistoryId).toBe('clip-1'); // the approved section was never touched+ });++ it('a stopped run ignores completion events, then resumes from its checkpoint without repeating a completed attempt', async () => {+ const p = await project();+ h.verdicts.push(FAIL_S2, PASS);+ await start(p.id, { maxAttempts: 1, maxGenerations: 3 });+ await finishDraft(p.id, 1);+ let current = await settled(p.id, (x) => expect(run(x).attempts[0].revisionId).toBeTruthy());+ const runId = run(current).id;+ const reviewed = run(current).attempts[0].review;++ expect((await request(app).post(`${base(p.id)}/auto-reviews/${runId}/stop`)).body.run.status).toBe('stopped');+ // The take the board already paid for still lands — but a stopped run+ // does not advance on it: no re-render, no review.+ await landTake(p.id, 's2', 'clip-2b');+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(h.procs).toHaveLength(1);++ // Resume: the revision renders (its section already holds a take — no+ // generation), and the next draft hits the 1-review attempt limit.+ await request(app).post(`${base(p.id)}/auto-reviews/${runId}/resume`).send({});+ await finishDraft(p.id, 2);+ current = await settled(p.id, (x) => expect(run(x).status).toBe('limit-reached'));+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);++ // Raising the limit reviews ONLY the new draft; attempt 1 keeps its review.+ await request(app).post(`${base(p.id)}/auto-reviews/${runId}/resume`).send({ limits: { maxAttempts: 2 } });+ current = await settled(p.id, (x) => expect(run(x).status).toBe('passed'));+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(2);+ expect(run(current).attempts[0].review).toEqual(reviewed);+ expect(run(current).usage).toEqual({ reviews: 2, generations: 0 });+ expect(h.procs).toHaveLength(2);+ });++ it('stops before handing out a revision the remaining spend cannot cover', async () => {+ const p = await project();+ h.verdicts.push(FAIL_S2);+ await start(p.id, { maxAttempts: 2, maxGenerations: 0 });+ await finishDraft(p.id, 1);+ const current = await settled(p.id, (x) => expect(run(x).status).toBe('limit-reached'));+ expect(run(current).stopReason).toMatch(/spend limit/);+ const revision = current.revisions.find((rv) => rv.id === run(current).attempts[0].revisionId);+ expect(revision.sections.find((s) => s.sceneId === 's2').claimedAt).toBeUndefined(); // nothing was handed out+ });++ it('a frame-only look cannot pass: without the continuous analysis the run stops for a human', async () => {+ const p = await project();+ h.analysisAvailable = false;+ h.verdicts.push(PASS);+ await start(p.id, { maxAttempts: 3, maxGenerations: 3 });+ await finishDraft(p.id, 1);+ const current = await settled(p.id, (x) => expect(run(x).status).toBe('needs-human'));+ expect(run(current).attempts[0].review).toMatchObject({+ verdict: 'inconclusive',+ checks: { composition: 'pass', continuity: 'pass', motion: 'unverified', audioSync: 'unverified' },+ evidence: { continuous: false },+ });+ expect(run(current).stopReason).toMatch(/frames alone cannot prove motion or audio sync/);+ });++ it('frozen footage found in the continuous excerpt fails motion even when the frames looked fine', async () => {+ const p = await project();+ // Excerpt timeline: s1 0–5, s2 5–15 (footage), s3 15–20 (still). A freeze+ // at 6–8.5s stalls footage s2…+ h.freezeStderr = '[freezedetect @ 0x1] lavfi.freezedetect.freeze_start: 6.0\n[freezedetect @ 0x1] lavfi.freezedetect.freeze_end: 8.5\n'+ // …and a freeze inside the still section (excerpt 15–20) is planned, not a stall.+ + '[freezedetect @ 0x1] lavfi.freezedetect.freeze_start: 15.5\n[freezedetect @ 0x1] lavfi.freezedetect.freeze_end: 19.5\n';+ h.verdicts.push(PASS);+ await start(p.id, { maxAttempts: 1, maxGenerations: 0 });+ await finishDraft(p.id, 1);+ const current = await settled(p.id, (x) => expect(run(x).attempts[0].review).toBeTruthy());+ const { review } = run(current).attempts[0];+ expect(review.checks.motion).toBe('fail');+ expect(review.findings).toEqual([expect.objectContaining({ atSec: 6, check: 'motion', source: 'analysis' })]);+ });+});diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.jsnew file mode 100644index 0000000000..743325b894--- /dev/null+++ b/server/services/musicVideo/autoReview.js@@ -0,0 +1,354 @@+/**+ * Music Video — opt-in automatic review/retries (#8988, part of #8966): pure+ * record transforms.+ *+ * An auto-review RUN is a persisted checkpoint on the project+ * (`project.autoReviews[]`) that exists only because the director explicitly+ * started one, with their own limits:+ *+ * - `limits.maxAttempts` — how many drafts may be REVIEWED (each review is+ * one provider call; the counter is spent before+ * the call, so a crash mid-call still counts it);+ * - `limits.maxGenerations` — the spend limit: how many paid scene-generation+ * jobs the run's revisions may put on the queue.+ * Charged at the enqueue choke point+ * (`chargeAutoReviewGeneration`, called from the+ * generation routes' revision guard) so a job over+ * the limit is refused BEFORE it is paid for.+ *+ * Each attempt renders the draft window (free), reviews it, and either passes+ * the run or files the review's timecoded findings as flagged notes on that+ * excerpt and opens a #8987 selective revision for the sections they land in.+ * The revision's re-rendered draft is the next attempt's excerpt. Everything a+ * later step needs is derived from the record (`nextAutoReviewStep`), so a+ * stopped or interrupted run resumes exactly where it was: an attempt that+ * already holds a review is never reviewed again, and a revised section that+ * already holds a take is never generated again (#8987 semantics).+ *+ * No boot or standing job ever advances a run — only the director's start /+ * resume and the completion events of work that run itself put in flight.+ *+ * Peer sync: `autoReviews` is an additive field on the whole-record LWW+ * project body (same posture as `excerpts`/`revisions`). An older peer stores+ * it verbatim and has no route that acts on it, so no schema bump is needed.+ */++import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';+import { addExcerptNote, projectExcerpts } from './excerpt.js';+import { projectRevisions } from './revision.js';++export const AUTO_REVIEW_LIMIT_BOUNDS = Object.freeze({+ maxAttempts: Object.freeze({ min: 1, max: 10 }),+ maxGenerations: Object.freeze({ min: 0, max: 100 }),+});+// Statuses: `running` (advancing), `stopped` (paused by the director —+// resumable), `limit-reached` (a limit stopped it — resumable once raised),+// and the terminal `passed` / `needs-human` / `failed` / `canceled`.+export const AUTO_REVIEW_STATUSES = Object.freeze(['running', 'stopped', 'limit-reached', 'passed', 'needs-human', 'failed', 'canceled']);+const RESUMABLE = new Set(['running', 'stopped', 'limit-reached']);+const ACTIVE = new Set(['running', 'stopped', 'limit-reached']);+export const AUTO_REVIEW_CHECKS = Object.freeze(['composition', 'continuity', 'motion', 'audioSync']);+// Draft renders are free, but a window that fails to render every time must+// not loop forever: this many failed renders of one attempt fail the run.+export const MAX_RENDER_FAILURES = 2;+const MAX_PROJECT_AUTO_REVIEWS = 10;+const MAX_FINDINGS = 20;+const MAX_FINDING_LEN = 500;+const NOTE_PREFIX = '[auto-review]';++const autoReviewError = (status, code, message, context) =>+ new ServerError(message, { status, code, ...(context ? { context } : {}) });++/** The run array on a project, tolerating a legacy record with none. */+export const projectAutoReviews = (project) => (Array.isArray(project?.autoReviews) ? project.autoReviews : []);++/** The run that is still live (running, paused, or waiting on raised limits), if any. */+export const activeAutoReview = (project) => projectAutoReviews(project).find((r) => ACTIVE.has(r.status)) || null;++const currentAttempt = (run) => run.attempts[run.attempts.length - 1];++function findRun(project, runId) {+ const run = projectAutoReviews(project).find((r) => r.id === runId);+ if (!run) throw autoReviewError(404, 'NOT_FOUND', 'Auto-review run not found');+ return run;+}++function replaceRun(project, run) {+ return { ...project, autoReviews: projectAutoReviews(project).map((r) => (r.id === run.id ? run : r)) };+}++function pruneRuns(runs) {+ const next = runs.slice();+ for (let i = 0; i < next.length && next.length > MAX_PROJECT_AUTO_REVIEWS;) {+ if (ACTIVE.has(next[i].status)) i += 1;+ else next.splice(i, 1);+ }+ return next;+}++const intIn = (value, { min, max }, name) => {+ if (!Number.isInteger(value) || value < min || value > max) {+ throw autoReviewError(422, 'VALIDATION_ERROR', `${name} must be a whole number from ${min} to ${max}`);+ }+ return value;+};++/** Validate a limits object; every limit is REQUIRED — a run never picks its own budget. */+export function normalizeAutoReviewLimits(limits) {+ return {+ maxAttempts: intIn(limits?.maxAttempts, AUTO_REVIEW_LIMIT_BOUNDS.maxAttempts, 'maxAttempts'),+ maxGenerations: intIn(limits?.maxGenerations, AUTO_REVIEW_LIMIT_BOUNDS.maxGenerations, 'maxGenerations'),+ };+}++const touchRun = (run, patch, now) => ({ ...run, ...patch, updatedAt: now });++/**+ * Start a run over `[startSec, endSec)`. Refuses while another run is live or+ * a manual revision is open (the run needs the revision slot for its own).+ */+export function startAutoReviewOnProject(project, { startSec, endSec, limits, reviewer = {} }, now = new Date().toISOString()) {+ const live = activeAutoReview(project);+ if (live) throw autoReviewError(409, 'AUTO_REVIEW_IN_PROGRESS', 'Finish, cancel or resume the existing auto-review run first', { runId: live.id });+ const openRevision = projectRevisions(project).find((r) => r.status === 'open' || r.status === 'rendering');+ if (openRevision) throw autoReviewError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before starting an auto-review run', { revisionId: openRevision.id });+ if (!(startSec >= 0) || !(endSec > startSec)) throw autoReviewError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec');+ const run = {+ id: `mvar-${randomUUID()}`,+ status: 'running',+ startSec,+ endSec,+ limits: normalizeAutoReviewLimits(limits),+ reviewer: {+ providerId: isNonBlankStr(reviewer.providerId) ? reviewer.providerId : null,+ model: isNonBlankStr(reviewer.model) ? reviewer.model : null,+ },+ usage: { reviews: 0, generations: 0 },+ attempts: [{ n: 1, excerptId: null, renderFailures: 0, reviewStartedAt: null, review: null, revisionId: null }],+ stopReason: null,+ error: null,+ createdAt: now,+ updatedAt: now,+ };+ return { project: { ...project, autoReviews: pruneRuns([...projectAutoReviews(project), run]), updatedAt: now }, run };+}++/**+ * Pure: what the run should do next, derived from the record alone:+ * `render` — the attempt has no draft yet (or its draft failed and may retry);+ * `review` — the attempt's draft is ready and unreviewed (and the attempt+ * budget allows another review);+ * `revise` — the review asked for changes and no revision was opened yet;+ * `resume-revision` — the attempt's revision is open (generate or re-render);+ * `next-attempt` — the revision's re-rendered draft is ready to review;+ * `wait` — a render is in flight;+ * `halt` — the run must stop now (`status` + `reason`);+ * `idle` — the run is not running.+ */+export function nextAutoReviewStep(project, run) {+ if (run.status !== 'running') return { type: 'idle' };+ const attempt = currentAttempt(run);+ if (!attempt.excerptId) return { type: 'render' };+ const excerpt = projectExcerpts(project).find((e) => e.id === attempt.excerptId);+ const renderFailed = !excerpt || excerpt.status === 'error' || excerpt.status === 'canceled';+ if (renderFailed && !attempt.review) {+ if (attempt.renderFailures >= MAX_RENDER_FAILURES) {+ return { type: 'halt', status: 'failed', reason: `The draft failed to render ${attempt.renderFailures + 1} times${excerpt?.error ? `: ${excerpt.error}` : ''}` };+ }+ return { type: 'render', retry: true };+ }+ if (excerpt?.status === 'rendering') return { type: 'wait', on: 'render', excerptId: excerpt.id };+ if (!attempt.review) {+ if (run.usage.reviews >= run.limits.maxAttempts) {+ return { type: 'halt', status: 'limit-reached', reason: `Reached the ${run.limits.maxAttempts}-review attempt limit` };+ }+ return { type: 'review', excerptId: attempt.excerptId };+ }+ if (!attempt.revisionId) return { type: 'revise', excerptId: attempt.excerptId };+ const revision = projectRevisions(project).find((r) => r.id === attempt.revisionId);+ if (!revision || revision.status === 'canceled') {+ return { type: 'halt', status: 'needs-human', reason: 'The run\'s revision was cancelled — review this draft by hand' };+ }+ if (revision.status === 'rendering') return { type: 'wait', on: 'render', excerptId: revision.renderExcerptId };+ if (revision.status === 'open') {+ // A revised draft that keeps failing to render must not re-render forever.+ if (revision.error && (revision.renderAttempts || 0) > MAX_RENDER_FAILURES) {+ return { type: 'halt', status: 'failed', reason: `The revised draft failed to render ${revision.renderAttempts} times: ${revision.error}` };+ }+ return { type: 'resume-revision', revisionId: revision.id };+ }+ return { type: 'next-attempt', excerptId: revision.renderExcerptId };+}++function mutateRun(project, runId, fn, now) {+ const run = findRun(project, runId);+ const next = fn(run);+ return { project: replaceRun(project, touchRun(run, next, now)), run: touchRun(run, next, now) };+}++const withAttempt = (run, patch) => ({+ attempts: run.attempts.map((a, i) => (i === run.attempts.length - 1 ? { ...a, ...patch } : a)),+});++/** Link the current attempt to a draft render it just started (a retry counts the failed one). */+export function attachAttemptExcerpt(project, runId, excerptId, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => {+ const attempt = currentAttempt(run);+ const failed = attempt.excerptId ? 1 : 0;+ return withAttempt(run, { excerptId, renderFailures: attempt.renderFailures + failed });+ }, now);+}++/** Open the next attempt on the revision's re-rendered draft. */+export function beginNextAttempt(project, runId, excerptId, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => ({+ attempts: [...run.attempts, { n: run.attempts.length + 1, excerptId, renderFailures: 0, reviewStartedAt: null, review: null, revisionId: null }],+ }), now);+}++/**+ * Spend one review from the attempt budget BEFORE the provider call. Throws+ * 409 when the budget is spent, the run is no longer running, or the attempt+ * already holds a review — so an overlapping advance can never pay twice.+ */+export function beginAttemptReview(project, runId, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => {+ if (run.status !== 'running') throw autoReviewError(409, 'AUTO_REVIEW_NOT_RUNNING', `This run is ${run.status}`);+ const attempt = currentAttempt(run);+ if (attempt.review) throw autoReviewError(409, 'ATTEMPT_ALREADY_REVIEWED', 'This draft was already reviewed');+ if (run.usage.reviews >= run.limits.maxAttempts) {+ throw autoReviewError(409, 'AUTO_REVIEW_ATTEMPT_LIMIT', `Reached the ${run.limits.maxAttempts}-review attempt limit`);+ }+ return { usage: { ...run.usage, reviews: run.usage.reviews + 1 }, ...withAttempt(run, { reviewStartedAt: now }) };+ }, now);+}++const cleanFinding = (f, spanSec) => {+ if (!f || typeof f !== 'object' || !isNonBlankStr(f.note)) return null;+ const atSec = typeof f.atSec === 'number' && Number.isFinite(f.atSec) ? Math.min(Math.max(0, f.atSec), spanSec) : null;+ if (atSec === null) return null;+ return {+ atSec: Math.round(atSec * 1000) / 1000,+ note: trimTo(f.note, MAX_FINDING_LEN),+ severity: f.severity === 'minor' ? 'minor' : 'blocking',+ check: AUTO_REVIEW_CHECKS.includes(f.check) ? f.check : null,+ source: f.source === 'analysis' ? 'analysis' : 'reviewer',+ };+};++/**+ * Record a gated review (see `gateAutoReview` in autoReviewJudge.js) on the+ * current attempt. `pass` ends the run `passed`; `inconclusive` ends it+ * `needs-human` (a frame-only look can never pass motion/audio sync); `revise`+ * files every blocking finding as a flagged, timecoded note on the draft so+ * the #8987 revision rejects exactly the sections they land in.+ */+export function recordAttemptReview(project, runId, review, now = new Date().toISOString()) {+ const run = findRun(project, runId);+ const attempt = currentAttempt(run);+ if (attempt.review) throw autoReviewError(409, 'ATTEMPT_ALREADY_REVIEWED', 'This draft was already reviewed');+ const excerpt = projectExcerpts(project).find((e) => e.id === attempt.excerptId);+ const spanSec = excerpt ? excerpt.endSec - excerpt.startSec : 0;+ const findings = (Array.isArray(review.findings) ? review.findings : []).map((f) => cleanFinding(f, spanSec)).filter(Boolean).slice(0, MAX_FINDINGS);+ const stored = { ...review, findings, reviewedAt: now };+ let next = project;+ if (review.verdict === 'revise' && excerpt) {+ for (const finding of findings.filter((f) => f.severity === 'blocking')) {+ next = addExcerptNote(next, excerpt.id, { atSec: finding.atSec, note: `${NOTE_PREFIX} ${finding.note}`, verdict: 'flagged' }, now).project;+ }+ }+ const terminal = review.verdict === 'pass'+ ? { status: 'passed', stopReason: null }+ : review.verdict === 'inconclusive'+ ? { status: 'needs-human', stopReason: review.reason || 'The review could not verify every check — a director must watch this draft' }+ : {};+ const updated = touchRun(run, { ...terminal, ...withAttempt(run, { review: stored }) }, now);+ return { project: replaceRun(next, updated), run: updated };+}++/** Link the attempt's revision (opened in the same write, see autoReviewService). */+export function attachAttemptRevision(project, runId, revisionId, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => withAttempt(run, { revisionId }), now);+}++/** Stop the run with a status/reason (a `halt` step, or a failed step). */+export function haltAutoReview(project, runId, { status, reason = null, error = null }, now = new Date().toISOString()) {+ if (!AUTO_REVIEW_STATUSES.includes(status) || status === 'running') throw new Error(`haltAutoReview: invalid status ${status}`);+ return mutateRun(project, runId, (run) => {+ if (!RESUMABLE.has(run.status)) throw autoReviewError(409, 'AUTO_REVIEW_CLOSED', `This run is already ${run.status}`);+ return { status, stopReason: reason, error };+ }, now);+}++/** Director pause: nothing new is handed out; resumable from the same checkpoint. */+export function stopAutoReviewOnProject(project, runId, now = new Date().toISOString()) {+ const run = findRun(project, runId);+ if (run.status !== 'running') throw autoReviewError(409, 'AUTO_REVIEW_NOT_RUNNING', `This run is ${run.status}`);+ return haltAutoReview(project, runId, { status: 'stopped', reason: 'Stopped by the director' }, now);+}++/**+ * Resume a stopped (or limit-reached) run from its checkpoint. `limits`+ * optionally RAISES the budget — never below what the run already spent.+ */+export function resumeAutoReviewOnProject(project, runId, { limits } = {}, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => {+ if (!RESUMABLE.has(run.status)) throw autoReviewError(409, 'AUTO_REVIEW_CLOSED', `This run is ${run.status} — start a new run instead`);+ const nextLimits = limits ? normalizeAutoReviewLimits({ ...run.limits, ...limits }) : run.limits;+ if (nextLimits.maxAttempts < run.usage.reviews || nextLimits.maxGenerations < run.usage.generations) {+ throw autoReviewError(422, 'VALIDATION_ERROR', 'A limit cannot be lowered below what this run already used');+ }+ return { status: 'running', limits: nextLimits, stopReason: null, error: null };+ }, now);+}++/** Cancel (terminal). Returns the open revision the caller must cancel too, if any. */+export function cancelAutoReviewOnProject(project, runId, now = new Date().toISOString()) {+ const run = findRun(project, runId);+ if (!RESUMABLE.has(run.status)) throw autoReviewError(409, 'AUTO_REVIEW_CLOSED', `This run is already ${run.status}`);+ const revisionId = currentAttempt(run).revisionId;+ const revision = revisionId ? projectRevisions(project).find((r) => r.id === revisionId) : null;+ const out = haltAutoReview(project, runId, { status: 'canceled', reason: 'Cancelled by the director' }, now);+ return { ...out, revisionId: revision && (revision.status === 'open' || revision.status === 'rendering') ? revision.id : null };+}++/**+ * The spend check at the enqueue choke point: a generation job tagged with a+ * revision that a RUNNING run opened is charged against the run's+ * `maxGenerations`, and refused (409 AUTO_REVIEW_SPEND_LIMIT) once it is spent+ * — before the job is queued. A revision no running run owns (a manual one, or+ * a paused run the director is finishing by hand) is not charged.+ * Returns `{ project, run }` — `run` null (and the project untouched) when no+ * running run owns the revision.+ */+export function chargeAutoReviewGeneration(project, revisionId, now = new Date().toISOString()) {+ const run = runOwningRevision(project, revisionId);+ if (!run) return { project, run: null };+ if (run.usage.generations >= run.limits.maxGenerations) {+ throw autoReviewError(409, 'AUTO_REVIEW_SPEND_LIMIT', `This auto-review run reached its ${run.limits.maxGenerations}-generation spend limit`, { runId: run.id });+ }+ return mutateRun(project, run.id, (r) => ({ usage: { ...r.usage, generations: r.usage.generations + 1 } }), now);+}++/** Generations still affordable before the spend limit. */+export const remainingGenerations = (run) => Math.max(0, run.limits.maxGenerations - run.usage.generations);++/**+ * The running run (if any) waiting on this excerpt's render: its current+ * attempt's own draft, or the re-render of its current attempt's revision.+ */+export function runAwaitingExcerpt(project, excerptId) {+ const revisions = projectRevisions(project);+ return projectAutoReviews(project).find((run) => {+ if (run.status !== 'running') return false;+ const attempt = currentAttempt(run);+ return attempt.excerptId === excerptId+ || (!!attempt.revisionId && revisions.some((r) => r.id === attempt.revisionId && r.renderExcerptId === excerptId));+ }) || null;+}++/** The running run (if any) whose current attempt's revision is this one. */+export const runOwningRevision = (project, revisionId) => projectAutoReviews(project)+ .find((run) => run.status === 'running' && currentAttempt(run).revisionId === revisionId) || null;diff --git a/server/services/musicVideo/autoReviewJudge.js b/server/services/musicVideo/autoReviewJudge.jsnew file mode 100644index 0000000000..083a705cc1--- /dev/null+++ b/server/services/musicVideo/autoReviewJudge.js@@ -0,0 +1,183 @@+/**+ * Music Video — automatic draft review (#8988): the reviewer prompt, its+ * response parser, and the EVIDENCE GATE that decides what a review may pass.+ *+ * A review looks at two kinds of evidence:+ * - FRAMES — the draft's cut/cue contact sheet (#8986) plus a dense strip of+ * frames sampled evenly across the whole excerpt, judged by a vision model+ * for composition and shot-to-shot continuity;+ * - the CONTINUOUS excerpt — the encoded file itself, analysed end to end:+ * frozen footage (`freezedetect`) inside a footage section, and the+ * audio/video stream-length parity that shows the song ran under the whole+ * cut without being clipped or padded.+ *+ * A vision model cannot hear, and a set of stills cannot show motion, so the+ * gate never lets frames alone pass `motion` or `audioSync`: without a+ * successful continuous analysis both stay `unverified`, and a review with any+ * unverified check can only be `inconclusive` — the run then stops for a+ * director to watch the draft rather than passing it. Pure; the I/O lives in+ * autoReviewService.js.+ */++import { extractJson } from '../../lib/jsonExtract.js';+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';+import { AUTO_REVIEW_CHECKS } from './autoReview.js';++const CHECK_VALUES = new Set(['pass', 'fail']);+const MODEL_CHECKS = ['composition', 'continuity', 'motion'];+// A frozen span shorter than this inside footage reads as a held beat, not a stall.+export const FREEZE_MIN_SEC = 1;+// Audio and video may differ by up to one frame plus encoder padding.+const AV_SLACK_SEC = 0.05;+const MAX_SUMMARY_LEN = 1000;++const round3 = (n) => Math.round(n * 1000) / 1000;++/** Parse `freezedetect` output (ffmpeg stderr) into `[{ startSec, endSec }]`; an open freeze runs to `spanSec`. */+export function parseFreezeIntervals(stderr, spanSec) {+ const out = [];+ let open = null;+ for (const line of String(stderr || '').split(/\r?\n/)) {+ const start = line.match(/freeze_start:\s*([\d.]+)/);+ if (start) { open = parseFloat(start[1]); continue; }+ const end = line.match(/freeze_end:\s*([\d.]+)/);+ if (end && open !== null) { out.push({ startSec: round3(open), endSec: round3(parseFloat(end[1])) }); open = null; }+ }+ if (open !== null && Number.isFinite(spanSec)) out.push({ startSec: round3(open), endSec: round3(spanSec) });+ return out.filter((f) => Number.isFinite(f.startSec) && f.endSec > f.startSec);+}++/** Parse `ffprobe -show_entries stream=codec_type,duration -of csv=p=0` into `{ video, audio }` seconds (null when absent). */+export function parseStreamDurations(stdout) {+ const out = { video: null, audio: null };+ for (const line of String(stdout || '').split(/\r?\n/)) {+ const [type, dur] = line.trim().split(',');+ const n = parseFloat(dur);+ if ((type === 'video' || type === 'audio') && Number.isFinite(n) && out[type] === null) out[type] = n;+ }+ return out;+}++/**+ * Keep only the freezes that stall FOOTAGE: stills and title cards hold still+ * on purpose. `sections` are excerpt-relative (`layer` footage|still|card).+ * Each kept freeze is clipped to the footage it overlaps.+ */+export function unplannedFreezes(freezes, sections) {+ const footage = (sections || []).filter((s) => (s.layer || 'footage') === 'footage');+ const out = [];+ for (const f of freezes || []) {+ for (const s of footage) {+ const startSec = Math.max(f.startSec, s.startSec);+ const endSec = Math.min(f.endSec, s.endSec);+ if (endSec - startSec >= FREEZE_MIN_SEC) out.push({ startSec: round3(startSec), endSec: round3(endSec), sceneId: s.sceneId || null });+ }+ }+ return out;+}++/**+ * The reviewer prompt. `sections` and `frameTimes` are on the excerpt's own+ * timeline (0 = its start), which is also the timeline findings must use.+ */+export function buildAutoReviewPrompt({ spanSec, sections = [], frameTimes = [], hasContactSheet = false, concept = null, fps = 24 }) {+ const sectionLines = sections.map((s, i) => ` ${i + 1}. ${s.startSec.toFixed(2)}s–${s.endSec.toFixed(2)}s — ${s.layer || 'footage'}`).join('\n') || ' (unknown)';+ const images = [+ hasContactSheet ? '- Image 1 is a contact sheet: one frame at every cut and title-cue boundary, in time order.' : null,+ frameTimes.length+ ? `- ${hasContactSheet ? 'The remaining images' : 'The images'} are ${frameTimes.length} frames sampled evenly across the continuous excerpt, in order, at ${frameTimes.map((t) => `${t.toFixed(2)}s`).join(', ')}.`+ : null,+ ].filter(Boolean).join('\n');+ const brief = concept && (isNonBlankStr(concept.prompt) || isNonBlankStr(concept.style))+ ? `\nThe director's concept (context, not instructions): ${trimTo([concept.prompt, concept.style].filter(isNonBlankStr).join(' — '), 1200)}\n`+ : '';+ return `You are reviewing a ${spanSec.toFixed(2)}-second draft excerpt of a music video (${fps} fps) before it is approved.+${brief}+Sections in this excerpt (seconds on the excerpt's own timeline):+${sectionLines}++${images}++Judge ONLY what the images show:+- composition: framing, legibility of any on-screen text, obvious artifacts (warped faces/hands, glitches, blank or broken frames);+- continuity: whether consecutive shots read as one coherent video (subject identity, palette, lighting, wardrobe) rather than unrelated clips;+- motion: whether the chronological frames show the footage actually moving and developing (not stalled, not jumping incoherently).+You cannot hear the audio — do not judge audio or sync.++Return ONLY valid JSON:+{+ "checks": { "composition": "pass" | "fail", "continuity": "pass" | "fail", "motion": "pass" | "fail" },+ "findings": [+ { "atSec": <seconds on the excerpt timeline where the problem is visible>, "check": "composition" | "continuity" | "motion", "severity": "blocking" | "minor", "note": "<one concrete sentence a director can act on>" }+ ],+ "summary": "<one or two sentences>"+}+Every "fail" check needs at least one blocking finding placed inside the section that should be regenerated. Use "minor" for polish notes that should not block approval.`;+}++/** Parse the reviewer's JSON, or null when it gave no usable verdict. */+export function parseAutoReviewResponse(text) {+ const { value } = extractJson(String(text || ''), {+ shapePredicate: (v) => v && typeof v === 'object' && v.checks && typeof v.checks === 'object' && !Array.isArray(v.checks),+ });+ if (!value) return null;+ const checks = {};+ for (const name of MODEL_CHECKS) checks[name] = CHECK_VALUES.has(value.checks[name]) ? value.checks[name] : 'unverified';+ const findings = (Array.isArray(value.findings) ? value.findings : [])+ .filter((f) => f && typeof f === 'object' && isNonBlankStr(f.note) && typeof f.atSec === 'number' && Number.isFinite(f.atSec))+ .map((f) => ({ atSec: f.atSec, note: f.note, check: MODEL_CHECKS.includes(f.check) ? f.check : null, severity: f.severity === 'minor' ? 'minor' : 'blocking', source: 'reviewer' }));+ return { checks, findings, summary: isNonBlankStr(value.summary) ? trimTo(value.summary, MAX_SUMMARY_LEN) : '' };+}++/**+ * The evidence gate. `parsed` is `parseAutoReviewResponse`'s result (null when+ * the reviewer failed); `analysis` is the continuous-excerpt analysis —+ * `{ ok, error?, spanSec, avDriftSec, freezes }` with `freezes` already+ * narrowed to unplanned ones — or `{ ok: false }` when it never ran.+ * Returns the review to record: `{ verdict, reason, checks, findings, evidence, summary }`.+ */+export function gateAutoReview({ parsed, analysis, evidence = {} }) {+ const continuous = analysis?.ok === true;+ const spanSec = analysis?.spanSec ?? null;+ const checks = { composition: 'unverified', continuity: 'unverified', motion: 'unverified', audioSync: 'unverified' };+ const findings = [...(parsed?.findings || [])];+ if (parsed) {+ checks.composition = parsed.checks.composition;+ checks.continuity = parsed.checks.continuity;+ }+ if (continuous) {+ const freezes = analysis.freezes || [];+ for (const f of freezes) {+ findings.push({ atSec: f.startSec, check: 'motion', severity: 'blocking', source: 'analysis', note: `Footage freezes for ${(f.endSec - f.startSec).toFixed(1)}s (${f.startSec.toFixed(2)}s–${f.endSec.toFixed(2)}s)` });+ }+ checks.motion = freezes.length ? 'fail' : (parsed ? parsed.checks.motion : 'unverified');+ const drift = analysis.avDriftSec;+ if (typeof drift === 'number' && Number.isFinite(drift)) {+ const tolerance = AV_SLACK_SEC + 1 / (evidence.fps || 24);+ if (Math.abs(drift) > tolerance) {+ checks.audioSync = 'fail';+ findings.push({ atSec: Math.max(0, (spanSec ?? 0) - 0.001), check: 'audioSync', severity: 'blocking', source: 'analysis', note: `Audio and picture lengths differ by ${Math.abs(drift).toFixed(2)}s — the song is ${drift > 0 ? 'longer' : 'shorter'} than the cut` });+ } else {+ checks.audioSync = 'pass';+ }+ }+ }+ const failed = AUTO_REVIEW_CHECKS.filter((c) => checks[c] === 'fail');+ const unverified = AUTO_REVIEW_CHECKS.filter((c) => checks[c] === 'unverified');+ const blocking = findings.filter((f) => f.severity === 'blocking');+ const base = {+ checks,+ findings,+ summary: parsed?.summary || '',+ evidence: { ...evidence, continuous, continuousError: continuous ? null : (analysis?.error || 'The continuous excerpt was not analysed'), avDriftSec: continuous ? analysis.avDriftSec ?? null : null },+ };+ if (!parsed) return { ...base, verdict: 'inconclusive', reason: 'The reviewer returned no usable verdict — watch this draft yourself' };+ // A blocking finding is something to regenerate, whatever else was verified —+ // revising never claims a pass, so it needs no continuous evidence.+ if (blocking.length) return { ...base, verdict: 'revise', reason: null };+ if (failed.length) return { ...base, verdict: 'inconclusive', reason: `The reviewer failed ${failed.join(', ')} without placing a finding on the timeline` };+ if (unverified.length) {+ return { ...base, verdict: 'inconclusive', reason: `Could not verify ${unverified.join(', ')}${continuous ? '' : ' — frames alone cannot prove motion or audio sync'}` };+ }+ return { ...base, verdict: 'pass', reason: null };+}diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.jsnew file mode 100644index 0000000000..60ac64b3fb--- /dev/null+++ b/server/services/musicVideo/autoReviewService.js@@ -0,0 +1,383 @@+/**+ * Music Video — opt-in automatic review/retries (#8988): the orchestrator+ * over the pure checkpoint in autoReview.js and the evidence gate in+ * autoReviewJudge.js.+ *+ * `advanceAutoReview` derives the run's next step from the record and keeps+ * taking steps until the run has to wait: for a draft render, for generation+ * jobs, or for the director's board to submit the sections it hands out+ * (generation goes through the board's normal scene lanes, tagged with the+ * run's revision — the same path a manual #8987 revision uses, so every job+ * passes the enqueue-time spend check in `assertRevisionOpen`).+ *+ * What moves a run forward:+ * - the director — start, resume (and the board submitting handed-out+ * sections);+ * - completion events of work THIS run put in flight: its draft render+ * finishing (`excerpt-render`) or a take landing on one of its revised+ * sections (`scene-image` / `scene-video`).+ * Nothing at boot advances a run, and a run that is not `running` ignores+ * every event — so no provider call is ever made without the director's+ * explicit, limited request. Advances for one run are coalesced in-process,+ * so an event arriving mid-step can never start a second review.+ */++import { unlink } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { promisify } from 'util';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/fileUtils.js';+import { execFile } from '../../lib/childProcess.js';+import { safeChildProcessOptions } from '../../lib/processEnv.js';+import { extractEvaluationFrames, findFfmpeg, findFfprobe, safeUnder } from '../../lib/ffmpeg.js';+import { isVisionCapableCliProvider } from '../../lib/localModelHeuristics.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';+import { startExcerptRender } from './excerptRender.js';+import { cancelRevision, resumeRevision } from './revisionService.js';+import { projectExcerpts } from './excerpt.js';+import { projectRevisions, revisionSectionStates, startRevisionOnProject } from './revision.js';+import {+ attachAttemptExcerpt,+ attachAttemptRevision,+ beginAttemptReview,+ beginNextAttempt,+ cancelAutoReviewOnProject,+ haltAutoReview,+ nextAutoReviewStep,+ projectAutoReviews,+ recordAttemptReview,+ remainingGenerations,+ resumeAutoReviewOnProject,+ runAwaitingExcerpt,+ startAutoReviewOnProject,+ stopAutoReviewOnProject,+} from './autoReview.js';+import {+ buildAutoReviewPrompt,+ gateAutoReview,+ parseAutoReviewResponse,+ parseFreezeIntervals,+ parseStreamDurations,+ unplannedFreezes,+ FREEZE_MIN_SEC,+} from './autoReviewJudge.js';++const execFileAsync = promisify(execFile);+// Frames sampled evenly across the continuous excerpt for the reviewer.+const STRIP_FRAMES = 12;+// A run takes at most this many steps per advance before yielding — a guard+// against a step that fails to change the record looping forever.+const MAX_STEPS_PER_ADVANCE = 16;+const REVIEW_TIMEOUT_MS = 240_000;++const advancing = new Map();++const short = (id) => String(id || '').slice(5, 13);++function findRun(project, runId) {+ const run = projectAutoReviews(project).find((r) => r.id === runId);+ if (!run) throw new ServerError('Auto-review run not found', { status: 404, code: 'NOT_FOUND' });+ return run;+}++async function requireProject(projectId) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return project;+}++function publish(projectId, project, run, action) {+ musicVideoEvents.emit('auto-review', { projectId, runId: run.id, run, action, project });+}++async function halt(projectId, runId, { status, reason, error = null }) {+ const out = await mutateProjectRecord(projectId, (current) => haltAutoReview(current, runId, { status, reason, error }));+ const log = status === 'failed' ? console.error : console.warn;+ log(`${status === 'failed' ? '❌' : '⏸️'} Music Video auto-review ${short(runId)} ${status}: ${reason}`);+ return out;+}++// ---- continuous-excerpt analysis + reviewer call ---------------------------++/** Analyse the encoded excerpt end to end: A/V stream parity and footage freezes. */+async function analyzeContinuousExcerpt(excerptPath, spanSec, sections) {+ const [ffmpeg, ffprobe] = await Promise.all([findFfmpeg(), findFfprobe()]);+ if (!ffmpeg || !ffprobe) return { ok: false, error: 'ffmpeg/ffprobe not found' };+ const { stdout } = await execFileAsync(ffprobe, ['-v', 'error', '-show_entries', 'stream=codec_type,duration', '-of', 'csv=p=0', excerptPath],+ safeChildProcessOptions({ timeout: 15_000 }));+ const durations = parseStreamDurations(stdout);+ if (durations.video === null || durations.audio === null) return { ok: false, error: 'The draft is missing its video or audio stream' };+ const { stderr } = await execFileAsync(ffmpeg, ['-hide_banner', '-nostats', '-i', excerptPath, '-map', '0:v:0', '-vf', `freezedetect=n=-60dB:d=${FREEZE_MIN_SEC}`, '-f', 'null', '-'],+ safeChildProcessOptions({ timeout: 300_000, maxBuffer: 16 * 1024 * 1024 }));+ return {+ ok: true,+ spanSec,+ avDriftSec: Math.round((durations.audio - durations.video) * 1000) / 1000,+ freezes: unplannedFreezes(parseFreezeIntervals(stderr, spanSec), sections),+ };+}++async function callReviewer(run, prompt, screenshots) {+ const { resolveProviderAndModel, runPromptThroughProvider, assertVisionRunUsedImages } = await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel(run.reviewer);+ if (!provider) throw new Error('No AI provider is configured');+ if (provider.enabled === false) throw new Error(`Provider "${provider.name || provider.id}" is disabled`);+ const used = { providerId: provider.id, model: selectedModel || null };+ if (provider.type !== 'api') {+ if (!isVisionCapableCliProvider(provider)) throw new Error(`Provider "${provider.name || provider.id}" cannot read images`);+ const { describeImagesFromPaths } = await import('../visionCli.js');+ const result = await describeImagesFromPaths({ provider, imagePaths: screenshots, prompt, model: selectedModel, timeout: provider.timeout || REVIEW_TIMEOUT_MS });+ return { text: result.text, used };+ }+ const result = await runPromptThroughProvider({+ provider, model: selectedModel, prompt, screenshots, source: 'music-video-auto-review', timeout: provider.timeout || REVIEW_TIMEOUT_MS,+ });+ assertVisionRunUsedImages(result, provider);+ return { text: result.text, used: { ...used, model: result.model || used.model } };+}++/** Review one rendered draft. Never throws — a failed look is an inconclusive review. */+async function reviewDraft(project, run, excerpt) {+ const excerptPath = safeUnder(PATHS.videos, excerpt.filename || '');+ const spanSec = excerpt.endSec - excerpt.startSec;+ const sections = (excerpt.sections || []).map((s) => ({+ ...s, startSec: Math.max(0, s.startSec - excerpt.startSec), endSec: Math.min(spanSec, s.endSec - excerpt.startSec),+ }));+ if (!excerptPath || !existsSync(excerptPath)) {+ return gateAutoReview({ parsed: null, analysis: { ok: false, error: 'The draft file is missing' } });+ }+ const analysis = await analyzeContinuousExcerpt(excerptPath, spanSec, sections).catch((err) => ({ ok: false, error: err.message }));+ const attemptN = run.attempts.length;+ const stripNames = await extractEvaluationFrames(excerptPath, `mvar-${short(run.id)}-a${attemptN}`, STRIP_FRAMES).catch(() => []);+ const strip = stripNames.map((name) => join(PATHS.videoThumbnails, name)).filter((p) => existsSync(p));+ const sheet = excerpt.contactSheetFilename ? safeUnder(PATHS.videoThumbnails, excerpt.contactSheetFilename) : null;+ const hasSheet = !!sheet && existsSync(sheet);+ const screenshots = [...(hasSheet ? [sheet] : []), ...strip];+ const frameTimes = strip.map((_, i) => (strip.length > 1 ? (i * spanSec) / (strip.length - 1) : 0));+ const evidence = { boundaryFrames: hasSheet ? 1 : 0, continuousFrames: strip.length };++ let parsed = null;+ let reviewerError = null;+ let used = { providerId: run.reviewer.providerId, model: run.reviewer.model };+ if (screenshots.length) {+ const prompt = buildAutoReviewPrompt({ spanSec, sections, frameTimes, hasContactSheet: hasSheet, concept: project.concept });+ try {+ const reply = await callReviewer(run, prompt, screenshots);+ used = reply.used;+ parsed = parseAutoReviewResponse(reply.text);+ if (!parsed) reviewerError = 'The reviewer returned no usable verdict';+ } catch (err) {+ reviewerError = err.message;+ console.warn(`⚠️ Music Video auto-review ${short(run.id)} reviewer call failed: ${err.message}`);+ }+ } else {+ reviewerError = 'No frames could be extracted from the draft';+ }+ await Promise.all(strip.map((p) => unlink(p).catch(() => {})));+ const review = gateAutoReview({ parsed, analysis, evidence });+ return {+ ...review,+ reason: review.verdict === 'inconclusive' && reviewerError ? `${reviewerError} — watch this draft yourself` : review.reason,+ reviewer: used,+ };+}++// ---- the step loop ----------------------------------------------------------++async function takeSteps(projectId, runId) {+ for (let i = 0; i < MAX_STEPS_PER_ADVANCE; i += 1) {+ const project = await requireProject(projectId);+ const run = findRun(project, runId);+ const step = nextAutoReviewStep(project, run);++ if (step.type === 'idle' || step.type === 'wait') return { project, run, action: step };++ if (step.type === 'halt') {+ const out = await halt(projectId, runId, { status: step.status, reason: step.reason });+ return { ...out, action: { type: 'idle' } };+ }++ if (step.type === 'render') {+ // Draft renders are free; a refusal (another draft rendering, a shot+ // that doesn't cover its span…) pauses the run so the director can fix+ // it and resume, rather than failing the whole checkpoint.+ const render = await startExcerptRender(projectId, { startSec: run.startSec, endSec: run.endSec }).catch((err) => ({ error: err }));+ if (render.error) {+ const out = await halt(projectId, runId, { status: 'stopped', reason: `The draft could not render: ${render.error.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ await mutateProjectRecord(projectId, (current) => attachAttemptExcerpt(current, runId, render.excerptId));+ console.log(`🎬 Music Video auto-review ${short(runId)} attempt ${run.attempts.length}: rendering draft${step.retry ? ' (retry)' : ''}`);+ continue;+ }++ if (step.type === 'review') {+ const begun = await mutateProjectRecord(projectId, (current) => beginAttemptReview(current, runId));+ publish(projectId, begun.project, begun.run, { type: 'reviewing', excerptId: step.excerptId });+ const excerpt = projectExcerpts(project).find((e) => e.id === step.excerptId);+ const review = await reviewDraft(project, run, excerpt);+ const out = await mutateProjectRecord(projectId, (current) => recordAttemptReview(current, runId, review));+ const log = review.verdict === 'inconclusive' ? console.warn : console.log;+ log(`🔎 Music Video auto-review ${short(runId)} attempt ${run.attempts.length}: ${review.verdict} (${review.findings.length} finding${review.findings.length === 1 ? '' : 's'})`);+ if (out.run.status !== 'running') return { ...out, action: { type: 'idle' } };+ continue;+ }++ if (step.type === 'revise') {+ const opened = await mutateProjectRecord(projectId, (current) => {+ const started = startRevisionOnProject(current, step.excerptId);+ return { ...attachAttemptRevision(started.project, runId, started.revision.id), revision: started.revision };+ }).catch((err) => ({ error: err }));+ if (opened.error) {+ const out = await halt(projectId, runId, { status: 'needs-human', reason: `The findings could not be revised automatically: ${opened.error.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ console.log(`🎬 Music Video auto-review ${short(runId)} opened revision ${opened.revision.id.slice(4, 12)}`);+ continue;+ }++ if (step.type === 'resume-revision') {+ const { listJobs } = await import('../mediaJobQueue/index.js');+ const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];+ const revision = projectRevisions(project).find((r) => r.id === step.revisionId);+ const needed = revisionSectionStates(project, revision, jobs).filter((s) => s.state === 'needs-generation').length;+ // Spend check BEFORE anything is handed out: the enqueue guard refuses+ // each job past the limit too, but a run that can't afford the whole+ // revision stops here instead of generating half of it.+ if (needed > remainingGenerations(run)) {+ const out = await halt(projectId, runId, {+ status: 'limit-reached',+ reason: `The revision needs ${needed} generation${needed === 1 ? '' : 's'} but only ${remainingGenerations(run)} remain of the ${run.limits.maxGenerations}-generation spend limit`,+ });+ return { ...out, action: { type: 'idle' } };+ }+ const resumed = await resumeRevision(projectId, step.revisionId);+ if (resumed.render) continue;+ const fresh = await requireProject(projectId);+ const current = findRun(fresh, runId);+ if (resumed.needsGeneration.length) {+ return { project: fresh, run: current, action: { type: 'generate', revisionId: step.revisionId, sections: resumed.needsGeneration } };+ }+ return { project: fresh, run: current, action: { type: 'wait', on: 'generation', revisionId: step.revisionId } };+ }++ if (step.type === 'next-attempt') {+ await mutateProjectRecord(projectId, (current) => beginNextAttempt(current, runId, step.excerptId));+ continue;+ }+ throw new Error(`Unknown auto-review step ${step.type}`);+ }+ const project = await requireProject(projectId);+ return { project, run: findRun(project, runId), action: { type: 'wait', on: 'step-budget' } };+}++/**+ * Advance a run as far as it can go right now. Concurrent calls for one run+ * coalesce onto the in-flight advance, which then takes one more pass.+ * Returns `{ project, run, action }`.+ */+export function advanceAutoReview(projectId, runId) {+ const live = advancing.get(runId);+ if (live) {+ live.again = true;+ return live.promise;+ }+ const entry = { again: false, promise: null };+ entry.promise = (async () => {+ try {+ let result;+ do {+ entry.again = false;+ result = await takeSteps(projectId, runId);+ } while (entry.again);+ publish(projectId, result.project, result.run, result.action);+ return result;+ } finally {+ advancing.delete(runId);+ }+ })();+ advancing.set(runId, entry);+ return entry.promise;+}++// ---- director actions ----------------------------------------------------++// A review can take minutes, so the director's request returns as soon as the+// checkpoint is written; the advance continues in the background and reports+// over the `auto-review` event.+function advanceInBackground(projectId, runId) {+ advanceAutoReview(projectId, runId).catch(async (err) => {+ console.error(`❌ Music Video auto-review ${short(runId)} step failed: ${err.message}`);+ await halt(projectId, runId, { status: 'stopped', reason: `A step failed: ${err.message}`, error: err.message })+ .then((out) => publish(projectId, out.project, out.run, { type: 'idle' }))+ .catch(() => {});+ });+}++/** Start a run (explicit director request with limits). Returns `{ project, run }`. */+export async function startAutoReview(projectId, input) {+ const out = await mutateProjectRecord(projectId, (current) => startAutoReviewOnProject(current, input));+ console.log(`🎬 Music Video auto-review ${short(out.run.id)} started: [${out.run.startSec}, ${out.run.endSec}]s, ≤${out.run.limits.maxAttempts} reviews, ≤${out.run.limits.maxGenerations} generations`);+ advanceInBackground(projectId, out.run.id);+ return out;+}++/** Resume a stopped/limit-reached run (optionally raising its limits), or re-kick a running one. Returns `{ project, run }`. */+export async function resumeAutoReview(projectId, runId, { limits } = {}) {+ const out = await mutateProjectRecord(projectId, (current) => resumeAutoReviewOnProject(current, runId, { limits }));+ advanceInBackground(projectId, runId);+ return out;+}++/** Pause a run: nothing new is handed out; work already in flight lands on the checkpoint. */+export async function stopAutoReview(projectId, runId) {+ const out = await mutateProjectRecord(projectId, (current) => stopAutoReviewOnProject(current, runId));+ publish(projectId, out.project, out.run, { type: 'idle' });+ return out;+}++/** Cancel a run, and the revision it has open (which stops its generation jobs). */+export async function cancelAutoReview(projectId, runId) {+ const { revisionId } = await mutateProjectRecord(projectId, (current) => cancelAutoReviewOnProject(current, runId));+ if (revisionId) {+ await cancelRevision(projectId, revisionId).catch((err) => {+ console.error(`❌ Music Video auto-review ${short(runId)} could not cancel its revision: ${err.message}`);+ });+ }+ const project = await requireProject(projectId);+ const run = findRun(project, runId);+ publish(projectId, project, run, { type: 'idle' });+ return { project, run };+}++// ---- completion events of work a run put in flight ------------------------++function continueFromEvent(projectId, pickRun, label) {+ getProject(projectId)+ .then((project) => {+ const run = project ? pickRun(project) : null;+ return run ? advanceAutoReview(projectId, run.id) : null;+ })+ .catch((err) => console.error(`❌ Music Video auto-review could not continue after ${label}: ${err.message}`));+}++musicVideoEvents.on('excerpt-render', ({ projectId, excerptId } = {}) => {+ if (projectId && excerptId) continueFromEvent(projectId, (project) => runAwaitingExcerpt(project, excerptId), 'a draft render');+});++const onSceneTake = ({ projectId, sceneId } = {}) => {+ if (!projectId || !sceneId) return;+ continueFromEvent(projectId, (project) => {+ const revisions = projectRevisions(project);+ return projectAutoReviews(project).find((run) => {+ if (run.status !== 'running') return false;+ const { revisionId } = run.attempts[run.attempts.length - 1];+ const revision = revisions.find((r) => r.id === revisionId && r.status === 'open');+ return !!revision?.sections?.some((s) => s.sceneId === sceneId && s.verdict === 'rejected');+ }) || null;+ }, 'a revised take landed');+};+musicVideoEvents.on('scene-image', onSceneTake);+musicVideoEvents.on('scene-video', onSceneTake);diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 590c96e2f2..1366acbecc 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -1,7 +1,7 @@import { EventEmitter } from 'events';// Event bus for Music Video async side effects that need to reach the client-// after the originating HTTP request has returned. It carries two events:+// after the originating HTTP request has returned. It carries://// 'scene-image' → { projectId, sceneId, referenceImageId, takes, takeId }// 'scene-video' → { projectId, sceneId, videoHistoryId, takes, takeId }@@ -16,4 +16,13 @@ import { EventEmitter } from 'events';// synchronous external-SD-API lane (which returns the image filename inline and// lets the client add it as a take through the takes route; video renders// always ride the queue, so the clip attach is hook-only).+//+// #8988 adds two more:+// 'excerpt-render' → { projectId, excerptId, status } — a draft excerpt+// render reached a terminal state and its record write landed; an opt-in+// auto-review run waiting on that draft continues from it (server-only).+// 'auto-review' → { projectId, runId, run, action, project } — an+// auto-review run advanced; socket.js bridges it to+// `music-video:auto-review` so an open board can submit the sections the+// run hands out for generation and show the run's progress.export const musicVideoEvents = new EventEmitter();diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex 6f6e9882d1..3fa7077fda 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -35,6 +35,7 @@ import { renderTypographyOverlays, removeCompositionScratch } from './compositioimport { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';import { markRevisionRendering, settleRevisionRender } from './revision.js';import { ensureInstanceId } from '../instanceIdentity.js';+import { musicVideoEvents } from './events.js';const jobs = new Map();const projectExcerptRenders = new Map();@@ -88,7 +89,7 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { revilet handedOff = false;try {- const { ffmpeg, audioPath, composed, clips, audioDurationSec } = await planMusicVideoRender(project);+ const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);@@ -163,6 +164,8 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { reviconsole.warn(`⚠️ Music-video excerpt render [${jobId.slice(4, 12)}] could not remove its overlay scratch: ${err.message}`);});closeJobAfterDelay(jobs, jobId);+ // #8988: an auto-review run waiting on this draft continues from here.+ if (persisted) musicVideoEvents.emit('excerpt-render', { projectId, excerptId, status: patch.status });return persisted;};@@ -267,7 +270,7 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { revi};if (!composition) {- const { args } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, excerpt: { startSec, endSec: endClamped } });+ const { args } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, excerpt: { startSec, endSec: endClamped }, soundBed });startEncode(args);return { jobId, excerptId };}@@ -286,7 +289,7 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { revi}).then((overlays) => {signal.throwIfAborted();job.overlayAbort = null;- const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, excerpt: { startSec, endSec: endClamped } });+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, excerpt: { startSec, endSec: endClamped }, soundBed });startEncode(layered.args, 0.5);}).catch(async (err) => {const canceled = signal.aborted;diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex acb679cd2d..161a680ce7 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -33,6 +33,7 @@ import { isPerformanceScene, planShotSplit, shotSplitLimit } from '../../lib/musimport { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';import { ensureSceneTakes, TAKE_SLOT } from './takes.js';import { normalizeComposition, invalidateCompositionTiming } from './composition.js';+import { normalizeSoundBed } from './soundBed.js';import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';@@ -241,6 +242,8 @@ export function applyProjectPatch(project, patch) {...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),// #8984 — the composition manifest is replaced whole; null clears it....('composition' in patch ? { composition: normalizeComposition(patch.composition) } : {}),+ // #8988 — an explicitly chosen sound-design bed; null clears it.+ ...('soundBed' in patch ? { soundBed: normalizeSoundBed(patch.soundBed) } : {}),};const conceptMergedPatch = ('concept' in timedPatch && timedPatch.concept && project.concept)? { ...timedPatch, concept: { ...project.concept, ...timedPatch.concept } }diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex ddc9db25e4..c639cda364 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -42,6 +42,8 @@ import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScrimport { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';import { findStalePerformanceTakes } from './performanceShot.js';import { ensureInstanceId } from '../instanceIdentity.js';+import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';+import { projectSoundBed } from './soundBed.js';// Per-project render mutex (keyed by projectId so two projects can render in// parallel; same-project re-entry returns 409 with the live jobId for re-attach).@@ -159,6 +161,20 @@ export async function resolveMasterAudioPath(project) {return safe;}+// #8988: resolve the project's explicitly chosen sound-design bed (a+// music-library track) to a verified path under data/music/, or null when the+// song is the sole audio master (the default).+export async function resolveSoundBed(project) {+ const bed = projectSoundBed(project);+ if (!bed) return null;+ const track = await getTrack(bed.trackId);+ const safe = track?.audioFilename ? safeUnder(PATHS.music, track.audioFilename) : null;+ if (!safe || !existsSync(safe)) {+ throw new ServerError('The sound-design bed track is missing — choose another bed or clear it', { status: 404, code: 'SOUND_BED_MISSING' });+ }+ return { path: safe, volume: bed.volume };+}+// A still/card section has no source clip to measure, so its authored span IS// its length. Null when the scene is not timed.const authoredSpan = (scene) => (sceneHasAuthoredSpan(scene) ? round3(scene.endSec - scene.startSec) : null);@@ -388,7 +404,7 @@ function sectionChain(c, input, { canonW, canonH, fps, frames, frameGrid }) {// overlap the window, clipped to it and re-based to the excerpt's own timeline// (0 = `startSec`) so a contact sheet built from the excerpt file can sample// cut boundaries directly. `totalDuration` becomes the excerpt's own length.-export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false, excerpt = null } = {}) {+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false, excerpt = null, soundBed = null } = {}) {if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');const frameGrid = gridOption || clips.some((c) => c.layer);// Stills and cards have no dimensions of their own: the first footage clip@@ -450,7 +466,24 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDconst fullDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;let videoMap = '[outv]';+ // The song is the sole audio master unless a sound-design bed was explicitly+ // chosen (#8988) — then the bed is mixed UNDER it through the shared bed+ // chain, trimmed to the song so it can never extend or replace the master.+ let audioSrc = `[${audioIdx}:a]`;let audioMap = `${audioIdx}:a`;+ if (soundBed?.path) {+ filters.push(`[${audioIdx}:a]${AUDIO_NORM}[master]`);+ const bed = buildAudioBedMix({+ beds: [{ assetPath: soundBed.path, offsetSec: 0, durationSec: fullDuration, volume: soundBed.volume }],+ firstInputIdx: audioIdx + 1 + overlays.length,+ mainLabel: '[master]',+ outLabel: '[mixa]',+ });+ inputs.push(...bed.inputs);+ filters.push(...bed.filters);+ audioSrc = '[mixa]';+ audioMap = '[mixa]';+ }let totalDuration = fullDuration;let sections = plan.map(({ c, startSec, endSec }) => ({ sceneId: c.sceneId, layer: c.layer || 'footage', startSec, endSec }));@@ -458,7 +491,7 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDconst excerptStart = Math.max(0, Math.min(excerpt.startSec, fullDuration));const excerptEnd = Math.max(excerptStart, Math.min(excerpt.endSec, fullDuration));filters.push(`[outv]trim=start=${excerptStart}:end=${excerptEnd},setpts=PTS-STARTPTS[outvx]`);- filters.push(`[${audioIdx}:a]atrim=start=${excerptStart}:end=${excerptEnd},asetpts=PTS-STARTPTS[outax]`);+ filters.push(`${audioSrc}atrim=start=${excerptStart}:end=${excerptEnd},asetpts=PTS-STARTPTS[outax]`);videoMap = '[outvx]';audioMap = '[outax]';totalDuration = excerptEnd - excerptStart;@@ -553,7 +586,8 @@ export async function planMusicVideoRender(project) {{ status: 422, code: 'INSUFFICIENT_CLIP_COVERAGE', context: { shortfalls, resolutions: COVERAGE_RESOLUTIONS } },);}- return { ffmpeg, audioPath, composed, clips, audioDurationSec };+ const soundBed = await resolveSoundBed(project);+ return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };}export async function renderMusicVideo(projectId) {@@ -573,7 +607,7 @@ export async function renderMusicVideo(projectId) {let handedOff = false;try {- const { ffmpeg, audioPath, composed, clips, audioDurationSec } = await planMusicVideoRender(project);+ const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);@@ -582,7 +616,7 @@ export async function renderMusicVideo(projectId) {const jobId = randomUUID();const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;const outputPath = join(PATHS.videos, filename);- const { args, totalDuration, canonW, canonH, fps, sections } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed });+ const { args, totalDuration, canonW, canonH, fps, sections } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, soundBed });// #8984: a composed project lays its timed text cues over the cut, and a// title card's text (#8985) joins them over its own section. No renderable// cue (plain mode, or nothing timed) skips the overlay capture entirely.@@ -764,7 +798,7 @@ export async function renderMusicVideo(projectId) {signal.throwIfAborted();// Capture is over: from here a cancel kills the encode (job.process).job.overlayAbort = null;- const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true });+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, soundBed });startEncode(layered.args, 0.5);}).catch(async (err) => {const canceled = signal.aborted;diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex a1375e5fe4..40de669b33 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -21,6 +21,7 @@ import {excerptBoundaryTimes,resolveSceneClips,resolveMasterAudioPath,+ resolveSoundBed,renderMusicVideo,} from './render.js';import { findFfmpeg, probeVideoGeometry } from '../../lib/ffmpeg.js';@@ -94,6 +95,45 @@ describe('buildMusicVideoFfmpegArgs', () => {});});+// #8988 — an optional, explicitly chosen sound-design bed mixed UNDER the song.+describe('sound-design bed (#8988)', () => {+ const clips = [clip({ videoPath: '/v/a.mp4' }), clip({ videoPath: '/v/b.mp4' })];+ const filterOf = (args) => args[args.indexOf('-filter_complex') + 1];+ const mapsOf = (args) => args.reduce((acc, a, i) => (a === '-map' ? [...acc, args[i + 1]] : acc), []);++ it('with no bed chosen, the output audio is exactly the master track — no mix stage at all', () => {+ const plain = buildMusicVideoFfmpegArgs(clips, '/music/song.wav', '/out.mp4', { audioDurationSec: 30 });+ const noBed = buildMusicVideoFfmpegArgs(clips, '/music/song.wav', '/out.mp4', { audioDurationSec: 30, soundBed: null });+ expect(noBed.args).toEqual(plain.args);+ expect(filterOf(noBed.args)).not.toMatch(/amix|\[master\]/);+ expect(mapsOf(noBed.args)).toEqual(['[outv]', '2:a']);+ });++ it('mixes a chosen bed under the master at its own level, trimmed to the song, after any overlay inputs', () => {+ const overlays = [{ startSec: 1, path: '/tmp/cue-0.mov' }];+ const { args } = buildMusicVideoFfmpegArgs(clips, '/music/song.wav', '/out.mp4', {+ audioDurationSec: 30, overlays, soundBed: { path: '/music/rain.wav', volume: 0.3 }, excerpt: { startSec: 1, endSec: 3 },+ });+ const fc = filterOf(args);+ // inputs: 0,1 clips · 2 song · 3 overlay · 4 bed+ const inputs = args.reduce((acc, a, i) => (a === '-i' ? [...acc, args[i + 1]] : acc), []);+ expect(inputs).toEqual(['/v/a.mp4', '/v/b.mp4', '/music/song.wav', '/tmp/cue-0.mov', '/music/rain.wav']);+ expect(fc).toContain('[2:a]aresample=48000');+ expect(fc).toMatch(/\[4:a\][^;]*atrim=start=0:end=4,[^;]*volume=0\.3\[bed0\]/);+ // The song keeps its length and level: duration=first, normalize=0.+ expect(fc).toContain('[master][bed0]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[mixa]');+ // A draft excerpt windows the MIXED audio, not the bare song.+ expect(fc).toContain('[mixa]atrim=start=1:end=3,asetpts=PTS-STARTPTS[outax]');+ expect(mapsOf(args)).toEqual(['[outvx]', '[outax]']);+ });++ it('refuses a render whose chosen bed track no longer resolves', async () => {+ getTrack.mockResolvedValue(null);+ await expect(resolveSoundBed({ soundBed: { trackId: 'trk-gone' } })).rejects.toMatchObject({ code: 'SOUND_BED_MISSING' });+ await expect(resolveSoundBed({})).resolves.toBeNull();+ });+});+describe('excerptBoundaryTimes (#8986)', () => {// No encoded file has a frame timestamped at its own total duration, so the// trailing boundary is always guarded back to `span - 1/fps` (default 24fps)diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.jsindex a3ab1fe352..981f63bc46 100644--- a/server/services/musicVideo/revision.js+++ b/server/services/musicVideo/revision.js@@ -335,8 +335,8 @@ export function cancelRevisionOnProject(project, revisionId, now = new Date().to* project itself is gone (the route's own lookup reports that separately).*/export function assertRevisionOpenForGeneration(project, revisionId) {- if (!project) return;- resumableRevision(project, revisionId);+ if (!project) return null;+ return resumableRevision(project, revisionId);}/**diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.jsindex ebbe7ebb63..55675069d5 100644--- a/server/services/musicVideo/revisionService.js+++ b/server/services/musicVideo/revisionService.js@@ -19,6 +19,7 @@* against the freshest record under the backend's write serialization.*/+import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';import {@@ -31,6 +32,7 @@ import {revisionSectionStates,startRevisionOnProject,} from './revision.js';+import { chargeAutoReviewGeneration, runOwningRevision } from './autoReview.js';/** Open a revision from a reviewed excerpt. Returns `{ project, revision, skippedSceneIds }`. */export async function startRevision(projectId, excerptId, input = {}) {@@ -44,11 +46,30 @@ export async function startRevision(projectId, excerptId, input = {}) {* revision's cancel/kickoff race is closed server-side rather than raced.* Throws 404/409 (ServerError, code REVISION_CLOSED); a no-op when the tag* carries no revisionId.+ *+ * #8988: this is also the spend choke point of an opt-in auto-review run. A+ * job for a revision a RUNNING run opened is charged against the run's+ * `maxGenerations` in one serialized write, and refused (409+ * AUTO_REVIEW_SPEND_LIMIT) once the limit is spent — before it is queued. A+ * second job for a section whose job for this revision is still queued or+ * running (a double submit) is refused too, so it is never paid for twice.*/-export async function assertRevisionOpen(projectId, revisionId) {+export async function assertRevisionOpen(projectId, revisionId, { sceneId = null, kind = null } = {}) {if (!revisionId) return;const project = await getProject(projectId);assertRevisionOpenForGeneration(project, revisionId);+ if (!project || !runOwningRevision(project, revisionId)) return;+ const { listJobs } = await import('../mediaJobQueue/index.js');+ const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];+ await mutateProjectRecord(projectId, (current) => {+ const revision = assertRevisionOpenForGeneration(current, revisionId);+ const inFlight = sceneId && revisionGenerationJobs(current, revision, jobs)+ .some((job) => job.params?.musicVideo?.sceneId === sceneId && (!kind || job.kind === kind));+ if (inFlight) {+ throw new ServerError('This section is already generating for the auto-review run', { status: 409, code: 'AUTO_REVIEW_SECTION_IN_FLIGHT', context: { sceneId } });+ }+ return chargeAutoReviewGeneration(current, revisionId);+ });}/**diff --git a/server/services/musicVideo/soundBed.js b/server/services/musicVideo/soundBed.jsnew file mode 100644index 0000000000..123ab7b886--- /dev/null+++ b/server/services/musicVideo/soundBed.js@@ -0,0 +1,38 @@+/**+ * Music Video — optional sound-design bed (#8988, part of #8966).+ *+ * The song is the video's sole audio master by default. A director may+ * EXPLICITLY choose one music-library track as a sound-design bed (ambience,+ * risers, texture); the render mixes it UNDER the master through the shared+ * audio-bed chain (`videoTimeline/audioBedMix.js`, the same one the video+ * timeline render uses). The master keeps its full level and its length —+ * the bed is trimmed to the song and can never extend or replace it. With no+ * bed chosen the render maps the master track as the only audio, unchanged.+ *+ * Peer sync: `soundBed` is an additive field on the whole-record LWW project+ * body. An older peer stores it verbatim and renders without it, which is the+ * pre-#8988 behaviour, so no `musicVideoProjects` schema bump is needed.+ */++import { isNonBlankStr } from '../../lib/textUtils.js';++export const DEFAULT_SOUND_BED_VOLUME = 0.3;+export const MIN_SOUND_BED_VOLUME = 0.05;+export const MAX_SOUND_BED_VOLUME = 1;++const clampVolume = (v) => {+ if (typeof v !== 'number' || !Number.isFinite(v)) return DEFAULT_SOUND_BED_VOLUME;+ return Math.min(MAX_SOUND_BED_VOLUME, Math.max(MIN_SOUND_BED_VOLUME, Math.round(v * 100) / 100));+};++/**+ * Normalize a `soundBed` patch value. `null` (or anything without a track)+ * clears the bed — the song alone is the soundtrack again.+ */+export function normalizeSoundBed(input) {+ if (!input || typeof input !== 'object' || !isNonBlankStr(input.trackId)) return null;+ return { trackId: input.trackId.trim(), volume: clampVolume(input.volume) };+}++/** The project's chosen bed, or null when the song is the sole audio. */+export const projectSoundBed = (project) => normalizeSoundBed(project?.soundBed);diff --git a/server/services/socket.js b/server/services/socket.jsindex 9e5f04aa7c..4c89dc4b45 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -434,6 +434,11 @@ function setupMusicVideoEventForwarding() {musicVideoEvents.on('scene-video', (data) => {if (ioInstance) ioInstance.emit('music-video:scene-video', data);});+ // An opt-in auto-review run advanced (#8988) — the board submits any+ // sections it hands out and shows the run's checkpoint without a refetch.+ musicVideoEvents.on('auto-review', (data) => {+ if (ioInstance) ioInstance.emit('music-video:auto-review', data);+ });}let aiStatusForwardingSetup = false;diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex 8bc366c861..ca9c3c5a84 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -202,7 +202,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {// import since only this rare path needs the revision service's closure.if (body.musicVideo?.revisionId) {const { assertRevisionOpen } = await import('../musicVideo/revisionService.js');- await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId);+ await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });}return enqueueJob({ kind: 'video', params });},diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex cea166c202..235500a880 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -238,7 +238,7 @@ describe('submitVideoGenJob', () => {mocks.prepareVideoGenParams.mockResolvedValue(prepared);await expect(submitVideoGenJob({ prompt: 'singer', backend: 'fal', musicVideo: tagged }, {})).rejects.toBe(closed);- expect(mocks.assertRevisionOpen).toHaveBeenCalledWith('mv-1', 'mvr-1');+ expect(mocks.assertRevisionOpen).toHaveBeenCalledWith('mv-1', 'mvr-1', { sceneId: musicVideo.sceneId, kind: 'video' });// The check runs immediately before enqueueJob — after staging, not before// it — so the race window against a concurrent cancel is as small as this// request can make it; a refusal there still rolls back what was staged.diff --git a/server/services/videoTimeline/audioBedMix.js b/server/services/videoTimeline/audioBedMix.jsnew file mode 100644index 0000000000..487f56870f--- /dev/null+++ b/server/services/videoTimeline/audioBedMix.js@@ -0,0 +1,58 @@+/**+ * The audio-bed mix chain shared by the video timeline render (`local.js`)+ * and the Music Video render's optional sound-design bed (#8988).+ *+ * Each bed is trimmed from its own offset, faded on its own clock, then+ * delayed to its project-time start and mixed under the main audio.+ * `amix … duration=first` keeps the main audio's length (a bed can never+ * extend the output), and `normalize=0` keeps adding a bed from silently+ * attenuating everything already in the mix.+ *+ * Pure: returns the ffmpeg `-i` args for the beds and the filter strings, so+ * each caller owns its own input numbering and graph labels.+ */++/** ffmpeg-safe number formatting (six decimals, no exponent). */+export const fmtSec = (n) => String(Math.round(Number(n) * 1e6) / 1e6);++// Every audio branch entering a mix/concat must present identical link parameters.+export const AUDIO_NORM = 'aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo';++/**+ * @param {object} opts+ * @param {Array<{assetPath:string, offsetSec:number, durationSec:number, startSec?:number, volume?:number, fadeInSec?:number, fadeOutSec?:number}>} opts.beds+ * @param {number} opts.firstInputIdx ffmpeg input index the first bed will take+ * @param {string} opts.mainLabel the main audio's filter label, e.g. `[ca]`+ * @param {string} opts.outLabel the mixed output label, e.g. `[outa]`+ * @returns {{ inputs: string[], filters: string[] }}+ */+export function buildAudioBedMix({ beds, firstInputIdx, mainLabel, outLabel }) {+ const inputs = [];+ const filters = [];+ const bedLabels = [];+ (beds || []).forEach((tr, j) => {+ inputs.push('-i', tr.assetPath);+ const parts = [+ 'aresample=48000',+ 'aformat=sample_fmts=fltp:channel_layouts=stereo',+ `atrim=start=${fmtSec(tr.offsetSec)}:end=${fmtSec(tr.offsetSec + tr.durationSec)}`,+ 'asetpts=PTS-STARTPTS',+ ];+ const volume = tr.volume == null ? 1 : tr.volume;+ if (volume !== 1) parts.push(`volume=${fmtSec(volume)}`);+ if (tr.fadeInSec > 0) parts.push(`afade=t=in:st=0:d=${fmtSec(tr.fadeInSec)}`);+ if (tr.fadeOutSec > 0) {+ parts.push(`afade=t=out:st=${fmtSec(Math.max(0, tr.durationSec - tr.fadeOutSec))}:d=${fmtSec(tr.fadeOutSec)}`);+ }+ if (tr.startSec > 0) {+ const ms = Math.round(tr.startSec * 1000);+ parts.push(`adelay=${ms}|${ms}`);+ }+ filters.push(`[${firstInputIdx + j}:a]${parts.join(',')}[bed${j}]`);+ bedLabels.push(`[bed${j}]`);+ });+ if (bedLabels.length > 0) {+ filters.push(`${mainLabel}${bedLabels.join('')}amix=inputs=${bedLabels.length + 1}:duration=first:dropout_transition=0:normalize=0${outLabel}`);+ }+ return { inputs, filters };+}diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex f8b746913b..6349fd9293 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -43,6 +43,7 @@ import {resolveAsset,fitFades,} from './segments.js';+import { AUDIO_NORM, buildAudioBedMix, fmtSec } from './audioBedMix.js';const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');@@ -54,8 +55,6 @@ const DEFAULT_CANVAS = { width: 1280, height: 720, fps: 24 };// Floor for a probe-clamped audio slice — atrim with start === end produces// an empty stream that amix rejects.const MIN_MEDIA_SEC = 0.05;-// Every audio branch entering concat must present identical link parameters.-const AUDIO_NORM = 'aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo';// Per-project render mutex map. Keyed by projectId so two different projects// can render in parallel; same project re-render returns 409 with the@@ -420,7 +419,7 @@ export async function resolveTimeline(rawProject) {// leaks float noise (`2.9000000000000004`) into the graph string, while// toFixed would pad clean integers to `4.000`. Round to microseconds, then// stringify.-const fmt = (n) => String(Math.round(Number(n) * 1e6) / 1e6);+const fmt = fmtSec;const fadeChain = (prefix, { fadeInSec = 0, fadeOutSec = 0 }, duration, lead = []) => {const parts = [...lead];@@ -552,36 +551,12 @@ export function buildFfmpegArgs(timeline, outputPath, { colorTagFilter = null }overlayIn = out;});- // Audio bed. Each track is trimmed from its own offset, faded on its own- // clock, then delayed to its project-time start before mixing under the- // concatenated lane audio. normalize=0 keeps adding a second bed from- // silently attenuating everything already in the mix.+ // Audio bed — the mix chain lives in audioBedMix.js, shared with the Music+ // Video render's optional sound-design bed (#8988).if (audioTracks.length > 0) {- const bedLabels = [];- audioTracks.forEach((tr, j) => {- const aIdx = inputIdx++;- inputs.push('-i', tr.assetPath);- const parts = [- 'aresample=48000',- 'aformat=sample_fmts=fltp:channel_layouts=stereo',- `atrim=start=${fmt(tr.offsetSec)}:end=${fmt(tr.offsetSec + tr.durationSec)}`,- 'asetpts=PTS-STARTPTS',- ];- if (tr.volume !== 1) parts.push(`volume=${fmt(tr.volume)}`);- if (tr.fadeInSec > 0) parts.push(`afade=t=in:st=0:d=${fmt(tr.fadeInSec)}`);- if (tr.fadeOutSec > 0) {- parts.push(`afade=t=out:st=${fmt(Math.max(0, tr.durationSec - tr.fadeOutSec))}:d=${fmt(tr.fadeOutSec)}`);- }- if (tr.startSec > 0) {- const ms = Math.round(tr.startSec * 1000);- parts.push(`adelay=${ms}|${ms}`);- }- filters.push(`[${aIdx}:a]${parts.join(',')}[bed${j}]`);- bedLabels.push(`[bed${j}]`);- });- filters.push(- `[ca]${bedLabels.join('')}amix=inputs=${bedLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[outa]`- );+ const bed = buildAudioBedMix({ beds: audioTracks, firstInputIdx: inputIdx, mainLabel: '[ca]', outLabel: '[outa]' });+ inputs.push(...bed.inputs);+ filters.push(...bed.filters);}if (tag) filters.push(`[vpre]${tag}[outv]`);