Skip to content

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

feat: preview and selectively repair stale music video dependencies (#9349)

Adam Eivyc6aa5effd850
diff --git a/client/src/components/musicVideo/AutoReviewPanel.jsx b/client/src/components/musicVideo/AutoReviewPanel.jsx
index 5e39776ed8..913a90298b 100644
--- a/client/src/components/musicVideo/AutoReviewPanel.jsx
+++ b/client/src/components/musicVideo/AutoReviewPanel.jsx
@@ -58,6 +58,7 @@ function AttemptRow({ attempt }) {
</span>
))}
</div>
+ {review?.dependencyState && review.dependencyState.status !== 'current' && <p className="text-port-warning">Historical review — {review.dependencyState.reasons.join('; ')}. This pass cannot be reused.</p>}
{review?.evidence && (
<p className="text-[10px] text-port-text-muted">
Evidence: {review.evidence.boundaryFrames ? 'cut/cue sheet + ' : ''}{review.evidence.continuousFrames || 0} continuous frames
diff --git a/client/src/components/musicVideo/DependencyImpactPanel.jsx b/client/src/components/musicVideo/DependencyImpactPanel.jsx
new file mode 100644
index 0000000000..6157e3f981
--- /dev/null
+++ b/client/src/components/musicVideo/DependencyImpactPanel.jsx
@@ -0,0 +1,41 @@
+import { useEffect, useState } from 'react';
+import { getMusicVideoDependencyImpact } from '../../services/apiMusicVideo.js';
+import { formatCount } from '../../utils/formatters.js';
+
+/** Preview first; only the director's Repair action starts any work. */
+export default function DependencyImpactPanel({ project, busy, onRepair }) {
+ const [result, setResult] = useState(null);
+ const [error, setError] = useState(null);
+ const [retry, setRetry] = useState(0);
+ useEffect(() => {
+ let active = true;
+ setResult(null);
+ setError(null);
+ getMusicVideoDependencyImpact(project.id, { silent: true }).then((impact) => {
+ if (active) setResult(impact);
+ }).catch((err) => {
+ if (active) setError(err.message || 'Could not check asset dependencies');
+ });
+ return () => { active = false; };
+ }, [project, retry]);
+ const revisionActive = (project.revisions || []).some((revision) => ['open', 'rendering'].includes(revision.status));
+ if (error) return <div role="alert" className="text-xs text-port-error">{error} <button type="button" onClick={() => setRetry((value) => value + 1)}>Retry dependency check</button></div>;
+ if (!result || (!result.shots.length && !result.evidence.length)) return null;
+ return (
+ <section aria-label="Stale asset impact" className="rounded border border-port-warning/40 bg-port-warning/5 p-3 space-y-2 text-xs">
+ <h3 className="font-medium">Asset changes need fresh evidence</h3>
+ <ul className="space-y-1">
+ {result.shots.map((shot) => {
+ const scene = project.scenes.find((entry) => entry.sceneId === shot.sceneId);
+ return <li key={shot.sceneId}>{scene?.label || shot.sceneId}: {shot.reasons.join('; ')} → derived clip, composition and review evidence</li>;
+ })}
+ </ul>
+ <p>Up to {formatCount(result.estimate.maxGenerations)} clip submissions ({formatCount(result.estimate.outputSeconds)} seconds of footage); {formatCount(result.estimate.evidenceRebuilds)} evidence records need rebuilding or review. Historical assets are retained.</p>
+ {!result.shots.length && <p>Selected takes can be kept. Rebuild the draft and review it again; historical passing reviews cannot approve changed dependencies.</p>}
+ <button type="button" disabled={busy || revisionActive} onClick={() => onRepair(result.basis)}
+ className="min-h-[44px] rounded border border-port-border px-3 text-port-accent disabled:opacity-50">
+ Repair affected dependencies
+ </button>
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/DependencyImpactPanel.test.jsx b/client/src/components/musicVideo/DependencyImpactPanel.test.jsx
new file mode 100644
index 0000000000..cd256b565e
--- /dev/null
+++ b/client/src/components/musicVideo/DependencyImpactPanel.test.jsx
@@ -0,0 +1,30 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import DependencyImpactPanel from './DependencyImpactPanel.jsx';
+import { getMusicVideoDependencyImpact } from '../../services/apiMusicVideo.js';
+vi.mock('../../services/apiMusicVideo.js', () => ({ getMusicVideoDependencyImpact: vi.fn() }));
+const project = { id: 'example-project', scenes: [{ sceneId: 'a', label: 'Example shot' }], revisions: [] };
+const impact = { basis: 'example-basis', shots: [{ sceneId: 'a', reasons: ['Selected plate changed'] }], evidence: [{ id: 'old-review' }], estimate: { maxGenerations: 1, outputSeconds: 5, evidenceRebuilds: 1 } };
+beforeEach(() => vi.clearAllMocks());
+describe('rendered stale impact', () => {
+ it('shows cause, downstream impact and a bounded estimate before the explicit repair action', async () => {
+ getMusicVideoDependencyImpact.mockResolvedValue(impact);
+ const repair = vi.fn();
+ render(<DependencyImpactPanel project={project} onRepair={repair} />);
+ await screen.findByRole('region', { name: 'Stale asset impact' });
+ expect(screen.getByText(/Example shot: Selected plate changed/)).toBeInTheDocument();
+ expect(screen.getByText(/Up to 1 clip submissions.*5 seconds.*1 evidence/)).toBeInTheDocument();
+ expect(repair).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Repair affected dependencies' }));
+ expect(repair).toHaveBeenCalledWith('example-basis');
+ });
+ it('drops an older project response and keeps an active repair disabled', async () => {
+ let resolveOld;
+ getMusicVideoDependencyImpact.mockReturnValueOnce(new Promise((resolve) => { resolveOld = resolve; })).mockResolvedValueOnce(impact);
+ const { rerender } = render(<DependencyImpactPanel project={project} onRepair={vi.fn()} />);
+ rerender(<DependencyImpactPanel project={{ ...project, id: 'new-project', revisions: [{ status: 'open' }] }} onRepair={vi.fn()} />);
+ await screen.findByRole('region', { name: 'Stale asset impact' });
+ resolveOld({ shots: [], evidence: [] });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Repair affected dependencies' })).toBeDisabled());
+ });
+});
diff --git a/client/src/components/musicVideo/TreatmentProofs.jsx b/client/src/components/musicVideo/TreatmentProofs.jsx
index ba194132de..f9a391ccf9 100644
--- a/client/src/components/musicVideo/TreatmentProofs.jsx
+++ b/client/src/components/musicVideo/TreatmentProofs.jsx
@@ -49,6 +49,7 @@ function ProofRow({ project, proof, onReview }) {
<span className="font-medium">{KIND_LABELS[proof.kind] || proof.kind}</span>
<span className="text-port-text-muted">{proof.sceneIds.map((id) => scenes.get(id)?.label || 'deleted scene').join(' → ')}</span>
</div>
+ {proof.evidence?.dependencyState && proof.evidence.dependencyState.status !== 'current' && <p className="text-port-warning">Historical verdict — {proof.evidence.dependencyState.reasons.join('; ')}. Review current evidence again.</p>}
<p>{proof.artifact}</p>
{proof.risk && <p className="text-port-text-muted">Risk: {proof.risk}</p>}
{proof.route && <p className="text-port-text-muted">Route: {proof.route}</p>}
diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsx
index 04e8a9aa5a..68a24b48e4 100644
--- a/client/src/components/musicVideo/stages/ReviewStage.jsx
+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx
@@ -1,3 +1,4 @@
+import DependencyImpactPanel from '../DependencyImpactPanel.jsx';
import RenderStatusPanel from '../RenderStatusPanel.jsx';
import ExcerptPanel from '../ExcerptPanel.jsx';
import DevArtifactsPanel from '../DevArtifactsPanel.jsx';
@@ -16,6 +17,7 @@ export default function ReviewStage({ board }) {
} = board;
return (
<fieldset disabled={locked} className="min-w-0 space-y-3">
+ <DependencyImpactPanel project={project} busy={revisions.busy} onRepair={revisions.repair} />
<section id="mv-final-video" aria-label="Final render" className="rounded-lg border border-port-border bg-port-card p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-medium">Final render</h3>
diff --git a/client/src/hooks/useMusicVideoRevisions.js b/client/src/hooks/useMusicVideoRevisions.js
index 2bffa07eb3..397c4ae128 100644
--- a/client/src/hooks/useMusicVideoRevisions.js
+++ b/client/src/hooks/useMusicVideoRevisions.js
@@ -1,6 +1,7 @@
import { useState } from 'react';
import toast from '../components/ui/Toast';
import {
+ startMusicVideoDependencyRepair,
startMusicVideoRevision,
resumeMusicVideoRevision,
cancelMusicVideoRevision,
@@ -115,7 +116,12 @@ export default function useMusicVideoRevisions({ project, replaceProject, sceneM
return res;
}));
+ const repair = (basis) => run(() => startMusicVideoDependencyRepair(projectId, basis, { silent: true }).then((res) => {
+ replaceProject(res.project);
+ return res;
+ })).then((res) => res?.revision ? resume(res.revision.id) : null);
+
// Also used by an opt-in auto-review run (#8988), which hands its revised
// sections to the open board over the `music-video:auto-review` event.
- return { busy, revise, resume, cancel, submitSections: generateSections };
+ return { busy, repair, revise, resume, cancel, submitSections: generateSections };
}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 041c99745f..ce61a14b33 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -95,6 +95,8 @@ vi.mock('../services/apiMusicVideo.js', () => ({
addMusicVideoExcerptNote: vi.fn(),
updateMusicVideoExcerptNote: vi.fn(),
deleteMusicVideoExcerptNote: vi.fn(),
+ getMusicVideoDependencyImpact: vi.fn(async () => ({ shots: [], evidence: [] })),
+ startMusicVideoDependencyRepair: vi.fn(),
startMusicVideoRevision: vi.fn(),
resumeMusicVideoRevision: vi.fn(),
cancelMusicVideoRevision: vi.fn(),
@@ -144,7 +146,7 @@ const pushSocket = (event, payload) => act(async () => {
});
vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn(), listUniverseNames: vi.fn(() => Promise.resolve([])) }));
vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));
-vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(), uploadGalleryImage: vi.fn() }));
+vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(async () => ({ status: 'queued', jobId: 'example-frame-job' })), uploadGalleryImage: vi.fn() }));
vi.mock('../hooks/useProviderModels', () => ({
default: () => ({
providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 7306672350..61fa9b0c0a 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -395,3 +395,9 @@ export async function fetchMusicVideoPreviewAsset(url) {
if (!response.ok) throw new Error(`Could not load preview media (${response.status})`);
return response.blob();
}
+
+
+export const getMusicVideoDependencyImpact = (id, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/dependency-impact`, options);
+export const startMusicVideoDependencyRepair = (id, basis, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/dependency-repairs`, { method: 'POST', body: JSON.stringify({ basis }), ...options });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index d5616fe49f..11086b2964 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -197,6 +197,7 @@ goal data together; interrupted intents remain retryable after restore.
- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes, tracked in `data/video-history.json`; indexed into `media_assets` keyed `video:<jobId>`. History file remains authoritative.
- Game asset manifests — immutable `data/games/{id}/manifests/game-assets-v{N}.json` artifacts reference sprite atlas and music-library bytes by stable path + SHA-256; the `games` DB record owns the current pointer and history. Both halves are backed up: PostgreSQL by the required dump, manifests and referenced media by the rsync snapshot.
- Music Video shot action contracts are optional versioned metadata on the existing db-primary project: authored in `treatment.shotDirections[].actionContract`, applied in `scenes[].direction.actionContract`, and snapshotted in take `shotInstruction.actionContract`. They require no seed/backfill or new store; `musicVideoProjects` schema v13 prevents older treatment writers from discarding intent. Clip-relative event times are revalidated before video queue submission.
+- Music Video dependency provenance — versioned plate/clip references, optional crop/mask input revisions, composition-window checksums, and review snapshots live on existing db-primary `musicVideoProject` rows. Repairs keep historical takes and files and reuse serialized revision checkpoints; no new store, seed, or install migration. Legacy evidence without a snapshot remains unverified. The `musicVideoProjects` schema gate prevents older peers from reusing stale evidence; existing asset channels retain byte ownership.
- Music Video development artifacts ("ingredients": a Cast & Sets check-in sheet, animatic, treatment, storyboard) — each version is an immutable file under `data/music-video/{projectId}/dev/{artifactId}/v{N}.{html,md,mp4,png,jpg}`; the `musicVideoProject` record owns the metadata (`devArtifacts[]`: kind, title, review status, notes, version history with each version's data-relative path). Versions are never overwritten and deletes are soft, so a clone that carried the metadata keeps valid pointers. The metadata is **wire-local** (stripped by `stripMusicVideoLocalRenderPins`, restored over a newer remote by `mergeProjectRecord`) because the bytes are not in the project's peer-sync asset manifest; both halves are backed up (PostgreSQL dump + rsync snapshot). Adapter: `server/services/musicVideo/devArtifactStore.js`.
- Music Video composition documents (render style `document`) — each import (zip, a folder inside `data/`, or the shipped `layered` template) is one immutable version folder `data/music-video/{projectId}/composition/{versionId}/` (index.html + scripts, fonts, media); the `musicVideoProject` record's `composition.document` holds the data-relative pointer plus source/size metadata. A clone shares the pointer; a version no project (live or tombstoned) points at is pruned on the next import or detach. The pointer is **wire-local** like the development artifacts (stripped by `stripMusicVideoLocalRenderPins`, restored by `mergeProjectRecord`) — a peer keeps its own and refuses to render without one. Renders stage a job-private copy under `data/music-video-song-renders/{jobId}/` (swept at boot, excluded from backups). Adapter: `server/services/musicVideo/compositionDocument.js`.
- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.
diff --git a/server/lib/README.md b/server/lib/README.md
index 39dd29a122..21d2d55ad5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -812,3 +812,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoActionContract.js` | Versioned shot intent shape/timing validation and clip-relative frame/motion prompt compilation, shared by treatment and the board. |
| `sheetPointers.js` | Browser-safe persisted character-sheet layout: `LEGACY_SHEET_VARIANT_ID`, `readSheetPointer`, `listSheetPointers`, identity-preserving `applySheetPointerToCharacter`, and default-variant browser adapter `applySheetPointer`. |
| `musicVideoGrade.js` | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. |
+| `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 8401af69b9..8f8a8af840 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -796,3 +796,4 @@ export * from './imageLimits.js';
export * from './musicVideoActionContract.js';
export * from './musicVideoGrade.js';
+export * from './musicVideoDependencies.js';
diff --git a/server/lib/musicVideoDependencies.js b/server/lib/musicVideoDependencies.js
new file mode 100644
index 0000000000..b83e31342b
--- /dev/null
+++ b/server/lib/musicVideoDependencies.js
@@ -0,0 +1,177 @@
+/** Versioned Music Video provenance. Only pointers/checksums live on project rows. */
+import { canonicalSnapshotChecksum } from './snapshotChecksum.js';
+
+export const MUSIC_VIDEO_DEPENDENCY_VERSION = 1;
+const slots = { plate: 'referenceImageId', clip: 'videoHistoryId' };
+const checksum = (value) => canonicalSnapshotChecksum(value);
+const selectedTake = (scene, role, assetId = scene?.[slots[role]]) => (scene?.takes || [])
+ .find((take) => take.kind === (role === 'plate' ? 'image' : 'video') && take.assetId === assetId);
+const assetRef = (scene, role, assetId = scene?.[slots[role]]) => ({
+ role, sceneId: scene.sceneId, assetId: assetId || null,
+ revision: checksum({ assetId: assetId || null, inputs: selectedTake(scene, role, assetId)?.inputAssets || [] }),
+});
+const layerRef = (scene) => ({ role: 'layer', sceneId: scene.sceneId, assetId: scene.sceneId,
+ revision: checksum(Object.fromEntries(['startSec', 'endSec', 'visualLayer', 'stillMove', 'cardText', 'cardColor', 'shotMode', 'loop']
+ .map((key) => [key, scene[key] ?? null]))) });
+const snapshot = (references) => ({ version: MUSIC_VIDEO_DEPENDENCY_VERSION, references });
+
+/** Capture the actual submitted plate, including optional crop/mask provenance. */
+export function captureTakeDependencies(scene, sourceImageId = scene?.referenceImageId) {
+ return snapshot(sourceImageId ? [assetRef(scene, 'plate', sourceImageId)] : []);
+}
+
+const intersects = (scene, startSec, endSec) => !(typeof scene.startSec === 'number' && typeof scene.endSec === 'number')
+ || (scene.startSec < endSec && scene.endSec > startSec);
+const compositionRef = (project, startSec, endSec) => {
+ const composition = project.composition || null;
+ const value = composition ? { ...composition,
+ cues: (composition.cues || []).filter((cue) => intersects(cue, startSec, endSec)),
+ } : null;
+ return { role: 'composition', assetId: 'composition', revision: checksum(value), startSec, endSec };
+};
+
+/** Evidence tracks its rendered window, selected layers and transitive take inputs. */
+export function captureMusicVideoEvidence(project, { sceneIds = null, startSec = 0, endSec = 36000, composition = true } = {}) {
+ const references = [];
+ for (const scene of project.scenes || []) {
+ if (sceneIds ? !sceneIds.includes(scene.sceneId) : !intersects(scene, startSec, endSec)) continue;
+ references.push(layerRef(scene));
+ const role = scene.visualLayer === 'still' ? 'plate' : scene.visualLayer === 'card' ? null : 'clip';
+ if (!role) continue;
+ references.push(assetRef(scene, role));
+ const take = selectedTake(scene, role);
+ if (take?.dependencies) references.push(...take.dependencies.references);
+ else if (role === 'clip' && take?.sourceImageId) references.push(...captureTakeDependencies(scene, take.sourceImageId).references);
+ }
+ if (composition) {
+ const sceneSet = (project.scenes || []).filter((scene) => intersects(scene, startSec, endSec)).map((scene) => scene.sceneId).sort();
+ references.push({ role: 'window', assetId: 'scene-set', startSec, endSec, sceneIds: sceneSet, revision: checksum(sceneSet) });
+ references.push(compositionRef(project, startSec, endSec));
+ }
+ return snapshot(references);
+}
+
+/** Absent legacy evidence is unknown, never an affirmative current verdict. */
+export function musicVideoDependencyChanges(project, dependencies) {
+ if (!dependencies || dependencies.version !== MUSIC_VIDEO_DEPENDENCY_VERSION || !Array.isArray(dependencies.references)) {
+ return [{ role: 'unknown', reason: 'Dependency evidence was not recorded; review again' }];
+ }
+ const changes = [];
+ for (const ref of dependencies.references) {
+ let current;
+ const scene = (project.scenes || []).find((entry) => entry.sceneId === ref.sceneId);
+ if (ref.role === 'window') current = { assetId: 'scene-set', revision: checksum((project.scenes || []).filter((scene) => intersects(scene, ref.startSec, ref.endSec)).map((scene) => scene.sceneId).sort()) };
+ else if (ref.role === 'composition') current = compositionRef(project, ref.startSec, ref.endSec);
+ else if (!scene) current = null;
+ else if (slots[ref.role]) current = assetRef(scene, ref.role);
+ else if (ref.role === 'layer') current = layerRef(scene);
+ if (!current || current.assetId !== ref.assetId || current.revision !== ref.revision) {
+ changes.push({ ...ref, reason: `${ref.role === 'plate' ? 'Selected plate or its crop/mask inputs' : ref.role === 'clip' ? 'Selected clip' : ref.role === 'layer' ? 'Shot timing or composition layer' : 'Composition'} changed` });
+ }
+ }
+ return changes;
+}
+
+export function musicVideoTakeChanges(project, scene, take) {
+ if (take?.dependencies) return musicVideoDependencyChanges(project, take.dependencies);
+ // Pre-provenance generated clips still recorded their actual source basename.
+ if (take?.sourceImageId && take.sourceImageId !== scene.referenceImageId) {
+ return [{ role: 'plate', sceneId: scene.sceneId, reason: 'Selected plate changed' }];
+ }
+ return [];
+}
+
+/** Before a write, materialize legacy provenance from the PRE-image, never new inputs. */
+export function retainMusicVideoDependencies(before, after) {
+ const previousScenes = new Map((before.scenes || []).map((scene) => [scene.sceneId, scene]));
+ const scenes = (after.scenes || []).map((scene) => {
+ const previous = previousScenes.get(scene.sceneId);
+ if (!previous) return scene;
+ const takes = (scene.takes || []).map((take) => {
+ if (take.dependencies || take.kind !== 'video') return take;
+ const old = (previous.takes || []).find((entry) => entry.takeId === take.takeId);
+ const source = old?.sourceImageId || (old ? (['legacy', 'manual'].includes(old.source) ? previous.referenceImageId : null)
+ : previous.videoHistoryId === take.assetId ? previous.referenceImageId : null);
+ return source ? { ...take, dependencies: captureTakeDependencies(previous, source) } : take;
+ });
+ return { ...scene, takes };
+ });
+ // Existing evidence without a trustworthy snapshot remains unknown. Do not
+ // bless historical passes by taking a snapshot of today's selections.
+ return presentMusicVideoDependencies({ ...after, scenes });
+}
+
+/** Read-only downstream preview. Generation count is an upper bound, not a price quote. */
+export function musicVideoDependencyImpact(project, performanceChanges = []) {
+ const shots = [];
+ for (const scene of project.scenes || []) {
+ const take = selectedTake(scene, 'clip') || (!scene.videoHistoryId
+ ? (scene.takes || []).findLast((entry) => entry.kind === 'video' && entry.status === 'rejected') : null);
+ const changes = take ? musicVideoTakeChanges(project, scene, take) : [];
+ const audio = performanceChanges.filter((entry) => entry.sceneId === scene.sceneId);
+ const reasons = [...new Set([...changes.map((entry) => entry.reason), ...audio.map((entry) => entry.reason)])];
+ if (reasons.length) shots.push({ sceneId: scene.sceneId, kind: 'video', assetId: take?.assetId || scene.videoHistoryId,
+ reasons, durationSec: Math.max(0, (scene.endSec || 0) - (scene.startSec || 0)) });
+ }
+ const affected = new Set(shots.map((shot) => shot.sceneId));
+ const evidence = [];
+ const check = (kind, id, dependencies, scope = {}) => {
+ const changes = musicVideoDependencyChanges(project, dependencies);
+ const transitive = (dependencies?.references || []).some((ref) => affected.has(ref.sceneId));
+ if (changes.length || transitive) evidence.push({ kind, id, reasons: [...new Set([
+ ...changes.map((entry) => entry.reason), ...(transitive ? ['Derived clip is stale'] : []),
+ ])], ...scope });
+ };
+ if (project.renderHistoryId) check('render', project.renderHistoryId, project.renderDependencies);
+ for (const excerpt of project.excerpts || []) {
+ if (excerpt.status === 'complete') check('excerpt', excerpt.id, excerpt.dependencies, { startSec: excerpt.startSec, endSec: excerpt.endSec });
+ }
+ for (const proof of project.treatment?.proofs || []) {
+ if (proof.status === 'passed') check('proof', proof.id, proof.evidence?.dependencies);
+ }
+ for (const run of project.autoReviews || []) {
+ for (const attempt of run.attempts || []) {
+ if (attempt.review?.verdict === 'pass') check('review', run.id, attempt.review.dependencies);
+ }
+ }
+ const estimate = { maxGenerations: shots.length, outputSeconds: shots.reduce((sum, shot) => sum + shot.durationSec, 0),
+ evidenceRebuilds: evidence.length };
+ return { version: MUSIC_VIDEO_DEPENDENCY_VERSION, basis: checksum({ shots, evidence,
+ current: captureMusicVideoEvidence(project) }), shots, evidence, estimate };
+}
+
+/** Bounded projection for readers: retain verdicts/assets, expose their validity separately. */
+export function presentMusicVideoDependencies(project) {
+ if (!project) return project;
+ const state = (dependencies) => {
+ const changes = musicVideoDependencyChanges(project, dependencies);
+ return { status: changes.length ? (changes[0].role === 'unknown' ? 'unknown' : 'stale') : 'current',
+ reasons: [...new Set(changes.map((change) => change.reason))] };
+ };
+ return { ...project,
+ scenes: (project.scenes || []).map((scene) => ({ ...scene, takes: (scene.takes || []).map((take) => ({ ...take,
+ ...(take.dependencies ? { dependencyState: state(take.dependencies) } : {}),
+ })) })),
+ ...(project.excerpts ? { excerpts: project.excerpts.map((excerpt) => ({ ...excerpt, dependencyState: state(excerpt.dependencies) })) } : {}),
+ ...(project.treatment ? { treatment: { ...project.treatment, proofs: (project.treatment.proofs || []).map((proof) => ({ ...proof,
+ ...(proof.evidence ? { evidence: { ...proof.evidence, dependencyState: state(proof.evidence.dependencies) } } : {}),
+ })) } } : {}),
+ ...(project.autoReviews ? { autoReviews: project.autoReviews.map((run) => ({ ...run, attempts: (run.attempts || []).map((attempt) => ({ ...attempt,
+ ...(attempt.review ? { review: { ...attempt.review, dependencyState: state(attempt.review.dependencies) } } : {}),
+ })) })) } : {}),
+ };
+}
+
+
+/** Clones reuse immutable bytes while remapping their scene-scoped provenance. */
+export function remapMusicVideoDependencies(dependencies, sceneIdMap) {
+ if (!dependencies?.references) return dependencies;
+ return { ...dependencies, references: dependencies.references.map((ref) => {
+ const sceneId = sceneIdMap.get(ref.sceneId) || ref.sceneId;
+ if (ref.role === 'window' && ref.sceneIds) {
+ const sceneIds = ref.sceneIds.map((id) => sceneIdMap.get(id) || id).sort();
+ return { ...ref, sceneIds, revision: checksum(sceneIds) };
+ }
+ return { ...ref, ...(ref.sceneId ? { sceneId } : {}), ...(ref.role === 'layer' ? { assetId: sceneId } : {}) };
+ }) };
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b7be73a23f..bdc46aed02 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -219,6 +219,8 @@ export const musicVideoTakeInputSchema = z.object({
source: z.enum(['generated', 'imported']).optional(),
provider: providerSlug.optional(),
originalName: z.string().max(255).optional(),
+ sourceImageId: galleryImageName.optional(),
+ inputAssets: z.array(z.object({ role: z.enum(['crop', 'mask']), assetId: galleryImageName, revision: z.number().int().min(1).max(1000000) }).strict()).max(4).optional(),
use: z.enum(MUSIC_VIDEO_TAKE_USES).optional(),
}).strict().superRefine((take, ctx) => {
const check = take.kind === 'image' ? galleryImageName : videoHistoryIdSchema;
@@ -633,6 +635,8 @@ export const musicVideoExcerptNoteUpdateSchema = z.object({
// Reject the flagged sections of a reviewed draft excerpt and regenerate only
// those. `sceneIds` names the sections explicitly; omitted, every section
// holding a `flagged` note is revised. See services/musicVideo/revision.js.
+export const musicVideoDependencyRepairSchema = z.object({ basis: z.string().min(1).max(128) }).strict();
+
export const musicVideoRevisionStartSchema = z.object({
sceneIds: z.array(z.string().min(1).max(200)).min(1).max(500).optional(),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 56243b7be2..ce9a0da805 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -658,7 +658,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v14 = selected conditioning source/speaker and separate temporal lip-sync
// evidence (#9347). Older peers can drop source intent and pass equal-length
// misaligned output, so reject ahead transfers. Absent fields stay legacy.
- musicVideoProjects: 14,
+ // v15 = versioned take and review dependency evidence. Older peers would
+ // reuse stale passes or render clips derived from a replaced plate. Legacy
+ // evidence remains unknown; no historical verdict is retroactively blessed.
+ musicVideoProjects: 15,
// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)
// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,
// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 4ea65bd88e..b397eb3598 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -46,6 +46,7 @@ import {
musicVideoCodeGenerateSchema,
musicVideoExcerptNoteSchema,
musicVideoExcerptNoteUpdateSchema,
+ musicVideoDependencyRepairSchema,
musicVideoRevisionStartSchema,
musicVideoRevisionReleaseSchema,
musicVideoAutoReviewStartSchema,
@@ -112,6 +113,8 @@ import { startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild,
import { preparePublishDraft, submitPublishDraft, discardPublishDraft, recordPublishPost } from '../services/musicVideo/publish/index.js';
import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';
import {
+ getDependencyImpact,
+ startDependencyRepair,
startRevision, resumeRevision, cancelRevision, releaseRevisionSection,
} from '../services/musicVideo/revisionService.js';
import {
@@ -735,6 +738,15 @@ router.delete('/:id/excerpt/:excerptId/notes/:noteId', asyncHandler(async (req,
// `needsGeneration` for the board to generate; once all hold one, the draft
// window re-renders. A section holding a take is never asked to generate again,
// so a render retry never re-submits paid generation.
+router.get('/:id/dependency-impact', asyncHandler(async (req, res) => {
+ res.json(await getDependencyImpact(req.params.id));
+}));
+
+router.post('/:id/dependency-repairs', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoDependencyRepairSchema, req.body || {});
+ res.status(201).json(await startDependencyRepair(req.params.id, input));
+}));
+
router.post('/:id/excerpt/:excerptId/revisions', asyncHandler(async (req, res) => {
const input = validateRequest(musicVideoRevisionStartSchema, req.body || {});
res.status(201).json(await startRevision(req.params.id, req.params.excerptId, input));
@@ -962,12 +974,15 @@ async function takeAssetExists(kind, assetId) {
// Add one candidate take to a scene: the synchronous image lane's inline
// render, or an asset the director imports from the gallery.
router.post('/:id/scenes/:sceneId/takes', asyncHandler(async (req, res) => {
- const { kind, assetId, source = 'imported', provider, originalName, use } = validateRequest(musicVideoTakeInputSchema, req.body);
+ const { kind, assetId, source = 'imported', provider, originalName, use, sourceImageId, inputAssets } = validateRequest(musicVideoTakeInputSchema, req.body);
if (!(await takeAssetExists(kind, assetId))) {
throw new ServerError(`${kind === 'image' ? 'Image' : 'Video'} not found in this install's media library`, { status: 400, code: 'TAKE_ASSET_NOT_FOUND' });
}
+ for (const imageId of [sourceImageId, ...(inputAssets || []).map((input) => input.assetId)].filter(Boolean)) {
+ if (!(await takeAssetExists('image', imageId))) throw new ServerError('Dependency image not found', { status: 400, code: 'TAKE_ASSET_NOT_FOUND' });
+ }
const { scene, appended } = await appendSceneTakes(req.params.id, req.params.sceneId, [{
- kind, assetId, source, provider: provider ?? (source === 'generated' ? 'portos' : null), originalName, use,
+ kind, assetId, source, provider: provider ?? (source === 'generated' ? 'portos' : null), originalName, use, sourceImageId, inputAssets,
}]);
res.status(201).json({ scene, take: appended[0] });
}));
diff --git a/server/routes/musicVideoDependencies.test.js b/server/routes/musicVideoDependencies.test.js
new file mode 100644
index 0000000000..77f362e8ae
--- /dev/null
+++ b/server/routes/musicVideoDependencies.test.js
@@ -0,0 +1,108 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { mkdirSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { EventEmitter } from 'events';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+import { captureMusicVideoEvidence } from '../lib/musicVideoDependencies.js';
+import { recordAttemptReview, nextAutoReviewStep } from '../services/musicVideo/autoReview.js';
+
+const ROOT = () => lazyTempDataRoot('mv-dependencies-');
+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), { dataRoot: ROOT }));
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+vi.mock('../services/mediaJobQueue/index.js', () => ({ listJobs: vi.fn(() => []), cancelJob: vi.fn(), mediaJobEvents: new EventEmitter() }));
+vi.mock('../services/musicVideo/excerptRender.js', () => ({ startExcerptRender: vi.fn(async () => ({ jobId: 'example-render', excerptId: 'example-excerpt' })), cancelExcerptRender: vi.fn(), attachExcerptRenderSseClient: vi.fn() }));
+const { default: router } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+const { assertRevisionOpen } = await import('../services/musicVideo/revisionService.js');
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', router);
+app.use(errorMiddleware);
+let project;
+const base = () => `/api/music-video/${project.id}`;
+const fresh = () => projects.getProject(project.id);
+const impact = () => request(app).get(`${base()}/dependency-impact`);
+
+beforeEach(async () => {
+ mkdirSync(join(ROOT(), 'images'), { recursive: true });
+ for (const image of ['a.png', 'b.png', 'new.png', 'mask.png']) writeFileSync(join(ROOT(), 'images', image), 'synthetic-image');
+ writeFileSync(join(ROOT(), 'video-history.json'), JSON.stringify(['clip-a', 'clip-b', 'clip-new'].map((id) => ({ id, filename: `${id}.mp4` }))));
+ project = await projects.createProject({ name: 'Example dependency project' });
+ await projects.updateProject(project.id, { scenes: ['a', 'b'].map((id, i) => ({ sceneId: id, startSec: i * 5, endSec: i * 5 + 5, visualLayer: 'footage', takes: [] })) });
+ for (const id of ['a', 'b']) {
+ await request(app).post(`${base()}/scenes/${id}/takes`).send({ kind: 'image', assetId: `${id}.png` });
+ await request(app).post(`${base()}/scenes/${id}/takes`).send({ kind: 'video', assetId: `clip-${id}`, sourceImageId: `${id}.png`, source: 'generated' });
+ }
+ await projects.mutateProjectRecord(project.id, (current) => ({ project: { ...current, excerpts: ['a', 'b'].map((id, i) => ({ id: `excerpt-${id}`, status: 'complete', startSec: i * 5, endSec: i * 5 + 5, dependencies: captureMusicVideoEvidence(current, { startSec: i * 5, endSec: i * 5 + 5 }) })) } }));
+});
+afterAll(cleanupTempDataRoots);
+
+describe('public dependency save / repair / review workflow', () => {
+ it('stales only dependents of a changed plate and keeps history through cancel, restart and duplicate resumes', async () => {
+ expect((await impact()).body.shots).toEqual([]);
+ await request(app).patch(`${base()}/scenes/a`).send({ referenceImageId: 'new.png' });
+ const preview = (await impact()).body;
+ expect(preview.shots.map((shot) => shot.sceneId)).toEqual(['a']);
+ expect(preview.evidence.map((entry) => entry.id)).toEqual(['excerpt-a']);
+ expect(preview.estimate).toMatchObject({ maxGenerations: 1, outputSeconds: 5 });
+ expect((await fresh()).scenes[1].takes.find((take) => take.assetId === 'clip-b').dependencyState.status).toBe('current');
+ const opened = await request(app).post(`${base()}/dependency-repairs`).send({ basis: preview.basis });
+ expect(opened.status).toBe(201);
+ expect(opened.body.project.scenes[0].referenceImageId).toBe('new.png');
+ expect(opened.body.project.scenes[0].videoHistoryId).toBeNull();
+ expect(opened.body.project.scenes[0].takes.some((take) => take.assetId === 'clip-a')).toBe(true);
+ const revisionId = opened.body.revision.id;
+ const resumed = await request(app).post(`${base()}/revisions/${revisionId}/resume`);
+ expect(resumed.body.needsGeneration).toEqual([{ sceneId: 'a', kind: 'video' }]);
+ expect((await request(app).post(`${base()}/revisions/${revisionId}/resume`)).body.needsGeneration).toEqual([]);
+ await assertRevisionOpen(project.id, revisionId, { sceneId: 'a', kind: 'video' });
+ await expect(assertRevisionOpen(project.id, revisionId, { sceneId: 'a', kind: 'video' })).rejects.toMatchObject({ code: 'REVISION_SECTION_IN_FLIGHT' });
+ await request(app).post(`${base()}/revisions/${revisionId}/cancel`);
+ await expect(assertRevisionOpen(project.id, revisionId, { sceneId: 'a', kind: 'video' })).rejects.toMatchObject({ code: 'REVISION_CLOSED' });
+ const restarted = await request(app).post(`${base()}/dependency-repairs`).send({ basis: (await impact()).body.basis });
+ expect(restarted.status).toBe(201);
+ await request(app).post(`${base()}/scenes/a/takes`).send({ kind: 'video', assetId: 'clip-new', sourceImageId: 'new.png', source: 'generated' });
+ expect((await request(app).post(`${base()}/revisions/${restarted.body.revision.id}/resume`)).body.needsGeneration).toEqual([]);
+ expect((await fresh()).scenes[0].takes.filter((take) => take.assetId === 'clip-new')).toHaveLength(1);
+ expect((await fresh()).scenes[1].videoHistoryId).toBe('clip-b');
+ });
+
+ it('refuses a stale preview and invalidates passing reviews including an in-flight review race', async () => {
+ const current = await fresh();
+ const run = { id: 'run-example', status: 'running', startSec: 0, endSec: 5, usage: { reviews: 1, generations: 0 }, limits: { maxAttempts: 2, maxGenerations: 1 }, attempts: [{ excerptId: 'excerpt-a' }] };
+ const before = { ...current, autoReviews: [run] };
+ const passed = recordAttemptReview(before, run.id, { verdict: 'pass', findings: [] }).project;
+ expect(passed.autoReviews[0].status).toBe('passed');
+ await projects.mutateProjectRecord(project.id, () => ({ project: passed }));
+ const preview = (await impact()).body;
+ await request(app).patch(`${base()}/scenes/a`).send({ referenceImageId: 'new.png' });
+ const response = await request(app).post(`${base()}/dependency-repairs`).send({ basis: preview.basis });
+ expect(response.status).toBe(409);
+ const changed = await fresh();
+ expect(changed.autoReviews[0].attempts[0].review.dependencyState.status).toBe('stale');
+ expect(nextAutoReviewStep(changed, { ...changed.autoReviews[0], status: 'running' })).toMatchObject({ type: 'halt', status: 'needs-human' });
+ const raced = recordAttemptReview({ ...changed, autoReviews: [run] }, run.id, { verdict: 'pass', findings: [] });
+ expect(raced.run.status).toBe('needs-human');
+ expect(raced.run.attempts[0].review.verdict).toBe('inconclusive');
+ });
+
+ it('keeps reused take provenance current when cloning a project', async () => {
+ const clone = await projects.cloneProject(project.id);
+ expect(clone.scenes[0].sceneId).not.toBe('a');
+ const result = await request(app).get(`/api/music-video/${clone.id}/dependency-impact`);
+ expect(result.status).toBe(200);
+ expect(result.body.shots).toEqual([]);
+ });
+
+ it('keeps legacy assets loadable but never blesses a historical review without dependency evidence', async () => {
+ await projects.updateProject(project.id, { scenes: [{ sceneId: 'legacy', startSec: 0, endSec: 5, referenceImageId: 'a.png', videoHistoryId: 'clip-a' }], excerpts: [{ id: 'old', status: 'complete', startSec: 0, endSec: 5 }] });
+ await request(app).patch(`${base()}/scenes/legacy`).send({ referenceImageId: 'new.png' });
+ const result = (await impact()).body;
+ expect(result.shots.map((shot) => shot.sceneId)).toEqual(['legacy']);
+ expect(result.evidence[0].reasons).toContain('Dependency evidence was not recorded; review again');
+ expect((await fresh()).scenes[0].takes.find((take) => take.assetId === 'clip-a').dependencies.version).toBe(1);
+ });
+});
diff --git a/server/routes/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.js
index f62d76ebe6..b5d454123f 100644
--- a/server/routes/musicVideoTreatment.test.js
+++ b/server/routes/musicVideoTreatment.test.js
@@ -13,6 +13,7 @@ import express from 'express';
import { mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { request } from '../lib/testHelper.js';
+import { captureMusicVideoEvidence } from '../lib/musicVideoDependencies.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
@@ -456,7 +457,7 @@ describe('treatment proofs, clone and motion references', () => {
expect(clip.status).toBe(422);
expect(clip.body.error).toMatch(/final render/);
- await projects.updateProject(project.id, { renderHistoryId: 'render-1' });
+ await projects.updateProject(project.id, { renderHistoryId: 'render-1', renderDependencies: captureMusicVideoEvidence(await projects.getProject(project.id)) });
const passed = await review(body.treatment.revision, { status: 'passed', evidence: { videoHistoryId: 'render-1', note: 'cut lands on the downbeat, text readable' } });
expect(passed.status).toBe(200);
const stored = (await reload(project.id)).treatment.proofs.find((p) => p.id === seq.id);
diff --git a/server/services/musicVideo/autoReview.js b/server/services/musicVideo/autoReview.js
index 1b02b9020b..607eb94c0e 100644
--- a/server/services/musicVideo/autoReview.js
+++ b/server/services/musicVideo/autoReview.js
@@ -33,6 +33,7 @@
* it verbatim and has no route that acts on it, so no schema bump is needed.
*/
+import { musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
@@ -183,6 +184,9 @@ export function nextAutoReviewStep(project, run) {
}
return { type: 'review', excerptId: attempt.excerptId };
}
+ if (!attempt.revisionId && musicVideoDependencyChanges(project, attempt.review.dependencies).length) {
+ return { type: 'halt', status: 'needs-human', reason: 'The reviewed dependencies changed or were not recorded — rebuild and review the draft again' };
+ }
// A review recorded while the run was paused keeps its verdict for resume.
if (attempt.review.verdict === 'pass') return { type: 'halt', status: 'passed', reason: null };
if (attempt.review.verdict !== 'revise') {
@@ -283,20 +287,22 @@ export function recordAttemptReview(project, runId, review, now = new Date().toI
const excerpt = projectExcerpts(project).find((e) => e.id === attempt.excerptId);
const spanSec = excerpt ? excerpt.endSec - excerpt.startSec : 0;
const findings = (Array.isArray(review.findings) ? review.findings : []).map((f) => cleanFinding(f, spanSec)).filter(Boolean).slice(0, MAX_FINDINGS);
- const stored = { ...review, findings, reviewedAt: now };
+ const stale = musicVideoDependencyChanges(project, excerpt?.dependencies).length > 0;
+ const result = stale ? { ...review, verdict: 'inconclusive', reason: 'The draft dependencies changed or were not recorded — rebuild and review it again' } : review;
+ const stored = { ...result, dependencies: excerpt?.dependencies || null, findings, reviewedAt: now };
let next = project;
// A review that returns after the run was paused is still recorded (it was
// paid for, and resume continues from it); one that returns after a cancel
// is recorded but files nothing and moves no status.
- if (review.verdict === 'revise' && excerpt && RESUMABLE.has(run.status)) {
+ if (result.verdict === 'revise' && excerpt && RESUMABLE.has(run.status)) {
for (const finding of findings.filter((f) => f.severity === 'blocking')) {
next = addExcerptNote(next, excerpt.id, { atSec: finding.atSec, note: `${NOTE_PREFIX} ${finding.note}`, verdict: 'flagged' }, now).project;
}
}
- const terminal = run.status !== 'running' ? {} : review.verdict === 'pass'
+ const terminal = run.status !== 'running' ? {} : result.verdict === 'pass'
? { status: 'passed', stopReason: null }
- : review.verdict === 'inconclusive'
- ? { status: 'needs-human', stopReason: review.reason || 'The review could not verify every check — a director must watch this draft' }
+ : result.verdict === 'inconclusive'
+ ? { status: 'needs-human', stopReason: result.reason || 'The review could not verify every check — a director must watch this draft' }
: {};
const updated = touchRun(run, { ...terminal, ...withAttempt(run, { review: stored }) }, now);
return { project: replaceRun(next, updated), run: updated };
diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.js
index 2e24f59bd6..b57ca21e31 100644
--- a/server/services/musicVideo/autoReviewService.js
+++ b/server/services/musicVideo/autoReviewService.js
@@ -37,7 +37,7 @@ import { isVisionCapableCliProvider } from '../../lib/localModelHeuristics.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoEvents } from './events.js';
import { startExcerptRender } from './excerptRender.js';
-import { cancelRevision, resumeRevision } from './revisionService.js';
+import { cancelRevision, getDependencyImpact, resumeRevision } from './revisionService.js';
import { projectExcerpts } from './excerpt.js';
import { projectRevisions, releaseRevisionClaim, revisionSectionStates, startRevisionOnProject } from './revision.js';
import {
@@ -264,7 +264,12 @@ async function takeSteps(projectId, runId) {
const begun = await mutateProjectRecord(projectId, (current) => beginAttemptReview(current, runId));
publish(projectId, begun.project, begun.run, { type: 'reviewing', excerptId: step.excerptId });
const excerpt = projectExcerpts(project).find((e) => e.id === step.excerptId);
- const review = await reviewDraft(project, run, excerpt);
+ let review = await reviewDraft(project, run, excerpt);
+ const impact = await getDependencyImpact(projectId);
+ if (impact.shots.some((shot) => {
+ const scene = project.scenes.find((entry) => entry.sceneId === shot.sceneId);
+ return scene && scene.startSec < excerpt.endSec && scene.endSec > excerpt.startSec;
+ })) review = { ...review, verdict: 'inconclusive', reason: 'A derived clip or its sung window changed — repair and review a fresh draft' };
const out = await mutateProjectRecord(projectId, (current) => recordAttemptReview(current, runId, review));
const log = review.verdict === 'inconclusive' ? console.warn : console.log;
log(`🔎 Music Video auto-review ${short(runId)} attempt ${run.attempts.length}: ${review.verdict} (${review.findings.length} finding${review.findings.length === 1 ? '' : 's'})`);
diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.js
index 1333d01a7a..624f4de9a7 100644
--- a/server/services/musicVideo/excerpt.js
+++ b/server/services/musicVideo/excerpt.js
@@ -23,6 +23,7 @@
*/
import { isPerformanceScene, selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
+import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
@@ -54,7 +55,7 @@ function findExcerpt(project, excerptId) {
* project; the render job fills in `filename`/`contactSheetFilename` (or
* `error`) once the encode finishes.
*/
-export function startExcerptOnProject(project, { startSec, endSec, sections = null, performanceProject = project, partialFilename = null, renderingOn = null, aspect = null, fade = false }, now = new Date().toISOString()) {
+export function startExcerptOnProject(project, { startSec, endSec, sections = null, performanceProject = project, partialFilename = null, renderingOn = null, aspect = null, fade = false, dependencies = null }, now = new Date().toISOString()) {
if (!(startSec >= 0) || !(endSec > startSec) || endSec > MAX_EXCERPT_SEC) {
throw excerptError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec, and both within range');
}
@@ -64,6 +65,7 @@ export function startExcerptOnProject(project, { startSec, endSec, sections = nu
startSec,
endSec,
status: 'rendering',
+ dependencies: dependencies || captureMusicVideoEvidence(project, { sceneIds: sections?.map((section) => section.sceneId), startSec, endSec }),
jobId: id,
filename: null,
contactSheetFilename: null,
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index 383ce14397..d6b12ad0e4 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -17,6 +17,7 @@
* the SAME project while one is already in flight.
*/
+import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';
import { unlink } from 'fs/promises';
import { join } from 'path';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
@@ -30,7 +31,7 @@ import { safeUnder } from '../../lib/ffmpeg.js';
import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';
import { getProject, listProjects, mutateProjectRecord } from './projects.js';
import { assertCurrentPerformanceTakes } from './performanceShot.js';
-import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath, resolveSoundBedPath } from './render.js';
+import { assertCurrentClipDependencies, planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath, resolveSoundBedPath } from './render.js';
import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';
import { encodeDocumentComposition, prepareDocumentRender } from './documentRender.js';
import { renderableCues, sectionCardCues } from './composition.js';
@@ -121,7 +122,10 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSe
// Same order as a full render: a missing master throws before the
// excerpt is marked rendering.
const audioPath = await resolveMasterAudioPath(project);
- if (renderer.performanceTakes) await assertCurrentPerformanceTakes(project, audioPath);
+ if (renderer.performanceTakes) {
+ assertCurrentClipDependencies(project);
+ await assertCurrentPerformanceTakes(project, audioPath);
+ }
const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
if (!(startSec >= 0) || !(endSec > startSec) || endSec > prepared.totalSec + 1e-6) {
throw new ServerError(
@@ -143,7 +147,7 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSe
}));
const renderingOn = await ensureInstanceId();
const { excerpt } = await mutateProjectRecord(projectId, (current) => {
- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: project, partialFilename: filename, renderingOn, aspect: musicVideoAspect(project), fade });
+ 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, aspect: musicVideoAspect(project), fade });
return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;
});
const excerptId = excerpt.id;
@@ -265,7 +269,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
// demote it (#9010).
const renderingOn = await ensureInstanceId();
const { excerpt } = await mutateProjectRecord(projectId, (current) => {
- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, performanceProject: project, partialFilename: filename, renderingOn });
+ 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 });
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.js
index e1a8f0ff2b..0076bf17bc 100644
--- a/server/services/musicVideo/production.js
+++ b/server/services/musicVideo/production.js
@@ -1,3 +1,4 @@
+import { musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';
/**
* Music Video — server-owned production run (#9066): pure record transforms.
*
@@ -353,6 +354,8 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }
return { type: 'wait', on: 'review' };
}
if (review.status === 'passed') {
+ const evidence = review.attempts?.at(-1)?.review?.dependencies;
+ if (musicVideoDependencyChanges(project, evidence).length) return { type: 'halt', status: 'needs-human', reason: 'The passing review has changed or unrecorded dependencies — rebuild and review the current draft' };
if (!run.authoring) return { type: 'halt', status: 'completed', reason: null };
if (run.documentCheckpoint?.directory !== project.composition?.document?.directory) return { type: 'halt', status: 'needs-replan', reason: 'The selected document changed after review — start a fresh run' };
if (!run.finalRender) return { type: 'render-document' };
diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.js
index 4821ec1b9d..aac60463ad 100644
--- a/server/services/musicVideo/productionService.test.js
+++ b/server/services/musicVideo/productionService.test.js
@@ -1,3 +1,4 @@
+import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';
/**
* Music Video production run (#9066) — orchestration contract with injected
* queue events. The project store is an in-memory double with the real
@@ -585,6 +586,7 @@ function passOwnedReview() {
const project = store.get('mv-example');
const review = project.autoReviews[0];
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) {
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 862f027ec1..0f2a9f7373 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -21,6 +21,7 @@
* sweep. The soft-delete fields were already on the record, so this was additive.
*/
+import { presentMusicVideoDependencies, retainMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
@@ -59,7 +60,7 @@ export async function listProjects(options = {}) {
}
export async function getProject(id, options = {}) {
- return (await selectBackend()).getProject(id, options);
+ return presentMusicVideoDependencies(await (await selectBackend()).getProject(id, options));
}
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
@@ -283,7 +284,10 @@ export async function reviewSceneTake(id, sceneId, takeId, review) {
* service (#8980) so its revision checks run against the freshest record.
*/
export async function mutateProjectRecord(id, transform) {
- const outcome = await (await selectBackend()).mutateProjectRecord(id, transform);
+ const outcome = await (await selectBackend()).mutateProjectRecord(id, (current) => {
+ const outcome = transform(current);
+ return { ...outcome, project: retainMusicVideoDependencies(current, outcome.project) };
+ });
emitRecordUpdated('musicVideoProject', id);
return outcome;
}
diff --git a/server/services/musicVideo/projectsDB.test.js b/server/services/musicVideo/projectsDB.test.js
index b6b97fc746..8eceb12d9f 100644
--- a/server/services/musicVideo/projectsDB.test.js
+++ b/server/services/musicVideo/projectsDB.test.js
@@ -10,6 +10,7 @@
import { describe, it, expect, vi, afterAll, beforeAll, beforeEach } from 'vitest';
import { rmSync } from 'fs';
import { join } from 'path';
+import { captureMusicVideoEvidence, musicVideoDependencyImpact } from '../../lib/musicVideoDependencies.js';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
import { getSyncBaseHash, __resetBaseHashCacheForTests } from '../../lib/conflictJournal.js';
@@ -81,6 +82,23 @@ describe.skipIf(!runDb)('music video projects DB adapter', () => {
await close();
});
+ it('round-trips dependency evidence and selective invalidation through PostgreSQL and peer merge', async () => {
+ const created = await db.createProject({ name: 'Example dependency record' });
+ await db.updateProject(created.id, { scenes: [{ sceneId: 'a', startSec: 0, endSec: 5, referenceImageId: 'plate.png', videoHistoryId: null, takes: [] }] });
+ await db.appendSceneTakes(created.id, 'a', [{ kind: 'video', assetId: 'clip-example', source: 'generated', sourceImageId: 'plate.png' }]);
+ const before = await db.getProject(created.id);
+ await db.mutateProjectRecord(created.id, (current) => ({ project: { ...current, excerpts: [{ id: 'excerpt-example', status: 'complete', dependencies: captureMusicVideoEvidence(before) }] } }));
+ await db.updateScene(created.id, 'a', { referenceImageId: 'new-plate.png' });
+ const stale = await db.getProject(created.id);
+ expect(musicVideoDependencyImpact(stale).shots.map((shot) => shot.sceneId)).toEqual(['a']);
+ expect(stale.excerpts[0].dependencies.version).toBe(1);
+ const remote = { ...stale, id: 'mv-peer-example', updatedAt: '2099-01-01T00:00:00.000Z' };
+ await db.mergeProjectsFromSync([remote]);
+ const synced = await db.getProject(remote.id);
+ expect(synced.scenes[0].takes[0].dependencies).toEqual(stale.scenes[0].takes[0].dependencies);
+ expect(musicVideoDependencyImpact(synced).shots).toEqual(musicVideoDependencyImpact(stale).shots);
+ });
+
it('backfills a missing JSONB id from the primary-key column', async () => {
const id = `${PRUNE_PREFIX}legacy-no-json-id`;
await query(
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index a362355c3f..a096af624c 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -14,6 +14,7 @@
* already on the record, so federation was purely additive (no record migration).
*/
+import { remapMusicVideoDependencies, retainMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
import { randomUUID } from 'crypto';
import { normalizeMusicVideoProductionPolicy } from '../../lib/musicVideoMediumPlan.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -53,7 +54,7 @@ export function mirrorStatus(status) {
/** Return the next record with `extra` merged and `updatedAt` freshly stamped. */
function touch(record, extra) {
- return { ...record, ...extra, updatedAt: new Date().toISOString() };
+ return retainMusicVideoDependencies(record, { ...record, ...extra, updatedAt: new Date().toISOString() });
}
/** safeParse a scene payload, throwing a 400 ServerError with field detail on failure. */
@@ -201,6 +202,9 @@ export function cloneProjectRecord(source, {
// carries the whole candidate history; a clean clone starts empty.
takes: includeGeneratedMedia ? ensureSceneTakes(scene, now) : [],
}));
+ for (const scene of scenes) scene.takes = scene.takes.map((take) => ({ ...take,
+ ...(take.dependencies ? { dependencies: remapMusicVideoDependencies(take.dependencies, sceneIdMap) } : {}),
+ }));
const mediaReady = includeGeneratedMedia
&& scenes.length > 0
&& scenes.every((scene) => scene.referenceImageId && scene.videoHistoryId);
@@ -236,7 +240,7 @@ export function cloneProjectRecord(source, {
// A running encoder belongs only to the source project. Copying its
// partial-file ownership would let clone recovery delete that output.
excerpts: source.excerpts.filter((excerpt) => excerpt?.status !== 'rendering').map((excerpt) => (Array.isArray(excerpt?.sections)
- ? { ...excerpt, sections: excerpt.sections.map((s) => ({ ...s, sceneId: sceneIdMap.get(s.sceneId) ?? s.sceneId })) }
+ ? { ...excerpt, dependencies: remapMusicVideoDependencies(excerpt.dependencies, sceneIdMap), sections: excerpt.sections.map((s) => ({ ...s, sceneId: sceneIdMap.get(s.sceneId) ?? s.sceneId })) }
: excerpt)),
} : {}),
// A revision is in-progress work against the SOURCE's takes; the clone
@@ -254,6 +258,7 @@ export function cloneProjectRecord(source, {
// interrupted on the clone and can be resumed there.
...(source.castAndSets ? { castAndSets: { ...source.castAndSets, processId: null, productionRunId: null } } : {}),
renderHistoryId: null,
+ renderDependencies: null,
// #9010: the source's in-flight render mark is not the clone's.
renderingOn: null,
renderPartialFilename: null,
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 4c42032651..2cc23ecfdf 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -43,6 +43,7 @@ import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from '.
import { encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
+import { captureMusicVideoEvidence, musicVideoTakeChanges } from '../../lib/musicVideoDependencies.js';
import { assertCurrentPerformanceTakes } from './performanceShot.js';
import { ensureInstanceId } from '../instanceIdentity.js';
import { AUDIO_NORM, buildAudioBedMix } from '../videoTimeline/audioBedMix.js';
@@ -572,7 +573,15 @@ export function excerptBoundaryTimes(sections, cues, startSec, endSec, { fps = 2
// every scene's clip, and refuse a render whose shots don't cover their
// authored span. Both callers build on the exact same resolved clip list, so
// an excerpt frame matches what a full render would produce at that song time.
+export function assertCurrentClipDependencies(project) {
+ const stale = (project.scenes || []).filter((scene) => scene.videoHistoryId && scene.visualLayer !== 'still' && scene.visualLayer !== 'card')
+ .filter((scene) => musicVideoTakeChanges(project, scene, (scene.takes || []).find((take) => take.kind === 'video' && take.assetId === scene.videoHistoryId)).length);
+ if (stale.length) throw new ServerError('Selected clips were derived from changed plates — preview and repair their dependencies before rendering',
+ { status: 422, code: 'STALE_CLIP_DEPENDENCIES', context: { sceneIds: stale.map((scene) => scene.sceneId) } });
+}
+
export async function planMusicVideoRender(project) {
+ assertCurrentClipDependencies(project);
const ffmpeg = await findFfmpeg();
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
@@ -675,7 +684,10 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =
// Resolve the master before any rendering mark. A missing track throws here
// and the caller releases the pending slot without leaving a job running.
const audioPath = await resolveMasterAudioPath(project);
- if (renderer.performanceTakes) await assertCurrentPerformanceTakes(project, audioPath);
+ if (renderer.performanceTakes) {
+ assertCurrentClipDependencies(project);
+ await assertCurrentPerformanceTakes(project, audioPath);
+ }
const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
@@ -741,7 +753,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =
createdAt: new Date().toISOString(),
musicVideoProjectId: projectId,
});
- await finish({ status: 'complete', extra: { renderHistoryId: jobId } });
+ await finish({ status: 'complete', extra: { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) } });
console.log(`✅ ${renderer.label[0].toUpperCase()}${renderer.label.slice(1)} music video rendered [${jobId.slice(0, 8)}]: ${filename}`);
broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}`, proof: proof ? `/data/video-thumbnails/${proof}` : null } });
}).catch(async (err) => {
@@ -933,7 +945,7 @@ export async function renderMusicVideo(projectId, options = {}) {
musicVideoProjectId: projectId,
};
await appendToVideoHistory(meta);
- await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId })).catch((updateErr) => {
+ await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) })).catch((updateErr) => {
console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);
});
console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);
diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.js
index 3991a5671d..abd41380cb 100644
--- a/server/services/musicVideo/revision.js
+++ b/server/services/musicVideo/revision.js
@@ -27,6 +27,7 @@
* route that acts on it, so no `musicVideoProjects` schema bump is needed.
*/
+import { captureTakeDependencies, musicVideoDependencyChanges, musicVideoTakeChanges } from '../../lib/musicVideoDependencies.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr } from '../../lib/textUtils.js';
@@ -247,7 +248,8 @@ export function revisionSectionStates(project, revision, jobs = [], nowMs = Date
if (section.verdict !== 'rejected') return { ...section, state: 'kept' };
const scene = scenesById.get(section.sceneId);
if (!scene) return { ...section, state: 'removed' };
- if (isNonBlankStr(scene[TAKE_SLOT[section.kind]])) return { ...section, state: 'ready' };
+ const selected = (scene.takes || []).find((take) => take.kind === section.kind && take.assetId === scene[TAKE_SLOT[section.kind]]);
+ if (isNonBlankStr(scene[TAKE_SLOT[section.kind]]) && !musicVideoTakeChanges(project, scene, selected).length) return { ...section, state: 'ready' };
const takes = Array.isArray(scene.takes) ? scene.takes : [];
const pending = jobs.some((job) => job?.kind === section.kind && tagMatches(job, project.id, section.sceneId, revision) && (
job.status === 'queued' || job.status === 'running'
@@ -290,6 +292,9 @@ export function revisionGenerationJobs(project, revision, jobs = []) {
*/
export function claimRevisionGeneration(project, revisionId, jobs = [], nowMs = Date.now()) {
const revision = resumableRevision(project, revisionId);
+ if (revision.type === 'dependencies' && revision.sections.some((section) => musicVideoDependencyChanges(project, section.dependencies).length)) {
+ throw revisionError(409, 'DEPENDENCY_REPAIR_CHANGED', 'The repair inputs changed — cancel and preview the affected dependencies again');
+ }
const states = revisionSectionStates(project, revision, jobs, nowMs);
const ref = ({ sceneId, kind }) => ({ sceneId, kind });
const needsGeneration = states.filter((s) => s.state === 'needs-generation').map(ref);
@@ -364,6 +369,12 @@ export function cancelRevisionOnProject(project, revisionId, now = new Date().to
export function assertRevisionOpenForGeneration(project, revisionId, { sceneId = null, kind = null } = {}) {
if (!project) return null;
const revision = resumableRevision(project, revisionId);
+ if (revision.type === 'dependencies') {
+ const section = revision.sections.find((entry) => entry.sceneId === sceneId && entry.kind === kind);
+ if (!section || musicVideoDependencyChanges(project, section.dependencies).length) {
+ throw revisionError(409, 'DEPENDENCY_REPAIR_CHANGED', 'This generation does not match the previewed repair inputs');
+ }
+ }
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');
@@ -392,8 +403,49 @@ export function releaseRevisionClaim(project, revisionId, sceneId, now = new Dat
const revision = resumableRevision(project, revisionId);
const next = {
...revision,
- sections: revision.sections.map((s) => (s.sceneId === sceneId && s.verdict === 'rejected' ? { ...s, claimedAt: null } : s)),
+ sections: revision.sections.map((s) => (s.sceneId === sceneId && s.verdict === 'rejected' ? { ...s, claimedAt: null, submissionClaimedAt: null } : s)),
updatedAt: now,
};
return { project: replaceRevision(project, next), revision: next };
}
+
+/** Start a previewed dependency repair under the existing serialized checkpoint. */
+export function startDependencyRepairOnProject(project, impact, { basis }, now = new Date().toISOString()) {
+ const active = projectRevisions(project).find(isActive);
+ if (active?.dependencyBasis === basis) return { project, revision: active, skippedSceneIds: [] };
+ if (active) throw revisionError(409, 'REVISION_IN_PROGRESS', 'Finish or cancel the open revision before repairing dependencies');
+ if (basis !== impact.basis) throw revisionError(409, 'DEPENDENCY_PREVIEW_CHANGED', 'Assets changed after the repair preview — review the impact again');
+ if (!impact.shots.length && !impact.evidence.length) throw revisionError(422, 'NOTHING_TO_REVISE', 'All recorded dependencies are current');
+ if (codeFirst(project)) {
+ assertCodeFirstPlan(project);
+ if (impact.shots.some((shot) => mediumFor(project, shot.sceneId) !== 'generated-footage')) {
+ throw revisionError(409, 'REVISION_MEDIUM_PLAN_CONFLICT', 'Select replacement footage for the affected existing-media shot; its approved medium does not permit generation');
+ }
+ }
+ let next = project;
+ const sections = [];
+ for (const shot of impact.shots) {
+ const scene = next.scenes.find((entry) => entry.sceneId === shot.sceneId);
+ const withTakes = { ...scene, takes: ensureSceneTakes(scene, now) };
+ next = { ...next, scenes: next.scenes.map((entry) => entry.sceneId === scene.sceneId ? withTakes : entry) };
+ const take = withTakes.takes.find((entry) => entry.kind === 'video' && entry.assetId === scene.videoHistoryId);
+ if (take) next = reviewSceneTake(next, scene.sceneId, take.takeId, { status: 'rejected' }).project;
+ sections.push({ sceneId: scene.sceneId, layer: 'footage', kind: 'video', verdict: 'rejected',
+ rejectedAssetId: shot.assetId, reasons: shot.reasons,
+ // A repair cannot silently continue against another newly selected plate.
+ dependencies: captureTakeDependencies(scene), noteIds: [] });
+ }
+ const ranges = [
+ ...impact.shots.map((shot) => project.scenes.find((scene) => scene.sceneId === shot.sceneId)),
+ ...impact.evidence.filter((entry) => entry.kind === 'excerpt'),
+ ].filter((entry) => typeof entry.startSec === 'number' && typeof entry.endSec === 'number' && entry.endSec > entry.startSec);
+ const startSec = ranges.length ? Math.min(...ranges.map((range) => range.startSec)) : 0;
+ const endSec = ranges.length ? Math.max(...ranges.map((range) => range.endSec)) : project.audioAnalysis?.durationSec;
+ if (!(endSec > startSec)) throw revisionError(422, 'DEPENDENCY_REPAIR_UNTIMED', 'Time the affected shots or analyze the song before repairing');
+ const revision = { id: `mvr-${randomUUID()}`, type: 'dependencies', dependencyBasis: basis,
+ excerptId: null, startSec, endSec, sections, status: 'open', renderExcerptId: null,
+ renderAttempts: 0, error: null, createdAt: now, updatedAt: now,
+ ...(codeFirst(project) ? { mediumBasis: mediumBasis(project) } : {}),
+ };
+ return { project: { ...next, revisions: pruneRevisions([...projectRevisions(next), revision]), updatedAt: now }, revision, skippedSceneIds: [] };
+}
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
index 3ec4571871..8c89a13ba0 100644
--- a/server/services/musicVideo/revisionService.js
+++ b/server/services/musicVideo/revisionService.js
@@ -19,6 +19,7 @@
* against the freshest record under the backend's write serialization.
*/
+import { musicVideoDependencyImpact } from '../../lib/musicVideoDependencies.js';
import { ServerError } from '../../lib/errorHandler.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';
@@ -30,6 +31,7 @@ import {
releaseRevisionClaim,
revisionGenerationJobs,
revisionSectionStates,
+ startDependencyRepairOnProject,
startRevisionOnProject,
} from './revision.js';
import { chargeAutoReviewGeneration, refundAutoReviewGeneration, runOwningRevision } from './autoReview.js';
@@ -58,16 +60,25 @@ export async function assertRevisionOpen(projectId, revisionId, { sceneId = null
if (!revisionId) return;
const project = await getProject(projectId);
assertRevisionOpenForGeneration(project, revisionId, { sceneId, kind });
- if (!project || !runOwningRevision(project, revisionId)) return;
+ const revision = projectRevisions(project).find((entry) => entry.id === revisionId);
+ if (!project || (!runOwningRevision(project, revisionId) && revision?.type !== 'dependencies')) 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, { sceneId, kind });
const inFlight = sceneId && revisionGenerationJobs(current, revision, jobs)
.some((job) => job.params?.musicVideo?.sceneId === sceneId && (!kind || job.kind === kind));
- if (inFlight) {
+ if (inFlight && revision.type !== 'dependencies') {
throw new ServerError('This section is already generating for the auto-review run', { status: 409, code: 'AUTO_REVIEW_SECTION_IN_FLIGHT', context: { sceneId } });
}
+ if (revision.type === 'dependencies') {
+ const section = revision.sections.find((entry) => entry.sceneId === sceneId && entry.kind === kind);
+ if (inFlight || (section.submissionClaimedAt && Date.now() - Date.parse(section.submissionClaimedAt) < 30_000)) {
+ throw new ServerError('This repair section is already submitting or generating', { status: 409, code: 'REVISION_SECTION_IN_FLIGHT' });
+ }
+ const updated = { ...revision, sections: revision.sections.map((entry) => entry === section ? { ...entry, submissionClaimedAt: new Date().toISOString() } : entry) };
+ return { project: { ...current, revisions: current.revisions.map((entry) => entry.id === revisionId ? updated : entry) } };
+ }
return chargeAutoReviewGeneration(current, revisionId, { sceneId, kind, jobs });
});
}
@@ -136,3 +147,35 @@ export async function cancelRevision(projectId, revisionId, { alsoOnProject = nu
if (canceledJobIds.length) console.log(`🛑 Music Video revision ${revisionId.slice(4, 12)} cancelled ${canceledJobIds.length} generation job(s)`);
return { project, revision, canceledJobIds };
}
+
+
+async function dependencyImpactFor(project) {
+ const performanceScenes = (project.scenes || []).filter((scene) => scene.shotMode === 'performance' && scene.videoHistoryId);
+ let performanceChanges = [];
+ if (performanceScenes.length) {
+ const { resolveMasterAudioPath } = await import('./render.js');
+ const { findStalePerformanceTakes } = await import('./performanceShot.js');
+ performanceChanges = await resolveMasterAudioPath(project).then((path) => findStalePerformanceTakes(project, path),
+ () => performanceScenes.map((scene) => ({ sceneId: scene.sceneId, reason: 'Current song audio is unavailable; window evidence cannot be verified' })));
+ }
+ return musicVideoDependencyImpact(project, performanceChanges);
+}
+
+export async function getDependencyImpact(projectId) {
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ return dependencyImpactFor(project);
+}
+
+export async function startDependencyRepair(projectId, input) {
+ const before = await getProject(projectId);
+ if (!before) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const impact = await dependencyImpactFor(before);
+ const structuralBasis = musicVideoDependencyImpact(before).basis;
+ return mutateProjectRecord(projectId, (current) => {
+ if (musicVideoDependencyImpact(current).basis !== structuralBasis) {
+ throw new ServerError('Assets changed while checking the repair preview', { status: 409, code: 'DEPENDENCY_PREVIEW_CHANGED' });
+ }
+ return startDependencyRepairOnProject(current, impact, input);
+ });
+}
diff --git a/server/services/musicVideo/takes.js b/server/services/musicVideo/takes.js
index 275d40b4fd..f45ad2d25e 100644
--- a/server/services/musicVideo/takes.js
+++ b/server/services/musicVideo/takes.js
@@ -21,6 +21,7 @@
* take the first time a take operation touches the scene (no record rewrite).
*/
+import { captureTakeDependencies, musicVideoTakeChanges, retainMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
@@ -39,7 +40,7 @@ const clip = (v, max) => (isNonBlankStr(v) ? trimTo(v, max) : null);
// A basename only — an imported file's name is provenance, never a path.
const takeOriginalName = (name) => (isNonBlankStr(name) ? clip(name.split(/[\\/]/).pop(), 200) : null);
-function buildTake({ kind, assetId, source, provider = null, jobId = null, prompt = null, sourceImageId = null, originalName = null, shotInstruction = null, use = 'final', now }) {
+function buildTake({ kind, assetId, source, provider = null, jobId = null, prompt = null, sourceImageId = null, originalName = null, shotInstruction = null, use = 'final', dependencies = null, inputAssets = null, now }) {
return {
takeId: `mvt-${randomUUID()}`,
kind,
@@ -51,6 +52,8 @@ function buildTake({ kind, assetId, source, provider = null, jobId = null, promp
sourceImageId: clip(sourceImageId, 256),
originalName: takeOriginalName(originalName),
status: 'candidate',
+ ...(dependencies ? { dependencies: structuredClone(dependencies) } : {}),
+ ...(inputAssets?.length ? { inputAssets: structuredClone(inputAssets) } : {}),
// #8980 — 'motion-reference' scaffolding never fills the slot on its own.
use: use === 'motion-reference' ? 'motion-reference' : 'final',
note: null,
@@ -106,7 +109,7 @@ function findSceneIndex(project, sceneId) {
function replaceScene(project, idx, scene) {
const scenes = project.scenes.slice();
scenes[idx] = scene;
- return { ...project, scenes, updatedAt: new Date().toISOString() };
+ return retainMusicVideoDependencies(project, { ...project, scenes, updatedAt: new Date().toISOString() });
}
/**
@@ -125,11 +128,12 @@ function appendToScene(scene, inputs, now) {
const appended = [];
for (const input of inputs) {
const existing = takes.find((t) => t.kind === input.kind && t.assetId === input.assetId);
- const take = existing || buildTake({ ...input, now });
+ const dependencies = input.dependencies || (input.kind === 'video' && input.sourceImageId ? captureTakeDependencies(scene, input.sourceImageId) : null);
+ const take = existing || buildTake({ ...input, dependencies, now });
if (!existing) takes = [...takes, take];
appended.push(take);
const field = TAKE_SLOT[input.kind];
- if (!isNonBlankStr(next[field]) && take.status !== 'rejected' && take.use !== 'motion-reference') next[field] = take.assetId;
+ if (!isNonBlankStr(next[field]) && take.status !== 'rejected' && take.use !== 'motion-reference' && !musicVideoTakeChanges({ scenes: [scene] }, scene, take).length) next[field] = take.assetId;
}
next.takes = pruneTakes(takes, next);
return { scene: next, appended };
@@ -165,7 +169,7 @@ export function appendTakesAcrossScenes(project, items) {
entries.forEach((e, i) => { appended[e.index] = { sceneId: scene.sceneId, take: result.appended[i] }; });
return result.scene;
});
- return { project: { ...project, scenes, updatedAt: now }, appended };
+ return { project: retainMusicVideoDependencies(project, { ...project, scenes, updatedAt: now }), appended };
}
function locateTake(project, sceneId, takeId) {
diff --git a/server/services/musicVideo/treatment.js b/server/services/musicVideo/treatment.js
index 389b75b311..c66995f343 100644
--- a/server/services/musicVideo/treatment.js
+++ b/server/services/musicVideo/treatment.js
@@ -40,6 +40,7 @@ import { shotActionContractProblem } from '../../lib/musicVideoActionContract.js
* against older writers that would discard them during treatment edits.
*/
+import { captureMusicVideoEvidence, musicVideoDependencyChanges, musicVideoTakeChanges, remapMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
import { createHash, randomUUID } from 'crypto';
import { MUSIC_VIDEO_MEDIA, normalizeMusicVideoProductionPolicy, summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -219,6 +220,8 @@ function normalizeEvidence(evidence) {
imageId: isNonBlankStr(evidence.imageId) ? evidence.imageId.slice(0, 256) : null,
note: text(evidence.note, 2000),
reviewedAt: typeof evidence.reviewedAt === 'string' ? evidence.reviewedAt : null,
+ ...(evidence.dependencies ? { dependencies: structuredClone(evidence.dependencies) } : {}),
+ ...(evidence.dependencyState ? { dependencyState: evidence.dependencyState } : {}),
};
}
@@ -511,6 +514,14 @@ export function reviewTreatmentProof(project, proofId, { baseRevision, status, e
throw treatmentError(422, 'PROOF_EVIDENCE_NOT_FOUND', 'That image is not a frame of this proof\'s scenes');
}
if (status === 'passed') {
+ const selectedArtifact = isRender || (project.scenes || []).some((scene) => proof.sceneIds.includes(scene.sceneId)
+ && (recorded.videoHistoryId ? scene.videoHistoryId === recorded.videoHistoryId : scene.referenceImageId === recorded.imageId));
+ if (!selectedArtifact || (isRender && musicVideoDependencyChanges(project, project.renderDependencies).length)) {
+ throw treatmentError(409, 'PROOF_DEPENDENCIES_STALE', 'Historical or untracked artifacts cannot pass the current proof — select or rebuild and review current evidence');
+ }
+ const stale = (project.scenes || []).filter((scene) => proof.sceneIds.includes(scene.sceneId))
+ .some((scene) => musicVideoTakeChanges(project, scene, (scene.takes || []).find((take) => take.assetId === scene.videoHistoryId && take.kind === 'video')).length);
+ if (stale) throw treatmentError(409, 'PROOF_DEPENDENCIES_STALE', 'Repair the derived clip before passing its proof');
if (proof.checks.includes('lip-sync') && treatment.capabilityGaps.some((g) => g.id === 'lip-sync')) {
throw treatmentError(422, 'PROOF_CAPABILITY_MISSING', 'This install has no source-audio lip-sync, so a lip-sync check cannot pass');
}
@@ -527,6 +538,7 @@ export function reviewTreatmentProof(project, proofId, { baseRevision, status, e
}
}
}
+ if (recorded) recorded.dependencies = recorded.videoHistoryId === project.renderHistoryId ? project.renderDependencies : captureMusicVideoEvidence(project, { sceneIds: proof.sceneIds, composition: recorded.videoHistoryId === project.renderHistoryId });
treatment.proofs[idx] = { ...proof, status, evidence: recorded };
return stamp(project, treatment, now);
}
@@ -831,7 +843,7 @@ export function remapTreatmentForClone(treatment, sceneIdMap, { includeGenerated
return {
...p,
sceneIds: p.sceneIds.map(remap),
- ...(lost ? { status: 'proposed', evidence: null } : {}),
+ ...(lost ? { status: 'proposed', evidence: null } : p.evidence ? { evidence: { ...p.evidence, dependencies: remapMusicVideoDependencies(p.evidence.dependencies, sceneIdMap) } } : {}),
};
}),
// The scene-set fingerprint covers ids; keep a clean basis clean.
diff --git a/server/services/musicVideoSceneHooks.test.js b/server/services/musicVideoSceneHooks.test.js
index 100a7d85cc..a1fc5a5ce7 100644
--- a/server/services/musicVideoSceneHooks.test.js
+++ b/server/services/musicVideoSceneHooks.test.js
@@ -134,18 +134,28 @@ describe('music-video scene completion hooks → takes', () => {
});
it('records a clip take with its source frame as a basename, filling only an empty video slot', async () => {
+ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: 'frame-a.png' });
mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-1'));
mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-2'));
await waitFor(() => emitted.length === 2);
const stored = await sceneOf(project.id, scene.sceneId);
expect(stored.videoHistoryId).toBe('clip-1');
- expect(stored.takes.map((t) => [t.kind, t.assetId, t.sourceImageId])).toEqual([
+ expect(stored.takes.filter((t) => t.kind === 'video').map((t) => [t.kind, t.assetId, t.sourceImageId])).toEqual([
['video', 'clip-1', 'frame-a.png'],
['video', 'clip-2', 'frame-a.png'],
]);
expect(emitted[1]).toMatchObject({ event: 'scene-video', videoHistoryId: 'clip-1' });
});
+ it('keeps a late clip as a historical candidate when its source plate was replaced', async () => {
+ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: 'frame-b.png' });
+ mediaJobEvents.emit('completed', videoJob(project.id, scene.sceneId, 'clip-old'));
+ await waitFor(() => emitted.length === 1);
+ const stored = await sceneOf(project.id, scene.sceneId);
+ expect(stored.videoHistoryId).toBeNull();
+ expect(stored.takes.find((take) => take.assetId === 'clip-old')).toMatchObject({ sourceImageId: 'frame-a.png', dependencyState: { status: 'stale' } });
+ });
+
it('a late completion cannot resurrect a deleted scene or a deleted project', async () => {
const other = await projects.addProjectScene(project.id, { prompt: 'second scene' });
await projects.deleteScene(project.id, scene.sceneId);
diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.js
index 05a5256b04..7de940ec7d 100644
--- a/server/services/musicVideoSceneVideoHook.js
+++ b/server/services/musicVideoSceneVideoHook.js
@@ -75,6 +75,7 @@ const hook = createMediaJobImageHook({
// edit in/out points and capability it was generated against — the
// renderer places the take by it, so a later retime can't misalign lips.
shotInstruction: job.params?.shotInstruction ?? null,
+ dependencies: job.params?.musicVideoDependencies ?? null,
}]),
onAttached: ({ projectId, sceneId, videoHistoryId }, { scene, appended }) => {
musicVideoEvents.emit('scene-video', {
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index bb85489f38..9d13bde299 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -580,6 +580,7 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }
const imageNames = [...new Set([
...scenes.map((s) => (isStr(s?.referenceImageId) ? s.referenceImageId : null)).filter(Boolean),
...takeIds('image'),
+ ...scenes.flatMap((scene) => (scene.takes || []).flatMap((take) => [take.sourceImageId, ...(take.inputAssets || []).map((input) => input.assetId)]).filter(isStr)),
...specRefs.map((r) => (isStr(r?.imageId) ? r.imageId : null)).filter(Boolean),
...(Array.isArray(project?.styleReferences) ? project.styleReferences : []).map((r) => (isStr(r?.imageId) ? r.imageId : null)).filter(Boolean),
])];
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index f824390707..acf6eb9c3b 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -240,6 +240,9 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
actionContract: structuredClone(scene.direction.actionContract),
};
}
+ const { captureTakeDependencies } = await import('../../lib/musicVideoDependencies.js');
+ const { basename } = await import('path');
+ if (scene) params.musicVideoDependencies = captureTakeDependencies(scene, prepared.sourceImagePath ? basename(prepared.sourceImagePath) : null);
}
return enqueueJob({ kind: 'video', params });
},