Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: Code Animation plans films like a studio short

[._.]/ Adam Eivy41da4c607c21
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index 931e56535f..83c37e8805 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -35,6 +35,7 @@ const DEFAULT_DRAFT = {
title: '',
seedIdea: '',
concept: '',
+ cast: '',
onScreenText: '',
styleNotes: '',
universeId: '',
@@ -81,6 +82,7 @@ const loadDraft = () => {
title: stringField('title'),
seedIdea: stringField('seedIdea'),
concept: stringField('concept'),
+ cast: stringField('cast'),
onScreenText: stringField('onScreenText'),
styleNotes: stringField('styleNotes'),
universeId: stringField('universeId'),
@@ -113,6 +115,7 @@ function toBrief(draft) {
return {
title: draft.title,
concept: draft.concept,
+ cast: draft.cast,
onScreenText: draft.onScreenText,
styleNotes: draft.styleNotes,
format: draft.format,
@@ -138,6 +141,7 @@ function toBriefIdeaInput(draft) {
current: {
title: draft.title,
concept: draft.concept,
+ cast: draft.cast,
onScreenText: draft.onScreenText,
styleNotes: draft.styleNotes,
},
@@ -159,6 +163,7 @@ function draftFromJob(job) {
title: input.title || '',
seedIdea: input.seedIdea || '',
concept: input.concept || '',
+ cast: input.cast || '',
onScreenText: input.onScreenText || '',
styleNotes: input.styleNotes || '',
universeId: input.universeId || '',
@@ -408,6 +413,7 @@ export default function CodeAnimation() {
const startingBrief = {
title: draft.title,
concept: draft.concept,
+ cast: draft.cast,
onScreenText: draft.onScreenText,
styleNotes: draft.styleNotes,
};
@@ -423,13 +429,14 @@ export default function CodeAnimation() {
});
setWritingBrief(false);
if (!result?.brief) return;
- const { title, concept, onScreenText, styleNotes } = result.brief;
+ const { title, concept, cast = '', onScreenText, styleNotes } = result.brief;
// Style refinements live in the Style section, not the brief — only replace
// the artist's own notes when the writer actually asked for a refinement.
setDraft((previous) => ({
...previous,
...(previous.title === startingBrief.title ? { title } : {}),
...(previous.concept === startingBrief.concept ? { concept } : {}),
+ ...(previous.cast === startingBrief.cast ? { cast } : {}),
...(previous.onScreenText === startingBrief.onScreenText ? { onScreenText } : {}),
...(styleNotes && previous.styleNotes === startingBrief.styleNotes ? { styleNotes } : {}),
}));
@@ -662,7 +669,11 @@ export default function CodeAnimation() {
</div>
<div>
<label htmlFor="ca-concept" className={labelClass}>What happens</label>
- <textarea id="ca-concept" rows={4} value={draft.concept} maxLength={limits?.conceptMax} onChange={(event) => update({ concept: event.target.value })} placeholder="A paper lantern drifts over a sleeping harbor town, gathers fireflies, and bursts into a constellation at the climax." className={`${inputClass} resize-y`} />
+ <textarea id="ca-concept" rows={6} value={draft.concept} maxLength={limits?.conceptMax} onChange={(event) => update({ concept: event.target.value })} placeholder={'A paper lantern drifts over a sleeping harbor town, gathers fireflies, and bursts into a constellation.\n0:00–0:04 Low tracking shot: the lantern bobs past rooftops, curious…'} className={`${inputClass} resize-y`} />
+ </div>
+ <div>
+ <label htmlFor="ca-cast" className={labelClass}>Characters <span className="text-gray-600">(optional; design bible the animation rigs)</span></label>
+ <textarea id="ca-cast" rows={4} value={draft.cast} maxLength={limits?.castMax} onChange={(event) => update({ cast: event.target.value })} placeholder="Wick — a palm-sized paper lantern: round body, bent-wire handle that droops when sad; palette cream #F3E6C4, ember #E8763A; face: two ink-dot eyes (curious, sleepy, startled, delighted, determined). Identity lock: silhouette and handle never change." className={`${inputClass} resize-y`} />
</div>
<div>
<label htmlFor="ca-text" className={labelClass}>On-screen text / narration <span className="text-gray-600">(optional)</span></label>
diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsx
index 0c6cbc5e72..9bdfdb4d5c 100644
--- a/client/src/pages/CodeAnimation.test.jsx
+++ b/client/src/pages/CodeAnimation.test.jsx
@@ -133,6 +133,7 @@ describe('Code Animation page', () => {
brief: {
title: 'The Brass Wick',
concept: 'Mira climbs the flooded arcade as the lamps go out.',
+ cast: 'Mira — tall, oil-stained coat',
onScreenText: '0:02 "One light remains"',
styleNotes: 'colder blues at the climax',
},
@@ -157,6 +158,7 @@ describe('Code Animation page', () => {
});
expect(await screen.findByLabelText(/what happens/i)).toHaveValue('Mira climbs the flooded arcade as the lamps go out.');
expect(screen.getByLabelText(/^title/i)).toHaveValue('The Brass Wick');
+ expect(screen.getByLabelText(/^characters/i)).toHaveValue('Mira — tall, oil-stained coat');
expect(screen.getByLabelText(/on-screen text/i)).toHaveValue('0:02 "One light remains"');
expect(screen.getByLabelText(/style refinements/i)).toHaveValue('colder blues at the climax');
});
diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.js
index bd2e6b5fe6..65bfc71f8e 100644
--- a/server/routes/codeAnimation.js
+++ b/server/routes/codeAnimation.js
@@ -49,6 +49,8 @@ const formatSchema = z.object({
const briefSchema = z.object({
title: z.string().trim().max(L.titleMax).default(''),
concept: z.string().trim().min(1, 'Describe what happens in the animation').max(L.conceptMax),
+ // The lead characters' design bible — what the coding model rigs.
+ cast: z.string().trim().max(L.castMax).default(''),
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(''),
@@ -90,7 +92,7 @@ const briefIdeaSchema = z.object({
// The same brief, partially filled — derived from briefSchema so the field
// caps are stated once, with `concept` relaxed because there may be none yet.
current: briefSchema
- .pick({ title: true, onScreenText: true, styleNotes: true })
+ .pick({ title: true, cast: true, onScreenText: true, styleNotes: true })
.extend({ concept: z.string().trim().max(L.conceptMax).default('') })
.prefault({}),
// Only the two the writer's prompt reads — the renderer, fps, and resolution
diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.js
index 2c2374dfdd..b33367c507 100644
--- a/server/routes/codeAnimation.test.js
+++ b/server/routes/codeAnimation.test.js
@@ -98,6 +98,7 @@ describe('POST /api/code-animation/brief', () => {
runPromptThroughProvider.mockResolvedValue(briefResponse({
title: 'The Brass Wick',
concept: 'Mira climbs the flooded arcade as the lamps go out one by one.',
+ cast: 'Mira — tall, oil-stained coat; lantern pole that dips when she is afraid.',
onScreenText: '0:02 "One light remains"',
styleNotes: 'colder blues at the climax',
}));
@@ -109,6 +110,7 @@ describe('POST /api/code-animation/brief', () => {
expect(res.body.brief).toEqual({
title: 'The Brass Wick',
concept: 'Mira climbs the flooded arcade as the lamps go out one by one.',
+ cast: 'Mira — tall, oil-stained coat; lantern pole that dips when she is afraid.',
onScreenText: '0:02 "One light remains"',
styleNotes: 'colder blues at the climax',
});
@@ -178,6 +180,16 @@ describe('POST /api/code-animation/prompt', () => {
expect(JSON.stringify(res.body)).not.toContain(PATHS.data);
});
+ it('rigs the brief\'s character bible into the coding prompt', async () => {
+ const res = await request(makeApp()).post('/api/code-animation/prompt').send({
+ ...brief,
+ cast: 'Wick — a palm-sized paper lantern whose wire handle droops when sad.',
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.prompt).toContain('CHARACTERS — the design bible');
+ expect(res.body.prompt).toContain('Wick — a palm-sized paper lantern whose wire handle droops when sad.');
+ });
+
it('skips the board when the user explicitly picks none', async () => {
const res = await request(makeApp()).post('/api/code-animation/prompt').send({ ...brief, moodBoardId: '' });
expect(res.status).toBe(200);
diff --git a/server/services/codeAnimation/brief.js b/server/services/codeAnimation/brief.js
index e60541393a..bc83af45f4 100644
--- a/server/services/codeAnimation/brief.js
+++ b/server/services/codeAnimation/brief.js
@@ -2,13 +2,21 @@
* Code Animation brief writer (pure).
*
* The sibling of `prompt.js`: where that one asks a model to CODE the film,
- * this one asks a model to WRITE the film — a title, what happens, the
- * on-screen text beats, and any style refinement — from the universe the user
+ * this one asks a model to WRITE the film — a title, a timed beat sheet, a
+ * character design bible, the on-screen text beats, and any style refinement —
+ * from the universe the user
* picked, exactly as the series/story surfaces do. The universe's narrative
* bible (logline, premise, style notes) and its canon cast/places/objects are
* the source material, so a generated brief stars the world's own characters
* in its own locations instead of inventing a parallel one.
*
+ * The writer plans the way a studio director briefs an animation team: a
+ * one-line hook, a lead whose design is specified tightly enough to rig (and
+ * locked so it survives style changes), wordless emotional acting, a payoff
+ * every few seconds, a signature device, an anchor motif, and an ending that
+ * lands. That plan is what lets the coding prompt aim at a studio short rather
+ * than a screensaver.
+ *
* Text prompt, not an image prompt: free-text `styleNotes` belongs here (see
* `lib/universeVisualStyle.js` for why the image side excludes it).
*
@@ -22,6 +30,18 @@ import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';
import { ServerError } from '../../lib/errorHandler.js';
import { CODE_ANIMATION_LIMITS, moodBoardSection, universeStyleLines } from './prompt.js';
+// What separates a studio short from a moving screensaver, distilled from how
+// strong animation briefs are written. Static text — the per-film specifics
+// come from the spark, universe, and board sections that follow.
+const DIRECTING_PRINCIPLES = `HOW TO DIRECT IT:
+- The film in one line: a premise that escalates and pays off with a reveal, twist, or loop. If you can't say it in one sentence, it's too complicated for this length.
+- Wordless and readable: the story must land with zero dialogue. Characters act through their eyes, posture, and one signature expressive feature (an antenna, a tail, ears, a scarf), plus a small vocabulary of non-verbal sounds.
+- Hook and density: open cold, mid-action, and hook within two seconds. Give the audience a new visual payoff every 3–5 seconds, and escalate — each repetition of a device bigger or stranger than the last (the rule of three works).
+- An emotional arc for the lead, beat by beat (e.g. delighted → curious → worried → determined), and one quiet, kind beat inside the chaos — often a small object or motif they protect — so we care.
+- A signature device: one distinctive, recurring visual mechanism (a transition, a transformation, a rule of the world) that is this film's own, varied each time it recurs.
+- Scale and camera: choose a point of view that makes the world cinematic (a tiny character with a camera at their eye level turns a curb into a cliff), and say how the camera moves in each beat.
+- The ending lands: a reveal that reframes everything, a punchline held for a beat, or a seamless loop back to the first frame.`;
+
function universeSection(universe) {
const lines = [`The film is set in the universe "${universe.name}". Everything you write must be canon to it.`];
if (isNonBlankStr(universe.logline)) lines.push(`Logline: ${universe.logline}`);
@@ -48,6 +68,7 @@ function currentSection(current) {
const rows = [
['Title', current.title],
['What happens', current.concept],
+ ['Characters', current.cast],
['On-screen text', current.onScreenText],
['Style refinements', current.styleNotes],
].filter(([, value]) => isNonBlankStr(value));
@@ -63,7 +84,7 @@ function currentSection(current) {
* @param {object|null} [input.moodBoard] - `collectBoardStyleContext` output
* @param {string} [input.seedIdea] - the artist's starting spark, if any
* @param {{ durationSeconds: number, aspectRatio: string }} input.format
- * @param {{ title: string, concept: string, onScreenText: string, styleNotes: string }} [input.current]
+ * @param {{ title: string, concept: string, cast?: string, onScreenText: string, styleNotes: string }} [input.current]
* @returns {string}
*/
export function buildCodeAnimationBriefPrompt({
@@ -75,7 +96,8 @@ export function buildCodeAnimationBriefPrompt({
}) {
const { durationSeconds, aspectRatio } = format;
const sections = [
- `You are a short-film director and writer. Write the brief for a ${durationSeconds}-second ${aspectRatio} animated film that will be drawn entirely in code — procedural shapes, strokes, particles, and typography, with no photographic or hand-drawn assets. Write something a creative coder can actually stage: silhouettes, light, motion, and a handful of clear beats rather than dialogue, facial acting, or crowds.`,
+ `You are a short-film director and writer briefing an animation team. Write the brief for a ${durationSeconds}-second ${aspectRatio} animated short that will be drawn entirely in code — procedural shapes, strokes, particles, and typography, with no photographic or hand-drawn assets. Aim for a real studio short people want to share, and write something a creative coder can actually stage: a small cast with strong silhouettes, stylized faces, light, motion, and clear timed beats rather than dialogue, lip-sync, or crowds.`,
+ DIRECTING_PRINCIPLES,
];
if (isNonBlankStr(seedIdea)) {
sections.push(`THE ARTIST'S SPARK — this is the film they want; honor it:\n${trimTo(seedIdea, CODE_ANIMATION_LIMITS.seedIdeaMax)}`);
@@ -93,11 +115,12 @@ export function buildCodeAnimationBriefPrompt({
}
sections.push(`WRITE:
- title: a short evocative title (max 80 characters).
-- concept: what happens, as a beat-by-beat account across the full ${durationSeconds} seconds (establish → develop → climax → resolve). Name the characters and places you are using, say what the camera does, and describe what the audience sees. 120–350 words, prose, no headings or markdown.
-- onScreenText: the on-screen typography and narration beats, one per line, each led by its timestamp (e.g. \`0:02 "Every night, one light remains"\`). Use at most a handful, and leave it as an empty string if the film is better with no text at all.
+- concept: the director's plan. First line: the film in one sentence — premise, escalation, and the payoff or twist. Then the beat sheet, one line per beat, each led by its time range covering the full ${durationSeconds} seconds (e.g. \`0:00–0:03 …\`), grouped into a few acts. For each beat say where we are, what the characters do and feel (their expression and body language), what the camera does, and the visual payoff. Name the characters and places you use. 200–650 words, plain text, no markdown.
+- cast: the design bible for the lead character(s), specific enough to build a 2D rig from without guessing — silhouette, proportions and scale, the parts and how they connect, a named palette with hex values, the face and a named expression set (at least five, each described by its shapes), the signature appendage that carries emotion, how they move, personality, and an identity lock (which features must never change, even when the world's style does). For canon characters, stay faithful to their entries and add the missing visual detail. 80–350 words, plain text, no markdown.
+- onScreenText: the on-screen typography and narration beats, one per line, each led by its timestamp (e.g. \`0:02 "Every night, one light remains"\`). Use at most a handful — text that is part of the world (a sign, a typed prompt, a note) beats captions — and leave it as an empty string if the film is better with no text at all.
- styleNotes: one or two sentences of refinement ON TOP OF the universe's established style — a palette shift, a grain, a camera behavior this particular film wants. Do NOT restate the universe's style; leave it an empty string if nothing needs refining.`);
sections.push(`OUTPUT: Return ONLY a JSON object, in a single \`\`\`json fenced code block, with exactly these keys:
-{"title": "...", "concept": "...", "onScreenText": "...", "styleNotes": "..."}
+{"title": "...", "concept": "...", "cast": "...", "onScreenText": "...", "styleNotes": "..."}
Every value is a plain string (use \\n for line breaks). No commentary before or after it, and do not create or edit any files.`);
return sections.join('\n\n');
}
@@ -124,6 +147,7 @@ export function extractBriefIdea(raw) {
return {
title: briefField(value.title, CODE_ANIMATION_LIMITS.titleMax),
concept,
+ cast: briefField(value.cast, CODE_ANIMATION_LIMITS.castMax),
onScreenText: briefField(value.onScreenText, CODE_ANIMATION_LIMITS.textMax),
styleNotes: briefField(value.styleNotes, CODE_ANIMATION_LIMITS.styleNotesMax),
};
diff --git a/server/services/codeAnimation/brief.test.js b/server/services/codeAnimation/brief.test.js
index 0b07468a45..b1a206777d 100644
--- a/server/services/codeAnimation/brief.test.js
+++ b/server/services/codeAnimation/brief.test.js
@@ -26,7 +26,7 @@ describe('buildCodeAnimationBriefPrompt', () => {
format: FORMAT,
current: { title: 'The Brass Wick', concept: '', onScreenText: '', styleNotes: '' },
});
- expect(prompt).toContain('20-second 16:9 animated film');
+ expect(prompt).toContain('20-second 16:9 animated short');
expect(prompt).toContain('a chase that ends in silence');
expect(prompt).toContain('The film is set in the universe "Example Universe"');
expect(prompt).toContain('Logline: A drowned city keeps its lamps lit');
@@ -35,7 +35,23 @@ describe('buildCodeAnimationBriefPrompt', () => {
expect(prompt).toContain(' - The Brass Wick (the last lamp that never gutters)');
expect(prompt).toContain('Mood board: "Dusk"');
expect(prompt).toContain('Title: The Brass Wick');
- expect(prompt).toContain('"title": "..."');
+ expect(prompt).toContain('"cast": "..."');
+ });
+
+ it('asks for a director\'s plan: a timed beat sheet and a rig-ready character bible', () => {
+ const prompt = buildCodeAnimationBriefPrompt({ seedIdea: 'a robot realizes its world is generated', format: FORMAT });
+ expect(prompt).toContain('HOW TO DIRECT IT');
+ expect(prompt).toContain('new visual payoff every 3–5 seconds');
+ expect(prompt).toContain('each led by its time range covering the full 20 seconds');
+ expect(prompt).toContain('identity lock');
+ });
+
+ it('shows the writer the character bible the artist already drafted', () => {
+ const prompt = buildCodeAnimationBriefPrompt({
+ format: FORMAT,
+ current: { title: '', concept: '', cast: 'Wick — a paper lantern with a drooping wire handle', onScreenText: '', styleNotes: '' },
+ });
+ expect(prompt).toContain('Characters: Wick — a paper lantern with a drooping wire handle');
});
it('tells the model to invent a cast when the universe has no canon yet', () => {
@@ -81,11 +97,13 @@ describe('extractBriefIdea', () => {
expect(extractBriefIdea(response({
title: 'The Brass Wick',
concept: 'Mira climbs the flooded arcade…',
+ cast: 'Mira — tall, oil-stained coat',
onScreenText: '',
styleNotes: 'colder blues at the climax',
}))).toEqual({
title: 'The Brass Wick',
concept: 'Mira climbs the flooded arcade…',
+ cast: 'Mira — tall, oil-stained coat',
onScreenText: '',
styleNotes: 'colder blues at the climax',
});
@@ -95,11 +113,13 @@ describe('extractBriefIdea', () => {
const parsed = extractBriefIdea(response({
title: 'T'.repeat(500),
concept: 'C'.repeat(CODE_ANIMATION_LIMITS.conceptMax + 100),
+ cast: 'K'.repeat(CODE_ANIMATION_LIMITS.castMax + 100),
onScreenText: 'O'.repeat(CODE_ANIMATION_LIMITS.textMax + 100),
styleNotes: 'S'.repeat(CODE_ANIMATION_LIMITS.styleNotesMax + 100),
}));
expect(parsed.title.length).toBe(CODE_ANIMATION_LIMITS.titleMax);
expect(parsed.concept.length).toBe(CODE_ANIMATION_LIMITS.conceptMax);
+ expect(parsed.cast.length).toBe(CODE_ANIMATION_LIMITS.castMax);
expect(parsed.onScreenText.length).toBe(CODE_ANIMATION_LIMITS.textMax);
expect(parsed.styleNotes.length).toBe(CODE_ANIMATION_LIMITS.styleNotesMax);
});
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
index 5bcefad1d4..6f92419c31 100644
--- a/server/services/codeAnimation/index.js
+++ b/server/services/codeAnimation/index.js
@@ -207,6 +207,7 @@ export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {
const promptInput = {
title: input.title,
concept: input.concept,
+ cast: input.cast,
onScreenText: input.onScreenText,
styleNotes: input.styleNotes,
format: input.format,
@@ -234,8 +235,8 @@ export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {
}
/**
- * Write the brief itself: ask a model for a title / concept / on-screen text /
- * style refinement grounded in the universe's bible and canon cast, the same
+ * Write the brief itself: ask a model for a title / beat sheet / character
+ * bible / on-screen text / style refinement grounded in the universe's bible and canon cast, the same
* way a series or story is generated from a universe. Synchronous — a few
* hundred words comes back inside one request, unlike the HTML generation.
*
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index 0ab7a2abae..b5ca4d6daf 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -6,7 +6,9 @@
* produced by code. The art style comes from the universe's style guide (its
* curated embrace/avoid tokens, style references, and tone notes), refined by a
* mood board's notes/captions/analyses, reference images, optional per-film
- * style notes, and an audio track.
+ * style notes, and an audio track. A character design bible, when the brief
+ * has one, becomes rigging instructions, and a fixed direction section and
+ * self-review pass hold the output to a studio-short craft bar.
*
* The prompt also pins a small RUNTIME CONTRACT the PortOS preview host relies
* on — a deterministic `renderFrame(t)`, `ANIMATION_META`, the audio URL hook,
@@ -60,6 +62,7 @@ export const CODE_ANIMATION_LIMITS = Object.freeze({
titleMax: 200,
seedIdeaMax: 2_000,
conceptMax: 6_000,
+ castMax: 4_000,
textMax: 4_000,
styleNotesMax: 2_000,
referenceImagesMax: 8,
@@ -177,11 +180,52 @@ function audioSection({ audio, soundtrack, durationSeconds }) {
return lines.join('\n');
}
if (soundtrack === 'procedural') {
- return 'No audio file was supplied. Compose a procedural soundtrack with the Web Audio API (oscillators, noise, envelopes, a simple sequencer) that matches the mood and is synchronized to the visual beats. Start it on the first user gesture (Play/Record); resume a suspended AudioContext.';
+ return [
+ 'No audio file was supplied. Design an original procedural soundtrack with the Web Audio API (oscillators, FM, filtered noise, envelopes, a simple sequencer), scheduled from the same timeline as the picture so every sound lands on its frame. Start it on the first user gesture (Play/Record); resume a suspended AudioContext.',
+ '- Voice: wordless characters get a small emotional vocabulary of synthesized chirps, boops, hums, or warbles (sine/FM tones with pitch bends) — e.g. a curious rising chirp, a happy trill, a worried wobble, a startled squeak, a grumpy buzz, a sigh — cued to their expressions.',
+ '- Foley: motion has sound — servo whirs, footsteps or wheel crunch, cloth or spring creaks, clicks — matched to the moves that cause it.',
+ '- Score: a light, loopable bed whose instrumentation or filter shifts with each scene or world, plus a distinct sound for the signature transition.',
+ '- Silence is a beat: cut all audio for a freeze, a reveal, or a punchline, then bring the room tone back.',
+ ].join('\n');
}
return 'The animation is silent — no audio.';
}
+// The character bible turned into rigging instructions. A studio short lives or
+// dies on its lead reading as the same character in every frame and every
+// style, so the model builds the character once, as a parameterized rig, and
+// animates that rig rather than redrawing a figure per shot.
+function castSection(cast) {
+ return `CHARACTERS — the design bible (non-negotiable; every frame must stay on-model):
+${trimTo(cast, CODE_ANIMATION_LIMITS.castMax)}
+
+Build each lead ONCE as a 2D cutout rig before animating anything:
+- A part hierarchy with pivots (root → body → head → face; limbs as segmented chains; appendages like antennae, tails, ears, or scarves as their own joints), drawn from functions that take pose parameters.
+- A procedural face: eyes, lids, pupils, brows, and mouth driven by parameters (size, lid cuts, pupil position, highlight, squash/stretch, special shapes such as hearts, stars, spirals, flat lines). Implement every named expression as a parameter preset and blend between presets; blink in 3–4 frames.
+- Secondary motion on damped springs — appendages, hair, cloth, suspension, head lag when the body accelerates or brakes — so nothing moves rigidly.
+- Reusable cycles (move, idle breathing with blinks and twitches, react) and turnaround views for turns.
+- A style/skin parameter (line weight, fill, texture, shading, outline boil) that restyles the rig without changing its geometry, so the character stays recognizable when the world changes style.
+- Locomotion that is physically honest: wheels rotate by distance traveled, feet plant without sliding, stops land with weight.`;
+}
+
+// The craft bar. A one-shot HTML file can't run a multi-session render-and-
+// review loop, so the loop is folded into how the model structures the code
+// and what it checks before answering.
+function directionSection() {
+ return `DIRECTION — make it feel like a studio short, not a tech demo:
+- Structure the code like a production: a shot/beat timeline (an array of { start, end, … } entries mapped from the brief's timestamps), a virtual camera (position, zoom, rotation, seeded handheld micro-shake, shake impulses, tilts, dolly moves), a scene/world layer system shared by every shot, the character rigs, the transitions, and a final finish pass.
+- Depth and scale (unless the art style is deliberately flat): at least four parallax layers per scene with atmospheric perspective (haze and desaturation with distance), a shallow-focus feel (blurred foreground elements), and a camera height chosen to sell the characters' scale.
+- Lighting: key, fill, and rim on the characters as gradient overlays and multiplied shadow layers; glowing elements cast light on nearby surfaces. Finish the whole frame with a pass that suits the style (e.g. subtle grain and a gentle vignette).
+- Performance: anticipation, squash and stretch, overlap, easing, and deliberate holds — a held reaction (a one-second deadpan, a freeze) is what lets a gag land. Emotion reads through the eyes, posture, and signature appendage, never through captions.
+- Pacing: open cold and hook in the first two seconds; give the audience a new visual payoff every 3–5 seconds; vary each repeated device (transition direction, noise seed, timing) so it never feels copy-pasted.
+- Readability: compose on thirds, and keep faces, eyes, and any text legible at phone size (about 360px wide); typed on-screen text types at a human rhythm with small pauses.
+- Endings: the player loops the film — when the brief ends by returning to its opening, match the final frame's framing, lighting, and motion to t=0 so the cut back feels intentional.`;
+}
+
+// The critique pass the reference workflow runs on rendered stills, as a
+// pre-answer check against the failures one-shot animation code shows most.
+const SELF_REVIEW = `SELF-REVIEW before you answer: step through renderFrame at every beat's key frame in your head and score it honestly on character on-model, emotion readable from the face and body alone, story clear without sound, composition, depth, scale, lighting, and phone-size readability. Fix anything that would score below 8/10. Hunt especially for: stiff or dead secondary motion, sliding feet or wheels, faces that look like stickers, missing weight on stops and landings, identical-looking transitions, muddy or unreadable text, off-model proportions, empty or static stretches, and beats the brief asked for that never made it on screen.`;
+
function runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio }) {
const m = CODE_ANIMATION_MESSAGES;
const audioTrack = hasAudio
@@ -210,6 +254,7 @@ ${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textur
* @param {object} input
* @param {string} [input.title]
* @param {string} input.concept - what happens in the film (required upstream)
+ * @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 {{ durationSeconds: number, aspectRatio: string, resolution: string, fps: number }} input.format
@@ -226,6 +271,7 @@ ${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textur
export function buildCodeAnimationPrompt({
title = '',
concept,
+ cast = '',
onScreenText = '',
styleNotes = '',
format,
@@ -241,9 +287,10 @@ export function buildCodeAnimationPrompt({
const { width, height } = resolveFrameSize(format.aspectRatio, format.resolution);
const { durationSeconds, fps } = format;
const sections = [
- `You are an award-winning creative coder and motion designer. Write ONE complete, self-contained HTML file that renders a ${durationSeconds}-second animated film entirely in code — no image, video, font, or library assets. Every shape, texture, character, and effect is drawn procedurally in the browser, in the art style below, with the craft of a finished title sequence rather than a tech demo.`,
+ `You are the director, animator, rigger, compositor, sound designer, and render engineer of a ${durationSeconds}-second animated short made entirely in code. Write ONE complete, self-contained HTML file that renders it — no image, video, font, or library assets. Every shape, texture, character, and effect is drawn procedurally in the browser, in the art style below. The bar: it looks like a real studio short that people share, not a tech demo.`,
`BRIEF${isNonBlankStr(title) ? ` — "${trimTo(title, 200)}"` : ''}:\n${trimTo(concept, CODE_ANIMATION_LIMITS.conceptMax)}`,
];
+ if (isNonBlankStr(cast)) sections.push(castSection(cast));
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)}`);
}
@@ -254,8 +301,10 @@ export function buildCodeAnimationPrompt({
if (imagesText) sections.push(imagesText);
sections.push(`SOUND:\n${audioSection({ audio, soundtrack, durationSeconds })}`);
sections.push(`FORMAT: ${format.aspectRatio} at ${width}×${height}px, ${fps}fps, ${durationSeconds}s. ${RENDERER_GUIDANCE[renderer] || RENDERER_GUIDANCE.auto}
-Plan the film as a sequence of beats with clear timestamps (establish → develop → climax → resolve) and build smooth transitions between them. Use easing curves, anticipation, overlap, and secondary motion; vary shot scale and camera movement (pan, zoom, parallax) so it feels directed.`);
+Stage the brief's beats at their timestamps; where it gives none, plan the film as timed beats yourself (establish → develop → climax → resolve).`);
+ sections.push(directionSection());
sections.push(runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio: !!audio }));
+ sections.push(SELF_REVIEW);
sections.push(`OUTPUT: Return ONLY the finished HTML document in a single \`\`\`html fenced code block, starting with <!DOCTYPE html>. No explanation before or after it.${delivery === 'cli' ? ' Do not create or edit any files — print the document as your final answer.' : ''}`);
return sections.join('\n\n');
}
diff --git a/server/services/codeAnimation/prompt.test.js b/server/services/codeAnimation/prompt.test.js
index 4cf1ec4462..54ea1a776d 100644
--- a/server/services/codeAnimation/prompt.test.js
+++ b/server/services/codeAnimation/prompt.test.js
@@ -31,6 +31,28 @@ describe('buildCodeAnimationPrompt', () => {
expect(prompt).not.toContain('No style was specified');
});
+ it('turns a character bible into rigging instructions, and omits them without one', () => {
+ const withCast = buildCodeAnimationPrompt({
+ concept: 'x',
+ cast: 'Wick — a palm-sized paper lantern whose wire handle droops when sad',
+ format,
+ });
+ expect(withCast).toContain('CHARACTERS — the design bible');
+ expect(withCast).toContain('Wick — a palm-sized paper lantern whose wire handle droops when sad');
+ expect(withCast).toContain('procedural face');
+ expect(buildCodeAnimationPrompt({ concept: 'x', format })).not.toContain('CHARACTERS —');
+ });
+
+ it('holds every film to the direction bar and a pre-answer self-review', () => {
+ const prompt = buildCodeAnimationPrompt({ concept: 'x', format });
+ expect(prompt).toContain('DIRECTION — make it feel like a studio short');
+ expect(prompt).toContain('virtual camera');
+ expect(prompt).toContain('SELF-REVIEW before you answer');
+ // The self-review follows the runtime contract, right before the output rule.
+ expect(prompt.indexOf('SELF-REVIEW')).toBeGreaterThan(prompt.indexOf('RUNTIME CONTRACT'));
+ expect(prompt.indexOf('SELF-REVIEW')).toBeLessThan(prompt.indexOf('OUTPUT:'));
+ });
+
it('lets the model choose a style only when nothing configures one', () => {
expect(buildCodeAnimationPrompt({ concept: 'x', format })).toContain('No style was specified');
const withBoard = buildCodeAnimationPrompt({
@@ -63,7 +85,9 @@ describe('buildCodeAnimationPrompt', () => {
expect(withTrack).toContain('120 BPM, drop at 0:16');
expect(withTrack).toContain('MediaStreamAudioDestinationNode');
- expect(buildCodeAnimationPrompt({ concept: 'x', format, soundtrack: 'procedural' })).toContain('procedural soundtrack');
+ const procedural = buildCodeAnimationPrompt({ concept: 'x', format, soundtrack: 'procedural' });
+ expect(procedural).toContain('procedural soundtrack');
+ expect(procedural).toContain('Silence is a beat');
expect(buildCodeAnimationPrompt({ concept: 'x', format })).toContain('The animation is silent');
});