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: gate music video production on budgeted asset pilots (#9351)
[._.]/ Adam Eivy33d9759ec4a2
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxindex b463ed6ed8..c896cab756 100644--- a/client/src/components/musicVideo/AutopilotPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -53,12 +53,16 @@ function StepRow({ step }) {);}-function RunView({ run, production, codeFirst }) {+function RunView({ run, production, codeFirst, project }) {+ const [budget, setBudget] = useState(null);const live = RESUMABLE_RUN_STATUSES.has(run.status);const steps = run.steps || [];const failures = steps.filter((s) => s.error);const cap = run.limits.spendCapUsd;const needsReplan = run.status === 'needs-replan';+ const resumeValid = !budget || (Number.isInteger(budget.maxGenerations) && budget.maxGenerations >= run.limits.maxGenerations && budget.maxGenerations <= 500+ && Number.isInteger(budget.maxReviewAttempts) && budget.maxReviewAttempts >= run.limits.maxReviewAttempts && budget.maxReviewAttempts <= 10+ && (budget.spendCapUsd == null || (Number.isFinite(budget.spendCapUsd) && budget.spendCapUsd >= cap && budget.spendCapUsd <= 100000)));const hint = run.interrupted? 'The server restarted — nothing is running. Resume to continue.': run.stopReason;@@ -79,6 +83,25 @@ function RunView({ run, production, codeFirst }) {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>+ {run.accounting && <div aria-label="Production budget" className="text-port-text-muted space-y-1">+ <p>Planned remaining: {formatCount(run.accounting.plannedGenerations)} asset jobs · Reserved: {formatUsd(run.accounting.reservedUsd)} · Spent: {formatUsd(run.accounting.spentUsd)}{run.accounting.unpriced ? ' + unpriced calls' : ''}</p>+ <p>Reviews: {formatCount(run.accounting.reviews)} / {formatCount(run.limits.maxReviewAttempts)} shared by pilots and final review.</p>+ <p>Expected next spend: {run.nextSpend ? run.nextSpend.costUsd == null ? 'unpriced — refused under a dollar cap' : formatUsd(run.nextSpend.costUsd) : 'quoted before the next submission'}</p>+ </div>}+ {run.pilot && <div aria-label="Production pilot evidence" className="border border-port-border rounded p-2 space-y-1">+ <p className="font-medium">Representative asset pilots</p>+ <p className="text-port-text-muted">Accepted takes are reused. Every current pilot must pass continuous review before bulk production. Document composition is reviewed after asset preparation.</p>+ {(run.pilot.scenes || []).map((pilot) => {+ const excerpt = project.excerpts?.find((e) => e.id === pilot.excerptId);+ return <div key={pilot.sceneId} className="space-y-0.5">+ <p>{pilot.operation}: {pilot.sceneId} · {pilot.status || 'pending'}+ {excerpt?.filename && <> · <a href={`/data/videos/${excerpt.filename}`} target="_blank" rel="noreferrer" className="text-port-accent underline">Watch pilot</a></>}+ </p>+ {pilot.evidence && <p className="text-port-text-muted">Continuous analysis: {pilot.evidence.continuous ? 'verified' : 'unverified'} · Sampled frames: {formatCount(pilot.evidence.continuousFrames)} · Temporal alignment: {pilot.evidence.temporal?.status || 'unverified'}</p>}+ {pilot.repair && <p className="text-port-warning">Repair: {pilot.repair.category} · {pilot.repair.reason} Replacement generation spend for this repair stage: {formatUsd(pilot.repair.expectedGenerationSpendUsd)}.</p>}+ </div>;+ })}+ </div>}{hint && <p className="text-port-warning break-words">{hint}</p>}{steps.some((step) => step.retryBlocked) && <p className="text-port-warning">Terminal refusal recorded: unchanged inputs will not be submitted again on Resume. Repair the shot or cancel and choose another supported route. No new spend is reserved while blocked.</p>}{run.error && <p role="status" className="text-port-error break-words">{run.error}</p>}@@ -88,6 +111,20 @@ function RunView({ run, production, codeFirst }) {{steps.slice(-SHOWN_STEPS).reverse().map((step) => <StepRow key={step.key} step={step} />)}</ul>)}+ {live && run.status === 'limit-reached' && <fieldset className="flex flex-wrap gap-2" aria-label="Raise production limits">+ <label htmlFor={`production-generations-${run.id}`}>Max generations+ <input id={`production-generations-${run.id}`} type="number" min={run.limits.maxGenerations} max={500} value={budget?.maxGenerations ?? run.limits.maxGenerations}+ onChange={(e) => setBudget((b) => ({ ...run.limits, ...b, maxGenerations: Number(e.target.value) }))} className={inputCls} />+ </label>+ <label htmlFor={`production-reviews-${run.id}`}>Max reviews+ <input id={`production-reviews-${run.id}`} type="number" min={run.limits.maxReviewAttempts} max={10} value={budget?.maxReviewAttempts ?? run.limits.maxReviewAttempts}+ onChange={(e) => setBudget((b) => ({ ...run.limits, ...b, maxReviewAttempts: Number(e.target.value) }))} className={inputCls} />+ </label>+ {cap != null && <label htmlFor={`production-cap-${run.id}`}>Spend cap (USD)+ <input id={`production-cap-${run.id}`} type="number" min={cap} max={100000} step={0.01} value={budget?.spendCapUsd ?? cap}+ onChange={(e) => setBudget((b) => ({ ...run.limits, ...b, spendCapUsd: Number(e.target.value) }))} className={inputCls} />+ </label>}+ </fieldset>}<div className="flex flex-wrap gap-2">{run.status === 'running' && !run.interrupted && (<button type="button" disabled={production.busy} onClick={() => production.stop(run.id)}@@ -96,8 +133,8 @@ function RunView({ run, production, codeFirst }) {</button>)}{live && (!codeFirst || run.authoring) && (run.status !== 'running' || run.interrupted) && (- <button type="button" disabled={production.busy}- onClick={() => production.resume(run.id, needsReplan ? { acceptBasis: true } : {})}+ <button type="button" disabled={production.busy || !resumeValid}+ onClick={() => production.resume(run.id, { ...(needsReplan ? { acceptBasis: true } : {}), ...(budget ? { limits: budget } : {}) })}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"><Play size={12} /> {needsReplan ? 'Resume with the new setup' : 'Resume'}</button>@@ -151,7 +188,7 @@ function StartForm({ project, production }) {return (<div className="space-y-2"><p className="text-port-text-muted">- {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.'}+ {assets ? 'Reviews representative selected assets before bulk preparation, authors the document, reviews motion and audio in a continuous excerpt, revises failed code sections, then renders the chosen document.' : 'Plans the board, reviews representative pilots before bulk generation, 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')}>@@ -328,7 +365,7 @@ function ProductionSection({ project, production }) {return (<div className="rounded border border-port-border p-2 space-y-2 text-xs" aria-label="Production run"><span className="font-medium flex items-center gap-1"><Clapperboard size={12} /> Autonomous production (opt-in)</span>- {run && <RunView run={run} production={production} codeFirst={codeFirst} />}+ {run && <RunView key={run.id} run={run} production={production} codeFirst={codeFirst} project={project} />}{codeFirst && <><MediumPlanSummary project={project} /><div className="rounded border border-port-border p-2 space-y-1" aria-label="Code-first asset preflight">diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxindex b06139503d..4bbe3f3440 100644--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -252,3 +252,37 @@ describe('AutopilotPanel production run', () => {expect(await screen.findByText(/No allowed route can generate the frame/)).toBeTruthy();});});++describe('AutopilotPanel budgeted pilot evidence (#9351)', () => {+ beforeEach(() => { vi.clearAllMocks(); listeners.clear(); });++ it('renders pushed pilot evidence, repair reasons and known versus unpriced accounting without starting work', () => {+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [run({+ status: 'blocked', accounting: { plannedGenerations: 1200, reservedUsd: 1.25, spentUsd: 2.5, unpriced: true, reviews: 1 },+ nextSpend: { kind: 'review', costUsd: null },+ pilot: { scenes: [{ sceneId: 'shot-example', operation: 'performance', status: 'inconclusive', excerptId: 'excerpt-example',+ evidence: { continuous: true, continuousFrames: 12, temporal: { status: 'unverified' } },+ repair: { category: 'temporal-alignment', reason: 'Preview a timing edit.', expectedGenerationSpendUsd: 0 } }] },+ })], excerpts: [{ id: 'excerpt-example', filename: 'synthetic-pilot.mp4' }] }} />);+ expect(screen.getByLabelText('Production budget')).toHaveTextContent('Planned remaining: 1,200 asset jobs · Reserved: $1.25 · Spent: $2.50 + unpriced calls');+ expect(screen.getByLabelText('Production budget')).toHaveTextContent('Expected next spend: unpriced');+ expect(screen.getByLabelText('Production pilot evidence')).toHaveTextContent('Temporal alignment: unverified');+ expect(screen.getByLabelText('Production pilot evidence')).toHaveTextContent('Repair: temporal-alignment');+ expect(screen.getByRole('link', { name: 'Watch pilot' })).toHaveAttribute('href', '/data/videos/synthetic-pilot.mp4');+ expect(api.startMusicVideoProduction).not.toHaveBeenCalled();+ expect(api.resumeMusicVideoProduction).not.toHaveBeenCalled();+ });++ it('raises only explicit limits on Resume and disables an invalid budget', async () => {+ api.resumeMusicVideoProduction.mockResolvedValueOnce({});+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [run({ status: 'limit-reached',+ limits: { maxGenerations: 12, maxReviewAttempts: 3, spendCapUsd: 5 } })] }} />);+ fireEvent.change(screen.getByLabelText('Max reviews'), { target: { value: '2' } });+ expect(screen.getByRole('button', { name: 'Resume' })).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Max reviews'), { target: { value: '5' } });+ fireEvent.change(screen.getByLabelText('Spend cap (USD)'), { target: { value: '8' } });+ fireEvent.click(screen.getByRole('button', { name: 'Resume' }));+ await waitFor(() => expect(api.resumeMusicVideoProduction).toHaveBeenCalled());+ expect(api.resumeMusicVideoProduction).toHaveBeenCalledWith('p1', 'run-1', { limits: { maxGenerations: 12, maxReviewAttempts: 5, spendCapUsd: 8 } }, { silent: true });+ });+});diff --git a/docs/features/music-video-temporal-evidence.md b/docs/features/music-video-temporal-evidence.mdindex a14e2e09a2..794b49f3da 100644--- a/docs/features/music-video-temporal-evidence.md+++ b/docs/features/music-video-temporal-evidence.md@@ -94,3 +94,33 @@ again. A synchronous enqueue failure with no durable job refunds the reservationOnce the suffix take lands, Resume renders the revised draft using both originalprefix footage and the continuation. Retrying the draft render generates no video.Existing active run budgets cannot be bypassed by opening a manual repair.+++## Budgeted production pilots++An explicitly started production run selects representative performance,+interaction, camera, cutaway and still asset pilots where those operations+exist. It generates only their missing media and reviews each on its original+song window before releasing the bulk wave. Passing evidence continues+automatically within the authorized budget; accepted pilot selections stay in+the board and are reused without another submission. An incomplete board does+not move a late pilot to the beginning of the song. Code-first runs pilot only+the assets permitted by their approved medium plan; their authored document+still receives its own continuous review.++Pilots and final review share the run's review limit. Reviewer calls are+reserved before execution and charged to the known dollar total; unknown+prices cannot run under a dollar cap. Interrupted calls remain spent.+Exhausted limits are resumable from the Autopilot panel, including raising the+review or dollar allowance, without replacing accepted media. No boot path+starts or resumes this work.++Failed or unverified evidence holds the bulk wave. Visible findings select a+plate, prompt/action or composition repair; measured timing failures select a+timing repair, and unsupported or missing evidence selects capability+verification. The first repair choice favors existing assets and edits before+replacement generation. The panel records the reason and next operation's+price when it can be quoted. Failed pilots do not automatically become identical+paid revision requests. After correcting/selecting assets or reviewing the+unverified evidence, explicitly resume; changed evidence is reviewed again.+A different provider operation needs a passing pilot of its own.diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.jsindex 607eb94c0e..58e5a823e3 100644--- a/server/services/musicVideo/autoReview.js+++ b/server/services/musicVideo/autoReview.js@@ -123,7 +123,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, documentRevisions = false }, now = new Date().toISOString()) {+export function startAutoReviewOnProject(project, { startSec, endSec, limits, reviewer = {}, productionRunId = null, documentRevisions = false, productionPilotSceneId = null }, 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');@@ -143,7 +143,8 @@ 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, ...(documentRevisions ? { documentRevisions: true } : {}) } : {}),+ ...(isNonBlankStr(productionRunId) ? { productionRunId, ...(documentRevisions ? { documentRevisions: true } : {}),+ ...(productionPilotSceneId ? { productionPilotSceneId } : {}) } : {}),attempts: [{ n: 1, excerptId: null, renderFailures: 0, reviewStartedAt: null, review: null, revisionId: null }],stopReason: null,error: null,@@ -192,6 +193,7 @@ 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.productionPilotSceneId) return { type: 'halt', status: 'needs-human', reason: 'The pilot failed. Choose a targeted repair before repeating generation.' };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 };@@ -258,6 +260,16 @@ export function beginAttemptReview(project, runId, now = new Date().toISOString(}, now);}+/** Production admission refused before provider execution: retain the draft, not a verdict. */+export function deferAttemptReview(project, runId, error, now = new Date().toISOString()) {+ return mutateRun(project, runId, (run) => ({+ usage: { ...run.usage, reviews: Math.max(0, run.usage.reviews - 1) },+ ...withAttempt(run, { reviewStartedAt: null }),+ ...(run.status === 'running' ? { status: ['PRODUCTION_REVIEW_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED'].includes(error.code) ? 'limit-reached' : 'stopped',+ stopReason: error.message } : {}),+ }), now);+}+const cleanFinding = (f, spanSec) => {if (!f || typeof f !== 'object' || !isNonBlankStr(f.note)) return null;// Clamped INSIDE the half-open excerpt, so a finding at (or past) its end@@ -270,6 +282,7 @@ const cleanFinding = (f, spanSec) => {severity: f.severity === 'minor' ? 'minor' : 'blocking',check: AUTO_REVIEW_CHECKS.includes(f.check) ? f.check : null,source: f.source === 'analysis' ? 'analysis' : 'reviewer',+ ...(['plate', 'prompt-action', 'composition'].includes(f.failureCategory) ? { failureCategory: f.failureCategory } : {}),};};diff --git a/server/services/musicVideo/autoReviewJudge.js b/server/services/musicVideo/autoReviewJudge.jsindex 2cb6269f66..fc81c64c3e 100644--- a/server/services/musicVideo/autoReviewJudge.js+++ b/server/services/musicVideo/autoReviewJudge.js@@ -154,11 +154,11 @@ Return ONLY valid JSON:{"checks": { "composition": "pass" | "fail", "continuity": "pass" | "fail", "motion": "pass" | "fail" },"findings": [- { "atSec": <seconds on the excerpt timeline where the problem is visible>, "check": "composition" | "continuity" | "motion", "severity": "blocking" | "minor", "note": "<one concrete sentence a director can act on>" }+ { "atSec": <seconds on the excerpt timeline where the problem is visible>, "check": "composition" | "continuity" | "motion", "severity": "blocking" | "minor", "failureCategory": "plate" | "prompt-action" | "composition", "note": "<one concrete sentence a director can act on>" }],"summary": "<one or two sentences>"}-Every "fail" check needs at least one blocking finding placed inside the section that should be regenerated. Use "minor" for polish notes that should not block approval.`;+Every "fail" check needs at least one blocking finding placed inside the affected section. Classify a visible starting-state or missing-subject mismatch as plate, a mismatch with authored action as prompt-action, and framing/type/layout failures as composition. The repair stage is chosen separately; a finding does not itself authorize regeneration. Use "minor" for polish notes that should not block approval.`;}/** Parse the reviewer's JSON, or null when it gave no usable verdict. */@@ -171,7 +171,9 @@ export function parseAutoReviewResponse(text) {for (const name of MODEL_CHECKS) checks[name] = CHECK_VALUES.has(value.checks[name]) ? value.checks[name] : 'unverified';const findings = (Array.isArray(value.findings) ? value.findings : []).filter((f) => f && typeof f === 'object' && isNonBlankStr(f.note) && typeof f.atSec === 'number' && Number.isFinite(f.atSec))- .map((f) => ({ atSec: f.atSec, note: f.note, check: MODEL_CHECKS.includes(f.check) ? f.check : null, severity: f.severity === 'minor' ? 'minor' : 'blocking', source: 'reviewer' }));+ .map((f) => ({ atSec: f.atSec, note: f.note, check: MODEL_CHECKS.includes(f.check) ? f.check : null,+ ...( ['plate', 'prompt-action', 'composition'].includes(f.failureCategory) ? { failureCategory: f.failureCategory } : {}),+ severity: f.severity === 'minor' ? 'minor' : 'blocking', source: 'reviewer' }));return { checks, findings, summary: isNonBlankStr(value.summary) ? trimTo(value.summary, MAX_SUMMARY_LEN) : '' };}diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.jsindex b57ca21e31..868e99647f 100644--- a/server/services/musicVideo/autoReviewService.js+++ b/server/services/musicVideo/autoReviewService.js@@ -29,6 +29,8 @@ import { existsSync } from 'fs';import { join } from 'path';import { promisify } from 'util';import { ServerError } from '../../lib/errorHandler.js';+import { isFreeProvider } from '../../lib/modelPricing.js';+import { isToolFreeOneShotProvider } from '../../lib/providerVendors.js';import { PATHS, ensureDir } from '../../lib/fileUtils.js';import { execFile } from '../../lib/childProcess.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';@@ -42,6 +44,7 @@ import { projectExcerpts } from './excerpt.js';import { projectRevisions, releaseRevisionClaim, revisionSectionStates, startRevisionOnProject } from './revision.js';import {attachAttemptExcerpt,+ deferAttemptReview,attachAttemptRevision,beginAttemptReview,beginNextAttempt,@@ -130,9 +133,18 @@ async function callReviewer(run, prompt, screenshots, projectId) {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);+ if (run.productionRunId) {+ if (!isToolFreeOneShotProvider(provider)) throw new Error('Production review requires a tool-free provider');+ if ((run.reviewer.providerId && provider.id !== run.reviewer.providerId)+ || (run.reviewer.model && selectedModel !== run.reviewer.model)) throw new Error('The selected production reviewer is unavailable');+ const { assertProductionContinuation, chargeProductionReview } = await import('./productionService.js');+ let charge = null;+ beforeExecute = async () => {+ await assertProductionContinuation(projectId, run.productionRunId);+ if (!charge) charge = chargeProductionReview(projectId, run.productionRunId, { reviewRunId: run.id, attemptN: run.attempts.at(-1).n,+ costUsd: isFreeProvider(provider) ? 0 : null });+ await charge;+ };await assertProductionContinuation(projectId, run.productionRunId);}if (provider.type !== 'api') {@@ -200,6 +212,7 @@ async function reviewDraft(project, run, excerpt) {let parsed = null;let reviewerError = null;+ let providerErrorCode = null;let used = { providerId: run.reviewer.providerId, model: run.reviewer.model };if (screenshots.length) {const shotIntents = (project.scenes || []).filter((scene) => scene.direction?.actionContract != null && scene.startSec < excerpt.endSec && scene.endSec > excerpt.startSec)@@ -212,6 +225,7 @@ async function reviewDraft(project, run, excerpt) {if (!parsed) reviewerError = 'The reviewer returned no usable verdict';} catch (err) {reviewerError = err.message;+ providerErrorCode = err.code || null;console.warn(`⚠️ Music Video auto-review ${short(run.id)} reviewer call failed: ${err.message}`);}} else {@@ -223,6 +237,7 @@ async function reviewDraft(project, run, excerpt) {...review,reason: review.verdict === 'inconclusive' && reviewerError ? `${reviewerError} — watch this draft yourself` : review.reason,reviewer: used,+ ...(providerErrorCode ? { providerErrorCode } : {}),};}@@ -232,7 +247,7 @@ 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) {+ if (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 } };@@ -250,7 +265,13 @@ async function takeSteps(projectId, runId) {// Draft renders are free; a refusal (another draft rendering, a shot// that doesn't cover its span…) pauses the run so the director can fix// it and resume, rather than failing the whole checkpoint.- const render = await startExcerptRender(projectId, { startSec: run.startSec, endSec: run.endSec }).catch((err) => ({ error: err }));+ const render = await startExcerptRender(projectId, { startSec: run.startSec, endSec: run.endSec }, {+ ...(run.productionPilotSceneId ? { pilotSceneId: run.productionPilotSceneId } : {}),+ ...(run.productionRunId ? { verifyCurrent: async () => {+ const { assertProductionContinuation } = await import('./productionService.js');+ await assertProductionContinuation(projectId, run.productionRunId);+ } } : {}),+ }).catch((err) => ({ error: err }));if (render.error) {const out = await halt(projectId, runId, { status: 'stopped', reason: `The draft could not render: ${render.error.message}` });return { ...out, action: { type: 'idle' } };@@ -265,6 +286,11 @@ async function takeSteps(projectId, runId) {publish(projectId, begun.project, begun.run, { type: 'reviewing', excerptId: step.excerptId });const excerpt = projectExcerpts(project).find((e) => e.id === step.excerptId);let review = await reviewDraft(project, run, excerpt);+ if (['PRODUCTION_REVIEW_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED', 'PRODUCTION_COST_UNKNOWN', 'PRODUCTION_NOT_RUNNING', 'PRODUCTION_BASIS_CHANGED'].includes(review.providerErrorCode)) {+ const out = await mutateProjectRecord(projectId, (current) => deferAttemptReview(current, runId,+ { code: review.providerErrorCode, message: review.reason }));+ return { ...out, action: { type: 'idle' } };+ }const impact = await getDependencyImpact(projectId);if (impact.shots.some((shot) => {const scene = project.scenes.find((entry) => entry.sceneId === shot.sceneId);@@ -375,7 +401,17 @@ function advanceInBackground(projectId, runId) {/** Start a run (explicit director request with limits). Returns `{ project, run }`. */export async function startAutoReview(projectId, input) {- const out = await mutateProjectRecord(projectId, (current) => startAutoReviewOnProject(current, input));+ const production = input.productionRunId ? await import('./production.js') : null;+ const owner = production ? await (await import('./productionService.js')).assertProductionContinuation(projectId, input.productionRunId) : null;+ const out = await mutateProjectRecord(projectId, (current) => {+ if (owner) production.assertProductionActive(current, owner.id, owner.processId);+ const started = startAutoReviewOnProject(current, input);+ if (!owner) return started;+ const attached = input.productionPilotSceneId+ ? production.attachProductionPilotReview(started.project, owner.id, input.productionPilotSceneId, started.run.id)+ : production.attachProductionReview(started.project, owner.id, started.run.id);+ return { ...started, project: attached.project };+ });console.log(`🎬 Music Video auto-review ${short(out.run.id)} started: [${out.run.startSec}, ${out.run.endSec}]s, ≤${out.run.limits.maxAttempts} reviews, ≤${out.run.limits.maxGenerations} generations`);advanceInBackground(projectId, out.run.id);return out;diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex d6b12ad0e4..2155bd539f 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -41,6 +41,8 @@ import { markRevisionRendering, settleRevisionRender } from './revision.js';import { ensureInstanceId } from '../instanceIdentity.js';import { musicVideoAspect, musicVideoAtAspect } from '../../lib/musicVideoAspect.js';import { musicVideoEvents } from './events.js';+import { pilotDependencies, productionPilotRenderProject } from './productionPilot.js';+import { musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';const jobs = new Map();const projectExcerptRenders = new Map();@@ -210,9 +212,16 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSereturn { jobId, excerptId };}-export async function startExcerptRender(projectId, { startSec, endSec, aspect = null, fade = false }, { revisionId = null } = {}) {- const project = await getProject(projectId);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+export async function startExcerptRender(projectId, { startSec, endSec, aspect = null, fade = false }, { revisionId = null, pilotSceneId = null, verifyCurrent = null } = {}) {+ const stored = await getProject(projectId);+ if (!stored) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ await verifyCurrent?.(stored);+ const project = pilotSceneId ? productionPilotRenderProject(stored, pilotSceneId) : stored;+ const pilotEvidence = pilotSceneId ? pilotDependencies(stored, pilotSceneId) : null;+ if (pilotSceneId) {+ const scene = stored.scenes.find((s) => s.sceneId === pilotSceneId);+ if (startSec !== scene.startSec || endSec !== scene.endSec) throw new ServerError('The pilot must review its exact song window', { status: 422, code: 'INVALID_EXCERPT_RANGE' });+ }const existingJob = projectExcerptRenders.get(projectId);if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {@@ -245,7 +254,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =// dims/fps/sections/cues in ABSOLUTE song time — the coordinate space// `startSec`/`endSec` and `excerptBoundaryTimes` are given in.const probe = buildMusicVideoFfmpegArgs(clips, audioPath, join(PATHS.videos, 'probe.mp4'), { audioDurationSec, frameGrid: composed });- if (!(startSec >= 0) || !(endSec > startSec) || endSec > probe.totalDuration + 1e-6) {+ if (!(startSec >= 0) || !(endSec > startSec) || endSec > probe.totalDuration + (pilotSceneId ? 1 / probe.fps : 1e-6)) {throw new ServerError(`The excerpt range must fall within the project's ${probe.totalDuration.toFixed(2)}s render`,{ status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: probe.totalDuration } },@@ -268,8 +277,10 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =// and the mark names this instance so a synced peer's boot recovery can't// demote it (#9010).const renderingOn = await ensureInstanceId();+ await verifyCurrent?.(await getProject(projectId));const { excerpt } = await mutateProjectRecord(projectId, (current) => {- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: project, dependencies: captureMusicVideoEvidence(project, { sceneIds: sections.map((section) => section.sceneId), startSec, endSec: endClamped }), partialFilename: filename, renderingOn });+ if (pilotEvidence && musicVideoDependencyChanges(current, pilotEvidence).length) throw new ServerError('The selected pilot changed before rendering', { status: 409, code: 'COMPOSITION_DRAFT_STALE' });+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: stored, dependencies: pilotEvidence || captureMusicVideoEvidence(project, { sceneIds: sections.map((section) => section.sceneId), startSec, endSec: endClamped }), partialFilename: filename, renderingOn });return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;});const excerptId = excerpt.id;diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex 07593b180d..af20a44beb 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -48,6 +48,7 @@ import { codeFirstProductionAssets, normalizeMusicVideoProductionPolicy, summariimport { projectAutoReviews } from './autoReview.js';import { projectRevisions } from './revision.js';import { castAndSetsSettled } from './castAndSets.js';+import { currentPilotPass, pilotClass, pilotInputBasis, pilotRepair, selectProductionPilots } from './productionPilot.js';const PRODUCTION_LIMIT_BOUNDS = Object.freeze({maxGenerations: Object.freeze({ min: 1, max: 500 }),@@ -237,6 +238,7 @@ export function startProductionOnProject(project, {usage: { generations: 0, spentUsd: 0 },planned: false,reviewRunId: null,+ pilot: { scenes: null },steps: [],processId: processId || null,stopReason: null,@@ -259,6 +261,12 @@ export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kinif (productionBasisRevision(project, run.basis.version || 1) !== run.basis.revision) {throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The production policy or approved plan changed before submission');}+ if (['image', 'video'].includes(kind) && run.pilot && (!run.pilot.scenes+ || (!run.pilot.scenes.some((pilot) => pilot.sceneId === sceneId)+ && !run.pilot.scenes.every((pilot) => currentPilotPass(project, pilot))))) {+ throw productionError(409, 'PRODUCTION_PILOT_REQUIRED', 'The pilot evidence changed before bulk submission');+ }+ assertProductionPilotRoute(project, run, sceneId, step.kind, step.route);if (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {const plan = summarizeMusicVideoMediumPlan(project);const medium = project.treatment?.shotDirections?.find((direction) => direction.sceneId === sceneId)?.medium;@@ -275,6 +283,19 @@ export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kinreturn step;}+/** A newly chosen backend or changed operation needs its own passing pilot. */+export function assertProductionPilotRoute(project, run, sceneId, kind, route) {+ if (!['frame', 'clip'].includes(kind) || !run.pilot?.scenes+ || run.pilot.scenes.some((pilot) => pilot.sceneId === sceneId)) return;+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);+ const representative = scene && run.pilot.scenes.find((pilot) => pilot.operation === pilotClass(scene, project));+ const tested = representative && run.steps.findLast((s) => s.sceneId === representative.sceneId && s.kind === kind && s.status === 'completed');+ if (!representative || !currentPilotPass(project, representative) || !tested || routeKey(tested.route) !== routeKey(route)+ || tested.providerBasis !== productionProviderBasis(project, kind)) {+ throw productionError(409, 'PRODUCTION_PILOT_REQUIRED', 'This provider operation has no accepted pilot. Keep the tested route or start a new run to pilot the changed route.');+ }+}+// ---- deriving the next step -------------------------------------------------const SLOT = Object.freeze({ frame: 'referenceImageId', clip: 'videoHistoryId' });@@ -284,6 +305,9 @@ const productionSceneBasis = (project, sceneId) => canonicalSnapshotChecksum({scene: (project.scenes || []).find((scene) => scene.sceneId === sceneId) || null,videoSettings: project.videoSettings || null,});+const productionProviderBasis = (project, kind) => canonicalSnapshotChecksum(kind === 'clip'+ ? { videoSettings: project.videoSettings || null }+ : { visualSpec: project.visualSpec || null, styleReferences: project.styleReferences || null });// A retry is a new provider operation only when its actual inputs changed.// Take history, review timestamps and UI labels must not clear a terminal refusal.@@ -338,7 +362,7 @@ function productionTargets(project) {const layered = isLayeredComposition(project);const scenes = Array.isArray(project?.scenes) ? project.scenes : [];return {- frame: scenes.filter((s) => sceneVisualLayer(s, { layered }) !== 'card'),+ frame: scenes.filter((s) => sceneVisualLayer(s, { layered }) === 'still' || (sceneVisualLayer(s, { layered }) !== 'card' && !s.videoHistoryId)),clip: scenes.filter((s) => sceneVisualLayer(s, { layered }) === 'footage'),};}@@ -410,6 +434,22 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }return { type: 'plan' };}const targets = productionTargets(project);+ if (run.pilot && !run.pilot.scenes) return { type: 'plan-pilots' };+ const pilots = run.pilot?.scenes || [];+ const pendingPilots = pilots.filter((pilot) => !currentPilotPass(project, pilot));+ for (const pilot of pendingPilots) {+ const review = projectAutoReviews(project).find((r) => r.id === pilot.reviewRunId);+ if (review?.status === 'running') return { type: 'wait', on: 'pilot-review' };+ if (review && ['stopped', 'limit-reached'].includes(review.status)) return { type: 'halt', status: review.status, reason: review.stopReason || 'Pilot review paused; resume to continue' };+ const result = review?.attempts?.at(-1)?.review;+ const changes = result && musicVideoDependencyChanges(project, result.dependencies);+ if (result && (changes.some((change) => change.role === 'unknown')+ || (pilot.inputBasis === pilotInputBasis(project, pilot.sceneId) && !changes.length))) {+ if (result.verdict === 'inconclusive' && result.reviewedAt < run.resumedAt) continue;+ const exhausted = ['PRODUCTION_REVIEW_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED'].includes(result.providerErrorCode);+ return { type: 'halt', status: exhausted ? 'limit-reached' : 'blocked', reason: `Pilot ${pilot.sceneId}: ${result.reason || result.verdict}. ${pilotRepair(result, scenes.find((s) => s.sceneId === pilot.sceneId), project).reason}` };+ }+ }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.' };@@ -417,6 +457,7 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }let waiting = false;for (const stepKind of ['frame', 'clip']) {for (const scene of targets[stepKind]) {+ if (pendingPilots.length && !pendingPilots.some((pilot) => pilot.sceneId === scene.sceneId)) continue;if (scene[SLOT[stepKind]]) continue;// A clip is generated from the scene's frame; wait for it.if (stepKind === 'clip' && !scene.referenceImageId) { waiting = true; continue; }@@ -432,6 +473,12 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }}}if (waiting) return { type: 'wait', on: 'generation' };+ if (pendingPilots.length) {+ const pilot = pendingPilots[0];+ const scene = scenes.find((s) => s.sceneId === pilot.sceneId);+ if (!scene || !(scene.startSec >= 0) || !(scene.endSec > scene.startSec)) return { type: 'halt', status: 'blocked', reason: 'A pilot needs a timed song window before bulk production' };+ return { type: 'pilot-review', sceneId: scene.sceneId, startSec: scene.startSec, endSec: scene.endSec };+ }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' };@@ -480,6 +527,12 @@ export function reserveProductionStep(project, runId, {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');assertProductionActive(project, runId, processId);+ if (['frame', 'clip'].includes(kind) && run.pilot+ && (!run.pilot.scenes || (!run.pilot.scenes.some((pilot) => pilot.sceneId === sceneId)+ && !run.pilot.scenes.every((pilot) => currentPilotPass(project, pilot))))) {+ throw productionError(409, 'PRODUCTION_PILOT_REQUIRED', 'Review current pilot evidence before submitting the bulk wave');+ }+ assertProductionPilotRoute(project, run, sceneId, kind, route);const author = kind === 'author';const plate = kind === 'plate';const plateRoute = plate && route?.kind === 'plate' && (!run.reviewer?.providerId || route.mode === run.reviewer.providerId) && (!run.reviewer?.model || route.model === run.reviewer.model);@@ -518,6 +571,7 @@ export function reserveProductionStep(project, runId, {rationale: trimTo(rationale, MAX_ERROR_LEN) || '',costUsd,...(['frame', 'clip'].includes(kind) ? { retryBasis: productionRetryBasis(project, sceneId, kind) } : {}),+ ...(['frame', 'clip'].includes(kind) ? { providerBasis: productionProviderBasis(project, kind) } : {}),...(kind === 'clip' && scene?.direction?.actionContract ? { plateAdmission: { assetId: scene.referenceImageId, basis: plateRequirementBasis(scene) } } : {}),...(plateRepairBasis ? { plateRepairBasis } : {}),...(run.authoring && !author ? { submissionBasis: productionSceneBasis(project, sceneId) } : {}),@@ -531,6 +585,7 @@ export function reserveProductionStep(project, runId, {return {usage: { ...run.usage, generations: run.usage.generations + 1, spentUsd: run.usage.spentUsd + (costUsd || 0) },steps: [...run.steps, step],+ nextSpend: null,};}, now);return { ...out, step };@@ -646,6 +701,32 @@ export const markProductionPlanned = (project, runId, now = new Date().toISOStriexport const attachProductionReview = (project, runId, reviewRunId, now = new Date().toISOString()) =>mutateRun(project, runId, () => ({ reviewRunId }), now);+export const planProductionPilots = (project, runId, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ pilot: { scenes: selectProductionPilots(project) } }), now);++export const attachProductionPilotReview = (project, runId, sceneId, reviewRunId, now = new Date().toISOString()) =>+ mutateRun(project, runId, (run) => ({ pilot: { ...run.pilot, scenes: run.pilot.scenes.map((pilot) =>+ pilot.sceneId === sceneId ? { ...pilot, reviewRunId, inputBasis: pilotInputBasis(project, sceneId) } : pilot) } }), now);++export const quoteProductionSpend = (project, runId, nextSpend, now = new Date().toISOString()) =>+ mutateRun(project, runId, () => ({ nextSpend }), now);++/** Shared review budget, charged before the call; interrupted calls stay spent. */+export function reserveProductionReview(project, runId, { reviewRunId, attemptN, costUsd, processId }, now = new Date().toISOString()) {+ assertProductionActive(project, runId, processId);+ const run = findProductionRun(project, runId);+ const reviews = run.steps.filter((s) => s.kind === 'review').length;+ if (reviews >= run.limits.maxReviewAttempts) throw productionError(409, 'PRODUCTION_REVIEW_LIMIT', 'The production review budget is exhausted; raise it and resume');+ if (run.limits.spendCapUsd !== null && (costUsd == null || run.usage.spentUsd + costUsd > run.limits.spendCapUsd + 1e-9)) {+ throw productionError(409, costUsd == null ? 'PRODUCTION_COST_UNKNOWN' : 'PRODUCTION_BUDGET_EXHAUSTED', 'The next review cannot fit the authorized dollar budget');+ }+ return mutateRun(project, runId, (r) => ({ nextSpend: null, usage: { ...r.usage, spentUsd: r.usage.spentUsd + (costUsd || 0) },+ steps: [...r.steps, { key: `review:${reviewRunId}:${attemptN}:${reviews + 1}`, kind: 'review', sceneId: 'review',+ route: { kind: 'review', mode: r.reviewer.providerId || 'default', model: r.reviewer.model }, costUsd,+ status: 'completed', rationale: 'Reserved reviewer call; interruption does not refund provider work',+ reservedAt: now, settledAt: now }] }), now);+}+/** Stop the run with a status/reason. */export function haltProduction(project, runId, { status, reason = null, error = null }, now = new Date().toISOString()) {if (!PRODUCTION_STATUSES.includes(status) || status === 'running') throw new Error(`haltProduction: invalid status ${status}`);@@ -691,6 +772,7 @@ export function resumeProductionOnProject(project, runId, { limits, acceptBasisprocessId,resumedAt: now,retryAcknowledged: run.steps.filter((step) => step.status === 'failed').map((step) => step.key),+ ...(!run.pilot && !run.reviewRunId ? { pilot: { scenes: null } } : {}),stopReason: null,error: null,...(run.finalRender?.status === 'failed' || (run.finalRender && run.processId !== processId) ? { finalRender: null } : {}),diff --git a/server/services/musicVideo/productionPilot.js b/server/services/musicVideo/productionPilot.jsnew file mode 100644index 0000000000..e51acb8525--- /dev/null+++ b/server/services/musicVideo/productionPilot.js@@ -0,0 +1,100 @@+/** Asset pilots use the existing review gate, never a second grading rubric. */+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';+import { captureMusicVideoEvidence, captureTakeDependencies, musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';+import { codeFirstProductionAssets } from '../../lib/musicVideoMediumPlan.js';+import { isLayeredComposition, sceneVisualLayer } from '../../lib/musicVideoLayers.js';++export function pilotClass(scene, project) {+ const medium = project.treatment?.shotDirections?.find((d) => d.sceneId === scene.sceneId)?.medium;+ if (medium === 'still' || sceneVisualLayer(scene, { layered: isLayeredComposition(project) }) === 'still') return 'still';+ if (scene.shotMode === 'performance') return 'performance';+ const contract = scene.direction?.actionContract;+ if (contract?.reactions?.length || new Set((contract?.actions || []).map((a) => a.subject)).size > 1) return 'interaction';+ if (contract?.cameraConstraints?.length || scene.direction?.camera) return 'camera';+ return 'cutaway';+}++/** One representative of each operation, hardest shots first. Existing assets count. */+export function selectProductionPilots(project) {+ const assets = codeFirstProductionAssets(project);+ const allowed = assets && new Set(assets.steps.filter((s) => s.action !== 'code').map((s) => s.sceneId));+ const seen = new Set();+ const rank = { performance: 5, interaction: 4, camera: 3, cutaway: 2, still: 1 };+ return (project.scenes || [])+ .filter((scene) => allowed ? allowed.has(scene.sceneId) : sceneVisualLayer(scene, { layered: isLayeredComposition(project) }) !== 'card')+ .map((scene) => ({ sceneId: scene.sceneId, operation: pilotClass(scene, project),+ missing: Number(!scene.referenceImageId) + Number(pilotClass(scene, project) !== 'still' && !scene.videoHistoryId),+ complexity: (scene.direction?.actionContract?.actions?.length || 0)+ + (scene.direction?.actionContract?.reactions?.length || 0)+ + (scene.direction?.actionContract?.cameraConstraints?.length || 0) }))+ .sort((a, b) => rank[b.operation] - rank[a.operation] || b.missing - a.missing || b.complexity - a.complexity)+ .filter(({ operation }) => !seen.has(operation) && seen.add(operation))+ .map(({ sceneId, operation }) => ({ sceneId, operation }));+}++export function pilotDependencies(project, sceneId) {+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);+ const evidence = captureMusicVideoEvidence(project, { sceneIds: [sceneId], composition: false });+ return { ...evidence,+ references: [...evidence.references,+ ...captureTakeDependencies(scene).references] };+}++export const pilotInputBasis = (project, sceneId) => {+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);+ return canonicalSnapshotChecksum({ scene: scene && Object.fromEntries(Object.entries(scene)+ .filter(([key]) => !['takes', 'referenceImageId', 'videoHistoryId', 'updatedAt'].includes(key))),+ videoSettings: project.videoSettings, audio: project.audioAnalysis, lyrics: project.lyricCues,+ master: { trackId: project.trackId, uploadedAudioFilename: project.uploadedAudioFilename, vocalStemFilename: project.vocalStemFilename },+ lyricMarkers: project.lyricMarkers, phrases: project.phrases, concept: project.concept,+ style: project.visualSpec, references: project.styleReferences });+};++export function currentPilotPass(project, pilot) {+ const review = project.autoReviews?.find((r) => r.id === pilot.reviewRunId);+ const result = review?.attempts?.at(-1)?.review;+ return review?.status === 'passed' && result?.verdict === 'pass'+ && pilot.inputBasis === pilotInputBasis(project, pilot.sceneId)+ && !musicVideoDependencyChanges(project, result.dependencies).length;+}++/** Prefer an edit/reuse before charging for replacement media. No identical retries. */+export function pilotRepair(review, scene, project) {+ const checks = review?.checks || {};+ const contract = scene?.direction?.actionContract;+ const plateFailed = scene?.takes?.some((take) => take.plateEvidence?.verdict === 'fail');+ const visibleFailure = review?.findings?.find((f) => f.severity === 'blocking'+ && ['plate', 'prompt-action', 'composition'].includes(f.failureCategory))?.failureCategory;+ const category = plateFailed ? 'plate'+ : checks.lipSync === 'fail' || checks.audioSync === 'fail' ? 'temporal-alignment'+ : visibleFailure || (checks.motion === 'fail' && contract ? 'prompt-action'+ : checks.composition === 'fail' || checks.continuity === 'fail' ? 'composition'+ : 'provider-capability');+ const choices = {+ plate: ['select-plate', 'Select a passing existing plate before generating a replacement.'],+ 'temporal-alignment': ['timing-edit', 'Preview a timing correction against temporal evidence before replacing footage.'],+ 'prompt-action': ['edit-action', 'Correct the authored action or select a take that meets it before paying for another take.'],+ composition: [project.productionPolicy?.strategy === 'code-first' ? 'revise-document' : 'composition-edit',+ 'Repair framing, cues or document code while retaining the selected media.'],+ 'provider-capability': ['verify-route', 'Verify the reviewer/provider capability and evidence; repeating an unsupported operation is not a repair.'],+ };+ const [action, reason] = choices[category];+ return { category, action, reason, expectedGenerationSpendUsd: 0 };+}++/**+ * A pilot from an incomplete board retains its absolute song position. A+ * prefix card occupies unproduced time; it is trimmed OUT of the excerpt.+ * Document projects test selected assets here, then review their authored+ * document separately. No placeholder can appear inside a pilot's window.+ */+export function productionPilotRenderProject(project, sceneId) {+ const scene = project.scenes?.find((s) => s.sceneId === sceneId);+ if (!scene || !(scene.startSec >= 0) || !(scene.endSec > scene.startSec)) throw new Error('The pilot needs an authored song window');+ const still = pilotClass(scene, project) === 'still';+ if (!(still ? scene.referenceImageId : scene.videoHistoryId)) throw new Error('The pilot selected asset is missing');+ const prefix = scene.startSec > 0 ? [{ sceneId: 'pilot-prefix', order: 0, visualLayer: 'card',+ startSec: 0, endSec: scene.startSec, cardText: '', cardColor: '#000000' }] : [];+ return { ...project, scenes: [...prefix, { ...scene, order: 1, visualLayer: still ? 'still' : 'footage' }],+ composition: { ...project.composition, mode: 'composed', cutting: 'sequential' } };+}diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex c2e371737a..fd223916b0 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -33,13 +33,19 @@ import { isToolFreeOneShotProvider } from '../../lib/providerVendors.js';import { codeFirstProductionAssets } from '../../lib/musicVideoMediumPlan.js';import { beginNextAttempt } from './autoReview.js';import { withAutopilotCutting } from './composition.js';+import { currentPilotPass, pilotClass, pilotRepair } from './productionPilot.js';import {attachProductionReview,+ attachProductionPilotReview,+ planProductionPilots,+ reserveProductionReview,+ quoteProductionSpend,attachProductionDocument,assertProductionActive,recordProductionDocumentRevision,setProductionRender,assertProductionStepOpen,+ assertProductionPilotRoute,cancelProductionOnProject,findProductionRun,haltProduction,@@ -73,7 +79,7 @@ const MAX_STEPS_PER_ADVANCE = 32;// The review's revision budget is bounded by the auto-review run's own limit.const AUTO_REVIEW_MAX_GENERATIONS = 100;// Refusals that mean "this run cannot continue as configured" — never retried.-const LIMIT_CODES = new Set(['PRODUCTION_SPEND_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED']);+const LIMIT_CODES = new Set(['PRODUCTION_SPEND_LIMIT', 'PRODUCTION_BUDGET_EXHAUSTED', 'PRODUCTION_REVIEW_LIMIT']);const advancing = new Map();const short = (id) => String(id || '').slice(5, 13);@@ -126,20 +132,56 @@ export async function assertProductionContinuation(projectId, runId) {return run;}+export async function chargeProductionReview(projectId, runId, input) {+ await mutateProjectRecord(projectId, (current) => quoteProductionSpend(current, runId, { kind: 'review', costUsd: input.costUsd }));+ return mutateProjectRecord(projectId, (current) => reserveProductionReview(current, runId, { ...input, processId: PROCESS_ID }));+}+async function liveJobs() {const { listJobs } = await deps.queue();return [...listJobs({ kind: 'image' }), ...listJobs({ kind: 'video' })];}/** The run as reported to the director: `interrupted` when a restart unpinned it. */-const present = (run) => ({ ...run, interrupted: run.status === 'running' && run.processId !== PROCESS_ID });+const present = (run, project) => {+ const counted = run.steps.filter((s) => s.status !== 'refused');+ const reserved = counted.filter((s) => s.status === 'reserved');+ const spent = counted.filter((s) => s.status !== 'reserved');+ const assets = project && codeFirstProductionAssets(project);+ return { ...run, interrupted: run.status === 'running' && run.processId !== PROCESS_ID,+ accounting: {+ plannedGenerations: assets ? assets.steps.filter((s) => ['generate-image', 'generate-video'].includes(s.action)).length+ : (project?.scenes || []).reduce((n, scene) => n + (scene.visualLayer !== 'card' && !scene.referenceImageId && (!scene.videoHistoryId || pilotClass(scene, project) === 'still') ? 1 : 0) + (!scene.videoHistoryId && pilotClass(scene, project) !== 'still' && scene.visualLayer !== 'card' ? 1 : 0), 0),+ reservedUsd: reserved.reduce((n, s) => n + (s.costUsd || 0), 0),+ spentUsd: spent.reduce((n, s) => n + (s.costUsd || 0), 0),+ unpriced: counted.some((s) => s.costUsd == null),+ reviews: counted.filter((s) => s.kind === 'review').length,+ },+ ...(run.pilot ? { pilot: { ...run.pilot, scenes: (run.pilot.scenes || []).map((pilot) => {+ const review = project?.autoReviews?.find((r) => r.id === pilot.reviewRunId);+ const result = review?.attempts?.at(-1)?.review;+ return { ...pilot, status: result ? currentPilotPass(project, pilot) ? 'accepted' : result.verdict : review?.status || 'pending',+ excerptId: review?.attempts?.at(-1)?.excerptId, evidence: result?.evidence || null,+ ...(result && result.verdict !== 'pass' ? { repair: pilotRepair(result, project?.scenes?.find((s) => s.sceneId === pilot.sceneId), project) } : {}) };+ }) } } : {}),+ };+};+const response = (project, run) => {+ const shown = present(run, project);+ return { run: shown, project: { ...project, productionRuns: project.productionRuns.map((r) => r.id === run.id ? shown : r) } };+};function publish(projectId, project, run, action) {- musicVideoEvents.emit('production', { projectId, runId: run.id, run: present(run), action, project });+ const shown = present(run, project);+ musicVideoEvents.emit('production', { projectId, runId: run.id, run: shown, action,+ project: { ...project, productionRuns: project.productionRuns.map((r) => r.id === run.id ? shown : r) } });}async function halt(projectId, runId, { status, reason, error = null }) {- const out = await mutateProjectRecord(projectId, (current) => haltProduction(current, runId, { status, reason, error }));+ const out = await mutateProjectRecord(projectId, (current) => {+ const run = findProductionRun(current, runId);+ return run.status === 'running' ? haltProduction(current, runId, { status, reason, error }) : { project: current, run };+ });const log = status === 'failed' ? console.error : status === 'completed' ? console.log : console.warn;log(`${status === 'completed' ? '✅' : status === 'failed' ? '❌' : '⏸️'} Music Video production ${short(runId)} ${status}${reason ? `: ${reason}` : ''}`);return out;@@ -244,6 +286,10 @@ async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId =// Enforced for ANY chooser — a model's pick outside the pool never reaches the queue.const refused = await assertRouteAllowed(run, choice.route, requirement, env).then(() => null, (err) => err);if (refused) return { halt: { status: 'blocked', reason: refused.message } };+ try { assertProductionPilotRoute(project, run, sceneId, stepKind, choice.route); }+ catch (error) { return { halt: { status: 'blocked', reason: error.message } }; }+ const costUsd = stepPriceUsd({ route: choice.route, project, scene, stepKind });+ await mutateProjectRecord(projectId, (current) => quoteProductionSpend(current, runId, { kind: stepKind, sceneId, costUsd }));const reserved = await mutateProjectRecord(projectId, (current) => reserveProductionStep(current, runId, {kind: stepKind, sceneId, revisionId, plateRepairBasis, route: choice.route, rationale: choice.rationale, processId: PROCESS_ID,@@ -369,6 +415,10 @@ async function takeSteps(projectId, runId) {const step = nextProductionStep(project, run, { jobs: await liveJobs(), processId: PROCESS_ID });if (step.type === 'idle' || step.type === 'wait') return { project, run, action: step };+ if (step.type === 'plan-pilots') {+ await mutateProjectRecord(projectId, (current) => planProductionPilots(current, runId));+ continue;+ }if (step.type === 'halt') {const out = await halt(projectId, runId, { status: step.status, reason: step.reason });@@ -452,24 +502,32 @@ async function takeSteps(projectId, runId) {continue;}- if (step.type === 'review') {+ if (step.type === 'review' || step.type === 'pilot-review') {+ const reviewsSpent = run.steps.filter((s) => s.kind === 'review').length;+ if (reviewsSpent >= run.limits.maxReviewAttempts) {+ const out = await halt(projectId, runId, { status: 'limit-reached', reason: 'The production review budget is exhausted; raise it and resume' });+ return { ...out, action: { type: 'idle' } };+ }const { startAutoReview } = await deps.autoReview();const started = await startAutoReview(projectId, {startSec: step.startSec,endSec: step.endSec,limits: {- maxAttempts: run.limits.maxReviewAttempts,+ maxAttempts: step.type === 'pilot-review' ? 1 : run.limits.maxReviewAttempts - reviewsSpent,maxGenerations: Math.min(AUTO_REVIEW_MAX_GENERATIONS, remainingProductionGenerations(run)),},reviewer: run.reviewer,productionRunId: runId,- ...(run.authoring ? { documentRevisions: true } : {}),+ ...(step.type === 'pilot-review' ? { productionPilotSceneId: step.sceneId } : {}),+ ...(run.authoring && step.type !== 'pilot-review' ? { 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}` });return { ...out, action: { type: 'idle' } };}- await mutateProjectRecord(projectId, (current) => attachProductionReview(current, runId, started.run.id));+ await mutateProjectRecord(projectId, (current) => step.type === 'pilot-review'+ ? attachProductionPilotReview(current, runId, step.sceneId, started.run.id)+ : attachProductionReview(current, runId, started.run.id));console.log(`🔎 Music Video production ${short(runId)} handed the draft [${step.startSec}, ${step.endSec}]s to review ${short(started.run.id)}`);continue;}@@ -550,7 +608,7 @@ export async function startProduction(projectId, { directive, pool: requested, l}));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);- return { project: out.project, run: present(out.run) };+ return response(out.project, out.run);}/**@@ -568,10 +626,9 @@ export async function resumeProduction(projectId, runId, { limits, acceptBasis =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' || (out.run.authoring && review.status === 'running'))) {+ const owned = new Set([out.run.reviewRunId, ...(out.run.pilot?.scenes || []).map((p) => p.reviewRunId)]);+ for (const review of (out.project.autoReviews || []).filter((r) => owned.has(r.id)+ && ['running', 'stopped', 'limit-reached'].includes(r.status))) {const { resumeAutoReview } = await deps.autoReview();const headroom = Math.min(AUTO_REVIEW_MAX_GENERATIONS, review.usage.generations + remainingProductionGenerations(out.run));await resumeAutoReview(projectId, review.id, {@@ -583,22 +640,22 @@ export async function resumeProduction(projectId, runId, { limits, acceptBasis =}advanceInBackground(projectId, runId);const fresh = await requireProject(projectId);- return { project: fresh, run: present(findProductionRun(fresh, runId)) };+ return response(fresh, findProductionRun(fresh, runId));}/** Stop: nothing new is dispatched and queued owned jobs are cancelled; running ones land. */export async function stopProduction(projectId, runId) {const out = await mutateProjectRecord(projectId, (current) => stopProductionOnProject(current, runId));await cancelOwnedJobs(runId);- const review = out.run.reviewRunId ? (out.project.autoReviews || []).find((r) => r.id === out.run.reviewRunId) : null;- if (review?.status === 'running') {+ const owned = new Set([out.run.reviewRunId, ...(out.run.pilot?.scenes || []).map((p) => p.reviewRunId)]);+ for (const review of (out.project.autoReviews || []).filter((r) => owned.has(r.id) && r.status === 'running')) {const { stopAutoReview } = await deps.autoReview();await stopAutoReview(projectId, review.id).catch(() => {});}const fresh = await requireProject(projectId);const run = findProductionRun(fresh, runId);publish(projectId, fresh, run, { type: 'idle' });- return { project: fresh, run: present(run) };+ return response(fresh, run);}/** Cancel (terminal): every owned job still live is cancelled, and the review with its revision. */@@ -606,21 +663,21 @@ 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 owned = new Set([out.run.reviewRunId, ...(out.run.pilot?.scenes || []).map((p) => p.reviewRunId)]);+ for (const review of (out.project.autoReviews || []).filter((r) => owned.has(r.id) && ['running', 'stopped', 'limit-reached'].includes(r.status))) {const { cancelAutoReview } = await deps.autoReview();await cancelAutoReview(projectId, review.id).catch(() => {});}const fresh = await requireProject(projectId);const run = findProductionRun(fresh, runId);publish(projectId, fresh, run, { type: 'idle' });- return { project: fresh, run: present(run) };+ return response(fresh, run);}/** One run as the director sees it (`interrupted` after a restart). */export async function getProduction(projectId, runId) {const project = await requireProject(projectId);- return { run: present(findProductionRun(project, runId)) };+ return { run: present(findProductionRun(project, runId), project) };}// ---- completion events of work a run put in flight --------------------------------@@ -651,7 +708,12 @@ 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) || run.reviewRunId !== review.id) return;+ if (!runningHere(run)) return;+ if (run.pilot?.scenes?.some((pilot) => pilot.reviewRunId === review.id)) {+ if (review.status !== 'running') await advanceProduction(projectId, run.id);+ return;+ }+ if (run.reviewRunId !== review.id) return;if (action?.type === 'revise-document' && run.authoring) {await advanceProduction(projectId, run.id);return;diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 7f8bacc83a..146ef1590a 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -1,6 +1,8 @@import { startProductionOnProject, markProductionPlanned, reserveProductionStep } from './production.js';import { plateReviewEvidence } from '../../lib/musicVideoPlateEvidence.js';import { plateRequirements } from '../../lib/musicVideoPlateEvidence.js';+import { startAutoReviewOnProject, nextAutoReviewStep, beginAttemptReview, deferAttemptReview } from './autoReview.js';+import { pilotDependencies } from './productionPilot.js';import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';/*** Music Video production run (#9066) — orchestration contract with injected@@ -67,7 +69,7 @@ const POOL = [{ kind: 'image', mode: 'codex', model: null },{ kind: 'video', mode: 'local', model: 'ltx-example' },];-const LIMITS = { maxGenerations: 10, maxReviewAttempts: 2 };+const LIMITS = { maxGenerations: 10, maxReviewAttempts: 4 };function seedProject(overrides = {}) {const project = {@@ -77,7 +79,7 @@ function seedProject(overrides = {}) {audioAnalysis: { sections: [{ startSec: 0, endSec: 8, label: 'Verse' }], durationSec: 8 },scenes: [{ sceneId: 'mvs-a', label: 'A', framePrompt: 'a lighthouse', prompt: 'waves roll', startSec: 0, endSec: 4, takes: [] },- { sceneId: 'mvs-b', label: 'B', framePrompt: 'a harbor', prompt: 'boats sway', startSec: 4, endSec: 8, takes: [] },+ { sceneId: 'mvs-b', label: 'B', framePrompt: 'a harbor', prompt: 'boats sway', direction: { camera: 'orbit' }, startSec: 4, endSec: 8, takes: [] },],...overrides,};@@ -134,7 +136,10 @@ beforeEach(() => {});planProject.mockResolvedValue({ scenesAdded: 0 });startAutoReview.mockImplementation(async (projectId, input) => {- const reviewRun = { id: 'mvar-example', status: 'running', productionRunId: input.productionRunId, limits: input.limits, usage: { reviews: 0, generations: 0 } };+ const pilot = input.productionPilotSceneId;+ const reviewRun = { id: pilot ? 'mvar-pilot-' + pilot : 'mvar-example', status: pilot ? 'passed' : 'running', productionRunId: input.productionRunId, limits: input.limits, usage: { reviews: pilot ? 1 : 0, generations: 0 },+ ...(pilot ? { attempts: [{ n: 1, review: { verdict: 'pass', dependencies: pilotDependencies(store.get(projectId), pilot) } }] } : {}) };+ if (pilot) await service.chargeProductionReview(projectId, input.productionRunId, { reviewRunId: reviewRun.id, attemptN: 1, costUsd: 0 });const project = store.get(projectId);project.autoReviews = [...(project.autoReviews || []), reviewRun];return { run: reviewRun };@@ -178,8 +183,8 @@ describe('music video production run (#9066)', () => {completeJob('job-3');completeJob('job-4');await settle();- expect(startAutoReview).toHaveBeenCalledTimes(1);- expect(startAutoReview.mock.calls[0][1]).toMatchObject({ startSec: 0, endSec: 8, productionRunId: theRun().id, limits: { maxAttempts: 2, maxGenerations: 6 } });+ expect(startAutoReview).toHaveBeenCalledTimes(3);+ expect(startAutoReview.mock.calls.at(-1)[1]).toMatchObject({ startSec: 0, endSec: 8, productionRunId: theRun().id, limits: { maxAttempts: 2, maxGenerations: 6 } });expect(theRun()).toMatchObject({ status: 'running', reviewRunId: 'mvar-example', usage: { generations: 4 } });expect(theRun().steps.every((s) => s.status === 'completed' && s.rationale)).toBe(true);@@ -527,7 +532,7 @@ describe('music video production run (#9066)', () => {await settle();completeJob('job-3'); completeJob('job-4');await settle();- const reviewRun = store.get('mv-example').autoReviews[0];+ const reviewRun = store.get('mv-example').autoReviews.find((r) => r.id === theRun().reviewRunId);store.get('mv-example').scenes[0].videoHistoryId = null;musicVideoEvents.emit('auto-review', { projectId: 'mv-example', run: { ...reviewRun }, action: { type: 'generate', revisionId: 'mvrv-example', sections: [{ sceneId: 'mvs-a', kind: 'video' }] } });await settle();@@ -635,13 +640,13 @@ function documentDoubles() {}function passOwnedReview() {const project = store.get('mv-example');- const review = project.autoReviews[0];+ const review = project.autoReviews.find((r) => r.id === project.productionRuns[0].reviewRunId);review.status = 'passed';review.attempts = [{ n: 1, review: { verdict: 'pass', dependencies: captureMusicVideoEvidence(project) } }];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];+ const review = store.get('mv-example').autoReviews.find((r) => r.id === theRun().reviewRunId);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' } });}@@ -1025,3 +1030,176 @@ describe('authored plate preflight', () => {expect(dispatch).not.toHaveBeenCalled();});});++// These regressions pin the public production workflow, not helper internals.+describe('budgeted production pilots (#9351)', () => {+ function board() {+ seedProject({ scenes: Array.from({ length: 4 }, (_, i) => ({+ sceneId: 'shot-' + i, label: 'Example shot ' + i, framePrompt: 'a stage', prompt: 'lights move',+ startSec: i * 2, endSec: (i + 1) * 2, takes: [],+ })) });+ }+ function pendingPilot() {+ startAutoReview.mockImplementationOnce(async (id, input) => {+ await service.chargeProductionReview(id, input.productionRunId, { reviewRunId: 'pilot-example', attemptN: 1, costUsd: 0 });+ const project = store.get(id);+ const review = { id: 'pilot-example', status: 'running', productionRunId: input.productionRunId,+ productionPilotSceneId: input.productionPilotSceneId, attempts: [{ n: 1 }], usage: { reviews: 1, generations: 0 }, limits: input.limits };+ project.autoReviews = [review];+ return { run: review };+ });+ }+ async function reachPilot() {+ await start();+ expect(dispatch.mock.calls.map(([a]) => a.scene.sceneId)).toEqual(['shot-0']);+ completeJob('job-1'); await settle();+ completeJob('job-2'); await settle();+ }+ function verdict(result, dependencies = pilotDependencies(current(), 'shot-0')) {+ const review = store.get('mv-example').autoReviews[0];+ review.status = result.verdict === 'pass' ? 'passed' : 'needs-human';+ review.attempts = [{ n: 1, review: { ...result, dependencies, reviewedAt: new Date().toISOString() } }];+ musicVideoEvents.emit('auto-review', { projectId: 'mv-example', run: clone(review), action: { type: 'idle' } });+ }++ it('selects performance, interaction and the more complex camera operation before ordinary shots', async () => {+ const scenes = Array.from({ length: 6 }, (_, i) => ({ sceneId: 'shot-' + i, framePrompt: 'a stage', prompt: 'movement',+ startSec: i, endSec: i + 1, takes: [] }));+ scenes[1].direction = { actionContract: { cameraConstraints: ['locked'] } };+ scenes[2].direction = { actionContract: { cameraConstraints: ['dolly inward', 'orbit the pair'] } };+ scenes[3].direction = { actionContract: { actions: [{ subject: 'singer' }], reactions: [{ subject: 'listener' }] } };+ scenes[4].shotMode = 'performance';+ scenes[5].visualLayer = 'still';+ seedProject({ scenes, composition: { mode: 'composed' } }); await start();+ expect(theRun().pilot.scenes.map((p) => [p.operation, p.sceneId])).toEqual([+ ['performance', 'shot-4'], ['interaction', 'shot-3'], ['camera', 'shot-2'], ['cutaway', 'shot-0'], ['still', 'shot-5'],+ ]);+ expect(dispatch.mock.calls.map(([a]) => a.scene.sceneId)).not.toContain('shot-1');+ });++ it('holds bulk reservations until a pass, then reuses the pilot without another submission', async () => {+ board(); pendingPilot(); await reachPilot();+ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(startAutoReview.mock.calls[0][1]).toMatchObject({ productionPilotSceneId: 'shot-0', startSec: 0, endSec: 2, limits: { maxAttempts: 1 } });+ expect(() => reserveProductionStep(current(), theRun().id, { kind: 'frame', sceneId: 'shot-1', route: POOL[0], processId: theRun().processId })).toThrow(/pilot/i);+ verdict({ verdict: 'pass', evidence: { continuous: true, continuousFrames: 12 } }); await settle();+ expect(dispatch.mock.calls.slice(2).map(([a]) => a.scene.sceneId)).toEqual(['shot-1', 'shot-2', 'shot-3']);+ expect(current().scenes[0].videoHistoryId).toBe('job-2');+ expect(dispatch.mock.calls.filter(([a]) => a.scene.sceneId === 'shot-0')).toHaveLength(2);+ const shown = (await service.getProduction('mv-example', theRun().id)).run;+ expect(shown.pilot.scenes[0]).toMatchObject({ status: 'accepted', evidence: { continuous: true } });+ expect(shown.accounting.reviews).toBe(1);+ });++ it.each([+ [{ composition: 'fail' }, 'composition'],+ [{ motion: 'fail' }, 'provider-capability'],+ [{ lipSync: 'fail' }, 'temporal-alignment'],+ ])('blocks failed evidence and chooses an edit before any replacement spend (%j)', async (checks, category) => {+ board(); pendingPilot(); await reachPilot();+ verdict({ verdict: 'revise', checks, reason: 'Synthetic failed evidence' }); await settle();+ expect(theRun().status).toBe('blocked');+ await service.resumeProduction('mv-example', theRun().id); await settle();+ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(startAutoReview).toHaveBeenCalledTimes(1);+ expect((await service.getProduction('mv-example', theRun().id)).run.pilot.scenes[0].repair)+ .toMatchObject({ category, expectedGenerationSpendUsd: 0 });+ });++ it('never treats missing provenance as an accepted pilot', async () => {+ board(); pendingPilot(); await reachPilot();+ verdict({ verdict: 'pass' }, null); await settle();+ expect(theRun().status).toBe('blocked');+ expect(dispatch).toHaveBeenCalledTimes(2);+ });++ it('stops late pilot completion and repins it only on explicit Resume after a restart', async () => {+ board(); pendingPilot(); await reachPilot();+ store.get('mv-example').productionRuns[0].processId = 'old-process';+ verdict({ verdict: 'pass' }); await settle();+ expect(dispatch).toHaveBeenCalledTimes(2);+ await service.resumeProduction('mv-example', theRun().id); await settle();+ expect(dispatch).toHaveBeenCalledTimes(5);+ expect(theRun().usage.generations).toBe(5);+ });++ it('does not let a changed allowed route bypass its pilot even after a pass', async () => {+ board(); pendingPilot(); await reachPilot();+ service.__setProductionDepsForTests({ loadEnv: async () => env, dispatch, queue: async () => queue,+ autoReview: async () => autoReview, chooseRoute: async () => ({ route: POOL[1], rationale: 'changed route' }) });+ verdict({ verdict: 'pass' }); await settle();+ expect(theRun().status).toBe('blocked');+ expect(theRun().stopReason).toMatch(/no accepted pilot/);+ expect(dispatch).toHaveBeenCalledTimes(2);+ });++ it('rechecks pilot assets at the final queue boundary and refunds a refused bulk reservation', async () => {+ board(); pendingPilot(); await reachPilot();+ dispatch.mockImplementationOnce(async (args) => {+ store.get('mv-example').scenes[0].referenceImageId = 'changed-plate.png';+ await service.assertProductionSubmission('mv-example', args.tag.productionRunId, args.tag.productionStepKey,+ { sceneId: args.tag.sceneId, kind: 'image' });+ return enqueueing(args);+ });+ verdict({ verdict: 'pass' }); await settle();+ expect(jobs).toHaveLength(2);+ expect(theRun()).toMatchObject({ status: 'blocked', usage: { generations: 2 } });+ expect(theRun().steps.at(-1)).toMatchObject({ status: 'refused', errorCode: 'PRODUCTION_PILOT_REQUIRED' });+ });++ it('keeps late pilot evidence after Stop without releasing the bulk wave', async () => {+ board(); pendingPilot(); await reachPilot();+ await service.stopProduction('mv-example', theRun().id);+ expect(autoReview.stopAutoReview).toHaveBeenCalledWith('mv-example', 'pilot-example');+ verdict({ verdict: 'pass' }); await settle();+ expect(theRun().status).toBe('stopped');+ expect(dispatch).toHaveBeenCalledTimes(2);+ await service.cancelProduction('mv-example', theRun().id); await settle();+ expect(theRun().status).toBe('canceled');+ expect(dispatch).toHaveBeenCalledTimes(2);+ });++ it('resumes an exhausted shared review budget without regenerating any accepted asset', async () => {+ board();+ await start({ limits: { maxGenerations: 10, maxReviewAttempts: 1 } });+ completeJob('job-1'); await settle();+ completeJob('job-2'); await settle();+ for (const id of ['job-3', 'job-4', 'job-5']) completeJob(id);+ await settle();+ for (const id of ['job-6', 'job-7', 'job-8']) completeJob(id);+ await settle();+ expect(theRun().status).toBe('limit-reached');+ expect(dispatch).toHaveBeenCalledTimes(8);+ await service.resumeProduction('mv-example', theRun().id, { limits: { maxReviewAttempts: 3 } }); await settle();+ expect(theRun()).toMatchObject({ status: 'running', reviewRunId: 'mvar-example' });+ expect(dispatch).toHaveBeenCalledTimes(8);+ expect(startAutoReview.mock.calls.at(-1)[1].limits.maxAttempts).toBe(2);+ });++ it('bounds pilot and final review calls together, including unknown costs and concurrent admissions', async () => {+ board(); pendingPilot(); await reachPilot();+ await service.chargeProductionReview('mv-example', theRun().id, { reviewRunId: 'second', attemptN: 1, costUsd: 0 });+ store.get('mv-example').productionRuns[0].limits.maxReviewAttempts = 3;+ const results = await Promise.allSettled([1, 2].map((n) => service.chargeProductionReview('mv-example', theRun().id,+ { reviewRunId: 'race-' + n, attemptN: 1, costUsd: 0 })));+ expect(results.map((r) => r.status).sort()).toEqual(['fulfilled', 'rejected']);+ expect(theRun().steps.filter((s) => s.kind === 'review')).toHaveLength(3);+ store.get('mv-example').productionRuns[0].limits = { ...theRun().limits, maxReviewAttempts: 4, spendCapUsd: 0 };+ await expect(service.chargeProductionReview('mv-example', theRun().id, { reviewRunId: 'unpriced', attemptN: 1, costUsd: null }))+ .rejects.toMatchObject({ code: 'PRODUCTION_COST_UNKNOWN' });+ expect(theRun().steps.filter((s) => s.kind === 'review')).toHaveLength(3);+ });++ it('pauses a failed pilot rather than opening an identical paid revision', () => {+ const project = seedProject();+ const started = startAutoReviewOnProject(project, { startSec: 0, endSec: 4, limits: { maxAttempts: 1, maxGenerations: 2 },+ productionRunId: 'production-example', productionPilotSceneId: 'mvs-a' });+ const dependencies = pilotDependencies(project, 'mvs-a');+ const run = { ...started.run, attempts: [{ n: 1, excerptId: 'draft-example', review: { verdict: 'revise', dependencies }, revisionId: null }] };+ const reviewed = { ...started.project, excerpts: [{ id: 'draft-example', status: 'complete' }], autoReviews: [run] };+ expect(nextAutoReviewStep(reviewed, run)).toMatchObject({ type: 'halt', status: 'needs-human' });+ const begun = beginAttemptReview(started.project, started.run.id);+ const deferred = deferAttemptReview(begun.project, begun.run.id, { code: 'PRODUCTION_BUDGET_EXHAUSTED', message: 'Raise cap and resume' });+ expect(deferred.run).toMatchObject({ status: 'limit-reached', usage: { reviews: 0 }, attempts: [{ review: null }] });+ });+});diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex a15c10e5be..fd241527f4 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -1,3 +1,4 @@+import { productionPilotRenderProject } from './productionPilot.js';import { describe, it, expect, vi, beforeEach } from 'vitest';// Isolate the module's I/O boundaries so the pure builders + resolvers can be@@ -16,6 +17,7 @@ vi.mock('./projects.js', () => ({ getProject: vi.fn(), updateProject: vi.fn(asynimport { existsSync } from 'fs';import {+ planMusicVideoRender,beatSnapClips,buildMusicVideoFfmpegArgs,excerptBoundaryTimes,@@ -433,3 +435,29 @@ describe('frame-grid in-points (#9290)', () => {expect(graph).toContain('trim=end_frame=24');});});++describe('partial-board production pilot rendering (#9351)', () => {+ it('keeps a late pilot on original song time without requiring bulk clips or a composition document', async () => {+ const project = { id: 'pilot-project', uploadedAudioFilename: 'example.wav', composition: { mode: 'document' },+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 25 }, audioAnalysis: { durationSec: 20, beats: [] },+ treatment: { shotDirections: [{ sceneId: 'pilot', medium: 'generated-footage' }] },+ scenes: [+ { sceneId: 'missing-first', startSec: 0, endSec: 10 },+ { sceneId: 'pilot', sectionIndex: 1, startSec: 10, endSec: 15, videoHistoryId: 'pilot-take', referenceImageId: 'plate.png' },+ { sceneId: 'missing-last', startSec: 15, endSec: 20 },+ ] };+ loadHistory.mockResolvedValue([{ id: 'pilot-take', filename: 'pilot.mp4', numFrames: 120, fps: 24, width: 768, height: 512 }]);+ const projected = productionPilotRenderProject(project, 'pilot');+ const plan = await planMusicVideoRender(projected);+ const excerpt = buildMusicVideoFfmpegArgs(plan.clips, plan.audioPath, '/out.mp4',+ { audioDurationSec: 20, frameGrid: plan.composed, excerpt: { startSec: 10, endSec: 15 } });+ expect(excerpt.totalDuration).toBe(5);+ expect(excerpt.sections).toEqual([{ sceneId: 'pilot', layer: 'footage', startSec: 0, endSec: 5 }]);+ const graph = excerpt.args[excerpt.args.indexOf('-filter_complex') + 1];+ expect(graph).toContain('trim=start=10:end=15');+ expect(graph).toContain('atrim=start=10:end=15');+ expect(project.scenes).toHaveLength(3);+ expect(project.composition.mode).toBe('document');+ expect(project.scenes[0].videoHistoryId).toBeUndefined();+ });+});