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(music-video): automation-first create flow and header project picker
[._.]/ Adam Eivyb4c7aa89ce4d
diff --git a/client/src/components/musicVideo/AutomationBriefFields.jsx b/client/src/components/musicVideo/AutomationBriefFields.jsxnew file mode 100644index 0000000000..342ddb4edd--- /dev/null+++ b/client/src/components/musicVideo/AutomationBriefFields.jsx@@ -0,0 +1,94 @@+import { MUSIC_VIDEO_AUTOMATION_TOOLS } from '../../../../server/lib/musicVideoAutomation.js';++const GROUPS = [['image', 'Image'], ['video', 'Video'], ['code', 'Code']];+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';++// Free (local) tools — the default pick for a new autopilot brief, so nothing+// metered is spent until the director opts in.+export const DEFAULT_AUTOMATION_TOOLS = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => !t.metered).map((t) => t.id);++// Form draft ↔ wire shape. The draft keeps budget as the raw input string so+// an empty field reads as "no cap" rather than 0.+export const automationDraftFrom = (automation) => ({+ tools: automation?.tools ?? DEFAULT_AUTOMATION_TOOLS,+ guidance: automation?.guidance ?? '',+ budget: automation?.budgetUsd != null ? String(automation.budgetUsd) : '',+});+export const automationFromDraft = (draft) => {+ const budget = Number.parseFloat(draft.budget);+ return {+ tools: draft.tools,+ guidance: draft.guidance.trim(),+ budgetUsd: draft.budget.trim() && Number.isFinite(budget) && budget >= 0 ? budget : null,+ };+};++/** Tool picker + guidance + budget for an automation-first music video. */+export default function AutomationBriefFields({ idPrefix, draft, onChange }) {+ const picked = new Set(draft.tools);+ const allPicked = picked.size === MUSIC_VIDEO_AUTOMATION_TOOLS.length;+ const toggle = (id) => onChange({+ tools: MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => t.id).filter((t) => (t === id ? !picked.has(t) : picked.has(t))),+ });+ return (+ <div className="space-y-3 min-w-0">+ <fieldset className="min-w-0" aria-labelledby={`${idPrefix}-tools-label`}>+ <div className="flex items-center justify-between gap-2 mb-1">+ <span id={`${idPrefix}-tools-label`} className="text-xs text-port-text-muted">Tools the agent may use</span>+ <button+ type="button"+ onClick={() => onChange({ tools: allPicked ? [] : MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => t.id) })}+ className="text-xs text-port-accent min-h-[44px] sm:min-h-0"+ >+ {allPicked ? 'Clear all' : 'Select all'}+ </button>+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">+ {GROUPS.map(([group, label]) => (+ <div key={group} className="border border-port-border rounded p-2 min-w-0">+ <div className="text-[11px] uppercase tracking-wide text-port-text-muted mb-1">{label}</div>+ {MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => t.group === group).map((tool) => (+ <label key={tool.id} htmlFor={`${idPrefix}-tool-${tool.id}`} className="flex items-center gap-2 text-sm py-0.5 min-h-[32px] sm:min-h-0">+ <input+ id={`${idPrefix}-tool-${tool.id}`}+ type="checkbox"+ checked={picked.has(tool.id)}+ onChange={() => toggle(tool.id)}+ />+ <span className="min-w-0 break-words">{tool.label}</span>+ {tool.metered && <span className="ml-auto text-[10px] text-port-warning" title="Spends money or remote quota"><span aria-hidden="true">$</span><span className="sr-only">(metered)</span></span>}+ </label>+ ))}+ </div>+ ))}+ </div>+ </fieldset>+ <div>+ <label htmlFor={`${idPrefix}-guidance`} className="block text-xs text-port-text-muted mb-1">Guidance</label>+ <textarea+ id={`${idPrefix}-guidance`}+ rows={3}+ maxLength={8000}+ value={draft.guidance}+ onChange={(e) => onChange({ guidance: e.target.value })}+ placeholder="Story, tone, pacing, what to avoid — the agent plans every shot against this."+ className={inputClass}+ />+ </div>+ <div className="max-w-[12rem]">+ <label htmlFor={`${idPrefix}-budget`} className="block text-xs text-port-text-muted mb-1">Budget cap (USD)</label>+ <input+ id={`${idPrefix}-budget`}+ type="number"+ min="0"+ step="1"+ inputMode="decimal"+ value={draft.budget}+ onChange={(e) => onChange({ budget: e.target.value })}+ placeholder="No cap"+ className={inputClass}+ />+ </div>+ </div>+ );+}diff --git a/client/src/components/musicVideo/AutomationPanel.jsx b/client/src/components/musicVideo/AutomationPanel.jsxnew file mode 100644index 0000000000..19a345222e--- /dev/null+++ b/client/src/components/musicVideo/AutomationPanel.jsx@@ -0,0 +1,93 @@+import { useState } from 'react';+import { Bot, Play } from 'lucide-react';+import AutomationBriefFields, { automationDraftFrom, automationFromDraft } from './AutomationBriefFields.jsx';+import { MUSIC_VIDEO_AUTOMATION_TOOLS } from '../../../../server/lib/musicVideoAutomation.js';+import { formatUsd } from '../../utils/formatters.js';++const toolLabel = new Map(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => [t.id, t.label]));++/**+ * The project's automation brief — tools, guidance, budget — shown first on+ * the board, with a one-click kickoff (analyze the song, then plan every shot+ * against the brief). Edits PATCH through `onSave`.+ */+export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffBlockedReason }) {+ const [draft, setDraft] = useState(null);+ const [saving, setSaving] = useState(false);+ const automation = project.automation || null;+ const editing = draft !== null;++ const save = () => {+ setSaving(true);+ onSave(automationFromDraft(draft))+ .then(() => setDraft(null))+ // The page owns the error toast; a failed save keeps the brief open.+ .catch(() => {})+ .finally(() => setSaving(false));+ };++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-2 min-w-0" aria-label="Autopilot">+ <div className="flex flex-wrap items-center gap-2">+ <Bot size={16} className="text-port-accent shrink-0" aria-hidden="true" />+ <h3 className="text-sm font-medium">Autopilot</h3>+ {automation && !editing && (+ <span className="text-xs text-port-text-muted">+ {automation.tools.length} tool{automation.tools.length === 1 ? '' : 's'}+ {' · '}+ {automation.budgetUsd != null ? `${formatUsd(automation.budgetUsd)} cap` : 'no budget cap'}+ </span>+ )}+ <div className="ml-auto flex flex-wrap items-center gap-2">+ {!editing && (+ <button type="button" onClick={() => setDraft(automationDraftFrom(automation))} className="text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1">+ {automation ? 'Edit brief' : 'Set up autopilot'}+ </button>+ )}+ {automation && !editing && (+ <button+ type="button"+ onClick={onKickoff}+ disabled={kickoffBusy || !!kickoffBlockedReason}+ title={kickoffBlockedReason || 'Analyze the song, then plan every shot against the brief'}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"+ >+ <Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}+ </button>+ )}+ </div>+ </div>++ {!editing && automation && (+ <>+ {automation.tools.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {automation.tools.map((id) => (+ <span key={id} className="text-[11px] px-1.5 py-0.5 rounded bg-port-border">{toolLabel.get(id) || id}</span>+ ))}+ </div>+ )}+ <p className="text-xs text-port-text-muted break-words line-clamp-3">+ {automation.guidance || 'No guidance yet — the agent plans from the song, universe and board alone.'}+ </p>+ {kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}+ </>+ )}+ {!editing && !automation && (+ <p className="text-xs text-port-text-muted">Hand this video to the agent: pick the tools it may use, give it guidance and a budget.</p>+ )}++ {editing && (+ <fieldset disabled={saving} className="space-y-3 min-w-0">+ <AutomationBriefFields idPrefix={`mv-auto-${project.id}`} draft={draft} onChange={(patch) => setDraft((d) => ({ ...d, ...patch }))} />+ <div className="flex flex-wrap gap-3">+ <button type="button" onClick={save} className="bg-port-accent text-white rounded px-3 py-2 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">+ {saving ? 'Saving…' : 'Save brief'}+ </button>+ <button type="button" onClick={() => setDraft(null)} className="text-sm min-h-[44px] sm:min-h-0">Cancel</button>+ </div>+ </fieldset>+ )}+ </section>+ );+}diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsxindex acdbb7dcac..8b1f77c1a3 100644--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx@@ -1,51 +1,105 @@-import { Plus } from 'lucide-react';+import { Bot, Clapperboard, Plus } from 'lucide-react';import Drawer from '../Drawer.jsx';import YoutubeImportControls from './YoutubeImportControls.jsx';+import AutomationBriefFields from './AutomationBriefFields.jsx';+import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';-const MODES = ['director', 'autonomous'];+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';+const MODES = [+ { id: 'autonomous', label: 'Autopilot', icon: Bot, hint: 'Seed it, pick tools and a budget, let the agent churn' },+ { id: 'director', label: 'Director', icon: Clapperboard, hint: 'Build the scene board by hand' },+];++// "New music video" drawer — automation first: name, audio, universe/board,+// then (autopilot) the tools, guidance and budget the agent works within.+// `universes` is null while the page's name list is still loading.+export default function CreateProjectDrawer({ open, onClose, form, onFormChange, tracks, universes, trackName, youtube, onSubmit, submitting }) {+ const autopilot = form.mode === 'autonomous';-// "New music video" drawer — name/mode/track, or import fresh audio from-// YouTube into the create form's own import slot.-export default function CreateProjectDrawer({ open, onClose, form, onFormChange, tracks, trackName, youtube, onSubmit }) {return (<Draweropen={open}onClose={onClose}+ size="md"title="New music video"- subtitle="Choose the audio now or attach it later"+ subtitle={autopilot ? 'Seed it, choose tools and a budget, and let the agent churn' : 'Choose the audio now or attach it later'}+ closeOnEsc={false}+ closeOnBackdrop={false}>- <form onSubmit={onSubmit} className="space-y-3">- <label htmlFor="mv-name" className="block text-sm font-medium">New project</label>- <input- id="mv-name" value={form.name} onChange={(e) => onFormChange({ name: e.target.value })}- placeholder="Project name" autoFocus- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"- />- <label htmlFor="mv-mode" className="block text-xs text-port-text-muted">Mode</label>- <select id="mv-mode" value={form.mode} onChange={(e) => onFormChange({ mode: e.target.value })}- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm">- {MODES.map((m) => <option key={m} value={m}>{m}</option>)}- </select>- <label htmlFor="mv-track" className="block text-xs text-port-text-muted">Track (optional)</label>- <select id="mv-track" value={form.trackId} onChange={(e) => onFormChange({ trackId: e.target.value })}- disabled={youtube.createJob.active}- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50">- <option value="">— no track —</option>- {tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}- </select>- <label htmlFor="mv-yt-create" className="block text-xs text-port-text-muted">…or import audio from YouTube</label>- <div className="flex gap-1">- <YoutubeImportControls- id="mv-yt-create" url={youtube.createUrl} onUrlChange={(e) => youtube.setCreateUrl(e.target.value)}- job={youtube.createJob} onStart={youtube.startCreate}+ <form onSubmit={onSubmit} className="space-y-4">+ <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">+ {MODES.map(({ id, label, icon: Icon, hint }) => (+ <button+ key={id}+ type="button"+ role="radio"+ aria-checked={form.mode === id}+ onClick={() => onFormChange({ mode: id })}+ className={`text-left rounded border px-3 py-2 min-h-[44px] ${form.mode === id ? 'border-port-accent bg-port-accent/10' : 'border-port-border'}`}+ >+ <span className="flex items-center gap-1.5 text-sm font-medium"><Icon size={15} /> {label}</span>+ <span className="block text-xs text-port-text-muted">{hint}</span>+ </button>+ ))}+ </div>++ <div>+ <label htmlFor="mv-name" className="block text-xs text-port-text-muted mb-1">Name</label>+ <input+ id="mv-name" value={form.name} onChange={(e) => onFormChange({ name: e.target.value })}+ placeholder="Project name" autoFocus maxLength={200}+ className={inputClass}/></div>- {form.trackId && !youtube.createJob.active && (- <p className="text-xs text-port-text-muted">Track set: {trackName(form.trackId)}</p>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="min-w-0">+ <label htmlFor="mv-track" className="block text-xs text-port-text-muted mb-1">Track</label>+ <select id="mv-track" value={form.trackId} onChange={(e) => onFormChange({ trackId: e.target.value })}+ disabled={youtube.createJob.active}+ className={`${inputClass} disabled:opacity-50`}>+ <option value="">— attach later —</option>+ {tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}+ </select>+ </div>+ <div className="min-w-0">+ <label htmlFor="mv-universe" className="block text-xs text-port-text-muted mb-1">Universe</label>+ <select id="mv-universe" value={form.universeId} onChange={(e) => onFormChange({ universeId: e.target.value })}+ className={inputClass}>+ <option value="">{universes === null ? 'Loading…' : 'No universe'}</option>+ {(universes || []).map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}+ </select>+ </div>+ </div>+ <div>+ <label htmlFor="mv-yt-create" className="block text-xs text-port-text-muted mb-1">…or import audio from YouTube</label>+ <div className="flex gap-1">+ <YoutubeImportControls+ id="mv-yt-create" url={youtube.createUrl} onUrlChange={(e) => youtube.setCreateUrl(e.target.value)}+ job={youtube.createJob} onStart={youtube.startCreate}+ />+ </div>+ {form.trackId && !youtube.createJob.active && (+ <p className="text-xs text-port-text-muted mt-1">Track set: {trackName(form.trackId)}</p>+ )}+ </div>+ <MoodBoardReferenceStrip+ value={form.moodBoardId}+ onChange={(id) => onFormChange({ moodBoardId: id || '' })}+ newBoardName={form.name.trim()}+ />++ {autopilot && (+ <AutomationBriefFields+ idPrefix="mv-create"+ draft={form.automation}+ onChange={(patch) => onFormChange({ automation: { ...form.automation, ...patch } })}+ />)}- <button type="submit" disabled={youtube.createJob.active}++ <button type="submit" disabled={youtube.createJob.active || submitting || !form.name.trim()}className="w-full flex items-center justify-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Plus size={16} /> Create+ <Plus size={16} /> {submitting ? 'Creating…' : (autopilot ? 'Create autopilot project' : 'Create')}</button></form></Drawer>diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsxindex 1636df9ef7..c37268d530 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx@@ -4,8 +4,7 @@ import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuildeimport { getMoodBoard } from '../../services/apiMoodBoard.js';import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';import { uuidv4 } from '../../lib/uuid.js';-import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';-import { collectBoardStyleContext } from '../../../../server/lib/moodBoardStyleContext.js';+import { pullUniverseCanonReferences, universeStyleSnapshot, moodBoardStyleSnapshot } from '../../lib/musicVideoUniverseRefs.js';const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';const kinds = [['character', 'Cast'], ['place', 'Places'], ['object', 'Objects']];@@ -75,7 +74,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })setError('');const concept = { subjects: draft.subjects, universeId: draft.universeId || null };if (draft.universeId !== (project.concept?.universeId || '') || project.concept?.universeStyle == null) {- concept.universeStyle = draft.universeId && universe?.id === draft.universeId ? [universe.name, universe.styleNotes, universe.influences?.embrace?.length ? `Embrace: ${universe.influences.embrace.join(', ')}` : '', universe.influences?.avoid?.length ? `Avoid: ${universe.influences.avoid.join(', ')}` : ''].filter(Boolean).join('\n').slice(0, 4000) : '';+ concept.universeStyle = draft.universeId && universe?.id === draft.universeId ? universeStyleSnapshot(universe) : '';}const visualSpec = { moodBoardId: draft.moodBoardId || null };const canon = { characters: [], places: [], objects: [] };@@ -88,10 +87,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })const boardRequest = draft.moodBoardId && refreshBoard? getMoodBoard(draft.moodBoardId, { silent: true }) : Promise.resolve(null);return boardRequest.then((board) => {- if (refreshBoard) {- const context = board ? collectBoardStyleContext(board) : null;- concept.moodBoardStyle = context ? [context.name, context.description, ...context.items.map((item) => Object.values(item).join('; '))].filter(Boolean).join('\n').slice(0, 4000) : '';- }+ if (refreshBoard) concept.moodBoardStyle = moodBoardStyleSnapshot(board);return onSave({ concept, visualSpec });}).then(() => setEditing(false)).catch((err) => setError(err.message || 'Could not save creative setup')).finally(() => setSaving(false));};diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 4c689164d6..6928ebe345 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -61,7 +61,7 @@ grep -i "what you want to do" client/src/lib/README.md| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectToolbar.jsx` and `hooks/useMusicVideoSceneMedia.js`. || `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. || `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |-| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. |+| `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. Also `universeStyleSnapshot(universe)` / `moodBoardStyleSnapshot(board)` — the bounded style text copied into `concept.universeStyle` / `concept.moodBoardStyle` by the creative setup panel and the automation-first create drawer. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). || `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |diff --git a/client/src/lib/musicVideoUniverseRefs.js b/client/src/lib/musicVideoUniverseRefs.jsindex c281d2ba15..034c45f3a4 100644--- a/client/src/lib/musicVideoUniverseRefs.js+++ b/client/src/lib/musicVideoUniverseRefs.js@@ -9,6 +9,31 @@// can never produce a spec the server would reject.import { uuidv4 } from './uuid.js';+import { collectBoardStyleContext } from '../../../server/lib/moodBoardStyleContext.js';++// Authored style snapshots copied into a project's concept (universeStyle /+// moodBoardStyle, bounded by the server's 4000-char schema cap) so later edits+// to the source universe or board never silently restyle a video.+const STYLE_SNAPSHOT_MAX = 4000;++export function universeStyleSnapshot(universe) {+ if (!universe) return '';+ const embrace = universe.influences?.embrace || [];+ const avoid = universe.influences?.avoid || [];+ return [+ universe.name,+ universe.styleNotes,+ embrace.length ? `Embrace: ${embrace.join(', ')}` : '',+ avoid.length ? `Avoid: ${avoid.join(', ')}` : '',+ ].filter(Boolean).join('\n').slice(0, STYLE_SNAPSHOT_MAX);+}++export function moodBoardStyleSnapshot(board) {+ const context = board ? collectBoardStyleContext(board) : null;+ if (!context) return '';+ return [context.name, context.description, ...context.items.map((item) => Object.values(item).join('; '))]+ .filter(Boolean).join('\n').slice(0, STYLE_SNAPSHOT_MAX);+}export const MUSIC_VIDEO_MAX_REFERENCES = 24;diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 46c5a3d151..7b580e62bf 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -41,6 +41,11 @@ import MidiGatedModal from '../components/install/MidiGatedModal.jsx';import { listTracks } from '../services/apiTracks.js';import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import CreateProjectDrawer from '../components/musicVideo/CreateProjectDrawer.jsx';+import AutomationPanel from '../components/musicVideo/AutomationPanel.jsx';+import { automationDraftFrom, automationFromDraft } from '../components/musicVideo/AutomationBriefFields.jsx';+import { getUniverse, listUniverseNames } from '../services/apiUniverseBuilder.js';+import { getMoodBoard } from '../services/apiMoodBoard.js';+import { universeStyleSnapshot, moodBoardStyleSnapshot } from '../lib/musicVideoUniverseRefs.js';import ProjectToolbar from '../components/musicVideo/ProjectToolbar.jsx';import TrackPanel from '../components/musicVideo/TrackPanel.jsx';import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';@@ -60,6 +65,11 @@ import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';import { sceneTakeList } from '../lib/musicVideoTakes.js';+// Automation first: a new project defaults to autopilot with the free tools.+const emptyCreateForm = () => ({+ name: '', mode: 'autonomous', trackId: '', universeId: '', moodBoardId: '', automation: automationDraftFrom(null),+});+const STATUS_COLORS = {draft: 'bg-port-border text-port-text',analyzed: 'bg-port-accent/30 text-port-accent',@@ -79,6 +89,7 @@ export default function MusicVideo() {const navigate = useNavigate();const [projects, setProjects] = useState([]);const [tracks, setTracks] = useState([]);+ const [universes, setUniverses] = useState(null);const selectedId = routeProjectId || null;const [loading, setLoading] = useState(true);const [analyzing, setAnalyzing] = useState(false);@@ -88,7 +99,9 @@ export default function MusicVideo() {const [cloning, setCloning] = useState(false);const [importingLyrics, setImportingLyrics] = useState(false);const [createOpen, setCreateOpen] = useState(false);- const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });+ const [creating, setCreating] = useState(false);+ const [kickingOff, setKickingOff] = useState(false);+ const [form, setForm] = useState(emptyCreateForm);const selected = projects.find((p) => p.id === selectedId) || null;const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));@@ -185,6 +198,7 @@ export default function MusicVideo() {.then((data) => { setProjects(data || []); setLoading(false); }).catch((err) => { toast.error(err?.message || 'Failed to load music video projects'); setLoading(false); });listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]));+ listUniverseNames({ silent: true }).then((u) => setUniverses(u || [])).catch(() => setUniverses([]));}, []);const trackName = useCallback((id) => tracks.find((t) => t.id === id)?.title || id || '—', [tracks]);@@ -210,15 +224,35 @@ export default function MusicVideo() {toast.error('Finish or cancel the in-progress YouTube import before creating the project');return;}- createMusicVideoProject({ name: form.name.trim(), mode: form.mode, trackId: form.trackId || null }, { silent: true })+ if (creating) return;+ setCreating(true);+ // Snapshot the chosen universe/board style into the concept at creation,+ // the same authored copy the creative setup panel saves.+ Promise.all([+ form.universeId ? getUniverse(form.universeId, { silent: true }) : null,+ form.moodBoardId ? getMoodBoard(form.moodBoardId, { silent: true }) : null,+ ])+ .then(([universe, board]) => createMusicVideoProject({+ name: form.name.trim(),+ mode: form.mode,+ trackId: form.trackId || null,+ concept: {+ universeId: form.universeId || null,+ universeStyle: universeStyleSnapshot(universe),+ moodBoardStyle: moodBoardStyleSnapshot(board),+ },+ ...(form.moodBoardId ? { visualSpec: { moodBoardId: form.moodBoardId } } : {}),+ ...(form.mode === 'autonomous' ? { automation: automationFromDraft(form.automation) } : {}),+ }, { silent: true })).then((proj) => {setProjects((prev) => [...prev, proj]);selectProject(proj.id);- setForm({ name: '', mode: 'director', trackId: '' });+ setForm(emptyCreateForm());setCreateOpen(false);toast.success('Project created');})- .catch((err) => toast.error(err?.message || 'Failed to create project'));+ .catch((err) => toast.error(err?.message || 'Failed to create project'))+ .finally(() => setCreating(false));};const handleDelete = (id) => {@@ -250,12 +284,13 @@ export default function MusicVideo() {.finally(() => setCloning(false));};+ // Resolves with the analyzed project, or null when analysis failed (toasted).const handleAnalyze = () => {- if (!selected) return;+ if (!selected) return Promise.resolve(null);setAnalyzing(true);- analyzeMusicVideoProject(selected.id, { silent: true })- .then((proj) => { replaceProject(proj); toast.success(`Analyzed — ${proj.audioAnalysis?.bpm ? `${proj.audioAnalysis.bpm} BPM` : 'no tempo detected'}`); })- .catch((err) => toast.error(err?.message || 'Analysis failed'))+ return analyzeMusicVideoProject(selected.id, { silent: true })+ .then((proj) => { replaceProject(proj); toast.success(`Analyzed — ${proj.audioAnalysis?.bpm ? `${proj.audioAnalysis.bpm} BPM` : 'no tempo detected'}`); return proj; })+ .catch((err) => { toast.error(err?.message || 'Analysis failed'); return null; }).finally(() => setAnalyzing(false));};@@ -264,10 +299,12 @@ export default function MusicVideo() {// the beat grid, capped at the renderer's clip length — and seed them onto// the board, optionally with a first-pass framePrompt/prompt per shot.// Director-first — seeded shots are ordinary, fully-editable board entries.- const handlePlan = () => {- if (!selected?.audioAnalysis) return;+ // `target` lets the autopilot kickoff plan the freshly analyzed record+ // before `selected` re-renders with it.+ const handlePlan = (target = selected) => {+ if (!target?.audioAnalysis) return Promise.resolve();setPlanning(true);- planMusicVideoProject(selected.id, { seedPrompts: true }, { silent: true })+ return planMusicVideoProject(target.id, { seedPrompts: true }, { silent: true }).then(({ project, scenesAdded, promptsSeeded, promptsSkippedReason }) => {replaceProject(project);const suffix = promptsSeeded@@ -279,6 +316,23 @@ export default function MusicVideo() {.finally(() => setPlanning(false));};+ // Autopilot kickoff: analyze the song when it has no beat map yet, then plan+ // every shot against the brief (the planner reads automation.guidance).+ const autopilotBlockedReason = !selected ? null+ : (!selected.trackId && !selected.uploadedAudioFilename) ? 'Attach a track before starting autopilot.'+ : (selected.scenes || []).length > 0 ? 'The board already has shots — edit them below or fork a new version to re-plan.'+ : null;+ const handleKickoff = () => {+ if (!selected || kickingOff || autopilotBlockedReason) return;+ setKickingOff(true);+ (selected.audioAnalysis ? Promise.resolve(selected) : handleAnalyze())+ .then((proj) => (proj?.audioAnalysis ? handlePlan(proj) : null))+ .finally(() => setKickingOff(false));+ };+ const saveAutomation = (automation) => updateMusicVideoProject(selected.id, { automation }, { silent: true })+ .then((proj) => patchProject(proj.id, { automation: proj.automation, updatedAt: proj.updatedAt }))+ .catch((err) => { toast.error(err?.message || 'Failed to save autopilot brief'); throw err; });+// Auto-arrange (#1915): distribute every scene across the analyzed song// sections weighted by each section's energy, writing the same persisted// startSec/endSec/beatAligned fields the manual drag-snap arranger (#1854)@@ -563,7 +617,45 @@ export default function MusicVideo() {onOpenPreview={openPreview}/>)}- <PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" />+ <PageHeader+ icon={Film}+ title="Music Video"+ subtitle="Beat-aware music videos — autopilot or hands-on"+ actions={(+ <>+ <label htmlFor="mv-project-picker" className="sr-only">Project</label>+ <select+ id="mv-project-picker"+ value={selectedId || ''}+ onChange={(e) => selectProject(e.target.value || null)}+ disabled={loading || youtube.editJob.active}+ className="min-w-0 w-full sm:w-72 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"+ >+ <option value="">{loading ? 'Loading projects…' : 'Select a project…'}</option>+ {projects.map((project) => (+ <option key={project.id} value={project.id}>+ {project.name} · {project.scenes?.length || 0} scenes · {project.status}+ </option>+ ))}+ </select>+ {selected && (+ <span className="flex items-center gap-1">+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-border">v{selected.version || 1}</span>+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[selected.status] || 'bg-port-border'}`}>+ {selected.status}+ </span>+ </span>+ )}+ <button+ type="button"+ onClick={() => setCreateOpen(true)}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"+ >+ <Plus size={15} /> New project+ </button>+ </>+ )}+ /><CreateProjectDraweropen={createOpen}@@ -571,45 +663,13 @@ export default function MusicVideo() {form={form}onFormChange={(patch) => setForm((f) => ({ ...f, ...patch }))}tracks={tracks}+ universes={universes}trackName={trackName}youtube={youtube}onSubmit={handleCreate}+ submitting={creating}/>- <div className="bg-port-card border border-port-border rounded-lg p-3 flex flex-wrap items-center gap-2">- <label htmlFor="mv-project-picker" className="text-xs text-port-text-muted">Project</label>- <select- id="mv-project-picker"- value={selectedId || ''}- onChange={(e) => selectProject(e.target.value || null)}- disabled={loading || youtube.editJob.active}- className="min-w-0 flex-1 sm:max-w-md bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm disabled:opacity-50"- >- <option value="">{loading ? 'Loading projects…' : 'Select a project…'}</option>- {projects.map((project) => (- <option key={project.id} value={project.id}>- {project.name} · {project.scenes?.length || 0} scenes · {project.status}- </option>- ))}- </select>- {selected && (- <>- <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-border">- v{selected.version || 1}- </span>- <span className={`text-[10px] px-1.5 py-0.5 rounded ${STATUS_COLORS[selected.status] || 'bg-port-border'}`}>- {selected.status}- </span>- </>- )}- <button- type="button"- onClick={() => setCreateOpen(true)}- className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"- >- <Plus size={15} /> New project- </button>- </div><div>{!selected && !loading && routeProjectId && (@@ -620,11 +680,26 @@ export default function MusicVideo() {)}{!selected && (loading || !routeProjectId) && (<div className="bg-port-card border border-port-border rounded-lg p-6 text-center">- <p className="text-sm text-port-text-muted">Select a project above or create one to open its scene board.</p>+ <p className="text-sm text-port-text-muted mb-3">Pick a project in the header, or start a new one — seed a name, universe and board, choose the tools and a budget, and let autopilot churn.</p>+ <button+ type="button"+ onClick={() => setCreateOpen(true)}+ className="inline-flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"+ >+ <Plus size={15} /> New music video+ </button></div>)}{selected && (<div className="space-y-3">+ <AutomationPanel+ key={`automation-${selected.id}`}+ project={selected}+ onSave={saveAutomation}+ onKickoff={handleKickoff}+ kickoffBusy={kickingOff || analyzing || planning}+ kickoffBlockedReason={autopilotBlockedReason}+ /><CreativeSetupPanel key={`creative-${selected.id}`} project={selected} onPendingChange={setCreativeSetupPending}onSave={(patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });@@ -640,7 +715,7 @@ export default function MusicVideo() {renderJob={renderJob}busy={{ analyzing, planning, arranging, cloning }}onAnalyze={handleAnalyze}- onPlan={handlePlan}+ onPlan={() => handlePlan()}onAutoArrange={handleAutoArrange}onClone={handleClone}onDelete={() => handleDelete(selected.id)}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 4bf13145b9..eda00d07b8 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -82,7 +82,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({resumeMusicVideoRevision: vi.fn(),cancelMusicVideoRevision: vi.fn(),}));-vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));+vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn(), listUniverseNames: vi.fn(() => Promise.resolve([])) }));vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn(), uploadGalleryImage: vi.fn() }));vi.mock('../hooks/useProviderModels', () => ({@@ -153,12 +153,12 @@ vi.mock('../hooks/useSseProgress.js', () => ({isTerminalSseFrame: (frame) => TERMINAL_TYPES.has(frame?.type),}));vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));-vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title}</div> }));+vi.mock('../components/PageHeader', () => ({ default: ({ title, actions }) => <div>{title}{actions}</div> }));import MusicVideo from './MusicVideo.jsx';import {listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,- deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,+ deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender, analyzeMusicVideoProject,importMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,addMusicVideoSceneTake, getMusicVideoHandoffBundle,@@ -1343,12 +1343,42 @@ describe('MusicVideo YouTube audio import (#1945)', () => {fireEvent.click(within(createInput.closest('div')).getByRole('button', { name: /Import/i }));await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalled());- const createBtn = screen.getByRole('button', { name: /^Create$/ });+ const createBtn = screen.getByRole('button', { name: /^Create/ });expect(createBtn).toHaveProperty('disabled', true);fireEvent.click(createBtn);expect(createMusicVideoProject).not.toHaveBeenCalled();});+ it('creates an autopilot project by default with the chosen tools, guidance and budget', async () => {+ listMusicVideoProjects.mockResolvedValue([]);+ createMusicVideoProject.mockResolvedValue({ ...PROJECT_NO_CLIP, id: 'mv-new', name: 'Auto MV', mode: 'autonomous' });+ renderMV();+ await openCreateForm();+ fireEvent.change(await screen.findByPlaceholderText('Project name'), { target: { value: 'Auto MV' } });+ fireEvent.click(screen.getByLabelText(/fal\.ai video/));+ fireEvent.change(screen.getByLabelText('Guidance'), { target: { value: ' one long take ' } });+ fireEvent.change(screen.getByLabelText('Budget cap (USD)'), { target: { value: '40' } });+ fireEvent.click(screen.getByRole('button', { name: /Create autopilot project/ }));+ await waitFor(() => expect(createMusicVideoProject).toHaveBeenCalled());+ const [body] = createMusicVideoProject.mock.calls[0];+ expect(body).toMatchObject({ name: 'Auto MV', mode: 'autonomous', trackId: null });+ expect(body.automation).toEqual({+ tools: ['image:local', 'image:external', 'video:local', 'video:fal', 'code:render'],+ guidance: 'one long take',+ budgetUsd: 40,+ });+ });++ it('autopilot kickoff analyzes the song, then plans the shots against the brief', async () => {+ const project = { ...PROJECT_NO_CLIP, scenes: [], automation: { tools: ['image:local'], guidance: 'noir', budgetUsd: null } };+ analyzeMusicVideoProject.mockResolvedValue({ ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, status: 'analyzed' });+ planMusicVideoProject.mockResolvedValue({ project: { ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis }, scenesAdded: 3, promptsSeeded: true });+ await openProject(project);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));+ expect(analyzeMusicVideoProject).toHaveBeenCalledWith(project.id, { silent: true });+ });+it('blocks relinking the track while a render is in progress for the selected project', async () => {await openProject(PROJECT_WITH_CLIP);fireEvent.click(await screen.findByRole('button', { name: /^Render final$/ }));diff --git a/server/lib/README.md b/server/lib/README.mdindex 6b59e82556..6b659c6417 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -782,3 +782,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoCreativeContext.js` | `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. || `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions and analyzed style for creative prompts. |+| `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 1a8e5643e9..954ae867ed 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -764,3 +764,4 @@ export * from './databaseWriterRegistry.js';export * from './musicVideoCreativeContext.js';export * from './moodBoardStyleContext.js';+export * from './musicVideoAutomation.js';diff --git a/server/lib/musicVideoAutomation.js b/server/lib/musicVideoAutomation.jsnew file mode 100644index 0000000000..42003259ac--- /dev/null+++ b/server/lib/musicVideoAutomation.js@@ -0,0 +1,63 @@+/**+ * Music Video automation brief — the tool catalog an automation-first project+ * is allowed to spend on, plus the brief normalizer.+ *+ * A dependency-free leaf (the client's create drawer and automation panel+ * import it directly, like navManifest.js) so the tool alphabet cannot drift+ * between the picker and the server schema. Image/video tool ids derive from+ * the render-backend alphabets in generationModes.js, so a backend added there+ * reaches the picker in the same commit; `code:render` is the code-rendered+ * pass (typography, composition layers, procedural frames).+ */++import { IMAGE_GEN_MODE, VIDEO_GEN_MODE } from './generationModes.js';++const IMAGE_TOOL_LABELS = {+ [IMAGE_GEN_MODE.LOCAL]: 'Local image gen',+ [IMAGE_GEN_MODE.CODEX]: 'Codex image gen',+ [IMAGE_GEN_MODE.GROK]: 'Grok image gen',+ [IMAGE_GEN_MODE.AGY]: 'Antigravity image gen',+ [IMAGE_GEN_MODE.EXTERNAL]: 'External SD API',+};++const VIDEO_TOOL_LABELS = {+ [VIDEO_GEN_MODE.LOCAL]: 'Local video gen',+ [VIDEO_GEN_MODE.GROK]: 'Grok video',+ [VIDEO_GEN_MODE.FAL]: 'fal.ai video',+ [VIDEO_GEN_MODE.REACTOR]: 'Reactor video',+};++// Metered = spends money or remote quota; the budget cap is meaningful only+// for these. Local backends cost electricity, not dollars.+const METERED = new Set([+ `image:${IMAGE_GEN_MODE.CODEX}`, `image:${IMAGE_GEN_MODE.GROK}`, `image:${IMAGE_GEN_MODE.AGY}`,+ `video:${VIDEO_GEN_MODE.GROK}`, `video:${VIDEO_GEN_MODE.FAL}`, `video:${VIDEO_GEN_MODE.REACTOR}`,+]);++export const MUSIC_VIDEO_AUTOMATION_TOOLS = Object.freeze([+ ...Object.entries(IMAGE_TOOL_LABELS).map(([mode, label]) => ({ id: `image:${mode}`, group: 'image', label })),+ ...Object.entries(VIDEO_TOOL_LABELS).map(([mode, label]) => ({ id: `video:${mode}`, group: 'video', label })),+ { id: 'code:render', group: 'code', label: 'Render with code' },+].map((tool) => Object.freeze({ ...tool, metered: METERED.has(tool.id) })));++export const MUSIC_VIDEO_AUTOMATION_TOOL_IDS = Object.freeze(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => t.id));++export const MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX = 8000;+export const MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD = 100000;++/**+ * Merge a validated automation patch onto the stored brief. Sub-fields merge+ * (a guidance edit cannot drop the tool list); `tools` replaces its list whole,+ * de-duplicated in catalog order. `budgetUsd: null` means "no cap".+ */+export function normalizeMusicVideoAutomation(patch, current = null) {+ const merged = { ...(current || {}), ...(patch || {}) };+ const picked = new Set(Array.isArray(merged.tools) ? merged.tools : []);+ const budget = Number(merged.budgetUsd);+ return {+ tools: MUSIC_VIDEO_AUTOMATION_TOOL_IDS.filter((id) => picked.has(id)),+ guidance: typeof merged.guidance === 'string' ? merged.guidance.slice(0, MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX) : '',+ budgetUsd: merged.budgetUsd != null && Number.isFinite(budget) && budget >= 0+ ? Math.min(budget, MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD) : null,+ };+}diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 3fe56eeb0f..14b61dd152 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -11,6 +11,11 @@import { z } from 'zod';import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';import { MUSIC_VIDEO_SHOT_MODES } from './musicVideoShotTiming.js';+import {+ MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,+ MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX,+ MUSIC_VIDEO_AUTOMATION_TOOL_IDS,+} from './musicVideoAutomation.js';// A project is authored hands-on (director) or seeded by the AI planner// (autonomous); both share the same record + scene board.@@ -430,6 +435,15 @@ export const musicVideoSoundBedSchema = z.object({volume: z.number().min(0.05).max(1).optional(),}).strict();+// Automation-first brief: which render tools the agent may use, the director's+// free-text guidance, and a spend cap (null = no cap). A patch merges per+// sub-field; `tools` replaces its list whole. See musicVideoAutomation.js.+export const musicVideoAutomationSchema = z.object({+ tools: z.array(z.enum(MUSIC_VIDEO_AUTOMATION_TOOL_IDS)).max(MUSIC_VIDEO_AUTOMATION_TOOL_IDS.length).optional(),+ guidance: z.string().max(MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX).optional(),+ budgetUsd: z.number().min(0).max(MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD).nullable().optional(),+}).strict();+export const musicVideoProjectCreateSchema = z.object({name: z.string().min(1).max(200),mode: z.enum(MUSIC_VIDEO_MODES).optional(),@@ -441,6 +455,7 @@ export const musicVideoProjectCreateSchema = z.object({concept: musicVideoConceptSchema.nullable().optional(),visualSpec: musicVideoVisualSpecSchema.optional(),videoSettings: musicVideoVideoSettingsSchema.optional(),+ automation: musicVideoAutomationSchema.nullable().optional(),}).strict();export const musicVideoProjectUpdateSchema = z.object({@@ -452,6 +467,7 @@ export const musicVideoProjectUpdateSchema = z.object({concept: musicVideoConceptSchema.nullable().optional(),visualSpec: musicVideoVisualSpecSchema.optional(),videoSettings: musicVideoVideoSettingsSchema.optional(),+ automation: musicVideoAutomationSchema.nullable().optional(),renderHistoryId: z.string().max(64).nullable().optional(),lyricCues: lyricCueList.optional(),phrases: phraseList.optional(),diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex f1bfa81a83..f04c1f1aa7 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -49,6 +49,8 @@ const SCENE_TEXT_MAX = 2000;// Lyric text per shot quoted into the LLM prompt (the full text persists on// the scene); keeps a lyric-dense plan inside the prompt budget.const PROMPT_LYRIC_MAX = 240;+// The automation brief's standing guidance is prose, not a lyric line.+const PROMPT_GUIDANCE_MAX = 2000;// A plan with more shots than this would blow the LLM prompt budget for// marginal value (a 4-minute song at ~5s shots is ~50) — scenes are still// seeded deterministically above the cap, just without the optional@@ -109,6 +111,9 @@ export function buildScenePlanPrompt(project, shots) {brief.hookObjective && `Opening hook objective: ${quote(brief.hookObjective, PROMPT_LYRIC_MAX)}`,brief.avoid && `Avoid: ${quote(brief.avoid, PROMPT_LYRIC_MAX)}`,].filter(Boolean).join('\n');+ // Automation-first projects carry the director's standing guidance.+ const guidance = project.automation?.guidance?.trim();+ const guidanceLine = guidance ? `Director guidance: ${quote(guidance, PROMPT_GUIDANCE_MAX)}` : '';const hasLyrics = shots.some((s) => s.lyricText);const shotLines = shots.map((s, i) => {const duration = (s.endSec - s.startSec).toFixed(1);@@ -126,6 +131,7 @@ ${conceptLine}${styleLine}${musicVideoCreativeContext(concept)}${briefLines}+${guidanceLine}The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent):${shotLines}diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.jsindex 7d05625d0a..8e34754815 100644--- a/server/services/musicVideo/planner.test.js+++ b/server/services/musicVideo/planner.test.js@@ -210,6 +210,13 @@ describe('planShots', () => {});describe('buildScenePlanPrompt', () => {+ it('carries the automation brief guidance into the plan prompt', () => {+ const base = makeProject({ concept: {} });+ expect(buildScenePlanPrompt(base, [])).not.toContain('Director guidance');+ const prompt = buildScenePlanPrompt({ ...base, automation: { tools: [], guidance: ' one long take,\n no cuts ', budgetUsd: null } }, []);+ expect(prompt).toContain('Director guidance: one long take, no cuts');+ });+it('bounds a maximal production bible without dropping cast identities', () => {const subjects = Array.from({ length: 24 }, (_, index) => ({id: `subject-${index}`, kind: 'character', role: 'protagonist',diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex fb54a4e800..41adce2d39 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -35,6 +35,7 @@ import { ensureSceneTakes, TAKE_SLOT } from './takes.js';import { normalizeComposition, invalidateCompositionTiming } from './composition.js';import { normalizeSoundBed } from './soundBed.js';import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';+import { normalizeMusicVideoAutomation } from '../../lib/musicVideoAutomation.js';export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';@@ -128,6 +129,9 @@ export function buildProjectRecord(input, { id, now }) {// renders (the shared universe/series/sprite field pair). Present only// when set, so existing records keep their on-disk shape byte-stable....persistedRenderPinFields(input),+ // Automation-first brief (tools, guidance, budget). Present only when set,+ // so director-authored records keep their on-disk shape byte-stable.+ ...(input.automation ? { automation: normalizeMusicVideoAutomation(input.automation) } : {}),audioAnalysis: null,midiTranscription: null,// #8964 — editable timed lyric cues + phrase annotations (timed against@@ -240,6 +244,10 @@ export function applyProjectPatch(project, patch) {const timedPatch = {...patch,...(patch.visualSpec ? { visualSpec: normalizeVisualSpec(patch.visualSpec, project.visualSpec) } : {}),+ // Automation brief merges per sub-field; null clears it.+ ...('automation' in patch ? {+ automation: patch.automation ? normalizeMusicVideoAutomation(patch.automation, project.automation) : null,+ } : {}),...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),// #8984 — the composition manifest is replaced whole; null clears it.diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex 48562fbcbf..157e6c5caf 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -288,6 +288,20 @@ describe('applyProjectPatch', () => {expect(second.visualSpec.references[0].id).toBe(ref.id);});+ it('stores the automation brief only when set, merges patches per sub-field, and clears with null', () => {+ expect('automation' in baseProject()).toBe(false);+ const created = buildProjectRecord({+ name: 'Auto', mode: 'autonomous',+ automation: { tools: ['video:fal', 'image:codex', 'video:fal'], guidance: 'surreal', budgetUsd: 25 },+ }, { id: 'mv-a', now: 'n' });+ // De-duplicated, in catalog order (image before video).+ expect(created.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'surreal', budgetUsd: 25 });+ const edited = applyProjectPatch(created, { automation: { guidance: 'darker' } });+ expect(edited.automation).toEqual({ tools: ['image:codex', 'video:fal'], guidance: 'darker', budgetUsd: 25 });+ expect(applyProjectPatch(edited, { automation: { budgetUsd: null } }).automation.budgetUsd).toBeNull();+ expect(applyProjectPatch(edited, { automation: null }).automation).toBeNull();+ });+it('persists explicit renderer settings and merges later partial changes', () => {const project = buildProjectRecord({name: 'A',