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: pick a film style grammar when creating a Code Animation (#10253)
[._.]/ Adam Eivy067090186e9e
diff --git a/client/src/components/codeAnimation/FilmStylePicker.jsx b/client/src/components/codeAnimation/FilmStylePicker.jsxnew file mode 100644index 0000000000..2db783c967--- /dev/null+++ b/client/src/components/codeAnimation/FilmStylePicker.jsx@@ -0,0 +1,72 @@+import { useEffect, useState } from 'react';+import { AlertTriangle } from 'lucide-react';+import { getFilmStyle, listFilmStyles } from '../../services/api';++/**+ * "Film style" select for the Code Animation form (#10253). The catalog loads+ * once on mount; the full record of the chosen grammar loads on selection so+ * its native moves can be judged before an agent run is spent. A failed load+ * leaves the form usable with "None".+ */+export default function FilmStylePicker({ id, value, onChange, labelClass, inputClass }) {+ const [styles, setStyles] = useState(null);+ const [loadError, setLoadError] = useState('');+ const [detail, setDetail] = useState(null);++ useEffect(() => {+ let live = true;+ listFilmStyles({ silent: true })+ .then((rows) => { if (live) setStyles(Array.isArray(rows) ? rows : []); })+ .catch((error) => { if (live) setLoadError(error?.message || 'Could not load film styles'); });+ return () => { live = false; };+ }, []);++ // A stored choice the catalog no longer carries must not reach the server.+ useEffect(() => {+ if (styles && value && !styles.some((style) => style.id === value)) onChange('');+ }, [styles, value, onChange]);++ const selected = styles?.find((style) => style.id === value) || null;++ useEffect(() => {+ if (!selected) return undefined;+ let live = true;+ getFilmStyle(selected.id, { silent: true })+ .then((record) => { if (live) setDetail(record); })+ .catch(() => { if (live) setDetail(null); });+ return () => { live = false; };+ }, [selected]);++ const moves = detail && detail.id === selected?.id ? detail.nativeMoves : null;++ return (+ <div>+ <label htmlFor={id} className={labelClass}>Film style <span className="text-gray-600">(optional medium recipe: rendering, camera and sound)</span></label>+ <select id={id} value={selected ? value : ''} onChange={(event) => onChange(event.target.value)} className={inputClass}>+ <option value="">None (derive from universe / notes)</option>+ {(styles || []).map((style) => <option key={style.id} value={style.id}>{style.label}</option>)}+ </select>+ {loadError && (+ <p role="alert" className="mt-1 flex items-center gap-1 text-xs text-port-error">+ <AlertTriangle className="h-3 w-3 shrink-0" /> Film styles unavailable: {loadError}. The form still works with None.+ </p>+ )}+ {selected && (+ <div className="mt-2 space-y-1 text-xs text-gray-400">+ <p>{selected.summary}</p>+ <details>+ <summary className="cursor-pointer text-gray-300">Native moves ({selected.nativeMoves.length})</summary>+ <ul className="mt-1 space-y-1">+ {(moves || selected.nativeMoves).map((move) => (+ <li key={move.name}>+ <span className="text-gray-200">{move.name}</span>+ {move.fitsContentLike && <span> — fits content like {move.fitsContentLike.join(', ')}</span>}+ </li>+ ))}+ </ul>+ </details>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex 32bdf56a18..3535daa584 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -5,6 +5,7 @@ import PageHeader from '../components/PageHeader';import ProviderModelSelector from '../components/ProviderModelSelector';import AlbumTrackPicker from '../components/music/AlbumTrackPicker';import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';+import FilmStylePicker from '../components/codeAnimation/FilmStylePicker';import ProductionProjects from '../components/codeAnimation/ProductionProjects';import UniverseMoodBoardPicker, { BOARD_FOLLOW_UNIVERSE, BOARD_NONE, useStyleSourceLists } from '../components/media/UniverseMoodBoardPicker';import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';@@ -39,6 +40,7 @@ const DEFAULT_DRAFT = {cast: '',onScreenText: '',styleNotes: '',+ styleGrammarId: '',universeId: '',moodBoardChoice: BOARD_FOLLOW_UNIVERSE,includeMoodBoardImages: true,@@ -101,6 +103,7 @@ const loadDraft = () => {cast: stringField('cast'),onScreenText: stringField('onScreenText'),styleNotes: stringField('styleNotes'),+ styleGrammarId: stringField('styleGrammarId'),universeId: stringField('universeId'),moodBoardChoice: stringField('moodBoardChoice'),includeMoodBoardImages: typeof stored.includeMoodBoardImages === 'boolean' ? stored.includeMoodBoardImages : DEFAULT_DRAFT.includeMoodBoardImages,@@ -134,6 +137,7 @@ function toBrief(draft) {cast: draft.cast,onScreenText: draft.onScreenText,styleNotes: draft.styleNotes,+ styleGrammarId: draft.styleGrammarId || null,format: draft.format,renderer: draft.renderer,interactive: draft.interactive,@@ -166,6 +170,7 @@ function toBriefIdeaInput(draft) {return {universeId: draft.universeId || null,...moodBoardSelection(draft),+ styleGrammarId: draft.styleGrammarId || null,seedIdea: draft.seedIdea,current: {title: draft.title,@@ -195,6 +200,7 @@ function draftFromJob(job) {cast: input.cast || '',onScreenText: input.onScreenText || '',styleNotes: input.styleNotes || '',+ styleGrammarId: input.styleGrammarId || '',universeId: input.universeId || '',moodBoardChoice,includeMoodBoardImages: input.includeMoodBoardImages !== false,@@ -308,6 +314,7 @@ function FastCodeAnimation() {} = useProviderModels({ filter: providerFilter, silent: true, withEffort: true });const update = (patch) => setDraft((prev) => ({ ...prev, ...patch }));+ const onStyleGrammarChange = useCallback((styleGrammarId) => setDraft((prev) => ({ ...prev, styleGrammarId })), []);const updateFormat = (patch) => setDraft((prev) => ({ ...prev, format: { ...prev.format, ...patch } }));const fetchGalleryPage = useCallback(async ({ cursor, signal }) => {@@ -601,6 +608,7 @@ function FastCodeAnimation() {onUniverseChange={(universeId) => update({ universeId })}onBoardChoiceChange={(moodBoardChoice) => update({ moodBoardChoice })}/>+ <FilmStylePicker id="ca-film-style" value={draft.styleGrammarId} onChange={onStyleGrammarChange} labelClass={labelClass} inputClass={inputClass} /><div><label htmlFor="ca-style-notes" className={labelClass}>Style refinements <span className="text-gray-600">(optional, applied on top of the universe style)</span></label><textarea id="ca-style-notes" rows={2} value={draft.styleNotes} maxLength={limits?.styleNotesMax} onChange={(event) => update({ styleNotes: event.target.value })} placeholder="Heavier film grain, slower camera, dusk palette" className={`${inputClass} resize-y`} />diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsxindex 3dba445a3b..42423573c7 100644--- a/client/src/pages/CodeAnimation.test.jsx+++ b/client/src/pages/CodeAnimation.test.jsx@@ -20,6 +20,8 @@ vi.mock('../services/api', () => ({generateCodeAnimationBrief: vi.fn(),getCodeAnimationJob: vi.fn(),getCodeAnimationOptions: vi.fn(),+ getFilmStyle: vi.fn(),+ listFilmStyles: vi.fn(),listCodeAnimationJobPage: vi.fn().mockResolvedValue({ items: [], total: 0, counts: { running: 0, completed: 0 }, nextCursor: null }),listMoodBoardNames: vi.fn(),listTracks: vi.fn().mockResolvedValue([]),@@ -48,6 +50,8 @@ import {getCodeAnimationJob,listCodeAnimationJobPage,getCodeAnimationOptions,+ getFilmStyle,+ listFilmStyles,listMoodBoardNames,listTracks,listUniverseNames,@@ -65,6 +69,14 @@ const OPTIONS = {audioExtensions: ['mp3', 'wav'],};+const FILM_STYLES = [+ { id: 'blueprint-draft', label: 'Blueprint draft', category: 'drawing', summary: 'White lines on a deep blue sheet.', nativeMoves: [{ name: 'Exploded assembly' }] },+];+const BLUEPRINT = {+ ...FILM_STYLES[0],+ nativeMoves: [{ name: 'Exploded assembly', how: 'Pull apart.', fitsContentLike: ['product anatomy', 'teardowns'] }],+};+const renderPage = async (initialEntry = '/code-animation') => {const result = render(<MemoryRouter initialEntries={[initialEntry]}>@@ -114,6 +126,8 @@ describe('Code Animation page', () => {listUniverseStyles.mockResolvedValue([{ id: 'u1', name: 'Example Universe', influences: { embrace: ['ink wash'], avoid: ['photorealism'] } }]);listMoodBoardNames.mockResolvedValue([{ id: 'b1', name: 'Dusk' }]);listTracks.mockResolvedValue([]);+ listFilmStyles.mockResolvedValue(FILM_STYLES);+ getFilmStyle.mockResolvedValue(BLUEPRINT);buildCodeAnimationPrompt.mockResolvedValue({prompt: 'You are an award-winning creative coder…',attachments: [{ label: 'Night markets', origin: 'universe', url: '/data/image-refs/style-ref.png' }],@@ -364,6 +378,47 @@ describe('Code Animation page', () => {expect(screen.getByLabelText(/^title/i)).toHaveValue('Edited after submit');});+ it('picks a film style, shows its moves, and sends the id with the brief and the prompt request', async () => {+ const user = userEvent.setup();+ await renderPage();+ const select = screen.getByLabelText(/^film style/i);+ expect(select).toHaveValue('');+ expect(screen.getByRole('option', { name: /^None \(derive from universe/ })).toBeInTheDocument();+ await user.selectOptions(select, 'blueprint-draft');+ expect(screen.getByText('White lines on a deep blue sheet.')).toBeInTheDocument();+ expect(await screen.findByText(/fits content like product anatomy, teardowns/)).toBeInTheDocument();+ await user.type(screen.getByLabelText(/what happens/i), 'A lantern');+ await user.click(screen.getByRole('button', { name: /build prompt/i }));+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());+ expect(buildCodeAnimationPrompt.mock.calls[0][0].styleGrammarId).toBe('blueprint-draft');+ expect(listFilmStyles).toHaveBeenCalledTimes(1);+ });++ it('restores the film style from a saved job', async () => {+ getCodeAnimationJob.mockResolvedValue({ ...runningJob, input: { ...runningJob.input, styleGrammarId: 'blueprint-draft' } });+ await renderPage('/code-animation/job-1');+ expect(screen.getByLabelText(/^film style/i)).toHaveValue('blueprint-draft');+ });++ it('drops a stored film style the catalog no longer has before it reaches the server', async () => {+ localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({ concept: 'x', styleGrammarId: 'retired-style' }));+ const user = userEvent.setup();+ await renderPage();+ await user.click(screen.getByRole('button', { name: /build prompt/i }));+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());+ expect(buildCodeAnimationPrompt.mock.calls[0][0].styleGrammarId).toBeNull();+ });++ it('shows an inline error and keeps the form usable when the catalog fails to load', async () => {+ listFilmStyles.mockRejectedValue(new Error('offline'));+ const user = userEvent.setup();+ await renderPage();+ expect(await screen.findByRole('alert')).toHaveTextContent(/film styles unavailable: offline/i);+ expect(screen.getByLabelText(/^film style/i)).toHaveValue('');+ await user.type(screen.getByLabelText(/what happens/i), 'A lantern');+ expect(screen.getByRole('button', { name: /build prompt/i })).toBeEnabled();+ });+it('sends an explicit empty board when the user opts out of a mood board', async () => {const user = userEvent.setup();await renderPage();diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex aee4b9dab9..cfde02c690 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -79,3 +79,8 @@ export const getCodeAnimationBlenderStarter = options => request('/code-animatio// evidence, and explicit promotion of one passing run.export const getCodeAnimationAcceptance = (id, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/acceptance`, options);export const acceptCodeAnimationOutput = (id, runId, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/accepted-output`, { method: 'POST', body: JSON.stringify({ runId }), ...options });++// Film style grammar catalog (#10253). The list is the picker projection; the+// full record carries each native move's "fits content like" examples.+export const listFilmStyles = (options) => request('/film-styles', options);+export const getFilmStyle = (id, options) => request(`/film-styles/${encodeURIComponent(id)}`, options);diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex 7b1c062217..0093185a33 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -26,6 +26,8 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';import { emptyToNull } from '../lib/zodCompat.js';+import { filmStyleIdSchema } from '../lib/filmStyleGrammarValidation.js';+import { getFilmStyleGrammar } from '../lib/filmStyleGrammars.js';import {buildCodeAnimationRequest,generateCodeAnimationBrief,@@ -62,6 +64,11 @@ const uploadFilenameSchema = z.string().trim().min(1).max(256).regex(/^[^/\\]+$/, 'filename must be an upload basename');const optionalId = z.preprocess(emptyToNull, z.string().trim().min(1).max(128).nullable().optional());+// Optional film style grammar (#10253): kebab-case id that must exist in the catalog.+const styleGrammarIdSchema = z.preprocess(emptyToNull, filmStyleIdSchema+ .refine((id) => !!getFilmStyleGrammar(id), 'Unknown film style grammar')+ .nullable().optional());+const formatSchema = z.object({durationSeconds: z.number().int().min(L.durationMin).max(L.durationMax).default(20),aspectRatio: z.enum(Object.keys(CODE_ANIMATION_ASPECT_RATIOS)).default('16:9'),@@ -95,6 +102,7 @@ const briefSchema = z.object({onScreenText: z.string().trim().max(L.textMax).default(''),// Refinements on top of the universe style — the universe is the art direction.styleNotes: z.string().trim().max(L.styleNotesMax).default(''),+ styleGrammarId: styleGrammarIdSchema,format: formatSchema.prefault({}),renderer: z.enum(CODE_ANIMATION_RENDERERS).default('auto'),interactive: z.boolean().default(false),@@ -124,6 +132,7 @@ const generateSchema = briefSchema.extend({const briefIdeaSchema = z.object({universeId: optionalId,moodBoardId: optionalId,+ styleGrammarId: styleGrammarIdSchema,seedIdea: z.string().trim().max(L.seedIdeaMax).default(''),// The same brief, partially filled — derived from briefSchema so the field// caps are stated once, with `concept` relaxed because there may be none yet.diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 3a7f585146..f6d7c25e3c 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -400,6 +400,14 @@ describe('POST /api/code-animation/brief', () => {expect(call.prompt).not.toContain('Reference images');});+ it('gives the brief writer the chosen grammar\'s native moves', async () => {+ runPromptThroughProvider.mockResolvedValue(briefResponse({ title: 't', concept: 'c', cast: '', onScreenText: '', styleNotes: '' }));+ const res = await request(makeApp()).post('/api/code-animation/brief').send({ universeId: 'universe-1', styleGrammarId: 'blueprint-draft' });+ expect(res.status).toBe(200);+ expect(runPromptThroughProvider.mock.calls[0][0].prompt).toContain('Exploded assembly');+ expect((await request(makeApp()).post('/api/code-animation/brief').send({ universeId: 'universe-1', styleGrammarId: 'no-such-style' })).status).toBe(400);+ });+it('502s a response that holds no brief', async () => {runPromptThroughProvider.mockResolvedValue({ text: 'I would rather not.' });const res = await request(makeApp()).post('/api/code-animation/brief').send({ universeId: 'universe-1' });@@ -473,6 +481,28 @@ describe('POST /api/code-animation/prompt', () => {expect(res.body.prompt).not.toContain('Mood board:');});+ it('renders a chosen film style grammar, persists it on the job input, and rejects an unknown id', async () => {+ const app = makeApp();+ const plain = await request(app).post('/api/code-animation/prompt').send(brief);+ expect(plain.body.prompt).not.toContain('STYLE GRAMMAR');+ const res = await request(app).post('/api/code-animation/prompt').send({ ...brief, styleGrammarId: 'blueprint-draft' });+ expect(res.status).toBe(200);+ expect(res.body.prompt.match(/STYLE GRAMMAR:/g)).toHaveLength(1);+ // '' / null mean "None", identical to omitting it.+ expect((await request(app).post('/api/code-animation/prompt').send({ ...brief, styleGrammarId: '' })).body.prompt).toBe(plain.body.prompt);+ const unknown = await request(app).post('/api/code-animation/prompt').send({ ...brief, styleGrammarId: 'no-such-style' });+ expect(unknown.status).toBe(400);+ expect((await request(app).post('/api/code-animation/prompt').send({ ...brief, styleGrammarId: 'Not Kebab' })).status).toBe(400);++ getProviderById.mockResolvedValue({ id: 'api-1', type: 'api', enabled: true });+ runPromptThroughProvider.mockReturnValue(new Promise(() => {}));+ const started = await request(app).post('/api/code-animation/generate').send({ ...brief, styleGrammarId: 'blueprint-draft', providerId: 'api-1' });+ expect(started.status).toBe(202);+ expect(started.body.input.styleGrammarId).toBe('blueprint-draft');+ expect(codeAnimationRecords.get(started.body.id).input.styleGrammarId).toBe('blueprint-draft');+ expect(runPromptThroughProvider.mock.calls[0][0].prompt).toContain('Film style grammar: Blueprint draft');+ });+it('rejects a missing brief, a stray upload, and an unknown universe', async () => {const app = makeApp();expect((await request(app).post('/api/code-animation/prompt').send({ concept: '' })).status).toBe(400);diff --git a/server/services/codeAnimation/brief.js b/server/services/codeAnimation/brief.jsindex 13dea74930..70b23bf45f 100644--- a/server/services/codeAnimation/brief.js+++ b/server/services/codeAnimation/brief.js@@ -29,6 +29,7 @@ import { extractJson } from '../../lib/jsonExtract.js';import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';import { ServerError } from '../../lib/errorHandler.js';import { moodBoardSection, universeStyleLines } from '../../lib/styleSourcePrompt.js';+import { getFilmStyleGrammar } from '../../lib/filmStyleGrammars.js';import { CODE_ANIMATION_LIMITS, PACING_RULE } from './prompt.js';// What separates a studio short from a moving screensaver, distilled from how@@ -65,6 +66,16 @@ function castSection(universe) {return `CANON — cast the film from these and use their names:\n${canon}\n\nPrefer the canon above over inventing new entities. A character you use must behave, speak, and look as their entry describes.`;}+// The film's medium (#10253). Only the native-move names reach the writer: the+// beat sheet can spend one at the emotional peak; the full recipe is the coding+// prompt's job.+function styleGrammarSection(styleGrammarId) {+ const grammar = styleGrammarId ? getFilmStyleGrammar(styleGrammarId) : null;+ if (!grammar) return '';+ const moves = grammar.nativeMoves.map(({ name }) => name).join('; ');+ return `MEDIUM — the film will be rendered as: ${grammar.label} (${grammar.summary})\nMoves only this medium can make: ${moves}. Spend exactly one of them at the emotional peak of the beat sheet, and name it in that beat.`;+}+function currentSection(current) {const rows = [['Title', current.title],@@ -84,6 +95,7 @@ function currentSection(current) {* @param {object|null} [input.universe] - the resolved universe: style tokens plus `{ logline, premise, characters, places, objects }`* @param {object|null} [input.moodBoard] - `collectBoardStyleContext` output* @param {string} [input.seedIdea] - the artist's starting spark, if any+ * @param {string|null} [input.styleGrammarId] - film style grammar id (#10253)* @param {{ durationSeconds: number, aspectRatio: string }} input.format* @param {{ title: string, concept: string, cast?: string, onScreenText: string, styleNotes: string }} [input.current]* @returns {string}@@ -92,6 +104,7 @@ export function buildCodeAnimationBriefPrompt({universe = null,moodBoard = null,seedIdea = '',+ styleGrammarId = null,format,current = {},}) {@@ -109,6 +122,8 @@ export function buildCodeAnimationBriefPrompt({}const boardText = moodBoardSection(moodBoard);if (boardText) sections.push(boardText);+ const grammarText = styleGrammarSection(styleGrammarId);+ if (grammarText) sections.push(grammarText);const currentText = currentSection(current);if (currentText) sections.push(currentText);if (!universe && !isNonBlankStr(seedIdea) && !currentText) {diff --git a/server/services/codeAnimation/brief.test.js b/server/services/codeAnimation/brief.test.jsindex b6dc758681..213fddf130 100644--- a/server/services/codeAnimation/brief.test.js+++ b/server/services/codeAnimation/brief.test.js@@ -89,6 +89,17 @@ describe('buildCodeAnimationBriefPrompt', () => {});});+describe('brief writer film style grammar', () => {+ it('hands the writer the native-move names only, and nothing without a grammar', () => {+ const base = { universe: UNIVERSE, seedIdea: 'a chase', format: FORMAT, current: {} };+ expect(buildCodeAnimationBriefPrompt(base)).not.toContain('MEDIUM');+ const prompt = buildCodeAnimationBriefPrompt({ ...base, styleGrammarId: 'blueprint-draft' });+ expect(prompt).toContain('MEDIUM');+ expect(prompt).toContain('Exploded assembly; Dimension lock; Revision cloud');+ expect(prompt).not.toContain('Pull an object apart along its axes');+ });+});+describe('extractBriefIdea', () => {const response = (body) => `Here you go:\n\`\`\`json\n${JSON.stringify(body)}\n\`\`\``;diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.jsindex c24150af09..7651b8b415 100644--- a/server/services/codeAnimation/index.js+++ b/server/services/codeAnimation/index.js@@ -237,6 +237,7 @@ export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {cast: input.cast,onScreenText: input.onScreenText,styleNotes: input.styleNotes,+ styleGrammarId: input.styleGrammarId,format: input.format,renderer: input.renderer,interactive: input.interactive,@@ -294,6 +295,7 @@ export async function generateCodeAnimationBrief(input) {universe,moodBoard: board,seedIdea: input.seedIdea,+ styleGrammarId: input.styleGrammarId,format: input.format,current: input.current,});diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex c46ca5deda..4a19c3335f 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -25,6 +25,7 @@import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';import { moodBoardSection, universeStyleLines } from '../../lib/styleSourcePrompt.js';+import { renderFilmStyleGrammarPrompt } from '../../lib/filmStyleGrammars.js';// The postMessage vocabulary between the preview host (parent) and the// generated page (sandboxed iframe). Served to the client through the options@@ -94,11 +95,13 @@ export function resolveFrameSize(aspectRatio, resolution) {return { width: shortSide, height: even((shortSide * ratio.height) / ratio.width) };}+const STYLE_GRAMMAR_PRECEDENCE = "Precedence: the universe style guide and mood board win on palette and subject content; the style grammar wins on rendering technique, motion stepping, camera moves and sound; the style refinements below refine both.";+// The art direction. The universe's style guide IS the look — the same curated// tokens every other Create surface renders that world with — so the film// matches the universe's stills and videos; the per-animation notes only// refine it. The model's job is to translate that look into drawing code.-function artDirectionSection({ universe, styleNotes, hasMoodBoard }) {+function artDirectionSection({ universe, styleNotes, styleGrammarId, hasMoodBoard }) {const lines = [];if (universe) {lines.push(`The art style comes from the universe "${universe.name}". Match its established look exactly — this film must sit beside the universe's other artwork as the same world.`);@@ -107,6 +110,11 @@ function artDirectionSection({ universe, styleNotes, hasMoodBoard }) {lines.push(`Tone and staging notes (context for mood — do not depict entities they name unless the brief asks): ${universe.styleNotes}`);}}+ const grammar = styleGrammarId ? renderFilmStyleGrammarPrompt(styleGrammarId) : '';+ if (grammar) {+ lines.push(`STYLE GRAMMAR:\n${grammar}`);+ lines.push(STYLE_GRAMMAR_PRECEDENCE);+ }if (isNonBlankStr(styleNotes)) {lines.push(`${universe ? 'Refinements for this animation' : 'Style direction from the artist'}: ${trimTo(styleNotes, CODE_ANIMATION_LIMITS.styleNotesMax)}`);}@@ -232,6 +240,7 @@ ${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textur* @param {string} [input.cast] - the character design bible the rig is built from* @param {string} [input.onScreenText] - titles, captions, narration beats* @param {string} [input.styleNotes] - refinements on top of the universe style+ * @param {string|null} [input.styleGrammarId] - film style grammar id (#10253); unknown ids throw a 400* @param {{ durationSeconds: number, aspectRatio: string, resolution: string, fps: number }} input.format* @param {'auto'|'canvas2d'|'webgl'|'svg'} [input.renderer]* @param {boolean} [input.interactive]@@ -249,6 +258,7 @@ export function buildCodeAnimationPrompt({cast = '',onScreenText = '',styleNotes = '',+ styleGrammarId = null,format,renderer = 'auto',interactive = false,@@ -269,7 +279,7 @@ export function buildCodeAnimationPrompt({if (isNonBlankStr(onScreenText)) {sections.push(`ON-SCREEN TEXT / NARRATION BEATS (render typography procedurally, timed to the story; system fonts only):\n${trimTo(onScreenText, CODE_ANIMATION_LIMITS.textMax)}`);}- sections.push(`ART DIRECTION:\n${artDirectionSection({ universe, styleNotes, hasMoodBoard: !!moodBoard })}`);+ sections.push(`ART DIRECTION:\n${artDirectionSection({ universe, styleNotes, styleGrammarId, hasMoodBoard: !!moodBoard })}`);const boardText = moodBoardSection(moodBoard);if (boardText) sections.push(boardText);const imagesText = referenceImagesSection(referenceImages, delivery);diff --git a/server/services/codeAnimation/prompt.test.js b/server/services/codeAnimation/prompt.test.jsindex e0ab78f0d0..66ff9a276c 100644--- a/server/services/codeAnimation/prompt.test.js+++ b/server/services/codeAnimation/prompt.test.js@@ -35,6 +35,28 @@ describe('buildCodeAnimationPrompt', () => {expect(prompt).not.toContain('No style was specified');});+ it('places one style grammar between the universe lines and the notes, with stated precedence, and is unchanged without one', () => {+ const input = {+ concept: 'x', styleNotes: 'slower camera', format,+ universe: { name: 'Example Universe', embrace: ['ink wash'], avoid: [], styleNotes: '', styleReferences: [] },+ };+ const plain = buildCodeAnimationPrompt(input);+ expect(plain).not.toContain('STYLE GRAMMAR');+ expect(buildCodeAnimationPrompt({ ...input, styleGrammarId: null })).toBe(plain);+ const prompt = buildCodeAnimationPrompt({ ...input, styleGrammarId: 'blueprint-draft' });+ expect(prompt.match(/STYLE GRAMMAR:/g)).toHaveLength(1);+ expect(prompt).toContain('Film style grammar: Blueprint draft');+ expect(prompt).toContain('the style grammar wins on rendering technique, motion stepping, camera moves and sound');+ const at = (text) => prompt.indexOf(text);+ expect(at('Visual style to embrace')).toBeLessThan(at('STYLE GRAMMAR:'));+ expect(at('STYLE GRAMMAR:')).toBeLessThan(at('Refinements for this animation'));+ expect(at('Refinements for this animation')).toBeLessThan(at('SOUND:'));+ });++ it('rejects an unknown style grammar id', () => {+ expect(() => buildCodeAnimationPrompt({ concept: 'x', format, styleGrammarId: 'no-such-style' })).toThrow(/Unknown film style grammar/);+ });+it('turns a character bible into rigging instructions, and omits them without one', () => {const withCast = buildCodeAnimationPrompt({concept: 'x',