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
add loadable Music Video character styles, starting with Claudia slopcore
[._.]/ Adam Eivy11e9337c5759
diff --git a/client/src/components/musicVideo/CharacterStylePicker.jsx b/client/src/components/musicVideo/CharacterStylePicker.jsxnew file mode 100644index 0000000000..ecd7636cf9--- /dev/null+++ b/client/src/components/musicVideo/CharacterStylePicker.jsx@@ -0,0 +1,68 @@+import { useEffect, useState } from 'react';+import { Link } from 'react-router';+import { listMusicVideoCharacterStyles, setMusicVideoCharacterStyleReference } from '../../services/apiMusicVideo.js';++const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';++/**+ * Loads a built-in character style (a fixed-identity performer) as the+ * project's base concept. Saving the creative setup casts the style's+ * character as protagonist and adds this install's character sheet as a+ * character reference. The sheet is rendered through Image Gen and chosen+ * from the project's look references.+ */+export default function CharacterStylePicker({ project, value, onChange, idFor }) {+ const [styles, setStyles] = useState(null);+ const [error, setError] = useState('');+ const [savingSheet, setSavingSheet] = useState(false);+ const style = (styles || []).find((s) => s.id === value) || null;+ const images = [...new Set((project.visualSpec?.references || []).map((r) => r.imageId))];++ useEffect(() => {+ let active = true;+ listMusicVideoCharacterStyles({ silent: true })+ .then((list) => { if (active) setStyles(list); })+ .catch((err) => { if (active) setError(err.message); });+ return () => { active = false; };+ }, []);++ const chooseSheet = (imageId) => {+ if (!style || !imageId) return;+ setSavingSheet(true);+ setError('');+ setMusicVideoCharacterStyleReference(style.id, imageId, { silent: true })+ .then((saved) => setStyles((list) => list.map((s) => (s.id === saved.id ? { ...s, referenceImageId: saved.referenceImageId } : s))))+ .catch((err) => setError(err.message || 'Could not set the character sheet'))+ .finally(() => setSavingSheet(false));+ };++ return <div className="space-y-2 min-w-0">+ <label htmlFor={idFor('character-style')} className="text-xs">Character style</label>+ <select id={idFor('character-style')} className={inputClass} value={value || ''} onChange={(e) => onChange(e.target.value)}>+ <option value="">No character style</option>+ {value && !style && <option value={value}>Selected style</option>}+ {(styles || []).map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}+ </select>+ {style && <div className="border border-port-border rounded p-2 space-y-2 min-w-0">+ <p className="text-xs">{style.summary}</p>+ <p className="text-xs text-port-text-muted">{style.credit} · <a className="text-port-accent" href={style.sourceUrl} target="_blank" rel="noreferrer">character spec</a></p>+ {value !== (project.concept?.characterStyleId || '') && <p className="text-xs text-port-text-muted">{style.characterName} joins the cast as protagonist when you save.</p>}+ <div className="flex flex-wrap items-start gap-2">+ {style.referenceImageId+ ? <img src={`/data/images/${encodeURIComponent(style.referenceImageId)}`} alt={`${style.characterName} character sheet`} className="w-24 h-24 object-cover rounded bg-black shrink-0" />+ : <p className="text-xs text-port-text-muted flex-1 min-w-0">No character sheet on this install yet. Render one, add it under Look references, then choose it here.</p>}+ <div className="flex flex-col gap-1 min-w-0">+ <Link className="text-sm text-port-accent min-h-[44px] inline-flex items-center" to={`/media/image?${new URLSearchParams({ prompt: style.sheetPrompt })}`}>Render a character sheet</Link>+ {images.length > 0 && <>+ <label htmlFor={idFor('character-sheet')} className="text-xs">Use a look reference as the sheet</label>+ <select id={idFor('character-sheet')} className={inputClass} value="" disabled={savingSheet} onChange={(e) => chooseSheet(e.target.value)}>+ <option value="">Choose an image…</option>+ {images.map((imageId) => <option key={imageId} value={imageId}>{imageId}</option>)}+ </select>+ </>}+ </div>+ </div>+ </div>}+ {error && <p role="alert" className="text-xs text-port-error">{error}</p>}+ </div>;+}diff --git a/client/src/components/musicVideo/CreativeSetupPanel.jsx b/client/src/components/musicVideo/CreativeSetupPanel.jsxindex e0f44db0ca..6d1a80eb97 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.jsx@@ -5,6 +5,7 @@ import { Link } from 'react-router';import { listUniverseNames, getUniverse } from '../../services/apiUniverseBuilder.js';import { uuidv4 } from '../../lib/uuid.js';import { pullUniverseCanonReferences } from '../../lib/musicVideoUniverseRefs.js';+import CharacterStylePicker from './CharacterStylePicker.jsx';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']];@@ -59,7 +60,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })}, [editing, universeId]);const begin = () => {- setDraft({ universeId: project.concept?.universeId || '', subjects: project.concept?.subjects || [] });+ setDraft({ universeId: project.concept?.universeId || '', characterStyleId: project.concept?.characterStyleId || '', subjects: project.concept?.subjects || [] });setSelectedCanon([]);setNewName('');setNewDescription('');@@ -83,7 +84,7 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })if (!universeReady) { setError('Wait for the selected universe to load before saving.'); return; }setSaving(true);setError('');- const concept = { subjects: draft.subjects, universeId: draft.universeId || null };+ const concept = { subjects: draft.subjects, universeId: draft.universeId || null, characterStyleId: draft.characterStyleId || null };const canon = { characters: [], places: [], objects: [] };for (const item of selectedCanon) {if (draft.subjects.some((s) => s.id === item.subjectId)) canon[fields[item.kind]].push(item.entry);@@ -94,12 +95,14 @@ export default function CreativeSetupPanel({ project, onSave, onPendingChange })return <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0 break-words" aria-label="Creative setup"><div className="flex flex-wrap items-center justify-between gap-2">- <h3 className="text-sm font-medium">Universe, cast, places & objects</h3>+ <h3 className="text-sm font-medium">Character style, universe, cast, places & objects</h3>{!editing && <button type="button" onClick={begin} className="text-sm text-port-accent min-h-[44px]">Set up creative direction</button>}</div>+ {!editing && project.concept?.characterStyleId && <p className="text-xs">Character style: {project.concept.characterStyle?.split(':')[0] || project.concept.characterStyleId}</p>}{!editing ? <p className="text-xs text-port-text-muted">{subjects.length ? subjects.map((s) => `${s.name}${s.role === 'protagonist' ? ' (protagonist)' : s.role === 'band' ? ' (band)' : ''}`).join(' · ') : 'Create the band or protagonist, choose a universe, and select the places and objects that anchor the story.'}</p> : <fieldset disabled={saving} className="space-y-3 min-w-0"><p className="text-xs text-port-text-muted">Save this setup before planning or generating. Canon and style are copied into this project; source records stay independent.</p><div className="grid grid-cols-1 gap-3">+ <CharacterStylePicker project={project} idFor={idFor} value={draft.characterStyleId} onChange={(characterStyleId) => setDraft((d) => ({ ...d, characterStyleId }))} /><div><label htmlFor={idFor('universe')} className="text-xs">Universe</label><select id={idFor('universe')} className={inputClass} value={universeId} onChange={(e) => {const nextId = e.target.value;diff --git a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx b/client/src/components/musicVideo/CreativeSetupPanel.test.jsxindex 30c54ceaa9..0bd2ec7151 100644--- a/client/src/components/musicVideo/CreativeSetupPanel.test.jsx+++ b/client/src/components/musicVideo/CreativeSetupPanel.test.jsx@@ -7,6 +7,11 @@ vi.mock('../../services/apiUniverseBuilder.js', () => ({listUniverseNames: vi.fn(async () => [{ id: 'u1', name: 'Example universe' }, { id: 'u2', name: 'Other universe' }]),getUniverse: vi.fn(),}));+const CLAUDIA = { id: 'claudia-slopcore', label: 'Claudia slopcore', summary: 'Deadpan AI pop singer.', credit: 'Claudia by anabology', sourceUrl: 'https://example.com/claudia', characterName: 'Claudia', sheetPrompt: 'Character reference sheet', referenceImageId: null };+vi.mock('../../services/apiMusicVideo.js', () => ({+ listMusicVideoCharacterStyles: vi.fn(async () => [CLAUDIA]),+ setMusicVideoCharacterStyleReference: vi.fn(async (id, imageId) => ({ ...CLAUDIA, referenceImageId: imageId })),+}));const project = { id: 'mv1', concept: {}, visualSpec: {} };const open = (onSave = vi.fn(async () => {})) => {render(<MemoryRouter><CreativeSetupPanel project={project} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);@@ -114,4 +119,21 @@ describe('tools / policy conflict', () => {render_(extra);expect(screen.queryByRole('status')).toBeNull();});++ it('loads a character style into the concept and picks its character sheet from the look references', async () => {+ const { setMusicVideoCharacterStyleReference } = await import('../../services/apiMusicVideo.js');+ const onSave = vi.fn(async () => {});+ render(<MemoryRouter><CreativeSetupPanel project={{ ...project, visualSpec: { references: [{ imageId: 'sheet.png' }] } }} onSave={onSave} onPendingChange={vi.fn()} /></MemoryRouter>);+ fireEvent.click(screen.getByText('Set up creative direction'));+ await screen.findByText('Claudia slopcore');+ fireEvent.change(screen.getByLabelText('Character style'), { target: { value: 'claudia-slopcore' } });+ expect(screen.getByText('Claudia joins the cast as protagonist when you save.')).toBeTruthy();+ expect(screen.getByText('Render a character sheet').getAttribute('href')).toBe('/media/image?prompt=Character+reference+sheet');+ fireEvent.change(screen.getByLabelText('Use a look reference as the sheet'), { target: { value: 'sheet.png' } });+ await screen.findByAltText('Claudia character sheet');+ expect(setMusicVideoCharacterStyleReference).toHaveBeenCalledWith('claudia-slopcore', 'sheet.png', { silent: true });+ fireEvent.click(screen.getByText('Save creative setup'));+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));+ expect(onSave.mock.calls[0][0].concept).toMatchObject({ characterStyleId: 'claudia-slopcore' });+ });});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 378dec64f4..b9258ba3de 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -20,6 +20,12 @@ export const listMusicVideoProjectSummaries = ({ cursor, limit } = {}, options =if (cursor != null) query.set('cursor', String(cursor));return request(`/music-video?${query}`, options);};+// Built-in character styles a project loads through `concept.characterStyleId`,+// each with this install's character sheet (`referenceImageId`, or null).+export const listMusicVideoCharacterStyles = (options = {}) => request('/music-video/character-styles', options);+export const setMusicVideoCharacterStyleReference = (id, imageId, options = {}) => request(`/music-video/character-styles/${encodeURIComponent(id)}/reference`, {+ method: 'PUT', body: JSON.stringify({ imageId }), ...options,+});// Newest MIDI transcription per track — bounded projection for the Tracks page (#10203).export const listMusicVideoMidiSources = (options = {}) => request('/music-video/midi-sources', options);export const createMusicVideoProject = (data, options = {}) => request('/music-video', {diff --git a/server/index.js b/server/index.jsindex bcf5f4513d..b5e98423c9 100644--- a/server/index.js+++ b/server/index.js@@ -146,6 +146,7 @@ import creativeCommissionRoutes from './routes/creativeCommissions.js';import gamesRoutes from './routes/games.js';import fableLoomRoutes from './routes/fableLoom.js';import musicVideoRoutes from './routes/musicVideo.js';+import musicVideoCharacterStyleRoutes from './routes/musicVideoCharacterStyles.js';import humanActionRoutes from './routes/humanActions.js';import spriteRoutes from './routes/sprites.js';import moodBoardRoutes from './routes/moodBoard.js';@@ -443,6 +444,8 @@ app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/creative-commission', creativeCommissionRoutes);app.use('/api/games', gamesRoutes);app.use('/api/fableloom', fableLoomRoutes);+// Before the project router so `/character-styles` is not read as a project id.+app.use('/api/music-video/character-styles', musicVideoCharacterStyleRoutes);app.use('/api/music-video', musicVideoRoutes);app.use('/api/sprites', spriteRoutes);app.use('/api/mood-boards', moodBoardRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 47abb150e2..5a9e23297f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -830,6 +830,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. || `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCodeDirectionContext(direction)` renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |+| `musicVideoCharacterStyles.js` | Built-in Music Video character styles (a fixed-identity performer a project loads as its base concept and cast): `MUSIC_VIDEO_CHARACTER_STYLES` / `_IDS`, `getMusicVideoCharacterStyle`, `summarizeMusicVideoCharacterStyle` (picker projection), `musicVideoCharacterStyleSnapshot` (the `concept.characterStyle` text), `musicVideoCharacterStyleSubject` / `…SubjectId` / `…ReferenceId` (the protagonist and character-sheet reference a pick adds), `musicVideoCharacterSheetPrompt` (renders the style's own sheet). Pure; `services/musicVideo/characterStyles.js` keeps each install's sheet image. || `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. || `musicVideoAutonomous.js` | Fully-autonomous Music Video vocabulary: `AUTONOMOUS_STAGES` (brief → lyrics → style → song → analyze → produce), optional `AUTONOMOUS_CHECKPOINT_IDS`, `normalizeAutonomousSettings` / `normalizeAutonomousBrief` / `normalizeAutopilotParams` (the shared run settings, a run's stored brief, and the scheduled task's params), `autonomousMedium` / `autonomousPool` (tool picks → footage vs code, production route pool), `sunoSongFields` + Suno limits/URL helpers, `normalizeSunoOptions` (the brief's optional `suno` form options: exclude styles, vocal gender, model version), and `pickBrainIdea` / `ideaToPrompt` for the scheduled task. Pure; the client drawer and the run service import it. || `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, `llm: null` clears the direction-LLM pin, `llmStages` merges per stage with `null` clearing one, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545), and `MUSIC_VIDEO_LLM_STAGES` / `MUSIC_VIDEO_LLM_STAGE_LABELS` / `normalizeMusicVideoLlmStages` for the per-stage pins. Dependency-light; the client create drawer imports it. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 776b105194..817b413a6c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -803,6 +803,7 @@ export * from './databaseRestoreRecovery.js';export * from './databaseWriterRegistry.js';export * from './musicVideoCreativeContext.js';+export * from './musicVideoCharacterStyles.js';export * from './moodBoardStyleContext.js';export * from './musicVideoAutomation.js';export * from './musicVideoAutonomous.js';diff --git a/server/lib/musicVideoCharacterStyles.js b/server/lib/musicVideoCharacterStyles.jsnew file mode 100644index 0000000000..a25581e5c6--- /dev/null+++ b/server/lib/musicVideoCharacterStyles.js@@ -0,0 +1,123 @@+// Built-in Music Video character styles: a named, fixed-identity performer a+// project can load as its base concept and character reference. Picking one+// (`concept.characterStyleId`) snapshots the style text into the project,+// casts the character as the protagonist, and — when this install has rendered+// or chosen a character sheet for the style — adds that sheet as a conditioning+// character reference. The catalog is static; the sheet image is per install+// (settings `musicVideoCharacterStyles[id].referenceImageId`) because gallery+// images are local to each install.++const deepFreeze = (value) => {+ if (value && typeof value === 'object') {+ Object.values(value).forEach(deepFreeze);+ Object.freeze(value);+ }+ return value;+};++export const MUSIC_VIDEO_CHARACTER_STYLES = deepFreeze([+ {+ id: 'claudia-slopcore',+ label: 'Claudia slopcore',+ summary: 'Claudia, the deadpan AI pop singer: black bob, one clay-orange streak, star clip, headset mic. Her clothes change with every world; her head never does.',+ credit: 'Claudia by anabology (open character)',+ sourceUrl: 'https://claudia.gallery/claudia.md',+ medium: 'photographic',+ character: {+ name: 'Claudia',+ description: 'An AI who looks like a person: a deadpan, curious pop singer in her late twenties. Always doing something on screen, never waiting.',+ // Close and medium shots. Wider framings use `identityWide`, because the+ // full text makes image models crop in to her face whatever the framing says.+ identity: 'a 28-year-old Caucasian American woman with a grown-up angular face, defined cheekbones and a strong jawline, pale skin and light freckles, a glossy black blunt jaw-length bob with heavy straight bangs and one clay-orange streak through the bangs, a small flat clay-orange eight-pointed star hair clip, a thin headset microphone at her cheek',+ identityWide: 'a Caucasian American woman in her late twenties with pale skin and a glossy black blunt bob with heavy straight bangs and one clay-orange streak, a thin headset microphone',+ face: 'pale skin, light freckles across the nose, dark calm eyes, a small defined mouth; deadpan, curious resting face; when she sings her mouth opens wide and her eyes close',+ hair: 'glossy black blunt bob to the jaw with heavy straight bangs to the brows; one clay-orange (#D97757) streak through the bangs on her right side (viewer\'s left)',+ signature: 'a small flat clay-orange eight-pointed star hair clip on her left side above the ear, and a thin headset microphone at her cheek',+ voice: 'deadpan, clipped spoken verses that rise into euphoric sung choruses; close and dry, every word crisp',+ },+ looks: [+ { name: 'Look 00', description: 'a white cropped puff-sleeve shirt, a black pleated coated-nylon skirt with a harness belt and a hanging white garment tag with a barcode, black knee-high boots' },+ { name: 'The Siren', description: 'a structured high-neck pearl-white couture gown with long sleeves, its sculpted ruffles rising around her like breaking sea foam, hair damp from the spray' },+ { name: 'Chrome', description: 'a liquid-chrome couture bodysuit, chrome opera gloves and chrome thigh-high boots, mirrored from head to toe' },+ { name: 'Bliss gown', description: 'a floor-length bias-cut silk chiffon gown printed edge to edge with a photograph of a deep blue sky and soft white cumulus clouds, a thin grass-green satin halter strap, clay-orange tinted rimless shield sunglasses' },+ { name: 'Cyber trench', description: 'a long glossy cobalt-blue patent-leather trench coat worn open over a white satin corset top and white satin flared trousers, wraparound clay-orange tinted shield sunglasses, silver hoop earrings' },+ { name: 'Silver night', description: 'a slinky liquid-silver lamé cowl-back gown, a white faux-fur stole around her arms, a diamanté choker, silver strappy sandals' },+ ],+ style: 'Slopcore pop music video: photographic film stills with grain and cinematic light, never illustrated. Everything on her is her look\'s own colour plus the streak and the clip in clay orange (#D97757), the one accent. Every world is a loud, specific internet-culture concept played completely straight. All lettering and UI are drawn in code on top, never generated in the image.',+ rules: [+ 'Her head never changes: same bob, bangs, single streak, star clip and headset mic in every shot; only the clothes change with the world.',+ 'Close and medium shots use the full identity text; full length and wider shots use the short identity text.',+ 'Prompt her age as late twenties; never use the word "young".',+ ],+ never: [+ 'a second streak, or orange anywhere else on her',+ 'logos or text on her clothes',+ 'an influencer smile for the camera',+ 'anything that reads under-age, or explicit or sexualised posing',+ 'designer or celebrity names in prompts',+ 'generic mall Y2K (velour tracksuits, plain tees and jeans)',+ 'generated lettering, logos or UI',+ 'illustrated or cartoon rendering',+ ],+ palette: ['#D97757', '#0A0B0D', '#F4F1EA'],+ // Our own turnaround, rendered through PortOS image gen. Outside images+ // only ever inspired this text; they are never used as references.+ sheetPrompt: 'Character reference sheet, photographic studio film still with fine grain and soft cinematic key light on a seamless warm-grey backdrop. Left: a medium close-up of {identity}, deadpan curious expression. Right: three full-length views (front, three-quarter, back) of the same woman wearing {look}. Same face, same hair, same single clay-orange streak and star clip in every view. No text, no labels, no logos.',+ },+]);++const BY_ID = new Map(MUSIC_VIDEO_CHARACTER_STYLES.map((style) => [style.id, style]));++export const MUSIC_VIDEO_CHARACTER_STYLE_IDS = MUSIC_VIDEO_CHARACTER_STYLES.map((style) => style.id);++export const getMusicVideoCharacterStyle = (id) => BY_ID.get(id) || null;++/** Picker projection: what a list needs, without the full wardrobe text. */+export const summarizeMusicVideoCharacterStyle = (style) => ({+ id: style.id,+ label: style.label,+ summary: style.summary,+ credit: style.credit,+ sourceUrl: style.sourceUrl,+ medium: style.medium,+ characterName: style.character.name,+ palette: style.palette,+});++/** The prompt that renders this style's character sheet (first look by default). */+export function musicVideoCharacterSheetPrompt(style, lookName = null) {+ const look = style.looks.find((l) => l.name === lookName) || style.looks[0];+ return style.sheetPrompt+ .replace('{identity}', style.character.identity)+ .replace('{look}', look.description);+}++/** The project snapshot (`concept.characterStyle`), bounded by the concept schema's 4000-char cap. */+export function musicVideoCharacterStyleSnapshot(style) {+ if (!style) return '';+ const c = style.character;+ return [+ `${style.label}: ${c.name}. ${c.description}`,+ `Identity (close and medium shots, verbatim): ${c.identity}`,+ `Identity (full length and wider, verbatim): ${c.identityWide}`,+ `Look: ${style.style}`,+ `Wardrobe options: ${style.looks.map((l) => `${l.name}: ${l.description}`).join(' | ')}`,+ `Rules: ${style.rules.join(' ')}`,+ `Never: ${style.never.join('; ')}`,+ ].join('\n').slice(0, 4000);+}++/** The protagonist subject a style casts; its stable id lets a re-pick replace rather than duplicate it. */+export const musicVideoCharacterStyleSubjectId = (style) => `mvc-style-${style.id}`;++export function musicVideoCharacterStyleSubject(style) {+ return {+ id: musicVideoCharacterStyleSubjectId(style),+ kind: 'character',+ name: style.character.name,+ description: `${style.character.identity}. ${style.character.description}`.slice(0, 1000),+ role: 'protagonist',+ };+}++export const musicVideoCharacterStyleReferenceId = (style) => `mvr-style-${style.id}`;diff --git a/server/lib/musicVideoCreativeContext.js b/server/lib/musicVideoCreativeContext.jsindex b88761659a..d4002b1d31 100644--- a/server/lib/musicVideoCreativeContext.js+++ b/server/lib/musicVideoCreativeContext.js@@ -8,6 +8,10 @@ const BIBLE_HEADER = 'Production bible (use the subjects relevant to this shot;// street or a bathroom), so it is labelled look-only wherever it is included.export const MOOD_BOARD_LOOK_LABEL = 'Mood board look (palette, lighting and texture only; never its locations, objects or poses)';+// A shot needs the character's identity, look, rules and never-list; the+// wardrobe catalogue is for Cast & Sets, which reads the full snapshot.+const characterStyleForShots = (snapshot) => snapshot.split('\n').filter((line) => !line.startsWith('Wardrobe options:')).join('\n');+/*** Shared, bounded creative bible for planning, media generation and handoff.* `moodBoard: false` leaves the mood-board look out — a motion prompt is@@ -17,6 +21,7 @@ export const MOOD_BOARD_LOOK_LABEL = 'Mood board look (palette, lighting and texexport function musicVideoCreativeContext(concept, { moodBoard = true } = {}) {if (!concept) return '';const styles = [+ concept.characterStyle && `Character style (fixed identity; use the identity text verbatim): ${trimTo(characterStyleForShots(concept.characterStyle), 1900)}`,concept.universeStyle && `Universe style: ${trimTo(concept.universeStyle, 800)}`,moodBoard && concept.moodBoardStyle && `${MOOD_BOARD_LOOK_LABEL}: ${trimTo(concept.moodBoardStyle, 800)}`,].filter(Boolean);diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex a9e4a2dec4..85063d76a6 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -69,6 +69,7 @@ import {normalizeAutoApprove,} from './musicVideoAutonomous.js';import { MUSCRIPTOR_MODELS } from './muscriptorModels.js';+import { MUSIC_VIDEO_CHARACTER_STYLE_IDS } from './musicVideoCharacterStyles.js';import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';// A project is authored hands-on (director) or seeded by the AI planner@@ -87,6 +88,10 @@ export const musicVideoConceptSchema = z.object({// Authored snapshots keep the production stable when source canon changes.universeStyle: z.string().max(4000).optional(),moodBoardStyle: z.string().max(4000).optional(),+ // A built-in character style (musicVideoCharacterStyles.js); the server+ // snapshots its text into `characterStyle` and casts its character.+ characterStyleId: z.enum(MUSIC_VIDEO_CHARACTER_STYLE_IDS).nullable().optional(),+ characterStyle: z.string().max(4000).optional(),subjects: z.array(z.object({id: z.string().min(1).max(64),kind: z.enum(['character', 'place', 'object']),@@ -208,6 +213,11 @@ const galleryImageName = z.string().min(1).max(256)// A video-history id (the scene clip vocabulary `videoHistoryId` already uses).const videoHistoryIdSchema = z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/, 'must be a video history id');+// Built-in character style routes (routes/musicVideoCharacterStyles.js).+export const musicVideoCharacterStyleParamsSchema = z.object({ id: z.enum(MUSIC_VIDEO_CHARACTER_STYLE_IDS) }).strict();+// null clears this install's character sheet for the style.+export const musicVideoCharacterStyleReferenceSchema = z.object({ imageId: galleryImageName.nullable() }).strict();+export const MUSIC_VIDEO_REFERENCE_ROLES = ['mood', 'character', 'wardrobe', 'set', 'prop', 'style'];// How a reference is meant to be used (#8980): `reference` guides the look// (style/character conditioning), `final-visible` is supplied media meant todiff --git a/server/routes/musicVideoCharacterStyles.js b/server/routes/musicVideoCharacterStyles.jsnew file mode 100644index 0000000000..c9a28f16cc--- /dev/null+++ b/server/routes/musicVideoCharacterStyles.js@@ -0,0 +1,37 @@+import { Router } from 'express';+import { join } from 'path';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { PATHS, pathExists } from '../lib/fileUtils.js';+import {+ musicVideoCharacterStyleParamsSchema, musicVideoCharacterStyleReferenceSchema,+} from '../lib/musicVideoValidation.js';+import {+ getCharacterStyleDetail, listCharacterStyles, setCharacterStyleReferenceImage,+} from '../services/musicVideo/characterStyles.js';++// Built-in Music Video character styles (server/lib/musicVideoCharacterStyles.js).+// A project loads one through `concept.characterStyleId`; `PUT /:id/reference`+// picks the gallery image this install uses as the style's character sheet.+const router = Router();++router.get('/', asyncHandler(async (req, res) => {+ res.json(await listCharacterStyles());+}));++router.get('/:id', asyncHandler(async (req, res) => {+ // An unknown id fails the enum, so a 400 here is "no such style".+ const { id } = validateRequest(musicVideoCharacterStyleParamsSchema, req.params);+ res.json(await getCharacterStyleDetail(id));+}));++router.put('/:id/reference', asyncHandler(async (req, res) => {+ const { id } = validateRequest(musicVideoCharacterStyleParamsSchema, req.params);+ const { imageId } = validateRequest(musicVideoCharacterStyleReferenceSchema, req.body);+ if (imageId && !(await pathExists(join(PATHS.images, imageId)))) {+ throw new ServerError('Gallery image not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(await setCharacterStyleReferenceImage(id, imageId));+}));++export default router;diff --git a/server/routes/musicVideoCharacterStyles.test.js b/server/routes/musicVideoCharacterStyles.test.jsnew file mode 100644index 0000000000..d1567b4675--- /dev/null+++ b/server/routes/musicVideoCharacterStyles.test.js@@ -0,0 +1,47 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++let settings = {};+vi.mock('../services/settings.js', () => ({+ getSettings: async () => structuredClone(settings),+ updateSettingsWith: async (mutate) => { settings = await mutate(structuredClone(settings)); return settings; },+}));+const pathExists = vi.fn();+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({ ...(await importOriginal()), pathExists: (...a) => pathExists(...a) }));++const { default: routes } = await import('./musicVideoCharacterStyles.js');+const app = express();+app.use(express.json());+app.use('/api/music-video/character-styles', routes);+app.use(errorMiddleware);++describe('/api/music-video/character-styles', () => {+ beforeEach(() => { settings = {}; pathExists.mockReset().mockResolvedValue(true); });++ it('lists the catalog and returns a style with its rendered sheet prompt', async () => {+ const list = await request(app).get('/api/music-video/character-styles');+ expect(list.status).toBe(200);+ expect(list.body.find((s) => s.id === 'claudia-slopcore')).toMatchObject({ characterName: 'Claudia', referenceImageId: null });+ const detail = await request(app).get('/api/music-video/character-styles/claudia-slopcore');+ expect(detail.body.sheetPrompt).toContain('eight-pointed star hair clip');+ expect(detail.body.sheetPrompt).not.toContain('{identity}');+ expect((await request(app).get('/api/music-video/character-styles/no-such-style')).status).toBe(400);+ });++ it('sets and clears this install\'s character sheet, refusing a missing gallery image', async () => {+ const set = await request(app).put('/api/music-video/character-styles/claudia-slopcore/reference').send({ imageId: 'sheet.png' });+ expect(set.status).toBe(200);+ expect(set.body.referenceImageId).toBe('sheet.png');+ expect(settings.musicVideoCharacterStyles['claudia-slopcore']).toEqual({ referenceImageId: 'sheet.png' });++ pathExists.mockResolvedValue(false);+ expect((await request(app).put('/api/music-video/character-styles/claudia-slopcore/reference').send({ imageId: 'gone.png' })).status).toBe(404);+ expect((await request(app).put('/api/music-video/character-styles/claudia-slopcore/reference').send({ imageId: '../x.png' })).status).toBe(400);++ const cleared = await request(app).put('/api/music-video/character-styles/claudia-slopcore/reference').send({ imageId: null });+ expect(cleared.body.referenceImageId).toBeNull();+ expect(settings.musicVideoCharacterStyles).toEqual({});+ });+});diff --git a/server/services/musicVideo/castAndSetsDirection.js b/server/services/musicVideo/castAndSetsDirection.jsindex d102d7c6b2..01e430277a 100644--- a/server/services/musicVideo/castAndSetsDirection.js+++ b/server/services/musicVideo/castAndSetsDirection.js@@ -211,7 +211,8 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,const boardNegative = trimTo(board?.style?.negativePrompt, 600);const moodLines = moodImages.map((img, i) => `${i}. ${[img.caption, img.analysis].filter(Boolean).join(' — ') || '(no caption or analysis)'}`);const sectionLines = sections.map((s) => `${s.index}. ${s.label} ${fmtTime(s.startSec)}–${fmtTime(s.endSec)}`);- const bible = musicVideoCreativeContext(concept);+ // The character style is given in full below, so the bible leaves it out.+ const bible = musicVideoCreativeContext({ ...concept, characterStyle: undefined });const header = procedural ? [`You are the creative director preparing the CAST & SETS check-in for a PROCEDURAL music video of "${project?.name || 'Untitled'}": its characters and environments are authored in code (SVG, Three.js or canvas), not filmed or photographed.`,@@ -232,6 +233,14 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,bible && bible,].filter(Boolean).join('\n');+ // A loaded character style fixes who the protagonist is; the song still+ // decides the world, the sets and which looks she wears.+ const characterStyle = concept.characterStyle ? [+ 'CHARACTER STYLE (fixed): the protagonist is the character below. Use her name, write face, hair and signature from her identity text, and keep every rule and never-list item.',+ 'Choose looks from the wardrobe options or design new ones in the same spirit for this song\'s world.',+ concept.characterStyle,+ ].join('\n') : '';+const board_ = [boardStyle && `Mood board composed style: ${boardStyle}`,boardNegative && `Mood board avoid: ${boardNegative}`,@@ -269,6 +278,7 @@ export function buildCastAndSetsPrompt(project, { moodImages = [], board = null,return [header,facts,+ characterStyle,`Lyrics (section headers and delivery directions in brackets):\n${lyrics || '(instrumental — no lyrics)'}`,sectionLines.length ? `Song sections (index. label start–end):\n${sectionLines.join('\n')}` : 'The song has not been sectioned.',board_,diff --git a/server/services/musicVideo/castAndSetsDirection.test.js b/server/services/musicVideo/castAndSetsDirection.test.jsindex 3b9a915587..1b16f85446 100644--- a/server/services/musicVideo/castAndSetsDirection.test.js+++ b/server/services/musicVideo/castAndSetsDirection.test.js@@ -53,6 +53,15 @@ describe('Cast & Sets direction', () => {expect(prompt).not.toContain('This is a REVISION');});+ it('fixes the protagonist to a loaded character style, stating it once with its wardrobe', () => {+ const characterStyle = 'Claudia slopcore: Claudia.\nWardrobe options: Look 00: a white shirt\nNever: a second streak';+ const prompt = buildCastAndSetsPrompt({ ...project, concept: { ...project.concept, characterStyle } });+ expect(prompt).toContain('CHARACTER STYLE (fixed)');+ expect(prompt.split('Never: a second streak')).toHaveLength(2);+ expect(prompt).toContain('Wardrobe options: Look 00');+ expect(buildCastAndSetsPrompt(project)).not.toContain('CHARACTER STYLE');+ });+it('parses a fenced answer after an echoed schema, normalizing ids, the song map and tests', () => {const echoed = buildCastAndSetsPrompt(project).split('no other text:\n')[1];const parsed = parseCastAndSetsResponse(`${echoed}\n\nSure:\n\`\`\`json\n${JSON.stringify(ANSWER)}\n\`\`\``);diff --git a/server/services/musicVideo/characterStyles.js b/server/services/musicVideo/characterStyles.jsnew file mode 100644index 0000000000..b397fb2b53--- /dev/null+++ b/server/services/musicVideo/characterStyles.js@@ -0,0 +1,43 @@+// Per-install state for the built-in Music Video character styles+// (server/lib/musicVideoCharacterStyles.js): which gallery image is each+// style's character sheet on this install. Stored in settings because gallery+// images are local to an install and the catalog itself is static code.++import { getSettings, updateSettingsWith } from '../settings.js';+import {+ MUSIC_VIDEO_CHARACTER_STYLES, getMusicVideoCharacterStyle, musicVideoCharacterSheetPrompt,+ summarizeMusicVideoCharacterStyle,+} from '../../lib/musicVideoCharacterStyles.js';++const SETTINGS_KEY = 'musicVideoCharacterStyles';++export async function getCharacterStyleReferenceImage(id) {+ const settings = await getSettings();+ return settings?.[SETTINGS_KEY]?.[id]?.referenceImageId || null;+}++export async function listCharacterStyles() {+ const stored = (await getSettings())?.[SETTINGS_KEY] || {};+ return MUSIC_VIDEO_CHARACTER_STYLES.map((style) => ({+ ...summarizeMusicVideoCharacterStyle(style),+ sheetPrompt: musicVideoCharacterSheetPrompt(style),+ referenceImageId: stored[style.id]?.referenceImageId || null,+ }));+}++export async function getCharacterStyleDetail(id) {+ const style = getMusicVideoCharacterStyle(id);+ if (!style) return null;+ return { ...style, sheetPrompt: musicVideoCharacterSheetPrompt(style), referenceImageId: await getCharacterStyleReferenceImage(id) };+}++/** Sets (or clears, with null) the install's character sheet for a style. */+export async function setCharacterStyleReferenceImage(id, imageId) {+ await updateSettingsWith((current) => {+ const all = { ...(current[SETTINGS_KEY] || {}) };+ if (imageId) all[id] = { ...(all[id] || {}), referenceImageId: imageId };+ else delete all[id];+ return { ...current, [SETTINGS_KEY]: all };+ });+ return getCharacterStyleDetail(id);+}diff --git a/server/services/musicVideo/handoff.js b/server/services/musicVideo/handoff.jsindex 6248e7674a..972c94ad29 100644--- a/server/services/musicVideo/handoff.js+++ b/server/services/musicVideo/handoff.js@@ -124,7 +124,7 @@ export function buildHandoffManifest(project, { now = new Date().toISOString() }exportedAt: now,project: { id: project.id, name: project.name, version: project.version || 1 },instructions: 'Generate each scene in your external tool, keep the scene file tag (for example S03-1a2b3c4d) in every downloaded filename, then import the files on the Music Video board. PortOS never contacts the external service; attach the reference files yourself.',- concept: { prompt: project.concept?.prompt || '', style: project.concept?.style || '', universeStyle: project.concept?.universeStyle || '', moodBoardStyle: project.concept?.moodBoardStyle || '', subjects: project.concept?.subjects || [] },+ concept: { prompt: project.concept?.prompt || '', style: project.concept?.style || '', universeStyle: project.concept?.universeStyle || '', moodBoardStyle: project.concept?.moodBoardStyle || '', characterStyle: project.concept?.characterStyle || '', subjects: project.concept?.subjects || [] },visualSpec: {palette: spec?.palette || [],typography: spec?.typography || '',diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 32a5e7922f..3a8d680d83 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -178,7 +178,8 @@ export async function cloneProject(id, options = {}) {export async function updateProject(id, patch) {const backend = await selectBackend();const seeded = await seedTrackMetadataOnUpdate(id, patch);- const needsSnapshot = seeded?.concept?.universeId !== undefined || seeded?.visualSpec?.moodBoardId !== undefined;+ const needsSnapshot = seeded?.concept?.universeId !== undefined || seeded?.concept?.characterStyleId !== undefined+ || seeded?.visualSpec?.moodBoardId !== undefined;const resolved = needsSnapshot ? await withStyleSnapshots(seeded, await backend.getProject(id)) : seeded;const next = await backend.updateProject(id, resolved);emitRecordUpdated('musicVideoProject', id);diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 531d0f3e3f..8b803804ae 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -305,7 +305,8 @@ export function cloneProjectRecord(source, {productionPolicy: normalizeMusicVideoProductionPolicy({ strategy: 'legacy' }),castAndSets: null,visualSpec: clone.visualSpec ? { ...clone.visualSpec, references: [], moodBoardId: null } : null,- concept: clone.concept ? { ...clone.concept, subjects: [], moodBoardStyle: '' } : null,+ // The cast resets, so a loaded character style (which casts the protagonist) does too.+ concept: clone.concept ? { ...clone.concept, subjects: [], moodBoardStyle: '', characterStyleId: null, characterStyle: '' } : null,styleReferences: [],...(clone.automation ? { automation: { ...clone.automation, tools: [], moodBoardId: null } } : {}),scenes: clone.scenes.map((scene) => ({ ...scene, visualLayer: 'footage',diff --git a/server/services/musicVideo/styleSnapshots.js b/server/services/musicVideo/styleSnapshots.jsindex 672c73656b..6b1f46dbaf 100644--- a/server/services/musicVideo/styleSnapshots.js+++ b/server/services/musicVideo/styleSnapshots.js@@ -6,6 +6,12 @@// dispatcher fills the snapshot text in here.import { collectBoardStyleContext } from '../../lib/moodBoardStyleContext.js';+import {+ getMusicVideoCharacterStyle, musicVideoCharacterStyleReferenceId, musicVideoCharacterStyleSnapshot,+ musicVideoCharacterStyleSubject, musicVideoCharacterStyleSubjectId,+} from '../../lib/musicVideoCharacterStyles.js';+import { MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES } from '../../lib/musicVideoValidation.js';+import { getCharacterStyleReferenceImage } from './characterStyles.js';const STYLE_SNAPSHOT_MAX = 4000;@@ -61,6 +67,7 @@ const has = (obj, key) => obj != null && Object.prototype.hasOwnProperty.call(obexport async function withStyleSnapshots(input, existing = null) {if (!input) return input;const concept = input.concept && typeof input.concept === 'object' ? { ...input.concept } : null;+ let visualSpec = input.visualSpec;let touched = false;if (concept && has(concept, 'universeId') && !has(concept, 'universeStyle')) {@@ -71,14 +78,68 @@ export async function withStyleSnapshots(input, existing = null) {}}+ if (concept && has(concept, 'characterStyleId') && !has(concept, 'characterStyle')) {+ const id = concept.characterStyleId || '';+ const previousId = existing?.concept?.characterStyleId || '';+ if (id !== previousId || existing?.concept?.characterStyle == null) {+ const cast = await castCharacterStyle(concept, visualSpec, existing, previousId, id);+ Object.assign(concept, cast.concept);+ visualSpec = cast.visualSpec;+ touched = true;+ }+ }++ let target = concept;if (has(input.visualSpec, 'moodBoardId') && !(concept && has(concept, 'moodBoardStyle'))) {const id = input.visualSpec.moodBoardId || '';if (id !== (existing?.visualSpec?.moodBoardId || '') || existing?.concept?.moodBoardStyle == null) {- const target = concept || {};+ target = concept || {};target.moodBoardStyle = id ? await loadOrEmpty(loadBoard, moodBoardStyleSnapshot, 'mood board', id) : '';- return { ...input, concept: target };+ touched = true;}}- return touched ? { ...input, concept } : input;+ if (!touched) return input;+ return { ...input, ...(target ? { concept: target } : {}), ...(visualSpec ? { visualSpec } : {}) };+}++/**+ * Picking a character style snapshots its text, casts its character as the+ * protagonist and adds this install's character sheet (if one is set) as a+ * character reference; switching away removes what the previous style added+ * and leaves every director-authored subject and reference alone.+ */+async function castCharacterStyle(concept, visualSpec, existing, previousId, id) {+ const style = id ? getMusicVideoCharacterStyle(id) : null;+ const previous = previousId ? getMusicVideoCharacterStyle(previousId) : null;++ const dropSubject = new Set([previous, style].filter(Boolean).map(musicVideoCharacterStyleSubjectId));+ let subjects = (concept.subjects ?? existing?.concept?.subjects ?? []).filter((s) => !dropSubject.has(s.id));+ if (style) {+ // The style's character leads the cast; an existing protagonist steps back.+ subjects = [musicVideoCharacterStyleSubject(style),+ ...subjects.map((s) => (s.role === 'protagonist' ? { ...s, role: 'supporting' } : s))].slice(0, 24);+ }++ const dropRef = new Set([previous, style].filter(Boolean).map(musicVideoCharacterStyleReferenceId));+ const baseRefs = visualSpec?.references ?? existing?.visualSpec?.references ?? [];+ let references = baseRefs.filter((ref) => !dropRef.has(ref.id));+ const imageId = style ? await getCharacterStyleReferenceImage(style.id) : null;+ if (imageId && references.length < 24) {+ const conditioning = references.filter((ref) => ref.condition).length;+ references = [...references, {+ id: musicVideoCharacterStyleReferenceId(style),+ imageId,+ role: 'character',+ label: `${style.character.name} character sheet`,+ use: 'reference',+ condition: conditioning < MUSIC_VIDEO_MAX_CONDITIONING_REFERENCES,+ }];+ }+ const referencesChanged = references.length !== baseRefs.length || references.some((ref, i) => ref !== baseRefs[i]);++ return {+ concept: { characterStyle: musicVideoCharacterStyleSnapshot(style), subjects },+ visualSpec: referencesChanged ? { ...(visualSpec || {}), references } : visualSpec,+ };}diff --git a/server/services/musicVideo/styleSnapshots.test.js b/server/services/musicVideo/styleSnapshots.test.jsindex 41a05674be..3a58ccf1df 100644--- a/server/services/musicVideo/styleSnapshots.test.js+++ b/server/services/musicVideo/styleSnapshots.test.js@@ -4,6 +4,8 @@ const getUniverse = vi.fn();const getBoard = vi.fn();vi.mock('../universeBuilder/crud.js', () => ({ getUniverse: (...a) => getUniverse(...a) }));vi.mock('../moodBoard/index.js', () => ({ getBoard: (...a) => getBoard(...a) }));+const getCharacterStyleReferenceImage = vi.fn();+vi.mock('./characterStyles.js', () => ({ getCharacterStyleReferenceImage: (...a) => getCharacterStyleReferenceImage(...a) }));const { withStyleSnapshots } = await import('./styleSnapshots.js');@@ -14,6 +16,7 @@ describe('withStyleSnapshots (#9105)', () => {beforeEach(() => {getUniverse.mockReset().mockResolvedValue(UNIVERSE);getBoard.mockReset().mockResolvedValue(BOARD);+ getCharacterStyleReferenceImage.mockReset().mockResolvedValue(null);});it('derives both snapshots on create from ids alone', async () => {@@ -56,4 +59,28 @@ describe('withStyleSnapshots (#9105)', () => {const out = await withStyleSnapshots({ concept: { universeId: 'gone' } });expect(out.concept.universeStyle).toBe('');});++ it('casts a character style: snapshot, protagonist and this install\'s sheet as a conditioning reference', async () => {+ getCharacterStyleReferenceImage.mockResolvedValue('sheet.png');+ const director = { id: 'mvc-1', kind: 'character', name: 'Example lead', role: 'protagonist' };+ const conditioned = [1, 2, 3, 4].map((n) => ({ id: `r${n}`, imageId: `r${n}.png`, condition: true }));+ const out = await withStyleSnapshots({ concept: { characterStyleId: 'claudia-slopcore', subjects: [director] } },+ { concept: {}, visualSpec: { references: conditioned } });+ expect(out.concept.characterStyle).toContain('one clay-orange streak through the bangs');+ expect(out.concept.subjects.map((s) => [s.id, s.role])).toEqual([['mvc-style-claudia-slopcore', 'protagonist'], ['mvc-1', 'supporting']]);+ // Four references already condition frames, so the sheet joins as a described reference only.+ expect(out.visualSpec.references.at(-1)).toMatchObject({ id: 'mvr-style-claudia-slopcore', imageId: 'sheet.png', role: 'character', condition: false });++ const picked = { concept: { characterStyleId: 'claudia-slopcore', characterStyle: out.concept.characterStyle, subjects: out.concept.subjects }, visualSpec: out.visualSpec };+ const cleared = await withStyleSnapshots({ concept: { characterStyleId: null } }, picked);+ expect(cleared.concept.characterStyle).toBe('');+ expect(cleared.concept.subjects.map((s) => s.id)).toEqual(['mvc-1']);+ expect(cleared.visualSpec.references).toEqual(conditioned);+ });++ it('casts without a reference when this install has no sheet for the style', async () => {+ const out = await withStyleSnapshots({ concept: { characterStyleId: 'claudia-slopcore' } });+ expect(out.concept.subjects).toHaveLength(1);+ expect(out.visualSpec).toBeUndefined();+ });});