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: direct music video shots from cast, sets and lyric markers (#9242)

Adam Eivy47ef909fa49d
diff --git a/server/lib/README.md b/server/lib/README.md
index 370bef94d2..08ca208060 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -786,7 +786,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
+| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `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, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. |
| `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap). Dependency-free; the client create drawer imports it. |
| `albumLimits.js` | Album record length/count caps shared by the albums sanitizer and client editors. |
diff --git a/server/lib/musicVideoCreativeContext.js b/server/lib/musicVideoCreativeContext.js
index c25c726a9b..333362a84f 100644
--- a/server/lib/musicVideoCreativeContext.js
+++ b/server/lib/musicVideoCreativeContext.js
@@ -24,3 +24,17 @@ export function musicVideoCreativeContext(concept) {
});
return [...styles, ...(lines.length ? [BIBLE_HEADER, ...lines] : [])].join('\n').slice(0, CONTEXT_MAX);
}
+
+/** Bounded Cast & Sets bible; mood-board subjects are never location authority. */
+export function musicVideoDirectionContext(direction) {
+ if (!direction) return '';
+ const p = direction.protagonist || {};
+ return [
+ 'Cast & Sets direction (authoritative locations and wardrobe):',
+ 'The mood board is LOOK-ONLY: borrow palette, lighting and texture, never its literal locations, objects or narrative. Use the assigned set for each shot.',
+ `Story: ${trimTo(direction.logline, 400)} ${trimTo(direction.interpretation, 600)}`,
+ `Protagonist: ${[p.name, p.description, p.face, p.hair, p.signature, p.gesture, ...(p.rules || [])].filter(Boolean).map((s) => trimTo(s, 300)).join('; ')}`,
+ ...((direction.looks || []).slice(0, 8).map((l) => `Look ${trimTo(l.name, 80)}: ${trimTo(l.description, 300)}; chapters: ${trimTo(l.chapters, 120)}`)),
+ ...((direction.sets || []).slice(0, 8).map((s) => `Set ${trimTo(s.name, 80)}: ${trimTo(s.description, 300)}; lighting: ${trimTo(s.lighting, 120)}`)),
+ ].join('\n').slice(0, 6000);
+}
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 07272a3ba8..19a3823884 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -1,4 +1,4 @@
-import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
+import { musicVideoCreativeContext, musicVideoDirectionContext } from '../../lib/musicVideoCreativeContext.js';
/**
* Music Video — autonomous shot planner (#1855; multi-shot + lyrics #8964).
*
@@ -41,9 +41,8 @@ import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.j
import { ServerError } from '../../lib/errorHandler.js';
import { extractJson } from '../../lib/jsonExtract.js';
import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';
-import { planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';
-import { getProject, addProjectScenes } from './projects.js';
-import { deliveryNotesWithin } from './lyricMarkers.js';
+import { directShots, planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';
+import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';
const SCENE_LABEL_MAX = 120;
const SCENE_TEXT_MAX = 2000;
@@ -83,10 +82,33 @@ function sceneInputsFromShots(shots) {
loop: false,
lyricText: shot.lyricText,
visualIntent: shot.visualIntent,
+ ...(shot.visualLayer ? {
+ visualLayer: shot.visualLayer, shotMode: shot.shotMode,
+ ...(shot.cardText !== undefined ? { cardText: shot.cardText } : {}),
+ ...directedPrompts(shot),
+ } : {}),
};
});
}
+const PERFORMANCE_FRAME = 'Frontal medium close-up, face unobstructed, mouth fully visible for source-audio lip-sync.';
+
+// Deterministic direction survives no-provider and partial-response paths, and
+// prefixes generated prose so the assigned set/look and keyframe remain explicit.
+function directedPrompts(shot, generated = {}) {
+ const frame = [
+ shot.shotMode === 'performance' && PERFORMANCE_FRAME,
+ shot.protagonist && `Subject: ${quote([shot.protagonist.name, shot.protagonist.description, shot.protagonist.face, shot.protagonist.hair, shot.protagonist.signature].filter(Boolean).join('; '), 450)}`,
+ shot.set && `Location: ${quote(`${shot.set.name}. ${shot.set.description}. ${shot.set.lighting || ''}`, 550)}`,
+ shot.look && `Wardrobe: ${quote(`${shot.look.name}. ${shot.look.description}`, 350)}`,
+ generated.framePrompt || (shot.visualLayer === 'card' ? 'Graphic title card.' : 'Cinematic shot in the directed setting.'),
+ ].filter(Boolean).join(' ');
+ const motion = generated.prompt || (shot.visualLayer === 'card' ? 'Hold the graphic beat.'
+ : shot.shotMode === 'performance' ? `Perform to the source audio: ${shot.lyricText}`
+ : `Slow camera push; interpret the emotion and action of ${shot.lyricText || shot.visualIntent || shot.sectionLabel || 'this instrumental passage'}.`);
+ return { framePrompt: frame.slice(0, SCENE_TEXT_MAX), prompt: motion.slice(0, SCENE_TEXT_MAX) };
+}
+
const quote = (text, max) => {
const flat = String(text).replace(/\s+/g, ' ').trim();
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
@@ -100,6 +122,7 @@ const quote = (text, max) => {
*/
export function buildScenePlanPrompt(project, shots) {
const concept = project.concept || {};
+ const direction = project.castAndSets?.status === 'skipped' ? null : project.castAndSets?.direction;
const conceptLine = concept.prompt ? `Concept: ${concept.prompt}` : '';
const styleLine = concept.style ? `Visual style: ${concept.style}` : '';
// #8980: the treatment brief (when the director wrote one) steers the
@@ -126,6 +149,10 @@ export function buildScenePlanPrompt(project, shots) {
if (s.visualIntent) parts.push(`intent: ${quote(s.visualIntent, PROMPT_LYRIC_MAX)}`);
if (s.delivery?.length) parts.push(`delivery: ${quote(s.delivery.join('; '), PROMPT_LYRIC_MAX)}`);
if (s.hook) parts.push('OPENING HOOK');
+ if (s.visualLayer) parts.push(`layer: ${s.visualLayer}; mode: ${s.shotMode}`);
+ if (s.set) parts.push(`assigned set: ${quote(`${s.set.name}: ${s.set.description}; ${s.set.lighting || ''}`, 650)}`);
+ if (s.look) parts.push(`assigned look: ${quote(`${s.look.name}: ${s.look.description}`, 400)}`);
+ if (s.shotMode === 'performance') parts.push(PERFORMANCE_FRAME);
return parts.join('; ');
}).join('\n');
@@ -133,6 +160,7 @@ export function buildScenePlanPrompt(project, shots) {
${conceptLine}
${styleLine}
${musicVideoCreativeContext(concept)}
+${musicVideoDirectionContext(direction)}
${briefLines}
${guidanceLine}
@@ -144,7 +172,7 @@ For EACH shot above, propose the shot for a generative video model:
- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more static/lingering.
- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.
- The OPENING HOOK shot must grab attention immediately.
-${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.
+${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text in footage; assigned card layers use their explicit card text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Keep the assigned layer and shot mode: performance uses source-audio lip-sync and a frontal medium close-up with the mouth visible; cutaways show narrative action without lip-sync; cards are graphic beats.\n- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.
Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:
[{ "index": 0, "framePrompt": "<the opening reference still, ready to render>", "prompt": "<the shot's motion, ready to render>" }]`;
@@ -256,7 +284,7 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
// One shot list drives both the seeded scenes and the prompt, so prompt
// indices agree 1:1 with `sceneInputs`.
- const { shots, pacing } = planShots(sections, {
+ const { shots: tiledShots, pacing } = planShots(sections, {
downbeats: project.audioAnalysis?.downbeats,
beats: project.audioAnalysis?.beats,
lyricCues: project.lyricCues,
@@ -264,15 +292,7 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
pacing: project.pacing,
clipCapacitySec: resolveClipCapacitySec(project.videoSettings),
});
- // Lyric-sheet stage directions ([Spoken, close], [Shouts], [Stop — silence])
- // placed by the timed lines, so the first-pass prompts can frame them.
- const markers = project.lyricMarkers || [];
- if (markers.length) {
- for (const shot of shots) {
- const delivery = deliveryNotesWithin(project.lyricCues, markers, shot.startSec, shot.endSec);
- if (delivery.length) shot.delivery = delivery;
- }
- }
+ const shots = directShots(tiledShots, project);
const sceneInputs = sceneInputsFromShots(shots);
let promptsSeeded = false;
@@ -285,8 +305,11 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
promptsSeeded = true;
for (const [idx, fields] of seeded) {
if (!sceneInputs[idx]) continue;
- if (fields.framePrompt) sceneInputs[idx].framePrompt = fields.framePrompt;
- if (fields.prompt) sceneInputs[idx].prompt = fields.prompt;
+ if (shots[idx].visualLayer) Object.assign(sceneInputs[idx], directedPrompts(shots[idx], fields));
+ else {
+ if (fields.framePrompt) sceneInputs[idx].framePrompt = fields.framePrompt;
+ if (fields.prompt) sceneInputs[idx].prompt = fields.prompt;
+ }
}
} else {
promptsSkippedReason = reason;
@@ -300,7 +323,25 @@ export async function planProject(id, { seedPrompts = true, providerId, model, d
// flight would otherwise be silently dropped from this response and
// visually reverted by the client's replaceProject) and a redundant
// second getProject round trip.
- const { project: updated, scenes } = await addProjectScenes(id, sceneInputs);
+ const hasCards = sceneInputs.some((s) => s.visualLayer === 'card');
+ // Persist card scenes and the mode that renders them in the same transaction.
+ // Read the current composition under the lock so concurrent edits survive.
+ const { project: updated, scenes } = hasCards
+ ? await persistCardPlan(id, sceneInputs)
+ : await addProjectScenes(id, sceneInputs);
console.log(`🪄 Music Video plan: seeded ${scenes.length} scene${scenes.length === 1 ? '' : 's'} for ${id} (prompts ${promptsSeeded ? 'seeded' : `skipped: ${promptsSkippedReason || 'n/a'}`})`);
return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason, pacing };
}
+
+async function persistCardPlan(id, sceneInputs) {
+ const { addScenes } = await import('./projectsLogic.js');
+ const { normalizeComposition } = await import('./composition.js');
+ return mutateProjectRecord(id, (current) => {
+ const outcome = addScenes(current, sceneInputs);
+ // An authored whole-song code/document renderer remains the operator's choice.
+ if (!current.composition?.mode || current.composition.mode === 'concat') {
+ outcome.project.composition = normalizeComposition({ ...current.composition, mode: 'composed' });
+ }
+ return outcome;
+ });
+}
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index e688ce2c3c..f2537d65aa 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -8,10 +8,11 @@ vi.mock('../promptRunner.js', () => ({
vi.mock('./projects.js', () => ({
getProject: vi.fn(),
addProjectScenes: vi.fn(),
+ mutateProjectRecord: vi.fn(),
}));
import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';
-import { getProject, addProjectScenes } from './projects.js';
+import { getProject, addProjectScenes, mutateProjectRecord } from './projects.js';
import {
validSections,
buildScenePlanPrompt,
@@ -510,3 +511,114 @@ Here is my answer:
for (let i = 1; i < seededInputs.length; i++) expect(seededInputs[i].startSec).toBe(seededInputs[i - 1].endSec);
});
});
+
+// Regression: direction must affect persisted render-facing scenes, including
+// provider failure, rather than merely adding advice to an LLM prompt.
+describe('directed planner', () => {
+ function directedProject(backend = 'fal') {
+ return makeProject({
+ videoSettings: { backend }, pacing: { hookSec: 5, maxShotSec: 5 },
+ concept: { moodBoardStyle: 'Amber light in an example greenhouse' },
+ audioAnalysis: {
+ durationSec: 80, beats: Array.from({ length: 161 }, (_, i) => i / 2),
+ sections: [
+ { label: 'Verse', startSec: 0, endSec: 20 },
+ { label: 'Chorus', startSec: 20, endSec: 30 },
+ { label: 'Bridge', startSec: 30, endSec: 80 },
+ ],
+ },
+ lyricCues: Array.from({ length: 16 }, (_, i) => ({
+ text: i === 10 ? 'Rise' : `We follow the signal ${i}`, startSec: i * 5, endSec: (i + 1) * 5,
+ })),
+ lyricMarkers: [
+ { type: 'section', kind: 'chorus', label: 'Chorus', line: 4 },
+ { type: 'section', kind: 'bridge', label: 'Bridge', line: 6 },
+ { type: 'direction', kind: 'whispered', label: 'Whispered', line: 6 },
+ { type: 'direction', kind: 'spoken', label: 'Spoken, close', line: 7 },
+ { type: 'direction', kind: 'silence', label: 'Stop — silence', line: 8 },
+ { type: 'direction', kind: 'shouted', label: 'Shouts', line: 9 },
+ { type: 'direction', kind: 'note', label: 'Title moment', line: 11 },
+ ],
+ castAndSets: { status: 'approved', direction: {
+ protagonist: { name: 'Signal keeper', description: 'A solitary explorer', signature: 'silver badge' },
+ sets: [
+ { id: 'tower', name: 'Signal tower', description: 'An open steel platform', lighting: 'Dawn' },
+ { id: 'hall', name: 'Echo hall', description: 'A vaulted stone chamber', lighting: 'Blue lamps' },
+ ],
+ looks: [
+ { name: 'Field', description: 'Ochre coat', chapters: 'Verse, Bridge' },
+ { name: 'Stage', description: 'Silver jacket', chapters: 'Chorus' },
+ ],
+ songMap: [{ section: 0, setId: 'tower' }, { section: 1, setId: 'hall' }, { section: 2, setId: 'tower' }],
+ } },
+ });
+ }
+
+ async function runDirected(project, options = { seedPrompts: false }) {
+ getProject.mockResolvedValue(project);
+ // Exercise the real validated addScenes transform on a fresh record. A
+ // concurrent composition edit must survive the same atomic persistence.
+ mutateProjectRecord.mockImplementation(async (_id, transform) => transform({
+ ...project, composition: { mode: 'concat', style: { color: '#abcdef' } },
+ }));
+ return planProject('mv-1', options);
+ }
+
+ it('persists mapped sets/looks, supported performances and renderable cards without changing cuts', async () => {
+ const project = directedProject();
+ const { project: planned } = await runDirected(project);
+ const scenes = planned.scenes;
+ expect(scenes.map((s) => [s.startSec, s.endSec])).toEqual(Array.from({ length: 16 }, (_, i) => [i * 5, (i + 1) * 5]));
+ expect(scenes.slice(4, 8).every((s) => s.shotMode === 'performance')).toBe(true);
+ for (const scene of scenes.filter((s) => s.shotMode === 'performance')) {
+ expect(scene.framePrompt).toMatch(/Frontal medium close-up.*mouth fully visible/);
+ }
+ expect(scenes.slice(8, 12).every((s) => s.visualLayer === 'card')).toBe(true);
+ expect(scenes[8].cardText).toBe('');
+ expect(scenes[10].cardText).toBe('Rise');
+ expect(scenes[0].framePrompt).toMatch(/Signal keeper.*Signal tower.*Ochre coat/);
+ expect(scenes[4].framePrompt).toMatch(/Echo hall.*Silver jacket/);
+ expect(scenes.every((s) => !s.framePrompt.includes('greenhouse'))).toBe(true);
+ expect(scenes[0].prompt).toContain('We follow the signal 0');
+ expect(planned.composition).toMatchObject({ mode: 'composed', style: { color: '#abcdef' } });
+ });
+
+ it('caps performances by footage seconds and never assigns them to unsupported backends', async () => {
+ const project = directedProject();
+ project.lyricMarkers = [{ type: 'section', kind: 'chorus', label: 'Chorus', line: 0 }];
+ // Retain a card to exercise persisted output through the real transform.
+ for (const backend of ['fal', 'grok', 'local', null]) {
+ project.videoSettings.backend = backend;
+ const { project: planned } = await runDirected(project);
+ const duration = (list) => list.reduce((sum, s) => sum + s.endSec - s.startSec, 0);
+ const performances = planned.scenes.filter((s) => s.shotMode === 'performance');
+ expect(duration(performances)).toBeLessThanOrEqual(duration(planned.scenes.filter((s) => s.visualLayer === 'footage')) * 0.4);
+ expect(performances.length > 0).toBe(backend === 'fal');
+ }
+ });
+
+ it('gives the provider per-shot direction and preserves keyframe requirements after partial seeding', async () => {
+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'example' }, selectedModel: 'example' });
+ runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify([{ index: 4, framePrompt: 'Soft light', prompt: 'Gentle camera arc' }]) });
+ const { project } = await runDirected(directedProject(), { seedPrompts: true });
+ const prompt = runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(prompt).toContain('mood board is LOOK-ONLY');
+ expect(prompt).toContain('Protagonist: Signal keeper');
+ expect(prompt).toContain('assigned set: Echo hall');
+ expect(prompt).toContain('assigned look: Stage');
+ expect(prompt).toContain('delivery: Whispered');
+ expect(project.scenes[4].framePrompt).toMatch(/mouth fully visible.*Echo hall.*Soft light/);
+ expect(project.scenes[4].prompt).toBe('Gentle camera arc');
+ expect(project.scenes[5].framePrompt).toContain('mouth fully visible');
+ });
+
+ it('leaves skipped-stage projects on the legacy scene path even with retained direction', async () => {
+ const project = directedProject();
+ project.castAndSets.status = 'skipped';
+ addProjectScenes.mockResolvedValue({ project, scenes: [] });
+ await runDirected(project);
+ expect(mutateProjectRecord).not.toHaveBeenCalled();
+ const inputs = addProjectScenes.mock.calls[0][1];
+ expect(inputs.every((s) => s.shotMode === undefined && s.visualLayer === undefined && s.framePrompt === undefined)).toBe(true);
+ });
+});
diff --git a/server/services/musicVideo/shotPlan.js b/server/services/musicVideo/shotPlan.js
index fb54687129..69a3bde4ec 100644
--- a/server/services/musicVideo/shotPlan.js
+++ b/server/services/musicVideo/shotPlan.js
@@ -24,6 +24,8 @@
* invented. Pure and deterministic: same inputs → same plan.
*/
+import { performanceCapability } from '../../lib/musicVideoShotTiming.js';
+import { deliveryNotesWithin } from './lyricMarkers.js';
import { snapSectionsToGrid } from './audioAnalysis.js';
const EPS = 1e-6;
@@ -86,6 +88,7 @@ function resolvePacing(pacing, clipCapacitySec) {
/** Timed cues sorted by start, each with a resolved end (explicit, next cue, or capped open end). */
function timedCues(cues) {
const timed = (Array.isArray(cues) ? cues : [])
+ .map((c, line) => ({ ...c, line }))
.filter((c) => c && typeof c.text === 'string' && c.text.trim() && typeof c.startSec === 'number')
.slice()
.sort((a, b) => a.startSec - b.startSec);
@@ -93,7 +96,7 @@ function timedCues(cues) {
const next = timed[i + 1];
const openEnd = Math.min(c.startSec + OPEN_CUE_MAX_SEC, next ? next.startSec : Infinity);
const endSec = typeof c.endSec === 'number' && c.endSec > c.startSec ? c.endSec : openEnd;
- return { text: c.text.trim(), startSec: c.startSec, endSec };
+ return { line: c.line, text: c.text.trim(), startSec: c.startSec, endSec };
});
}
@@ -264,3 +267,53 @@ export function planShots(sections, {
});
return { shots, pacing: resolved };
}
+
+/** Enrich an already-tiled plan; never move a cut to accommodate direction. */
+export function directShots(shots, project) {
+ const direction = project.castAndSets?.status === 'skipped' ? null : project.castAndSets?.direction;
+ const cues = project.lyricCues || [];
+ const markers = project.lyricMarkers || [];
+ const timed = timedCues(cues);
+ const directed = shots.map((shot) => {
+ const delivery = deliveryNotesWithin(cues, markers, shot.startSec, shot.endSec);
+ if (!direction) return { ...shot, ...(delivery.length ? { delivery } : {}) };
+ const setId = direction.songMap?.find((m) => m.section === shot.sectionIndex)?.setId;
+ const set = direction.sets?.find((s) => s.id === setId)
+ || direction.sets?.find((s) => s.sections?.some((label) => label.toLowerCase() === shot.sectionLabel?.toLowerCase()))
+ || direction.sets?.[0];
+ const chapter = shot.sectionLabel?.toLowerCase();
+ const look = direction.looks?.find((l) => chapter && l.chapters?.toLowerCase().includes(chapter))
+ || direction.looks?.find((l) => direction.tests?.some((t) => t.setId === set?.id && t.look === l.name))
+ || direction.looks?.[0];
+ // Keep the cue's original index: markers refer to sheet order, not sorted time.
+ const line = phraseFor(timed, shot.startSec, shot.endSec)?.line ?? -1;
+ const activeSection = markers.filter((m) => m.type === 'section' && line >= m.line)
+ .sort((a, b) => a.line - b.line).at(-1);
+ const kinds = markers.filter((m) => m.type === 'direction' && (delivery.includes(m.label) || m.line === line));
+ const silence = kinds.some((m) => m.kind === 'silence');
+ const card = silence || kinds.some((m) => ['shouted', 'hits'].includes(m.kind) || /\btitle\b/i.test(m.label))
+ || (shot.lyricText && shot.lyricText.trim().split(/\s+/).length === 1);
+ const intimate = kinds.some((m) => m.kind === 'whispered' || (m.kind === 'spoken' && /close/i.test(m.label)));
+ const sungHook = ['chorus', 'hook', 'refrain'].includes(activeSection?.kind)
+ || /^(?:(?:final|last|double|big)\s+)?(?:chorus|hook|refrain)\b/i.test(shot.sectionLabel || '');
+ return {
+ ...shot, delivery, set, look, protagonist: direction.protagonist,
+ visualLayer: card ? 'card' : 'footage', shotMode: 'cutaway',
+ ...(card ? { cardText: silence ? '' : (shot.lyricText || project.name || '').slice(0, 500) } : {}),
+ performanceCandidate: !card && !!shot.lyricText && (intimate || (sungHook && kinds.length === 0)),
+ };
+ });
+ if (!direction) return directed;
+ const footageSec = directed.filter((s) => s.visualLayer === 'footage').reduce((sum, s) => sum + s.endSec - s.startSec, 0);
+ let used = 0;
+ if (performanceCapability(project.videoSettings?.backend)) {
+ for (const shot of directed) {
+ const duration = shot.endSec - shot.startSec;
+ if (shot.performanceCandidate && used + duration <= footageSec * 0.4 + EPS) {
+ shot.shotMode = 'performance';
+ used += duration;
+ }
+ }
+ }
+ return directed;
+}