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

Music Video director scene board: project store, analyze, beat-aligned scenes (#1760 Phase 1)

[._.]/ Adam Eivy068893dfeacb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 75bcc61d93..9fc879a2d2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,6 +7,7 @@
## Music Video production mode
- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)
+- **[issue-1760] Director scene board: create a Music Video project, analyze its track, and storyboard beat-aligned scenes (Phase 1).** Builds the first user-facing surface on top of the Phase 0 analyzer: a new **Create → Music Video** page (also reachable via `⌘K` and voice) where you pick an existing track (or name an uploaded audio file), create a project, and run the offline analyzer with one click — the detected BPM, beat/downbeat counts, and section map render inline. From there you storyboard the video as an ordered list of **scenes**, each with a label, a start/end time, a beat-aligned flag, and image/frame prompts; scenes can be added, edited (blur-to-save), reordered, and removed. Projects persist through a db-primary store (PostgreSQL `music_video_projects` with a file-backend fallback for dev/test), mirroring the creative-director pattern with soft-delete tombstones and LWW timestamps. Cross-machine federation of projects, per-scene reference-frame/image generation + image-to-video, and the beat-snapped render with a master audio bed are filed as follow-ups on #1760. (`server/services/musicVideo/`, `server/routes/musicVideo.js`, `server/lib/musicVideoValidation.js`, `client/src/pages/MusicVideo.jsx`, `client/src/services/apiMusicVideo.js`)
## Devtools
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 8545bf99b2..4994304c7b 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -62,6 +62,7 @@ const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));
const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));
+const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));
const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));
const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
@@ -274,6 +275,7 @@ export default function App() {
<Route path="creative-director" element={<CreativeDirector />} />
<Route path="creative-director/:id" element={<Navigate to="overview" replace />} />
<Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />
+ <Route path="music-video" element={<MusicVideo />} />
<Route path="timeline" element={<VideoTimeline />} />
<Route path="timeline/:projectId" element={<VideoTimelineEditor />} />
<Route path="models" element={<MediaModels />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 064f26aea7..445a495d5f 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -214,6 +214,7 @@ const navItems = [
{ to: '/media', label: 'Media Gen', icon: Layers },
{ to: '/mood-boards', label: 'Mood Boards', icon: Palette },
{ to: '/music', label: 'Music', icon: Mic },
+ { to: '/media/music-video', label: 'Music Video', icon: Music },
{ to: '/rounds', label: 'Rounds', icon: Music },
{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
{ to: '/sharing', label: 'Sharing', icon: Share2 },
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
new file mode 100644
index 0000000000..4513bf24a6
--- /dev/null
+++ b/client/src/pages/MusicVideo.jsx
@@ -0,0 +1,244 @@
+import { useEffect, useState, useCallback } from 'react';
+import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import PageHeader from '../components/PageHeader';
+import {
+ listMusicVideoProjects,
+ createMusicVideoProject,
+ deleteMusicVideoProject,
+ analyzeMusicVideoProject,
+ addMusicVideoScene,
+ updateMusicVideoScene,
+ deleteMusicVideoScene,
+ reorderMusicVideoScenes,
+} from '../services/apiMusicVideo.js';
+import { listTracks } from '../services/apiTracks.js';
+import { formatDurationSec } from '../utils/formatters.js';
+
+const MODES = ['director', 'autonomous'];
+
+// The two timeline-bound scene fields rendered as identical number inputs.
+const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];
+
+const STATUS_COLORS = {
+ draft: 'bg-port-border text-port-text',
+ analyzed: 'bg-port-accent/30 text-port-accent',
+ ready: 'bg-port-accent/30 text-port-accent',
+ rendering: 'bg-port-warning/30 text-port-warning',
+ complete: 'bg-port-success/30 text-port-success',
+ failed: 'bg-port-error/30 text-port-error',
+};
+
+export default function MusicVideo() {
+ const [projects, setProjects] = useState([]);
+ const [tracks, setTracks] = useState([]);
+ const [selectedId, setSelectedId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [analyzing, setAnalyzing] = useState(false);
+ const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });
+
+ const selected = projects.find((p) => p.id === selectedId) || null;
+ const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
+
+ useEffect(() => {
+ listMusicVideoProjects()
+ .then((data) => { setProjects(data || []); setLoading(false); })
+ .catch((err) => { toast.error(err?.message || 'Failed to load music video projects'); setLoading(false); });
+ listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]));
+ }, []);
+
+ const trackName = useCallback((id) => tracks.find((t) => t.id === id)?.title || id || '—', [tracks]);
+
+ const handleCreate = (e) => {
+ e.preventDefault();
+ if (!form.name.trim()) return;
+ createMusicVideoProject({ name: form.name.trim(), mode: form.mode, trackId: form.trackId || null })
+ .then((proj) => {
+ setProjects((prev) => [...prev, proj]);
+ setSelectedId(proj.id);
+ setForm({ name: '', mode: 'director', trackId: '' });
+ toast.success('Project created');
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to create project'));
+ };
+
+ const handleDelete = (id) => {
+ deleteMusicVideoProject(id)
+ .then(() => {
+ setProjects((prev) => prev.filter((p) => p.id !== id));
+ if (selectedId === id) setSelectedId(null);
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to delete project'));
+ };
+
+ const handleAnalyze = () => {
+ if (!selected) return;
+ setAnalyzing(true);
+ analyzeMusicVideoProject(selected.id)
+ .then((proj) => { replaceProject(proj); toast.success(`Analyzed — ${proj.audioAnalysis?.bpm ? `${proj.audioAnalysis.bpm} BPM` : 'no tempo detected'}`); })
+ .catch((err) => toast.error(err?.message || 'Analysis failed'))
+ .finally(() => setAnalyzing(false));
+ };
+
+ const handleAddScene = () => {
+ addMusicVideoScene(selected.id, { prompt: '' })
+ .then((scene) => replaceProject({ ...selected, scenes: [...(selected.scenes || []), scene] }))
+ .catch((err) => toast.error(err?.message || 'Failed to add scene'));
+ };
+
+ // Optimistic local edit; PATCH on blur (silent — this owns its error toast).
+ const editSceneLocal = (sceneId, patch) => {
+ replaceProject({ ...selected, scenes: selected.scenes.map((s) => (s.sceneId === sceneId ? { ...s, ...patch } : s)) });
+ };
+ const saveScene = (sceneId, patch) => {
+ updateMusicVideoScene(selected.id, sceneId, patch, { silent: true })
+ .catch((err) => toast.error(err?.message || 'Failed to save scene'));
+ };
+
+ const handleDeleteScene = (sceneId) => {
+ deleteMusicVideoScene(selected.id, sceneId)
+ .then((proj) => replaceProject(proj))
+ .catch((err) => toast.error(err?.message || 'Failed to delete scene'));
+ };
+
+ const moveScene = (idx, dir) => {
+ const scenes = selected.scenes || [];
+ const target = idx + dir;
+ if (target < 0 || target >= scenes.length) return;
+ const ids = scenes.map((s) => s.sceneId);
+ [ids[idx], ids[target]] = [ids[target], ids[idx]];
+ reorderMusicVideoScenes(selected.id, ids)
+ .then((proj) => replaceProject(proj))
+ .catch((err) => toast.error(err?.message || 'Failed to reorder'));
+ };
+
+ return (
+ <div className="space-y-4">
+ <PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" />
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ {/* Projects + create */}
+ <div className="space-y-3">
+ <form onSubmit={handleCreate} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
+ <label htmlFor="mv-name" className="block text-sm font-medium">New project</label>
+ <input
+ id="mv-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ placeholder="Project name" className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ />
+ <label htmlFor="mv-mode" className="block text-xs text-port-text-muted">Mode</label>
+ <select id="mv-mode" value={form.mode} onChange={(e) => setForm((f) => ({ ...f, mode: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm">
+ {MODES.map((m) => <option key={m} value={m}>{m}</option>)}
+ </select>
+ <label htmlFor="mv-track" className="block text-xs text-port-text-muted">Track (optional)</label>
+ <select id="mv-track" value={form.trackId} onChange={(e) => setForm((f) => ({ ...f, trackId: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm">
+ <option value="">— no track —</option>
+ {tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}
+ </select>
+ <button type="submit" className="w-full flex items-center justify-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
+ <Plus size={16} /> Create
+ </button>
+ </form>
+
+ <div className="space-y-1">
+ {loading && <p className="text-sm text-port-text-muted">Loading…</p>}
+ {!loading && projects.length === 0 && <p className="text-sm text-port-text-muted">No projects yet.</p>}
+ {projects.map((p) => (
+ <button key={p.id} onClick={() => setSelectedId(p.id)}
+ className={`w-full text-left px-3 py-2 rounded border ${selectedId === p.id ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-card'}`}>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm truncate">{p.name}</span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[p.status] || 'bg-port-border'}`}>{p.status}</span>
+ </div>
+ <div className="text-xs text-port-text-muted flex items-center gap-1 mt-0.5">
+ <Music size={11} /> {trackName(p.trackId)} · {p.scenes?.length || 0} scenes
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Detail / scene board */}
+ <div className="md:col-span-2">
+ {!selected && <p className="text-sm text-port-text-muted">Select or create a project to open its scene board.</p>}
+ {selected && (
+ <div className="space-y-3">
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <h2 className="text-lg font-semibold">{selected.name}</h2>
+ <div className="flex items-center gap-2">
+ <button onClick={handleAnalyze} disabled={analyzing || (!selected.trackId && !selected.uploadedAudioFilename)}
+ title={!selected.trackId && !selected.uploadedAudioFilename ? 'Link a track first' : 'Analyze beat grid'}
+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
+ <Activity size={15} /> {analyzing ? 'Analyzing…' : 'Analyze'}
+ </button>
+ <button onClick={() => handleDelete(selected.id)} title="Delete project"
+ className="flex items-center gap-1 text-port-error border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
+ <Trash2 size={15} />
+ </button>
+ </div>
+ </div>
+ {selected.audioAnalysis && (
+ <div className="text-xs text-port-text-muted mt-2 flex flex-wrap gap-x-4 gap-y-1">
+ <span>Tempo: {selected.audioAnalysis.bpm ? `${selected.audioAnalysis.bpm} BPM` : '—'}</span>
+ <span>Duration: {formatDurationSec(selected.audioAnalysis.durationSec)}</span>
+ <span>Beats: {selected.audioAnalysis.beats?.length || 0}</span>
+ <span>Sections: {selected.audioAnalysis.sections?.length || 0}</span>
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium">Scene board</h3>
+ <button onClick={handleAddScene} className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
+ <Plus size={15} /> Add scene
+ </button>
+ </div>
+
+ {(selected.scenes || []).length === 0 && <p className="text-sm text-port-text-muted">No scenes yet — add one to start the board.</p>}
+ <div className="space-y-2">
+ {(selected.scenes || []).map((scene, idx) => (
+ <div key={scene.sceneId} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-mono text-port-text-muted">#{scene.order + 1}</span>
+ <div className="flex items-center gap-1">
+ <button onClick={() => moveScene(idx, -1)} disabled={idx === 0} className="p-1 disabled:opacity-30" title="Move up"><ArrowUp size={14} /></button>
+ <button onClick={() => moveScene(idx, 1)} disabled={idx === selected.scenes.length - 1} className="p-1 disabled:opacity-30" title="Move down"><ArrowDown size={14} /></button>
+ <button onClick={() => handleDeleteScene(scene.sceneId)} className="p-1 text-port-error" title="Delete scene"><Trash2 size={14} /></button>
+ </div>
+ </div>
+ <textarea
+ value={scene.prompt || ''} rows={2}
+ onChange={(e) => editSceneLocal(scene.sceneId, { prompt: e.target.value })}
+ onBlur={(e) => saveScene(scene.sceneId, { prompt: e.target.value })}
+ placeholder="Shot prompt — what this scene's video should show"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
+ />
+ <div className="flex flex-wrap gap-2 items-center text-xs">
+ {SCENE_TIME_FIELDS.map(([labelText, key]) => {
+ const toValue = (v) => (v === '' ? null : Number(v));
+ return (
+ <label key={key} className="flex items-center gap-1">{labelText}
+ <input type="number" min="0" step="0.1" value={scene[key] ?? ''} className="w-16 bg-port-bg border border-port-border rounded px-1 py-1"
+ onChange={(e) => editSceneLocal(scene.sceneId, { [key]: toValue(e.target.value) })}
+ onBlur={(e) => saveScene(scene.sceneId, { [key]: toValue(e.target.value) })} />
+ </label>
+ );
+ })}
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={!!scene.beatAligned}
+ onChange={(e) => { editSceneLocal(scene.sceneId, { beatAligned: e.target.checked }); saveScene(scene.sceneId, { beatAligned: e.target.checked }); }} />
+ Beat-aligned
+ </label>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 4e2c27376f..4e90d1ad18 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -58,6 +58,7 @@ export * from './apiRounds.js';
export * from './apiPeerSync.js';
export * from './apiSyncReview.js';
export * from './apiCreativeDirector.js';
+export * from './apiMusicVideo.js';
export * from './apiMoodBoard.js';
export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
new file mode 100644
index 0000000000..30c947da01
--- /dev/null
+++ b/client/src/services/apiMusicVideo.js
@@ -0,0 +1,40 @@
+import { request } from './apiCore.js';
+
+// Music Video production mode (#1760). Director scene-board project CRUD + the
+// offline beat/tempo/section analysis. `options` lets a caller suppress
+// request()'s auto-toast with `{ silent: true }` when it owns its own error UI.
+
+export const listMusicVideoProjects = (options = {}) => request('/music-video', options);
+export const getMusicVideoProject = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}`, options);
+export const createMusicVideoProject = (data, options = {}) => request('/music-video', {
+ method: 'POST', body: JSON.stringify(data), ...options,
+});
+export const updateMusicVideoProject = (id, patch, options = {}) => request(`/music-video/${encodeURIComponent(id)}`, {
+ method: 'PATCH', body: JSON.stringify(patch), ...options,
+});
+export const deleteMusicVideoProject = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}`, {
+ method: 'DELETE', ...options,
+});
+
+// Run the offline analyzer on the project's audio and cache the result. Returns
+// the updated project (with `audioAnalysis` populated).
+export const analyzeMusicVideoProject = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/analyze`, {
+ method: 'POST', ...options,
+});
+
+// ---- Director scene board ----
+export const addMusicVideoScene = (id, scene, options = {}) => request(`/music-video/${encodeURIComponent(id)}/scenes`, {
+ method: 'POST', body: JSON.stringify(scene), ...options,
+});
+export const updateMusicVideoScene = (id, sceneId, patch, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}`, {
+ method: 'PATCH', body: JSON.stringify(patch), ...options,
+ });
+export const deleteMusicVideoScene = (id, sceneId, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}`, {
+ method: 'DELETE', ...options,
+ });
+export const reorderMusicVideoScenes = (id, sceneIds, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/scenes/reorder`, {
+ method: 'POST', body: JSON.stringify({ sceneIds }), ...options,
+ });
diff --git a/server/index.js b/server/index.js
index e77555595e..5df49a65a1 100644
--- a/server/index.js
+++ b/server/index.js
@@ -106,6 +106,7 @@ import videoGenRoutes from './routes/videoGen.js';
import videoTimelineRoutes from './routes/videoTimeline.js';
import mediaJobsRoutes from './routes/mediaJobs.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
+import musicVideoRoutes from './routes/musicVideo.js';
import moodBoardRoutes from './routes/moodBoard.js';
import writersRoomRoutes from './routes/writersRoom.js';
import universeBuilderRoutes from './routes/universeBuilder.js';
@@ -532,6 +533,7 @@ app.use('/api/video-gen', videoGenRoutes);
app.use('/api/video-timeline', videoTimelineRoutes);
app.use('/api/media-jobs', mediaJobsRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
+app.use('/api/music-video', musicVideoRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/universe-builder', universeBuilderRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 955836a6f1..d94fa18e30 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -34,6 +34,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
| `memoryValidation.js` | Memory record + retrieval schemas. |
| `moodBoardValidation.js` | Mood board + board-item create/update schemas. |
+| `musicVideoValidation.js` | Music Video project/scene/reorder + cached audio-analysis schemas. |
| `notesValidation.js` | Notes route schemas + safe-relative-path guard. |
| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `postValidation.js` | Social post schemas. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 5a1db50e1c..97f347626c 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -833,6 +833,25 @@ async function ensureSchemaImpl() {
`ALTER TABLE creative_director_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
`CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE`,
+ // Music Video projects (issue #1760). The director scene board's db-primary
+ // record: id/status/created_at/updated_at mirrored as columns, the full
+ // project (track link, cached audioAnalysis, scenes[]) in `data` JSONB —
+ // same shape as creative_director_projects. The soft-delete tombstone trio is
+ // present so peer-sync federation (a follow-up) is additive. Mirrors the
+ // music_video_projects block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS music_video_projects (
+ id TEXT PRIMARY KEY,
+ status VARCHAR(32) NOT NULL DEFAULT 'draft',
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,
+ `ALTER TABLE music_video_projects ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,
+ `CREATE INDEX IF NOT EXISTS idx_music_video_projects_live ON music_video_projects (deleted) WHERE deleted = FALSE`,
+
// Mood boards (issue #911). A dedicated inspiration/mood-board canvas,
// distinct from raw Media History, for collecting visual + textual
// references that feed the Create suite. One row per board, the full record
diff --git a/server/lib/index.js b/server/lib/index.js
index 99e38733fa..e147bb1a6b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -26,6 +26,7 @@ export * as identityValidation from './identityValidation.js';
export * as meatspaceValidation from './meatspaceValidation.js';
export * as memoryValidation from './memoryValidation.js';
export * as moodBoardValidation from './moodBoardValidation.js';
+export * as musicVideoValidation from './musicVideoValidation.js';
export * as notesValidation from './notesValidation.js';
export * as peerSyncValidation from './peerSyncValidation.js';
export * as postValidation from './postValidation.js';
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
new file mode 100644
index 0000000000..aa815bcfec
--- /dev/null
+++ b/server/lib/musicVideoValidation.js
@@ -0,0 +1,96 @@
+/**
+ * Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).
+ *
+ * Validates the `musicVideoProject` db-primary record's route inputs: project
+ * create/update, the per-scene create/update/reorder operations of the director
+ * scene board, and the cached audio-analysis shape (produced by
+ * services/musicVideo/audioAnalysis.js, Phase 0). Re-exported flat from
+ * validation.js and as a namespace from server/lib/index.js.
+ */
+
+import { z } from 'zod';
+
+// A project is authored hands-on (director) or seeded by the AI planner
+// (autonomous); both share the same record + scene board.
+export const MUSIC_VIDEO_MODES = ['director', 'autonomous'];
+
+// Lifecycle. `draft` → has scenes/analysis → `ready` → `rendering` → `complete`
+// (or `failed`). `analyzed` marks "beat map cached but not yet arranged". The
+// render states land with Phase 2; Phase 1 only reaches up to `ready`.
+export const MUSIC_VIDEO_STATUSES = ['draft', 'analyzed', 'ready', 'rendering', 'complete', 'failed'];
+
+// Optional global visual direction for the whole video.
+export const musicVideoConceptSchema = z.object({
+ prompt: z.string().max(8000).optional(),
+ style: z.string().max(2000).optional(),
+ universeId: z.string().max(64).nullable().optional(),
+}).strict();
+
+export const musicVideoProjectCreateSchema = z.object({
+ name: z.string().min(1).max(200),
+ mode: z.enum(MUSIC_VIDEO_MODES).optional(),
+ // The source audio: either a music-library track or an uploaded file basename
+ // under data/music/. At least one is needed before analysis, but a project can
+ // be created empty and have the track set later via PATCH.
+ trackId: z.string().max(64).nullable().optional(),
+ uploadedAudioFilename: z.string().max(256).nullable().optional(),
+ concept: musicVideoConceptSchema.nullable().optional(),
+}).strict();
+
+export const musicVideoProjectUpdateSchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ mode: z.enum(MUSIC_VIDEO_MODES).optional(),
+ status: z.enum(MUSIC_VIDEO_STATUSES).optional(),
+ trackId: z.string().max(64).nullable().optional(),
+ uploadedAudioFilename: z.string().max(256).nullable().optional(),
+ concept: musicVideoConceptSchema.nullable().optional(),
+ renderHistoryId: z.string().max(64).nullable().optional(),
+}).strict();
+
+// A scene on the director board. `startSec`/`endSec` place it on the timeline;
+// `prompt` drives the shot's video; `framePrompt`/`referenceImageId` are the
+// reference-frame inputs the i2v generation (Phase 1b) will consume.
+export const musicVideoSceneCreateSchema = z.object({
+ label: z.string().max(120).optional(),
+ sectionLabel: z.string().max(120).nullable().optional(),
+ prompt: z.string().max(8000).optional(),
+ framePrompt: z.string().max(8000).nullable().optional(),
+ startSec: z.number().min(0).max(36000).optional(),
+ endSec: z.number().min(0).max(36000).optional(),
+ beatAligned: z.boolean().optional(),
+}).strict().refine(
+ (s) => s.startSec == null || s.endSec == null || s.endSec >= s.startSec,
+ { message: 'endSec must be >= startSec', path: ['endSec'] },
+);
+
+export const musicVideoSceneUpdateSchema = z.object({
+ label: z.string().max(120).optional(),
+ sectionLabel: z.string().max(120).nullable().optional(),
+ prompt: z.string().max(8000).optional(),
+ framePrompt: z.string().max(8000).nullable().optional(),
+ startSec: z.number().min(0).max(36000).optional(),
+ endSec: z.number().min(0).max(36000).optional(),
+ beatAligned: z.boolean().optional(),
+ referenceImageId: z.string().max(256).nullable().optional(),
+ videoHistoryId: z.string().max(64).nullable().optional(),
+}).strict();
+
+// Reorder the board: the full set of scene ids in their new order.
+export const musicVideoSceneReorderSchema = z.object({
+ sceneIds: z.array(z.string().min(1).max(64)).min(1).max(500),
+}).strict();
+
+// The cached beat/tempo/section map (audioAnalysis.js output). Validated when a
+// record round-trips so a hand-edited/legacy project can't carry a malformed
+// analysis; the analyzer itself produces this shape.
+export const musicVideoAudioAnalysisSchema = z.object({
+ bpm: z.number().nullable(),
+ beats: z.array(z.number()),
+ downbeats: z.array(z.number()),
+ sections: z.array(z.object({
+ label: z.string(),
+ startSec: z.number(),
+ endSec: z.number(),
+ })),
+ durationSec: z.number(),
+}).strict();
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index a1f9568153..53dfc4225b 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -19,6 +19,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },
+ { id: 'nav.media.music-video', path: '/media/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },
{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 32a868712b..89777f45b1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1889,5 +1889,6 @@ export const legacyExportSchema = z.object({
// (e.g. `emptyToUndefined`) live in zodCompat.js.
export * from './peerSyncValidation.js';
export * from './creativeDirectorValidation.js';
+export * from './musicVideoValidation.js';
export * from './storyBuilderValidation.js';
export * from './moodBoardValidation.js';
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
new file mode 100644
index 0000000000..b72f22827b
--- /dev/null
+++ b/server/routes/musicVideo.js
@@ -0,0 +1,128 @@
+/**
+ * Music Video Routes — REST surface for the director scene board (#1760, Phase 1).
+ *
+ * Project CRUD + per-scene board operations + a synchronous beat/tempo/section
+ * analysis endpoint that runs the offline analyzer (Phase 0) on the project's
+ * audio. Per-scene reference-frame + i2v generation and the beat-snapped render
+ * are filed follow-ups; this surface covers the director MVP up to "scenes
+ * arranged against the beat grid".
+ */
+
+import { Router } from 'express';
+import { join } from 'path';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import {
+ validateRequest,
+ musicVideoProjectCreateSchema,
+ musicVideoProjectUpdateSchema,
+ musicVideoSceneCreateSchema,
+ musicVideoSceneUpdateSchema,
+ musicVideoSceneReorderSchema,
+} from '../lib/validation.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { safeUnder } from '../lib/ffmpeg.js';
+import {
+ listProjects,
+ getProject,
+ createProject,
+ updateProject,
+ deleteProject,
+ setProjectAnalysis,
+ addProjectScene,
+ updateScene,
+ deleteScene,
+ reorderProjectScenes,
+} from '../services/musicVideo/projects.js';
+import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
+import { getTrack } from '../services/tracks/index.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await listProjects());
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const p = await getProject(req.params.id);
+ if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(p);
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const data = validateRequest(musicVideoProjectCreateSchema, req.body);
+ const project = await createProject(data);
+ res.status(201).json(project);
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(musicVideoProjectUpdateSchema, req.body);
+ const updated = await updateProject(req.params.id, data);
+ res.json(updated);
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ await deleteProject(req.params.id);
+ res.json({ ok: true });
+}));
+
+// Resolve a project's source audio to an absolute path under data/music/. The
+// filename comes from the linked track or the uploaded-audio field; both are
+// validated as safe basenames so a tampered record can't escape the directory.
+async function resolveAudioPath(project) {
+ let filename = null;
+ if (project.trackId) {
+ const track = await getTrack(project.trackId);
+ if (!track) throw new ServerError('Linked track not found', { status: 404, code: 'NOT_FOUND' });
+ filename = track.audioFilename;
+ } else if (project.uploadedAudioFilename) {
+ filename = project.uploadedAudioFilename;
+ }
+ if (!filename) {
+ throw new ServerError('Project has no audio to analyze — set a track or upload audio first', { status: 400, code: 'NO_AUDIO' });
+ }
+ const safe = safeUnder(PATHS.music, filename);
+ if (!safe) throw new ServerError('Invalid audio filename', { status: 400, code: 'VALIDATION_ERROR' });
+ return safe;
+}
+
+// Run the offline beat/tempo/section analysis and cache it on the project.
+// Synchronous: the DSP pass over a song-length track is a couple of seconds, so
+// it returns the updated project directly (the SSE-streamed render lands later).
+router.post('/:id/analyze', asyncHandler(async (req, res) => {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const audioPath = await resolveAudioPath(project);
+ const analysis = await analyzeAudioFile(audioPath);
+ if (!analysis) {
+ throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });
+ }
+ const updated = await setProjectAnalysis(project.id, analysis);
+ res.json(updated);
+}));
+
+// --- Director scene board ---
+
+router.post('/:id/scenes', asyncHandler(async (req, res) => {
+ const data = validateRequest(musicVideoSceneCreateSchema, req.body);
+ const scene = await addProjectScene(req.params.id, data);
+ res.status(201).json(scene);
+}));
+
+router.patch('/:id/scenes/:sceneId', asyncHandler(async (req, res) => {
+ const data = validateRequest(musicVideoSceneUpdateSchema, req.body);
+ const updated = await updateScene(req.params.id, req.params.sceneId, data);
+ res.json(updated);
+}));
+
+router.delete('/:id/scenes/:sceneId', asyncHandler(async (req, res) => {
+ const updated = await deleteScene(req.params.id, req.params.sceneId);
+ res.json(updated);
+}));
+
+router.post('/:id/scenes/reorder', asyncHandler(async (req, res) => {
+ const { sceneIds } = validateRequest(musicVideoSceneReorderSchema, req.body);
+ const updated = await reorderProjectScenes(req.params.id, sceneIds);
+ res.json(updated);
+}));
+
+export default router;
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
new file mode 100644
index 0000000000..85d599ffa4
--- /dev/null
+++ b/server/routes/musicVideo.test.js
@@ -0,0 +1,161 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/musicVideo/projects.js', () => ({
+ listProjects: vi.fn(async () => [{ id: 'mv-1', name: 'A' }]),
+ getProject: vi.fn(),
+ createProject: vi.fn(async (d) => ({ id: 'mv-new', ...d })),
+ updateProject: vi.fn(async (id, p) => ({ id, ...p })),
+ deleteProject: vi.fn(async () => ({ ok: true })),
+ setProjectAnalysis: vi.fn(async (id, analysis) => ({ id, audioAnalysis: analysis, status: 'analyzed' })),
+ addProjectScene: vi.fn(async (id, s) => ({ sceneId: 'mvs-1', order: 0, ...s })),
+ updateScene: vi.fn(async (id, sceneId, p) => ({ sceneId, ...p })),
+ deleteScene: vi.fn(async (id) => ({ id, scenes: [] })),
+ reorderProjectScenes: vi.fn(async (id, ids) => ({ id, scenes: ids.map((sceneId, order) => ({ sceneId, order })) })),
+}));
+
+vi.mock('../services/musicVideo/audioAnalysis.js', () => ({
+ analyzeAudioFile: vi.fn(),
+}));
+
+vi.mock('../services/tracks/index.js', () => ({
+ getTrack: vi.fn(),
+}));
+
+import * as svc from '../services/musicVideo/projects.js';
+import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';
+import { getTrack } from '../services/tracks/index.js';
+import musicVideoRoutes from './musicVideo.js';
+
+describe('musicVideo routes', () => {
+ let app;
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/music-video', musicVideoRoutes);
+ vi.clearAllMocks();
+ });
+
+ it('GET / lists projects', async () => {
+ const r = await request(app).get('/api/music-video');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([{ id: 'mv-1', name: 'A' }]);
+ });
+
+ it('GET /:id 404s when missing', async () => {
+ svc.getProject.mockResolvedValue(null);
+ const r = await request(app).get('/api/music-video/mv-x');
+ expect(r.status).toBe(404);
+ expect(r.body.code).toBe('NOT_FOUND');
+ });
+
+ it('POST / creates after Zod validation', async () => {
+ const r = await request(app).post('/api/music-video').send({ name: 'New', mode: 'director' });
+ expect(r.status).toBe(201);
+ expect(r.body.name).toBe('New');
+ });
+
+ it('POST / rejects an invalid body (unknown mode)', async () => {
+ const r = await request(app).post('/api/music-video').send({ name: 'New', mode: 'wat' });
+ expect(r.status).toBe(400);
+ expect(svc.createProject).not.toHaveBeenCalled();
+ });
+
+ it('POST / rejects a missing name', async () => {
+ const r = await request(app).post('/api/music-video').send({ mode: 'director' });
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /:id updates', async () => {
+ const r = await request(app).patch('/api/music-video/mv-1').send({ name: 'Renamed' });
+ expect(r.status).toBe(200);
+ expect(r.body.name).toBe('Renamed');
+ });
+
+ it('DELETE /:id soft-deletes', async () => {
+ const r = await request(app).delete('/api/music-video/mv-1');
+ expect(r.status).toBe(200);
+ expect(svc.deleteProject).toHaveBeenCalledWith('mv-1');
+ });
+
+ describe('POST /:id/analyze', () => {
+ it('400s when the project has no audio source', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: null, uploadedAudioFilename: null });
+ const r = await request(app).post('/api/music-video/mv-1/analyze');
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('NO_AUDIO');
+ });
+
+ it('404s when the linked track is missing', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't-gone' });
+ getTrack.mockResolvedValue(null);
+ const r = await request(app).post('/api/music-video/mv-1/analyze');
+ expect(r.status).toBe(404);
+ });
+
+ it('400s on a path-traversal audio filename', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', uploadedAudioFilename: '../../etc/passwd' });
+ const r = await request(app).post('/api/music-video/mv-1/analyze');
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('422s when the analyzer cannot decode', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1' });
+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });
+ analyzeAudioFile.mockResolvedValue(null);
+ const r = await request(app).post('/api/music-video/mv-1/analyze');
+ expect(r.status).toBe(422);
+ expect(r.body.code).toBe('ANALYZE_FAILED');
+ });
+
+ it('caches the analysis and returns the updated project', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1' });
+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });
+ const analysis = { bpm: 120, beats: [0], downbeats: [0], sections: [], durationSec: 5 };
+ analyzeAudioFile.mockResolvedValue(analysis);
+ const r = await request(app).post('/api/music-video/mv-1/analyze');
+ expect(r.status).toBe(200);
+ expect(r.body.audioAnalysis).toEqual(analysis);
+ expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis);
+ });
+ });
+
+ describe('scene board', () => {
+ it('POST /:id/scenes adds a scene', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/scenes').send({ prompt: 'wide shot' });
+ expect(r.status).toBe(201);
+ expect(r.body.prompt).toBe('wide shot');
+ });
+
+ it('POST /:id/scenes rejects endSec < startSec', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/scenes').send({ startSec: 9, endSec: 1 });
+ expect(r.status).toBe(400);
+ expect(svc.addProjectScene).not.toHaveBeenCalled();
+ });
+
+ it('PATCH /:id/scenes/:sceneId updates a scene', async () => {
+ const r = await request(app).patch('/api/music-video/mv-1/scenes/mvs-1').send({ prompt: 'new' });
+ expect(r.status).toBe(200);
+ expect(r.body.prompt).toBe('new');
+ });
+
+ it('DELETE /:id/scenes/:sceneId removes a scene', async () => {
+ const r = await request(app).delete('/api/music-video/mv-1/scenes/mvs-1');
+ expect(r.status).toBe(200);
+ expect(svc.deleteScene).toHaveBeenCalledWith('mv-1', 'mvs-1');
+ });
+
+ it('POST /:id/scenes/reorder reorders', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/scenes/reorder').send({ sceneIds: ['b', 'a'] });
+ expect(r.status).toBe(200);
+ expect(r.body.scenes.map((s) => s.sceneId)).toEqual(['b', 'a']);
+ });
+
+ it('POST /:id/scenes/reorder rejects an empty list', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/scenes/reorder').send({ sceneIds: [] });
+ expect(r.status).toBe(400);
+ });
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index cd13afe299..79232f3442 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -655,6 +655,24 @@ CREATE TABLE IF NOT EXISTS creative_director_projects (
-- Partial index for the live-list filter (deleted = FALSE).
CREATE INDEX IF NOT EXISTS idx_creative_director_projects_live ON creative_director_projects (deleted) WHERE deleted = FALSE;
+-- Music Video projects (issue #1760). The director scene board's db-primary
+-- record: id/status/created_at/updated_at mirrored as columns, the full project
+-- (track link, cached audioAnalysis, scenes[]) in `data` JSONB — same shape as
+-- creative_director_projects. The soft-delete tombstone trio is present so
+-- peer-sync federation (a follow-up) is additive. Mirrors the music_video_projects
+-- block in db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS music_video_projects (
+ id TEXT PRIMARY KEY,
+ status VARCHAR(32) NOT NULL DEFAULT 'draft',
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so deletes propagate to peers
+ deleted_at TIMESTAMPTZ
+);
+-- Partial index for the live-list filter (deleted = FALSE).
+CREATE INDEX IF NOT EXISTS idx_music_video_projects_live ON music_video_projects (deleted) WHERE deleted = FALSE;
+
-- Mood boards (issue #911). A dedicated inspiration/mood-board canvas, distinct
-- from raw Media History, for collecting visual + textual references that feed
-- the Create suite. One row per board, the full record (name/description/items[])
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
new file mode 100644
index 0000000000..c660015b12
--- /dev/null
+++ b/server/services/musicVideo/projects.js
@@ -0,0 +1,92 @@
+/**
+ * Music Video — project store backend dispatcher (#1760, Phase 1).
+ *
+ * Mirrors the Creative Director dispatcher (services/creativeDirector/local.js):
+ * a thin layer that picks the backend so every import site + test mock targets
+ * one module.
+ *
+ * Backend selection (same posture as the memory backend):
+ * - PostgreSQL (projectsDB.js) for normal installs.
+ * - File (projectsFile.js) only via MEMORY_BACKEND=file (escape hatch) or
+ * NODE_ENV=test — both UNSUPPORTED for production. Tests boot without a DB,
+ * so they exercise the file backend.
+ *
+ * Federation note: peer-sync of `musicVideoProject` records (record-event emit,
+ * LWW merge, tombstone GC — the wiring the CD store carries) is a deliberate
+ * follow-up, tracked as its own issue. The store is db-primary and fully usable
+ * locally now; adding federation later is additive (the soft-delete fields are
+ * already on the record). Until then this dispatcher does no record-event emit.
+ */
+
+import { checkHealth, ensureSchema } from '../../lib/db.js';
+
+let backend = null;
+let backendName = null;
+
+async function selectBackend() {
+ if (backend) return backend;
+
+ const envBackend = process.env.MEMORY_BACKEND;
+ if (envBackend === 'file' || process.env.NODE_ENV === 'test') {
+ backend = await import('./projectsFile.js');
+ backendName = 'file';
+ return backend;
+ }
+
+ // Default + explicit postgres → PostgreSQL. ensureSchema() is idempotent and
+ // run here (mirroring memoryBackend.js) so the backend is self-sufficient
+ // regardless of boot ordering.
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Music Video requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env)');
+ }
+ await ensureSchema();
+ backend = await import('./projectsDB.js');
+ backendName = 'postgres';
+ return backend;
+}
+
+/** Name of the active backend, or null before first call (for diagnostics/tests). */
+export function getProjectsBackendName() {
+ return backendName;
+}
+
+export async function listProjects(options = {}) {
+ return (await selectBackend()).listProjects(options);
+}
+
+export async function getProject(id, options = {}) {
+ return (await selectBackend()).getProject(id, options);
+}
+
+export async function createProject(input) {
+ return (await selectBackend()).createProject(input);
+}
+
+export async function updateProject(id, patch) {
+ return (await selectBackend()).updateProject(id, patch);
+}
+
+export async function deleteProject(id) {
+ return (await selectBackend()).deleteProject(id);
+}
+
+export async function setProjectAnalysis(id, analysis) {
+ return (await selectBackend()).setProjectAnalysis(id, analysis);
+}
+
+export async function addProjectScene(id, sceneInput) {
+ return (await selectBackend()).addProjectScene(id, sceneInput);
+}
+
+export async function updateScene(id, sceneId, patch) {
+ return (await selectBackend()).updateScene(id, sceneId, patch);
+}
+
+export async function deleteScene(id, sceneId) {
+ return (await selectBackend()).deleteScene(id, sceneId);
+}
+
+export async function reorderProjectScenes(id, orderedIds) {
+ return (await selectBackend()).reorderProjectScenes(id, orderedIds);
+}
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
new file mode 100644
index 0000000000..e657716c28
--- /dev/null
+++ b/server/services/musicVideo/projectsDB.js
@@ -0,0 +1,144 @@
+/**
+ * Music Video — PostgreSQL-backed project store (default backend, #1760).
+ *
+ * One row per project in `music_video_projects`: id / status / created_at /
+ * updated_at mirrored as columns, the full record in `data` JSONB. Mirrors the
+ * Creative Director store (#997): every mutator runs inside withTransaction +
+ * `SELECT … FOR UPDATE` so a blur-save and an explicit action against the same
+ * project serialize instead of losing an update. Mutation semantics live in
+ * projectsLogic.js (shared with projectsFile.js) so the two can't drift.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ mirrorStatus,
+ mirrorTimestamp,
+ buildProjectRecord,
+ applyProjectPatch,
+ setAudioAnalysis,
+ addScene,
+ applySceneUpdate,
+ removeScene,
+ reorderScenes,
+} from './projectsLogic.js';
+
+// `data` JSONB is the whole record; status/created_at/updated_at are a queryable
+// mirror kept in lockstep but never read back — reads return `data` verbatim so
+// callers see the exact shape the file backend gives.
+function rowToProject(row) {
+ return row ? row.data : null;
+}
+
+async function persist(exec, project) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(project.createdAt, now);
+ await exec(
+ `INSERT INTO music_video_projects (id, status, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ status = EXCLUDED.status,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ project.id,
+ mirrorStatus(project.status),
+ JSON.stringify(project),
+ createdAt,
+ mirrorTimestamp(project.updatedAt, createdAt),
+ project.deleted === true,
+ mirrorTimestamp(project.deletedAt, null),
+ ],
+ );
+ return project;
+}
+
+export async function listProjects({ includeDeleted = false } = {}) {
+ const result = includeDeleted
+ ? await query(`SELECT data FROM music_video_projects ORDER BY created_at ASC`)
+ : await query(`SELECT data FROM music_video_projects WHERE deleted = FALSE ORDER BY created_at ASC`);
+ return result.rows.map(rowToProject);
+}
+
+export async function getProject(id, { includeDeleted = false } = {}) {
+ const result = await query(`SELECT data FROM music_video_projects WHERE id = $1`, [id]);
+ const project = rowToProject(result.rows[0]);
+ if (!project) return null;
+ return includeDeleted || !project.deleted ? project : null;
+}
+
+export async function createProject(input) {
+ const id = `mv-${randomUUID()}`;
+ const now = new Date().toISOString();
+ const project = buildProjectRecord(input, { id, now });
+ await persist(query, project);
+ console.log(`🎞️ Created Music Video project: ${id} (${input.name})`);
+ return project;
+}
+
+// Lock the row, apply `mutate(project)`, persist, return the mutator's result.
+// Throws NOT_FOUND when the row is absent or tombstoned (a post-delete write
+// must not resurrect the row).
+async function withLockedProject(id, mutate) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [id]);
+ const project = rowToProject(sel.rows[0]);
+ if (!project || project.deleted) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const { project: next, result } = mutate(project);
+ await persist(client.query.bind(client), next);
+ return { project: next, result };
+ });
+}
+
+export async function updateProject(id, patch) {
+ const { project } = await withLockedProject(id, (p) => ({ project: applyProjectPatch(p, patch) }));
+ return project;
+}
+
+export async function deleteProject(id) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(`SELECT data FROM music_video_projects WHERE id = $1 FOR UPDATE`, [id]);
+ const current = rowToProject(sel.rows[0]);
+ if (!current || current.deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const now = new Date().toISOString();
+ const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };
+ await persist(client.query.bind(client), next);
+ return { ok: true };
+ });
+}
+
+export async function setProjectAnalysis(id, analysis) {
+ const { project } = await withLockedProject(id, (p) => ({ project: setAudioAnalysis(p, analysis) }));
+ return project;
+}
+
+export async function addProjectScene(id, sceneInput) {
+ const { result } = await withLockedProject(id, (p) => {
+ const { project, scene } = addScene(p, sceneInput);
+ return { project, result: scene };
+ });
+ return result;
+}
+
+export async function updateScene(id, sceneId, patch) {
+ const { result } = await withLockedProject(id, (p) => {
+ const { project, updated } = applySceneUpdate(p, sceneId, patch);
+ return { project, result: updated };
+ });
+ return result;
+}
+
+export async function deleteScene(id, sceneId) {
+ const { project } = await withLockedProject(id, (p) => ({ project: removeScene(p, sceneId) }));
+ return project;
+}
+
+export async function reorderProjectScenes(id, orderedIds) {
+ const { project } = await withLockedProject(id, (p) => ({ project: reorderScenes(p, orderedIds) }));
+ return project;
+}
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
new file mode 100644
index 0000000000..635b668a79
--- /dev/null
+++ b/server/services/musicVideo/projectsFile.js
@@ -0,0 +1,117 @@
+/**
+ * Music Video — file-backed project store (escape-hatch / test backend).
+ *
+ * Persists to data/music-video-projects.json (array, atomicWrite). Reachable
+ * only via MEMORY_BACKEND=file or NODE_ENV=test — PostgreSQL (projectsDB.js) is
+ * the default. All mutation semantics live in projectsLogic.js so this backend
+ * and the PG backend can't drift; this module only does load/find/persist.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ buildProjectRecord,
+ applyProjectPatch,
+ setAudioAnalysis,
+ addScene,
+ applySceneUpdate,
+ removeScene,
+ reorderScenes,
+} from './projectsLogic.js';
+
+const PROJECTS_FILE = join(PATHS.data, 'music-video-projects.json');
+
+async function loadAll() {
+ const raw = await readJSONFile(PROJECTS_FILE, []);
+ return Array.isArray(raw) ? raw : [];
+}
+
+async function saveAll(projects) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(PROJECTS_FILE, projects);
+}
+
+export async function listProjects({ includeDeleted = false } = {}) {
+ const all = await loadAll();
+ return includeDeleted ? all : all.filter((p) => !p.deleted);
+}
+
+export async function getProject(id, { includeDeleted = false } = {}) {
+ const all = await loadAll();
+ const found = all.find((p) => p.id === id);
+ if (!found) return null;
+ return includeDeleted || !found.deleted ? found : null;
+}
+
+export async function createProject(input) {
+ const id = `mv-${randomUUID()}`;
+ const now = new Date().toISOString();
+ const project = buildProjectRecord(input, { id, now });
+ const all = await loadAll();
+ all.push(project);
+ await saveAll(all);
+ console.log(`🎞️ Created Music Video project: ${id} (${input.name})`);
+ return project;
+}
+
+// Locate a live (non-tombstoned) project for a user-facing mutator, or throw 404.
+async function loadAllAndIndex(id) {
+ const all = await loadAll();
+ const idx = all.findIndex((p) => p.id === id);
+ if (idx < 0 || all[idx].deleted) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ return { all, idx };
+}
+
+export async function updateProject(id, patch) {
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = applyProjectPatch(all[idx], patch);
+ await saveAll(all);
+ return all[idx];
+}
+
+export async function deleteProject(id) {
+ const { all, idx } = await loadAllAndIndex(id);
+ const now = new Date().toISOString();
+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };
+ await saveAll(all);
+ return { ok: true };
+}
+
+export async function setProjectAnalysis(id, analysis) {
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = setAudioAnalysis(all[idx], analysis);
+ await saveAll(all);
+ return all[idx];
+}
+
+export async function addProjectScene(id, sceneInput) {
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, scene } = addScene(all[idx], sceneInput);
+ all[idx] = project;
+ await saveAll(all);
+ return scene;
+}
+
+export async function updateScene(id, sceneId, patch) {
+ const { all, idx } = await loadAllAndIndex(id);
+ const { project, updated } = applySceneUpdate(all[idx], sceneId, patch);
+ all[idx] = project;
+ await saveAll(all);
+ return updated;
+}
+
+export async function deleteScene(id, sceneId) {
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = removeScene(all[idx], sceneId);
+ await saveAll(all);
+ return all[idx];
+}
+
+export async function reorderProjectScenes(id, orderedIds) {
+ const { all, idx } = await loadAllAndIndex(id);
+ all[idx] = reorderScenes(all[idx], orderedIds);
+ await saveAll(all);
+ return all[idx];
+}
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
new file mode 100644
index 0000000000..cbb82e0c66
--- /dev/null
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -0,0 +1,85 @@
+/**
+ * Music Video file-backend round-trip (#1760). Runs against a tmpdir in the
+ * normal (non-DB) suite — covers create/list/get/update/delete + the scene-board
+ * mutators + analysis caching + soft-delete, without touching real `data/` or
+ * needing Postgres. The PG backend shares the same projectsLogic decisions, so
+ * its row I/O mirrors this.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'mv-projects-file-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const file = await import('./projectsFile.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'music-video-projects.json'), { force: true });
+}
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('projectsFile backend', () => {
+ it('creates, lists, and gets a project', async () => {
+ const created = await file.createProject({ name: 'MV One', trackId: 't1' });
+ expect(created.id).toMatch(/^mv-/);
+ const list = await file.listProjects();
+ expect(list).toHaveLength(1);
+ expect((await file.getProject(created.id)).name).toBe('MV One');
+ });
+
+ it('updates project metadata', async () => {
+ const p = await file.createProject({ name: 'A' });
+ const updated = await file.updateProject(p.id, { name: 'B', status: 'ready' });
+ expect(updated.name).toBe('B');
+ expect(updated.status).toBe('ready');
+ });
+
+ it('caches audio analysis and flips draft to analyzed', async () => {
+ const p = await file.createProject({ name: 'A' });
+ const analysis = { bpm: 128, beats: [0], downbeats: [0], sections: [], durationSec: 10 };
+ const updated = await file.setProjectAnalysis(p.id, analysis);
+ expect(updated.audioAnalysis).toEqual(analysis);
+ expect(updated.status).toBe('analyzed');
+ });
+
+ it('runs the full scene-board lifecycle', async () => {
+ const p = await file.createProject({ name: 'A' });
+ const s1 = await file.addProjectScene(p.id, { prompt: 'one' });
+ const s2 = await file.addProjectScene(p.id, { prompt: 'two' });
+ expect(s1.order).toBe(0);
+ expect(s2.order).toBe(1);
+
+ const upd = await file.updateScene(p.id, s1.sceneId, { prompt: 'one-edited' });
+ expect(upd.prompt).toBe('one-edited');
+
+ let proj = await file.reorderProjectScenes(p.id, [s2.sceneId, s1.sceneId]);
+ expect(proj.scenes.map((s) => s.sceneId)).toEqual([s2.sceneId, s1.sceneId]);
+
+ proj = await file.deleteScene(p.id, s2.sceneId);
+ expect(proj.scenes).toHaveLength(1);
+ expect(proj.scenes[0].order).toBe(0);
+ });
+
+ it('soft-deletes a project (tombstone hidden from live list)', async () => {
+ const p = await file.createProject({ name: 'A' });
+ await file.deleteProject(p.id);
+ expect(await file.listProjects()).toHaveLength(0);
+ expect(await file.getProject(p.id)).toBeNull();
+ expect(await file.listProjects({ includeDeleted: true })).toHaveLength(1);
+ });
+
+ it('404s mutating a deleted project (no resurrection)', async () => {
+ const p = await file.createProject({ name: 'A' });
+ await file.deleteProject(p.id);
+ await expect(file.updateProject(p.id, { name: 'X' })).rejects.toThrow(/not found/i);
+ await expect(file.addProjectScene(p.id, { prompt: 'x' })).rejects.toThrow(/not found/i);
+ });
+});
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
new file mode 100644
index 0000000000..da864a658a
--- /dev/null
+++ b/server/services/musicVideo/projectsLogic.js
@@ -0,0 +1,169 @@
+/**
+ * Music Video — pure record transforms (issue #1760, Phase 1).
+ *
+ * Mirrors the Creative Director store split: the file backend (projectsFile.js)
+ * and the PostgreSQL backend (projectsDB.js) share the SAME mutation semantics
+ * and differ only in load/persist, so all storage-agnostic logic lives here.
+ * Each function takes a plain project record and returns the next record (or
+ * throws a ServerError on a validation failure), leaving read/write to the
+ * caller.
+ *
+ * Scope note: peer-sync federation (sanitize/merge/tombstone-GC helpers the CD
+ * store carries) is deferred to a follow-up — see services/musicVideo/projects.js.
+ * The soft-delete fields are kept on the record now so adding federation later
+ * is purely additive.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ MUSIC_VIDEO_STATUSES,
+ musicVideoAudioAnalysisSchema,
+ musicVideoSceneCreateSchema,
+ musicVideoSceneUpdateSchema,
+} from '../../lib/validation.js';
+
+// Re-exported for the PG backend's typed mirror columns (mirrors the CD store).
+export { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+const STATUS_COLUMN_MAX = 32;
+
+/** Safe value for the `status` mirror column — bounded, never null. */
+export function mirrorStatus(status) {
+ return (typeof status === 'string' && status ? status : 'draft').slice(0, STATUS_COLUMN_MAX);
+}
+
+/** Return the next record with `extra` merged and `updatedAt` freshly stamped. */
+function touch(record, extra) {
+ return { ...record, ...extra, updatedAt: new Date().toISOString() };
+}
+
+/** safeParse a scene payload, throwing a 400 ServerError with field detail on failure. */
+function parseSceneOrThrow(schema, input) {
+ const parsed = schema.safeParse(input);
+ if (!parsed.success) {
+ throw new ServerError(
+ `Scene validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,
+ { status: 400, code: 'VALIDATION_ERROR' },
+ );
+ }
+ return parsed.data;
+}
+
+/** Build a fresh project record from validated create input. */
+export function buildProjectRecord(input, { id, now }) {
+ const {
+ name, mode = 'director', trackId = null,
+ uploadedAudioFilename = null, concept = null,
+ } = input;
+ return {
+ id,
+ name,
+ status: 'draft',
+ mode,
+ createdAt: now,
+ updatedAt: now,
+ trackId,
+ uploadedAudioFilename,
+ concept,
+ audioAnalysis: null,
+ scenes: [],
+ renderHistoryId: null,
+ // Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)
+ // is additive rather than a record-shape migration.
+ deleted: false,
+ deletedAt: null,
+ };
+}
+
+/** Merge a project metadata patch, validating status. Returns the next record. */
+export function applyProjectPatch(project, patch) {
+ if (patch.status && !MUSIC_VIDEO_STATUSES.includes(patch.status)) {
+ throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ return touch(project, patch);
+}
+
+/**
+ * Cache the offline beat/tempo/section analysis on the project. Flips a `draft`
+ * project to `analyzed`; leaves any later status untouched (re-analysis of a
+ * ready/rendering project shouldn't regress its lifecycle). The analysis shape
+ * is validated so a hand-edited/legacy record can't store a malformed map.
+ */
+export function setAudioAnalysis(project, analysis) {
+ const validated = musicVideoAudioAnalysisSchema.parse(analysis);
+ const status = project.status === 'draft' ? 'analyzed' : project.status;
+ return touch(project, { audioAnalysis: validated, status });
+}
+
+/** Default runtime fields for a scene the director (or planner) didn't supply. */
+function buildScene(input, { order }) {
+ return {
+ sceneId: `mvs-${randomUUID()}`,
+ order,
+ label: input.label ?? '',
+ sectionLabel: input.sectionLabel ?? null,
+ startSec: input.startSec ?? null,
+ endSec: input.endSec ?? null,
+ beatAligned: input.beatAligned ?? false,
+ prompt: input.prompt ?? '',
+ framePrompt: input.framePrompt ?? null,
+ referenceImageId: null,
+ videoHistoryId: null,
+ };
+}
+
+/**
+ * Append a scene to the board. Validates the input, assigns a sceneId and the
+ * next order index. Returns `{ project, scene }`.
+ */
+export function addScene(project, sceneInput) {
+ const data = parseSceneOrThrow(musicVideoSceneCreateSchema, sceneInput);
+ const scenes = project.scenes || [];
+ const scene = buildScene(data, { order: scenes.length });
+ const next = touch(project, { scenes: [...scenes, scene] });
+ return { project: next, scene };
+}
+
+/**
+ * Apply a patch to a single scene. Returns `{ project, updated }`. Throws if the
+ * scene id is unknown.
+ */
+export function applySceneUpdate(project, sceneId, patch) {
+ const data = parseSceneOrThrow(musicVideoSceneUpdateSchema, patch);
+ const scenes = project.scenes || [];
+ const idx = scenes.findIndex((s) => s.sceneId === sceneId);
+ if (idx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ const updated = { ...scenes[idx], ...data };
+ const nextScenes = scenes.slice();
+ nextScenes[idx] = updated;
+ const next = touch(project, { scenes: nextScenes });
+ return { project: next, updated };
+}
+
+/** Remove a scene and re-sequence the remaining scenes' `order`. Returns the next record. */
+export function removeScene(project, sceneId) {
+ const scenes = project.scenes || [];
+ if (!scenes.some((s) => s.sceneId === sceneId)) {
+ throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const nextScenes = scenes
+ .filter((s) => s.sceneId !== sceneId)
+ .map((s, i) => ({ ...s, order: i }));
+ return touch(project, { scenes: nextScenes });
+}
+
+/**
+ * Reorder the board to the given sceneId order. `orderedIds` must be exactly the
+ * project's current scene ids (a permutation) — a missing/extra/unknown id is a
+ * 400 so a stale client can't silently drop scenes. Returns the next record.
+ */
+export function reorderScenes(project, orderedIds) {
+ const scenes = project.scenes || [];
+ const byId = new Map(scenes.map((s) => [s.sceneId, s]));
+ if (orderedIds.length !== scenes.length || !orderedIds.every((id) => byId.has(id)) || new Set(orderedIds).size !== orderedIds.length) {
+ throw new ServerError('Reorder must list each existing scene id exactly once', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const nextScenes = orderedIds.map((id, i) => ({ ...byId.get(id), order: i }));
+ return touch(project, { scenes: nextScenes });
+}
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
new file mode 100644
index 0000000000..fb6366610a
--- /dev/null
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -0,0 +1,131 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildProjectRecord,
+ applyProjectPatch,
+ setAudioAnalysis,
+ addScene,
+ applySceneUpdate,
+ removeScene,
+ reorderScenes,
+ mirrorStatus,
+} from './projectsLogic.js';
+
+const baseProject = () => buildProjectRecord({ name: 'Test MV' }, { id: 'mv-1', now: '2026-01-01T00:00:00.000Z' });
+
+describe('buildProjectRecord', () => {
+ it('builds a draft director project with sensible defaults', () => {
+ const p = buildProjectRecord({ name: 'Neon Nights', trackId: 'track-9' }, { id: 'mv-x', now: '2026-01-01T00:00:00.000Z' });
+ expect(p).toMatchObject({
+ id: 'mv-x', name: 'Neon Nights', status: 'draft', mode: 'director',
+ trackId: 'track-9', uploadedAudioFilename: null, concept: null,
+ audioAnalysis: null, scenes: [], renderHistoryId: null,
+ deleted: false, deletedAt: null,
+ });
+ expect(p.createdAt).toBe(p.updatedAt);
+ });
+
+ it('honors an explicit autonomous mode and concept', () => {
+ const p = buildProjectRecord({ name: 'A', mode: 'autonomous', concept: { prompt: 'noir' } }, { id: 'mv-2', now: 'n' });
+ expect(p.mode).toBe('autonomous');
+ expect(p.concept).toEqual({ prompt: 'noir' });
+ });
+});
+
+describe('applyProjectPatch', () => {
+ it('merges fields and bumps updatedAt', () => {
+ const next = applyProjectPatch(baseProject(), { name: 'Renamed', trackId: 't2' });
+ expect(next.name).toBe('Renamed');
+ expect(next.trackId).toBe('t2');
+ expect(next.updatedAt).not.toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('rejects an invalid status', () => {
+ expect(() => applyProjectPatch(baseProject(), { status: 'bogus' })).toThrow(/Invalid status/);
+ });
+
+ it('accepts a valid status', () => {
+ expect(applyProjectPatch(baseProject(), { status: 'ready' }).status).toBe('ready');
+ });
+});
+
+describe('setAudioAnalysis', () => {
+ const analysis = { bpm: 120, beats: [0, 0.5], downbeats: [0], sections: [{ label: 'Section 1', startSec: 0, endSec: 1 }], durationSec: 1 };
+
+ it('caches the analysis and flips a draft to analyzed', () => {
+ const next = setAudioAnalysis(baseProject(), analysis);
+ expect(next.audioAnalysis).toEqual(analysis);
+ expect(next.status).toBe('analyzed');
+ });
+
+ it('does not regress a later lifecycle status', () => {
+ const ready = { ...baseProject(), status: 'ready' };
+ expect(setAudioAnalysis(ready, analysis).status).toBe('ready');
+ });
+});
+
+describe('scene board operations', () => {
+ it('adds scenes with incrementing order and unique ids', () => {
+ const { project: p1, scene: s1 } = addScene(baseProject(), { prompt: 'wide shot' });
+ const { project: p2, scene: s2 } = addScene(p1, { prompt: 'close up' });
+ expect(s1.order).toBe(0);
+ expect(s2.order).toBe(1);
+ expect(s1.sceneId).not.toBe(s2.sceneId);
+ expect(p2.scenes).toHaveLength(2);
+ expect(s1.prompt).toBe('wide shot');
+ expect(s1.referenceImageId).toBeNull();
+ });
+
+ it('rejects a scene whose endSec precedes startSec', () => {
+ expect(() => addScene(baseProject(), { startSec: 10, endSec: 5 })).toThrow(/Scene validation failed/);
+ });
+
+ it('updates a scene by id', () => {
+ const { project, scene } = addScene(baseProject(), { prompt: 'a' });
+ const { updated } = applySceneUpdate(project, scene.sceneId, { prompt: 'b', referenceImageId: 'img-1' });
+ expect(updated.prompt).toBe('b');
+ expect(updated.referenceImageId).toBe('img-1');
+ });
+
+ it('404s updating an unknown scene', () => {
+ expect(() => applySceneUpdate(baseProject(), 'nope', { prompt: 'x' })).toThrow(/Scene not found/);
+ });
+
+ it('removes a scene and re-sequences order', () => {
+ let p = baseProject();
+ const ids = [];
+ for (const prompt of ['a', 'b', 'c']) { const r = addScene(p, { prompt }); p = r.project; ids.push(r.scene.sceneId); }
+ const next = removeScene(p, ids[0]);
+ expect(next.scenes).toHaveLength(2);
+ expect(next.scenes.map((s) => s.order)).toEqual([0, 1]);
+ expect(next.scenes.map((s) => s.sceneId)).toEqual([ids[1], ids[2]]);
+ });
+
+ it('404s removing an unknown scene', () => {
+ expect(() => removeScene(baseProject(), 'nope')).toThrow(/Scene not found/);
+ });
+
+ it('reorders scenes to the given id order and reassigns order', () => {
+ let p = baseProject();
+ const ids = [];
+ for (const prompt of ['a', 'b', 'c']) { const r = addScene(p, { prompt }); p = r.project; ids.push(r.scene.sceneId); }
+ const next = reorderScenes(p, [ids[2], ids[0], ids[1]]);
+ expect(next.scenes.map((s) => s.sceneId)).toEqual([ids[2], ids[0], ids[1]]);
+ expect(next.scenes.map((s) => s.order)).toEqual([0, 1, 2]);
+ });
+
+ it('rejects a reorder that is not an exact permutation', () => {
+ let p = baseProject();
+ const r = addScene(p, { prompt: 'a' }); p = r.project;
+ expect(() => reorderScenes(p, [r.scene.sceneId, 'extra'])).toThrow(/each existing scene id exactly once/);
+ expect(() => reorderScenes(p, [])).toThrow(/each existing scene id exactly once/);
+ });
+});
+
+describe('mirrorStatus', () => {
+ it('bounds and defaults the status column value', () => {
+ expect(mirrorStatus('rendering')).toBe('rendering');
+ expect(mirrorStatus('')).toBe('draft');
+ expect(mirrorStatus(null)).toBe('draft');
+ expect(mirrorStatus('x'.repeat(40))).toHaveLength(32);
+ });
+});