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
fix: guard code-first music video media submissions (#9301)
[._.]/ Adam Eivyc4be75fb1bac
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxindex 2226d962d3..6bb318016c 100644--- a/client/src/components/musicVideo/AutopilotPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -5,6 +5,7 @@ import Pill from '../ui/Pill.jsx';import useProviderModels from '../../hooks/useProviderModels.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';import ToggleChip from '../ui/ToggleChip.jsx';+import MediumPlanSummary from './MediumPlanSummary.jsx';import {DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS, automationDraftFrom, automationFromDraft,} from '../../lib/musicVideoAutomation.js';@@ -49,7 +50,7 @@ function StepRow({ step }) {);}-function RunView({ run, production }) {+function RunView({ run, production, codeFirst }) {const live = RESUMABLE_RUN_STATUSES.has(run.status);const steps = run.steps || [];const failures = steps.filter((s) => s.error);@@ -83,7 +84,7 @@ function RunView({ run, production }) {<Pause size={12} /> Stop</button>)}- {live && (run.status !== 'running' || run.interrupted) && (+ {live && !codeFirst && (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">@@ -293,11 +294,16 @@ function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, kifunction ProductionSection({ project, production }) {const run = currentProductionRun(project);const active = run && RESUMABLE_RUN_STATUSES.has(run.status);+ const codeFirst = project.productionPolicy?.strategy === 'code-first';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} />}- {!active && <StartForm key={run?.id || 'new'} project={project} production={production} />}+ {run && <RunView run={run} production={production} codeFirst={codeFirst} />}+ {codeFirst && <>+ <MediumPlanSummary project={project} />+ <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} />}</div>);}diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxindex 92c6afe5d0..59e0344419 100644--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -154,6 +154,15 @@ 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', () => {+ 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.queryByRole('button', { name: /Start production/ })).toBeNull();+ });+it('starts only when the director presses Start, with the allowed pool and limits', async () => {api.startMusicVideoProduction.mockResolvedValue({ project: { id: 'p1', productionRuns: [run()] }, run: run() });render(<ProductionHarness initial={{ id: 'p1', productionRuns: [] }} />);diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.jsindex 469ee28bb6..94cf1df6a5 100644--- a/server/routes/musicVideoRevision.test.js+++ b/server/routes/musicVideoRevision.test.js@@ -342,6 +342,37 @@ describe('selective section revision (#8987)', () => {await expect(assertRevisionOpen(project.id, revision.id)).rejects.toMatchObject({ status: 409, code: 'REVISION_CLOSED' });});+ it('enforces code-first video share and a concurrent policy edit at the revision submission boundary', async () => {+ const created = await projects.createProject({ name: 'Example Video' });+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {+ ...current,+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ audioAnalysis: { durationSec: 100 },+ scenes: [{ sceneId: 'selected', startSec: 0, endSec: 20 }],+ treatment: { shotDirections: [{ sceneId: 'selected', medium: 'generated-footage', mediumRationale: 'Selected payoff.' }] },+ excerpts: [{ id: 'mve-code', status: 'complete', startSec: 0, endSec: 20,+ sections: [{ sceneId: 'selected', startSec: 0, endSec: 20 }] }],+ } }));+ const path = `${base(created.id)}/excerpt/mve-code/revisions`;+ const forbidden = await request(app).post(path).send({ sceneIds: ['selected'] });+ expect(forbidden.status).toBe(409);+ expect(forbidden.body.code).toBe('REVISION_MEDIUM_PLAN_CONFLICT');+ expect(h.enqueueJob).not.toHaveBeenCalled();++ await projects.mutateProjectRecord(created.id, (current) => ({ project: {+ ...current, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 20 },+ } }));+ const allowed = await request(app).post(path).send({ sceneIds: ['selected'] });+ expect(allowed.status).toBe(201);+ const revisionId = allowed.body.revision.id;+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {+ ...current, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ } }));+ await expect(assertRevisionOpen(created.id, revisionId, { sceneId: 'selected', kind: 'video' }))+ .rejects.toMatchObject({ code: 'REVISION_MEDIUM_PLAN_CHANGED' });+ expect(h.enqueueJob).not.toHaveBeenCalled();+ });+it('refuses a second open revision, a section outside the draft, and a draft without a section map', async () => {const project = await reviewedProject();const first = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({ sceneIds: ['s1'] });diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex 18935de015..aa70a0a881 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -42,6 +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 { projectAutoReviews } from './autoReview.js';import { projectRevisions } from './revision.js';import { castAndSetsSettled } from './castAndSets.js';@@ -107,7 +108,7 @@ function pruneRuns(runs) {* part of it: the run itself seeds and fills them, and a director editing one* scene's prompt mid-run changes only what that scene generates next.*/-function productionBasisRevision(project) {+export function productionBasisRevision(project, version = 1) {const pick = (value) => value ?? null;return canonicalSnapshotChecksum({concept: pick(project?.concept),@@ -123,6 +124,11 @@ function productionBasisRevision(project) {},pacing: pick(project?.pacing),composition: pick(project?.composition?.mode),+ ...(version >= 2 ? {+ productionPolicy: normalizeMusicVideoProductionPolicy(project?.productionPolicy),+ ...(normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first'+ ? { shotDirections: pick(project?.treatment?.shotDirections) } : {}),+ } : {}),});}@@ -183,6 +189,9 @@ 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');+ }if (project?.composition?.mode === 'code') {throw productionError(409, 'PRODUCTION_UNSUPPORTED', 'A code-rendered project generates no footage — render it directly');}@@ -209,7 +218,7 @@ export function startProductionOnProject(project, {providerId: isNonBlankStr(reviewer.providerId) ? reviewer.providerId : null,model: isNonBlankStr(reviewer.model) ? reviewer.model : null,},- basis: { revision: productionBasisRevision(project), capturedAt: now },+ basis: { version: 2, revision: productionBasisRevision(project, 2), capturedAt: now },usage: { generations: 0, spentUsd: 0 },planned: false,reviewRunId: null,@@ -224,6 +233,29 @@ export function startProductionOnProject(project, {return { project: { ...project, productionRuns: pruneRuns([...projectProductionRuns(project), run]), updatedAt: now }, run };}+/** Final submission guard, called after provider preparation and before queueing. */+export function assertProductionStepOpen(project, runId, stepKey, { sceneId, kind, processId }) {+ const run = findProductionRun(project, runId);+ const step = run.steps.find((entry) => entry.key === stepKey);+ if (run.status !== 'running' || run.processId !== processId || !step || step.status !== 'reserved' || step.sceneId !== sceneId+ || JOB_KIND[step.kind] !== kind) {+ throw productionError(409, 'PRODUCTION_STEP_CLOSED', 'The production step was stopped or changed before submission');+ }+ if (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 (normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first') {+ const plan = summarizeMusicVideoMediumPlan(project);+ const medium = project.treatment?.shotDirections?.find((direction) => direction.sceneId === sceneId)?.medium;+ if (plan.blocked || (kind === 'video' && medium !== 'generated-footage')+ || (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');+ }+ return step;+}+// ---- deriving the next step -------------------------------------------------const SLOT = Object.freeze({ frame: 'referenceImageId', clip: 'videoHistoryId' });@@ -263,9 +295,12 @@ const slotSteps = (run, sceneId, stepKind, revisionId = null) => run.stepsexport function nextProductionStep(project, run, { jobs = [], processId = null } = {}) {if (run.status !== 'running') return { type: 'idle' };if (!processId || run.processId !== processId) return { type: 'idle', interrupted: true };- if (productionBasisRevision(project) !== run.basis.revision) {+ 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.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' };@@ -476,12 +511,11 @@ export const markProductionCastAndSets = (project, runId, now = new Date().toISOexport function rebaseProductionAfterCheckin(project, now = new Date().toISOString()) {const runs = projectProductionRuns(project);if (!runs.some((r) => r.status === 'running' && !r.planned)) return { project };- const revision = productionBasisRevision(project);return {project: {...project,productionRuns: runs.map((r) => (r.status === 'running' && !r.planned- ? { ...r, basis: { revision, capturedAt: now }, updatedAt: now } : r)),+ ? { ...r, basis: { ...r.basis, revision: productionBasisRevision(project, r.basis.version || 1), capturedAt: now }, updatedAt: now } : r)),},};}@@ -518,7 +552,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`);- const basisChanged = productionBasisRevision(project) !== run.basis.revision;+ 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 (basisChanged && !acceptBasis) {throw productionError(409, 'PRODUCTION_BASIS_CHANGED', 'The creative setup changed since Start — resume with the new setup accepted, or cancel');}@@ -537,7 +574,7 @@ export function resumeProductionOnProject(project, runId, { limits, acceptBasisresumedAt: now,stopReason: null,error: null,- ...(basisChanged ? { basis: { revision: productionBasisRevision(project), capturedAt: now } } : {}),+ ...(basisChanged ? { basis: { ...run.basis, revision: productionBasisRevision(project, run.basis.version || 1), capturedAt: now } } : {}),};}, now);}diff --git a/server/services/musicVideo/productionDispatch.js b/server/services/musicVideo/productionDispatch.jsindex 8c9e5325b2..b833bf52fd 100644--- a/server/services/musicVideo/productionDispatch.js+++ b/server/services/musicVideo/productionDispatch.js@@ -72,6 +72,8 @@ async function dispatchFrame({ project, scene, route, tag, settings }) {: { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: route.model, ...common };const params = await withMusicVideoStyle(project, baseParams, route.mode, route.model, settings);await guardRevision(tag, 'image');+ const { assertProductionSubmission } = await import('./productionService.js');+ await assertProductionSubmission(tag.projectId, tag.productionRunId, tag.productionStepKey, { sceneId: tag.sceneId, kind: 'image' });const { jobId } = await enqueueJob({ kind: 'image', params, owner: `music-video-production:${tag.productionRunId}` });return { jobId };}diff --git a/server/services/musicVideo/productionDispatch.test.js b/server/services/musicVideo/productionDispatch.test.jsindex f81aa73c33..79a7079dde 100644--- a/server/services/musicVideo/productionDispatch.test.js+++ b/server/services/musicVideo/productionDispatch.test.js@@ -14,9 +14,11 @@ const enqueueJob = vi.fn(async () => ({ jobId: 'job-image' }));const submitVideoGenJob = vi.fn(async () => ({ jobId: 'job-video' }));vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJob(...a) }));vi.mock('../videoGen/submitJob.js', () => ({ submitVideoGenJob: (...a) => submitVideoGenJob(...a) }));+vi.mock('./productionService.js', () => ({ assertProductionSubmission: vi.fn(async () => {}) }));vi.mock('../imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));const { dispatchProductionStep } = await import('./productionDispatch.js');+const { assertProductionSubmission } = await import('./productionService.js');const project = {id: 'mv-example',@@ -85,6 +87,15 @@ describe('production scene dispatch (#9066)', () => {expect(enqueueJob.mock.calls[0][0].params).not.toHaveProperty('mode');});+ it('refuses an image after provider preparation when the production plan changed before enqueue', async () => {+ assertProductionSubmission.mockRejectedValueOnce(Object.assign(new Error('Plan changed'), { code: 'PRODUCTION_BASIS_CHANGED' }));+ await expect(dispatchProductionStep({ stepKind: 'frame', project, scene,+ route: { kind: 'image', mode: 'codex', model: null }, tag, settings })).rejects.toMatchObject({ code: 'PRODUCTION_BASIS_CHANGED' });+ expect(assertProductionSubmission).toHaveBeenCalledWith(tag.projectId, tag.productionRunId, tag.productionStepKey,+ { sceneId: tag.sceneId, kind: 'image' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });+it('submits a clip with an explicit backend so the install pin ladder cannot substitute one', async () => {const clipTag = { ...tag, productionStepKey: 'clip:mvs-a:base:1' };await dispatchProductionStep({ stepKind: 'clip', project, scene, route: { kind: 'video', mode: 'grok', model: null }, tag: clipTag, settings });diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex 07c191d340..aa9909d333 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -29,6 +29,7 @@ import { musicVideoEvents } from './events.js';import { withAutopilotCutting } from './composition.js';import {attachProductionReview,+ assertProductionStepOpen,cancelProductionOnProject,findProductionRun,haltProduction,@@ -90,6 +91,12 @@ async function requireProject(projectId) {return project;}+/** Read the newest record at the queue boundary, after provider preparation. */+export async function assertProductionSubmission(projectId, runId, stepKey, input) {+ const project = await requireProject(projectId);+ assertProductionStepOpen(project, runId, stepKey, { ...input, processId: PROCESS_ID });+}+async function liveJobs() {const { listJobs } = await deps.queue();return [...listJobs({ kind: 'image' }), ...listJobs({ kind: 'video' })];diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex c1c6359935..0b0d8cd167 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -29,6 +29,7 @@ vi.mock('./projects.js', () => ({const { musicVideoEvents } = await import('./events.js');const service = await import('./productionService.js');+const { productionBasisRevision } = await import('./production.js');// ---- queue, lanes and review doubles ------------------------------------------let jobs;@@ -477,4 +478,45 @@ describe('music video production run (#9066)', () => {const last = dispatch.mock.calls.at(-1)[0];expect(last).toMatchObject({ stepKind: 'clip', tag: { revisionId: 'mvrv-example', sceneId: 'mvs-a' } });});++ 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' });+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('refuses a generation if the director changes to zero code-first allowance during provider preparation', async () => {+ seedProject();+ let release;+ const prepared = new Promise((resolve) => { release = resolve; });+ dispatch.mockImplementationOnce(async (args) => {+ await prepared;+ await service.assertProductionSubmission('mv-example', args.tag.productionRunId, args.tag.productionStepKey,+ { sceneId: args.tag.sceneId, kind: 'image' });+ return enqueueing(args);+ });+ await service.startProduction('mv-example', { pool: POOL, limits: LIMITS });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(theRun().steps[0].status).toBe('reserved');+ store.get('mv-example').productionPolicy = { strategy: 'code-first', maxGeneratedVideoPercent: 0 };+ release();+ await settle();+ expect(jobs).toHaveLength(0);+ 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' });+ });++ it('keeps pre-upgrade legacy run checksums valid after adding the policy-aware basis', async () => {+ seedProject();+ await start();+ const stored = store.get('mv-example');+ stored.productionRuns[0].basis = { revision: productionBasisRevision(stored), capturedAt: stored.productionRuns[0].createdAt };+ completeJob('job-1');+ await settle();+ expect(theRun().status).toBe('running');+ expect(theRun().basis).not.toHaveProperty('version');+ });});diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.jsindex 981f63bc46..3991a5671d 100644--- a/server/services/musicVideo/revision.js+++ b/server/services/musicVideo/revision.js@@ -30,6 +30,8 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { isNonBlankStr } from '../../lib/textUtils.js';+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';+import { normalizeMusicVideoProductionPolicy, summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';import { ensureSceneTakes, reviewSceneTake, TAKE_SLOT } from './takes.js';import { projectExcerpts } from './excerpt.js';@@ -49,6 +51,21 @@ const TAKE_ATTACH_GRACE_MS = 120_000;const revisionError = (status, code, message, context) =>new ServerError(message, { status, code, ...(context ? { context } : {}) });+const codeFirst = (project) => normalizeMusicVideoProductionPolicy(project?.productionPolicy).strategy === 'code-first';+const mediumFor = (project, sceneId) => project?.treatment?.shotDirections?.find((direction) => direction.sceneId === sceneId)?.medium;+const mediumBasis = (project) => canonicalSnapshotChecksum({+ productionPolicy: project?.productionPolicy || null,+ directions: project?.treatment?.shotDirections || null,+ scenes: (project?.scenes || []).map(({ sceneId, startSec, endSec }) => ({ sceneId, startSec, endSec })),+ durationSec: project?.audioAnalysis?.durationSec ?? null,+});++function assertCodeFirstPlan(project) {+ const plan = summarizeMusicVideoMediumPlan(project);+ if (plan.blocked) throw revisionError(409, 'REVISION_MEDIUM_PLAN_CONFLICT',+ plan.unresolved.filter((item) => item.blocking).map((item) => item.message).join(' '));+}+/** The revision array on a project, tolerating a legacy record with none. */export const projectRevisions = (project) => (Array.isArray(project?.revisions) ? project.revisions : []);@@ -117,6 +134,14 @@ export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, norejectIds = new Set(noteIdsByScene.keys());}+ if (codeFirst(project)) {+ assertCodeFirstPlan(project);+ const conflicts = [...rejectIds].filter((sceneId) => !['still', 'generated-footage'].includes(mediumFor(project, sceneId)));+ if (conflicts.length) throw revisionError(409, 'REVISION_MEDIUM_PLAN_CONFLICT',+ 'The review flagged a procedural or existing-footage section. Revise its code or selected asset, or explicitly change the medium plan before retrying.',+ { sceneIds: conflicts });+ }+const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));const skippedSceneIds = [];let next = project;@@ -128,11 +153,12 @@ export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, noconst scene = scenesById.get(section.sceneId);if (!scene) continue; // deleted since the draft — nothing left to keep or reviseconst rejected = rejectIds.has(section.sceneId);- if (section.layer === 'card') {+ if (!codeFirst(project) && section.layer === 'card') {if (rejected) skippedSceneIds.push(section.sceneId);continue;}- const kind = section.layer === 'still' ? 'image' : 'video';+ const kind = codeFirst(project) ? (mediumFor(project, section.sceneId) === 'still' ? 'image' : 'video')+ : section.layer === 'still' ? 'image' : 'video';const assetId = isNonBlankStr(scene[TAKE_SLOT[kind]]) ? scene[TAKE_SLOT[kind]] : null;if (rejected && assetId) {// Materialize a legacy selection as a take first, so the take id the@@ -168,6 +194,7 @@ export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, nostartSec: excerpt.startSec,endSec: excerpt.endSec,status: 'open',+ ...(codeFirst(project) ? { mediumBasis: mediumBasis(project) } : {}),sections: revisionSections,renderExcerptId: null,renderAttempts: 0,@@ -334,9 +361,22 @@ export function cancelRevisionOnProject(project, revisionId, now = new Date().to* there is nothing left to hand this generation's output to. No-op when the* project itself is gone (the route's own lookup reports that separately).*/-export function assertRevisionOpenForGeneration(project, revisionId) {+export function assertRevisionOpenForGeneration(project, revisionId, { sceneId = null, kind = null } = {}) {if (!project) return null;- return resumableRevision(project, revisionId);+ const revision = resumableRevision(project, revisionId);+ if (revision.mediumBasis || codeFirst(project)) {+ if (!revision.mediumBasis || revision.mediumBasis !== mediumBasis(project)) {+ throw revisionError(409, 'REVISION_MEDIUM_PLAN_CHANGED', 'The medium plan or allowance changed since this revision opened');+ }+ assertCodeFirstPlan(project);+ const section = revision.sections.find((entry) => entry.sceneId === sceneId && entry.verdict === 'rejected');+ const medium = mediumFor(project, sceneId);+ if (!section || section.kind !== kind || (kind === 'video' && medium !== 'generated-footage')+ || (kind === 'image' && medium !== 'still')) {+ throw revisionError(409, 'REVISION_MEDIUM_PLAN_CONFLICT', 'This generation request does not match the approved medium for the rejected section');+ }+ }+ return revision;}/**diff --git a/server/services/musicVideo/revision.test.js b/server/services/musicVideo/revision.test.jsnew file mode 100644index 0000000000..b66dffbfbc--- /dev/null+++ b/server/services/musicVideo/revision.test.js@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { assertRevisionOpenForGeneration, startRevisionOnProject } from './revision.js';++const scene = (sceneId, startSec, endSec) => ({ sceneId, startSec, endSec });+const direction = (sceneId, medium) => ({ sceneId, medium, mediumRationale: 'Approved for this shot.' });++function documentProject(percent = 20) {+ const scenes = [scene('code', 0, 30), scene('still', 30, 50), scene('clip', 50, 70)];+ return {+ id: 'mv-example',+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: percent },+ audioAnalysis: { durationSec: 100 },+ treatment: { shotDirections: [direction('code', 'procedural'), direction('still', 'still'), direction('clip', 'generated-footage')] },+ scenes,+ excerpts: [{ id: 'mve-example', status: 'complete', startSec: 0, endSec: 70,+ sections: scenes.map(({ sceneId, startSec, endSec }) => ({ sceneId, startSec, endSec })) }],+ };+}++describe('code-first document review revisions', () => {+ it('routes selected still and footage shots to their approved medium despite document excerpts having no layer', () => {+ const project = documentProject();+ const { project: revised, revision } = startRevisionOnProject(project, 'mve-example', { sceneIds: ['still', 'clip'] });+ expect(revision.sections.filter((section) => section.verdict === 'rejected').map(({ sceneId, kind }) => [sceneId, kind]))+ .toEqual([['still', 'image'], ['clip', 'video']]);+ expect(assertRevisionOpenForGeneration(revised, revision.id, { sceneId: 'clip', kind: 'video' })).toBeTruthy();+ expect(() => assertRevisionOpenForGeneration(revised, revision.id, { sceneId: 'still', kind: 'video' }))+ .toThrow(/approved medium/);+ });++ it('stops review at a procedural finding instead of silently promoting it to footage', () => {+ const project = documentProject();+ expect(() => startRevisionOnProject(project, 'mve-example', { sceneIds: ['code', 'clip'] }))+ .toThrow(/procedural or existing-footage/);+ });++ it('refuses zero or exceeded video share, and a policy edit after the revision opened', () => {+ expect(() => startRevisionOnProject(documentProject(0), 'mve-example', { sceneIds: ['clip'] }))+ .toThrow(/allowance/);+ const project = documentProject();+ const { project: revised, revision } = startRevisionOnProject(project, 'mve-example', { sceneIds: ['clip'] });+ expect(() => assertRevisionOpenForGeneration({ ...revised,+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },+ }, revision.id, { sceneId: 'clip', kind: 'video' })).toThrow(/changed/);+ const retimed = { ...revised, scenes: revised.scenes.map((shot) => shot.sceneId === 'clip' ? { ...shot, endSec: 71 } : shot) };+ expect(() => assertRevisionOpenForGeneration(retimed, revision.id, { sceneId: 'clip', kind: 'video' })).toThrow(/changed/);+ });+});diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.jsindex 8236083c20..3ec4571871 100644--- a/server/services/musicVideo/revisionService.js+++ b/server/services/musicVideo/revisionService.js@@ -57,12 +57,12 @@ export async function startRevision(projectId, excerptId, input = {}) {export async function assertRevisionOpen(projectId, revisionId, { sceneId = null, kind = null } = {}) {if (!revisionId) return;const project = await getProject(projectId);- assertRevisionOpenForGeneration(project, revisionId);+ assertRevisionOpenForGeneration(project, revisionId, { sceneId, kind });if (!project || !runOwningRevision(project, revisionId)) return;const { listJobs } = await import('../mediaJobQueue/index.js');const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];await mutateProjectRecord(projectId, (current) => {- const revision = assertRevisionOpenForGeneration(current, revisionId);+ const revision = assertRevisionOpenForGeneration(current, revisionId, { sceneId, kind });const inFlight = sceneId && revisionGenerationJobs(current, revision, jobs).some((job) => job.params?.musicVideo?.sceneId === sceneId && (!kind || job.kind === kind));if (inFlight) {diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex 2590f855ff..209cd27820 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -210,6 +210,11 @@ const submitValidatedVideoGenJob = async (body, uploads) => {const { assertRevisionOpen } = await import('../musicVideo/revisionService.js');await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });}+ if (body.musicVideo?.productionRunId) {+ const { assertProductionSubmission } = await import('../musicVideo/productionService.js');+ await assertProductionSubmission(body.musicVideo.projectId, body.musicVideo.productionRunId,+ body.musicVideo.productionStepKey, { sceneId: body.musicVideo.sceneId, kind: 'video' });+ }return enqueueJob({ kind: 'video', params });},);diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex 6f913e683d..416006b969 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({prepareVideoGenParams: vi.fn(),preparePerformanceShot: vi.fn(async () => null),assertRevisionOpen: vi.fn(async () => {}),+ assertProductionSubmission: vi.fn(async () => {}),}));vi.mock('../../lib/federatedMediaRequest.js', () => ({@@ -31,6 +32,7 @@ vi.mock('../fableLoom/visualConditioning.js', () => ({vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: mocks.enqueueJob }));vi.mock('../musicVideo/performanceShot.js', () => ({ preparePerformanceShot: mocks.preparePerformanceShot }));vi.mock('../musicVideo/revisionService.js', () => ({ assertRevisionOpen: mocks.assertRevisionOpen }));+vi.mock('../musicVideo/productionService.js', () => ({ assertProductionSubmission: mocks.assertProductionSubmission }));vi.mock('./prepareParams.js', async (importOriginal) => ({...await importOriginal(),cleanupMultipartTemp: mocks.cleanupMultipartTemp,@@ -258,5 +260,20 @@ describe('submitVideoGenJob', () => {await submitVideoGenJob({ prompt: 'singer', backend: 'fal', musicVideo }, {});expect(mocks.assertRevisionOpen).not.toHaveBeenCalled();});++ it('checks the current production policy after video preparation, before queueing', async () => {+ const changed = Object.assign(new Error('The approved plan changed'), { status: 409, code: 'PRODUCTION_BASIS_CHANGED' });+ const prepared = falPrepared();+ mocks.prepareVideoGenParams.mockResolvedValue(prepared);+ mocks.assertProductionSubmission.mockRejectedValueOnce(changed);+ const tagged = { ...musicVideo, productionRunId: 'mvpr-1', productionStepKey: 'clip:scene:base:1' };++ await expect(submitVideoGenJob({ prompt: 'selected shot', backend: 'fal', musicVideo: tagged }, {})).rejects.toBe(changed);+ expect(mocks.prepareVideoGenParams).toHaveBeenCalledTimes(1);+ expect(mocks.assertProductionSubmission).toHaveBeenCalledWith('mv-1', 'mvpr-1', tagged.productionStepKey,+ { sceneId: musicVideo.sceneId, kind: 'video' });+ expect(prepared.cleanupStaged).toHaveBeenCalledTimes(1);+ expect(mocks.enqueueJob).not.toHaveBeenCalled();+ });});});