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: add universe and cast setup to music videos

[._.]/ Adam Eivy6b59a9be7df3
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsx
new file mode 100644
index 0000000000..6ee9e95a49
--- /dev/null
+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx
@@ -0,0 +1,146 @@
+import { useEffect, useState } from 'react';
+import { Link } from 'react-router';
+import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuilder.js';
+import { getMoodBoard } from '../../services/apiMoodBoard.js';
+import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';
+import { uuidv4 } from '../../lib/uuid.js';
+import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';
+import { collectBoardStyleContext } from '../../../../server/lib/moodBoardStyleContext.js';
+
+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
+const kinds = [['character', 'Cast'], ['place', 'Places'], ['object', 'Objects']];
+const fields = { character: 'characters', place: 'places', object: 'objects' };
+
+/** Project-owned snapshots: changing source canon never silently recasts a video. */
+export default function CreativeSetupPanel({ project, onSave, onPendingChange }) {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(null);
+ const [lists, setLists] = useState({ universes: [] });
+ const [universe, setUniverse] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [newKind, setNewKind] = useState('character');
+ const [newName, setNewName] = useState('');
+ const [newDescription, setNewDescription] = useState('');
+ const [selectedCanon, setSelectedCanon] = useState([]);
+ const universeId = draft?.universeId ?? project.concept?.universeId ?? '';
+ const subjects = draft?.subjects || project.concept?.subjects || [];
+ const idFor = (name) => `mv-creative-${project.id}-${name}`;
+
+ useEffect(() => {
+ onPendingChange(editing);
+ return () => onPendingChange(false);
+ }, [editing, onPendingChange]);
+
+ useEffect(() => {
+ if (!editing) return undefined;
+ let active = true;
+ listUniverseNames({ silent: true })
+ .then((universes) => { if (active) setLists({ universes }); })
+ .catch((err) => { if (active) setError(err.message); });
+ return () => { active = false; };
+ }, [editing]);
+
+ useEffect(() => {
+ if (!editing || !universeId) { setUniverse(null); setLoading(false); return undefined; }
+ let active = true;
+ setLoading(true);
+ setUniverse(null);
+ getUniverse(universeId, { silent: true })
+ .then((value) => { if (active) setUniverse(value); })
+ .catch((err) => { if (active) setError(err.message); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [editing, universeId]);
+
+ const begin = () => {
+ setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [], moodBoardId: project.visualSpec?.moodBoardId || '' });
+ setSelectedCanon([]);
+ setNewName('');
+ setNewDescription('');
+ setError('');
+ setEditing(true);
+ };
+ const add = (kind, name, description, canon) => {
+ if (!name.trim() || subjects.length >= 24) return;
+ const subject = { id: `mvc-${uuidv4()}`, kind, name: name.trim().slice(0, 120), description: (description || '').slice(0, 1000), ...(kind === 'character' ? { role: subjects.some((s) => s.kind === 'character') ? 'supporting' : 'protagonist' } : {}), ...(canon?.id ? { canonId: canon.id } : {}) };
+ setDraft((d) => ({ ...d, subjects: [...d.subjects, subject] }));
+ if (canon) setSelectedCanon((items) => [...items, { subjectId: subject.id, kind, entry: canon }]);
+ };
+ const save = async () => {
+ setSaving(true);
+ setError('');
+ const concept = { subjects: draft.subjects, universeId: draft.universeId || null };
+ if (draft.universeId !== (project.concept?.universeId || '') || project.concept?.universeStyle == null) {
+ concept.universeStyle = universe ? [universe.name, universe.styleNotes, universe.influences?.embrace?.length ? `Embrace: ${universe.influences.embrace.join(', ')}` : '', universe.influences?.avoid?.length ? `Avoid: ${universe.influences.avoid.join(', ')}` : ''].filter(Boolean).join('\n').slice(0, 4000) : '';
+ }
+ const visualSpec = { moodBoardId: draft.moodBoardId || null };
+ const canon = { characters: [], places: [], objects: [] };
+ for (const item of selectedCanon) {
+ if (draft.subjects.some((s) => s.id === item.subjectId)) canon[fields[item.kind]].push(item.entry);
+ }
+ const pulled = pullUniverseCanonReferences(canon, project.visualSpec?.references || []);
+ if (pulled.added) visualSpec.references = pulled.next;
+ const refreshBoard = draft.moodBoardId !== (project.visualSpec?.moodBoardId || '') || project.concept?.moodBoardStyle == null;
+ const boardRequest = draft.moodBoardId && refreshBoard
+ ? getMoodBoard(draft.moodBoardId, { silent: true }) : Promise.resolve(null);
+ return boardRequest.then((board) => {
+ if (refreshBoard) {
+ const context = board ? collectBoardStyleContext(board) : null;
+ concept.moodBoardStyle = context ? [context.name, context.description, ...context.items.map((item) => Object.values(item).join('; '))].filter(Boolean).join('\n').slice(0, 4000) : '';
+ }
+ return onSave({ concept, visualSpec });
+ }).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));
+ };
+
+ return <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0 break-words" aria-label="Creative setup">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 className="text-sm font-medium">Universe, cast, places &amp; objects</h3>
+ {!editing && <button type="button" onClick={begin} className="text-sm text-port-accent min-h-[44px]">Set up creative direction</button>}
+ </div>
+ {!editing ? <p className="text-xs text-port-text-muted">{subjects.length ? subjects.map((s) => `${s.name}${s.role === 'protagonist' ? ' (protagonist)' : s.role === 'band' ? ' (band)' : ''}`).join(' · ') : 'Create the band or protagonist, choose a universe, and select the places and objects that anchor the story.'}</p> : <fieldset disabled={saving} className="space-y-3 min-w-0">
+ <p className="text-xs text-port-text-muted">Save this setup before planning or generating. Canon and style are copied into this project; source records stay independent.</p>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div><label htmlFor={idFor('universe')} className="text-xs">Universe</label>
+ <select id={idFor('universe')} className={inputClass} value={universeId} onChange={(e) => { setDraft((d) => ({ ...d, universeId: e.target.value })); setError(''); }}>
+ <option value="">No universe</option>
+ {universeId && !lists.universes.some((u) => u.id === universeId) && <option value={universeId}>Selected universe</option>}
+ {lists.universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ {universeId && <Link className="text-xs text-port-accent" target="_blank" to={`/universes/${encodeURIComponent(universeId)}`}>Edit universe canon</Link>}
+ </div>
+ <div>
+ <MoodBoardReferenceStrip value={draft.moodBoardId} onChange={(id) => setDraft((d) => ({ ...d, moodBoardId: id || '' }))} newBoardName={project.name} />
+ <p className="text-xs text-port-text-muted">Copies captions, notes and analyzed styles. Add images in Visual spec to condition frames.</p>
+ </div>
+ </div>
+ {loading && <p className="text-xs">Loading canon…</p>}
+ {universe && <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">{kinds.map(([kind, label]) => <div key={kind}>
+ <label htmlFor={idFor(`pick-${kind}`)} className="text-xs">Select {label.toLowerCase()}</label>
+ <select id={idFor(`pick-${kind}`)} value="" className={inputClass} disabled={subjects.length >= 24} onChange={(e) => {
+ const entry = (universe[fields[kind]] || []).find((item) => item.id === e.target.value);
+ if (entry) add(kind, entry.name, entry.physicalDescription || entry.description, entry);
+ }}><option value="">Add from universe…</option>{(universe[fields[kind]] || []).filter((entry) => !subjects.some((s) => s.canonId === entry.id && s.kind === kind)).map((entry) => <option key={entry.id} value={entry.id}>{entry.name}</option>)}</select>
+ </div>)}</div>}
+ <p className="text-xs text-port-text-muted">Up to 24 subjects. Selected canon images are added as look references when space is available; enable “Condition frames” in Visual spec to use their pixels.</p>
+ <ul className="space-y-2">{subjects.map((subject) => <li key={subject.id} className="border border-port-border rounded p-2 space-y-1">
+ <div className="flex flex-wrap items-center gap-2"><span className="text-sm min-w-0 flex-1 break-words">{subject.name} · {subject.kind}</span>
+ {subject.kind === 'character' && <><label htmlFor={idFor(subject.id)} className="sr-only">Role for {subject.name}</label><select id={idFor(subject.id)} className="bg-port-bg border border-port-border rounded text-xs" value={subject.role || 'supporting'} onChange={(e) => setDraft((d) => ({ ...d, subjects: d.subjects.map((s) => s.id === subject.id ? { ...s, role: e.target.value } : s) }))}><option value="protagonist">Protagonist</option><option value="band">Band</option><option value="supporting">Supporting</option></select></>}
+ <button type="button" aria-label={`Remove ${subject.name}`} className="ml-auto text-xs text-port-error min-h-[44px]" onClick={() => setDraft((d) => ({ ...d, subjects: d.subjects.filter((s) => s.id !== subject.id) }))}>Remove</button>
+ </div>
+ <label htmlFor={idFor(`description-${subject.id}`)} className="sr-only">Description for {subject.name}</label>
+ <textarea id={idFor(`description-${subject.id}`)} rows={2} maxLength={1000} className={inputClass} value={subject.description || ''} onChange={(e) => setDraft((d) => ({ ...d, subjects: d.subjects.map((s) => s.id === subject.id ? { ...s, description: e.target.value } : s) }))} />
+ </li>)}</ul>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <div><label htmlFor={idFor('kind')} className="text-xs">Create for this video</label><select id={idFor('kind')} className={inputClass} value={newKind} onChange={(e) => setNewKind(e.target.value)}>{kinds.map(([kind, label]) => <option key={kind} value={kind}>{label}</option>)}</select></div>
+ <div><label htmlFor={idFor('name')} className="text-xs">Name</label><input id={idFor('name')} maxLength={120} className={inputClass} value={newName} onChange={(e) => setNewName(e.target.value)} /></div>
+ </div>
+ <label htmlFor={idFor('description')} className="block text-xs">Appearance / description</label><textarea id={idFor('description')} rows={2} maxLength={1000} className={inputClass} value={newDescription} onChange={(e) => setNewDescription(e.target.value)} />
+ <button type="button" className="text-port-accent text-sm min-h-[44px]" disabled={!newName.trim() || subjects.length >= 24} onClick={() => { add(newKind, newName, newDescription); setNewName(''); setNewDescription(''); }}>Add to production</button>
+ {(newName.trim() || newDescription.trim()) && <p className="text-xs text-port-text-muted">Add the new subject to the production before saving.</p>}
+ <div className="flex flex-wrap gap-3"><button type="button" onClick={save} disabled={loading || (!!universeId && !universe) || !!newName.trim() || !!newDescription.trim()} className="bg-port-accent text-white rounded px-3 py-2 text-sm disabled:opacity-50">{saving ? 'Saving…' : 'Save creative setup'}</button><button type="button" onClick={() => setEditing(false)} className="text-sm">Cancel</button></div>
+ </fieldset>}
+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}
+ </section>;
+}
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
new file mode 100644
index 0000000000..1eca0702ca
--- /dev/null
+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import CreativeSetupPanel from './CreativeSetupPanel.jsx';
+import { getUniverse } from '../../services/apiUniverseBuilder.js';
+vi.mock('../../services/apiUniverseBuilder.js', () => ({
+ listUniverseNames: vi.fn(async () => [{ id: 'u1', name: 'Example universe' }, { id: 'u2', name: 'Other universe' }]),
+ getUniverse: vi.fn(),
+}));
+vi.mock('../../services/apiMoodBoard.js', () => ({
+ listMoodBoards: vi.fn(async () => [{ id: 'b1', name: 'Painted style' }]),
+ getMoodBoard: vi.fn(async () => ({ name: 'Painted style', description: 'Watercolor', items: [{ type: 'text', text: 'Loose brush strokes' }] })),
+}));
+const project = { id: 'mv1', concept: {}, visualSpec: {} };
+const open = (onSave = vi.fn(async () => {})) => {
+ render(<MemoryRouter><CreativeSetupPanel project={project} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);
+ fireEvent.click(screen.getByText('Set up creative direction'));
+ return onSave;
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ getUniverse.mockResolvedValue({ id: 'u1', name: 'Example universe', styleNotes: 'Ink silhouettes', characters: [{ id: 'c1', name: 'Example singer', physicalDescription: 'Silver coat' }], places: [], objects: [] });
+});
+describe('creative setup', () => {
+ it('saves image-free canon, an authored prop and mood-board direction together', async () => {
+ const onSave = open();
+ await screen.findByText('Example universe');
+ fireEvent.change(screen.getByLabelText('Universe'), { target: { value: 'u1' } });
+ await screen.findByText('Example singer');
+ fireEvent.change(screen.getByLabelText('Select cast'), { target: { value: 'c1' } });
+ fireEvent.change(screen.getByLabelText('Role for Example singer'), { target: { value: 'band' } });
+ fireEvent.change(screen.getByLabelText('Create for this video'), { target: { value: 'object' } });
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Glass guitar' } });
+ fireEvent.change(screen.getByLabelText('Appearance / description'), { target: { value: 'Transparent blue glass' } });
+ fireEvent.click(screen.getByText('Add to production'));
+ fireEvent.click(screen.getByText('Mood board reference'));
+ await screen.findByText('Painted style');
+ fireEvent.change(screen.getByLabelText('Board'), { target: { value: 'b1' } });
+ fireEvent.click(screen.getByText('Save creative setup'));
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
+ expect(onSave.mock.calls[0][0]).toMatchObject({
+ concept: { universeId: 'u1', universeStyle: 'Example universe\nInk silhouettes', moodBoardStyle: expect.stringContaining('Loose brush strokes'), subjects: [
+ { kind: 'character', name: 'Example singer', role: 'band', description: 'Silver coat', canonId: 'c1' },
+ { kind: 'object', name: 'Glass guitar', description: 'Transparent blue glass' },
+ ] }, visualSpec: { moodBoardId: 'b1' },
+ });
+ });
+ it('ignores stale universe responses and retains the draft when saving fails', async () => {
+ let resolveOld;
+ getUniverse.mockImplementation((id) => id === 'u1' ? new Promise((resolve) => { resolveOld = resolve; }) : Promise.resolve({ id: 'u2', name: 'Other universe', characters: [] }));
+ open(vi.fn(async () => { throw new Error('Save rejected'); }));
+ await screen.findByText('Example universe');
+ fireEvent.change(screen.getByLabelText('Universe'), { target: { value: 'u1' } });
+ fireEvent.change(screen.getByLabelText('Universe'), { target: { value: 'u2' } });
+ await waitFor(() => expect(screen.queryByText('Loading canon…')).toBeNull());
+ resolveOld({ id: 'u1', characters: [{ id: 'c1', name: 'Stale singer' }] });
+ fireEvent.click(screen.getByText('Save creative setup'));
+ await screen.findByText('Save rejected');
+ expect(screen.queryByText('Stale singer')).toBeNull();
+ expect(screen.getByLabelText('Universe').value).toBe('u2');
+ });
+});
diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsx
index a8716d7c4a..2eca967986 100644
--- a/client/src/components/musicVideo/VisualSpecPanel.jsx
+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx
@@ -1,7 +1,6 @@
import { useRef, useState } from 'react';
import { ImagePlus, Trash2, Plus, Palette, Sparkles } from 'lucide-react';
import useFieldDraft from '../../hooks/useFieldDraft.js';
-import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';
import { MAX_CONDITIONING_REFERENCES } from '../../hooks/useMusicVideoSceneMedia.js';
import { getUniverse } from '../../services/apiUniverseBuilder.js';
import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';
@@ -189,11 +188,7 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {
</div>
</div>
- <MoodBoardReferenceStrip
- value={spec.moodBoardId || ''}
- onChange={(id) => onSave({ moodBoardId: id || null })}
- newBoardName={project.name}
- />
+
</div>
</details>
);
diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.js
index 92f71aeaf9..28b291300a 100644
--- a/client/src/hooks/useMusicVideoSceneMedia.js
+++ b/client/src/hooks/useMusicVideoSceneMedia.js
@@ -1,3 +1,4 @@
+import { musicVideoCreativeContext } from '../../../server/lib/musicVideoCreativeContext.js';
import toast from '../components/ui/Toast';
import { addMusicVideoSceneTake } from '../services/apiMusicVideo.js';
import { generateImage } from '../services/apiSystem.js';
@@ -106,7 +107,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS
const genVideoScenes = videoLane.genScenes;
const style = project?.concept?.style?.trim();
- const direction = visualDirection(project?.visualSpec);
+ const direction = [musicVideoCreativeContext(project?.concept), visualDirection(project?.visualSpec)].filter(Boolean).join('; ');
const conditioning = conditioningReferences(project?.visualSpec);
// The image prompt for a scene's reference frame: its frame prompt (or the
// shot prompt as a fallback) suffixed with the project's global concept style
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index cafb6e9127..46c5a3d151 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,3 +1,4 @@
+import CreativeSetupPanel from '../components/musicVideo/CreativeSetupPanel.jsx';
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router';
import { Plus, Film } from 'lucide-react';
@@ -82,6 +83,7 @@ export default function MusicVideo() {
const [loading, setLoading] = useState(true);
const [analyzing, setAnalyzing] = useState(false);
const [arranging, setArranging] = useState(false);
+ const [creativeSetupPending, setCreativeSetupPending] = useState(false);
const [planning, setPlanning] = useState(false);
const [cloning, setCloning] = useState(false);
const [importingLyrics, setImportingLyrics] = useState(false);
@@ -623,6 +625,11 @@ export default function MusicVideo() {
)}
{selected && (
<div className="space-y-3">
+ <CreativeSetupPanel key={`creative-${selected.id}`} project={selected} onPendingChange={setCreativeSetupPending}
+ onSave={(patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {
+ patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });
+ })} />
+ <fieldset disabled={creativeSetupPending} className="space-y-3 min-w-0">
<div className="bg-port-card border border-port-border rounded-lg p-3">
<ProjectToolbar
project={selected}
@@ -785,6 +792,7 @@ export default function MusicVideo() {
/>
))}
</div>
+ </fieldset>
</div>
)}
</div>
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 0a298a27a2..4bf13145b9 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -1455,6 +1455,20 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {
scenes: [{ sceneId: 's1', order: 0, prompt: 'waves', framePrompt: 'harbor at dawn', referenceImageId: null, videoHistoryId: null, takes: [] }],
};
+ it('carries authored character identity and source styles into actual frame requests', async () => {
+ await openProject({ ...SPEC_PROJECT, concept: { ...SPEC_PROJECT.concept,
+ universeStyle: 'Ink silhouettes', moodBoardStyle: 'Watercolor', subjects: [
+ { id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' },
+ ],
+ } });
+ fireEvent.click(screen.getByRole('button', { name: /^Generate frame$/ }));
+ await waitFor(() => expect(generateImage).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: expect.stringContaining('character (protagonist): Example singer — Silver coat'),
+ }), { silent: true }));
+ expect(generateImage.mock.calls[0][0].prompt).toContain('Mood board style: Watercolor');
+ expect(generateImage.mock.calls[0][0].prompt).toContain('Universe style: Ink silhouettes');
+ });
+
it('sends flagged references as conditioning inputs and names the capability gap when the backend refuses them', async () => {
generateImage.mockRejectedValueOnce(Object.assign(
new Error('Reference images are only supported for FLUX.2 and Qwen Image 2.1 models on the local backend'),
diff --git a/server/lib/README.md b/server/lib/README.md
index 25f03e20e9..6b59e82556 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -779,3 +779,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, worker process-group records, immutable recovery-dump and import receipts, durable forward-only stages through `verified`, per-pid target proofs from a restarted server, token-persisting same-operation recovery, and `releaseAdmission` (authority record, then completed archive); source-only cancellation archives an unowned accepted operation. |
| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |
+
+| `musicVideoCreativeContext.js` | `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
+| `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions and analyzed style for creative prompts. |
diff --git a/server/lib/index.js b/server/lib/index.js
index de0ab46550..1a8e5643e9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -761,3 +761,6 @@ export * from './databaseAuthority.js';
export * from './databaseMaintenanceJournal.js';
export * from './databaseWriterRegistry.js';
+
+export * from './musicVideoCreativeContext.js';
+export * from './moodBoardStyleContext.js';
diff --git a/server/lib/moodBoardStyleContext.js b/server/lib/moodBoardStyleContext.js
new file mode 100644
index 0000000000..94ff3f0d27
--- /dev/null
+++ b/server/lib/moodBoardStyleContext.js
@@ -0,0 +1,71 @@
+/**
+ * Mood board → style-relevant text context (pure).
+ *
+ * Shared by the style synthesis run (`moodBoardStyleSynthesis.js`) and Code
+ * Animation's art direction, and kept dependency-light so a caller that only
+ * needs the board's text fragments doesn't import the provider stack.
+ */
+
+import { trimTo } from './textUtils.js';
+
+// Context bounds: a board caps at 500 items, but the synthesis context must
+// stay well inside a chat-completion window. Items are taken in board order
+// (the user's curation order); fragments beyond either cap are dropped and
+// the count is reported in the result so the UI can say so. The aggregate
+// character budget is the load-bearing one — 60 items can each carry four
+// 600-char fields, far past what a small local model's window fits — and it
+// is a FIXED conservative budget (≈6k tokens) rather than model-aware:
+// provider window metadata isn't reliably known here, and a proposal
+// synthesized from the first N curated items beats a request the model
+// truncates or rejects.
+const CONTEXT_ITEMS_MAX = 60;
+const CONTEXT_FIELD_MAX = 600;
+const CONTEXT_TOTAL_CHARS_MAX = 24000;
+
+/**
+ * Reduce a board to the style-relevant text fragments the LLM sees. An item
+ * contributes only what it actually carries: a text note, a caption, and/or a
+ * persisted analysis (prompt + negative + rationale). Media items without any
+ * of those contribute nothing — synthesis reads text, not pixels (analyzing
+ * an item is Phase 3's explicit per-item vision step).
+ */
+export function collectBoardStyleContext(board) {
+ const items = Array.isArray(board?.items) ? board.items : [];
+ const fragments = [];
+ let dropped = 0;
+ let totalChars = 0;
+ for (const it of items) {
+ if (!it || typeof it !== 'object') continue;
+ const entry = {};
+ if (it.type === 'text' && typeof it.text === 'string' && it.text.trim()) {
+ entry.note = trimTo(it.text, CONTEXT_FIELD_MAX);
+ }
+ if (typeof it.caption === 'string' && it.caption.trim()) {
+ entry.caption = trimTo(it.caption, CONTEXT_FIELD_MAX);
+ }
+ const analysis = it.analysis;
+ if (analysis && typeof analysis === 'object' && typeof analysis.prompt === 'string' && analysis.prompt.trim()) {
+ entry.analyzedPrompt = trimTo(analysis.prompt, CONTEXT_FIELD_MAX);
+ if (typeof analysis.negativePrompt === 'string' && analysis.negativePrompt.trim()) {
+ entry.analyzedNegative = trimTo(analysis.negativePrompt, CONTEXT_FIELD_MAX);
+ }
+ if (typeof analysis.rationale === 'string' && analysis.rationale.trim()) {
+ entry.analysisRationale = trimTo(analysis.rationale, CONTEXT_FIELD_MAX);
+ }
+ }
+ if (!Object.keys(entry).length) continue;
+ const entrySize = Object.values(entry).reduce((sum, v) => sum + v.length, 0);
+ if (fragments.length >= CONTEXT_ITEMS_MAX || totalChars + entrySize > CONTEXT_TOTAL_CHARS_MAX) {
+ dropped += 1;
+ continue;
+ }
+ totalChars += entrySize;
+ fragments.push({ kind: it.type, ...entry });
+ }
+ return {
+ name: trimTo(board?.name, 200) || null,
+ description: trimTo(board?.description, 2000) || null,
+ items: fragments,
+ droppedItems: dropped,
+ };
+}
diff --git a/server/lib/musicVideoCreativeContext.js b/server/lib/musicVideoCreativeContext.js
new file mode 100644
index 0000000000..e26ccff0ba
--- /dev/null
+++ b/server/lib/musicVideoCreativeContext.js
@@ -0,0 +1,11 @@
+/** Shared creative bible for planning, local media generation and external handoff. */
+export function musicVideoCreativeContext(concept) {
+ if (!concept) return '';
+ const subjects = (concept.subjects || []).map((s) =>
+ `${s.kind}${s.kind === 'character' && s.role ? ` (${s.role})` : ''}: ${s.name}${s.description ? ` — ${s.description}` : ''}`);
+ return [
+ concept.universeStyle && `Universe style: ${concept.universeStyle}`,
+ concept.moodBoardStyle && `Mood board style: ${concept.moodBoardStyle}`,
+ subjects.length && `Production bible (use the subjects relevant to this shot; preserve their identity):\n${subjects.join('\n')}`,
+ ].filter(Boolean).join('\n');
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 2b519d0e64..3fe56eeb0f 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -25,6 +25,17 @@ export const musicVideoConceptSchema = z.object({
prompt: z.string().max(8000).optional(),
style: z.string().max(2000).optional(),
universeId: z.string().max(64).nullable().optional(),
+ // Authored snapshots keep the production stable when source canon changes.
+ universeStyle: z.string().max(4000).optional(),
+ moodBoardStyle: z.string().max(4000).optional(),
+ subjects: z.array(z.object({
+ id: z.string().min(1).max(64),
+ kind: z.enum(['character', 'place', 'object']),
+ name: z.string().trim().min(1).max(120),
+ description: z.string().max(1000).optional(),
+ role: z.enum(['protagonist', 'band', 'supporting']).optional(),
+ canonId: z.string().max(64).optional(),
+ }).strict()).max(24).optional(),
}).strict();
// Renderer settings travel with the project so reopening a director board (or
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 5c16b94445..2b9f23398c 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -602,7 +602,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// and submits performance scenes to a cutaway-only lane — edits that then win
// LWW onto the upgraded peer. Pre-#8977 records need no rewrite (absent
// `shotMode` = cutaway; takes without an instruction render as before).
- musicVideoProjects: 4,
+ // v5 = authored universe style and cast/place/object snapshots in concept.
+ // Older peers ignore these when generating, losing character continuity.
+ musicVideoProjects: 5,
// 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.test.js b/server/routes/musicVideo.test.js
index 6560ed8403..594f7fd5c2 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -159,6 +159,20 @@ describe('musicVideo routes', () => {
expect(svc.cloneProject).not.toHaveBeenCalled();
});
+ it('PATCH /:id validates an image-free production bible and bounds its subjects', async () => {
+ const concept = { universeId: 'u1', universeStyle: 'Ink silhouettes', moodBoardStyle: 'Watercolor', subjects: [
+ { id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' },
+ { id: 'place', kind: 'place', name: 'Example stage' },
+ ] };
+ const saved = await request(app).patch('/api/music-video/mv-1').send({ concept });
+ expect(saved.status).toBe(200);
+ expect(saved.body.concept).toEqual(concept);
+ const rejected = await request(app).patch('/api/music-video/mv-1').send({ concept: { subjects: Array(25).fill(concept.subjects[0]) } });
+ expect(rejected.status).toBe(400);
+ const invalidKind = await request(app).patch('/api/music-video/mv-1').send({ concept: { subjects: [{ ...concept.subjects[0], kind: 'unknown' }] } });
+ expect(invalidKind.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);
diff --git a/server/routes/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.js
index c987c858e4..033bc9e6f3 100644
--- a/server/routes/musicVideoTreatment.test.js
+++ b/server/routes/musicVideoTreatment.test.js
@@ -197,6 +197,21 @@ describe('treatment compile', () => {
expect(res.body.treatment.arc.beats).toHaveLength(5);
});
+ it('uses the saved cast and rejects a compile that raced a recast', async () => {
+ const project = await plannedProject();
+ await projects.updateProject(project.id, { concept: { universeStyle: 'Ink silhouettes', subjects: [
+ { id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' },
+ ] } });
+ runPromptThroughProvider.mockImplementationOnce(async ({ prompt }) => {
+ expect(prompt).toContain('character (protagonist): Example singer — Silver coat');
+ await projects.updateProject(project.id, { concept: { subjects: [] } });
+ return { text: '{}' };
+ });
+ const res = await compile(project.id, { baseRevision: 0 });
+ expect(res.status).toBe(409);
+ expect((await reload(project.id)).concept.subjects).toEqual([]);
+ });
+
it('refuses a compile whose provider call raced a brief edit, keeping the edit', async () => {
const project = await plannedProject();
runPromptThroughProvider.mockImplementationOnce(async () => {
diff --git a/server/services/moodBoard/styleContext.js b/server/services/moodBoard/styleContext.js
index dcf15e2a28..8955384f8d 100644
--- a/server/services/moodBoard/styleContext.js
+++ b/server/services/moodBoard/styleContext.js
@@ -1,71 +1,2 @@
-/**
- * Mood board → style-relevant text context (pure).
- *
- * Shared by the style synthesis run (`moodBoardStyleSynthesis.js`) and Code
- * Animation's art direction, and kept dependency-light so a caller that only
- * needs the board's text fragments doesn't import the provider stack.
- */
-
-import { trimTo } from '../../lib/textUtils.js';
-
-// Context bounds: a board caps at 500 items, but the synthesis context must
-// stay well inside a chat-completion window. Items are taken in board order
-// (the user's curation order); fragments beyond either cap are dropped and
-// the count is reported in the result so the UI can say so. The aggregate
-// character budget is the load-bearing one — 60 items can each carry four
-// 600-char fields, far past what a small local model's window fits — and it
-// is a FIXED conservative budget (≈6k tokens) rather than model-aware:
-// provider window metadata isn't reliably known here, and a proposal
-// synthesized from the first N curated items beats a request the model
-// truncates or rejects.
-const CONTEXT_ITEMS_MAX = 60;
-const CONTEXT_FIELD_MAX = 600;
-const CONTEXT_TOTAL_CHARS_MAX = 24000;
-
-/**
- * Reduce a board to the style-relevant text fragments the LLM sees. An item
- * contributes only what it actually carries: a text note, a caption, and/or a
- * persisted analysis (prompt + negative + rationale). Media items without any
- * of those contribute nothing — synthesis reads text, not pixels (analyzing
- * an item is Phase 3's explicit per-item vision step).
- */
-export function collectBoardStyleContext(board) {
- const items = Array.isArray(board?.items) ? board.items : [];
- const fragments = [];
- let dropped = 0;
- let totalChars = 0;
- for (const it of items) {
- if (!it || typeof it !== 'object') continue;
- const entry = {};
- if (it.type === 'text' && typeof it.text === 'string' && it.text.trim()) {
- entry.note = trimTo(it.text, CONTEXT_FIELD_MAX);
- }
- if (typeof it.caption === 'string' && it.caption.trim()) {
- entry.caption = trimTo(it.caption, CONTEXT_FIELD_MAX);
- }
- const analysis = it.analysis;
- if (analysis && typeof analysis === 'object' && typeof analysis.prompt === 'string' && analysis.prompt.trim()) {
- entry.analyzedPrompt = trimTo(analysis.prompt, CONTEXT_FIELD_MAX);
- if (typeof analysis.negativePrompt === 'string' && analysis.negativePrompt.trim()) {
- entry.analyzedNegative = trimTo(analysis.negativePrompt, CONTEXT_FIELD_MAX);
- }
- if (typeof analysis.rationale === 'string' && analysis.rationale.trim()) {
- entry.analysisRationale = trimTo(analysis.rationale, CONTEXT_FIELD_MAX);
- }
- }
- if (!Object.keys(entry).length) continue;
- const entrySize = Object.values(entry).reduce((sum, v) => sum + v.length, 0);
- if (fragments.length >= CONTEXT_ITEMS_MAX || totalChars + entrySize > CONTEXT_TOTAL_CHARS_MAX) {
- dropped += 1;
- continue;
- }
- totalChars += entrySize;
- fragments.push({ kind: it.type, ...entry });
- }
- return {
- name: trimTo(board?.name, 200) || null,
- description: trimTo(board?.description, 2000) || null,
- items: fragments,
- droppedItems: dropped,
- };
-}
+// Compatibility entrypoint; pure context is shared with creative setup clients.
+export { collectBoardStyleContext } from '../../lib/moodBoardStyleContext.js';
diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.js
index de541b5eae..6a98686f62 100644
--- a/server/services/musicVideo/handoff.js
+++ b/server/services/musicVideo/handoff.js
@@ -1,3 +1,4 @@
+import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
/**
* Music Video external-asset handoff (#8965) — provider-neutral export/import
* for tools PortOS does not drive, such as Midjourney.
@@ -85,6 +86,7 @@ function composePrompt(primary, fallback, project, clause) {
return [
primary?.trim() || fallback?.trim() || '',
project.concept?.style?.trim() || '',
+ musicVideoCreativeContext(project.concept),
visualDirection(project.visualSpec),
clause?.trim() || '',
].filter(Boolean).join(', ');
@@ -110,7 +112,7 @@ export function buildHandoffManifest(project, { now = new Date().toISOString() }
exportedAt: now,
project: { id: project.id, name: project.name, version: project.version || 1 },
instructions: 'Generate each scene in your external tool, keep the scene file tag (for example S03-1a2b3c4d) in every downloaded filename, then import the files on the Music Video board. PortOS never contacts the external service; attach the reference files yourself.',
- concept: { prompt: project.concept?.prompt || '', style: project.concept?.style || '' },
+ concept: { prompt: project.concept?.prompt || '', style: project.concept?.style || '', universeStyle: project.concept?.universeStyle || '', moodBoardStyle: project.concept?.moodBoardStyle || '', subjects: project.concept?.subjects || [] },
visualSpec: {
palette: spec?.palette || [],
typography: spec?.typography || '',
diff --git a/server/services/musicVideo/handoff.test.js b/server/services/musicVideo/handoff.test.js
index 18366f5062..12563dd0fe 100644
--- a/server/services/musicVideo/handoff.test.js
+++ b/server/services/musicVideo/handoff.test.js
@@ -110,3 +110,20 @@ describe('buildHandoffManifest typography (#8992)', () => {
expect(manifest.scenes[0].shotPrompt).not.toMatch(/typography/i);
});
});
+
+ it('preserves the authored bible through save, partial edit, clone and handoff', async () => {
+ const concept = { universeId: 'u1', universeStyle: 'Ink silhouettes', moodBoardStyle: 'Watercolor', subjects: [
+ { id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' },
+ ] };
+ const p = await projects.createProject({ name: 'Example production', concept });
+ await projects.updateProject(p.id, { concept: { style: 'Monochrome' } });
+ const saved = await projects.getProject(p.id);
+ expect(saved.concept).toEqual({ ...concept, style: 'Monochrome' });
+ const clone = await projects.cloneProject(p.id, {});
+ expect(clone.concept).toEqual(saved.concept);
+ await projects.addProjectScene(p.id, { framePrompt: 'A close-up', prompt: 'Slow push in' });
+ const manifest = buildHandoffManifest(await projects.getProject(p.id));
+ expect(manifest.concept.subjects).toEqual(concept.subjects);
+ expect(manifest.scenes[0].framePrompt).toContain('Example singer — Silver coat');
+ expect(manifest.scenes[0].shotPrompt).toContain('Mood board style: Watercolor');
+ });
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 8cb1d31f69..f1bfa81a83 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -1,3 +1,4 @@
+import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
/**
* Music Video — autonomous shot planner (#1855; multi-shot + lyrics #8964).
*
@@ -123,6 +124,7 @@ export function buildScenePlanPrompt(project, shots) {
return `You are directing a music video for "${project.name}".
${conceptLine}
${styleLine}
+${musicVideoCreativeContext(concept)}
${briefLines}
The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent):
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index 3a2d981d34..28e1ebce0c 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -218,7 +218,13 @@ describe('buildScenePlanPrompt', () => {
lyricCues: [{ text: 'we run the night', startSec: 10, endSec: 14 }],
phrases: [{ label: 'Lift', startSec: 18, endSec: 30, intent: 'the city falls away' }],
});
- const prompt = buildScenePlanPrompt(makeProject(), shots);
+ const prompt = buildScenePlanPrompt(makeProject({ concept: {
+ prompt: 'cyberpunk chase', style: 'neon, rain-slicked streets', universeStyle: 'Ink silhouettes', moodBoardStyle: 'Watercolor',
+ subjects: [{ id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' }],
+ } }), shots);
+ expect(prompt).toContain('Universe style: Ink silhouettes');
+ expect(prompt).toContain('Mood board style: Watercolor');
+ expect(prompt).toContain('character (protagonist): Example singer — Silver coat');
expect(prompt).toContain('Neon Nights');
expect(prompt).toContain('cyberpunk chase');
expect(prompt).toContain('neon, rain-slicked streets');
diff --git a/server/services/musicVideo/treatment.js b/server/services/musicVideo/treatment.js
index cd13fc299e..60b61a8bff 100644
--- a/server/services/musicVideo/treatment.js
+++ b/server/services/musicVideo/treatment.js
@@ -316,10 +316,10 @@ export function treatmentBasis(project) {
analysis: fingerprint(analysis
? [analysis.durationSec ?? null, (analysis.sections || []).map((s) => [s?.startSec ?? null, s?.endSec ?? null, s?.energy ?? null])]
: null),
- visualSpec: fingerprint(spec ? [
+ visualSpec: fingerprint([project?.concept || null, spec ? [
(spec.references || []).map((r) => [r.imageId, r.role || 'mood', r.use || 'reference', r.label || '', r.note || '']),
spec.palette || [], spec.typography || '', spec.cameraRules || '',
- ] : null),
+ ] : null]),
lyrics: fingerprint((project?.lyricCues || []).map((c) => [c.text, c.startSec ?? null, c.endSec ?? null])),
scenes: fingerprint((project?.scenes || []).map((s) => [s.sceneId, s.startSec ?? null, s.endSec ?? null])),
};
diff --git a/server/services/musicVideo/treatmentDraft.js b/server/services/musicVideo/treatmentDraft.js
index 327dbaa30c..7879cd0e3e 100644
--- a/server/services/musicVideo/treatmentDraft.js
+++ b/server/services/musicVideo/treatmentDraft.js
@@ -1,3 +1,4 @@
+import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
/**
* Music Video — treatment compiler (#8980).
*
@@ -98,6 +99,9 @@ function deriveMotifs(project, brief) {
const fromBrief = (brief.mustHave || '').split(/[\n;,]+/).map((s) => s.trim()).filter(Boolean).slice(0, 3)
.map((name) => ({ name: name.slice(0, 120), description: 'A must-have from the brief.', evolution, rationale: `A recurring image ${audience} can track across the song.` }));
if (fromBrief.length > 0) return fromBrief;
+ const subjects = (project.concept?.subjects || []).slice(0, 3)
+ .map((subject) => ({ name: subject.name, description: subject.description || `The selected ${subject.kind}.`, evolution, rationale: `Preserves the production's cast and recurring subjects for ${audience}.` }));
+ if (subjects.length > 0) return subjects;
const refs = (project.visualSpec?.references || [])
.filter((r) => ['character', 'prop', 'set'].includes(r.role) && isNonBlankStr(r.label)).slice(0, 3)
.map((r) => ({ name: r.label.trim().slice(0, 120), description: `The ${r.role} reference "${r.label.trim()}".`, evolution, rationale: `Anchors identity continuity for ${audience}.` }));
@@ -141,7 +145,8 @@ const FRAMINGS = ['wide establishing', 'medium', 'close-up'];
function focalFor(mode, project, motifs) {
const character = (project.visualSpec?.references || []).find((r) => r.role === 'character' && isNonBlankStr(r.label));
- if (mode === 'performance') return character ? character.label.trim() : 'the performer';
+ const lead = (project.concept?.subjects || []).find((s) => s.kind === 'character' && ['protagonist', 'band'].includes(s.role));
+ if (mode === 'performance') return lead?.name || (character ? character.label.trim() : 'the performer');
if (mode === 'graphic') return 'a bold graphic composition';
return motifs[0]?.name || 'the recurring motif';
}
@@ -359,6 +364,7 @@ export function buildTreatmentPrompt(project, draft) {
brief.hookObjective && `Opening hook objective: ${quote(brief.hookObjective)}`,
brief.mustHave && `Must have: ${quote(brief.mustHave, 400)}`,
brief.avoid && `Avoid: ${quote(brief.avoid, 400)}`,
+ musicVideoCreativeContext(concept),
concept.prompt && `Concept: ${quote(concept.prompt, 600)}`,
concept.style && `Visual style: ${quote(concept.style)}`,
spec.palette?.length && `Palette: ${spec.palette.join(' ')}`,