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: plan music-video media with an explicit video allowance (#9299)

[._.]/ Adam Eivy7e245f038606
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsx
index 2461bb54bc..d85d3b56de 100644
--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx
+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx
@@ -1,4 +1,6 @@
import { useEffect, useState } from 'react';
+import { normalizeMusicVideoProductionPolicy } from '../../../../server/lib/musicVideoMediumPlan.js';
+import { formatCount } from '../../utils/formatters.js';
import { Link } from 'react-router';
import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuilder.js';
import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';
@@ -54,7 +56,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
}, [editing, universeId]);
const begin = () => {
- setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [], moodBoardId: project.visualSpec?.moodBoardId || '' });
+ setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [], moodBoardId: project.visualSpec?.moodBoardId || '', productionPolicy: normalizeMusicVideoProductionPolicy(project.productionPolicy) });
setSelectedCanon([]);
setNewName('');
setNewDescription('');
@@ -69,6 +71,11 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
};
const save = async () => {
if (!universeReady) { setError('Wait for the selected universe to load before saving.'); return; }
+ const percent = draft.productionPolicy.maxGeneratedVideoPercent;
+ if (percent === '' || !Number.isFinite(Number(percent)) || Number(percent) < 0 || Number(percent) > 100) {
+ setError('Choose a generated-video allowance from 0 to 100%.');
+ return;
+ }
setSaving(true);
setError('');
const concept = { subjects: draft.subjects, universeId: draft.universeId || null };
@@ -79,7 +86,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
}
const pulled = pullUniverseCanonReferences(canon, project.visualSpec?.references || []);
if (pulled.added) visualSpec.references = pulled.next;
- return onSave({ concept, visualSpec }).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));
+ return onSave({ concept, visualSpec, productionPolicy: { ...draft.productionPolicy, maxGeneratedVideoPercent: Number(percent) } }).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));
};
return <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0 break-words" aria-label="Creative setup">
@@ -110,6 +117,22 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
<p className="text-xs text-port-text-muted">Copies captions, notes and analyzed styles. Add images in Visual spec to condition frames.</p>
</div>
</div>
+ <div className="space-y-2">
+ <label htmlFor={idFor('strategy')} className="block text-xs">Production strategy</label>
+ <select id={idFor('strategy')} className={inputClass} value={draft.productionPolicy.strategy} onChange={(e) => setDraft((d) => ({ ...d, productionPolicy: normalizeMusicVideoProductionPolicy({ strategy: e.target.value }, d.productionPolicy) }))}>
+ <option value="legacy">Legacy / manual workflow</option>
+ <option value="code-first">Code-first medium planning</option>
+ </select>
+ {draft.productionPolicy.strategy === 'code-first' && <>
+ <label htmlFor={idFor('selective-video')} className="flex items-center gap-2 text-xs min-h-[44px]">
+ <input id={idFor('selective-video')} type="checkbox" checked={Number(draft.productionPolicy.maxGeneratedVideoPercent) > 0} onChange={(e) => setDraft((d) => ({ ...d, productionPolicy: { ...d.productionPolicy, maxGeneratedVideoPercent: e.target.checked ? 20 : 0 } }))} />
+ Allow selective generated footage
+ </label>
+ <label htmlFor={idFor('video-allowance')} className="block text-xs">Maximum generated video (% of final song time)</label>
+ <input id={idFor('video-allowance')} type="number" min="0" max="100" step="any" className={inputClass} value={draft.productionPolicy.maxGeneratedVideoPercent} onChange={(e) => setDraft((d) => ({ ...d, productionPolicy: { ...d.productionPolicy, maxGeneratedVideoPercent: e.target.value } }))} />
+ <p className="text-xs text-port-text-muted">Start with code and images. This policy plans final-edit seconds; it does not change the renderer or enforce generation budgets in manual controls.</p>
+ </>}
+ </div>
{loading && <p className="text-xs">Loading canon…</p>}
{universeReady && universe && <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">{kinds.map(([kind, label]) => <div key={kind}>
<label htmlFor={idFor(`pick-${kind}`)} className="text-xs">Select {label.toLowerCase()}</label>
@@ -136,6 +159,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })
{(newName.trim() || newDescription.trim()) && <p className="text-xs text-port-text-muted">Add the new subject to the production before saving.</p>}
<div className="flex flex-wrap gap-3"><button type="button" onClick={save} disabled={!universeReady || !!newName.trim() || !!newDescription.trim()} className="bg-port-accent text-white rounded px-3 py-2 text-sm disabled:opacity-50">{saving ? 'Saving…' : 'Save creative setup'}</button><button type="button" onClick={() => setEditing(false)} className="text-sm">Cancel</button></div>
</fieldset>}
+ {!editing && project.productionPolicy?.strategy === 'code-first' && <p className="text-xs text-port-text-muted">Code-first plan · generated video allowance {formatCount(project.productionPolicy.maxGeneratedVideoPercent, { maximumFractionDigits: 3 })}% of final song time</p>}
{error && <p role="alert" className="text-sm text-port-error">{error}</p>}
</section>;
}
diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
index 2d3580bfa6..e69e8a4e68 100644
--- a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx
@@ -88,3 +88,17 @@ describe('creative setup', () => {
expect(screen.getByLabelText('Universe').value).toBe('u2');
});
});
+
+it('defaults code-first to zero, offers 20% selective footage, and saves the explicit allowance', async () => {
+ const onSave = open();
+ fireEvent.change(screen.getByLabelText('Production strategy'), { target: { value: 'code-first' } });
+ const allowance = screen.getByLabelText('Maximum generated video (% of final song time)');
+ expect(allowance.value).toBe('0');
+ fireEvent.click(screen.getByLabelText('Allow selective generated footage'));
+ expect(allowance.value).toBe('20');
+ fireEvent.change(allowance, { target: { value: '12.5' } });
+ fireEvent.click(screen.getByText('Save creative setup'));
+ await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 12.5 },
+ })));
+});
diff --git a/client/src/components/musicVideo/MediumPlanSummary.jsx b/client/src/components/musicVideo/MediumPlanSummary.jsx
new file mode 100644
index 0000000000..260236db8b
--- /dev/null
+++ b/client/src/components/musicVideo/MediumPlanSummary.jsx
@@ -0,0 +1,23 @@
+import { MUSIC_VIDEO_MEDIUM_LABELS, summarizeMusicVideoMediumPlan } from '../../../../server/lib/musicVideoMediumPlan.js';
+import { formatCount, formatTimecode } from '../../utils/formatters.js';
+
+/** Same interval accounting as Apply; these are edit seconds, never a spend estimate. */
+export default function MediumPlanSummary({ project, plan = summarizeMusicVideoMediumPlan(project) }) {
+ if (plan.strategy !== 'code-first') return null;
+ const labels = new Map((project.scenes || []).map((s) => [s.sceneId, s.label || s.sectionLabel || 'Scene']));
+ return <section aria-label="Medium plan" className="rounded border border-port-border p-2 text-xs space-y-2">
+ <p className="font-medium">Code-first plan · generated video {formatCount(plan.generatedSec, { maximumFractionDigits: 3 })} / {formatCount(plan.allowedGeneratedSec, { maximumFractionDigits: 3 })} seconds ({formatCount(plan.maxGeneratedVideoPercent, { maximumFractionDigits: 3 })}% of the song)</p>
+ <p className="text-port-text-muted">Planning only: Apply saves direction. It does not generate media, select a renderer, or make procedural rendering ready. Manual generation and rendering still use their existing controls.</p>
+ <p>{Object.entries(plan.secondsByMedium).map(([medium, seconds]) => `${MUSIC_VIDEO_MEDIUM_LABELS[medium]}: ${formatCount(seconds, { maximumFractionDigits: 3 })}s`).join(' · ')}</p>
+ <p className="text-port-text-muted">Overlapping intervals count once per medium. Provider minimum clip lengths affect spend, not this allowance.</p>
+ {plan.exceptions.length > 0 && <div>
+ <p className="font-medium">Generated-footage exceptions</p>
+ <ul className="list-disc pl-4">{plan.exceptions.map((entry) => <li key={entry.sceneId}>
+ {labels.get(entry.sceneId) || 'Scene'} · {formatTimecode(entry.startSec)}–{formatTimecode(entry.endSec)} · {entry.rationale || 'Add a rationale.'}
+ </li>)}</ul>
+ </div>}
+ {plan.unresolved.length > 0 && <ul className="space-y-1">{plan.unresolved.map((item, index) => <li key={`${item.sceneId || 'plan'}-${index}`} className={item.blocking ? 'text-port-error' : 'text-port-warning'}>
+ {item.sceneId ? `${labels.get(item.sceneId) || 'Scene'}: ` : ''}{item.message}
+ </li>)}</ul>}
+ </section>;
+}
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index f15ba0ffb8..7a5839884a 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -1,3 +1,4 @@
+import { MUSIC_VIDEO_MEDIUM_LABELS } from '../../../../server/lib/musicVideoMediumPlan.js';
import { useRef, useState } from 'react';
import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';
import { formatDurationSec, formatUsd } from '../../utils/formatters.js';
@@ -169,7 +170,7 @@ export default function SceneCard({
{/* Applied treatment direction (#8980) — appended to both generated prompts. */}
{scene.direction && (
<p className="break-words" title={scene.direction.frameClause}>
- Direction: {scene.direction.mode}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}
+ Direction: {scene.direction.mode}{scene.direction.medium ? ` · planned ${MUSIC_VIDEO_MEDIUM_LABELS[scene.direction.medium] || scene.direction.medium}${scene.direction.mediumPinned ? ' (pinned)' : ''}` : ''}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}
{scene.direction.typographyRole !== 'none' ? ` · ${scene.direction.typographyRole} text, ${scene.direction.negativeSpace} region kept clear` : ' · no text'}
</p>
)}
diff --git a/client/src/components/musicVideo/TreatmentApplyReview.jsx b/client/src/components/musicVideo/TreatmentApplyReview.jsx
index 3d9482788d..f4ed63968f 100644
--- a/client/src/components/musicVideo/TreatmentApplyReview.jsx
+++ b/client/src/components/musicVideo/TreatmentApplyReview.jsx
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import MediumPlanSummary from './MediumPlanSummary.jsx';
import { ClipboardCheck, AlertTriangle } from 'lucide-react';
const PROMPT_LABELS = {
@@ -58,6 +59,7 @@ export default function TreatmentApplyReview({ project, api }) {
{preview && (
<div className="space-y-2 rounded border border-port-border p-2 text-xs">
+ {preview.mediumPlan && <MediumPlanSummary project={project} plan={preview.mediumPlan} />}
{preview.stale.length > 0 && (
<ul className="space-y-1">
{preview.stale.map((s) => (
diff --git a/client/src/components/musicVideo/TreatmentPanel.jsx b/client/src/components/musicVideo/TreatmentPanel.jsx
index 47ea6116e4..d9da1d85db 100644
--- a/client/src/components/musicVideo/TreatmentPanel.jsx
+++ b/client/src/components/musicVideo/TreatmentPanel.jsx
@@ -4,6 +4,7 @@ import useFieldDraft from '../../hooks/useFieldDraft.js';
import useProviderModels from '../../hooks/useProviderModels.js';
import ProviderModelSelector from '../ProviderModelSelector.jsx';
import { formatTimecode } from '../../utils/formatters.js';
+import MediumPlanSummary from './MediumPlanSummary.jsx';
import TreatmentShotList from './TreatmentShotList.jsx';
import TreatmentProofs from './TreatmentProofs.jsx';
import TreatmentApplyReview from './TreatmentApplyReview.jsx';
@@ -239,6 +240,7 @@ export default function TreatmentPanel({ project, treatment: api }) {
{arc.balance.rationale && <p className="text-port-text-muted">{arc.balance.rationale}</p>}
</div>
</div>
+ <MediumPlanSummary project={project} />
<TreatmentShotList project={project} treatment={t} onSave={api.save} />
<TreatmentProofs project={project} treatment={t} onReview={api.reviewProof} />
<TreatmentApplyReview project={project} api={api} />
diff --git a/client/src/components/musicVideo/TreatmentPanel.test.jsx b/client/src/components/musicVideo/TreatmentPanel.test.jsx
index 22ec136911..83e9c22b48 100644
--- a/client/src/components/musicVideo/TreatmentPanel.test.jsx
+++ b/client/src/components/musicVideo/TreatmentPanel.test.jsx
@@ -202,3 +202,41 @@ describe('TreatmentPanel edits and compile', () => {
]);
});
});
+
+it('shows union totals and explicit exceptions before Apply, and pins a director-selected medium', async () => {
+ const planned = {
+ ...PROJECT,
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 20 },
+ audioAnalysis: { durationSec: 100, sections: [] },
+ scenes: [
+ { ...PROJECT.scenes[0], startSec: 0, endSec: 15 },
+ { ...PROJECT.scenes[1], startSec: 10, endSec: 20 },
+ ],
+ treatment: {
+ ...TREATMENT,
+ shotDirections: ['s1', 's2'].map((sceneId) => ({
+ sceneId, medium: 'generated-footage', mediumRationale: 'Visible payoff', mediumPinned: false,
+ mode: 'cutaway', route: 'generated', typographyRole: 'none', negativeSpace: 'none',
+ })),
+ },
+ };
+ api.updateMusicVideoTreatment.mockImplementation(async (_id, patch) => ({
+ treatment: {
+ ...planned.treatment, revision: 4,
+ shotDirections: planned.treatment.shotDirections.map((d) => d.sceneId === 's1' ? { ...d, ...patch.shotDirections[0] } : d),
+ },
+ }));
+ render(<Harness initial={planned} />);
+ expect(screen.getByText(/generated video 20 \/ 20 seconds/)).toBeTruthy();
+ expect(screen.getByText('Generated-footage exceptions')).toBeTruthy();
+ expect(screen.getByText(/Planning only: Apply saves direction/)).toBeTruthy();
+ expect(api.applyMusicVideoTreatment).not.toHaveBeenCalled();
+ fireEvent.change(screen.getAllByLabelText('Planned medium')[0], { target: { value: 'still' } });
+ await waitFor(() => expect(api.updateMusicVideoTreatment).toHaveBeenCalledWith(
+ 'mv-1',
+ { baseRevision: 3, shotDirections: [{ sceneId: 's1', medium: 'still', mediumPinned: true }] },
+ { silent: true },
+ ));
+ await waitFor(() => expect(screen.getAllByLabelText('Keep medium on recompile')[0].checked).toBe(true));
+ expect(screen.getByText(/generated video 10 \/ 20 seconds/)).toBeTruthy();
+});
diff --git a/client/src/components/musicVideo/TreatmentShotList.jsx b/client/src/components/musicVideo/TreatmentShotList.jsx
index 12aece5a1f..426a53e87f 100644
--- a/client/src/components/musicVideo/TreatmentShotList.jsx
+++ b/client/src/components/musicVideo/TreatmentShotList.jsx
@@ -1,3 +1,4 @@
+import { MUSIC_VIDEO_MEDIUM_LABELS } from '../../../../server/lib/musicVideoMediumPlan.js';
import useFieldDraft from '../../hooks/useFieldDraft.js';
import { formatTimecode } from '../../utils/formatters.js';
@@ -57,10 +58,19 @@ export default function TreatmentShotList({ project, treatment, onSave }) {
{scene?.lyricText ? <span className="text-port-text-muted truncate max-w-[16rem]">· “{scene.lyricText}”</span> : <span className="text-port-text-muted">· instrumental</span>}
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-1.5">
+ <DirectionSelect id={idFor(d.sceneId, 'medium')} label="Planned medium" value={d.medium || ''}
+ options={[['', 'Not planned'], ...Object.entries(MUSIC_VIDEO_MEDIUM_LABELS)]} onChange={(medium) => medium && save(d.sceneId, { medium, mediumPinned: true })} />
+ <DirectionText id={idFor(d.sceneId, 'medium-rationale')} label="Medium rationale" value={d.mediumRationale || ''} maxLength={1000}
+ onCommit={(mediumRationale) => save(d.sceneId, { mediumRationale })} />
+ <label htmlFor={idFor(d.sceneId, 'medium-pin')} className="flex items-center gap-1.5 text-xs min-h-[44px]">
+ <input id={idFor(d.sceneId, 'medium-pin')} type="checkbox" checked={d.mediumPinned === true}
+ onChange={(e) => save(d.sceneId, { mediumPinned: e.target.checked })} />
+ Keep medium on recompile
+ </label>
<DirectionSelect id={idFor(d.sceneId, 'mode')} label="Mode" value={d.mode}
options={MODES.map((m) => [m, m])} onChange={(mode) => save(d.sceneId, { mode })} />
- <DirectionSelect id={idFor(d.sceneId, 'route')} label="Route" value={d.route}
- options={ROUTES} onChange={(route) => save(d.sceneId, { route })} />
+ {project.productionPolicy?.strategy !== 'code-first' && <DirectionSelect id={idFor(d.sceneId, 'route')} label="Route" value={d.route}
+ options={ROUTES} onChange={(route) => save(d.sceneId, { route })} />}
<DirectionSelect id={idFor(d.sceneId, 'type')} label="Typography" value={d.typographyRole}
options={TYPE_ROLES} onChange={(typographyRole) => save(d.sceneId, { typographyRole })} />
<DirectionSelect id={idFor(d.sceneId, 'space')} label="Reserved region" value={d.negativeSpace}
diff --git a/server/lib/README.md b/server/lib/README.md
index 431b020a3d..77f4949737 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -801,3 +801,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoAspect.js` | `musicVideoAspect(project)` (treatment brief aspect, default 16:9), `MUSIC_VIDEO_FRAME_GEN_SIZES` and `musicVideoFrameGenSize(project)`: the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. `musicVideoAtAspect(project, aspect)` re-frames the project for one render (a vertical social cut) without touching the record. Shared by `productionDispatch.js`, `documentRender.js` and the client board. |
| `musicVideoMotion.js` | `MOTION_CONTINUITY_CLAUSE`: the clause every Music Video motion (i2v) prompt ends with, pinning the reference frame's lighting, time of day and palette. Shared by `handoff.js` and the client board. |
| `musicVideoConditioning.js` | `musicVideoStyleImages`, `musicVideoStylePrompt`, `musicVideoStyleBasis`, and `musicVideoStyleReferenceCapacity` supply bounded moodboard conditioning and text fallback; `musicVideoConditioningReferences(project, scene)` selects the approved character sheet and scene's mapped set plate, with capped project-wide fallback; shared by board and production. |
+| `musicVideoMediumPlan.js` | `normalizeMusicVideoProductionPolicy`, `planMusicVideoMedia`, and `summarizeMusicVideoMediumPlan`: pinned shot media and union-of-intervals video allowance shared by treatment planning and Board review. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 313313467e..65b5598c5a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -783,3 +783,5 @@ export * from './defaultRequestBody.js';
export * from './musicVideoConditioning.js';
export * from './musicVideoAspect.js';
export * from './musicVideoMotion.js';
+
+export * from './musicVideoMediumPlan.js';
diff --git a/server/lib/musicVideoMediumPlan.js b/server/lib/musicVideoMediumPlan.js
new file mode 100644
index 0000000000..834ba25afb
--- /dev/null
+++ b/server/lib/musicVideoMediumPlan.js
@@ -0,0 +1,126 @@
+/**
+ * Planning-only medium policy. Final-edit seconds are an interval union, not
+ * provider clip lengths or a sum that double-counts overlapping footage.
+ * Dependency-free so the Board and server Apply use the same accounting.
+ */
+export const MUSIC_VIDEO_MEDIA = ['procedural', 'still', 'existing-footage', 'generated-footage'];
+export const MUSIC_VIDEO_MEDIUM_LABELS = {
+ procedural: 'Procedural',
+ still: 'Still',
+ 'existing-footage': 'Existing footage',
+ 'generated-footage': 'Generated footage',
+};
+
+export function normalizeMusicVideoProductionPolicy(patch, base = null) {
+ const strategy = (patch?.strategy ?? base?.strategy) === 'code-first' ? 'code-first' : 'legacy';
+ const defaultPercent = strategy === 'code-first' ? 0 : 100;
+ const percent = patch?.maxGeneratedVideoPercent
+ ?? (base?.strategy === strategy ? base.maxGeneratedVideoPercent : defaultPercent);
+ return {
+ strategy,
+ maxGeneratedVideoPercent: typeof percent === 'number' && Number.isFinite(percent)
+ ? Math.max(0, Math.min(100, percent)) : defaultPercent,
+ };
+}
+
+function unionSeconds(intervals) {
+ let end = 0;
+ let total = 0;
+ for (const [start, stop] of intervals.sort((a, b) => a[0] - b[0])) {
+ total += Math.max(0, stop - Math.max(start, end));
+ end = Math.max(end, stop);
+ }
+ return total;
+}
+
+/** Read current scene timing on every call; retiming cannot retain an old allowance. */
+export function summarizeMusicVideoMediumPlan(project, directions = project?.treatment?.shotDirections || []) {
+ const policy = normalizeMusicVideoProductionPolicy(project?.productionPolicy);
+ const durationSec = project?.audioAnalysis?.durationSec;
+ const validDuration = typeof durationSec === 'number' && Number.isFinite(durationSec) && durationSec > 0;
+ const intervals = Object.fromEntries(MUSIC_VIDEO_MEDIA.map((medium) => [medium, []]));
+ const byScene = new Map(directions.map((d) => [d.sceneId, d]));
+ const unresolved = [];
+ const exceptions = [];
+ const codeFirst = policy.strategy === 'code-first';
+ for (const scene of project?.scenes || []) {
+ const d = byScene.get(scene.sceneId);
+ if (!d || !MUSIC_VIDEO_MEDIA.includes(d.medium)) {
+ if (codeFirst) unresolved.push({ sceneId: scene.sceneId, blocking: true, message: 'Compile a medium plan for this shot.' });
+ continue;
+ }
+ const { startSec, endSec } = scene;
+ const valid = validDuration && Number.isFinite(startSec) && Number.isFinite(endSec)
+ && startSec >= 0 && endSec > startSec && endSec <= durationSec + 0.000001;
+ if (!valid) {
+ if (codeFirst) unresolved.push({ sceneId: scene.sceneId, blocking: true, message: 'This shot needs a valid final-edit interval within the song.' });
+ } else {
+ intervals[d.medium].push([startSec, Math.min(endSec, durationSec)]);
+ }
+ if (d.medium === 'generated-footage') exceptions.push({
+ sceneId: scene.sceneId, startSec, endSec, rationale: d.mediumRationale || '',
+ });
+ if (codeFirst && d.medium === 'existing-footage' && !scene.videoHistoryId) {
+ unresolved.push({ sceneId: scene.sceneId, blocking: false, message: 'Select existing footage before executing this plan.' });
+ }
+ if (codeFirst && d.mode === 'performance' && !['existing-footage', 'generated-footage'].includes(d.medium)) {
+ unresolved.push({ sceneId: scene.sceneId, blocking: false, message: 'Visible performance is unresolved with this medium; supply footage or explicitly revise the plan and allowance.' });
+ }
+ }
+ const secondsByMedium = Object.fromEntries(MUSIC_VIDEO_MEDIA.map((medium) => [medium, unionSeconds(intervals[medium])]));
+ const generatedSec = secondsByMedium['generated-footage'];
+ const allowedGeneratedSec = validDuration ? durationSec * policy.maxGeneratedVideoPercent / 100 : 0;
+ if (codeFirst && !validDuration) unresolved.push({ blocking: true, message: 'Analyze the song duration before applying a medium plan.' });
+ if (codeFirst && generatedSec > allowedGeneratedSec + 0.000001) {
+ unresolved.push({ blocking: true, message: 'Generated footage exceeds the final-edit allowance. Shorten its intervals, change its medium, or explicitly increase the allowance.' });
+ }
+ return {
+ ...policy, durationSec: validDuration ? durationSec : null, allowedGeneratedSec,
+ generatedSec, secondsByMedium, exceptions, unresolved,
+ blocked: unresolved.some((item) => item.blocking),
+ };
+}
+
+/** Retain director pins; allocate optional generated shots only within the union budget. */
+export function planMusicVideoMedia(project, directions) {
+ const policy = normalizeMusicVideoProductionPolicy(project.productionPolicy);
+ const codeFirst = policy.strategy === 'code-first';
+ const scenes = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
+ const previous = new Map((project.treatment?.shotDirections || []).map((d) => [d.sceneId, d]));
+ const planned = directions.map((d) => {
+ const scene = scenes.get(d.sceneId);
+ const prior = previous.has(d.sceneId) ? previous.get(d.sceneId) : scene?.direction;
+ if (prior?.mediumPinned && MUSIC_VIDEO_MEDIA.includes(prior.medium)) {
+ return { ...d, medium: prior.medium, mediumRationale: prior.mediumRationale, mediumPinned: true };
+ }
+ let medium = d.medium;
+ let rationale = d.mediumRationale;
+ const manualLayer = scene?.visualLayer === 'still' || scene?.visualLayer === 'card';
+ if (manualLayer) {
+ medium = scene.visualLayer === 'still' ? 'still' : 'procedural';
+ rationale = 'Retain the director-selected visual layer.';
+ } else if (scene?.videoHistoryId) {
+ medium = 'existing-footage';
+ rationale = 'Reuse the selected footage without a new video request.';
+ } else if (!MUSIC_VIDEO_MEDIA.includes(medium)) {
+ medium = codeFirst ? (scene?.referenceImageId ? 'still' : 'procedural')
+ : d.route === 'code-2d' ? (scene?.lyricText ? 'procedural' : 'still')
+ : d.route === 'supplied-asset' ? 'existing-footage' : 'generated-footage';
+ rationale = codeFirst ? 'Carry the section motif and transitions with code or available images.'
+ : 'Retain the legacy treatment route.';
+ }
+ return { ...d, medium, mediumRationale: rationale || d.rationale || 'Director-selected medium.', mediumPinned: manualLayer };
+ });
+ // Reserve pinned exceptions first. Automatic suggestions never displace a pin.
+ const accepted = planned.map((d) => codeFirst && d.medium === 'generated-footage' && !d.mediumPinned
+ ? { ...d, medium: 'procedural' } : d);
+ for (let i = 0; codeFirst && i < planned.length; i++) {
+ if (planned[i].medium !== 'generated-footage' || planned[i].mediumPinned) continue;
+ const candidate = [...accepted];
+ candidate[i] = planned[i];
+ const summary = summarizeMusicVideoMediumPlan(project, candidate);
+ if (!summary.blocked && policy.maxGeneratedVideoPercent > 0) accepted[i] = planned[i];
+ else accepted[i] = { ...accepted[i], mediumRationale: 'Use procedural visuals to stay within the generated-video allowance; any visible performance remains unresolved.' };
+ }
+ return codeFirst ? accepted : planned;
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 80b929d475..ade7864f92 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -9,6 +9,7 @@
*/
import { z } from 'zod';
+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';
import {
@@ -448,8 +449,16 @@ export const musicVideoTreatmentMotifSchema = z.object({
rationale: treatmentText(1000),
}).strict();
+export const musicVideoProductionPolicySchema = z.object({
+ strategy: z.enum(['legacy', 'code-first']).optional(),
+ maxGeneratedVideoPercent: z.number().min(0).max(100).optional(),
+}).strict();
+
export const musicVideoShotDirectionPatchSchema = z.object({
sceneId: z.string().min(1).max(64),
+ medium: z.enum(MUSIC_VIDEO_MEDIA).optional(),
+ mediumRationale: treatmentText(1000),
+ mediumPinned: z.boolean().optional(),
mode: z.enum(MUSIC_VIDEO_TREATMENT_SHOT_MODES).optional(),
route: z.enum(MUSIC_VIDEO_SHOT_ROUTES).optional(),
focalSubject: treatmentText(500),
@@ -751,6 +760,7 @@ export const musicVideoCastAndSetsRegenerateSchema = z.object({
}).strict();
export const musicVideoProjectCreateSchema = z.object({
+ productionPolicy: musicVideoProductionPolicySchema.optional(),
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
// The source audio: either a music-library track or an uploaded file basename
@@ -772,6 +782,7 @@ export const musicVideoProjectCreateSchema = z.object({
}).strict();
export const musicVideoProjectUpdateSchema = z.object({
+ productionPolicy: musicVideoProductionPolicySchema.optional(),
name: z.string().min(1).max(200).optional(),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
status: z.enum(MUSIC_VIDEO_STATUSES).optional(),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 5c6bb9c1f7..3a800bc73d 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -650,7 +650,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v11 = phrase-alignment confidence (`lyricCues[].matched`). Older peers
// drop it on edits or retain stale confidence after audio changes. Existing
// records need no rewrite: absent means alignment has not measured it.
- musicVideoProjects: 11,
+ // v12 = code-first production policy and pinned per-shot medium plans.
+ // Older treatment writers drop these fields and can reinterpret them as
+ // footage. Absent policy remains legacy; no existing record needs rewriting.
+ musicVideoProjects: 12,
// 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/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.js
index 2f3567598e..cb8e836d53 100644
--- a/server/routes/musicVideoTreatment.test.js
+++ b/server/routes/musicVideoTreatment.test.js
@@ -520,3 +520,143 @@ it('persists a treatment look once and invalidates its application when the mood
const preview = await request(app).get(`${base(project.id)}/treatment/apply-preview`);
expect(preview.body.stale.some((entry) => entry.input === 'visualSpec')).toBe(true);
});
+
+describe('code-first medium planning (#9299)', () => {
+ async function hundredSecondPlan(percent = 0) {
+ const created = await request(app).post('/api/music-video').send({
+ name: 'Synthetic medium plan',
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: percent },
+ });
+ expect(created.status).toBe(201);
+ const id = created.body.id;
+ await projects.setProjectAnalysis(id, {
+ ...ANALYSIS, durationSec: 100, sections: [{ label: 'Example section', startSec: 0, endSec: 100, energy: 0.5 }],
+ });
+ await projects.addProjectScenes(id, [
+ { label: 'First', startSec: 0, endSec: 15, prompt: 'Director motion', framePrompt: 'Director frame', lyricText: 'An invented lyric' },
+ { label: 'Overlap', startSec: 10, endSec: 20 },
+ { label: 'Rest', startSec: 20, endSec: 100 },
+ ]);
+ const compiled = await compile(id, { baseRevision: 0, useAi: false });
+ expect(compiled.status).toBe(200);
+ return compiled.body.project;
+ }
+
+ it('persists a zero-video plan, shows unmet performance, and applies without changing manual prompts, takes or renderer', async () => {
+ const project = await hundredSecondPlan();
+ const treatment = project.treatment;
+ expect(treatment.shotDirections.map((d) => d.medium)).not.toContain('generated-footage');
+ expect(treatment.shotDirections.every((d) => d.mediumRationale)).toBe(true);
+ const sceneId = project.scenes[0].sceneId;
+ seedImage('medium-still.png');
+ await projects.appendSceneTakes(project.id, sceneId, [{ kind: 'image', assetId: 'medium-still.png', source: 'imported' }]);
+ const before = await reload(project.id);
+ const preview = await request(app).get(`${base(project.id)}/treatment/apply-preview`);
+ expect(preview.body.mediumPlan).toMatchObject({ generatedSec: 0, allowedGeneratedSec: 0, blocked: false });
+ expect(preview.body.mediumPlan.unresolved).toEqual(expect.arrayContaining([expect.objectContaining({ message: expect.stringMatching(/performance is unresolved/) })]));
+ expect(preview.body.scenes.every((s) => Object.keys(s.renderFields).length === 0)).toBe(true);
+ const applied = await request(app).post(`${base(project.id)}/treatment/apply`).send({ revision: treatment.revision });
+ expect(applied.status).toBe(200);
+ const stored = await reload(project.id);
+ expect(stored.productionPolicy).toEqual({ strategy: 'code-first', maxGeneratedVideoPercent: 0 });
+ expect(stored.composition).toEqual(before.composition);
+ expect(stored.scenes[0]).toMatchObject({
+ prompt: 'Director motion', framePrompt: 'Director frame', takes: before.scenes[0].takes,
+ referenceImageId: before.scenes[0].referenceImageId, shotMode: 'cutaway', visualLayer: 'footage',
+ direction: { medium: 'procedural' },
+ });
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('counts overlapping generated intervals once, rejects 21 seconds at 20%, and rechecks live timing on Apply', async () => {
+ const project = await hundredSecondPlan(20);
+ const [first, overlap] = project.scenes;
+ const edited = await patchTreatment(project.id, {
+ baseRevision: project.treatment.revision,
+ shotDirections: [first, overlap].map((s) => ({ sceneId: s.sceneId, medium: 'generated-footage', mediumRationale: 'The shared payoff.' })),
+ });
+ expect(edited.status).toBe(200);
+ let preview = await request(app).get(`${base(project.id)}/treatment/apply-preview`);
+ expect(preview.body.mediumPlan).toMatchObject({ generatedSec: 20, allowedGeneratedSec: 20, blocked: false });
+ await projects.updateScene(project.id, overlap.sceneId, { endSec: 21 });
+ preview = await request(app).get(`${base(project.id)}/treatment/apply-preview`);
+ expect(preview.body).toMatchObject({ blocked: true, mediumPlan: { generatedSec: 21 } });
+ const rejected = await request(app).post(`${base(project.id)}/treatment/apply`).send({ revision: edited.body.treatment.revision });
+ expect(rejected.status).toBe(422);
+ expect(rejected.body.code).toBe('MEDIUM_PLAN_UNRESOLVED');
+ const invalidEdit = await patchTreatment(project.id, {
+ baseRevision: edited.body.treatment.revision,
+ shotDirections: [{ sceneId: first.sceneId, medium: 'generated-footage' }],
+ });
+ expect(invalidEdit.status).toBe(422);
+ await projects.updateScene(project.id, overlap.sceneId, { endSec: 20 });
+ const applied = await request(app).post(`${base(project.id)}/treatment/apply`).send({ revision: edited.body.treatment.revision });
+ expect(applied.status).toBe(200);
+ });
+
+ it('retains manual still/procedural pins across AI re-planning, clone and wire round trips', async () => {
+ const project = await hundredSecondPlan();
+ const pinned = await patchTreatment(project.id, {
+ baseRevision: project.treatment.revision,
+ shotDirections: [
+ { sceneId: project.scenes[0].sceneId, medium: 'still', mediumRationale: 'Hold the motif as a photograph.' },
+ { sceneId: project.scenes[1].sceneId, medium: 'procedural', mediumRationale: 'Evolve the motif into linework.' },
+ ],
+ });
+ expect(pinned.status).toBe(200);
+ runPromptThroughProvider.mockResolvedValueOnce({ text: JSON.stringify({
+ motifs: [{ name: 'Glass arc', evolution: 'A line becomes a circle in each repeated hook.' }],
+ shots: project.scenes.map((_, index) => ({ index, medium: 'generated-footage', focalSubject: 'A luminous arc' })),
+ }) });
+ const replanned = await compile(project.id, { baseRevision: pinned.body.treatment.revision, useAi: true });
+ expect(replanned.status).toBe(200);
+ expect(replanned.body.treatment.shotDirections.map((d) => d.medium)).toEqual(['still', 'procedural', 'procedural']);
+ expect(replanned.body.treatment.shotDirections[0]).toMatchObject({ mediumPinned: true, mediumRationale: 'Hold the motif as a photograph.' });
+ expect(replanned.body.treatment.arc.motifs[0].evolution).toContain('each repeated hook');
+ expect(runPromptThroughProvider.mock.calls[0][0].prompt).toContain('generated-video allowance: 0%');
+ const applied = await request(app).post(`${base(project.id)}/treatment/apply`).send({ revision: replanned.body.treatment.revision });
+ expect(applied.status).toBe(200);
+ const cloned = await request(app).post(`${base(project.id)}/clone`).send({});
+ expect(cloned.status).toBe(201);
+ const clone = await reload(cloned.body.id);
+ expect(clone.productionPolicy).toEqual(project.productionPolicy);
+ expect(clone.treatment.shotDirections[0]).toMatchObject({ sceneId: clone.scenes[0].sceneId, medium: 'still', mediumPinned: true });
+ const { sanitizeRecordForWire } = await import('../lib/syncWire.js');
+ const { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
+ const wire = JSON.parse(JSON.stringify(sanitizeRecordForWire('musicVideoProject', clone)));
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ await projects.mergeProjectsFromSync([wire]);
+ expect((await reload(clone.id)).treatment).toEqual(clone.treatment);
+ expect((await reload(clone.id)).productionPolicy).toEqual(project.productionPolicy);
+ // Explicitly releasing a pin also beats the older applied scene direction.
+ const released = await patchTreatment(clone.id, {
+ baseRevision: clone.treatment.revision,
+ shotDirections: [{ sceneId: clone.scenes[0].sceneId, mediumPinned: false }],
+ });
+ expect(released.status).toBe(200);
+ const redrafted = await compile(clone.id, { baseRevision: released.body.treatment.revision, useAi: false });
+ expect(redrafted.status).toBe(200);
+ expect(redrafted.body.treatment.shotDirections[0]).toMatchObject({ medium: 'procedural', mediumPinned: false });
+ expect(PORTOS_SCHEMA_VERSIONS.musicVideoProjects).toBeGreaterThan(11);
+ expect(compareSchemaVersions(
+ { musicVideoProjects: PORTOS_SCHEMA_VERSIONS.musicVideoProjects },
+ { musicVideoProjects: 11 },
+ )).toMatchObject({ compatible: false, ahead: [{ category: 'musicVideoProjects', receiverV: 11 }] });
+ });
+
+ it('defaults legacy projects and blocks a compile raced by a production-policy edit', async () => {
+ const project = await plannedProject();
+ expect(project.productionPolicy.strategy).toBe('legacy');
+ runPromptThroughProvider.mockImplementationOnce(async () => {
+ const saved = await request(app).patch(base(project.id)).send({ productionPolicy: { strategy: 'code-first' } });
+ expect(saved.status).toBe(200);
+ return { text: JSON.stringify({ beats: [{ sectionIndex: 0, objective: 'An opening' }] }) };
+ });
+ const raced = await compile(project.id, { baseRevision: 0 });
+ expect(raced.status).toBe(409);
+ expect(raced.body.code).toBe('TREATMENT_INPUTS_CHANGED');
+ expect((await reload(project.id)).productionPolicy).toEqual({ strategy: 'code-first', maxGeneratedVideoPercent: 0 });
+ const invalid = await request(app).patch(base(project.id)).send({ productionPolicy: { maxGeneratedVideoPercent: 101 } });
+ expect(invalid.status).toBe(400);
+ });
+});
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 1349b0faff..a366dc8d09 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -15,6 +15,7 @@
*/
import { randomUUID } from 'crypto';
+import { normalizeMusicVideoProductionPolicy } from '../../lib/musicVideoMediumPlan.js';
import { ServerError } from '../../lib/errorHandler.js';
import {
MUSIC_VIDEO_STATUSES,
@@ -158,6 +159,7 @@ export function buildProjectRecord(input, { id, now }) {
// #8980 — optional pre-production treatment (brief, arc, shot direction,
// proof checklist); null until the director starts one. See treatment.js.
treatment: null,
+ productionPolicy: normalizeMusicVideoProductionPolicy(input.productionPolicy),
scenes: [],
renderHistoryId: null,
// Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)
@@ -268,6 +270,7 @@ export function applyProjectPatch(project, patch) {
// `visualSpec` patch merges per sub-field the same way (#8965).
const timedPatch = {
...patch,
+ ...(patch.productionPolicy ? { productionPolicy: normalizeMusicVideoProductionPolicy(patch.productionPolicy, project.productionPolicy) } : {}),
...(patch.visualSpec ? { visualSpec: normalizeVisualSpec(patch.visualSpec, project.visualSpec) } : {}),
// Automation brief merges per sub-field; null clears it.
...('automation' in patch ? {
diff --git a/server/services/musicVideo/treatment.js b/server/services/musicVideo/treatment.js
index aff3054762..3df0e45b15 100644
--- a/server/services/musicVideo/treatment.js
+++ b/server/services/musicVideo/treatment.js
@@ -35,13 +35,12 @@
* edited by hand unless they explicitly list that scene with the fingerprint
* of the prompts they reviewed. Takes and slot selections are never touched.
*
- * Peer sync: the treatment and `scene.direction` are additive fields on the
- * whole-record LWW project body. An older peer stores them verbatim, carries
- * them through its own edits (every mutator spreads the record), and never
- * executes them, so no `musicVideoProjects` schema bump is needed.
+ * Peer sync: musicVideoProjects v12 gates medium plans and production policy
+ * against older writers that would discard them during treatment edits.
*/
import { createHash, randomUUID } from 'crypto';
+import { MUSIC_VIDEO_MEDIA, normalizeMusicVideoProductionPolicy, summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';
import { ServerError } from '../../lib/errorHandler.js';
import { trimTo, isNonBlankStr } from '../../lib/textUtils.js';
import {
@@ -182,6 +181,11 @@ function normalizeArc(arc) {
function normalizeShotDirection(d) {
return {
sceneId: String(d.sceneId),
+ ...(MUSIC_VIDEO_MEDIA.includes(d.medium) ? {
+ medium: d.medium,
+ mediumRationale: text(d.mediumRationale, 1000),
+ mediumPinned: d.mediumPinned === true,
+ } : {}),
beatId: typeof d.beatId === 'string' && d.beatId ? d.beatId : null,
mode: pick(d.mode, SHOT_MODES, 'cutaway'),
route: pick(d.route, SHOT_ROUTES, 'generated'),
@@ -298,8 +302,9 @@ function assertRevision(project, baseRevision) {
// ---- basis / staleness ------------------------------------------------------
-const BASIS_KEYS = ['audio', 'analysis', 'visualSpec', 'lyrics', 'scenes'];
+const BASIS_KEYS = ['audio', 'analysis', 'visualSpec', 'lyrics', 'scenes', 'productionPolicy'];
const STALE_MESSAGES = {
+ productionPolicy: 'The production policy changed since this treatment was compiled.',
audio: 'The song changed since this treatment was compiled — recompile it.',
analysis: 'The song was re-analyzed since this treatment was compiled.',
visualSpec: 'The visual spec changed since this treatment was compiled.',
@@ -308,13 +313,14 @@ const STALE_MESSAGES = {
};
// A stale basis on these inputs blocks Apply (old direction must not overwrite
// newer edits); scene-set changes only leave some scenes unmapped.
-const BLOCKING_STALE = new Set(['audio', 'analysis', 'visualSpec', 'lyrics']);
+const BLOCKING_STALE = new Set(['audio', 'analysis', 'visualSpec', 'lyrics', 'productionPolicy']);
/** Fingerprints of every input a compile reads. */
export function treatmentBasis(project) {
const analysis = project?.audioAnalysis;
const spec = project?.visualSpec;
return {
+ productionPolicy: fingerprint(normalizeMusicVideoProductionPolicy(project?.productionPolicy)),
audio: fingerprint([project?.trackId ?? null, project?.uploadedAudioFilename ?? null]),
analysis: fingerprint(analysis
? [analysis.durationSec ?? null, (analysis.sections || []).map((s) => [s?.startSec ?? null, s?.endSec ?? null, s?.energy ?? null])]
@@ -333,7 +339,12 @@ function treatmentStaleness(project, treatment = normalizeTreatment(project?.tre
if (!treatment?.basis) return [];
const current = treatmentBasis(project);
return BASIS_KEYS
- .filter((key) => treatment.basis[key] !== current[key])
+ .filter((key) => {
+ // Old treatments predate policy; absent remains the original legacy behavior.
+ if (key === 'productionPolicy' && !treatment.basis[key]
+ && normalizeMusicVideoProductionPolicy(project.productionPolicy).strategy === 'legacy') return false;
+ return treatment.basis[key] !== current[key];
+ })
.map((key) => ({ input: key, blocking: BLOCKING_STALE.has(key), message: STALE_MESSAGES[key] }));
}
@@ -341,6 +352,15 @@ function stamp(project, treatment, now) {
return { ...project, treatment: { ...treatment, revision: treatment.revision + 1, updatedAt: now }, updatedAt: now };
}
+function assertMediumAllowance(project, directions) {
+ const summary = summarizeMusicVideoMediumPlan(project, directions);
+ if (summary.strategy === 'code-first' && summary.generatedSec > summary.allowedGeneratedSec + 0.000001) {
+ throw treatmentError(422, 'GENERATED_VIDEO_ALLOWANCE_EXCEEDED',
+ 'Generated footage exceeds the final-edit allowance. Adjust the medium plan or explicitly increase the allowance.',
+ { generatedSec: summary.generatedSec, allowedGeneratedSec: summary.allowedGeneratedSec });
+ }
+}
+
// ---- edits ------------------------------------------------------------------
/**
@@ -372,9 +392,13 @@ export function applyTreatmentPatch(project, patch, now = new Date().toISOString
for (const edit of patch.shotDirections) {
const idx = byScene.get(edit.sceneId);
if (idx === undefined) throw treatmentError(404, 'NOT_FOUND', `The treatment has no direction for scene ${edit.sceneId}`);
- next.shotDirections[idx] = normalizeShotDirection({ ...next.shotDirections[idx], ...edit });
+ next.shotDirections[idx] = normalizeShotDirection({
+ ...next.shotDirections[idx], ...edit,
+ ...((edit.medium !== undefined || edit.mediumRationale !== undefined) && edit.mediumPinned === undefined ? { mediumPinned: true } : {}),
+ });
}
}
+ if (patch.shotDirections) assertMediumAllowance(project, next.shotDirections);
if (patch.rebase && next.basis) {
const stale = treatmentStaleness(project, next);
if (stale.some((s) => s.input === 'audio')) {
@@ -414,6 +438,7 @@ export function writeCompiledTreatment(project, { baseRevision, draft, basis, co
compiledAt: now,
compiledWith,
};
+ assertMediumAllowance(project, next.shotDirections);
return stamp(project, next, now);
}
@@ -525,7 +550,7 @@ function composeDirectionClauses(direction, { aspectRatio = null, lipSyncUnavail
};
}
-const DIRECTION_FIELDS = ['beatId', 'mode', 'route', 'focalSubject', 'framing', 'negativeSpace', 'typographyRole', 'emphasis', 'transitionIn', 'transitionOut'];
+const DIRECTION_FIELDS = ['medium', 'mediumRationale', 'mediumPinned', 'beatId', 'mode', 'route', 'focalSubject', 'framing', 'negativeSpace', 'typographyRole', 'emphasis', 'transitionIn', 'transitionOut'];
const directionKey = (d) => fingerprint(DIRECTION_FIELDS.map((f) => d?.[f] ?? null));
function sceneDirection(treatment, direction) {
@@ -642,6 +667,7 @@ export function buildApplyPreview(project) {
throw treatmentError(409, 'TREATMENT_NOT_COMPILED', 'Compile the treatment before applying it');
}
const stale = treatmentStaleness(project, treatment);
+ const mediumPlan = summarizeMusicVideoMediumPlan(project, treatment.shotDirections);
const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
const lipSyncAvailable = !!performanceCapability(project.videoSettings?.backend || null);
const planned = [];
@@ -654,7 +680,9 @@ export function buildApplyPreview(project) {
directed.add(scene.sceneId);
const next = sceneDirection(treatment, direction);
const fields = promptFieldPlans(scene, direction);
- const renderFields = renderFieldPatch(scene, direction, { lipSyncAvailable });
+ // This slice only plans code-first execution: never reinterpret procedural
+ // direction as legacy footage/card selection or switch a render mode.
+ const renderFields = mediumPlan.strategy === 'code-first' ? {} : renderFieldPatch(scene, direction, { lipSyncAvailable });
planned.push({ ...scene, ...renderFields });
scenes.push({
sceneId: scene.sceneId,
@@ -673,7 +701,8 @@ export function buildApplyPreview(project) {
return {
revision: treatment.revision,
stale,
- blocked: stale.some((s) => s.blocking),
+ mediumPlan,
+ blocked: stale.some((s) => s.blocking) || mediumPlan.blocked,
scenes,
missingSceneIds,
unmappedSceneIds: (project.scenes || []).map((s) => s.sceneId).filter((id) => !directed.has(id)),
@@ -695,6 +724,10 @@ export function applyTreatmentToProject(project, { revision, overwrite = [], add
{ currentRevision: treatment.revision });
}
const preview = buildApplyPreview(project);
+ if (preview.mediumPlan.blocked) {
+ throw treatmentError(422, 'MEDIUM_PLAN_UNRESOLVED',
+ preview.mediumPlan.unresolved.filter((item) => item.blocking).map((item) => item.message).join(' '));
+ }
if (preview.blocked) {
throw treatmentError(409, 'TREATMENT_STALE',
`${preview.stale.filter((s) => s.blocking).map((s) => s.message).join(' ')} Recompile, or keep it for the current inputs, before applying.`,
diff --git a/server/services/musicVideo/treatmentDraft.js b/server/services/musicVideo/treatmentDraft.js
index e0db9997f4..22e623a479 100644
--- a/server/services/musicVideo/treatmentDraft.js
+++ b/server/services/musicVideo/treatmentDraft.js
@@ -35,6 +35,7 @@ import {
import { performanceCapability } from '../../lib/musicVideoShotTiming.js';
import { validSections } from './shotPlan.js';
import { normalizeBrief } from './treatment.js';
+import { MUSIC_VIDEO_MEDIA, normalizeMusicVideoProductionPolicy, planMusicVideoMedia } from '../../lib/musicVideoMediumPlan.js';
// Beyond this many mapped shots the AI prompt would blow its budget; the
// deterministic draft still covers every shot.
@@ -226,7 +227,7 @@ function riskOf(direction, beat) {
}
/** The bounded proof checklist: the riskiest shot, plus one short transition/text sequence. */
-function draftProofs(directions, scenes, beatsById, gaps) {
+function draftProofs(directions, scenes, beatsById, gaps, codeFirst = false) {
if (directions.length === 0) return [];
const sceneById = new Map(scenes.map((s) => [s.sceneId, s]));
const labelOf = (id) => sceneById.get(id)?.label || sceneById.get(id)?.sectionLabel || id;
@@ -243,9 +244,11 @@ function draftProofs(directions, scenes, beatsById, gaps) {
const riskShot = {
kind: 'risk-shot',
sceneIds: [best.d.sceneId],
- artifact: `Reference frame and generated clip for "${labelOf(best.d.sceneId)}", reviewed in the final render.`,
+ artifact: codeFirst
+ ? `Final-render proof of "${labelOf(best.d.sceneId)}" using its planned ${best.d.medium} medium after authoring and asset preparation.`
+ : `Reference frame and generated clip for "${labelOf(best.d.sceneId)}", reviewed in the final render.`,
risk: best.risk.reasons.join('; ') || 'the highest-energy shot in the song',
- route: best.d.mode === 'performance' && lipSyncGap
+ route: codeFirst ? `${best.d.medium} — planned only; verify against an actual final render` : best.d.mode === 'performance' && lipSyncGap
? `${best.d.route} — performance framed as non-sync (wide, silhouette, hands, backs); cut away on sung lines if mouth motion reads wrong`
: best.d.route === 'code-2d' ? 'code-2d — a code-rendered title card or moved still in a composed render' : best.d.route,
checks,
@@ -269,7 +272,7 @@ function draftProofs(directions, scenes, beatsById, gaps) {
sceneIds: [pair.a.sceneId, pair.b.sceneId],
artifact: `The cut from "${labelOf(pair.a.sceneId)}" to "${labelOf(pair.b.sceneId)}"${pair.withText ? ' with its composited text cue' : ''}, reviewed in the final render.`,
risk: 'A cut and its text timing are only judged correctly against the song.',
- route: pair.withText ? 'composed render: typography layer over the generated clips' : 'plain cut in the final render',
+ route: codeFirst ? 'Review the planned medium transition in the final render' : pair.withText ? 'composed render: typography layer over the generated clips' : 'plain cut in the final render',
checks: seqChecks,
passCriteria: seqChecks.map((c) => PASS_CRITERIA[c]),
status: 'proposed',
@@ -279,6 +282,11 @@ function draftProofs(directions, scenes, beatsById, gaps) {
/** What the treatment asks for that this install cannot do (yet). */
function deriveCapabilityGaps(project, brief, directions) {
const gaps = [];
+ const codeFirst = normalizeMusicVideoProductionPolicy(project.productionPolicy).strategy === 'code-first';
+ if (codeFirst) gaps.push({
+ id: 'medium-planning',
+ detail: 'This treatment plans media only. Apply saves direction without selecting a renderer or generating assets; procedural document authoring and production enforcement are separate capabilities.',
+ });
// Source-audio lip-sync exists only on a verified lane (#8977, fal.ai today);
// judged against the project's pinned video backend at compile time.
const backend = project.videoSettings?.backend || null;
@@ -290,7 +298,7 @@ function deriveCapabilityGaps(project, brief, directions) {
if (motionRefs) {
gaps.push({ id: 'rotoscope', detail: 'Motion-reference media is scaffolding only: turning footage into hand-drawn or vector animation is not automated, and it is never selected into the timeline automatically.' });
}
- if (directions.some((d) => d.route === 'code-2d')) {
+ if (!codeFirst && directions.some((d) => d.route === 'code-2d')) {
// #8985 supplies title cards and moved stills — but only a composed render
// draws them, and richer 2D animation is not available.
const composed = project.composition?.mode === 'composed';
@@ -303,10 +311,11 @@ function deriveCapabilityGaps(project, brief, directions) {
}
function finalize(project, brief, arc, directions, scenes) {
+ directions = planMusicVideoMedia(project, directions);
const gaps = deriveCapabilityGaps(project, brief, directions);
const beatsById = new Map(arc.beats.map((b) => [b.id, b]));
return { graphicLanguage: brief.graphicLanguage || 'Bold lyric keywords, pictograms and counters on one-beat graphic cards.',
- arc, shotDirections: directions, proofs: draftProofs(directions, scenes, beatsById, gaps), capabilityGaps: gaps };
+ arc, shotDirections: directions, proofs: draftProofs(directions, scenes, beatsById, gaps, normalizeMusicVideoProductionPolicy(project.productionPolicy).strategy === 'code-first'), capabilityGaps: gaps };
}
/**
@@ -357,7 +366,9 @@ export function buildTreatmentPrompt(project, draft) {
const hasLyrics = draft.arc.lyricInterpretation !== null;
const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
const beatsById = new Map(draft.arc.beats.map((b) => [b.id, b]));
+ const policy = normalizeMusicVideoProductionPolicy(project.productionPolicy);
const briefLines = [
+ `Production strategy: ${policy.strategy}; generated-video allowance: ${policy.maxGeneratedVideoPercent}% of final song seconds (union of overlapping intervals, not provider clip lengths).`,
brief.audience && `Audience: ${quote(brief.audience)}`,
brief.destination && `Destination: ${quote(brief.destination)}`,
brief.aspectRatio && `Aspect ratio: ${brief.aspectRatio}`,
@@ -382,6 +393,7 @@ export function buildTreatmentPrompt(project, draft) {
const scene = scenesById.get(d.sceneId) || {};
const beat = beatsById.get(d.beatId);
const parts = [`${i}. ${beat?.role || 'build'} / "${beat?.label || ''}" ${(scene.endSec - scene.startSec).toFixed(1)}s`];
+ parts.push(`planned medium: ${d.medium}; ${d.mediumPinned ? 'director-pinned, retain it' : 'may propose a revision'}; rationale: ${quote(d.mediumRationale)}`);
parts.push(scene.lyricText ? `lyrics: "${quote(scene.lyricText)}"` : 'instrumental');
if (scene.visualIntent) parts.push(`director intent: ${quote(scene.visualIntent)}`);
if (scene.prompt || scene.framePrompt) parts.push(`current prompt: ${quote(scene.framePrompt || scene.prompt, 160)}`);
@@ -402,6 +414,8 @@ ${project.styleReferences?.length ? '- "styleLook": one short sentence summarizi
- The balance of "performance", "cutaway" and "graphic" shots as percentages, with a rationale.
- "graphicLanguage": a concise visual note for the graphic cards and typography (HUD, pictograms, counters), honoring any graphic direction in the brief.
${hasLyrics ? '- "lyricInterpretation": what the lyrics mean and how the picture interprets them (not word-for-word illustration).\n' : '- The song is instrumental: set "lyricInterpretation" to null and invent no lyrics.\n'}- For EACH shot: "mode" (performance|cutaway|graphic), "route" (generated|supplied-asset|code-2d — code-2d becomes a code-rendered title card for a sung line or a moved still; prefer it where a video model cannot hold the requirement), "focalSubject", "framing", "negativeSpace" (none|upper|center|lower — the region kept clean for the separately composited text), "typographyRole" (none|subtitle|hero; must be none on instrumental shots), "emphasis", "transitionIn", "transitionOut", "rationale", and a "framePrompt" (the opening still) and "prompt" (the motion) for the image/video model.
+- For EACH shot also supply "medium" (procedural|still|existing-footage|generated-footage) and "mediumRationale". Medium is independent of performance/cutaway intent. Retain director pins. Tie the medium to the shared motifs, their evolution across repeated sections, and entry/exit transitions.
+- For code-first, prefer procedural or still. Existing footage must be selected already; generated footage is an explicit exception within the allowance. At zero allowance never assign generated footage: report unmet performance intent rather than quietly generating it. This is planning, not a claim that procedural rendering is ready.
- Never ask the image or video model to render the lyrics or any text: typography is composited separately into the reserved region.
${lipSync ? `- Performance shots are lip-synced to the song on ${lipSync.label} (each shot a ${lipSync.minAudioSec}–${lipSync.maxAudioSec}s song window); use them for sung lines where a visible singer matters.` : '- This project\'s video backend cannot lip-sync: no shot can rely on a singer synced to the song.'}
@@ -410,7 +424,7 @@ Respond with ONLY a JSON object (replace every <…> with real content; do NOT o
"beats": [{ "sectionIndex": 0, "objective": "<objective>", "rationale": "<rationale>" }],
"motifs": [{ "name": "<motif>", "description": "<what it is>", "evolution": "<how it changes>", "rationale": "<why>" }],
"balance": { "performance": 40, "cutaway": 45, "graphic": 15, "rationale": "<why>" },
- "shots": [{ "index": 0, "mode": "<mode>", "route": "<route>", "focalSubject": "<subject>", "framing": "<framing>", "negativeSpace": "<region>", "typographyRole": "<role>", "emphasis": "<emphasis>", "transitionIn": "<entry>", "transitionOut": "<exit>", "rationale": "<why>", "framePrompt": "<still>", "prompt": "<motion>" }] }`;
+ "shots": [{ "index": 0, "medium": "<medium>", "mediumRationale": "<why this medium serves the motif and transition>", "mode": "<mode>", "route": "<route>", "focalSubject": "<subject>", "framing": "<framing>", "negativeSpace": "<region>", "typographyRole": "<role>", "emphasis": "<emphasis>", "transitionIn": "<entry>", "transitionOut": "<exit>", "rationale": "<why>", "framePrompt": "<still>", "prompt": "<motion>" }] }`;
}
const isPlaceholder = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);
@@ -478,6 +492,9 @@ export function mergeAiTreatment(project, draft, parsed) {
if (!Number.isInteger(idx) || !directions[idx]) continue;
const d = directions[idx];
const sung = isNonBlankStr(scenesById.get(d.sceneId)?.lyricText);
+ if (MUSIC_VIDEO_MEDIA.includes(entry.medium)) d.medium = entry.medium;
+ const mediumRationale = strField(entry.mediumRationale, 1000);
+ if (mediumRationale !== undefined) d.mediumRationale = mediumRationale;
if (SHOT_MODES.includes(entry.mode)) d.mode = entry.mode;
if (SHOT_ROUTES.includes(entry.route)) d.route = entry.route;
if (TYPOGRAPHY_ROLES.includes(entry.typographyRole)) d.typographyRole = sung ? entry.typographyRole : 'none';