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: execute selective code-first music video production (#9301)
[._.]/ Adam Eivyc3d33a269da6
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsxindex ee15fd59ed..fc1ad1c7b7 100644--- a/client/src/components/musicVideo/AutoReviewPanel.jsx+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx@@ -151,6 +151,7 @@ export default function AutoReviewPanel({ project, startSec, endSec, rangeValid,</div></div>)}+ {run?.documentRevisions && <p className="text-port-text-muted">Code-first review revises failed document sections through the production authoring budget. Selected assets and the generated-video allowance stay fixed; changing the medium requires your plan edit.</p>}{run && (<div className="space-y-1.5"><div className="flex flex-wrap items-center justify-between gap-2">diff --git a/client/src/components/musicVideo/AutomationBriefFields.jsx b/client/src/components/musicVideo/AutomationBriefFields.jsxindex d2bc7e9bb6..a9bee95423 100644--- a/client/src/components/musicVideo/AutomationBriefFields.jsx+++ b/client/src/components/musicVideo/AutomationBriefFields.jsx@@ -43,7 +43,7 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {</div>))}</div>- <p className="text-xs text-port-text-muted mt-1">Analyze & plan uses the guidance today. The tool list and budget are saved now and will limit the automated generation run.</p>+ <p className="text-xs text-port-text-muted mt-1">Analyze & plan uses this guidance. Start production selects its own explicit provider pool and limits; the brief does not submit media jobs.</p></fieldset><div><label htmlFor={`${idPrefix}-guidance`} className="block text-xs text-port-text-muted mb-1">Guidance</label>@@ -69,7 +69,7 @@ export default function AutomationBriefFields({ idPrefix, draft, onChange }) {<option value="review">Stop for my review</option><option value="auto">Auto-approve</option></select>- <p className="text-[11px] text-port-text-muted mt-1">Before planning, autopilot builds a cast & sets sheet for your feedback.</p>+ <p className="text-[11px] text-port-text-muted mt-1">Footage-led planning builds a cast & sets sheet for your feedback. Code-first plans skip image batches unless a selected performance shot needs references.</p></div><div><label htmlFor={`${idPrefix}-budget`} className="block text-xs text-port-text-muted mb-1">Budget cap (USD)</label>diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxindex 9d0dce9c1b..24a29a39f2 100644--- a/client/src/components/musicVideo/AutopilotPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -36,7 +36,9 @@ const routeLabel = (route) => `${toolLabel.get(`${route.kind}:${route.mode}`) ||const initialPool = (project) => {const fromBrief = (project?.automation?.tools || []).filter((id) => POOL_TOOL_IDS.has(id));- return fromBrief.length ? fromBrief : DEFAULT_AUTOMATION_TOOLS.filter((id) => POOL_TOOL_IDS.has(id));+ const assets = codeFirstProductionAssets(project);+ const choices = fromBrief.length ? fromBrief : DEFAULT_AUTOMATION_TOOLS.filter((id) => POOL_TOOL_IDS.has(id));+ return assets ? choices.filter((id) => assets.requiredRoutes[id.split(':')[0]]) : choices;};function StepRow({ step }) {@@ -69,6 +71,12 @@ function RunView({ run, production, codeFirst }) {</span></div>{run.directive && <p className="text-port-text-muted break-words">Directive: {run.directive}</p>}+ {run.authoring && <p className="text-port-text-muted">Authoring: {run.authoring.providerId} · {run.authoring.model} · {run.authoring.costUsd == null ? 'unknown dollar cost (generation count still bounded)' : 'no per-call dollar charge; local compute or quota may apply'}</p>}+ {run.authoring && <p className="text-port-text-muted">{['author', 'frame', 'clip'].map((kind) => {+ const used = steps.filter((step) => step.kind === kind && step.status !== 'refused');+ const cost = used.reduce((total, step) => total + (step.costUsd || 0), 0);+ return `${kind === 'author' ? 'Code authoring' : kind === 'frame' ? 'Images' : 'Video'}: ${formatUsd(cost)} known${used.some((step) => step.costUsd == null) ? ' + unpriced calls' : ''}`;+ }).join(' · ')}. Reviewer calls use the separate review limit and may also cost money.</p>}<p className="text-port-text-muted">Allowed: {(run.pool || []).map(routeLabel).join(', ')}</p>{hint && <p className="text-port-warning break-words">{hint}</p>}{run.error && <p role="status" className="text-port-error break-words">{run.error}</p>}@@ -85,7 +93,7 @@ function RunView({ run, production, codeFirst }) {<Pause size={12} /> Stop</button>)}- {live && !codeFirst && (run.status !== 'running' || run.interrupted) && (+ {live && (!codeFirst || run.authoring) && (run.status !== 'running' || run.interrupted) && (<button type="button" disabled={production.busy}onClick={() => production.resume(run.id, needsReplan ? { acceptBasis: true } : {})}className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-2 min-h-[44px] sm:min-h-0 sm:px-2 sm:py-1 disabled:opacity-50">@@ -104,6 +112,8 @@ function RunView({ run, production, codeFirst }) {}function StartForm({ project, production }) {+ const assets = codeFirstProductionAssets(project);+ const author = useProviderModels({ allowDefault: false, silent: true });const [pool, setPool] = useState(() => initialPool(project));const [directive, setDirective] = useState('');const [maxGenerations, setMaxGenerations] = useState(12);@@ -117,7 +127,8 @@ function StartForm({ project, production }) {const capValue = spendCap === '' ? null : Number(spendCap);const hasImage = pool.some((id) => id.startsWith('image:'));const hasVideo = pool.some((id) => id.startsWith('video:'));- const valid = hasImage && hasVideo+ const routesValid = assets ? (!assets.requiredRoutes.image || hasImage) && (!assets.requiredRoutes.video || hasVideo) : hasImage && hasVideo;+ const valid = routesValid && (!assets || (project.scenes?.length > 0 && assets.conflicts.length === 0 && author.selectedProviderId && author.selectedModel))&& Number.isInteger(maxGenerations) && maxGenerations >= 1 && maxGenerations <= 500&& Number.isInteger(maxReviewAttempts) && maxReviewAttempts >= 1 && maxReviewAttempts <= 10&& (capValue == null || (Number.isFinite(capValue) && capValue >= 0));@@ -129,6 +140,7 @@ function StartForm({ project, production }) {const [kind, mode] = t.id.split(':');return { kind, mode };}),+ ...(assets ? { authoring: { providerId: author.selectedProviderId, model: author.selectedModel } } : {}),limits: { maxGenerations, maxReviewAttempts, ...(capValue != null ? { spendCapUsd: capValue } : {}) },...(selectedProviderId ? { providerId: selectedProviderId } : {}),...(selectedModel ? { model: selectedModel } : {}),@@ -137,7 +149,7 @@ function StartForm({ project, production }) {return (<div className="space-y-2"><p className="text-port-text-muted">- Plans the board, generates the missing frames and clips, renders and reviews the draft, and revises failed sections — on the server, so you can close this tab.+ {assets ? 'Prepares only the approved selected assets, authors the document, reviews motion and audio in a continuous excerpt, revises failed code sections, then renders the chosen document.' : 'Plans the board, generates the missing frames and clips, renders and reviews the draft, and revises failed sections — on the server, so you can close this tab.'}Only the routes you allow are ever used, and it never exceeds the limits below. fal.ai video is charged each take's estimated list price (its model, length and resolution); other metered routes have no known price, so a dollar cap refuses them.</p><fieldset className="min-w-0" aria-labelledby={idFor('pool-label')}>@@ -154,7 +166,7 @@ function StartForm({ project, production }) {/>))}</div>- {!(hasImage && hasVideo) && <p className="text-port-warning mt-1">Allow at least one image and one video route.</p>}+ {!routesValid && <p className="text-port-warning mt-1">{assets ? 'Allow routes only for the still/video jobs required by the approved plan.' : 'Allow at least one image and one video route.'}</p>}</fieldset><div><label htmlFor={idFor('directive')} className="block text-[10px] text-port-text-muted">Production directive</label>@@ -178,6 +190,19 @@ function StartForm({ project, production }) {<input id={idFor('cap')} type="number" min={0} step={1} inputMode="decimal" value={spendCap} disabled={production.busy}placeholder="No cap" onChange={(e) => setSpendCap(e.target.value)} className={inputCls} /></div>+ {assets && <ProviderModelSelector+ providers={author.providers}+ selectedProviderId={author.selectedProviderId}+ selectedModel={author.selectedModel}+ availableModels={author.availableModels}+ onProviderChange={author.setSelectedProviderId}+ onModelChange={author.setSelectedModel}+ label="Code authoring"+ disabled={production.busy}+ modelDisabled={author.availableModels.length === 0}+ compact+ />}+ {assets && <p className="text-port-text-muted">Authoring calls consume the generation limit. Unknown authoring prices require no dollar cap; a free/local authoring provider can use a cap. Reviews have a separate call limit.</p>}{providers.length > 0 && (<ProviderModelSelectorproviders={providers}@@ -313,11 +338,10 @@ function ProductionSection({ project, production }) {{assets.conflicts.length > 0 && <ul className="list-disc pl-4 text-port-warning">{assets.conflicts.map((conflict, index) => <li key={`${index}-${conflict}`}>{conflict}</li>)}</ul>}- <p className="text-port-text-muted">Code authoring, still jobs, and video jobs use separate providers and costs when autonomous dispatch is available. This preflight does not submit jobs.</p>+ <p className="text-port-text-muted">Code authoring, still jobs, and video jobs use separate providers and costs. Starting production uses only this approved asset plan.</p></div>- <p className="text-port-warning">Autonomous code-first production is waiting for document authoring and review checkpoints. Use the mixed-media document controls for the approved plan.</p></>}- {!active && !codeFirst && <StartForm key={run?.id || 'new'} project={project} production={production} />}+ {!active && <StartForm key={run?.id || 'new'} project={project} production={production} />}</div>);}diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxindex 37981f05dc..6ba3169e69 100644--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -24,7 +24,10 @@ vi.mock('../../services/apiMusicVideo.js', () => ({}));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));vi.mock('../../hooks/useProviderModels.js', () => ({- default: () => ({+ default: (options) => options.allowDefault === false ? {+ providers: [{ id: 'local-fixture', name: 'Local fixture', models: ['fixture-model'] }], selectedProviderId: 'local-fixture', selectedModel: 'fixture-model', availableModels: ['fixture-model'],+ setSelectedProviderId: () => {}, setSelectedModel: () => {},+ } : ({providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],setSelectedProviderId: () => {}, setSelectedModel: () => {},}),@@ -154,14 +157,28 @@ function ProductionHarness({ initial }) {describe('AutopilotPanel production run', () => {beforeEach(() => { vi.clearAllMocks(); listeners.clear(); });- it('shows a zero-allowance code-first plan without offering the legacy autonomous Start', () => {+ it('shows a zero-allowance plan and requires an approved scene plan before Start', () => {render(<ProductionHarness initial={{ id: 'p1', productionRuns: [],productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },audioAnalysis: { durationSec: 30 }, scenes: [], treatment: { shotDirections: [] },}} />);expect(screen.getByText(/generated video 0 \/ 0 seconds/)).toBeTruthy();expect(screen.getByLabelText('Code-first asset preflight')).toHaveTextContent('Routes needed for selected assets: no image · no video');- expect(screen.queryByRole('button', { name: /Start production/ })).toBeNull();+ expect(screen.getByRole('button', { name: /Start production/ })).toBeDisabled();+ });++ it('starts a code-only plan with a separate authoring model and an empty image/video pool', async () => {+ api.startMusicVideoProduction.mockResolvedValueOnce({});+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [],+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ composition: { mode: 'document' }, audioAnalysis: { durationSec: 8 },+ scenes: [{ sceneId: 'code', startSec: 0, endSec: 8 }],+ treatment: { shotDirections: [{ sceneId: 'code', medium: 'procedural', mediumRationale: 'Typography' }] },+ }} />);+ expect(api.startMusicVideoProduction).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Start production' }));+ await waitFor(() => expect(api.startMusicVideoProduction).toHaveBeenCalled());+ expect(api.startMusicVideoProduction.mock.calls[0][1]).toMatchObject({ pool: [], authoring: { providerId: 'local-fixture', model: 'fixture-model' } });});it('preflights selected assets without treating procedural or imported shots as generation jobs', () => {diff --git a/client/src/hooks/useMusicVideoKickoff.js b/client/src/hooks/useMusicVideoKickoff.jsindex c4bb5148e4..e959bd01d5 100644--- a/client/src/hooks/useMusicVideoKickoff.js+++ b/client/src/hooks/useMusicVideoKickoff.js@@ -67,7 +67,10 @@ export default function useMusicVideoKickoff({ analyze, importLyrics, separateVoenter('align');project = (await attempt(alignLyrics, project)) || project;}- if (castAndSets && !castAndSetsDone(project)) {+ const codeFirst = project.productionPolicy?.strategy === 'code-first';+ const needsPerformanceReference = (project.scenes || []).some((scene) => scene.shotMode === 'performance' && !scene.referenceImageId && !scene.videoHistoryId+ && project.treatment?.shotDirections?.some((direction) => direction.sceneId === scene.sceneId && direction.medium === 'generated-footage'));+ if (castAndSets && (!codeFirst || needsPerformanceReference) && !castAndSetsDone(project)) {enter('castAndSets');const checked = await attempt(castAndSets, project);// Waiting for the director (review), or the check-in failed: stop here.diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 58e2dfe6be..87520a34e0 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -1604,6 +1604,17 @@ describe('MusicVideo YouTube audio import (#1945)', () => {expect(alignMusicVideoLyrics).not.toHaveBeenCalled();});+ it('plans a code-first board without starting a Cast & Sets image batch when no selected shot needs references', async () => {+ const project = { ...PROJECT_ANALYZED, trackId: null, uploadedAudioFilename: 'song.mp3', lyricCues: [], scenes: [],+ composition: { mode: 'document' }, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ automation: { tools: ['code:render'], guidance: '', budgetUsd: null, checkins: { castAndSets: 'review' } } };+ planMusicVideoProject.mockResolvedValue({ project, scenesAdded: 1, promptsSeeded: true });+ await openProject(project, 'produce');+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalled());+ expect(startMusicVideoCastAndSets).not.toHaveBeenCalled();+ });+it('autopilot stops at the Cast & Sets check-in in review mode, and Approve & continue plans', async () => {const project = { ...PROJECT_ANALYZED, trackId: null, uploadedAudioFilename: 'song.mp3', lyricCues: [], scenes: [], automation: { tools: ['image:codex'], guidance: '', budgetUsd: null, checkins: { castAndSets: 'review' } } };const directing = { ...project, castAndSets: { status: 'directing', revision: 1, plan: {}, images: {} } };diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex e937ba31c4..7cbfd71b0f 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -471,7 +471,7 @@ export function createRunnerService(config = {}) {// child process via registerExternalRun, so stopRun/isRunActive/deleteRun// still account for it.if (cliRunnerOverride) return cliRunnerOverride(opts);- const { runId, provider, prompt, workspacePath, onData, onComplete, timeout } = opts;+ const { runId, provider, prompt, workspacePath, onData, onComplete, timeout, beforeExecute } = opts;const runDir = join(RUNS_PATH, runId);const outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');@@ -507,6 +507,18 @@ export function createRunnerService(config = {}) {// provider-configured PATH override is honored.const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);+ if (beforeExecute) {+ try { await beforeExecute(); }+ catch {+ const metadata = { ...safeJsonParse(await readFile(metadataPath, 'utf8').catch(() => '{}')),+ endTime: new Date().toISOString(), duration: Date.now() - startTime,+ success: false, canceled: true, completionReason: 'canceled', error: 'CLI run canceled', errorCategory: ERROR_CATEGORIES.CANCELED };+ await atomicWrite(metadataPath, metadata);+ safeSettle(() => hooks.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ return runId;+ }+ }const childProcess = spawn(spawnCommand, spawnArgs, {cwd: workspacePath,env: childEnv,@@ -656,7 +668,7 @@ export function createRunnerService(config = {}) {return runId;},- async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout, absoluteTimeoutMs, maxTokens }) {+ async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout, absoluteTimeoutMs, maxTokens, beforeExecute }) {const runDir = join(RUNS_PATH, runId);const outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');@@ -744,6 +756,17 @@ export function createRunnerService(config = {}) {const ready = endpointGuard.allowed? await ensureProviderReady(provider).catch((err) => ({ success: false, error: err.message })): { success: false, error: `Endpoint blocked: ${endpointGuard.reason}` };+ if (controller.signal.aborted) {+ await finalizer.finalize({ type: 'canceled' });+ return runId;+ }+ if (ready.success && beforeExecute) {+ try { await beforeExecute(); }+ catch {+ await finalizer.finalize({ type: 'canceled' });+ return runId;+ }+ }const response = !endpointGuard.allowed? { ok: false, error: `Endpoint blocked: ${endpointGuard.reason}`, status: 0 }: ready.success@@ -769,7 +792,9 @@ export function createRunnerService(config = {}) {})}), {signal: controller.signal,- allowReplay: isReplaySafeLocalRequest(provider),+ // A caller-owned budget/admission hook accounts for one invocation;+ // do not silently replay a possibly processed local generation.+ allowReplay: !beforeExecute && isReplaySafeLocalRequest(provider),}).catch(err => ({ ok: false, error: describeTransportError(err), status: 0 })): { ok: false, error: ready.error || 'Provider readiness check failed', status: 0 };diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 7950938dd9..cc0b4c1f02 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -178,6 +178,29 @@ describe('AI Toolkit runner service', () => {});});+ it('refuses a stopped caller after API readiness without fetching and settles its run as canceled', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ let release;+ const waiting = new Promise((resolve) => { release = resolve; });+ let active = true;+ const ensureProviderReady = vi.fn(async () => { await waiting; return { success: true }; });+ const onRunFailed = vi.fn();+ const onRunCanceled = vi.fn();+ const onComplete = vi.fn();+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady, onRunFailed, onRunCanceled } });+ const execution = runner.executeApiRun({ runId: 'run-admission', provider: { id: 'local', endpoint: 'http://localhost:11434/v1' },+ prompt: 'hello', beforeExecute: () => { if (!active) throw new Error('Production stopped'); }, onComplete });+ await vi.waitFor(() => expect(ensureProviderReady).toHaveBeenCalled());+ active = false; release(); await execution;+ expect(fetch).not.toHaveBeenCalled();+ expect(await runner.isRunActive('run-admission')).toBe(false);+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ canceled: true, success: false }));+ expect(onRunCanceled).toHaveBeenCalledOnce(); expect(onRunFailed).not.toHaveBeenCalled();+ expect(JSON.parse(await readFile(join(dataDir, 'runs', 'run-admission', 'metadata.json'), 'utf8'))).toMatchObject({ canceled: true, errorCategory: 'canceled' });+ });+it('classifies an injected missing-key prerequisite as an authentication failure', async () => {const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));tempDirs.push(dataDir);diff --git a/server/lib/musicVideoMediumPlan.js b/server/lib/musicVideoMediumPlan.jsindex 1f1bb79c62..ed349ab113 100644--- a/server/lib/musicVideoMediumPlan.js+++ b/server/lib/musicVideoMediumPlan.js@@ -95,10 +95,17 @@ export function codeFirstProductionAssets(project) {if (plan.strategy !== 'code-first') return null;const directions = new Map((project?.treatment?.shotDirections || []).map((d) => [d.sceneId, d]));const steps = [];- const conflicts = plan.unresolved.filter((item) => item.blocking).map((item) => item.message);+ const conflicts = plan.unresolved.filter((item) => item.blocking || item.message.startsWith('Visible performance')).map((item) => item.message);for (const scene of project?.scenes || []) {- const medium = directions.get(scene.sceneId)?.medium;+ const direction = directions.get(scene.sceneId);+ const medium = direction?.medium;if (!MUSIC_VIDEO_MEDIA.includes(medium)) continue;+ if (scene.shotMode === 'performance' && !['existing-footage', 'generated-footage'].includes(medium)) conflicts.push(`Performance shot ${scene.label || scene.sceneId} requires selected footage; revise its shot mode or medium explicitly.`);+ if ((direction?.mode === 'performance' || scene.shotMode === 'performance')+ && ['existing-footage', 'generated-footage'].includes(medium)+ && (scene.shotMode !== 'performance' || (scene.visualLayer != null && scene.visualLayer !== 'footage'))) {+ conflicts.push(`Set ${scene.label || scene.sceneId} to a Performance footage shot before production; its approved performance must retain source-audio timing.`);+ }if (medium === 'procedural') {steps.push({ sceneId: scene.sceneId, medium, action: 'code' });} else if (medium === 'still') {diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 0a08c505bb..72e87d913b 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -664,8 +664,9 @@ export const musicVideoProductionLimitsSchema = z.object({export const musicVideoProductionStartSchema = z.object({directive: z.string().max(4000).optional(),- pool: z.array(musicVideoProductionRouteSchema).min(1).max(12),+ pool: z.array(musicVideoProductionRouteSchema).max(12),limits: musicVideoProductionLimitsSchema,+ authoring: z.object({ providerId: z.string().min(1).max(200), model: z.string().min(1).max(200) }).strict().optional(),providerId: z.string().min(1).max(200).nullable().optional(),model: z.string().min(1).max(200).nullable().optional(),}).strict();diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.jsindex 30097c34da..f76c7a2337 100644--- a/server/services/musicVideo/autoReview.js+++ b/server/services/musicVideo/autoReview.js@@ -122,7 +122,7 @@ 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 = {}, productionRunId = null }, now = new Date().toISOString()) {+export function startAutoReviewOnProject(project, { startSec, endSec, limits, reviewer = {}, productionRunId = null, documentRevisions = false }, 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');@@ -142,7 +142,7 @@ export function startAutoReviewOnProject(project, { startSec, endSec, limits, re// #9066: a production run that handed this run its draft dispatches the// run's revised sections server-side (productionService.js), so the board// must not also submit them.- ...(isNonBlankStr(productionRunId) ? { productionRunId } : {}),+ ...(isNonBlankStr(productionRunId) ? { productionRunId, ...(documentRevisions ? { documentRevisions: true } : {}) } : {}),attempts: [{ n: 1, excerptId: null, renderFailures: 0, reviewStartedAt: null, review: null, revisionId: null }],stopReason: null,error: null,@@ -188,6 +188,10 @@ export function nextAutoReviewStep(project, run) {if (attempt.review.verdict !== 'revise') {return { type: 'halt', status: 'needs-human', reason: attempt.review.reason || 'The review could not verify every check — watch this draft yourself' };}+ if (run.documentRevisions) {+ if (run.usage.reviews >= run.limits.maxAttempts) return { type: 'halt', status: 'limit-reached', reason: 'The review limit was reached before another document revision could be reviewed' };+ return { type: 'revise-document', 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') {diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.jsindex df2c7a8b57..064e504a9c 100644--- a/server/services/musicVideo/autoReviewService.js+++ b/server/services/musicVideo/autoReviewService.js@@ -121,20 +121,27 @@ async function analyzeContinuousExcerpt(excerptPath, spanSec, sections) {};}-async function callReviewer(run, prompt, screenshots) {+async function callReviewer(run, prompt, screenshots, projectId) {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 };+ let beforeExecute;+ if (run.documentRevisions && run.productionRunId) {+ const { assertProductionContinuation } = await import('./productionService.js');+ beforeExecute = () => assertProductionContinuation(projectId, run.productionRunId);+ await assertProductionContinuation(projectId, run.productionRunId);+ }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 });+ const result = await describeImagesFromPaths({ provider, imagePaths: screenshots, prompt, model: selectedModel, timeout: provider.timeout || REVIEW_TIMEOUT_MS, ...(beforeExecute ? { beforeExecute } : {}) });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,+ ...(beforeExecute ? { beforeExecute, allowFallback: false } : {}),});assertVisionRunUsedImages(result, provider);return { text: result.text, used: { ...used, model: result.model || used.model } };@@ -185,7 +192,7 @@ async function reviewDraft(project, run, excerpt) {if (screenshots.length) {const prompt = buildAutoReviewPrompt({ spanSec, sections, frameTimes, hasContactSheet: hasSheet, tiled: true, concept: project.concept });try {- const reply = await callReviewer(run, prompt, screenshots);+ const reply = await callReviewer(run, prompt, screenshots, project.id);used = reply.used;parsed = parseAutoReviewResponse(reply.text);if (!parsed) reviewerError = 'The reviewer returned no usable verdict';@@ -211,6 +218,11 @@ 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);+ if (run.documentRevisions && run.productionRunId) {+ const { assertProductionContinuation } = await import('./productionService.js');+ const permitted = await assertProductionContinuation(projectId, run.productionRunId).then(() => true, () => false);+ if (!permitted) return { project, run, action: { type: 'idle', interrupted: true } };+ }const step = nextAutoReviewStep(project, run);if (step.type === 'idle' || step.type === 'wait') return { project, run, action: step };@@ -246,6 +258,8 @@ async function takeSteps(projectId, runId) {continue;}+ if (step.type === 'revise-document') return { project, run, action: { type: 'revise-document', excerptId: step.excerptId } };+if (step.type === 'revise') {const opened = await mutateProjectRecord(projectId, (current) => {const started = startRevisionOnProject(current, step.excerptId);diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.jsindex 17cdbc08c4..aeb0b571d9 100644--- a/server/services/musicVideo/codeGeneration.js+++ b/server/services/musicVideo/codeGeneration.js@@ -42,7 +42,7 @@ function acceptSources(parsed, ids) {return accepted;}-export async function runModel({ providerId, model, prompt, source = 'music-video-code' }) {+export async function runModel({ providerId, model, prompt, source = 'music-video-code', beforeSubmit = null }) {const { assertProvider, resolveProviderAndModel, runPromptThroughProvider } = await import('../promptRunner.js');const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: 'No AI provider available to write the code video', code: 'PROVIDER_UNAVAILABLE', status: 400 });@@ -53,6 +53,7 @@ export async function runModel({ providerId, model, prompt, source = 'music-videprompt,source,cwd: PATHS.data,+ ...(beforeSubmit ? { allowFallback: false, toolFree: true, beforeExecute: beforeSubmit } : {}),});return { text, providerId: provider.id, model: selectedModel || null };}diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.jsindex fbcf54282b..3b70c4c99b 100644--- a/server/services/musicVideo/documentGeneration.js+++ b/server/services/musicVideo/documentGeneration.js@@ -134,7 +134,7 @@ async function priorManifest(project) {return { pointer, manifest };}-async function runAuthoring(projectId, { providerId, model, sectionId = null, expectedDraft = null } = {}) {+async function runAuthoring(projectId, { providerId, model, sectionId = null, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);if (!project) throw fail('Project not found', 'NOT_FOUND', 404);const context = await authoringContext(project);@@ -160,7 +160,8 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, exvisualSpec: project.visualSpec, scenes: context.scenes, styleLines: sharedStyle.styleLines,onlySectionId: sectionId, sharedStyle,});- const run = await runModel({ providerId, model, prompt, source: 'music-video-document' });+ const directedPrompt = feedback ? `${prompt}\n\nReview findings for this section (retain the approved medium and selected assets; never invent a footage fallback):\n${feedback.slice(0, 8000)}` : prompt;+ const run = await runModel({ providerId, model, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });const ids = sectionId ? [sectionId] : context.song.sections.map((section) => section.id);const updated = acceptedSections(run.text, ids);const merged = new Map((prior?.manifest.sections || []).map((section) => [section.id, section.source]));@@ -176,6 +177,7 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, exconst draft = project.composition?.documentDraft?.directory || null;const result = await stageGeneratedDocument(projectId, generatedFiles(manifest), {verifyCurrent: (current) => {+ verifyCurrent(current);if (basisFor(current) !== context.basis || (current.composition?.document?.directory || null) !== active|| (current.composition?.documentDraft?.directory || null) !== draft) {throw fail('The project or candidate changed during generation — review the current state and retry', 'COMPOSITION_DRAFT_STALE', 409);@@ -188,7 +190,7 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, exexport const generateMixedMediaDocument = (projectId, input = {}) => runAuthoring(projectId, input);export const regenerateMixedMediaSection = (projectId, sectionId, input = {}) => runAuthoring(projectId, { ...input, sectionId });-export async function acceptMixedMediaDocument(projectId, directory) {+export async function acceptMixedMediaDocument(projectId, directory, { verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);if (!project?.composition?.documentDraft || project.composition.documentDraft.directory !== directory) {throw fail('The composition candidate changed', 'COMPOSITION_DRAFT_STALE', 409);@@ -196,6 +198,7 @@ export async function acceptMixedMediaDocument(projectId, directory) {const { manifest } = await priorManifest(project);return acceptGeneratedDocument(projectId, directory, {verifyCurrent: (current) => {+ verifyCurrent(current);if (basisFor(current) !== manifest.basis || (current.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)) {throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);}diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.jsindex 32881df73c..b08b165bcb 100644--- a/server/services/musicVideo/documentGeneration.test.js+++ b/server/services/musicVideo/documentGeneration.test.js@@ -3,15 +3,17 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';-const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '' }));+const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '', onSubmit: null }));vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {dataRoot: () => lazyTempDataRoot('portos-mv-document-author-'),}));vi.mock('../promptRunner.js', () => ({assertProvider: () => {},resolveProviderAndModel: async () => ({ provider: { id: 'stub-provider' }, selectedModel: 'fixture-model' }),- runPromptThroughProvider: async ({ prompt }) => {+ runPromptThroughProvider: async ({ prompt, beforeExecute }) => {+ if (beforeExecute) await beforeExecute({ provider: { id: 'stub-provider' }, model: 'fixture-model' });h.calls += 1; h.prompt = prompt;+ if (h.onSubmit) await h.onSubmit();return { text: h.response };},}));@@ -26,7 +28,7 @@ const response = (colors) => JSON.stringify({ sections: Object.entries(colors).mconst manifestAt = async (document) => JSON.parse(await readFile(join(PATHS.data, document.directory, 'manifest.json'), 'utf8'));afterAll(() => cleanupTempDataRoots());-beforeEach(() => { h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });+beforeEach(() => { h.onSubmit = null; h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });async function fixture() {await mkdir(PATHS.images, { recursive: true });@@ -116,3 +118,20 @@ describe('treatment-driven mixed-media document authoring', () => {await expect(acceptMixedMediaDocument(id, candidate.directory)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });});});+++it('checks production authorization before provider submission and again before candidate publication/acceptance', async () => {+ const id = await fixture();+ const blocked = () => { throw Object.assign(new Error('Production canceled'), { code: 'PRODUCTION_STEP_CLOSED' }); };+ await expect(generateMixedMediaDocument(id, { beforeSubmit: blocked })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });+ expect(h.calls).toBe(0);+ let active = true;+ h.onSubmit = () => { active = false; };+ await expect(generateMixedMediaDocument(id, { verifyCurrent: () => { if (!active) blocked(); } })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });+ expect(h.calls).toBe(1);+ expect((await projects.getProject(id)).composition?.documentDraft).toBeUndefined();+ h.onSubmit = null;+ const staged = (await generateMixedMediaDocument(id)).document;+ await expect(acceptMixedMediaDocument(id, staged.directory, { verifyCurrent: blocked })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });+ expect((await projects.getProject(id)).composition.documentDraft.directory).toBe(staged.directory);+});diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex cfef92ec34..e1a8f0ff2b 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -42,7 +42,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';import { isLayeredComposition, sceneVisualLayer } from '../../lib/musicVideoLayers.js';-import { normalizeMusicVideoProductionPolicy, summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';+import { codeFirstProductionAssets, normalizeMusicVideoProductionPolicy, summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';import { projectAutoReviews } from './autoReview.js';import { projectRevisions } from './revision.js';import { castAndSetsSettled } from './castAndSets.js';@@ -128,6 +128,15 @@ function productionBasisRevision(project, version = 1) {productionPolicy: normalizeMusicVideoProductionPolicy(project?.productionPolicy),...(normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first'? { shotDirections: pick(project?.treatment?.shotDirections) } : {}),+ ...(version >= 3 ? {+ sceneTiming: (project?.scenes || []).map(({ sceneId, startSec, endSec, shotMode }) => ({ sceneId, startSec, endSec, shotMode: shotMode || 'cutaway' })),+ videoSettings: pick(project?.videoSettings),+ treatment: pick(project?.treatment),+ audioAnalysis: pick(project?.audioAnalysis),+ lyricCues: pick(project?.lyricCues),+ lyricMarkers: pick(project?.lyricMarkers),+ compositionStyle: pick(project?.composition?.style),+ } : {}),} : {}),});}@@ -156,7 +165,7 @@ function normalizeProductionLimits(limits) {export const routeKey = (route) => `${route.kind}:${route.mode}:${route.model || ''}`;/** De-duplicate a validated pool, keeping the director's order (it is the preference order). */-export function normalizeProductionPool(pool) {+export function normalizeProductionPool(pool, { allowEmpty = false } = {}) {const seen = new Set();const out = [];for (const entry of Array.isArray(pool) ? pool : []) {@@ -166,7 +175,7 @@ export function normalizeProductionPool(pool) {seen.add(routeKey(route));out.push(route);}- if (!out.length) throw productionError(422, 'VALIDATION_ERROR', 'The allowed pool needs at least one image or video route');+ if (!out.length && !allowEmpty) throw productionError(422, 'VALIDATION_ERROR', 'The allowed pool needs at least one image or video route');if (out.length > PRODUCTION_POOL_MAX) throw productionError(422, 'VALIDATION_ERROR', `The allowed pool holds at most ${PRODUCTION_POOL_MAX} routes`);return out;}@@ -181,7 +190,7 @@ export const poolHasRoute = (run, route) => !!route && run.pool.some((r) => rout* when unknown); a dollar cap requires every route to have a known price.*/export function startProductionOnProject(project, {- directive = '', pool, limits, reviewer = {}, processId, pricing = {},+ directive = '', pool, limits, reviewer = {}, authoring = null, processId, pricing = {},}, now = new Date().toISOString()) {const live = activeProductionRun(project);if (live) throw productionError(409, 'PRODUCTION_IN_PROGRESS', 'Finish, cancel or resume the existing production run first', { runId: live.id });@@ -189,18 +198,23 @@ export function startProductionOnProject(project, {if (liveReview) throw productionError(409, 'AUTO_REVIEW_IN_PROGRESS', 'Finish or cancel the auto-review run before starting production', { runId: liveReview.id });const openRevision = projectRevisions(project).find((r) => r.status === 'open' || r.status === 'rendering');if (openRevision) throw productionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before starting production', { revisionId: openRevision.id });- if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {- throw productionError(409, 'PRODUCTION_CODE_FIRST_NOT_READY', 'Autonomous code-first production needs document authoring and review checkpoints; use the mixed-media document controls until those steps are available');+ const codeFirst = normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first';+ if (codeFirst) {+ if (project?.composition?.mode !== 'document') throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'Code-first production needs document composition mode');+ const assets = codeFirstProductionAssets(project);+ if (!project.scenes?.length || assets.conflicts.length) throw productionError(409, 'PRODUCTION_MEDIUM_CONFLICT', assets.conflicts.join(' ') || 'Approve a timed medium plan before starting production');+ if (!authoring?.providerId || !authoring?.model) throw productionError(422, 'PRODUCTION_AUTHORING_REQUIRED', 'Select a separate code-authoring provider and model');}- if (project?.composition?.mode === 'code') {+ if (!codeFirst && project?.composition?.mode === 'code') {throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'A code-rendered project generates no footage — render it directly');}if (!Array.isArray(project?.audioAnalysis?.sections) || !project.audioAnalysis.sections.length) {throw productionError(409, 'NOT_ANALYZED', 'Analyze the song before starting production');}- const normalizedPool = normalizeProductionPool(pool);+ const normalizedPool = normalizeProductionPool(pool, { allowEmpty: codeFirst });const normalizedLimits = normalizeProductionLimits(limits);if (normalizedLimits.spendCapUsd !== null) {+ if (codeFirst && authoring.costUsd == null) throw productionError(409, 'PRODUCTION_COST_UNKNOWN', 'Code-authoring has no bounded dollar price. Choose a free/local authoring provider or remove the dollar cap; every authoring call still consumes the generation limit.');const unpriced = normalizedPool.filter((r) => typeof pricing[routeKey(r)] !== 'number');if (unpriced.length) {throw productionError(409, 'PRODUCTION_COST_UNKNOWN',@@ -214,11 +228,12 @@ export function startProductionOnProject(project, {pool: normalizedPool,pricing: Object.fromEntries(normalizedPool.map((r) => [routeKey(r), typeof pricing[routeKey(r)] === 'number' ? pricing[routeKey(r)] : null])),limits: normalizedLimits,+ ...(codeFirst ? { authoring: { ...authoring }, documentCheckpoint: null, finalRender: null } : {}),reviewer: {providerId: isNonBlankStr(reviewer.providerId) ? reviewer.providerId : null,model: isNonBlankStr(reviewer.model) ? reviewer.model : null,},- basis: { version: 2, revision: productionBasisRevision(project, 2), capturedAt: now },+ basis: { version: codeFirst ? 3 : 2, revision: productionBasisRevision(project, codeFirst ? 3 : 2), capturedAt: now },usage: { generations: 0, spentUsd: 0 },planned: false,reviewRunId: null,@@ -251,7 +266,7 @@ export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kin|| (kind === 'image' && !['still', 'generated-footage'].includes(medium))) {throw productionError(409, 'PRODUCTION_MEDIUM_CONFLICT', 'The approved medium plan or generated-video allowance no longer permits this submission');}- throw productionError(409, 'PRODUCTION_CODE_FIRST_NOT_READY', 'Autonomous code-first production cannot submit media until document authoring and review checkpoints are available');+ if (kind !== 'code' && step.submissionBasis !== productionSceneBasis(project, sceneId)) throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'This shot changed while its provider request was being prepared');}return step;}@@ -259,10 +274,32 @@ export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kin// ---- deriving the next step -------------------------------------------------const SLOT = Object.freeze({ frame: 'referenceImageId', clip: 'videoHistoryId' });-const JOB_KIND = Object.freeze({ frame: 'image', clip: 'video' });+const JOB_KIND = Object.freeze({ frame: 'image', clip: 'video', author: 'code' });++const productionSceneBasis = (project, sceneId) => canonicalSnapshotChecksum({+ scene: (project.scenes || []).find((scene) => scene.sceneId === sceneId) || null,+ videoSettings: project.videoSettings || null,+});++/** All code-first work stays tied to the process and approved plan that reserved it. */+export function assertProductionActive(project, runId, processId) {+ const run = findProductionRun(project, runId);+ if (run.status !== 'running' || run.processId !== processId) throw productionError(409, 'PRODUCTION_NOT_RUNNING', 'Resume this production run before dispatching more work');+ if (productionBasisRevision(project, run.basis.version || 1) !== run.basis.revision) throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The approved setup changed — review it and resume');+ if (run.documentCheckpoint?.scenesRevision && run.documentCheckpoint.scenesRevision !== canonicalSnapshotChecksum(project.scenes || [])) throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The selected media changed since the document was authored — replan and review it');+ if (run.authoring && codeFirstProductionAssets(project)?.conflicts.length) throw productionError(409, 'PRODUCTION_MEDIUM_CONFLICT', codeFirstProductionAssets(project).conflicts.join(' '));+ return run;+}/** The scenes that need a still frame and a clip, per the project's render mode. */function productionTargets(project) {+ const assets = codeFirstProductionAssets(project);+ if (assets) {+ const ids = (action) => new Set(assets.steps.filter((step) => step.action === action).map((step) => step.sceneId));+ const frames = ids('generate-image');+ const clips = ids('generate-video');+ return { frame: project.scenes.filter((scene) => frames.has(scene.sceneId)), clip: project.scenes.filter((scene) => clips.has(scene.sceneId)) };+ }const layered = isLayeredComposition(project);const scenes = Array.isArray(project?.scenes) ? project.scenes : [];return {@@ -286,6 +323,9 @@ const slotSteps = (run, sceneId, stepKind, revisionId = null) => run.steps* start one (it runs before the plan; see castAndSetsService.js);* `plan` — the board is empty: seed it (one planner call, first time only);* `dispatch` — generate `kind` (frame|clip) for `sceneId`;+ * `author-document` / `revise-document` — author the approved document or+ * just the failed song sections, without changing its assets;+ * `render-document` — encode the chosen document after continuous review;* `review` — every scene holds its media: hand the continuous excerpt* `[startSec, endSec)` to an auto-review run;* `wait` — work in flight (generation jobs, or the review run);@@ -298,14 +338,28 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }if (productionBasisRevision(project, run.basis.version || 1) !== run.basis.revision) {return { type: 'halt', status: 'needs-replan', reason: 'The creative setup changed since Start — review it, then resume against the new setup' };}- if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {- return { type: 'halt', status: 'needs-replan', reason: 'Autonomous code-first production needs document authoring and review checkpoints before it can dispatch' };+ if (run.authoring) {+ const assets = codeFirstProductionAssets(project);+ if (!assets || assets.conflicts.length) return { type: 'halt', status: 'needs-replan', reason: assets?.conflicts.join(' ') || 'The code-first policy changed' };+ if (run.documentCheckpoint && (run.documentCheckpoint.directory !== project.composition?.document?.directory+ || run.documentCheckpoint.scenesRevision !== canonicalSnapshotChecksum(project.scenes || []))) return { type: 'halt', status: 'needs-replan', reason: 'The selected document changed — review and resume against the new setup' };}if (run.reviewRunId) {const review = projectAutoReviews(project).find((r) => r.id === run.reviewRunId);if (!review) return { type: 'halt', status: 'needs-human', reason: 'The review run is gone — watch the draft yourself' };- if (review.status === 'running') return { type: 'wait', on: 'review' };- if (review.status === 'passed') return { type: 'halt', status: 'completed', reason: null };+ if (review.status === 'running') {+ const attempt = review.attempts?.[review.attempts.length - 1];+ if (run.authoring && attempt?.review?.verdict === 'revise') return { type: 'revise-document', reviewRunId: review.id, attemptN: attempt.n };+ return { type: 'wait', on: 'review' };+ }+ if (review.status === 'passed') {+ if (!run.authoring) return { type: 'halt', status: 'completed', reason: null };+ if (run.documentCheckpoint?.directory !== project.composition?.document?.directory) return { type: 'halt', status: 'needs-replan', reason: 'The selected document changed after review — start a fresh run' };+ if (!run.finalRender) return { type: 'render-document' };+ if (run.finalRender.status === 'completed') return { type: 'halt', status: 'completed', reason: null };+ if (run.finalRender.status === 'failed') return { type: 'halt', status: 'blocked', reason: run.finalRender.error || 'The final document render failed — resume to retry' };+ return { type: 'wait', on: 'final-render' };+ }if (review.status === 'stopped' || review.status === 'limit-reached') {return { type: 'halt', status: review.status === 'limit-reached' ? 'limit-reached' : 'stopped', reason: `The review paused: ${review.stopReason || review.status}` };}@@ -319,6 +373,10 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }return { type: 'plan' };}const targets = productionTargets(project);+ if (run.authoring && targets.frame.some((scene) => scene.shotMode === 'performance')) {+ const gate = castAndSetsGate(project, run);+ if (gate) return { type: 'halt', status: 'blocked', reason: 'This selected performance shot needs the reviewed Cast & Sets references. Build and approve that check-in, then resume; production will not start an unbudgeted image batch.' };+ }let waiting = false;for (const stepKind of ['frame', 'clip']) {for (const scene of targets[stepKind]) {@@ -337,6 +395,7 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }}}if (waiting) return { type: 'wait', on: 'generation' };+ if (run.authoring && !run.documentCheckpoint) return { type: 'author-document' };const spans = scenes.filter((s) => typeof s.startSec === 'number' && typeof s.endSec === 'number' && s.endSec > s.startSec);if (!spans.length) return { type: 'halt', status: 'blocked', reason: 'No scene is timed on the song, so there is no excerpt to review' };return {@@ -377,13 +436,20 @@ function castAndSetsGate(project, run) {* Returns `{ project, run, step }`.*/export function reserveProductionStep(project, runId, {- kind, sceneId, revisionId = null, route, rationale = '', processId, costUsd: stepCostUsd = null,+ kind, sceneId, revisionId = null, route, rationale = '', processId, costUsd: stepCostUsd = undefined,}, now = new Date().toISOString()) {let step = null;const out = mutateRun(project, runId, (run) => {if (run.status !== 'running') throw productionError(409, 'PRODUCTION_NOT_RUNNING', `This production run is ${run.status}`);if (run.processId !== processId) throw productionError(409, 'PRODUCTION_INTERRUPTED', 'The server restarted since this run was started — resume it first');- if (!poolHasRoute(run, route)) throw productionError(409, 'PRODUCTION_ROUTE_NOT_ALLOWED', `${route?.kind} ${route?.mode} is not in this run's allowed pool`);+ assertProductionActive(project, runId, processId);+ const author = kind === 'author';+ const authorRoute = author && run.authoring && route?.kind === 'code' && route.mode === run.authoring.providerId && route.model === run.authoring.model;+ if (!(authorRoute || (!author && poolHasRoute(run, route)))) throw productionError(409, 'PRODUCTION_ROUTE_NOT_ALLOWED', `${route?.kind} ${route?.mode} is not in this run's allowed pool`);+ if (!author && run.authoring) {+ const medium = project.treatment?.shotDirections?.find((d) => d.sceneId === sceneId)?.medium;+ if ((kind === 'clip' && medium !== 'generated-footage') || (kind === 'frame' && !['still', 'generated-footage'].includes(medium))) throw productionError(409, 'PRODUCTION_MEDIUM_CONFLICT', 'This shot does not permit the requested generation');+ }const existing = slotSteps(run, sceneId, kind, revisionId);if (existing.some((s) => LIVE_STEP.has(s.status))) {throw productionError(409, 'PRODUCTION_STEP_IN_FLIGHT', 'This scene is already generating for the production run', { sceneId });@@ -393,8 +459,8 @@ export function reserveProductionStep(project, runId, {}// A scene-specific estimate (a fal take priced by its own length and// resolution) wins over the route's flat start-time price.- const price = typeof stepCostUsd === 'number' ? stepCostUsd : run.pricing?.[routeKey(route)];- const costUsd = typeof price === 'number' ? price : null;+ const price = stepCostUsd !== undefined ? stepCostUsd : run.pricing?.[routeKey(route)];+ const costUsd = typeof price === 'number' && Number.isFinite(price) && price >= 0 ? price : null;if (run.limits.spendCapUsd !== null) {if (costUsd === null) throw productionError(409, 'PRODUCTION_COST_UNKNOWN', 'This route has no known price, so the dollar cap cannot bound it');if (run.usage.spentUsd + costUsd > run.limits.spendCapUsd + 1e-9) {@@ -410,6 +476,8 @@ export function reserveProductionStep(project, runId, {route: { kind: route.kind, mode: route.mode, model: route.model || null },rationale: trimTo(rationale, MAX_ERROR_LEN) || '',costUsd,+ ...(run.authoring && !author ? { submissionBasis: productionSceneBasis(project, sceneId) } : {}),+ ...(run.authoring && kind === 'clip' ? { editInterval: (({ startSec, endSec }) => ({ startSec, endSec }))(project.scenes.find((scene) => scene.sceneId === sceneId)) } : {}),status: 'reserved',jobId: null,error: null,@@ -417,7 +485,7 @@ export function reserveProductionStep(project, runId, {settledAt: null,};return {- usage: { generations: run.usage.generations + 1, spentUsd: run.usage.spentUsd + (costUsd || 0) },+ usage: { ...run.usage, generations: run.usage.generations + 1, spentUsd: run.usage.spentUsd + (costUsd || 0) },steps: [...run.steps, step],};}, now);@@ -425,6 +493,7 @@ export function reserveProductionStep(project, runId, {}const refund = (run, step) => ({+ ...run.usage,generations: Math.max(0, run.usage.generations - 1),spentUsd: Math.max(0, run.usage.spentUsd - (step.costUsd || 0)),});@@ -476,6 +545,9 @@ export function reconcileProductionSteps(project, runId, jobs = [], nowMs = Datelet usage = run.usage;const steps = run.steps.map((step) => {if (!LIVE_STEP.has(step.status)) return step;+ // An authoring call is not a queue job: after interruption its reserved+ // budget stays spent, and explicit Resume may retry with another charge.+ if (step.kind === 'author') return { ...step, status: 'failed', error: 'Authoring interrupted — resume explicitly to retry', settledAt: now };const job = (jobs || []).find((j) => (step.jobId && j.id === step.jobId)|| (j.params?.musicVideo?.productionRunId === runId && j.params.musicVideo.productionStepKey === step.key));if (job) {@@ -552,10 +624,10 @@ export function stopProductionOnProject(project, runId, now = new Date().toISOStexport function resumeProductionOnProject(project, runId, { limits, acceptBasis = false, processId } = {}, now = new Date().toISOString()) {return mutateRun(project, runId, (run) => {if (!RESUMABLE.has(run.status)) throw productionError(409, 'PRODUCTION_CLOSED', `This production run is ${run.status} — start a new run instead`);- if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {- throw productionError(409, 'PRODUCTION_CODE_FIRST_NOT_READY', 'Autonomous code-first production needs document authoring and review checkpoints; use the mixed-media document controls');- }- const basisChanged = productionBasisRevision(project, run.basis.version || 1) !== run.basis.revision;+ if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first' && !run.authoring) throw productionError(409, 'PRODUCTION_AUTHORING_REQUIRED', 'Cancel this legacy run and start a code-first run with an authoring model');+ const basisChanged = productionBasisRevision(project, run.basis.version || 1) !== run.basis.revision+ || (run.authoring && run.documentCheckpoint && (run.documentCheckpoint.directory !== project.composition?.document?.directory+ || run.documentCheckpoint.scenesRevision !== canonicalSnapshotChecksum(project.scenes || [])));if (basisChanged && !acceptBasis) {throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The creative setup changed since Start — resume with the new setup accepted, or cancel');}@@ -574,6 +646,8 @@ export function resumeProductionOnProject(project, runId, { limits, acceptBasisresumedAt: now,stopReason: null,error: null,+ ...(run.finalRender?.status === 'failed' || (run.finalRender && run.processId !== processId) ? { finalRender: null } : {}),+ ...(basisChanged && run.authoring ? { documentCheckpoint: null, documentRevision: null, reviewRunId: null, finalRender: null } : {}),...(basisChanged ? { basis: { ...run.basis, revision: productionBasisRevision(project, run.basis.version || 1), capturedAt: now } } : {}),};}, now);@@ -586,3 +660,16 @@ export function cancelProductionOnProject(project, runId, now = new Date().toISO/** Generations still affordable before the limit. */export const remainingProductionGenerations = (run) => Math.max(0, run.limits.maxGenerations - run.usage.generations);++/** Persist the exact authored/selected version, never a free-form model decision. */+export const attachProductionDocument = (project, runId, directory, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ documentCheckpoint: { directory, scenesRevision: canonicalSnapshotChecksum(project.scenes || []) } }), now);++/** Final render checkpoint; late link writes must preserve terminal evidence. */+export const setProductionRender = (project, runId, render, now = new Date().toISOString()) =>+ mutateRun(project, runId, (run) => ({ finalRender: run.finalRender && render.status !== 'reserved'+ && (render.attemptId !== run.finalRender.attemptId || (['completed', 'failed'].includes(run.finalRender.status) && render.status === 'queued'))+ ? run.finalRender : render }), now);++export const recordProductionDocumentRevision = (project, runId, checkpoint, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ documentRevision: checkpoint }), now);diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex aa9909d333..ae59475d9b 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -26,9 +26,17 @@ import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';+import { isFreeProvider } from '../../lib/modelPricing.js';+import { isToolFreeOneShotProvider } from '../../lib/providerVendors.js';+import { codeFirstProductionAssets } from '../../lib/musicVideoMediumPlan.js';+import { beginNextAttempt } from './autoReview.js';import { withAutopilotCutting } from './composition.js';import {attachProductionReview,+ attachProductionDocument,+ assertProductionActive,+ recordProductionDocumentRevision,+ setProductionRender,assertProductionStepOpen,cancelProductionOnProject,findProductionRun,@@ -79,6 +87,16 @@ const defaults = {planProject: async (...args) => (await import('./planner.js')).planProject(...args),startCastAndSets: async (...args) => (await import('./castAndSetsService.js')).startCastAndSets(...args),autoReview: async () => import('./autoReviewService.js'),+ documents: async () => import('./documentGeneration.js'),+ render: async () => import('./render.js'),+ resolveAuthoring: async (input) => {+ if (!input?.providerId || !input?.model) throw new ServerError('Select a code-authoring provider and model', { status: 422, code: 'PRODUCTION_AUTHORING_REQUIRED' });+ const { resolveProviderAndModel } = await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel(input);+ if (!provider || provider.id !== input?.providerId || provider.enabled === false || !selectedModel || selectedModel !== input?.model) throw new ServerError('The selected code-authoring provider/model is unavailable', { status: 409, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });+ if (!isToolFreeOneShotProvider(provider)) throw new ServerError('Choose an API or a tool-free headless CLI for code authoring', { status: 422, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });+ return { providerId: provider.id, model: selectedModel, costUsd: isFreeProvider(provider) ? 0 : null };+ },releaseRevisionSection: async (...args) => (await import('./revisionService.js')).releaseRevisionSection(...args),};let deps = { ...defaults };@@ -97,6 +115,13 @@ export async function assertProductionSubmission(projectId, runId, stepKey, inpuassertProductionStepOpen(project, runId, stepKey, { ...input, processId: PROCESS_ID });}+export async function assertProductionContinuation(projectId, runId) {+ const project = await requireProject(projectId);+ const run = assertProductionActive(project, runId, PROCESS_ID);+ if (run.documentCheckpoint && run.documentCheckpoint.directory !== project.composition?.document?.directory) throw new ServerError('The selected document changed since this review began', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ return run;+}+async function liveJobs() {const { listJobs } = await deps.queue();return [...listJobs({ kind: 'image' }), ...listJobs({ kind: 'video' })];@@ -141,7 +166,7 @@ async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId =const reserved = await mutateProjectRecord(projectId, (current) => reserveProductionStep(current, runId, {kind: stepKind, sceneId, revisionId, route: choice.route, rationale: choice.rationale, processId: PROCESS_ID,- costUsd: stepPriceUsd({ route: choice.route, project, scene, stepKind }),+ costUsd: stepPriceUsd({ route: choice.route, project: current, scene: (current.scenes || []).find((s) => s.sceneId === sceneId), stepKind }),})).catch((err) => ({ error: err }));if (reserved.error) {const code = reserved.error.code;@@ -151,7 +176,7 @@ async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId =}const { step } = reserved;const tag = { projectId, sceneId, productionRunId: runId, productionStepKey: step.key, ...(revisionId ? { revisionId } : {}) };- const sent = await deps.dispatch({ stepKind, project, scene, route: choice.route, tag, settings: env.settings })+ const sent = await deps.dispatch({ stepKind, project: reserved.project, scene: reserved.project.scenes.find((s) => s.sceneId === sceneId), route: choice.route, tag, settings: env.settings }).catch((err) => ({ error: err }));if (sent.error) {await mutateProjectRecord(projectId, (current) => settleProductionStep(current, runId, step.key, { status: 'refused', error: sent.error.message }));@@ -166,6 +191,89 @@ async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId =return { ok: true };}+/** Author only the failed song sections, preserving every approved asset and medium. */+async function authorDocument(projectId, runId, action) {+ const project = await requireProject(projectId);+ const run = assertProductionActive(project, runId, PROCESS_ID);+ const documents = await deps.documents();+ const revise = action.type === 'revise-document';+ const review = revise ? project.autoReviews.find((entry) => entry.id === action.reviewRunId) : null;+ const attempt = review?.attempts?.[review.attempts.length - 1];+ if (revise && (!attempt || attempt.n !== action.attemptN || review.status !== 'running')) return;+ const revisionId = revise ? `${review.id}:${attempt.n}` : null;+ const progress = run.documentRevision?.revisionId === revisionId ? run.documentRevision : null;+ const verifyReviewCurrent = (current, acceptedDirectory = null) => {+ assertProductionActive(current, runId, PROCESS_ID);+ if (!revise) return;+ const liveReview = current.autoReviews.find((entry) => entry.id === review.id);+ if (liveReview?.status !== 'running' || liveReview.attempts.at(-1)?.n !== attempt.n) throw new ServerError('This document review was stopped or changed', { status: 409, code: 'PRODUCTION_STEP_CLOSED' });+ if (current.composition?.document?.directory !== (acceptedDirectory || run.documentCheckpoint?.directory)) throw new ServerError('The reviewed document changed during revision', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ };+ const context = revise ? await documents.readMixedMediaCandidate(projectId) : null;+ if (revise && (context.stale || !context.sections.length || context.source?.directory !== (progress?.directory || run.documentCheckpoint?.directory))) throw new ServerError('The reviewed document changed — author and review a fresh candidate', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ const findings = attempt?.review?.findings?.filter((finding) => finding.severity === 'blocking') || [];+ const sections = revise ? context.sections.filter((section) => findings.some((finding) => {+ const time = review.startSec + finding.atSec;+ return time >= section.startSec && time < section.endSec;+ })).map((section) => section.id) : [null];+ if (revise && !sections.length) throw new ServerError('The review has no failed document section to revise — inspect the plan', { status: 409, code: 'PRODUCTION_MEDIUM_CONFLICT' });+ if (progress && progress.directory !== (project.composition.documentDraft || project.composition.document)?.directory) throw new ServerError('The revision candidate changed — review the current document', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ const completed = new Set(progress?.completed || []);+ let directory = progress?.directory || project.composition.document?.directory || null;+ for (const sectionId of sections) {+ if (completed.has(sectionId)) continue;+ let key = null;+ const sceneId = sectionId || 'document';+ const verifyCurrent = (current) => {+ verifyReviewCurrent(current);+ if (key) assertProductionStepOpen(current, runId, key, { sceneId, kind: 'code', processId: PROCESS_ID });+ };+ const input = {+ ...run.authoring,+ ...(revise ? { expectedDraft: directory, feedback: findings.map((finding) => `${finding.atSec}s: ${finding.note}`).join('\n') } : {}),+ verifyCurrent,+ beforeSubmit: async ({ provider, model }) => {+ if (provider.id !== run.authoring.providerId || model !== run.authoring.model) throw new ServerError('The authoring provider/model changed; no fallback is allowed', { status: 409, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });+ if (!isToolFreeOneShotProvider(provider)) throw new ServerError('This code authoring provider cannot run without tools', { status: 422, code: 'PRODUCTION_AUTHORING_UNAVAILABLE' });+ const costUsd = isFreeProvider(provider) ? 0 : null;+ const reserved = await mutateProjectRecord(projectId, (current) => {+ verifyCurrent(current);+ return reserveProductionStep(current, runId, { kind: 'author', sceneId, revisionId,+ route: { kind: 'code', mode: provider.id, model }, costUsd,+ rationale: revise ? 'Revise this failed document section without changing the medium plan' : 'Author the approved mixed-media document', processId: PROCESS_ID });+ });+ key = reserved.step.key;+ },+ };+ const result = await (revise ? documents.regenerateMixedMediaSection(projectId, sectionId, input) : documents.generateMixedMediaDocument(projectId, input))+ .catch(async (error) => {+ if (key) await mutateProjectRecord(projectId, (current) => settleProductionStep(current, runId, key, { status: 'failed', error: error.message }));+ throw error;+ });+ directory = result.document.directory;+ completed.add(sectionId);+ await mutateProjectRecord(projectId, (current) => {+ verifyCurrent(current);+ const settled = settleProductionStep(current, runId, key, { status: 'completed' });+ return recordProductionDocumentRevision(settled.project, runId, { revisionId, completed: [...completed], directory });+ });+ }+ await documents.acceptMixedMediaDocument(projectId, directory, { verifyCurrent: verifyReviewCurrent });+ await mutateProjectRecord(projectId, (current) => {+ verifyReviewCurrent(current, directory);+ if (current.composition.document?.directory !== directory) throw new ServerError('The selected document changed', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ const attached = attachProductionDocument(current, runId, directory);+ if (!revise) return attached;+ const liveReview = attached.project.autoReviews.find((entry) => entry.id === review.id);+ if (liveReview?.status !== 'running' || liveReview.attempts.at(-1)?.n !== attempt.n) throw new ServerError('The review stopped during authoring', { status: 409, code: 'PRODUCTION_STEP_CLOSED' });+ return { ...attached, project: beginNextAttempt(attached.project, review.id, null).project };+ });+ if (revise) {+ const { resumeAutoReview } = await deps.autoReview();+ await resumeAutoReview(projectId, review.id);+ }+}+// ---- the step loop --------------------------------------------------------------async function takeSteps(projectId, runId) {@@ -222,6 +330,42 @@ async function takeSteps(projectId, runId) {continue;}+ if (step.type === 'author-document' || step.type === 'revise-document') {+ const failure = await authorDocument(projectId, runId, step).then(() => null, (error) => error);+ if (failure) {+ const fresh = await requireProject(projectId);+ const active = findProductionRun(fresh, runId);+ if (active.status !== 'running') return { project: fresh, run: active, action: { type: 'idle' } };+ const out = await halt(projectId, runId, { status: LIMIT_CODES.has(failure.code) ? 'limit-reached' : 'blocked', reason: `Document authoring stopped: ${failure.message}` });+ return { ...out, action: { type: 'idle' } };+ }+ continue;+ }++ if (step.type === 'render-document') {+ const attemptId = randomUUID();+ await mutateProjectRecord(projectId, (current) => {+ assertProductionActive(current, runId, PROCESS_ID);+ return setProductionRender(current, runId, { status: 'reserved', jobId: null, attemptId });+ });+ const { renderMusicVideo } = await deps.render();+ const rendered = await renderMusicVideo(projectId, {+ productionRunId: runId,+ productionRenderAttemptId: attemptId,+ verifyCurrent: (current) => {+ const active = assertProductionActive(current, runId, PROCESS_ID);+ if (active.documentCheckpoint?.directory !== current.composition?.document?.directory) throw new ServerError('The reviewed document changed before final render', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ },+ }).catch((error) => ({ error }));+ if (rendered.error) {+ await mutateProjectRecord(projectId, (current) => setProductionRender(current, runId, { status: 'failed', jobId: null, attemptId, error: rendered.error.message }));+ } else {+ const out = await mutateProjectRecord(projectId, (current) => setProductionRender(current, runId, { status: 'queued', jobId: rendered.jobId, attemptId }));+ if (out.run.status !== 'running') (await deps.render()).cancelRender(rendered.jobId);+ }+ continue;+ }+if (step.type === 'review') {const { startAutoReview } = await deps.autoReview();const started = await startAutoReview(projectId, {@@ -233,6 +377,7 @@ async function takeSteps(projectId, runId) {},reviewer: run.reviewer,productionRunId: runId,+ ...(run.authoring ? { documentRevisions: true } : {}),}).catch((err) => ({ error: err }));if (started.error) {const out = await halt(projectId, runId, { status: 'blocked', reason: `The draft review could not start: ${started.error.message}` });@@ -306,14 +451,16 @@ async function cancelOwnedJobs(runId, { includeRunning = false, jobIds = null }* Start a run (explicit director request). Every pool route must be eligible* now. Returns `{ project, run }`; the run advances in the background.*/-export async function startProduction(projectId, { directive, pool: requested, limits, reviewer }) {- await requireProject(projectId);- const pool = normalizeProductionPool(requested);+export async function startProduction(projectId, { directive, pool: requested, limits, reviewer, authoring: requestedAuthoring }) {+ const project = await requireProject(projectId);+ const assets = codeFirstProductionAssets(project);+ const authoring = assets ? await deps.resolveAuthoring(requestedAuthoring) : null;+ const pool = normalizeProductionPool(requested, { allowEmpty: !!assets });await assertPoolEligible(pool, await deps.loadEnv());// The autopilot cuts on the song (#9290) unless the director chose how it// cuts — set before the run captures its creative-setup basis.const out = await mutateProjectRecord(projectId, (current) => startProductionOnProject(withAutopilotCutting(current), {- directive, pool, limits, reviewer, processId: PROCESS_ID, pricing: poolPricing(pool, current),+ directive, pool, limits, reviewer, authoring, processId: PROCESS_ID, pricing: poolPricing(pool, current),}));console.log(`🎬 Music Video production ${short(out.run.id)} started: ${out.run.pool.length} allowed route(s), ≤${out.run.limits.maxGenerations} generations, ≤${out.run.limits.maxReviewAttempts} reviews`);advanceInBackground(projectId, out.run.id);@@ -326,13 +473,19 @@ export async function startProduction(projectId, { directive, pool: requested, l* paused review, and continue. Returns `{ project, run }`.*/export async function resumeProduction(projectId, runId, { limits, acceptBasis = false } = {}) {+ const before = await requireProject(projectId);+ const priorReviewId = findProductionRun(before, runId).reviewRunId;const jobs = await liveJobs();await mutateProjectRecord(projectId, (current) => reconcileProductionSteps(current, runId, jobs));const out = await mutateProjectRecord(projectId, (current) => resumeProductionOnProject(current, runId, { limits, acceptBasis, processId: PROCESS_ID }));+ if (priorReviewId && !out.run.reviewRunId) {+ const oldReview = before.autoReviews?.find((entry) => entry.id === priorReviewId);+ if (oldReview && ['running', 'stopped', 'limit-reached'].includes(oldReview.status)) await (await deps.autoReview()).cancelAutoReview(projectId, priorReviewId);+ }const review = out.run.reviewRunId? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId): null;- if (review && (review.status === 'stopped' || review.status === 'limit-reached')) {+ if (review && (review.status === 'stopped' || review.status === 'limit-reached' || (out.run.authoring && review.status === 'running'))) {const { resumeAutoReview } = await deps.autoReview();const headroom = Math.min(AUTO_REVIEW_MAX_GENERATIONS, review.usage.generations + remainingProductionGenerations(out.run));await resumeAutoReview(projectId, review.id, {@@ -366,6 +519,7 @@ export async function stopProduction(projectId, runId) {export async function cancelProduction(projectId, runId) {const out = await mutateProjectRecord(projectId, (current) => cancelProductionOnProject(current, runId));await cancelOwnedJobs(runId, { includeRunning: true });+ if (out.run.finalRender?.jobId) (await deps.render()).cancelRender(out.run.finalRender.jobId);const review = out.run.reviewRunId ? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId) : null;if (review && ['running', 'stopped', 'limit-reached'].includes(review.status)) {const { cancelAutoReview } = await deps.autoReview();@@ -411,7 +565,11 @@ async function onOwnedReviewAdvanced({ projectId, run: review, action } = {}) {if (!projectId || !review?.productionRunId) return;const project = await getProject(projectId);const run = project ? projectProductionRuns(project).find((r) => r.id === review.productionRunId) : null;- if (!runningHere(run)) return;+ if (!runningHere(run) || run.reviewRunId !== review.id) return;+ if (action?.type === 'revise-document' && run.authoring) {+ await advanceProduction(projectId, run.id);+ return;+ }if (action?.type === 'generate' && review.status === 'running' && action.sections?.length) {for (const section of action.sections) {const stepKind = section.kind === 'image' ? 'frame' : 'clip';@@ -471,3 +629,11 @@ function armJobListeners() {console.error(`❌ Music Video production could not watch generation jobs: ${err.message}`);});}++// Internal final-render event: settle only this run, and never advance a run+// pinned to an older process after a restart.+musicVideoEvents.on('document-render', guarded('its final document rendered', async ({ projectId, runId, jobId, status, error, attemptId }) => {+ if (!projectId || !runId) return;+ const out = await mutateProjectRecord(projectId, (current) => setProductionRender(current, runId, { jobId, status, error, attemptId }));+ if (runningHere(out.run)) await advanceProduction(projectId, runId);+}));diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 7cbbfbcac7..be824b3876 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -135,6 +135,10 @@ beforeEach(() => {planProject,startCastAndSets,autoReview: async () => autoReview,+ resolveAuthoring: async (input) => {+ if (!input?.providerId || !input?.model) throw Object.assign(new Error('Select an authoring model'), { code: 'PRODUCTION_AUTHORING_REQUIRED' });+ return { ...input, costUsd: 0 };+ },releaseRevisionSection: vi.fn(async () => {}),});});@@ -482,7 +486,7 @@ describe('music video production run (#9066)', () => {it('does not start a code-first document run through legacy frame and clip lanes', async () => {seedProject({ composition: { mode: 'document' }, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } });await expect(service.startProduction('mv-example', { pool: POOL, limits: LIMITS }))- .rejects.toMatchObject({ code: 'PRODUCTION_CODE_FIRST_NOT_READY' });+ .rejects.toMatchObject({ code: 'PRODUCTION_AUTHORING_REQUIRED' });expect(dispatch).not.toHaveBeenCalled();});@@ -506,7 +510,7 @@ describe('music video production run (#9066)', () => {expect(theRun()).toMatchObject({ status: 'blocked', usage: { generations: 0 } });expect(theRun().steps[0]).toMatchObject({ status: 'refused', error: expect.stringMatching(/policy|plan/i) });await expect(service.resumeProduction('mv-example', theRun().id, { acceptBasis: true }))- .rejects.toMatchObject({ code: 'PRODUCTION_CODE_FIRST_NOT_READY' });+ .rejects.toMatchObject({ code: 'PRODUCTION_AUTHORING_REQUIRED' });});it('keeps pre-upgrade legacy run checksums valid after adding the policy-aware basis', async () => {@@ -530,3 +534,303 @@ describe('music video production run (#9066)', () => {expect(theRun().basis).not.toHaveProperty('version');});});++// The real state machine/pool run against controlled authors and encoders;+// collaborators must honor the same publication/submission guards as providers.+const AUTHORING = { providerId: 'local-fixture', model: 'fixture-model' };+const authorProvider = { id: AUTHORING.providerId, type: 'api', endpoint: 'http://localhost:11434' };+const storeMutation = async (transform) => (await import('./projects.js')).mutateProjectRecord('mv-example', transform);+function seedCodeFirst({ scenes, directions, percent = 0, ...patch } = {}) {+ return seedProject({ composition: { mode: 'document' },+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: percent },+ scenes: scenes || [{ sceneId: 'mvs-code', label: 'Code', startSec: 0, endSec: 8 }],+ treatment: { shotDirections: directions || [{ sceneId: 'mvs-code', medium: 'procedural', mediumRationale: 'Typography' }] }, ...patch,+ });+}+function documentDoubles() {+ let version = 0;+ const author = vi.fn(async (_id, input) => {+ await input.beforeSubmit({ provider: authorProvider, model: AUTHORING.model });+ return storeMutation((project) => {+ input.verifyCurrent(project);+ const document = { directory: `music-video/mv-example/composition/doc-${version += 1}`, source: { kind: 'generated' } };+ return { project: { ...project, composition: { ...project.composition, documentDraft: document } }, document };+ });+ });+ const regenerate = vi.fn(async (id, _sectionId, input) => author(id, input));+ const accept = vi.fn(async (_id, directory, options) => storeMutation((project) => {+ options.verifyCurrent(project);+ if (project.composition.documentDraft?.directory !== directory) throw new Error('stale candidate');+ const { documentDraft, ...composition } = project.composition;+ return { project: { ...project, composition: { ...composition, document: documentDraft } }, document: documentDraft };+ }));+ const documents = { generateMixedMediaDocument: author, regenerateMixedMediaSection: regenerate, acceptMixedMediaDocument: accept,+ readMixedMediaCandidate: async () => ({ stale: false, source: current().composition.documentDraft || current().composition.document, sections: [+ { id: 'verse', startSec: 0, endSec: 4 }, { id: 'hook', startSec: 4, endSec: 8 },+ ] }),+ };+ const render = vi.fn(async (_id, options) => { options.verifyCurrent(current()); return { jobId: 'final-render' }; });+ const cancelRender = vi.fn();+ service.__setProductionDepsForTests({ loadEnv: async () => env, dispatch, queue: async () => queue,+ autoReview: async () => autoReview, documents: async () => documents,+ render: async () => ({ renderMusicVideo: render, cancelRender }),+ resolveAuthoring: async (input) => {+ if (!input?.providerId) throw Object.assign(new Error('Select an authoring model'), { code: 'PRODUCTION_AUTHORING_REQUIRED' });+ return { ...input, costUsd: 0 };+ },+ });+ return { author, regenerate, accept, render, cancelRender };+}+function passOwnedReview() {+ const project = store.get('mv-example');+ const review = project.autoReviews[0];+ review.status = 'passed';+ musicVideoEvents.emit('auto-review', { projectId: project.id, run: clone(review), action: { type: 'idle' } });+}+function failOwnedReview(atSec = 6) {+ const review = store.get('mv-example').autoReviews[0];+ Object.assign(review, { startSec: 0, attempts: [{ n: 1, review: { verdict: 'revise', findings: [{ severity: 'blocking', atSec, note: 'Type transition jumps' }] } }] });+ musicVideoEvents.emit('auto-review', { projectId: 'mv-example', run: clone(review), action: { type: 'revise-document' } });+}++describe('code-first production execution (#9301)', () => {+ it('authors a code-only plan with no media routes/jobs and completes only after its reviewed final render', async () => {+ seedCodeFirst(); const { author, render } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING });+ expect(jobs).toEqual([]); expect(dispatch).not.toHaveBeenCalled(); expect(author).toHaveBeenCalledOnce();+ expect(theRun()).toMatchObject({ usage: { generations: 1, spentUsd: 0 }, documentCheckpoint: { directory: current().composition.document.directory } });+ expect(startAutoReview.mock.calls[0][1]).toMatchObject({ documentRevisions: true, startSec: 0, endSec: 8 });+ passOwnedReview(); await settle();+ expect(render).toHaveBeenCalledOnce(); expect(theRun().status).toBe('running');+ musicVideoEvents.emit('document-render', { projectId: 'mv-example', runId: theRun().id, jobId: 'final-render', attemptId: theRun().finalRender.attemptId, status: 'completed' });+ await settle(); expect(theRun().status).toBe('completed');+ });++ it('prepares only missing selected still/footage assets and reuses imported takes', async () => {+ seedCodeFirst({ percent: 50,+ scenes: [{ sceneId: 'code', startSec: 0, endSec: 1 }, { sceneId: 'still', startSec: 1, endSec: 2, framePrompt: 'still' },+ { sceneId: 'imported', startSec: 2, endSec: 4, videoHistoryId: 'imported-take' },+ { sceneId: 'generated', startSec: 4, endSec: 8, framePrompt: 'frame', prompt: 'motion' }],+ directions: ['procedural', 'still', 'existing-footage', 'generated-footage'].map((medium, index) => ({ sceneId: ['code', 'still', 'imported', 'generated'][index], medium, mediumRationale: 'Selected look' })),+ });+ const { author } = documentDoubles();+ await start({ pool: [POOL[0], POOL[2]], authoring: AUTHORING });+ expect(dispatch.mock.calls.map(([args]) => [args.stepKind, args.scene.sceneId])).toEqual([['frame', 'still'], ['frame', 'generated']]);+ completeJob('job-1'); completeJob('job-2'); await settle();+ expect(dispatch.mock.calls.at(-1)[0]).toMatchObject({ stepKind: 'clip', scene: { sceneId: 'generated' } });+ expect(theRun().steps.at(-1).editInterval).toEqual({ startSec: 4, endSec: 8 });+ completeJob('job-3'); await settle();+ expect(author).toHaveBeenCalledOnce(); expect(current().scenes[2].videoHistoryId).toBe('imported-take');+ expect(theRun().usage.generations).toBe(4);+ });++ it('refuses over-allowance and missing-import plans before any provider submission', async () => {+ seedCodeFirst({ directions: [{ sceneId: 'mvs-code', medium: 'generated-footage', mediumRationale: 'Motion' }] });+ const { author } = documentDoubles();+ await expect(start({ pool: [], authoring: AUTHORING })).rejects.toMatchObject({ code: 'PRODUCTION_MEDIUM_CONFLICT' });+ expect(dispatch).not.toHaveBeenCalled(); expect(author).not.toHaveBeenCalled();+ seedCodeFirst({ directions: [{ sceneId: 'mvs-code', medium: 'existing-footage', mediumRationale: 'Imported' }] });+ await expect(start({ pool: POOL, authoring: AUTHORING })).rejects.toMatchObject({ code: 'PRODUCTION_MEDIUM_CONFLICT' });+ });++ it('refuses an approved performance disguised by a legacy card layer before any provider call', async () => {+ seedCodeFirst({ percent: 100,+ scenes: [{ sceneId: 'mvs-code', shotMode: 'performance', visualLayer: 'card', startSec: 0, endSec: 8 }],+ directions: [{ sceneId: 'mvs-code', mode: 'performance', medium: 'generated-footage', mediumRationale: 'Sung performance' }],+ });+ const { author } = documentDoubles();+ await expect(start({ pool: POOL, authoring: AUTHORING })).rejects.toMatchObject({ code: 'PRODUCTION_MEDIUM_CONFLICT' });+ expect(dispatch).not.toHaveBeenCalled(); expect(author).not.toHaveBeenCalled();+ });++ it('revises only the failed code section while retaining selected assets and a zero video allowance', async () => {+ seedCodeFirst(); const { regenerate } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING });+ failOwnedReview(); await settle();+ expect(regenerate).toHaveBeenCalledOnce(); expect(regenerate.mock.calls[0][1]).toBe('hook');+ expect(theRun().usage.generations).toBe(2); expect(jobs).toEqual([]);+ expect(current().productionPolicy.maxGeneratedVideoPercent).toBe(0);+ expect(current().autoReviews[0].attempts.at(-1)).toMatchObject({ n: 2, excerptId: null });+ });++ it('halts a review-driven code revision before a provider call past the generation cap', async () => {+ seedCodeFirst(); const { author } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING, limits: { maxGenerations: 1, maxReviewAttempts: 2 } });+ let submitted = 0;+ author.mockImplementationOnce(async (_id, input) => { await input.beforeSubmit({ provider: authorProvider, model: AUTHORING.model }); submitted += 1; });+ failOwnedReview(); await settle();+ expect(submitted).toBe(0); expect(theRun().usage.generations).toBe(1); expect(theRun().status).toBe('limit-reached');+ });++ it('refuses an unpriced author at the actual submission boundary under a dollar cap', async () => {+ seedCodeFirst(); const { author } = documentDoubles();+ let submitted = 0;+ author.mockImplementationOnce(async (_id, input) => {+ await input.beforeSubmit({ provider: { ...authorProvider, endpoint: 'https://api.example.com/v1' }, model: AUTHORING.model });+ submitted += 1;+ });+ await start({ pool: [], authoring: AUTHORING, limits: { ...LIMITS, spendCapUsd: 1 } });+ expect(submitted).toBe(0); expect(theRun()).toMatchObject({ status: 'blocked', usage: { generations: 0, spentUsd: 0 } });+ expect(theRun().stopReason).toMatch(/no known price/);+ });++ it('does not accept a completed revision after its owning review stops', async () => {+ seedCodeFirst(); const { accept } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING });+ const selected = current().composition.document.directory;+ const normal = accept.getMockImplementation();+ accept.mockImplementationOnce(async (...args) => {+ store.get('mv-example').autoReviews[0].status = 'stopped';+ return normal(...args);+ });+ failOwnedReview(); await settle();+ expect(current().composition.document.directory).toBe(selected);+ expect(current().composition.documentDraft.directory).not.toBe(selected);+ expect(theRun().usage.generations).toBe(2);+ expect(theRun().status).toBe('blocked');+ });++ it('does not submit late authoring after cancellation during preparation', async () => {+ seedCodeFirst(); const { author } = documentDoubles();+ let release; const waiting = new Promise((resolve) => { release = resolve; });+ const normal = author.getMockImplementation();+ author.mockImplementationOnce(async (id, input) => { await waiting; return normal(id, input); });+ await service.startProduction('mv-example', { pool: [], authoring: AUTHORING, limits: LIMITS });+ await new Promise((resolve) => setTimeout(resolve, 0));+ await service.cancelProduction('mv-example', theRun().id);+ release(); await settle();+ expect(theRun().status).toBe('canceled'); expect(theRun().usage.generations).toBe(0);+ expect(current().composition.documentDraft).toBeUndefined();+ });++ it('drops a paid authoring result when the policy changes before publication', async () => {+ seedCodeFirst(); const { author } = documentDoubles();+ let release; const waiting = new Promise((resolve) => { release = resolve; });+ author.mockImplementationOnce(async (_id, input) => {+ await input.beforeSubmit({ provider: authorProvider, model: AUTHORING.model }); await waiting;+ await storeMutation((project) => { input.verifyCurrent(project); return { project }; });+ });+ await service.startProduction('mv-example', { pool: [], authoring: AUTHORING, limits: LIMITS });+ await new Promise((resolve) => setTimeout(resolve, 0));+ store.get('mv-example').productionPolicy.maxGeneratedVideoPercent = 5;+ release(); await settle();+ expect(current().composition.document).toBeUndefined(); expect(theRun().usage.generations).toBe(1);+ expect(theRun().steps[0].status).toBe('failed');+ });++ it('retains a fast final-render terminal event when its queue link arrives later', async () => {+ seedCodeFirst(); const { render } = documentDoubles();+ render.mockImplementationOnce(async () => {+ musicVideoEvents.emit('document-render', { projectId: 'mv-example', runId: theRun().id, jobId: 'fast-render', attemptId: theRun().finalRender.attemptId, status: 'completed' });+ await new Promise((resolve) => setTimeout(resolve, 0)); return { jobId: 'fast-render' };+ });+ await start({ pool: [], authoring: AUTHORING }); passOwnedReview(); await settle();+ expect(theRun()).toMatchObject({ status: 'completed', finalRender: { status: 'completed', jobId: 'fast-render' } });+ });++ it('refuses a replaced selected document before final render', async () => {+ seedCodeFirst(); const { render } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING });+ store.get('mv-example').composition.document.directory = 'music-video/mv-example/composition/doc-replaced';+ passOwnedReview(); await settle();+ expect(render).not.toHaveBeenCalled(); expect(theRun().status).toBe('needs-replan');+ });++ it('stops a pending final-render preparation before encoding', async () => {+ seedCodeFirst(); const { render } = documentDoubles();+ let release; const waiting = new Promise((resolve) => { release = resolve; });+ let encoded = 0;+ render.mockImplementationOnce(async (_id, options) => { await waiting; options.verifyCurrent(current()); encoded += 1; return { jobId: 'late-render' }; });+ await start({ pool: [], authoring: AUTHORING }); passOwnedReview();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await service.stopProduction('mv-example', theRun().id); release(); await settle();+ expect(encoded).toBe(0); expect(theRun().status).toBe('stopped');+ });+});++it('rechecks a generated shot and zero allowance after asynchronous provider preparation', async () => {+ seedCodeFirst({ percent: 100,+ scenes: [{ sceneId: 'mvs-a', startSec: 0, endSec: 8, referenceImageId: 'frame.png', prompt: 'move' }],+ directions: [{ sceneId: 'mvs-a', medium: 'generated-footage', mediumRationale: 'Selected exception' }],+ });+ documentDoubles();+ let release; const waiting = new Promise((resolve) => { release = resolve; });+ dispatch.mockImplementationOnce(async (args) => {+ await waiting;+ await service.assertProductionSubmission('mv-example', args.tag.productionRunId, args.tag.productionStepKey, { sceneId: 'mvs-a', kind: 'video' });+ return enqueueing(args);+ });+ await service.startProduction('mv-example', { pool: [POOL[2]], authoring: AUTHORING, limits: LIMITS });+ await new Promise((resolve) => setTimeout(resolve, 0));+ store.get('mv-example').productionPolicy.maxGeneratedVideoPercent = 0;+ release(); await settle();+ expect(jobs).toHaveLength(0); expect(theRun().usage.generations).toBe(0);+ expect(theRun().steps[0].status).toBe('refused');+});++it('charges a selected performance retry by its actual padded provider duration without adding edit share', async () => {+ seedCodeFirst({ percent: 100, videoSettings: { backend: 'fal', falModelId: 'minimax/h3-max/image-to-video' },+ audioAnalysis: { durationSec: 30, sections: [{ startSec: 0, endSec: 30 }] },+ scenes: [{ sceneId: 'performance', shotMode: 'performance', startSec: 0, endSec: 4, referenceImageId: 'frame.png', prompt: 'perform' }],+ directions: [{ sceneId: 'performance', medium: 'generated-footage', mediumRationale: 'Sung performance' }],+ });+ documentDoubles();+ const usable = env.isVideoModeUsable;+ env.isVideoModeUsable = (_settings, mode) => mode === 'fal';+ try {+ await start({ pool: [{ kind: 'video', mode: 'fal' }], authoring: AUTHORING, limits: { ...LIMITS, spendCapUsd: 1.7 } });+ const job = jobs[0]; job.status = 'failed'; mediaJobEvents.emit('failed', job); await settle();+ const clips = theRun().steps.filter((step) => step.kind === 'clip');+ expect(clips).toHaveLength(2);+ expect(clips.map((step) => step.costUsd)).toEqual([0.808, 0.808]);+ expect(clips.map((step) => step.editInterval)).toEqual([{ startSec: 0, endSec: 4 }, { startSec: 0, endSec: 4 }]);+ jobs[1].status = 'failed'; mediaJobEvents.emit('failed', jobs[1]); await settle();+ // Explicit resume resets slot failure count, but the paid retry budget stays spent.+ await service.resumeProduction('mv-example', theRun().id); await settle();+ expect(jobs).toHaveLength(2); expect(theRun()).toMatchObject({ status: 'limit-reached', usage: { generations: 2, spentUsd: 1.616 } });+ } finally { env.isVideoModeUsable = usable; }+});++it.each([1_000, 120_000])('keeps interrupted authoring charged at %i ms without a queue job and requires explicit resume', async (reservationAge) => {+ seedCodeFirst(); const { author } = documentDoubles();+ let release; const waiting = new Promise((resolve) => { release = resolve; });+ author.mockImplementationOnce(async (_id, input) => {+ await input.beforeSubmit({ provider: authorProvider, model: AUTHORING.model }); await waiting;+ input.verifyCurrent(current());+ });+ await service.startProduction('mv-example', { pool: [], authoring: AUTHORING, limits: LIMITS });+ await new Promise((resolve) => setTimeout(resolve, 0));+ store.get('mv-example').productionRuns[0].processId = 'previous-process';+ release(); await settle();+ expect(author).toHaveBeenCalledOnce(); expect(current().composition.document).toBeUndefined();+ expect(theRun().usage.generations).toBe(1);+ // Persisted submission intent after a crash is not refundable even past the queue lease.+ store.get('mv-example').productionRuns[0].steps[0].status = 'reserved';+ store.get('mv-example').productionRuns[0].steps[0].reservedAt = new Date(Date.now() - reservationAge).toISOString();+ await service.resumeProduction('mv-example', theRun().id); await settle();+ expect(author).toHaveBeenCalledTimes(2); expect(theRun().usage.generations).toBe(2);+});++it('ignores an earlier failed render attempt completion after explicit retry', async () => {+ seedCodeFirst(); documentDoubles();+ await start({ pool: [], authoring: AUTHORING }); passOwnedReview(); await settle();+ const oldAttempt = theRun().finalRender.attemptId;+ musicVideoEvents.emit('document-render', { projectId: 'mv-example', runId: theRun().id, jobId: 'final-render', attemptId: oldAttempt, status: 'failed', error: 'encoder failed' });+ await settle(); expect(theRun().status).toBe('blocked');+ await service.resumeProduction('mv-example', theRun().id); await settle();+ expect(theRun().finalRender.attemptId).not.toBe(oldAttempt);+ musicVideoEvents.emit('document-render', { projectId: 'mv-example', runId: theRun().id, jobId: 'final-render', attemptId: oldAttempt, status: 'completed' });+ await settle(); expect(theRun().status).toBe('running');+ expect(theRun().finalRender.status).toBe('queued');+});++it('requires reauthoring and a new review after an accepted policy/selected-asset change', async () => {+ seedCodeFirst(); const { author } = documentDoubles();+ await start({ pool: [], authoring: AUTHORING });+ store.get('mv-example').scenes[0].referenceImageId = 'new-selection.png';+ await settle(); expect(theRun().status).toBe('needs-replan');+ await service.resumeProduction('mv-example', theRun().id, { acceptBasis: true }); await settle();+ expect(author).toHaveBeenCalledTimes(2);+ expect(autoReview.cancelAutoReview).toHaveBeenCalledWith('mv-example', 'mvar-example');+ expect(theRun().documentCheckpoint.directory).toBe(current().composition.document.directory);+});diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.jsindex b3cc09740a..8591b574a5 100644--- a/server/services/musicVideo/render.document.test.js+++ b/server/services/musicVideo/render.document.test.js@@ -41,6 +41,23 @@ async function documentProject() {}describe('composition-document render plan', () => {+ it('checks owning production after preparation and again before encoding, releasing refused render slots', async () => {+ const id = await documentProject();+ await importDocumentTemplate(id);+ encodeDocumentComposition.mockClear();+ const refused = () => { throw Object.assign(new Error('Production stopped'), { code: 'PRODUCTION_NOT_RUNNING' }); };+ await expect(renderMusicVideo(id, { verifyCurrent: refused })).rejects.toMatchObject({ code: 'PRODUCTION_NOT_RUNNING' });+ expect(encodeDocumentComposition).not.toHaveBeenCalled();+ let checks = 0;+ await renderMusicVideo(id, { verifyCurrent: () => { if (++checks === 2) refused(); } });+ await vi.waitFor(async () => expect((await projects.getProject(id)).status).toBe('failed'));+ expect(checks).toBe(2);+ expect(encodeDocumentComposition).not.toHaveBeenCalled();+ // Both preparation and asynchronous encode refusal release the per-project slot.+ await renderMusicVideo(id);+ await vi.waitFor(() => expect(encodeDocumentComposition).toHaveBeenCalledOnce());+ });+it('refuses a full render and an excerpt while no document is attached, and releases both slots', async () => {const id = await documentProject();for (let attempt = 0; attempt < 2; attempt++) {diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex e75e42d28a..b52864a41f 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -45,6 +45,7 @@ import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.jimport { assertCurrentPerformanceTakes } from './performanceShot.js';import { ensureInstanceId } from '../instanceIdentity.js';import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';+import { musicVideoEvents } from './events.js';import { projectSoundBed } from './soundBed.js';import { intercutClips } from './intercut.js';@@ -666,7 +667,7 @@ const SEEKED_RENDERERS = Object.freeze({/** The seeked renderer for a project's render mode, or null for footage modes. */export const seekedRendererFor = (project) => SEEKED_RENDERERS[project?.composition?.mode] || null;-async function renderSeekedMode(projectId, project, handOff, renderer) {+async function renderSeekedMode(projectId, project, handOff, renderer, options = {}) {const plan = await renderer.prepare(project);// Resolve the master before any rendering mark. A missing track throws here// and the caller releases the pending slot without leaving a job running.@@ -676,6 +677,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer) {await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);const renderingOn = await ensureInstanceId();+ if (options.verifyCurrent) options.verifyCurrent(await getProject(projectId));const jobId = randomUUID();const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;const outputPath = join(PATHS.videos, filename);@@ -698,12 +700,17 @@ async function renderSeekedMode(projectId, project, handOff, renderer) {await updateProject(projectId, settledRender(patch.status, patch.extra || {})).catch((err) => {console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);});+ if (options.productionRunId) musicVideoEvents.emit('document-render', { projectId, runId: options.productionRunId, attemptId: options.productionRenderAttemptId, jobId, status: patch.status === 'complete' ? 'completed' : 'failed', error: job.lastError || null });closeJobAfterDelay(jobs, jobId);};- Promise.resolve().then(() => renderer.encode({- plan, project, projectId, jobId, audioPath, soundBed, outputPath, signal,- onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),- })).then(async (encoded) => {+ Promise.resolve().then(async () => {+ if (options.verifyCurrent) options.verifyCurrent(await getProject(projectId));+ if (signal.aborted) throw Object.assign(new Error('Render cancelled'), { code: 'CANCELED' });+ return renderer.encode({+ plan, project, projectId, jobId, audioPath, soundBed, outputPath, signal,+ onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),+ });+ }).then(async (encoded) => {job.overlayAbort = null;job.status = 'complete';let proof = null;@@ -770,7 +777,7 @@ export async function renderMusicVideo(projectId, options = {}) {try {const seeked = seekedRendererFor(project);if (seeked) {- return await renderSeekedMode(projectId, project, () => { handedOff = true; }, seeked);+ return await renderSeekedMode(projectId, project, () => { handedOff = true; }, seeked, options);}const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 1802aaf04a..57eb7dc04f 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -587,6 +587,10 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* TUI run has been registered as an attachable shell session.* @param {(runId:string)=>void} [args.onRunSettled] — called when that concrete* attempt resolves or rejects. Observational; callback errors are ignored.+ * @param {(meta:object)=>Promise<void>} [args.beforeExecute] — enforced caller+ * admission immediately before provider dispatch, after concurrency/readiness+ * and attachment preparation. A rejection cancels this attempt without+ * retrying, benching the provider, or investigating a provider failure.* @param {string[]} [args.screenshots] — image paths for a vision/multimodal* call (relative to the runner's screenshots dir, or absolute). API providers* base64-encode each into `image_url` blocks. Codex and Claude Code CLI@@ -1387,6 +1391,7 @@ async function executeProviderRunOnce({onRunCreated,onRunReady,onRunSettled,+ beforeExecute,timeout: timeoutOverride,absoluteTimeoutMs,maxTokens,@@ -1555,6 +1560,16 @@ async function executeProviderRunOnce({let text = '';let settled = false;let apiTimeoutHandle = null;+ let dispatchRefusal = null;+ const admitDispatch = typeof beforeExecute === 'function' ? async () => {+ try {+ await beforeExecute({ runId, provider: effectiveProvider, model: effectiveModel });+ } catch (error) {+ dispatchRefusal = error instanceof Error ? error : new Error(String(error));+ dispatchRefusal.canceled = true;+ throw dispatchRefusal;+ }+ } : undefined;const safeResolve = (value) => { if (!settled) { settled = true; if (apiTimeoutHandle) clearTimeout(apiTimeoutHandle); resolve(value); } };const safeReject = (err) => {@@ -1587,6 +1602,7 @@ async function executeProviderRunOnce({// explicit `success === false`. Per-site drift was the bug.const labelByType = { cli: 'CLI', api: 'API', tui: 'TUI' };const onComplete = (result) => {+ if (dispatchRefusal) { safeReject(dispatchRefusal); return; }if (result?.error || result?.success === false) {const err = new Error(result?.error || `${labelByType[effectiveProvider.type] || effectiveProvider.type} execution failed`);if (result?.canceled === true) {@@ -1658,7 +1674,7 @@ async function executeProviderRunOnce({}if (effectiveProvider.type === PROVIDER_TYPES.CLI) {- executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout, toolFree }).catch(safeReject);+ executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout, toolFree, ...(admitDispatch ? { beforeExecute: admitDispatch } : {}) }).catch(safeReject);} else if (effectiveProvider.type === PROVIDER_TYPES.API) {// API runs take model as a first-class arg — no clone needed. The// toolkit's executeApiRun now owns the primary wall-clock timeout (it@@ -1693,12 +1709,12 @@ async function executeProviderRunOnce({// a per-call override (e.g. the importer's long stage timeout) governs the// ceiling instead of the runner's provider/default fallback — same// caller-override precedence CLI/TUI runs already get.- executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout, absoluteTimeoutMs, maxTokens }).catch(safeReject);+ executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout, absoluteTimeoutMs, maxTokens, ...(admitDispatch ? { beforeExecute: admitDispatch } : {}) }).catch(safeReject);} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,// interactive view this TUI run surfaces in the Shell page.import('./tuiPromptRunner.js')- .then(({ executeTuiRun }) => executeTuiRun({ runId, provider: providerForRun, prompt, screenshots, workspacePath: effectiveCwd, onData, onComplete, onReady: onRunReady, timeout: effectiveTimeout, label: source }))+ .then(({ executeTuiRun }) => executeTuiRun({ runId, provider: providerForRun, prompt, screenshots, workspacePath: effectiveCwd, onData, onComplete, onReady: onRunReady, timeout: effectiveTimeout, label: source, ...(admitDispatch ? { beforeExecute: admitDispatch } : {}) })).catch(safeReject);} else {safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex 8aa32a82e5..8b856e285c 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -1078,6 +1078,33 @@ describe('promptRunner — retry-with-fallback', () => {return { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider };}+ it('refuses a stopped caller after local concurrency wait without provider fallback, benching, or escalation', async () => {+ const status = mockToolkitWithFallback();+ const local = apiProvider({ id: 'local-guard', endpoint: 'http://localhost:11434/v1' });+ let release;+ const waiting = new Promise((resolve) => { release = resolve; });+ let invoked = 0;+ runner.executeApiRun.mockImplementation(async ({ beforeExecute, onComplete }) => {+ if (beforeExecute) await beforeExecute();+ invoked += 1;+ await waiting;+ onComplete({ success: true });+ });+ const first = runPromptThroughProvider({ provider: local, prompt: 'first', source: 'test' });+ await vi.waitFor(() => expect(invoked).toBe(1));+ let active = true;+ const beforeExecute = vi.fn(() => { if (!active) throw Object.assign(new Error('Production stopped'), { code: 'PRODUCTION_NOT_RUNNING' }); });+ const second = expect(runPromptThroughProvider({ provider: local, prompt: 'second', source: 'test', beforeExecute }))+ .rejects.toMatchObject({ code: 'PRODUCTION_NOT_RUNNING', canceled: true });+ active = false;+ expect(beforeExecute).not.toHaveBeenCalled();+ release(); await first; await second;+ expect(invoked).toBe(1);+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ });+it('keeps an exact provider pin and skips every fallback tier when disabled', async () => {const status = mockToolkitWithFallback();runner.executeCliRun.mockImplementation(async ({ onComplete }) => {diff --git a/server/services/runner.js b/server/services/runner.jsindex f8776dc68f..876fc9ac75 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -323,7 +323,7 @@ const describeSpawnFailure = (spawnError, command) =>* `.cmd`/`.bat` spawn under `shell:false` fails outright post-CVE-2024-27980,* and why the `cmd.exe` wrapper avoids DEP0190's unescaped-join hazard).*/-export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout, toolFree = false }) {+export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout, toolFree = false, beforeExecute }) {const toolkit = requireToolkit();const runsPath = join(runnerConfig.dataDir, 'runs');@@ -436,6 +436,17 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scconst { command: spawnCommand, args: spawnArgs, wrapped } = resolveCliSpawn(provider, runCommand, args, childEnv);processGroup = needsProcessGroup(wrapped);+ if (beforeExecute) {+ try { await beforeExecute(); }+ catch (error) {+ cleanupPromptFile();+ await cleanupVisionFiles().catch(() => {});+ await finalizeRunRecord({ runId, output: '', exitCode: 1, success: false, error: error.message, startTime,+ extras: { canceled: true, completionReason: 'canceled' } });+ throw error;+ }+ }+childProcess = spawn(spawnCommand, spawnArgs, {cwd: runCwd,env: childEnv,diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex f7704ece9a..b3ba9ca0cc 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -444,6 +444,17 @@ describe('executeCliRun — wall-clock timeout classification', () => {});describe('executeCliRun — intentional cancellation', () => {+ it('refuses a stopped caller after CLI preparation before spawning and files a canceled run', async () => {+ const onRunFailed = vi.fn(); const onRunCanceled = vi.fn();+ setAIToolkit(fakeToolkit({ analyzeError }), { dataDir: '/tmp/test-runner', hooks: { onRunFailed, onRunCanceled } });+ await expect(executeCliRun({ runId: 'run-admission', provider: { id: 'codex', type: 'cli', command: 'codex', args: [] },+ prompt: 'hello', workspacePath: TEST_WORKSPACE, beforeExecute: () => { throw new Error('Production stopped'); } }))+ .rejects.toThrow('Production stopped');+ expect(spawn).not.toHaveBeenCalled();+ expect(onRunCanceled).toHaveBeenCalledOnce(); expect(onRunFailed).not.toHaveBeenCalled();+ expect(atomicWrite).toHaveBeenCalledWith(expect.stringContaining('metadata.json'), expect.objectContaining({ canceled: true, errorCategory: ERROR_CATEGORIES.CANCELED }));+ });+it.each([1, 0])('handles shutdown exit %i without a Node signal or provider penalty', async (exitCode) => {const child = makeChild();spawn.mockReturnValue(child);diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex c6717936fd..aa61d55e8d 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -154,7 +154,7 @@ const PTY_ROWS = 50;* it reports itself, not a provider incident for the autofixer to escalate.* @returns {Promise<void>}*/-export async function executeTuiRun({ runId, provider, prompt, screenshots = [], workspacePath, onData, onComplete, onReady, timeout, idleMs, label, guard = false, reportFailure = true }) {+export async function executeTuiRun({ runId, provider, prompt, screenshots = [], workspacePath, onData, onComplete, onReady, timeout, idleMs, label, guard = false, reportFailure = true, beforeExecute }) {if (!provider || typeof provider !== 'object') {throw new Error('executeTuiRun: provider is required');}@@ -299,6 +299,14 @@ ${prompt}`;}let ptyProcess;+ if (beforeExecute) {+ try { await beforeExecute(); }+ catch (error) {+ await finalizeRunRecord({ runId, output: '', exitCode: 1, success: false, error: error.message, startTime: Date.now(),+ extras: { canceled: true, completionReason: 'canceled' }, identity: runIdentity });+ throw error;+ }+ }try {ptyProcess = ptySpawn(spawnCommand, spawnArgs, {name: 'xterm-256color',diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.jsindex 055306dd3d..ef004d5d21 100644--- a/server/services/tuiPromptRunner.test.js+++ b/server/services/tuiPromptRunner.test.js@@ -373,6 +373,14 @@ describe('executeTuiRun', () => {});describe('input validation', () => {+ it('settles a caller admission refusal before spawning the prepared TUI', async () => {+ await expect(executeTuiRun({ runId: 'run-admission', provider: { id: 'example-tui', type: 'tui', command: 'codex', args: [] },+ prompt: 'hello', workspacePath: TEST_WORKSPACE, beforeExecute: () => { throw new Error('Production stopped'); } }))+ .rejects.toThrow('Production stopped');+ expect(ptySpawnMock).not.toHaveBeenCalled();+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({ extras: { canceled: true, completionReason: 'canceled' } }));+ });+it('throws when provider is missing', async () => {await expect(executeTuiRun({ runId: 'run-x', provider: null, prompt: 'prompt', workspacePath: '/tmp' })).rejects.toThrow(/provider is required/);diff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 4849f792ba..e4cb0187e6 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -193,7 +193,7 @@ export async function describeImageViaCli({* @returns {Promise<{ text:string, finishReason:null, usage:null, reasoning:string }>}*/export async function describeImagesFromPaths({- provider, imagePaths, prompt, model, effort, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn,+ provider, imagePaths, prompt, model, effort, timeout = CLI_VISION_TIMEOUT_MS, spawnImpl = spawn, beforeExecute,}) {const visionModel = model || provider?.defaultModel || null;const prepared = await prepareCliVisionRun({ provider, imagePaths, prompt, model: visionModel, effort });@@ -201,6 +201,7 @@ export async function describeImagesFromPaths({try {const text = await runCliVisionSpawn({provider, model: visionModel, invocation: prepared.invocation, timeout, spawnImpl,+ beforeExecute,setCleanup: (fn) => { cleanupPromptFile = fn; },});return { text, finishReason: null, usage: null, reasoning: '' };@@ -212,7 +213,7 @@ export async function describeImagesFromPaths({// Shared spawn for the two public CLI-vision entry points. `setCleanup` receives// the prompt-file cleanup from prepareCliPrompt (Grok-on-Windows temp file).-async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnImpl, setCleanup }) {+async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnImpl, setCleanup, beforeExecute }) {const { command, args, stdin, cwd } = invocation;// Deliver the prompt per provider convention: antigravity as the --print// VALUE (agy doesn't read stdin); grok's --prompt-file /dev/stdin via stdin@@ -252,6 +253,7 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnIm// kills below must signal the whole process group (#7496). False — and so// byte-identical to today — for every unwrapped provider.const processGroup = needsProcessGroup(wrapped);+ if (beforeExecute) await beforeExecute();const text = await new Promise((resolve, reject) => {const child = spawnImpl(spawnCommand, spawnArgs, {diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.jsindex 97f4f175cb..a56d50f7a4 100644--- a/server/services/visionCli.test.js+++ b/server/services/visionCli.test.js@@ -26,6 +26,7 @@ const {buildCliVisionInvocation,prepareCliVisionRun,describeImageViaCli,+ describeImagesFromPaths,} = await import('./visionCli.js');const { resolveWindowsExecutable, prepareWindowsSafeSpawn } = await import('../lib/bufferedSpawn.js');@@ -37,6 +38,17 @@ const EXPECT_GROUP = process.platform !== 'win32';const PNG_DATA_URL = `data:image/png;base64,${Buffer.from('fake-png').toString('base64')}`;+it('refuses stopped production after vision attachments are staged without spawning', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'vision-admission-'));+ try {+ const path = join(dir, 'frame.png'); await writeFile(path, 'fake-png');+ const spawnImpl = vi.fn();+ await expect(describeImagesFromPaths({ provider: { id: 'codex', command: 'codex', args: [] }, imagePaths: [path], prompt: 'review',+ spawnImpl, beforeExecute: () => { throw new Error('Production stopped'); } })).rejects.toThrow('Production stopped');+ expect(spawnImpl).not.toHaveBeenCalled();+ } finally { await rm(dir, { recursive: true, force: true }); }+});+describe('decodeImageDataUrl', () => {it('decodes the base64 payload to bytes', () => {expect(decodeImageDataUrl(PNG_DATA_URL).toString()).toBe('fake-png');