Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: bind Music Video narrative graphics to musical events (#9352)
Adam Eivycebad2e213e3
diff --git a/client/src/components/musicVideo/BeatTimeline.jsx b/client/src/components/musicVideo/BeatTimeline.jsxindex 2b677e962d..880e808dbd 100644--- a/client/src/components/musicVideo/BeatTimeline.jsx+++ b/client/src/components/musicVideo/BeatTimeline.jsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { buildBeatGridPoints, computeDragSpan, computeSceneSpans, shouldMarkBeatAligned } from '../../lib/beatGrid.js';import { formatTimecode } from '../../utils/formatters.js';+import { resolveNarrativeEvents } from '../../lib/musicVideoNarrativeEvents.js';// Beat-quantized timeline arranger for a music-video project's scene board// (#1854). Renders a beat-grid overlay (section bands, beat/downbeat ticks)@@ -34,7 +35,20 @@ function lyricSpans(cues) {});}-export default function BeatTimeline({ audioAnalysis, scenes, lyricCues, onCommit }) {+export default function BeatTimeline({ audioAnalysis, scenes, lyricCues, narrativeEvents = [], onSeek, onCommit }) {+ const narrative = useMemo(() => resolveNarrativeEvents({ audioAnalysis, lyricCues, composition: { narrativeEvents } }, []), [audioAnalysis, lyricCues, narrativeEvents]);+ const eventLane = useMemo(() => {+ const ends = [];+ const events = narrative.events.map((event) => {+ const left = event.startSec * PX_PER_SEC;+ const width = Math.max(44, (event.endSec - event.startSec) * PX_PER_SEC);+ let row = ends.findIndex((end) => end + 4 <= left);+ if (row < 0) row = ends.length;+ ends[row] = left + width;+ return { ...event, left, width, row };+ });+ return { events, rows: ends.length };+ }, [narrative]);const gridPoints = useMemo(() => buildBeatGridPoints(audioAnalysis), [audioAnalysis]);const baseSpans = useMemo(() => computeSceneSpans(scenes, audioAnalysis?.durationSec),@@ -200,7 +214,7 @@ export default function BeatTimeline({ audioAnalysis, scenes, lyricCues, onCommi</div><div ref={scrollRef} className="overflow-x-auto border border-port-border rounded-lg bg-port-bg">- <div className={`relative ${cueSpans.length > 0 ? 'h-44' : 'h-36'}`} style={{ width: `${widthPx}px`, touchAction: 'none' }}>+ <div className="relative" style={{ width: `${widthPx}px`, height: eventLane.rows ? 179 + eventLane.rows * 26 : cueSpans.length ? 176 : 144, touchAction: 'none' }}>{(audioAnalysis.sections || []).map((section, i) => (<div key={`sec-${i}`}className="absolute top-0 h-6 border-r border-port-border/60 overflow-hidden"@@ -266,8 +280,17 @@ export default function BeatTimeline({ audioAnalysis, scenes, lyricCues, onCommi{cue.text}</div>))}+ {eventLane.events.map((event) => <button key={event.id} type="button"+ className="absolute h-5 overflow-hidden rounded border border-port-accent bg-port-card px-1 text-left text-[10px] text-port-text"+ style={{ left: event.left, top: 175 + event.row * 26, width: event.width }}+ title={`${event.kind}: ${event.narrativeFunction} · ${event.mediumRationale}`}+ aria-label={`Seek event ${event.name} at frame ${event.startFrame}`} onClick={() => onSeek?.(event.startSec)}>+ {event.name} · {event.kind}+ </button>)}</div></div>+ {narrative.events.length > 0 && <p className="text-xs text-port-text-muted">Narrative event lane · click an event to seek its resolved song frame.</p>}+ {narrative.unresolved.length > 0 && <p role="status" className="text-xs text-port-warning">Rebind {narrative.unresolved.length} unresolved narrative events in Compose.</p>}</div>);}diff --git a/client/src/components/musicVideo/BeatTimeline.test.jsx b/client/src/components/musicVideo/BeatTimeline.test.jsxnew file mode 100644index 0000000000..221657c25e--- /dev/null+++ b/client/src/components/musicVideo/BeatTimeline.test.jsx@@ -0,0 +1,19 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import BeatTimeline from './BeatTimeline.jsx';++describe('narrative event lane', () => {+ it('seeks the resolved onset frame, displays unresolved bindings, and never commits scene edits', () => {+ const onSeek = vi.fn(); const onCommit = vi.fn();+ const base = { name: 'Impact', kind: 'impact', durationSec: 1, narrativeFunction: 'Mark a turn', mediumRationale: 'Exact graphic' };+ render(<BeatTimeline audioAnalysis={{ durationSec: 5, features: { onsets: { low: [0.51] } } }}+ scenes={[{ sceneId: 's1', startSec: 0, endSec: 5 }]} narrativeEvents={[+ { ...base, id: 'hit', anchor: { kind: 'onset', band: 'low', index: 0 } },+ { ...base, id: 'lost', anchor: null },+ ]} onSeek={onSeek} onCommit={onCommit} />);+ fireEvent.click(screen.getByRole('button', { name: 'Seek event Impact at frame 13' }));+ expect(onSeek).toHaveBeenCalledWith(13 / 24);+ expect(onCommit).not.toHaveBeenCalled();+ expect(screen.getByRole('status').textContent).toContain('1 unresolved');+ });+});diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.jsxindex 82e9e97616..a67334c998 100644--- a/client/src/components/musicVideo/DocumentCompositionPanel.jsx+++ b/client/src/components/musicVideo/DocumentCompositionPanel.jsx@@ -5,6 +5,7 @@ import toast from '../ui/Toast';import useProviderModels from '../../hooks/useProviderModels.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';import CompositionPreviewPlayer from './CompositionPreviewPlayer.jsx';+import NarrativeEventsEditor from './NarrativeEventsEditor.jsx';import { downloadBlob } from '../../lib/downloadBlob';import { formatBytes, timeAgo } from '../../utils/formatters.js';import { compositionDraft } from './compositionDraft.js';@@ -12,6 +13,7 @@ import {detachMusicVideoCompositionDocument, getMusicVideoCompositionDocument, getMusicVideoCompositionExport,importMusicVideoCompositionDirectory, importMusicVideoCompositionZip, startMusicVideoCompositionTemplate,generateMusicVideoMixedMediaDocument, regenerateMusicVideoMixedMediaSection,+ reviseMusicVideoMixedMediaEvents, updateMusicVideoProject,getMusicVideoMixedMediaCandidate, acceptMusicVideoMixedMediaDocument, discardMusicVideoMixedMediaDocument,} from '../../services/apiMusicVideo.js';@@ -130,6 +132,7 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,const [folder, setFolder] = useState('');const [candidate, setCandidate] = useState(null);const [selectedSection, setSelectedSection] = useState('');+ const [eventPending, setEventPending] = useState(false);const {providers, selectedProviderId, selectedModel, availableModels, selectedProvider,setSelectedProviderId, setSelectedModel,@@ -176,6 +179,12 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,{ ...provider, expectedDraft: candidate?.source?.directory }, { silent: true }), 'New candidate ready to review');const accept = () => run('accept', () => acceptMusicVideoMixedMediaDocument(project.id, candidate?.candidate?.directory, { silent: true }), 'Candidate selected for rendering');const discard = () => run('discard', () => discardMusicVideoMixedMediaDocument(project.id, candidate?.candidate?.directory, { silent: true }), 'Candidate discarded');+ const saveEvents = (events) => run('events', async () => ({ project: await updateMusicVideoProject(project.id,+ { composition: compositionDraft(project, events) }, { silent: true }) }), 'Event bindings saved');+ const reviseEvents = () => run('event-revision', () => reviseMusicVideoMixedMediaEvents(project.id,+ { ...provider, expectedDraft: candidate?.source?.directory }, { silent: true }), 'Affected sections revised; selected footage retained');+ const compareSection = candidate?.sections?.find((section) => section.id === selectedSection);+ const comparisonSeek = compareSection ? { t: compareSection.startSec, n: compareSection.startSec + 1 } : null;return (<section className="mt-3 space-y-2 rounded-lg border border-port-border bg-port-bg p-2" aria-label="Composition document">@@ -217,6 +226,8 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,</button></div><div className="space-y-2 rounded border border-port-border p-2">+ <NarrativeEventsEditor key={`${project.id}-${JSON.stringify([project.composition?.narrativeEvents, project.composition?.reactiveSections])}`}+ project={project} sections={candidate?.sections || []} disabled={!!busy} onSave={saveEvents} onPendingChange={setEventPending} /><p className="text-xs text-port-text-muted">Generate from the approved treatment, song timing and selected project assets. Missing media is reported before any provider call.</p>{providers.length > 0 && <ProviderModelSelectorproviders={providers} selectedProviderId={selectedProviderId} selectedModel={selectedModel}@@ -226,7 +237,7 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,/>}<p className="text-xs text-port-text-muted">Code authoring uses {selectedProvider?.name || selectedProviderId || 'no provider selected'} / {effectiveModel || 'no model selected'}. Nothing is sent until you click.</p><div className="flex flex-wrap items-end gap-2">- <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || !selectedProviderId || !effectiveModel} onClick={generate}>+ <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || eventPending || !selectedProviderId || !effectiveModel} onClick={generate}><Film size={14} /> {busy === 'generate' ? 'Generating…' : 'Generate mixed-media composition'}</button>{candidate?.source && <>@@ -237,19 +248,28 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,{candidate.sections.map((section) => <option key={section.id} value={section.id}>{section.label || section.id} · {section.startSec}s</option>)}</select></div>- <button type="button" className={buttonCls} disabled={!!busy || !selectedSectionValid || candidate.stale || !selectedProviderId || !effectiveModel} onClick={regenerate}>+ <button type="button" className={buttonCls} disabled={!!busy || eventPending || !selectedSectionValid || candidate.stale || !selectedProviderId || !effectiveModel} onClick={regenerate}><RotateCcw size={14} /> {busy === 'regenerate' ? 'Regenerating…' : 'Regenerate section'}</button>+ <button type="button" className={buttonCls} disabled={!!busy || eventPending || !candidate.eventRevisionAvailable || !selectedProviderId || !effectiveModel} onClick={reviseEvents}>+ {busy === 'event-revision' ? 'Revising events…' : 'Revise events only'}+ </button></>}{candidate?.candidate && <>- <button type="button" className={buttonCls} disabled={!!busy || candidate.stale} onClick={accept}>Accept reviewed version</button>+ <button type="button" className={buttonCls} disabled={!!busy || eventPending || candidate.stale} onClick={accept}>Accept reviewed version</button><button type="button" className={buttonCls} disabled={!!busy} onClick={discard}>Discard candidate</button></>}</div>- {candidate?.stale && <p className="text-xs text-port-warning" role="status">The treatment, song or selected assets changed. Generate a fresh candidate.</p>}+ {candidate?.stale && <p className="text-xs text-port-warning" role="status">{candidate.eventRevisionAvailable ? 'Event bindings changed. Revise events only to retain selected footage.' : 'The treatment, song or selected assets changed. Generate a fresh candidate.'}</p>}{candidate?.candidate && <div className="rounded border border-port-border p-2"><p className="mb-2 text-xs text-port-text-muted">Candidate preview · {candidate.providerId || 'provider'} / {candidate.model || 'default model'} · active document stays selected until accepted</p>- <CompositionPreviewPlayer project={project} audioUrl={audioUrl} draft />+ <div className="grid grid-cols-1 gap-2 xl:grid-cols-2">+ {doc?.source?.kind === 'generated' && <div><p className="text-xs text-port-text-muted">Before · accepted section</p><CompositionPreviewPlayer project={project} audioUrl={audioUrl} seekRequest={comparisonSeek} /></div>}+ <div><p className="text-xs text-port-text-muted">After · candidate section</p><CompositionPreviewPlayer project={project} audioUrl={audioUrl} seekRequest={comparisonSeek} draft /></div>+ </div>+ {(candidate.comparisons || []).filter((entry) => !selectedSection || entry.sectionId === selectedSection).map((entry) => <p key={entry.sectionId} className="mt-2 text-xs text-port-text-muted">+ {entry.sectionId}: before {entry.before.map((event) => `${event.name} @ frame ${event.startFrame}`).join(', ') || 'no events'}; after {entry.after.map((event) => `${event.name} @ frame ${event.startFrame}`).join(', ') || 'no events'}+ </p>)}</div>}</div><OverlayEditor key={`${project.id}-${project.composition?.overlay ? 'hud' : 'none'}`} project={project} onSave={onSave} />diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsxindex d37af8a291..b9b23d28d5 100644--- a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx+++ b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx@@ -13,6 +13,8 @@ const api = vi.hoisted(() => ({regenerateMusicVideoMixedMediaSection: vi.fn(),acceptMusicVideoMixedMediaDocument: vi.fn(),discardMusicVideoMixedMediaDocument: vi.fn(),+ reviseMusicVideoMixedMediaEvents: vi.fn(),+ updateMusicVideoProject: vi.fn(),}));vi.mock('../../services/apiMusicVideo.js', () => api);vi.mock('../../hooks/useProviderModels.js', () => ({ default: () => ({@@ -39,6 +41,34 @@ beforeEach(() => {});describe('DocumentCompositionPanel', () => {+ it('gates authoring on saved event bindings and sends an event-only revision against the reviewed document', async () => {+ api.getMusicVideoMixedMediaCandidate.mockResolvedValue({ candidate: generated, source: generated, stale: true, eventRevisionAvailable: true,+ sections: [{ id: 'verse', label: 'Verse', startSec: 0, endSec: 10 }] });+ let finishSave;+ api.updateMusicVideoProject.mockImplementation(() => new Promise((resolve) => { finishSave = resolve; }));+ const onProject = vi.fn();+ const { rerender } = render(<DocumentCompositionPanel project={withCandidate} onProject={onProject} onSave={vi.fn()} />);+ const revise = await screen.findByRole('button', { name: 'Revise events only' });+ await waitFor(() => expect(revise.disabled).toBe(false));+ fireEvent.click(screen.getByRole('button', { name: 'Add narrative event' }));+ expect(screen.getByRole('button', { name: /Generate mixed-media/ }).disabled).toBe(true);+ expect(revise.disabled).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Save event bindings' }));+ await waitFor(() => expect(api.updateMusicVideoProject).toHaveBeenCalledTimes(1));+ const saved = { ...withCandidate, updatedAt: '2026-01-02', composition: api.updateMusicVideoProject.mock.calls[0][1].composition };+ expect(saved.composition.narrativeEvents[0]).toMatchObject({ kind: 'reveal', anchor: { kind: 'time', atSec: 0 } });+ expect(revise.disabled).toBe(true);+ finishSave(saved);+ await waitFor(() => expect(onProject).toHaveBeenCalledWith(saved));+ rerender(<DocumentCompositionPanel project={saved} onProject={onProject} onSave={vi.fn()} />);+ await waitFor(() => expect(screen.getByRole('button', { name: 'Revise events only' }).disabled).toBe(false));+ fireEvent.click(screen.getByRole('button', { name: 'Revise events only' }));+ await waitFor(() => expect(api.reviseMusicVideoMixedMediaEvents).toHaveBeenCalledWith('mv-1', {+ providerId: 'stub-provider', model: 'fixture-model', expectedDraft: generated.directory,+ }, { silent: true }));+ expect(api.generateMusicVideoMixedMediaDocument).not.toHaveBeenCalled();+ });+it('starts from the template in one click when nothing is attached', async () => {const onProject = vi.fn();render(<DocumentCompositionPanel project={bare} onProject={onProject} onSave={vi.fn()} />);diff --git a/client/src/components/musicVideo/NarrativeEventsEditor.jsx b/client/src/components/musicVideo/NarrativeEventsEditor.jsxnew file mode 100644index 0000000000..fdc60db04c--- /dev/null+++ b/client/src/components/musicVideo/NarrativeEventsEditor.jsx@@ -0,0 +1,98 @@+import { useEffect, useState } from 'react';+import { NARRATIVE_EVENT_KINDS } from '../../lib/musicVideoNarrativeEvents.js';+import { uuidv4 } from '../../lib/uuid.js';++const inputCls = 'w-full min-w-0 rounded border border-port-border bg-port-bg px-2 py-1 text-xs';++/** Explicit saved event bindings; provider actions wait for this draft. */+export default function NarrativeEventsEditor({ project, sections = [], disabled, onSave, onPendingChange }) {+ const [events, setEvents] = useState(project.composition?.narrativeEvents || []);+ const [reactiveSections, setReactiveSections] = useState(project.composition?.reactiveSections || []);+ const dirty = JSON.stringify({ events, reactiveSections }) !== JSON.stringify({+ events: project.composition?.narrativeEvents || [], reactiveSections: project.composition?.reactiveSections || [],+ });+ useEffect(() => { onPendingChange(dirty); }, [dirty, onPendingChange]);+ const edit = (id, patch) => setEvents((events) => events.map((event) => event.id === id ? { ...event, ...patch } : event));+ const add = () => setEvents((events) => [...events, {+ id: `mne-${uuidv4()}`, name: 'New reveal', kind: 'reveal', anchor: { kind: 'time', atSec: 0 }, durationSec: 1,+ narrativeFunction: 'Introduce the next narrative beat', mediumRationale: 'Exact graphics use code over selected media',+ }]);+ const words = (project.lyricCues || []).flatMap((cue) => (cue.words || []).map((word, wordIndex) => ({+ cueId: cue.id, wordIndex, label: `${word.w || word.text} · ${word.startSec}s`,+ })));+ return <details className="rounded border border-port-border p-2 text-xs">+ <summary className="cursor-pointer py-2">Narrative events and section reactivity</summary>+ <form className="space-y-3" onSubmit={(event) => { event.preventDefault(); onSave({ narrativeEvents: events, reactiveSections }); }}>+ <fieldset disabled={disabled} className="space-y-3">+ <p className="text-port-text-muted">Bind exact graphics to a song time, measured onset, or aligned word. Silence holds the picture. Save, then revise events to retain accepted footage.</p>+ {events.map((event) => {+ const prefix = `mv-event-${event.id}`;+ const field = (key, label, numeric = false) => <div key={key}>+ <label htmlFor={`${prefix}-${key}`}>{label}</label>+ <input id={`${prefix}-${key}`} className={inputCls} type={numeric ? 'number' : 'text'}+ required={['name', 'narrativeFunction', 'mediumRationale', 'durationSec'].includes(key)}+ maxLength={key === 'text' ? 500 : key === 'narrativeFunction' || key === 'mediumRationale' ? 1000 : 120}+ min={key === 'durationSec' ? 0.042 : numeric ? -1000000 : undefined} max={key === 'durationSec' ? 900 : numeric ? 1000000 : undefined}+ step={numeric ? 'any' : undefined} value={event[key] ?? ''}+ onChange={(e) => edit(event.id, { [key]: numeric ? Number(e.target.value) : e.target.value })} />+ </div>;+ return <div key={event.id} className="space-y-2 rounded border border-port-border p-2">+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {field('name', 'Event name')}+ <div><label htmlFor={`${prefix}-kind`}>Graphic action</label>+ <select id={`${prefix}-kind`} className={inputCls} value={event.kind} onChange={(e) => edit(event.id, { kind: e.target.value })}>+ {NARRATIVE_EVENT_KINDS.map((kind) => <option key={kind}>{kind}</option>)}+ </select></div>+ <div><label htmlFor={`${prefix}-anchor`}>Timing source</label>+ <select id={`${prefix}-anchor`} className={inputCls} value={event.anchor?.kind || ''} onChange={(e) => {+ const kind = e.target.value;+ edit(event.id, { anchor: kind === 'time' ? { kind, atSec: 0 } : kind === 'onset' ? { kind, band: 'low', index: 0 }+ : words.length ? { kind, cueId: words[0].cueId, wordIndex: words[0].wordIndex } : null });+ }}>+ <option value="" disabled>Rebind after song change</option><option value="time">Song time</option>+ <option value="onset">Band onset</option><option value="word" disabled={!words.length}>Aligned word</option>+ </select></div>+ {event.anchor?.kind === 'time' && <div><label htmlFor={`${prefix}-time`}>Song seconds</label>+ <input id={`${prefix}-time`} className={inputCls} type="number" min="0" max="36000" step="any" required value={event.anchor.atSec}+ onChange={(e) => edit(event.id, { anchor: { ...event.anchor, atSec: Number(e.target.value) } })} /></div>}+ {event.anchor?.kind === 'onset' && <>+ <div><label htmlFor={`${prefix}-band`}>Onset band</label><select id={`${prefix}-band`} className={inputCls} value={event.anchor.band}+ onChange={(e) => edit(event.id, { anchor: { ...event.anchor, band: e.target.value } })}>+ {['low', 'mid', 'high'].map((band) => <option key={band}>{band}</option>)}</select></div>+ <div><label htmlFor={`${prefix}-index`}>Onset index (from 0)</label><input id={`${prefix}-index`} className={inputCls} type="number" min="0" max="100000" required value={event.anchor.index}+ onChange={(e) => edit(event.id, { anchor: { ...event.anchor, index: Number(e.target.value) } })} /></div>+ </>}+ {event.anchor?.kind === 'word' && <div><label htmlFor={`${prefix}-word`}>Aligned word</label><select id={`${prefix}-word`} className={inputCls}+ value={JSON.stringify([event.anchor.cueId, event.anchor.wordIndex])} onChange={(e) => {+ const [cueId, wordIndex] = JSON.parse(e.target.value); edit(event.id, { anchor: { ...event.anchor, cueId, wordIndex } });+ }}>+ {words.map((word) => <option key={`${word.cueId}-${word.wordIndex}`} value={JSON.stringify([word.cueId, word.wordIndex])}>{word.label}</option>)}+ </select></div>}+ {field('durationSec', 'Duration seconds', true)}+ {field('text', 'Graphic text')}+ {field('narrativeFunction', 'Narrative function')}+ {field('mediumRationale', 'Medium rationale')}+ {event.kind === 'counter-change' && <>{field('fromValue', 'Counter before', true)}{field('toValue', 'Counter after', true)}</>}+ {event.kind === 'motif-transformation' && <>{field('motif', 'Motif')}{field('before', 'Motif before')}{field('after', 'Motif after')}</>}+ </div>+ <button type="button" className="min-h-[44px] text-port-error" onClick={() => setEvents((events) => events.filter((other) => other.id !== event.id))}>Remove {event.name}</button>+ </div>;+ })}+ <button type="button" className="min-h-[44px] text-port-accent" disabled={events.length >= 200} onClick={add}>Add narrative event</button>+ {sections.map((section) => {+ const current = reactiveSections.find((entry) => entry.sectionId === section.id) || { sectionId: section.id, gain: 0.25, maxGain: 0.35 };+ return <div key={section.id} className="flex flex-wrap items-end gap-2">+ <span>{section.label || section.id}</span>+ {['gain', 'maxGain'].map((key) => <div key={key}><label htmlFor={`mv-reactive-${section.id}-${key}`}>{key === 'gain' ? 'Reactive gain' : 'Gain cap'}</label>+ <input id={`mv-reactive-${section.id}-${key}`} className={`${inputCls} max-w-24`} type="number" min="0" max="1" step="0.05" required value={current[key]}+ onChange={(e) => setReactiveSections((entries) => [...entries.filter((entry) => entry.sectionId !== section.id), { ...current, [key]: Number(e.target.value) }])} /></div>)}+ </div>;+ })}+ <button className="min-h-[44px] rounded border border-port-border px-2" type="submit" disabled={!dirty || events.some((event) => !event.anchor)}>Save event bindings</button>+ <button className="ml-2 min-h-[44px] rounded border border-port-border px-2" type="button" disabled={!dirty} onClick={() => {+ setEvents(project.composition?.narrativeEvents || []); setReactiveSections(project.composition?.reactiveSections || []);+ }}>Discard event edits</button>+ </fieldset>+ </form>+ </details>;+}diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsxindex f14cc06020..af0d453bdd 100644--- a/client/src/components/musicVideo/stages/BoardStage.jsx+++ b/client/src/components/musicVideo/stages/BoardStage.jsx@@ -36,7 +36,8 @@ export default function BoardStage({ board }) {<AudioTimingPanel key={project.id} project={project} tracks={board.tracks} onApplied={board.replaceProject} disabled={locked || board.renderBound} />{project.audioAnalysis && scenes.length > 0 && (- <BeatTimeline audioAnalysis={project.audioAnalysis} scenes={scenes} lyricCues={project.lyricCues} onCommit={board.commitSceneTiming} />+ <BeatTimeline audioAnalysis={project.audioAnalysis} scenes={scenes} lyricCues={project.lyricCues} narrativeEvents={project.composition?.narrativeEvents}+ onSeek={(startSec) => board.seekToScene({ startSec })} onCommit={board.commitSceneTiming} />)}<div className="flex items-center justify-between">diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 05ec29d44e..03b94e65ea 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -301,3 +301,4 @@ grep -i "what you want to do" client/src/lib/README.md| `navPresentation.js` | Sidebar icon presentation and section ordering, separate from the Layout React refresh boundary. || `musicVideoGrade.js` | Shared Music Video grade preset and grain bounds for the composition controls. |+| `musicVideoNarrativeEvents.js` | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 71f4b35efa..446752a039 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -261,3 +261,4 @@ export * from './styleSourceChoice.js';export * from './trackProvenance.js';export * from './musicVideoGrade.js';+export * from './musicVideoNarrativeEvents.js';diff --git a/client/src/lib/musicVideoNarrativeEvents.js b/client/src/lib/musicVideoNarrativeEvents.jsnew file mode 100644index 0000000000..5ffc76f9cb--- /dev/null+++ b/client/src/lib/musicVideoNarrativeEvents.js@@ -0,0 +1 @@+export { NARRATIVE_EVENT_KINDS, resolveNarrativeEvents, narrativeFrameState } from '../../../server/lib/musicVideoNarrativeEvents.js';diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex ee108b5fe6..06eb489f15 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -380,6 +380,8 @@ export const getMusicVideoCompositionPreview = (id, { draft = false, ...optionsexport const generateMusicVideoMixedMediaDocument = (id, body, options = {}) =>request(`${compositionDocumentPath(id)}/generate`, { method: 'POST', body: JSON.stringify(body || {}), ...options });export const getMusicVideoMixedMediaCandidate = (id, options = {}) => request(`${compositionDocumentPath(id)}/candidate`, options);+export const reviseMusicVideoMixedMediaEvents = (id, body, options = {}) =>+ request(`${compositionDocumentPath(id)}/events/revise`, { method: 'POST', body: JSON.stringify(body), ...options });export const regenerateMusicVideoMixedMediaSection = (id, sectionId, body, options = {}) =>request(`${compositionDocumentPath(id)}/sections/${encodeURIComponent(sectionId)}/regenerate`, { method: 'POST', body: JSON.stringify(body), ...options });export const acceptMusicVideoMixedMediaDocument = (id, directory, options = {}) =>diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex d2cd496866..78a142e9d4 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -200,6 +200,7 @@ goal data together; interrupted intents remain retryable after restore.- Music Video shot action contracts are optional versioned metadata on the existing db-primary project: authored in `treatment.shotDirections[].actionContract`, applied in `scenes[].direction.actionContract`, and snapshotted in take `shotInstruction.actionContract`. They require no seed/backfill or new store; `musicVideoProjects` schema v13 prevents older treatment writers from discarding intent. Clip-relative event times are revalidated before video queue submission.- Music Video dependency provenance — versioned plate/clip references, optional crop/mask input revisions, composition-window checksums, and review snapshots live on existing db-primary `musicVideoProject` rows. Repairs keep historical takes and files and reuse serialized revision checkpoints; no new store, seed, or install migration. Legacy evidence without a snapshot remains unverified. The `musicVideoProjects` schema gate prevents older peers from reusing stale evidence; existing asset channels retain byte ownership.- Music Video development artifacts ("ingredients": a Cast & Sets check-in sheet, animatic, treatment, storyboard) — each version is an immutable file under `data/music-video/{projectId}/dev/{artifactId}/v{N}.{html,md,mp4,png,jpg}`; the `musicVideoProject` record owns the metadata (`devArtifacts[]`: kind, title, review status, notes, version history with each version's data-relative path). Versions are never overwritten and deletes are soft, so a clone that carried the metadata keeps valid pointers. The metadata is **wire-local** (stripped by `stripMusicVideoLocalRenderPins`, restored over a newer remote by `mergeProjectRecord`) because the bytes are not in the project's peer-sync asset manifest; both halves are backed up (PostgreSQL dump + rsync snapshot). Adapter: `server/services/musicVideo/devArtifactStore.js`.+- Music Video narrative events (`composition.narrativeEvents`) and section reactive gain caps (`composition.reactiveSections`) persist in the existing db-primary `music_video_projects` JSONB record. Anchors are song seconds, measured band-onset indices, or aligned cue/word indices; absent fields preserve legacy behavior. Audio replacement clears anchors while retaining narrative intent. Schema v14 gates peers whose composition normalizer would drop these fields. Resolved absolute frames live in immutable, wire-local document manifests; an event revision retains selected takes and replaces only affected section functions.- Music Video composition documents (render style `document`) — each import (zip, a folder inside `data/`, or the shipped `layered` template) is one immutable version folder `data/music-video/{projectId}/composition/{versionId}/` (index.html + scripts, fonts, media); the `musicVideoProject` record's `composition.document` holds the data-relative pointer plus source/size metadata. A clone shares the pointer; a version no project (live or tombstoned) points at is pruned on the next import or detach. The pointer is **wire-local** like the development artifacts (stripped by `stripMusicVideoLocalRenderPins`, restored by `mergeProjectRecord`) — a peer keeps its own and refuses to render without one. Renders stage a job-private copy under `data/music-video-song-renders/{jobId}/` (swept at boot, excluded from backups). Adapter: `server/services/musicVideo/compositionDocument.js`.- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.diff --git a/server/lib/README.md b/server/lib/README.mdindex 95d5007d6c..781a08685c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -818,3 +818,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoPlateEvidence.js` | Asset-bound authored-shot plate requirements, current evidence and selected-image admission. || `codeAnimationProjects.js` | Machine-local Production project, patch and independent budget schemas; package imports grant no execution authority. |+| `musicVideoNarrativeEvents.js` | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 7e70a6d307..95c9ca420d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -802,3 +802,4 @@ export * from './musicVideoDependencies.js';export * from './musicVideoPlateEvidence.js';export * from './codeAnimationProjects.js';+export * from './musicVideoNarrativeEvents.js';diff --git a/server/lib/musicVideoNarrativeEvents.js b/server/lib/musicVideoNarrativeEvents.jsnew file mode 100644index 0000000000..4b11b33ed0--- /dev/null+++ b/server/lib/musicVideoNarrativeEvents.js@@ -0,0 +1,57 @@+/** Named graphics on the absolute document clock. No media or provider I/O. */+export const NARRATIVE_EVENT_KINDS = ['reveal', 'impact', 'silence', 'counter-change', 'motif-transformation'];++/** Resolve every anchor once, never relative to an excerpt or a seek. */+export function resolveNarrativeEvents(project, sections, fps = 24) {+ const duration = Math.min(project.audioAnalysis?.durationSec || 0, 900);+ const frames = Math.floor(duration * fps + 1e-6);+ const events = [];+ const unresolved = [];+ for (const event of project.composition?.narrativeEvents || []) {+ const anchor = event.anchor;+ let time = null;+ if (anchor?.kind === 'time') time = anchor.atSec;+ if (anchor?.kind === 'onset') time = project.audioAnalysis?.features?.onsets?.[anchor.band]?.[anchor.index];+ if (anchor?.kind === 'word') {+ const cue = (project.lyricCues || []).find((cue) => cue.id === anchor.cueId);+ time = cue?.words?.[anchor.wordIndex]?.startSec;+ }+ if (!Number.isFinite(time)) { unresolved.push(event.id); continue; }+ time += anchor.offsetSec || 0;+ const startFrame = Math.ceil(time * fps - 1e-6);+ if (startFrame < 0 || startFrame >= frames) { unresolved.push(event.id); continue; }+ const endFrame = Math.min(frames, startFrame + Math.max(1, Math.ceil(event.durationSec * fps - 1e-6)));+ const section = sections.find((section) => startFrame / fps >= section.startSec && startFrame / fps < section.endSec);+ events.push({ ...event, startFrame, endFrame, startSec: startFrame / fps, endSec: endFrame / fps, sectionId: section?.id || null });+ }+ return { events: events.sort((a, b) => a.startFrame - b.startFrame || a.id.localeCompare(b.id)), unresolved };+}++/** Self-contained: embedded verbatim in both the preview and render pages. */+export function narrativeFrameState(song, time, fps) {+ const frame = Math.max(0, Math.floor(time * fps + 1e-6));+ const events = song.narrativeEvents || [];+ let holdFrame = null;+ let holdEnd = -1;+ let holdStart = -1;+ for (const event of events.filter((event) => event.kind === 'silence')) {+ if (event.startFrame > holdEnd) { holdStart = event.startFrame; holdEnd = event.endFrame; }+ else holdEnd = Math.max(holdEnd, event.endFrame);+ if (frame >= holdStart && frame < holdEnd) holdFrame = holdStart;+ }+ const drawFrame = holdFrame ?? frame;+ const t = drawFrame / fps;+ const section = (song.sections || []).find((section) => t >= section.startSec && t < section.endSec);+ const reactive = (song.reactiveSections || []).find((entry) => entry.sectionId === section?.id);+ const gain = reactive?.gain ?? 0.25;+ const maxGain = reactive?.maxGain ?? 0.35;+ const envelope = song.features?.envelopes;+ const level = envelope?.rms?.[Math.floor(t * envelope.fps)] ?? 0;+ const reactiveGain = holdFrame != null ? 0 : Math.max(0, Math.min(maxGain, level * gain));+ const activeEvents = events.filter((event) => event.kind !== 'silence' && drawFrame >= event.startFrame && drawFrame < event.endFrame)+ .map((event) => {+ const progress = Math.min(1, (drawFrame - event.startFrame) / Math.max(1, event.endFrame - event.startFrame - 1));+ return { ...event, progress, value: (event.fromValue ?? 0) + ((event.toValue ?? 1) - (event.fromValue ?? 0)) * progress };+ });+ return { frame: drawFrame, t, hold: holdFrame != null, reactiveGain, activeEvents };+}diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 16ca0da2aa..8b98220bca 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -11,6 +11,7 @@ import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVimport { z } from 'zod';import { shotActionContractProblem } from './musicVideoActionContract.js';+import { NARRATIVE_EVENT_KINDS } from './musicVideoNarrativeEvents.js';import { MUSIC_VIDEO_MEDIA } from './musicVideoMediumPlan.js';import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';import { MUSIC_VIDEO_SHOT_MODES, SOURCE_AUDIO_LIPSYNC } from './musicVideoShotTiming.js';@@ -361,6 +362,31 @@ export const musicVideoCompositionOverlaySchema = z.object({timecodeStartSec: z.number().min(0).max(86400).optional(),}).strict();+export const musicVideoNarrativeEventSchema = z.object({+ id: z.string().min(1).max(64),+ name: z.string().min(1).max(120),+ kind: z.enum(NARRATIVE_EVENT_KINDS),+ anchor: z.discriminatedUnion('kind', [+ z.object({ kind: z.literal('time'), atSec: z.number().min(0).max(36000), offsetSec: z.number().min(-900).max(900).optional() }).strict(),+ z.object({ kind: z.literal('onset'), band: z.enum(['low', 'mid', 'high']), index: z.number().int().min(0).max(100000), offsetSec: z.number().min(-900).max(900).optional() }).strict(),+ z.object({ kind: z.literal('word'), cueId: z.string().min(1).max(64), wordIndex: z.number().int().min(0).max(1000), offsetSec: z.number().min(-900).max(900).optional() }).strict(),+ ]).nullable(),+ durationSec: z.number().positive().max(900),+ narrativeFunction: z.string().min(1).max(1000),+ mediumRationale: z.string().min(1).max(1000),+ text: z.string().max(500).optional(),+ motif: z.string().max(120).optional(),+ before: z.string().max(120).optional(),+ after: z.string().max(120).optional(),+ fromValue: z.number().finite().min(-1000000).max(1000000).optional(),+ toValue: z.number().finite().min(-1000000).max(1000000).optional(),+}).strict();+export const musicVideoReactiveSectionSchema = z.object({+ sectionId: z.string().min(1).max(64),+ gain: z.number().min(0).max(1),+ maxGain: z.number().min(0).max(1),+}).strict();+// Replaced whole by a project PATCH (the editor sends the full manifest).export const musicVideoCompositionSchema = z.object({version: z.literal(1).optional(),@@ -385,6 +411,8 @@ export const musicVideoCompositionSchema = z.object({document: musicVideoCompositionDocumentSchema.nullable().optional(),documentDraft: musicVideoCompositionDocumentSchema.nullable().optional(),overlay: musicVideoCompositionOverlaySchema.nullable().optional(),+ narrativeEvents: z.array(musicVideoNarrativeEventSchema).max(200).refine((events) => new Set(events.map((event) => event.id)).size === events.length, 'event ids must be unique').optional(),+ reactiveSections: z.array(musicVideoReactiveSectionSchema).max(40).refine((sections) => new Set(sections.map((section) => section.sectionId)).size === sections.length, 'section ids must be unique').optional(),}).strict();// A relative folder inside data/ to copy a composition document from.diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 2f26864db8..62d0a0a2ed 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -666,7 +666,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// a submitted suffix after restart. Absent repair metadata stays legacy.// v17 = piecewise audio timing receipts and historical source/timing snapshots.// Optional on legacy records; no backfill. Older peers cannot apply receipts safely.- musicVideoProjects: 17,+ // v18 = named narrative event anchors and bounded section reactivity. Older+ // composition normalizers drop these fields on edit. Absent remains legacy;+ // no stored row rewrite is needed. Document manifests remain wire-local.+ musicVideoProjects: 18,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex b72e2fb89b..b5302f1f92 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -140,7 +140,7 @@ import {resolveDocumentFile,} from '../services/musicVideo/compositionDocument.js';import { buildDocumentPreview } from '../services/musicVideo/documentPreview.js';-import { acceptMixedMediaDocument, generateMixedMediaDocument, readMixedMediaCandidate, regenerateMixedMediaSection } from '../services/musicVideo/documentGeneration.js';+import { acceptMixedMediaDocument, generateMixedMediaDocument, readMixedMediaCandidate, regenerateMixedMediaSection, reviseMixedMediaEvents } from '../services/musicVideo/documentGeneration.js';import { isZipUpload } from '../lib/zipStream.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';@@ -578,6 +578,11 @@ router.get('/:id/composition/document/candidate', asyncHandler(async (req, res)res.json(await readMixedMediaCandidate(req.params.id));}));+router.post('/:id/composition/document/events/revise', asyncHandler(async (req, res) => {+ const body = validateRequest(musicVideoMixedMediaRegenerateSchema, req.body || {});+ res.status(201).json(await reviseMixedMediaEvents(req.params.id, body));+}));+router.post('/:id/composition/document/sections/:sectionId/regenerate', asyncHandler(async (req, res) => {const body = validateRequest(musicVideoMixedMediaRegenerateSchema, req.body || {});res.status(201).json(await regenerateMixedMediaSection(req.params.id, req.params.sectionId, body));diff --git a/server/routes/musicVideoCompositionDocument.test.js b/server/routes/musicVideoCompositionDocument.test.jsindex 1acab659eb..9449afd486 100644--- a/server/routes/musicVideoCompositionDocument.test.js+++ b/server/routes/musicVideoCompositionDocument.test.js@@ -76,6 +76,24 @@ beforeEach(async () => {afterAll(cleanupTempDataRoots);describe('music-video composition documents', () => {+ it('persists validated narrative events and gain caps through the project route, and clears anchors on a song replacement', async () => {+ const event = { id: 'counter', name: 'Count rises', kind: 'counter-change', anchor: { kind: 'time', atSec: 0.51 }, durationSec: 1,+ narrativeFunction: 'Show progress', mediumRationale: 'Exact code counter', fromValue: 3, toValue: 8 };+ const composition = { mode: 'document', narrativeEvents: [event], reactiveSections: [{ sectionId: 'song', gain: 1, maxGain: 0.2 }] };+ const patched = await request(app).patch(`/api/music-video/${project.id}`).send({ composition });+ expect(patched.status).toBe(200);+ expect((await projects.getProject(project.id)).composition).toMatchObject(composition);+ const invalid = await request(app).patch(`/api/music-video/${project.id}`).send({ composition: { ...composition, reactiveSections: [{ sectionId: 'song', gain: 1, maxGain: 2 }] } });+ expect(invalid.status).toBe(400);+ const duplicate = await request(app).patch(`/api/music-video/${project.id}`).send({ composition: { ...composition, narrativeEvents: [event, event] } });+ expect(duplicate.status).toBe(400);+ const replaced = await request(app).patch(`/api/music-video/${project.id}`).send({ trackId: 'track-example' });+ expect(replaced.status).toBe(200);+ expect(replaced.body.composition.narrativeEvents).toEqual([{ ...event, anchor: null }]);+ const invalidRevision = await request(app).post(`/api/music-video/${project.id}/composition/document/events/revise`).send({ expectedDraft: '../../other' });+ expect(invalidRevision.status).toBe(400);+ });+it('imports a zip (one top folder), switches the render style, lists, exports, previews and serves its files inert', async () => {const zip = createZip(Object.entries(FILES).map(([name, data]) => ({ name: `my-video/${name}`, data })), { compress: true });const created = await uploadZip(project.id, zip, 'my-video.zip');diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex 54314c63a4..e3dbd010ef 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -319,6 +319,8 @@ function promptSong(song) {beats: (song.beats || []).slice(0, 400),downbeats: (song.downbeats || []).slice(0, 200),featureNames: song.featureNames || [],+ narrativeEvents: song.narrativeEvents || [],+ reactiveSections: song.reactiveSections || [],};}@@ -370,6 +372,7 @@ export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment,`Write original Canvas 2D section functions for a mixed-media music-video document titled ${JSON.stringify(trimTo(title, 200))}. The host owns the document, song clock, selected local media and lyric pass. Return code functions only; do not request or generate image/video assets.`,CODE_VIDEO_RULES.replace('- Canvas 2D only. No external assets, fonts, or network.', '- Canvas 2D only. No network, remote URLs, filesystem paths or font loading. The host binds only the listed selected project assets; draw over footage/stills without obscuring them, and draw the entire frame for card scenes.'),'env additionally has mediaKind (video, image or null) and visualLayer (footage, still or card). The host has already drawn the selected media at its in/out time. Do not read DOM or load assets in a section function. Use seeded arithmetic from env.frame for visual motion. Keep repeated hooks related but deliberately vary their action.',+ 'NARRATIVE CLOCK: song.narrativeEvents are resolved absolute startFrame/endFrame bindings. env.events supplies active events with progress and counter value; env.reactiveGain is bounded by the section gain/maxGain and is zero during silence. The host freezes song time, media and graphics for silence, and draws exact event text/counters/motif labels after your function. Use the narrativeFunction, motif and mediumRationale to motivate your graphic actions; do not duplicate event text or infer new onsets. Prefer code/stills/selected media for exact text and graphics. Footage is for actions that need it and must already be selected.',`SHARED STYLE CONTRACT:\n${JSON.stringify(sharedStyle || { palette, treatment: { brief: treatment?.brief || null, motifs: treatment?.arc?.motifs || [], styleLook: treatment?.styleLook || null }, visualSpec, styleLines })}`,`SONG AND LYRIC TIMING:\n${JSON.stringify(promptSong(song))}`,`APPROVED SCENE ASSIGNMENTS AND LOCAL ASSET IDS:\n${JSON.stringify(scenes)}`,diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.jsindex e3be8b5531..c77357eada 100644--- a/server/services/musicVideo/composition.js+++ b/server/services/musicVideo/composition.js@@ -29,6 +29,8 @@ import {MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS as TYPOGRAPHY_PLACEMENTS,MUSIC_VIDEO_TYPOGRAPHY_TEMPLATES as TYPOGRAPHY_TEMPLATES,isDeterministicCodeSource,+ musicVideoNarrativeEventSchema,+ musicVideoReactiveSectionSchema,} from '../../lib/musicVideoValidation.js';export const COMPOSITION_VERSION = 1;@@ -167,6 +169,12 @@ export function normalizeComposition(input) {...(documentRef ? { document: documentRef } : {}),...(documentDraft ? { documentDraft } : {}),...(overlay ? { overlay } : {}),+ ...(Array.isArray(input.narrativeEvents) ? { narrativeEvents: input.narrativeEvents.slice(0, 200)+ .map((event) => musicVideoNarrativeEventSchema.safeParse(event)).filter((result) => result.success).map((result) => result.data)+ .filter((event, index, events) => events.findIndex((other) => other.id === event.id) === index) } : {}),+ ...(Array.isArray(input.reactiveSections) ? { reactiveSections: input.reactiveSections.slice(0, 40)+ .map((section) => musicVideoReactiveSectionSchema.safeParse(section)).filter((result) => result.success).map((result) => result.data)+ .filter((section, index, sections) => sections.findIndex((other) => other.sectionId === section.sectionId) === index) } : {}),};}@@ -200,6 +208,7 @@ export function invalidateCompositionTiming(composition) {...composition,textCues: (composition.textCues || []).map((cue) => ({ ...cue, startSec: null, endSec: null })),posterSec: null,+ ...(composition.narrativeEvents ? { narrativeEvents: composition.narrativeEvents.map((event) => ({ ...event, anchor: null })) } : {}),};}diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.jsindex 3b70c4c99b..9525793122 100644--- a/server/services/musicVideo/documentGeneration.js+++ b/server/services/musicVideo/documentGeneration.js@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';import { readFile } from 'node:fs/promises';import { parse } from '@babel/parser';import { ServerError } from '../../lib/errorHandler.js';+import { resolveNarrativeEvents } from '../../lib/musicVideoNarrativeEvents.js';import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';import { summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';import { buildMixedMediaDocumentPrompt, extractCodeSections } from '../codeAnimation/prompt.js';@@ -43,7 +44,7 @@ function checkedFunction(source) {return source;}-function basisFor(project) {+function basisFor(project, includeEvents = true) {// These are all inputs that can change which pixels or authoring directions// a section means. A new candidate cannot publish across such an edit.const input = {@@ -59,10 +60,38 @@ function basisFor(project) {lyricMarkers: project.lyricMarkers || null,scenes: project.scenes || [],compositionStyle: project.composition?.style || { color: '#ffffff', font: 'sans' },+ ...(includeEvents ? { eventInputs: eventInputs(project) } : {}),};return createHash('sha256').update(JSON.stringify(input)).digest('hex');}+const eventInputs = (project) => ({+ narrativeEvents: project.composition?.narrativeEvents || [],+ reactiveSections: project.composition?.reactiveSections || [],+});++function matchesBasis(project, manifest) {+ if (manifest.structuralBasis) return manifest.basis === basisFor(project);+ const inputs = eventInputs(project);+ return !inputs.narrativeEvents.length && !inputs.reactiveSections.length && manifest.basis === basisFor(project, false);+}++function affectedEventSections(before, after) {+ const changedSpans = [];+ const oldEvents = new Map((before.narrativeEvents || []).map((event) => [event.id, event]));+ const newEvents = new Map((after.narrativeEvents || []).map((event) => [event.id, event]));+ for (const id of new Set([...oldEvents.keys(), ...newEvents.keys()])) {+ const old = oldEvents.get(id); const next = newEvents.get(id);+ if (JSON.stringify(old) !== JSON.stringify(next)) changedSpans.push(...[old, next].filter(Boolean));+ }+ return after.sections.filter((section) => {+ const oldGain = (before.reactiveSections || []).find((entry) => entry.sectionId === section.id);+ const nextGain = (after.reactiveSections || []).find((entry) => entry.sectionId === section.id);+ return JSON.stringify(oldGain) !== JSON.stringify(nextGain)+ || changedSpans.some((event) => event.startSec < section.endSec && event.endSec > section.startSec);+ }).map((section) => section.id);+}+async function authoringContext(project) {const plan = summarizeMusicVideoMediumPlan(project);if (plan.strategy === 'code-first' && plan.blocked) {@@ -82,6 +111,7 @@ async function authoringContext(project) {const media = await resolveSceneMedia(project, { history, strictLayers: true });const frame = DOCUMENT_FRAME_SIZES[documentAspect(project)];const data = buildDocumentData(project, { media, frame, clock: documentRenderClock(duration), songDurationSec: duration, generated: true });+ Object.assign(song, { narrativeEvents: data.song.narrativeEvents, reactiveSections: data.song.reactiveSections });const scenes = data.scenes.map((scene) => {const original = project.scenes.find((entry) => entry.sceneId === scene.sceneId);const wanted = scene.visualLayer === 'still' ? 'image' : scene.visualLayer === 'footage' ? 'video' : null;@@ -97,7 +127,7 @@ async function authoringContext(project) {inSec: scene.media?.inSec ?? null, outSec: scene.media?.outSec ?? null,};});- return { song, scenes, basis: basisFor(project), palette: paletteFromProject(project) };+ return { song, scenes, basis: basisFor(project), structuralBasis: basisFor(project, false), palette: paletteFromProject(project) };}function acceptedSections(text, ids) {@@ -134,21 +164,24 @@ async function priorManifest(project) {return { pointer, manifest };}-async function runAuthoring(projectId, { providerId, model, sectionId = null, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {+async function runAuthoring(projectId, { providerId, model, sectionId = null, eventRevision = false, expectedDraft = null, feedback = '', beforeSubmit = null, verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);if (!project) throw fail('Project not found', 'NOT_FOUND', 404);const context = await authoringContext(project);let prior = null;- if (sectionId) {+ if (sectionId || eventRevision) {prior = await priorManifest(project);- if (prior.manifest.basis !== context.basis) throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);+ if (eventRevision ? (prior.manifest.structuralBasis || prior.manifest.basis) !== context.structuralBasis : !matchesBasis(project, prior.manifest)) throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);if (project.composition?.documentDraft&& (project.composition?.document?.directory || null) !== (prior.manifest.baseDocumentDirectory || null)) {throw fail('The selected document changed — generate a fresh candidate', 'COMPOSITION_DRAFT_STALE', 409);}- if (!prior.manifest.sections.some((section) => section.id === sectionId)) throw fail('Section not found in the generated document', 'SECTION_NOT_FOUND', 404);+ if (sectionId && !prior.manifest.sections.some((section) => section.id === sectionId)) throw fail('Section not found in the generated document', 'SECTION_NOT_FOUND', 404);if (expectedDraft !== prior.pointer.directory) throw fail('The candidate changed — review it again', 'COMPOSITION_DRAFT_STALE', 409);}+ const ids = eventRevision ? affectedEventSections(prior.manifest.song, context.song)+ : sectionId ? [sectionId] : context.song.sections.map((section) => section.id);+ if (!ids.length) throw fail('No narrative event or section gain changes to revise', 'NO_EVENT_CHANGES', 409);const sharedStyle = prior?.manifest.sharedStyle || {palette: context.palette,treatment: { brief: project.treatment?.brief || null, motifs: project.treatment?.arc?.motifs || [], arc: project.treatment?.arc?.beats || [], styleLook: project.treatment?.styleLook || null },@@ -156,18 +189,19 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, exstyleLines: await styleLinesFor(project),};const prompt = buildMixedMediaDocumentPrompt({- title: project.name, song: context.song, palette: context.palette, treatment: project.treatment,+ title: project.name, song: { ...context.song, sections: context.song.sections.filter((section) => ids.includes(section.id)) }, palette: context.palette, treatment: project.treatment,visualSpec: project.visualSpec, scenes: context.scenes, styleLines: sharedStyle.styleLines,onlySectionId: sectionId, sharedStyle,});const directedPrompt = feedback ? `${prompt}\n\nReview findings for this section (retain the approved medium and selected assets; never invent a footage fallback):\n${feedback.slice(0, 8000)}` : prompt;const run = await runModel({ providerId, model, prompt: directedPrompt, source: 'music-video-document', beforeSubmit });- const ids = sectionId ? [sectionId] : context.song.sections.map((section) => section.id);const updated = acceptedSections(run.text, ids);const merged = new Map((prior?.manifest.sections || []).map((section) => [section.id, section.source]));for (const [id, source] of updated) merged.set(id, source);const manifest = {- version: 1, basis: context.basis, baseDocumentDirectory: project.composition?.document?.directory || null,+ version: 1, basis: context.basis, structuralBasis: context.structuralBasis, baseDocumentDirectory: project.composition?.document?.directory || null,+ changedSectionIds: [...new Set([...((prior && project.composition?.documentDraft) ? prior.manifest.changedSectionIds || [] : []), ...ids])],+ beforeSong: prior ? (project.composition?.documentDraft ? prior.manifest.beforeSong || prior.manifest.song : prior.manifest.song) : null,sharedStyle, song: context.song, palette: context.palette,scenes: context.scenes,sections: context.song.sections.map(({ id }) => ({ id, source: merged.get(id) })),@@ -189,6 +223,7 @@ async function runAuthoring(projectId, { providerId, model, sectionId = null, exexport const generateMixedMediaDocument = (projectId, input = {}) => runAuthoring(projectId, input);export const regenerateMixedMediaSection = (projectId, sectionId, input = {}) => runAuthoring(projectId, { ...input, sectionId });+export const reviseMixedMediaEvents = (projectId, input = {}) => runAuthoring(projectId, { ...input, eventRevision: true });export async function acceptMixedMediaDocument(projectId, directory, { verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);@@ -199,7 +234,7 @@ export async function acceptMixedMediaDocument(projectId, directory, { verifyCurreturn acceptGeneratedDocument(projectId, directory, {verifyCurrent: (current) => {verifyCurrent(current);- if (basisFor(current) !== manifest.basis || (current.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)) {+ if (!matchesBasis(current, manifest) || (current.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)) {throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);}},@@ -211,12 +246,22 @@ export async function readMixedMediaCandidate(projectId) {if (!project) throw fail('Project not found', 'NOT_FOUND', 404);if (!project.composition?.documentDraft && project.composition?.document?.source?.kind !== 'generated') return { candidate: null, source: null, sections: [] };const { pointer, manifest } = await priorManifest(project);+ const currentSong = buildSongDocument(project);+ const resolved = resolveNarrativeEvents(project, currentSong.sections, currentSong.fps);+ Object.assign(currentSong, { narrativeEvents: resolved.events, reactiveSections: project.composition?.reactiveSections || [] });return {candidate: project.composition?.documentDraft || null,source: pointer,sections: (manifest.song?.sections || []).map(({ id, label, startSec, endSec }) => ({ id, label, startSec, endSec })),providerId: manifest.providerId, model: manifest.model,- stale: manifest.basis !== basisFor(project)+ eventRevisionAvailable: !resolved.unresolved.length && (manifest.structuralBasis || manifest.basis) === basisFor(project, false)+ && affectedEventSections(manifest.song, currentSong).length > 0,+ comparisons: (manifest.changedSectionIds || []).map((id) => ({+ sectionId: id,+ before: (manifest.beforeSong?.narrativeEvents || []).filter((event) => event.sectionId === id),+ after: (manifest.song?.narrativeEvents || []).filter((event) => event.sectionId === id),+ })),+ stale: !matchesBasis(project, manifest)|| (Boolean(project.composition?.documentDraft)&& (project.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)),};diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.jsindex b08b165bcb..71a05538f5 100644--- a/server/services/musicVideo/documentGeneration.test.js+++ b/server/services/musicVideo/documentGeneration.test.js@@ -21,7 +21,7 @@ vi.mock('../promptRunner.js', () => ({const { PATHS } = await import('../../lib/paths.js');const projects = await import('./projects.js');const { importDocumentTemplate } = await import('./compositionDocument.js');-const { generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js');+const { generateMixedMediaDocument, regenerateMixedMediaSection, reviseMixedMediaEvents, readMixedMediaCandidate, acceptMixedMediaDocument } = await import('./documentGeneration.js');const source = (color) => `function render(ctx, env) { ctx.fillStyle = '${color}'; ctx.fillRect(0, 0, env.width, env.height); }`;const response = (colors) => JSON.stringify({ sections: Object.entries(colors).map(([id, color]) => ({ id, source: source(color) })) });@@ -64,6 +64,77 @@ async function fixture() {}describe('treatment-driven mixed-media document authoring', () => {+ it('accepts a legacy generated manifest and upgrades it through an event-only revision', async () => {+ const id = await fixture();+ const first = (await generateMixedMediaDocument(id)).document;+ const legacy = await manifestAt(first);+ legacy.basis = legacy.structuralBasis;+ delete legacy.structuralBasis;+ delete legacy.song.narrativeEvents;+ delete legacy.song.reactiveSections;+ await writeFile(join(PATHS.data, first.directory, 'manifest.json'), JSON.stringify(legacy));+ expect((await readMixedMediaCandidate(id)).stale).toBe(false);+ await acceptMixedMediaDocument(id, first.directory);+ const current = await projects.getProject(id);+ await projects.updateProject(id, { composition: { ...current.composition, narrativeEvents: [{ id: 'new', name: 'Reveal', kind: 'reveal',+ anchor: { kind: 'time', atSec: 1 }, durationSec: 1, narrativeFunction: 'Introduce the kite', mediumRationale: 'Exact graphic' }] } });+ h.response = response({ intro: '#00ff00' });+ const updated = (await reviseMixedMediaEvents(id, { expectedDraft: first.directory })).document;+ expect((await manifestAt(updated)).structuralBasis).toBe(legacy.basis);+ expect((await projects.getProject(id)).scenes).toEqual(current.scenes);+ });++ it('resolves onset/word events and revises only their old/new sections while retaining accepted takes', async () => {+ const id = await fixture();+ const event = { id: 'reveal', name: 'Kite opens', kind: 'reveal', anchor: { kind: 'onset', band: 'low', index: 0 }, durationSec: 1,+ narrativeFunction: 'Reveal flight', mediumRationale: 'Precise cut-paper graphic', text: 'FLIGHT' };+ await projects.updateProject(id, { composition: { mode: 'document', narrativeEvents: [event], reactiveSections: [{ sectionId: 'intro', gain: 1, maxGain: 0.2 }] } });+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, audioAnalysis: { ...current.audioAnalysis,+ features: { envelopes: { fps: 1, rms: [1], low: [1], mid: [0], high: [0] }, onsets: { low: [0.51], mid: [], high: [] } },+ } } }));+ const first = (await generateMixedMediaDocument(id)).document;+ const before = await manifestAt(first);+ expect(before.song.narrativeEvents[0]).toMatchObject({ startFrame: 13, endFrame: 37, sectionId: 'intro' });+ expect(h.prompt).toContain('Precise cut-paper graphic');+ expect(h.prompt).toContain('env.reactiveGain');+ await acceptMixedMediaDocument(id, first.directory);+ const original = await projects.getProject(id);+ await projects.updateProject(id, { composition: { ...original.composition, narrativeEvents: [{ ...event, anchor: { kind: 'word', cueId: 'l1', wordIndex: 0 } }] } });+ expect((await readMixedMediaCandidate(id)).eventRevisionAvailable).toBe(true);+ h.response = response({ intro: '#aa0000', clip: '#00aa00' });+ const second = (await reviseMixedMediaEvents(id, { expectedDraft: first.directory })).document;+ const after = await manifestAt(second);+ expect(after.changedSectionIds).toEqual(['intro', 'clip']);+ expect(after.song.narrativeEvents[0]).toMatchObject({ startFrame: 480, endFrame: 504 });+ expect(after.sections.find((section) => section.id === 'still').source).toBe(before.sections.find((section) => section.id === 'still').source);+ expect((await projects.getProject(id)).scenes).toEqual(original.scenes);+ expect((await projects.getProject(id)).composition.document.directory).toBe(first.directory);+ await acceptMixedMediaDocument(id, second.directory);+ await expect(reviseMixedMediaEvents(id, { expectedDraft: second.directory })).rejects.toMatchObject({ code: 'NO_EVENT_CHANGES' });+ expect(h.calls).toBe(2); // document code only, no media generation+ const comparisons = (await readMixedMediaCandidate(id)).comparisons;+ expect(comparisons.find((entry) => entry.sectionId === 'intro').before[0].startFrame).toBe(13);+ expect(comparisons.find((entry) => entry.sectionId === 'clip').after[0].startFrame).toBe(480);+ });++ it('fails unresolved anchors before spending and refuses publication across a concurrent event edit', async () => {+ const id = await fixture();+ const event = { id: 'hold', name: 'Pause', kind: 'silence', anchor: { kind: 'onset', band: 'mid', index: 8 }, durationSec: 1,+ narrativeFunction: 'Let the image breathe', mediumRationale: 'Hold existing media' };+ await projects.updateProject(id, { composition: { mode: 'document', narrativeEvents: [event] } });+ await expect(generateMixedMediaDocument(id)).rejects.toMatchObject({ code: 'NARRATIVE_EVENT_UNRESOLVED' });+ expect(h.calls).toBe(0);+ await projects.updateProject(id, { composition: { mode: 'document', narrativeEvents: [{ ...event, anchor: { kind: 'time', atSec: 1 } }] } });+ const first = (await generateMixedMediaDocument(id)).document;+ h.onSubmit = async () => {+ const current = await projects.getProject(id);+ await projects.updateProject(id, { composition: { ...current.composition, narrativeEvents: [{ ...event, anchor: { kind: 'time', atSec: 2 } }] } });+ };+ await expect(regenerateMixedMediaSection(id, 'intro', { expectedDraft: first.directory })).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });+ expect((await projects.getProject(id)).composition.documentDraft.directory).toBe(first.directory);+ await expect(acceptMixedMediaDocument(id, first.directory)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });+ });+it('preflights selected media before a provider call and stages a reviewable 30-second document', async () => {const id = await fixture();const original = await projects.getProject(id);diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.jsindex 92910f52bc..e953abc7ee 100644--- a/server/services/musicVideo/documentPreview.js+++ b/server/services/musicVideo/documentPreview.js@@ -20,6 +20,7 @@*/import { readFile } from 'fs/promises';+import { narrativeFrameState } from '../../lib/musicVideoNarrativeEvents.js';import { extname } from 'path';import { loadHistory } from '../videoGen/history.js';import { readDocumentFiles, documentMimeType } from './compositionDocument.js';@@ -171,7 +172,7 @@ export async function buildDocumentPreview(project, { draft = false } = {}) {const url = rel ? await dataUrl(rel) : null;if (url) html = html.split(match[0]).join(match[0].replace(match[1], () => `"${url}"`));}- const head = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};</script>`;+ const head = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;const at = html.match(/<head[^>]*>/i);html = at ? `${html.slice(0, at.index + at[0].length)}${head}${html.slice(at.index + at[0].length)}` : `${head}${html}`;diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.jsindex 486c4be784..5c996a71cb 100644--- a/server/services/musicVideo/documentRender.browser.test.js+++ b/server/services/musicVideo/documentRender.browser.test.js@@ -70,6 +70,68 @@ describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpe}, 30000);afterAll(() => _cleanupTestBrowser({ browser, proc, cleanup: () => {} }));+ it('keeps event frames identical across shuffled seeks, an excerpt and a full render, and freezes silence', async () => {+ const created = await projects.createProject({ name: 'Synthetic event proof' });+ const base = { durationSec: 0.2, narrativeFunction: 'Mark the story turn', mediumRationale: 'Exact code graphics' };+ await projects.mutateProjectRecord(created.id, (current) => ({ project: { ...current,+ audioAnalysis: { durationSec: 2, beats: [0, 0.5, 1, 1.5], downbeats: [0], sections: [{ id: 'song', label: 'Hook', startSec: 0, endSec: 2 }],+ features: { envelopes: { fps: 2, rms: [1, 1, 1, 1], low: [1, 1, 1, 1], mid: [0, 0, 0, 0], high: [0, 0, 0, 0] }, onsets: { low: [0.51], mid: [], high: [] } } },+ lyricCues: [{ id: 'line', text: 'UP', startSec: 0.8, words: [{ w: 'UP', startSec: 0.8 }] }],+ composition: { mode: 'document', reactiveSections: [{ sectionId: 'song', gain: 1, maxGain: 0.2 }], narrativeEvents: [+ { ...base, id: 'hit', name: 'Impact', kind: 'impact', text: 'TURN', anchor: { kind: 'onset', band: 'low', index: 0 } },+ { ...base, id: 'count', name: 'Count', kind: 'counter-change', fromValue: 0, toValue: 9, anchor: { kind: 'word', cueId: 'line', wordIndex: 0 } },+ { ...base, id: 'quiet', name: 'Quiet', kind: 'silence', durationSec: 0.4, anchor: { kind: 'time', atSec: 1 } },+ { ...base, id: 'quiet-more', name: 'Keep quiet', kind: 'silence', durationSec: 0.2, anchor: { kind: 'time', atSec: 1.25 } },+ { ...base, id: 'motif', name: 'Kite', kind: 'motif-transformation', before: 'Fold', after: 'Flight', anchor: { kind: 'time', atSec: 1.5 } },+ { ...base, id: 'reveal', name: 'Reveal', kind: 'reveal', anchor: { kind: 'time', atSec: 1.8 } },+ ] },+ scenes: [{ sceneId: 'card', startSec: 0, endSec: 2, visualLayer: 'card', cardText: '' }],+ } }));+ await importDocumentTemplate(created.id);+ const project = await projects.getProject(created.id);+ const preview = await buildDocumentPreview(project);+ const page = await browser.newPage();+ await page.setContent(preview.html);+ await page.evaluate(() => window.postMessage({ type: 'portos-mv:assets', files: {} }, '*'));+ const at = (frame) => page.evaluate(async (frame) => {+ await window.portosComposition.seek(frame / 24);+ return { pixels: document.getElementById('stage').toDataURL(), state: window.PORTOS_MV_EVENT_STATE(window.PORTOS_MV.song, frame / 24, 24) };+ }, frame);+ const hit = await at(13);+ expect(hit.state.activeEvents[0].id).toBe('hit');+ expect((await at(12)).state.activeEvents).toEqual([]);+ expect(hit.pixels).not.toBe((await at(12)).pixels);+ expect((await at(20)).state.activeEvents[0].id).toBe('count');+ expect((await at(36)).state.activeEvents[0].id).toBe('motif');+ expect((await at(44)).state.activeEvents[0].id).toBe('reveal');+ const held = await at(24);+ expect(held.state).toMatchObject({ hold: true, reactiveGain: 0, frame: 24 });+ expect((await at(30)).pixels).toBe(held.pixels);+ expect((await at(34)).pixels).toBe(held.pixels); // overlapping holds share one frozen frame+ expect((await at(13)).pixels).toBe(hit.pixels);+ expect(hit.state.reactiveGain).toBe(0.2);+ await page.close();++ await mkdir(PATHS.music, { recursive: true });+ await mkdir(PATHS.videos, { recursive: true });+ const master = join(PATHS.music, 'event-master.wav');+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=2', master]);+ const plan = { ...(await prepareDocumentRender(project)), frame: { width: 1280, height: 720 } };+ const full = join(PATHS.videos, 'event-full.mp4');+ const excerpt = join(PATHS.videos, 'event-excerpt.mp4');+ await encodeDocumentComposition({ project, plan, jobId: 'event-full', audioPath: master, outputPath: full });+ await encodeDocumentComposition({ project, plan, jobId: 'event-excerpt', audioPath: master, outputPath: excerpt, windowStart: 13 / 24, windowEnd: 18 / 24 });+ const pixels = (path) => execFileSync(ffmpeg, ['-v', 'error', '-i', path, '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 1 << 26 });+ const fullPixels = pixels(full); const excerptPixels = pixels(excerpt); const frameBytes = 64 * 36 * 3;+ expect(excerptPixels.length).toBe(frameBytes * 5);+ for (let frame = 0; frame < 5; frame++) {+ const expected = fullPixels.subarray((frame + 13) * frameBytes, (frame + 14) * frameBytes);+ const actual = excerptPixels.subarray(frame * frameBytes, (frame + 1) * frameBytes);+ const difference = actual.reduce((sum, value, i) => sum + Math.abs(value - expected[i]), 0) / frameBytes;+ expect(difference, `event frame ${frame + 13}`).toBeLessThan(5); // lossy encoder tolerance+ }+ }, 120000);+it('draws the selected take at SONG time in an excerpt, identically on every render, with the master muxed', async () => {// A 3s clip: red, then green, then blue — each second a solid colour.await mkdir(PATHS.videos, { recursive: true });diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex 9e2915924a..42cf4633a2 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -37,6 +37,7 @@ import { musicVideoAspect } from '../../lib/musicVideoAspect.js';import { documentDirectoryForRender } from './compositionDocument.js';import { musicVideoSongDocument } from './compositionRender.js';import { buildSongDocument } from './codeTimeline.js';+import { resolveNarrativeEvents, narrativeFrameState } from '../../lib/musicVideoNarrativeEvents.js';export const DOCUMENT_RENDER_FPS = 24;// The frame each project aspect renders at (the composition browser's sizes).@@ -180,7 +181,13 @@ export function buildDocumentData(project, { media = new Map(), frame, clock, so} : null,};});- const lyrics = buildSongDocument(project).lyrics;+ const songDocument = buildSongDocument(project);+ const lyrics = songDocument.lyrics;+ const narrative = resolveNarrativeEvents(project, songDocument.sections, clock.fps);+ if (narrative.unresolved.length) throw new ServerError(`Rebind narrative events: ${narrative.unresolved.join(', ')}`, { status: 422, code: 'NARRATIVE_EVENT_UNRESOLVED' });+ if ((project.composition?.reactiveSections || []).some((entry) => !songDocument.sections.some((section) => section.id === entry.sectionId))) {+ throw new ServerError('Rebind reactive gain caps to current composition sections', { status: 422, code: 'NARRATIVE_SECTION_UNRESOLVED' });+ }const composition = project?.composition || {};return {version: 1,@@ -193,6 +200,10 @@ export function buildDocumentData(project, { media = new Map(), frame, clock, sodownbeats: song.downbeats,sections: song.sections,words: song.words || [],+ narrativeEvents: narrative.events,+ narrativeSections: songDocument.sections,+ reactiveSections: project.composition?.reactiveSections || [],+ features: analysis.features || null,},lyrics,lyricMarkers: Array.isArray(project?.lyricMarkers) ? project.lyricMarkers : [],@@ -237,7 +248,7 @@ async function stageDocumentData(compositionDir, data, media) {throw error;});}- await writeFile(join(compositionDir, 'portos-mv.js'), `window.PORTOS_MV = ${scriptJson(data)};\n`);+ await writeFile(join(compositionDir, 'portos-mv.js'), `window.PORTOS_MV = ${scriptJson(data)};\nwindow.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};\n`);}/**diff --git a/server/services/musicVideo/documentTemplates/layered/engine.js b/server/services/musicVideo/documentTemplates/layered/engine.jsindex f6312afff4..7c6e78647d 100644--- a/server/services/musicVideo/documentTemplates/layered/engine.js+++ b/server/services/musicVideo/documentTemplates/layered/engine.js@@ -24,6 +24,12 @@let H = MV.render.height;const FPS = MV.render.fps || 24;const DURATION = MV.render.durationSec;+ const eventSong = { ...MV.song, sections: GENERATED?.song?.sections || MV.song.narrativeSections || MV.song.sections,+ narrativeEvents: GENERATED?.song?.narrativeEvents || MV.song.narrativeEvents,+ reactiveSections: GENERATED?.song?.reactiveSections || MV.song.reactiveSections };+ const eventState = (t) => window.PORTOS_MV_EVENT_STATE+ ? window.PORTOS_MV_EVENT_STATE(eventSong, t, FPS)+ : { t, frame: Math.floor(t * FPS + 1e-6), reactiveGain: 0, activeEvents: [], hold: false };const canvas = document.getElementById('stage');const ctx = canvas.getContext('2d');let U = 1; // type/HUD unit: 1 at 1080px on the short side@@ -367,7 +373,7 @@// A card draws the whole scene layer: (t, localT, durationSec, scene, source).const CARDS = {// A title card from the scene's card text on its card colour.- title(t, lt, d, scene) {+ title(t, lt, d, scene, source, state) {ctx.fillStyle = scene.cardColor || C.ink; ctx.fillRect(0, 0, W, H);const str = (scene.cardText || scene.label || '').toUpperCase();if (!str) return;@@ -379,7 +385,7 @@ctx.translate(W / 2, H / 2 + px * 0.36); ctx.scale(lerp(1.2, 1, k), lerp(1.2, 1, k));text(str, 0, 0, F.stencil(px), C.paper, 'center');ctx.restore();- glitch(t, pulse(t, downs, 9) * 0.6);+ glitch(t, pulse(t, downs, 9) * state.reactiveGain);},};const cardFor = (scene) => (scene?.visualLayer === 'card' ? CARDS.title : null);@@ -390,19 +396,38 @@}// ---------- frame ----------- function render(t, scene, source) {+ function drawNarrativeEvents(state) {+ for (const event of state.activeEvents) {+ const k = event.progress;+ const label = event.kind === 'counter-change' ? `${event.text || event.name} ${Math.round(event.value)}`+ : event.kind === 'motif-transformation' ? `${event.motif || event.name}: ${k < 0.5 ? event.before || 'Before' : event.after || 'After'}`+ : event.text || event.name;+ let px = Math.round(96 * U);+ ctx.font = F.cond(px, 700);+ while (ctx.measureText(label).width > W * 0.8 && px > 12 * U) { px *= 0.9; ctx.font = F.cond(px, 700); }+ ctx.save();+ ctx.globalAlpha = event.kind === 'reveal' ? easeOut(clamp(k * 4)) : 1;+ ctx.translate(W / 2, H / 2);+ const scale = event.kind === 'impact' ? 1 + 0.2 * (1 - easeOut(clamp(k * 4))) : 1;+ ctx.scale(scale, scale);+ text(label, 0, px * 0.3, F.cond(px, 700), C.paper, 'center');+ ctx.restore();+ }+ }++ function render(t, scene, source, state) {ctx.fillStyle = C.ink; ctx.fillRect(0, 0, W, H);const authored = sectionFunction(t);if (scene) {const lt = t - scene.startSec; const d = scene.endSec - scene.startSec;const card = authored?.fn ? null : cardFor(scene);- if (card) card(t, lt, d, scene, source);+ if (card) card(t, lt, d, scene, source, state);else if (source) {const energetic = isHighEnergy(t) || scene.shotMode === 'performance';- const punch = 1 + 0.018 * pulse(t, energetic ? beats : downs, 8);+ const punch = 1 + 0.018 * pulse(t, energetic ? beats : downs, 8) * state.reactiveGain;drawCover(source, seg(t, scene.startSec, scene.endSec), moveFor(scene), punch);}- if (isHighEnergy(t)) glitch(t, pulse(t, downs, 8) * 0.5);+ if (isHighEnergy(t)) glitch(t, pulse(t, downs, 8) * state.reactiveGain);}if (authored?.fn) {const inset = 0.1;@@ -413,12 +438,14 @@song: GENERATED.song, palette: GENERATED.palette, section: authored.section,safe: { x: W * inset, y: H * inset, w: W * (1 - 2 * inset), h: H * (1 - 2 * inset) },karaoke: [], mediaKind: scene?.media?.kind || null, visualLayer: scene?.visualLayer || null,+ events: state.activeEvents, reactiveGain: state.reactiveGain, hold: state.hold,});} finally { ctx.restore(); }}vignette(0.5);grain(t, 0.09);drawHud(t);+ drawNarrativeEvents(state);const hero = HERO.find((c) => t >= c.startSec && t < c.endSec);if (hero) heroWords(t, hero);else {@@ -443,9 +470,11 @@layout({ width, height }) { resize(width, height); },async seek(t) {await ready;+ const state = eventState(t);+ t = state.t;const scene = sceneAt(t);const source = scene && !cardFor(scene) ? await sourceFor(scene, t) : null;- render(t, scene, source);+ render(t, scene, source, state);return true;},};