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: persist Code Animation Production projects and source revisions (#9386)

[._.]/ Adam Eivyd615b3930b65
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 233f86df79..0745d44789 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -606,6 +606,8 @@ export default function App() {
<Route path="catalog/:type/:id" element={<CatalogIngredient />} />
<Route path="code-animation" element={<CodeAnimation />} />
<Route path="code-animation/:jobId" element={<CodeAnimation />} />
+ <Route path="code-animation/production" element={<CodeAnimation />} />
+ <Route path="code-animation/production/:projectId" element={<CodeAnimation />} />
<Route path="mood-boards" element={<MoodBoards />} />
<Route path="mood-boards/:id" element={<MoodBoardDetail />} />
<Route path="decks" element={<Decks />} />
diff --git a/client/src/components/codeAnimation/ProductionProjectForm.jsx b/client/src/components/codeAnimation/ProductionProjectForm.jsx
new file mode 100644
index 0000000000..a60c0544d6
--- /dev/null
+++ b/client/src/components/codeAnimation/ProductionProjectForm.jsx
@@ -0,0 +1,75 @@
+import { useEffect, useState } from 'react';
+
+const inputClass = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm';
+const budgets = { iterations: 8, timeSeconds: 900, tokens: 128000, renderSeconds: 300, diskBytes: 512 * 1024 * 1024 };
+const emptyManifest = {
+ title: '', brief: { concept: '', cast: '', onScreenText: '' }, styleGuide: '',
+ renderer: { kind: 'browser', version: 'code-animation-html-v1', engine: null },
+ format: { width: 1920, height: 1080, fps: 30, durationSeconds: 20 }, seed: null,
+ entrypoints: [{ role: 'preview', path: 'index.html' }], assets: [], shots: [], events: [],
+ audio: { kind: 'silence' }, execution: { requested: null, effective: null },
+};
+
+export default function ProductionProjectForm({ project, onSave, busy, onDirtyChange }) {
+ const [manifest, setManifest] = useState(() => project?.manifest || emptyManifest);
+ const [limits, setLimits] = useState(() => project?.budgets || budgets);
+ const [baseline, setBaseline] = useState(() => JSON.stringify({ manifest: project?.manifest || emptyManifest, budgets: project?.budgets || budgets }));
+ const dirty = JSON.stringify({ manifest, budgets: limits }) !== baseline;
+ useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]);
+ const field = (name, label, value, change, type = 'text', props = {}) => (
+ <div key={name} className="min-w-0">
+ <label htmlFor={`cap-${name}`} className="mb-1 block text-xs text-gray-400">{label}</label>
+ <input id={`cap-${name}`} type={type} value={value ?? ''} onChange={event => change(type === 'number' ? Number(event.target.value) : event.target.value)} className={inputClass} {...props} />
+ </div>
+ );
+ return <form className="space-y-3" onSubmit={event => {
+ event.preventDefault();
+ onSave({ manifest, budgets: limits }).then(saved => {
+ if (saved) {
+ setManifest(saved.manifest);
+ setLimits(saved.budgets);
+ setBaseline(JSON.stringify({ manifest: saved.manifest, budgets: saved.budgets }));
+ }
+ });
+ }}>
+ <fieldset disabled={busy} className="min-w-0 space-y-3">
+ {field('title', 'Title', manifest.title, title => setManifest(previous => ({ ...previous, title })), 'text', { maxLength: 200 })}
+ <div>
+ <label htmlFor="cap-concept" className="mb-1 block text-xs text-gray-400">Film brief</label>
+ <textarea id="cap-concept" rows={3} maxLength={6000} value={manifest.brief.concept} onChange={event => setManifest(previous => ({ ...previous, brief: { ...previous.brief, concept: event.target.value } }))} className={inputClass} />
+ </div>
+ <div>
+ <label htmlFor="cap-style" className="mb-1 block text-xs text-gray-400">Style and reference intent</label>
+ <textarea id="cap-style" rows={2} maxLength={16000} value={manifest.styleGuide} onChange={event => setManifest(previous => ({ ...previous, styleGuide: event.target.value }))} className={inputClass} />
+ </div>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div>
+ <label htmlFor="cap-renderer" className="mb-1 block text-xs text-gray-400">Renderer</label>
+ <select id="cap-renderer" className={inputClass} value={manifest.renderer.kind} onChange={event => setManifest(previous => ({ ...previous, renderer: { ...previous.renderer, kind: event.target.value } }))}>
+ <option value="browser">Browser</option><option value="blender">Blender</option>
+ </select>
+ </div>
+ {field('version', 'Renderer version', manifest.renderer.version, version => setManifest(previous => ({ ...previous, renderer: { ...previous.renderer, version } })), 'text', { required: true, maxLength: 128 })}
+ {Object.entries({ width: 'Width (pixels)', height: 'Height (pixels)', fps: 'Frames per second', durationSeconds: 'Duration (seconds)' }).map(([name, label]) =>
+ field(name, label, manifest.format[name], value => setManifest(previous => ({ ...previous, format: { ...previous.format, [name]: value } })), 'number', { required: true, min: name === 'width' || name === 'height' ? 2 : 1, step: name === 'width' || name === 'height' ? 2 : 1 }))}
+ <div>
+ <label htmlFor="cap-seed" className="mb-1 block text-xs text-gray-400">Deterministic seed (optional)</label>
+ <input id="cap-seed" type="number" min={0} max={4294967295} step={1} value={manifest.seed ?? ''} className={inputClass} onChange={event => setManifest(previous => ({ ...previous, seed: event.target.value === '' ? null : Number(event.target.value) }))} />
+ </div>
+ <div>
+ <label htmlFor="cap-audio" className="mb-1 block text-xs text-gray-400">Soundtrack policy</label>
+ <select id="cap-audio" value={manifest.audio.kind} className={inputClass} onChange={event => setManifest(previous => ({ ...previous, audio: event.target.value === 'silence' ? { kind: 'silence' } : { kind: event.target.value, notes: '' } }))}>
+ <option value="silence">Intentional silence</option><option value="procedural">Procedural sound</option><option value="external">External soundtrack</option>
+ {manifest.audio.kind === 'file' && <option value="file">Packaged audio file</option>}
+ </select>
+ </div>
+ </div>
+ <h3 className="text-sm font-medium">Independent budgets</h3>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {Object.entries({ iterations: 'Iterations', timeSeconds: 'Elapsed time (seconds)', tokens: 'Tokens', renderSeconds: 'Render time (seconds)', diskBytes: 'Retained source disk (bytes)' }).map(([name, label]) =>
+ field(name, label, limits[name], value => setLimits(previous => ({ ...previous, [name]: value })), 'number', { required: true, min: 1, step: 1 }))}
+ </div>
+ <button type="submit" className="rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">{busy ? 'Saving…' : project ? 'Save project settings' : 'Create Production project'}</button>
+ </fieldset>
+ </form>;
+}
diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsx
new file mode 100644
index 0000000000..03ce1a465b
--- /dev/null
+++ b/client/src/components/codeAnimation/ProductionProjects.jsx
@@ -0,0 +1,138 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Link, useNavigate, useParams } from 'react-router';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { useSocketResource } from '../../hooks/useSocketResource';
+import { useSocketSubscription } from '../../hooks/useSocketSubscription';
+import { usePagedCollection } from '../../hooks/usePagedCollection';
+import socket from '../../services/socket';
+import {
+ listCodeAnimationProjects, createCodeAnimationProject, getCodeAnimationProject,
+ updateCodeAnimationProject, importCodeAnimationPackage, acceptCodeAnimationSource,
+ getCodeAnimationProjectBrief, getCodeAnimationRevisionPackage, listCodeAnimationProjectHistory,
+} from '../../services/apiCodeAnimation';
+import { downloadBlob } from '../../lib/downloadBlob';
+import { formatCount, formatBytes, timeAgo } from '../../utils/formatters';
+import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
+import ProductionProjectForm from './ProductionProjectForm';
+
+const EVENTS = ['code-animation:changed'];
+const buttonClass = 'rounded border border-port-border px-3 py-2 text-sm hover:border-port-accent disabled:opacity-50';
+
+export default function ProductionProjects() {
+ const { projectId = '' } = useParams();
+ const navigate = useNavigate();
+ const [dirty, setDirty] = useState(false);
+ const loadProjects = useCallback(({ cursor, signal }) => listCodeAnimationProjects({ cursor, signal }), []);
+ const projects = usePagedCollection(loadProjects);
+ const resource = useSocketResource(({ signal }) => getCodeAnimationProject(projectId, { signal, silent: true }), {
+ namespace: 'code-animation', events: EVENTS, resourceKey: projectId, enabled: !!projectId,
+ matchesEvent: payload => payload?.id === projectId,
+ });
+ const loadHistory = useCallback(({ cursor, signal }) => listCodeAnimationProjectHistory(projectId, { cursor, signal }), [projectId]);
+ const history = usePagedCollection(loadHistory, { enabled: !!projectId });
+ useSocketSubscription('code-animation', { onResubscribe: () => {
+ projects.refreshFirst();
+ if (projectId) history.refreshFirst();
+ } });
+ useEffect(() => {
+ const changed = payload => {
+ projects.refreshFirst();
+ if (projectId && payload?.id === projectId) history.refreshFirst();
+ };
+ socket.on('code-animation:changed', changed);
+ return () => socket.off('code-animation:changed', changed);
+ }, [projectId, projects.refreshFirst, history.refreshFirst]);
+
+ const [act, busy] = useAsyncAction(async operation => operation());
+ const applyProject = project => {
+ resource.updateData(project);
+ projects.setItems(previous => [project, ...previous.filter(item => item.id !== project.id)]);
+ };
+ const save = input => act(async () => {
+ const project = projectId
+ ? await updateCodeAnimationProject(projectId, input, { silent: true })
+ : await createCodeAnimationProject(input, { silent: true });
+ applyProject(project);
+ if (!projectId) navigate(`/code-animation/production/${project.id}`);
+ return project;
+ });
+ const importFile = event => {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (!file) return;
+ act(async () => {
+ if (file.size > 55 * 1024 * 1024) throw new Error('Package file exceeds the import size limit');
+ const result = await importCodeAnimationPackage(projectId, JSON.parse(await file.text()), { silent: true });
+ applyProject(result.project);
+ history.setItems(previous => [{
+ id: result.runId, status: 'completed', revisionId: result.revision.id,
+ createdAt: result.revision.createdAt,
+ data: { kind: 'package-import', executed: false, packageHash: result.revision.packageHash, totalBytes: result.revision.totalBytes },
+ }, ...previous]);
+ });
+ };
+ const download = (revisionId = null) => act(async () => {
+ const data = revisionId
+ ? await getCodeAnimationRevisionPackage(projectId, revisionId, { silent: true })
+ : await getCodeAnimationProjectBrief(projectId, { silent: true });
+ downloadBlob(JSON.stringify(data, null, 2), revisionId ? `source-${revisionId}.json` : 'animation-brief.json', 'application/json');
+ });
+ const project = resource.data;
+ return <div className="space-y-4">
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h2 className="text-base font-semibold">Production projects</h2>
+ <Link to="/code-animation/production" className={buttonClass}>New Production project</Link>
+ </div>
+ <p className="text-sm text-gray-400">Keep a film brief, independent budgets and immutable source revisions. Import and source acceptance stage files; rendering and evidence review are separate production stages.</p>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
+ {projects.items.map(item => <Link key={item.id} to={`/code-animation/production/${item.id}`} className="min-w-0 rounded border border-port-border p-3 hover:border-port-accent" aria-current={item.id === projectId ? 'page' : undefined}>
+ <span className="block truncate font-medium">{item.title || 'Untitled production'}</span>
+ <span className="text-xs text-gray-400">{item.acceptedRevisionId ? 'Accepted source' : 'No accepted source'} · {timeAgo(item.createdAt)}</span>
+ </Link>)}
+ </div>
+ <InfiniteScrollFooter hasMore={projects.hasMore} loading={projects.loading} error={projects.error} onLoadMore={projects.loadMore} autoLoad={false} label="Load older projects" />
+ </section>
+
+ {projectId && resource.loading && <p>Loading production project…</p>}
+ {resource.error && <div role="alert" className="rounded border border-port-error p-3">
+ <p>{resource.error.status === 404 ? 'Production project not found' : resource.error.message}</p>
+ {resource.error.status !== 404 && <button className={buttonClass} onClick={resource.refetch}>Retry project</button>}
+ </div>}
+ {(!projectId || project) && <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <section className="min-w-0 space-y-3 rounded-xl border border-port-border bg-port-card p-4">
+ <h2 className="text-base font-semibold">{project ? project.title || 'Untitled production' : 'New Production project'}</h2>
+ <ProductionProjectForm key={projectId || 'new'} project={project} onSave={save} busy={busy} onDirtyChange={setDirty} />
+ </section>
+ {project && <section className="min-w-0 space-y-4 rounded-xl border border-port-border bg-port-card p-4">
+ <h2 className="text-base font-semibold">Source and history</h2>
+ <div className="flex flex-wrap gap-2">
+ <button className={buttonClass} disabled={busy || dirty} onClick={() => download()}>Export brief</button>
+ {project.acceptedRevisionId && <button className={buttonClass} disabled={busy} onClick={() => download(project.acceptedRevisionId)}>Export accepted package</button>}
+ {project.candidateRevisionId && <>
+ <button className={buttonClass} disabled={busy} onClick={() => download(project.candidateRevisionId)}>Export candidate package</button>
+ <button className={buttonClass} disabled={busy} onClick={() => act(async () => applyProject(await acceptCodeAnimationSource(projectId, project.candidateRevisionId, { silent: true })))}>Accept candidate source</button>
+ </>}
+ </div>
+ <div>
+ <label htmlFor="cap-import" className="mb-1 block text-sm">Import source package as a new candidate</label>
+ <input id="cap-import" type="file" accept=".json,application/json" disabled={busy || dirty} onChange={importFile} className="w-full min-w-0 text-sm" />
+ {dirty && <p className="mt-1 text-xs text-gray-400">Save project settings before importing or exporting the brief.</p>}
+ </div>
+ <p className="text-xs text-gray-400">Imports never execute source or install dependencies. Failed candidates retain accepted source. Accepting source records your selection; it does not mark rendering, motion or sound as verified.</p>
+ <p className="text-xs text-gray-400">Requested model: {project.localSettings?.model || 'Unspecified'} · Mode: {project.localSettings?.mode || 'Unspecified'}</p>
+ <ul className="space-y-2">
+ {history.items.map(run => <li key={run.id} className="min-w-0 space-y-1 rounded border border-port-border p-3">
+ <div className="flex flex-wrap justify-between gap-2 text-sm"><span>Package import · {run.status}</span><span>{timeAgo(run.createdAt)}</span></div>
+ <p className="break-all text-xs text-gray-400">{run.data.packageHash}</p>
+ <p className="text-xs text-gray-400">{formatBytes(run.data.totalBytes || 0)} · Source execution: {run.data.executed ? 'Recorded' : 'None'}</p>
+ {run.data.error && <p className="text-xs text-port-error">{run.data.error}</p>}
+ {run.revisionId && <button className={buttonClass} disabled={busy} onClick={() => download(run.revisionId)}>Export this revision</button>}
+ </li>)}
+ </ul>
+ <InfiniteScrollFooter hasMore={history.hasMore} loading={history.loading} error={history.error} onLoadMore={history.loadMore} autoLoad={false} label="Load older runs" />
+ <p className="text-xs text-gray-400">{formatCount(history.items.length)} loaded runs</p>
+ </section>}
+ </div>}
+ </div>;
+}
diff --git a/client/src/components/codeAnimation/ProductionProjects.test.jsx b/client/src/components/codeAnimation/ProductionProjects.test.jsx
new file mode 100644
index 0000000000..6608a02e82
--- /dev/null
+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router';
+
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
+vi.mock('../../services/apiCodeAnimation', () => ({
+ listCodeAnimationProjects: vi.fn(), createCodeAnimationProject: vi.fn(), getCodeAnimationProject: vi.fn(),
+ updateCodeAnimationProject: vi.fn(), importCodeAnimationPackage: vi.fn(), acceptCodeAnimationSource: vi.fn(),
+ getCodeAnimationProjectBrief: vi.fn(), getCodeAnimationRevisionPackage: vi.fn(), listCodeAnimationProjectHistory: vi.fn(),
+}));
+import * as api from '../../services/apiCodeAnimation';
+import ProductionProjects from './ProductionProjects';
+
+const project = {
+ id: '00000000-0000-4000-8000-000000000001', title: 'Example Production',
+ manifest: {
+ title: 'Example Production', brief: { concept: 'A cube hops.', cast: '', onScreenText: '' }, styleGuide: 'Graphic shapes',
+ renderer: { kind: 'browser', version: 'example-v1', engine: null },
+ format: { width: 1280, height: 720, fps: 24, durationSeconds: 10 }, seed: 7,
+ audio: { kind: 'silence' }, entrypoints: [{ role: 'preview', path: 'index.html' }],
+ execution: { requested: null, effective: null }, assets: [], events: [], shots: [],
+ },
+ budgets: { iterations: 3, timeSeconds: 123, tokens: 4321, renderSeconds: 45, diskBytes: 123456 },
+ localSettings: { model: 'example-model', mode: 'cli' },
+ acceptedRevisionId: null, candidateRevisionId: '00000000-0000-4000-8000-000000000002',
+};
+const page = (items = []) => ({ items, nextCursor: null });
+const renderPage = (entry = '/code-animation/production/' + project.id) => render(
+ <MemoryRouter initialEntries={[entry]}><Routes>
+ <Route path="/code-animation/production" element={<ProductionProjects />} />
+ <Route path="/code-animation/production/:projectId" element={<ProductionProjects />} />
+ </Routes></MemoryRouter>
+);
+beforeEach(() => {
+ vi.resetAllMocks();
+ api.listCodeAnimationProjects.mockResolvedValue(page([project]));
+ api.getCodeAnimationProject.mockResolvedValue(project);
+ api.listCodeAnimationProjectHistory.mockResolvedValue(page());
+});
+
+describe('Production project rendered interactions', () => {
+ it('opens a URL-selected detail and applies accepted-source responses immediately', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ expect(await screen.findByLabelText('Film brief')).toHaveValue('A cube hops.');
+ api.acceptCodeAnimationSource.mockResolvedValue({ ...project, acceptedRevisionId: project.candidateRevisionId, candidateRevisionId: null });
+ await user.click(screen.getByRole('button', { name: 'Accept candidate source' }));
+ expect(await screen.findByRole('button', { name: 'Export accepted package' })).toBeEnabled();
+ expect(screen.queryByRole('button', { name: 'Accept candidate source' })).toBeNull();
+ expect(api.acceptCodeAnimationSource).toHaveBeenCalledWith(project.id, project.candidateRevisionId, { silent: true });
+ expect(api.getCodeAnimationProject).toHaveBeenCalledTimes(1);
+ });
+
+ it('gates imports on saved budgets and stages package responses without execution', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ const tokenInput = await screen.findByLabelText('Tokens');
+ await user.clear(tokenInput); await user.type(tokenInput, '5555');
+ expect(screen.getByLabelText('Import source package as a new candidate')).toBeDisabled();
+ const saved = { ...project, budgets: { ...project.budgets, tokens: 5555 } };
+ api.updateCodeAnimationProject.mockResolvedValue(saved);
+ await user.click(screen.getByRole('button', { name: 'Save project settings' }));
+ await waitFor(() => expect(screen.getByLabelText('Import source package as a new candidate')).toBeEnabled());
+ expect(api.updateCodeAnimationProject).toHaveBeenCalledWith(project.id, expect.objectContaining({ budgets: saved.budgets }), { silent: true });
+ const source = { schemaVersion: 1, revisionHash: 'example-hash' };
+ const file = new File([JSON.stringify(source)], 'example.json', { type: 'application/json' });
+ file.text = async () => JSON.stringify(source);
+ api.importCodeAnimationPackage.mockResolvedValue({
+ project: saved, runId: 'example-run', executed: false,
+ revision: { id: saved.candidateRevisionId, packageHash: 'example-hash', totalBytes: 128, createdAt: '2026-01-01T00:00:00Z' },
+ });
+ await user.upload(screen.getByLabelText('Import source package as a new candidate'), file);
+ expect(await screen.findByText('example-hash')).toBeInTheDocument();
+ expect(screen.getByText(/Source execution: None/)).toBeInTheDocument();
+ expect(api.importCodeAnimationPackage).toHaveBeenCalledWith(project.id, source, { silent: true });
+ });
+
+ it('creates an opt-in project and navigates to its durable detail URL', async () => {
+ const user = userEvent.setup();
+ api.createCodeAnimationProject.mockResolvedValue(project);
+ renderPage('/code-animation/production');
+ await user.type(screen.getByLabelText('Title'), 'Example Production');
+ await user.click(screen.getByRole('button', { name: 'Create Production project' }));
+ expect(await screen.findByRole('button', { name: 'Save project settings' })).toBeInTheDocument();
+ expect(api.getCodeAnimationProject).toHaveBeenCalledWith(project.id, expect.objectContaining({ silent: true }));
+ });
+});
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index 1311cf909a..e74d70c3fc 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -1,10 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';
-import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
+import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router';
import PageHeader from '../components/PageHeader';
import ProviderModelSelector from '../components/ProviderModelSelector';
import AlbumTrackPicker from '../components/music/AlbumTrackPicker';
import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';
+import ProductionProjects from '../components/codeAnimation/ProductionProjects';
import UniverseMoodBoardPicker, { BOARD_FOLLOW_UNIVERSE, BOARD_NONE, useStyleSourceLists } from '../components/media/UniverseMoodBoardPicker';
import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
import useProviderModels from '../hooks/useProviderModels';
@@ -262,7 +263,7 @@ async function uploadOrToast(file) {
});
}
-export default function CodeAnimation() {
+function FastCodeAnimation() {
const [searchParams] = useSearchParams();
const routeParams = useParams();
const navigate = useNavigate();
@@ -864,3 +865,17 @@ export default function CodeAnimation() {
</div>
);
}
+
+
+// Route-mounted lanes keep inactive galleries and provider calls idle.
+export default function CodeAnimation() {
+ const { pathname } = useLocation();
+ const production = pathname.startsWith('/code-animation/production');
+ return <div className="space-y-4">
+ <nav aria-label="Animation mode" className="flex flex-wrap gap-2">
+ <Link to="/code-animation" className={buttonSecondary} aria-current={!production ? 'page' : undefined}>Fast HTML</Link>
+ <Link to="/code-animation/production" className={buttonSecondary} aria-current={production ? 'page' : undefined}>Production</Link>
+ </nav>
+ {production ? <ProductionProjects /> : <FastCodeAnimation />}
+ </div>;
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 7074bf4bed..9e8bd5c29e 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -115,7 +115,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). |
| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |
-| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, and portable package download. |
+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, portable package download, and opt-in Production project settings, immutable candidate/accepted source imports, brief handoff and paged run history. |
| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. |
| `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. |
| `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |
diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.js
index da6f318513..3ea9ea1ab0 100644
--- a/client/src/services/apiCodeAnimation.js
+++ b/client/src/services/apiCodeAnimation.js
@@ -1,5 +1,18 @@
import { request } from './apiCore.js';
+const projectPath = id => `/code-animation/projects/${encodeURIComponent(id)}`;
+export const listCodeAnimationProjects = ({ cursor, signal, limit = 50 } = {}) =>
+ request(`/code-animation/projects?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`, { signal, silent: true });
+export const createCodeAnimationProject = (input, options) => request('/code-animation/projects', { method: 'POST', body: JSON.stringify(input), ...options });
+export const getCodeAnimationProject = (id, options) => request(projectPath(id), options);
+export const updateCodeAnimationProject = (id, input, options) => request(projectPath(id), { method: 'PATCH', body: JSON.stringify(input), ...options });
+export const importCodeAnimationPackage = (id, pkg, options) => request(`${projectPath(id)}/import`, { method: 'POST', body: JSON.stringify(pkg), ...options });
+export const acceptCodeAnimationSource = (id, revisionId, options) => request(`${projectPath(id)}/accept`, { method: 'POST', body: JSON.stringify({ revisionId }), ...options });
+export const getCodeAnimationProjectBrief = (id, options) => request(`${projectPath(id)}/brief`, options);
+export const getCodeAnimationRevisionPackage = (id, revisionId, options) => request(`${projectPath(id)}/revisions/${encodeURIComponent(revisionId)}/package`, options);
+export const listCodeAnimationProjectHistory = (id, { cursor, signal, limit = 50 } = {}) =>
+ request(`${projectPath(id)}/history?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`, { signal, silent: true });
+
// Code Animation — build an LLM prompt for a procedurally coded animation film
// styled by a universe (plus mood board, references, audio), and optionally run
// it on a provider to get the film's HTML. `options` is forwarded to the
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 11086b2964..d2cd496866 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -56,6 +56,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`; PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.
+- `code_animation_projects`, `code_animation_project_revisions`, `code_animation_project_runs` — opt-in Code Animation Production settings, accepted/candidate source pointers, immutable source/package hashes, portable manifest metadata and bounded import history. PostgreSQL owns metadata; source/asset bytes are write-once files under `data/code-animations/projects/<project-id>/revisions/<revision-id>/`. Settings, reference IDs, execution snapshots, managed paths and run IDs are machine-local and never federate. Budgets independently record iterations, elapsed time, tokens, render time and total retained disk bytes; imports consume disk only and never execute or install dependencies. Every attempted import has its own UUID-owned destination; failed/interrupted staging stays attributable to its run and never replaces accepted source. Boot DDL and migration 420 install empty tables without a seed. The PostgreSQL dump covers all three tables, and normal filesystem backup includes the entire project directory (no new excludes). Brief handoff omits local settings/IDs/paths; revision packages export only the validated portable contract. Source acceptance is explicit and does not assert visual, motion, sound or render evidence.
- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.
- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). Broker-case `evidence` follows the same rule (#8333): the matched name/location and the identity-bearing search/listing URLs a scan records are sealed under `evidence.sealed_identity` with the same key, erased on `confirmed_removed`, on the per-case erase action, and when the source `legal_name`/`address` vault record is deleted. **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
diff --git a/scripts/migrations/420-code-animation-production-projects.js b/scripts/migrations/420-code-animation-production-projects.js
new file mode 100644
index 0000000000..4633476d28
--- /dev/null
+++ b/scripts/migrations/420-code-animation-production-projects.js
@@ -0,0 +1,7 @@
+/** Empty db-primary Production stores are installed by boot DDL and init-db.sql. */
+export default {
+ async up() {
+ console.log('🎞️ Code Animation Production project, revision and run tables are installed by ensureSchema at boot');
+ return { success: true };
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index f3857b1e7a..95d5007d6c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -817,3 +817,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. |
| `musicVideoPlateEvidence.js` | Asset-bound authored-shot plate requirements, current evidence and selected-image admission. |
+| `codeAnimationProjects.js` | Machine-local Production project, patch and independent budget schemas; package imports grant no execution authority. |
diff --git a/server/lib/codeAnimationPackage.js b/server/lib/codeAnimationPackage.js
index f9e1f61056..47509e3ade 100644
--- a/server/lib/codeAnimationPackage.js
+++ b/server/lib/codeAnimationPackage.js
@@ -29,7 +29,7 @@ const settingsSchema = z.object({
effort: z.enum(EFFORT_LEVELS).nullable(),
}).strict();
-const manifestSchema = z.object({
+export const codeAnimationManifestSchema = z.object({
title: text(200),
brief: z.object({ concept: text(6000), cast: text(4000), onScreenText: text(4000) }).strict(),
styleGuide: text(16000),
@@ -80,7 +80,7 @@ const revisionHashOf = ({ schemaVersion, manifest, files }) => digest(canonicalS
const shapeSchema = z.object({
schemaVersion: z.literal(1),
- manifest: manifestSchema,
+ manifest: codeAnimationManifestSchema,
files: z.array(fileSchema).min(1).max(L.files),
revisionHash: hashSchema,
}).strict();
diff --git a/server/lib/codeAnimationProjects.js b/server/lib/codeAnimationProjects.js
new file mode 100644
index 0000000000..208d36f9b1
--- /dev/null
+++ b/server/lib/codeAnimationProjects.js
@@ -0,0 +1,34 @@
+/** Machine-local Production persistence contracts; no execution authority. */
+import { z } from 'zod';
+import { EFFORT_LEVELS } from './providerModels.js';
+import { codeAnimationManifestSchema } from './codeAnimationPackage.js';
+import { partialWithoutDefaults } from './zodCompat.js';
+
+export const codeAnimationBudgetsSchema = z.object({
+ iterations: z.number().int().min(1).max(1000).default(8),
+ timeSeconds: z.number().int().min(1).max(86400).default(900),
+ tokens: z.number().int().min(1).max(100000000).default(128000),
+ renderSeconds: z.number().int().min(1).max(86400).default(300),
+ diskBytes: z.number().int().min(1).max(1000000000000).default(512 * 1024 * 1024),
+}).strict();
+
+const localSettingsSchema = z.object({
+ providerId: z.string().max(128).nullable().default(null),
+ connectionId: z.string().max(128).nullable().default(null),
+ mode: z.enum(['api', 'cli', 'tui']).nullable().default(null),
+ model: z.string().max(256).nullable().default(null),
+ effort: z.enum(EFFORT_LEVELS).nullable().default(null),
+}).strict();
+
+export const codeAnimationProjectSchema = z.object({
+ manifest: codeAnimationManifestSchema,
+ budgets: codeAnimationBudgetsSchema.prefault({}),
+ localSettings: localSettingsSchema.prefault({}),
+ referenceIntent: z.object({
+ universeId: z.string().max(128).nullable().default(null),
+ moodBoardId: z.string().max(128).nullable().default(null),
+ notes: z.string().max(16000).default(''),
+ }).strict().prefault({}),
+}).strict();
+
+export const codeAnimationProjectPatchSchema = partialWithoutDefaults(codeAnimationProjectSchema);
diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.js
index 6745ae68cf..13ec06c6bc 100644
--- a/server/lib/db/schema/media.js
+++ b/server/lib/db/schema/media.js
@@ -199,4 +199,48 @@ export const mediaDdl = [
`CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_created ON code_animation_jobs (created_at DESC, id DESC)`,
`CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_status_created ON code_animation_jobs (status, created_at DESC)`,
+ // Machine-local Production metadata; immutable bytes remain managed assets.
+ `CREATE TABLE IF NOT EXISTS code_animation_projects (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL DEFAULT '',
+ data JSONB NOT NULL,
+ accepted_revision_id TEXT,
+ candidate_revision_id TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+)`,
+ `CREATE INDEX IF NOT EXISTS idx_code_animation_projects_created ON code_animation_projects (created_at DESC, id DESC)`,
+ `CREATE TABLE IF NOT EXISTS code_animation_project_revisions (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL REFERENCES code_animation_projects(id) ON DELETE CASCADE,
+ package_hash TEXT NOT NULL,
+ source_hash TEXT NOT NULL,
+ total_bytes BIGINT NOT NULL,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (project_id, id)
+)`,
+ `CREATE INDEX IF NOT EXISTS idx_code_animation_project_revisions_project ON code_animation_project_revisions (project_id, created_at DESC, id DESC)`,
+ `CREATE TABLE IF NOT EXISTS code_animation_project_runs (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL REFERENCES code_animation_projects(id) ON DELETE CASCADE,
+ revision_id TEXT,
+ status VARCHAR(16) NOT NULL,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ completed_at TIMESTAMPTZ,
+ FOREIGN KEY (project_id, revision_id) REFERENCES code_animation_project_revisions(project_id, id)
+)`,
+ `CREATE INDEX IF NOT EXISTS idx_code_animation_project_runs_project ON code_animation_project_runs (project_id, created_at DESC, id DESC)`,
+ `DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'code_animation_projects_accepted_fk' AND conrelid = 'code_animation_projects'::regclass) THEN
+ ALTER TABLE code_animation_projects ADD CONSTRAINT code_animation_projects_accepted_fk
+ FOREIGN KEY (id, accepted_revision_id) REFERENCES code_animation_project_revisions(project_id, id) DEFERRABLE INITIALLY DEFERRED;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'code_animation_projects_candidate_fk' AND conrelid = 'code_animation_projects'::regclass) THEN
+ ALTER TABLE code_animation_projects ADD CONSTRAINT code_animation_projects_candidate_fk
+ FOREIGN KEY (id, candidate_revision_id) REFERENCES code_animation_project_revisions(project_id, id) DEFERRABLE INITIALLY DEFERRED;
+ END IF;
+END $$`,
+
];
diff --git a/server/lib/index.js b/server/lib/index.js
index 362b07bd26..7e70a6d307 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -801,3 +801,4 @@ export * from './musicVideoGrade.js';
export * from './musicVideoDependencies.js';
export * from './musicVideoPlateEvidence.js';
+export * from './codeAnimationProjects.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 47564bf58b..15febcde93 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -55,6 +55,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', tabGroup: 'media', tabId: 'collections', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.create.video', path: '/video', label: 'Video', section: 'Create', aliases: ['video', 'browse-video'], keywords: ['videos', 'watch', 'browse', 'commission outputs'] },
{ id: 'nav.create.code-animation', path: '/code-animation', label: 'Code Animation', section: 'Create', aliases: ['code-animation', 'codeanimation', 'code-video', 'procedural-animation', 'animation-prompt'], keywords: ['animation', 'canvas', 'webgl', 'procedural', 'no assets', 'llm prompt', 'motion graphics', 'universe style', 'mood board', 'audio reactive', 'record video', 'html animation'] },
+ { id: 'nav.create.code-animation.production', path: '/code-animation/production', label: 'Code Animation Production', section: 'Create', aliases: ['code-animation-production', 'animation-production', 'production-animation'], keywords: ['film projects', 'source packages', 'immutable revisions', 'animation history'] },
{ id: 'nav.create.creative-director', path: '/creative-director', label: 'Creative Director', section: 'Create', previousPaths: ['/media/creative-director', '/media/creative-director/:id', '/media/creative-director/:id/:tab'], aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode', 'video-production', 'create-video', 'video-workspace'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },
{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },
{ id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 673a050c7b..8ccf16adf3 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -324,7 +324,7 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
},
'code-animation:changed': {
direction: 'server-to-client',
- summary: 'Invalidate the bounded Code Animation gallery and matching selected job after a durable job change.',
+ summary: 'Invalidate bounded Code Animation job/project galleries and matching details after a durable change.',
payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },
},
diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.js
index 80c4f5f7da..3b293f847c 100644
--- a/server/routes/codeAnimation.js
+++ b/server/routes/codeAnimation.js
@@ -31,6 +31,12 @@ import {
import { startCodeAnimationExport } from '../services/codeAnimation/export.js';
import { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';
import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';
+import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema } from '../lib/codeAnimationProjects.js';
+import {
+ createProductionProject, getProductionProject, patchProductionProject,
+ listProductionProjects, getProductionHistory, importProductionPackage,
+ acceptProductionSource, exportProductionPackage, exportProductionBrief,
+} from '../services/codeAnimation/projects.js';
import {
CODE_ANIMATION_ASPECT_RATIOS,
CODE_ANIMATION_LIMITS,
@@ -162,6 +168,56 @@ router.get('/generate/:id', asyncHandler(async (req, res) => {
const exportParamsSchema = z.object({ id: z.string().uuid() }).strict();
+const projectPageSchema = z.object({
+ limit: z.coerce.number().int().min(1).max(100).default(50),
+ cursor: z.string().regex(/^(0|[1-9][0-9]{0,8})$/).optional(),
+}).strict();
+const projectPage = query => {
+ const { limit, cursor } = validateRequest(projectPageSchema, query);
+ return { limit, offset: Number(cursor || 0) };
+};
+const revisionParamsSchema = exportParamsSchema.extend({ revisionId: z.string().uuid() });
+
+router.get('/projects', asyncHandler(async (req, res) => {
+ res.json(await listProductionProjects(projectPage(req.query)));
+}));
+router.post('/projects', asyncHandler(async (req, res) => {
+ res.status(201).json(await createProductionProject(validateRequest(codeAnimationProjectSchema, req.body)));
+}));
+router.get('/projects/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ res.json(await getProductionProject(id));
+}));
+router.patch('/projects/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ res.json(await patchProductionProject(id, validateRequest(codeAnimationProjectPatchSchema, req.body)));
+}));
+router.get('/projects/:id/history', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ res.json(await getProductionHistory(id, projectPage(req.query)));
+}));
+router.post('/projects/:id/import', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ res.status(201).json(await importProductionPackage(id, validateRequest(codeAnimationPackageSchema, req.body)));
+}));
+router.post('/projects/:id/accept', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ const { revisionId } = validateRequest(z.object({ revisionId: z.string().uuid() }).strict(), req.body);
+ res.json(await acceptProductionSource(id, revisionId));
+}));
+router.get('/projects/:id/brief', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(exportParamsSchema, req.params);
+ res.attachment(`code-animation-brief-${id}.json`);
+ res.set('X-Content-Type-Options', 'nosniff');
+ res.json(await exportProductionBrief(id));
+}));
+router.get('/projects/:id/revisions/:revisionId/package', asyncHandler(async (req, res) => {
+ const { id, revisionId } = validateRequest(revisionParamsSchema, req.params);
+ res.attachment(`code-animation-source-${revisionId}.json`);
+ res.set('X-Content-Type-Options', 'nosniff');
+ res.json(await exportProductionPackage(id, revisionId));
+}));
+
// External harness handoff is data-only. Validation grants no execution and
// neither stages imported files nor changes a saved/accepted animation.
router.post('/packages/validate', (req, res) => {
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 94091bd5bc..48825b359a 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -989,6 +989,56 @@ CREATE TABLE IF NOT EXISTS code_animation_jobs (
CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_created ON code_animation_jobs (created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_code_animation_jobs_status_created ON code_animation_jobs (status, created_at DESC);
+-- Code Animation Production projects, immutable source revisions and run history.
+CREATE TABLE IF NOT EXISTS code_animation_projects (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL DEFAULT '',
+ data JSONB NOT NULL,
+ accepted_revision_id TEXT,
+ candidate_revision_id TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX IF NOT EXISTS idx_code_animation_projects_created ON code_animation_projects (created_at DESC, id DESC);
+
+CREATE TABLE IF NOT EXISTS code_animation_project_revisions (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL REFERENCES code_animation_projects(id) ON DELETE CASCADE,
+ package_hash TEXT NOT NULL,
+ source_hash TEXT NOT NULL,
+ total_bytes BIGINT NOT NULL,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (project_id, id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_code_animation_project_revisions_project ON code_animation_project_revisions (project_id, created_at DESC, id DESC);
+
+CREATE TABLE IF NOT EXISTS code_animation_project_runs (
+ id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL REFERENCES code_animation_projects(id) ON DELETE CASCADE,
+ revision_id TEXT,
+ status VARCHAR(16) NOT NULL,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ completed_at TIMESTAMPTZ,
+ FOREIGN KEY (project_id, revision_id) REFERENCES code_animation_project_revisions(project_id, id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_code_animation_project_runs_project ON code_animation_project_runs (project_id, created_at DESC, id DESC);
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'code_animation_projects_accepted_fk' AND conrelid = 'code_animation_projects'::regclass) THEN
+ ALTER TABLE code_animation_projects ADD CONSTRAINT code_animation_projects_accepted_fk
+ FOREIGN KEY (id, accepted_revision_id) REFERENCES code_animation_project_revisions(project_id, id) DEFERRABLE INITIALLY DEFERRED;
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'code_animation_projects_candidate_fk' AND conrelid = 'code_animation_projects'::regclass) THEN
+ ALTER TABLE code_animation_projects ADD CONSTRAINT code_animation_projects_candidate_fk
+ FOREIGN KEY (id, candidate_revision_id) REFERENCES code_animation_project_revisions(project_id, id) DEFERRABLE INITIALLY DEFERRED;
+ END IF;
+END $$;
+
-- Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per
-- user-defined ingredient type — the registry that defines catalog row
-- semantics, moved out of data/settings.json (`catalogUserTypes`) so type
diff --git a/server/services/codeAnimation/db.test.js b/server/services/codeAnimation/db.test.js
new file mode 100644
index 0000000000..cc9aadc90e
--- /dev/null
+++ b/server/services/codeAnimation/db.test.js
@@ -0,0 +1,118 @@
+/** HTTP → PostgreSQL → immutable managed bytes; synthetic records only. */
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { readFile, mkdir, symlink, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';
+vi.mock('../../lib/paths.js', async importOriginal =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('code-animation-production-') }));
+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+import { requireDbOrSkip } from '../../lib/dbTestGate.js';
+import { request } from '../../lib/testHelper.js';
+import { errorMiddleware } from '../../lib/errorHandler.js';
+import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
+import { PATHS } from '../../lib/paths.js';
+import routes from '../../routes/codeAnimation.js';
+
+const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));
+const ready = requireDbOrSkip('codeAnimation/db.test', health.connected, health.error);
+if (ready) await ensureSchema();
+const ids = [];
+afterAll(async () => {
+ if (ready && ids.length) await query('DELETE FROM code_animation_projects WHERE id = ANY($1::text[])', [ids]);
+ await close(); cleanupTempDataRoots('code-animation-production-');
+});
+const app = express();
+app.use(express.json({ limit: '55mb' })); app.use('/animation', routes); app.use(errorMiddleware);
+const get = path => request(app).get('/animation' + path);
+const post = (path, body) => request(app).post('/animation' + path).send(body);
+const patch = (path, body) => request(app).patch('/animation' + path).send(body);
+const manifest = {
+ title: 'Synthetic film', brief: { concept: 'A cube hops over a cone.', cast: '', onScreenText: '' },
+ styleGuide: 'Graphic shapes', renderer: { kind: 'browser', version: 'synthetic-v1', engine: null },
+ format: { width: 1280, height: 720, fps: 24, durationSeconds: 10 }, seed: 42,
+ entrypoints: [{ role: 'preview', path: 'src/index.html' }], assets: ['assets/example.bin'], shots: [], events: [],
+ audio: { kind: 'silence' }, execution: {
+ requested: { harness: 'example', connection: null, mode: 'api', model: 'example-model', effort: 'low' }, effective: null,
+ },
+};
+const pkg = (source = '<html>synthetic</html>') => createCodeAnimationPackage(manifest, [
+ { path: 'src/index.html', content: source },
+ { path: 'assets/example.bin', encoding: 'base64', content: Buffer.from([0, 1, 2, 255]).toString('base64') },
+]);
+const localSettings = { providerId: 'example-provider', connectionId: 'example-local', mode: 'cli', model: 'example-model', effort: 'high' };
+const create = async extra => {
+ const response = await post('/projects', { manifest, localSettings, ...extra });
+ expect(response.status).toBe(201); ids.push(response.body.id); return response.body;
+};
+const imported = async (id, value = pkg()) => {
+ const response = await post(`/projects/${id}/import`, value);
+ expect(response.status).toBe(201); return response.body;
+};
+
+describe.skipIf(!ready)('Production persisted public boundary', () => {
+ it('reopens settings and execution provenance, pages history and exports immutable accepted source separately from new candidates', async () => {
+ const project = await create({ referenceIntent: { universeId: 'example-universe', moodBoardId: null, notes: 'Warm light' } });
+ const limits = { iterations: 3, timeSeconds: 123, tokens: 4321, renderSeconds: 45, diskBytes: 123456 };
+ expect((await patch(`/projects/${project.id}`, { budgets: limits })).status).toBe(200);
+ const first = await imported(project.id);
+ expect(first).toMatchObject({ executed: false, project: { acceptedRevisionId: null, candidateRevisionId: first.revision.id } });
+ expect((await post(`/projects/${project.id}/accept`, { revisionId: first.revision.id })).body.acceptedRevisionId).toBe(first.revision.id);
+ const second = await imported(project.id, pkg('<html>new</html>'));
+ expect((await get(`/projects/${project.id}`)).body).toMatchObject({ budgets: limits, localSettings, acceptedRevisionId: first.revision.id, candidateRevisionId: second.revision.id });
+ const history = (await get(`/projects/${project.id}/history?limit=1`)).body;
+ expect(history.items).toHaveLength(1); expect(history.nextCursor).toBe('1');
+ expect(history.items[0]).toMatchObject({ status: 'completed', revisionId: second.revision.id, data: { requested: localSettings, effective: null, stageRunIds: {}, budgets: limits, executed: false } });
+ expect((await get(`/projects/${project.id}/revisions/${first.revision.id}/package`)).body).toEqual(pkg());
+ const brief = (await get(`/projects/${project.id}/brief`)).body;
+ expect(brief).toMatchObject({ budgets: limits, manifest: { execution: { requested: null, effective: null } } });
+ expect(JSON.stringify(brief)).not.toMatch(/example-provider|example-local|example-universe|relativePath/);
+ expect((await get('/projects?limit=1')).body.items[0]).not.toHaveProperty('manifest');
+ await query("INSERT INTO code_animation_project_runs (id, project_id, status, data) VALUES ($1, $2, 'staging', $3)", [randomUUID(), project.id, { executed: false }]);
+ expect((await get(`/projects/${project.id}/history`)).body.items.some(run => run.status === 'interrupted' && run.data.executed === false)).toBe(true);
+ });
+
+ it('gives overlapping imports distinct owned destinations and rejects stale or cross-project acceptance', async () => {
+ const project = await create();
+ const [a, b] = await Promise.all([imported(project.id), imported(project.id)]);
+ expect(a.revision.storage.relativePath).not.toBe(b.revision.storage.relativePath);
+ for (const revision of [a.revision, b.revision]) {
+ expect(await readFile(join(PATHS.data, revision.storage.relativePath, 'src/index.html'), 'utf8')).toBe('<html>synthetic</html>');
+ }
+ const current = (await get(`/projects/${project.id}`)).body.candidateRevisionId;
+ const stale = current === a.revision.id ? b.revision.id : a.revision.id;
+ expect((await post(`/projects/${project.id}/accept`, { revisionId: stale })).status).toBe(409);
+ expect((await post(`/projects/${project.id}/accept`, { revisionId: current })).status).toBe(200);
+ const other = await create();
+ expect((await post(`/projects/${other.id}/accept`, { revisionId: current })).status).toBe(404);
+ });
+
+ it('refuses unsafe packages, symlinks and cumulative disk overflow while retaining accepted work', async () => {
+ const project = await create();
+ const first = await imported(project.id);
+ await post(`/projects/${project.id}/accept`, { revisionId: first.revision.id });
+ const value = pkg(); value.files[0].path = '../escape.html';
+ expect((await post(`/projects/${project.id}/import`, value)).status).toBe(400);
+ expect((await patch(`/projects/${project.id}`, { budgets: { ...project.budgets, diskBytes: first.revision.totalBytes - 1 } })).status).toBe(409);
+ await patch(`/projects/${project.id}`, { budgets: { ...project.budgets, diskBytes: first.revision.totalBytes } });
+ expect((await post(`/projects/${project.id}/import`, pkg())).status).toBe(409);
+ expect((await get(`/projects/${project.id}`)).body).toMatchObject({ acceptedRevisionId: first.revision.id, candidateRevisionId: null });
+ expect((await get(`/projects/${project.id}/history`)).body.items.some(run => run.status === 'failed')).toBe(true);
+
+ const linked = await create();
+ const parent = join(PATHS.data, 'code-animations', 'projects', linked.id);
+ const outside = join(PATHS.data, 'synthetic-outside');
+ await mkdir(parent); await mkdir(outside);
+ await symlink(outside, join(parent, 'revisions'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect((await post(`/projects/${linked.id}/import`, pkg())).status).toBe(409);
+ expect((await get(`/projects/${linked.id}`)).body.candidateRevisionId).toBeNull();
+ const file = join(PATHS.data, first.revision.storage.relativePath, 'src/index.html');
+ await rm(file); await writeFile(join(outside, 'example.html'), '<html>outside</html>');
+ await symlink(join(outside, 'example.html'), file);
+ expect((await get(`/projects/${project.id}/revisions/${first.revision.id}/package`)).status).toBe(409);
+ await rm(file); await writeFile(file, '<html>changed</html>');
+ expect((await get(`/projects/${project.id}/revisions/${first.revision.id}/package`)).status).toBe(409);
+ });
+});
diff --git a/server/services/codeAnimation/projectFiles.js b/server/services/codeAnimation/projectFiles.js
new file mode 100644
index 0000000000..aebd865e20
--- /dev/null
+++ b/server/services/codeAnimation/projectFiles.js
@@ -0,0 +1,81 @@
+/** Bytes live only in server-owned, write-once revision directories. */
+import { constants } from 'fs';
+import { mkdir, lstat, open, rm } from 'fs/promises';
+import { join } from 'path';
+import { createHash } from 'crypto';
+import { PATHS } from '../../lib/paths.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const unsafe = () => new ServerError('Managed revision storage is not a regular directory or file', {
+ status: 409, code: 'CODE_ANIMATION_UNSAFE_STORAGE',
+});
+
+async function directory(path, create) {
+ if (create) await mkdir(path, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error; });
+ const info = await lstat(path);
+ if (!info.isDirectory() || info.isSymbolicLink()) throw unsafe();
+}
+
+async function root(projectId, revisionId, create) {
+ // IDs originate in the service, never in package paths or local settings.
+ let path = PATHS.data;
+ await directory(path, false);
+ for (const part of ['code-animations', 'projects', projectId, 'revisions']) {
+ path = join(path, part);
+ await directory(path, create);
+ }
+ path = join(path, revisionId);
+ if (create) {
+ // Exclusive ownership: an existing UUID destination is never reused.
+ await mkdir(path, { mode: 0o700 });
+ } else await directory(path, false);
+ return path;
+}
+
+export async function stageProjectFiles(projectId, revisionId, files) {
+ const owned = await root(projectId, revisionId, true);
+ try {
+ for (const file of files) {
+ let parent = owned;
+ for (const part of file.path.split('/').slice(0, -1)) {
+ parent = join(parent, part);
+ await directory(parent, true);
+ }
+ const handle = await open(join(owned, file.path), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0), 0o444);
+ try {
+ await handle.writeFile(Buffer.from(file.content, file.encoding === 'base64' ? 'base64' : 'utf8'));
+ await handle.sync();
+ } finally { await handle.close(); }
+ }
+ } catch (error) {
+ // Only this invocation's exclusively-created directory can be removed.
+ await rm(owned, { recursive: true, force: true });
+ throw error;
+ }
+ return { relativePath: `code-animations/projects/${projectId}/revisions/${revisionId}` };
+}
+
+export async function readProjectFiles(projectId, revisionId, files) {
+ const owned = await root(projectId, revisionId, false);
+ const result = [];
+ for (const file of files) {
+ const path = join(owned, file.path);
+ let parent = owned;
+ for (const part of file.path.split('/').slice(0, -1)) {
+ parent = join(parent, part);
+ await directory(parent, false);
+ }
+ if (!(await lstat(path)).isFile()) throw unsafe();
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
+ let bytes;
+ try {
+ if (!(await handle.stat()).isFile()) throw unsafe();
+ bytes = await handle.readFile();
+ } finally { await handle.close(); }
+ if (createHash('sha256').update(bytes).digest('hex') !== file.sha256) {
+ throw new ServerError('Stored revision bytes failed integrity validation', { status: 409, code: 'CODE_ANIMATION_REVISION_CORRUPT' });
+ }
+ result.push({ ...file, content: bytes.toString(file.encoding === 'base64' ? 'base64' : 'utf8') });
+ }
+ return result;
+}
diff --git a/server/services/codeAnimation/projectStore.js b/server/services/codeAnimation/projectStore.js
new file mode 100644
index 0000000000..3dcfc652d9
--- /dev/null
+++ b/server/services/codeAnimation/projectStore.js
@@ -0,0 +1,112 @@
+/** PostgreSQL owns projects, source revision lineage and import-run records. */
+import { query, withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const columns = `id, title, data, accepted_revision_id AS "acceptedRevisionId",
+ candidate_revision_id AS "candidateRevisionId", created_at AS "createdAt", updated_at AS "updatedAt"`;
+const present = row => {
+ if (!row) return null;
+ const { data, ...metadata } = row;
+ return { ...data, ...metadata };
+};
+const missing = () => new ServerError('Production project not found', { status: 404, code: 'NOT_FOUND' });
+
+export async function createProjectRecord(id, settings) {
+ const { rows } = await query(`INSERT INTO code_animation_projects (id, title, data)
+ VALUES ($1, $2, $3) RETURNING ${columns}`, [id, settings.manifest.title, settings]);
+ return present(rows[0]);
+}
+
+export async function getProjectRecord(id) {
+ const { rows } = await query(`SELECT ${columns} FROM code_animation_projects WHERE id = $1`, [id]);
+ return present(rows[0]) || null;
+}
+
+export async function pageProjectRecords({ limit, offset }) {
+ const [page, count] = await Promise.all([
+ query(`SELECT id, title, accepted_revision_id AS "acceptedRevisionId",
+ candidate_revision_id AS "candidateRevisionId", created_at AS "createdAt", updated_at AS "updatedAt"
+ FROM code_animation_projects ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2`, [limit + 1, offset]),
+ query('SELECT COUNT(*)::integer AS total FROM code_animation_projects'),
+ ]);
+ return { items: page.rows.slice(0, limit), total: count.rows[0].total,
+ nextCursor: page.rows.length > limit ? String(offset + limit) : null };
+}
+
+export async function patchProjectRecord(id, patch) {
+ return withTransaction(async client => {
+ const { rows } = await client.query(`SELECT ${columns} FROM code_animation_projects WHERE id = $1 FOR UPDATE`, [id]);
+ if (!rows[0]) throw missing();
+ const settings = { ...rows[0].data, ...patch };
+ if (patch.budgets) {
+ const used = await client.query("SELECT COALESCE(SUM((data->>'reservedBytes')::bigint), 0) AS bytes FROM code_animation_project_runs WHERE project_id = $1", [id]);
+ if (Number(used.rows[0].bytes) > settings.budgets.diskBytes) {
+ throw new ServerError('Disk budget cannot be smaller than retained source reservations', { status: 409, code: 'CODE_ANIMATION_DISK_BUDGET' });
+ }
+ }
+ const result = await client.query(`UPDATE code_animation_projects SET title = $2, data = $3, updated_at = NOW()
+ WHERE id = $1 RETURNING ${columns}`, [id, settings.manifest.title, settings]);
+ return present(result.rows[0]);
+ });
+}
+
+export async function startImportRecord(id, projectId, data) {
+ return withTransaction(async client => {
+ const project = await client.query('SELECT data FROM code_animation_projects WHERE id = $1 FOR UPDATE', [projectId]);
+ if (!project.rows[0]) throw missing();
+ const settings = project.rows[0].data;
+ const used = await client.query("SELECT COALESCE(SUM((data->>'reservedBytes')::bigint), 0) AS bytes FROM code_animation_project_runs WHERE project_id = $1", [projectId]);
+ const allowed = Number(used.rows[0].bytes) + data.totalBytes <= settings.budgets.diskBytes;
+ await client.query(`INSERT INTO code_animation_project_runs (id, project_id, status, data, completed_at)
+ VALUES ($1, $2, $3, $4, $5)`, [id, projectId, allowed ? 'staging' : 'failed',
+ { ...data, requested: settings.localSettings, budgets: settings.budgets, reservedBytes: allowed ? data.totalBytes : 0 },
+ allowed ? null : new Date().toISOString()]);
+ return allowed;
+ });
+}
+
+export async function failImportRecord(id, error, releaseReservation = false) {
+ await query(`UPDATE code_animation_project_runs SET status = 'failed',
+ data = data || jsonb_build_object('error', $2::text) ||
+ CASE WHEN $3 THEN '{"reservedBytes":0}'::jsonb ELSE '{}'::jsonb END,
+ completed_at = NOW() WHERE id = $1`, [id, error, releaseReservation]);
+}
+
+export async function commitImportRecord(projectId, revision, runId) {
+ return withTransaction(async client => {
+ const { rows } = await client.query(`SELECT ${columns} FROM code_animation_projects WHERE id = $1 FOR UPDATE`, [projectId]);
+ if (!rows[0]) throw missing();
+ await client.query(`INSERT INTO code_animation_project_revisions
+ (id, project_id, package_hash, source_hash, total_bytes, data)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [revision.id, projectId, revision.packageHash, revision.sourceHash, revision.totalBytes, revision]);
+ await client.query(`UPDATE code_animation_project_runs SET status = 'completed', revision_id = $2, completed_at = NOW() WHERE id = $1`, [runId, revision.id]);
+ const saved = await client.query(`UPDATE code_animation_projects SET candidate_revision_id = $2, updated_at = NOW()
+ WHERE id = $1 RETURNING ${columns}`, [projectId, revision.id]);
+ return present(saved.rows[0]);
+ });
+}
+
+export async function acceptProjectRevision(projectId, revisionId) {
+ const { rows } = await query(`UPDATE code_animation_projects SET accepted_revision_id = $2,
+ candidate_revision_id = NULL, updated_at = NOW() WHERE id = $1 AND candidate_revision_id = $2 RETURNING ${columns}`, [projectId, revisionId]);
+ if (!rows[0]) throw new ServerError('Candidate changed; reload before accepting source', { status: 409, code: 'CODE_ANIMATION_CANDIDATE_CHANGED' });
+ return present(rows[0]);
+}
+
+export async function getRevisionRecord(projectId, revisionId) {
+ const { rows } = await query('SELECT data FROM code_animation_project_revisions WHERE project_id = $1 AND id = $2', [projectId, revisionId]);
+ return rows[0]?.data || null;
+}
+
+export async function pageProjectHistory(projectId, { limit, offset }) {
+ const { rows } = await query(`SELECT id, status, revision_id AS "revisionId", data,
+ created_at AS "createdAt", completed_at AS "completedAt" FROM code_animation_project_runs
+ WHERE project_id = $1 ORDER BY created_at DESC, id DESC LIMIT $2 OFFSET $3`, [projectId, limit + 1, offset]);
+ return { items: rows.slice(0, limit), nextCursor: rows.length > limit ? String(offset + limit) : null };
+}
+
+export async function interruptImports(projectId, activeIds) {
+ await query(`UPDATE code_animation_project_runs SET status = 'interrupted', completed_at = NOW()
+ WHERE project_id = $1 AND status = 'staging' AND NOT (id = ANY($2::text[]))`, [projectId, activeIds]);
+}
diff --git a/server/services/codeAnimation/projects.js b/server/services/codeAnimation/projects.js
new file mode 100644
index 0000000000..5c4fb27f65
--- /dev/null
+++ b/server/services/codeAnimation/projects.js
@@ -0,0 +1,102 @@
+/** Production persistence is data-only; later stages own contained execution. */
+import { randomUUID, createHash } from 'crypto';
+import { canonicalStringify } from '../../lib/objects.js';
+import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
+import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema } from '../../lib/codeAnimationProjects.js';
+import { validateRequest } from '../../lib/validation.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { emitCodeAnimationChanged } from '../socket.js';
+import * as store from './projectStore.js';
+import { stageProjectFiles, readProjectFiles } from './projectFiles.js';
+
+const activeImports = new Set();
+
+export async function getProductionProject(id) {
+ const project = await store.getProjectRecord(id);
+ if (!project) throw new ServerError('Production project not found', { status: 404, code: 'NOT_FOUND' });
+ return project;
+}
+
+export async function createProductionProject(input) {
+ const project = await store.createProjectRecord(randomUUID(), validateRequest(codeAnimationProjectSchema, input));
+ emitCodeAnimationChanged(project.id);
+ return project;
+}
+
+export async function patchProductionProject(id, input) {
+ const project = await store.patchProjectRecord(id, validateRequest(codeAnimationProjectPatchSchema, input));
+ emitCodeAnimationChanged(id);
+ return project;
+}
+
+export const listProductionProjects = page => store.pageProjectRecords(page);
+export async function getProductionHistory(id, page) {
+ await getProductionProject(id);
+ await store.interruptImports(id, [...activeImports]);
+ return store.pageProjectHistory(id, page);
+}
+
+export async function importProductionPackage(projectId, input) {
+ const pkg = validateRequest(codeAnimationPackageSchema, input);
+ await getProductionProject(projectId);
+ const runId = randomUUID();
+ const revisionId = randomUUID();
+ const totalBytes = summarizeCodeAnimationPackage(pkg).totalBytes;
+ let staged = false;
+ activeImports.add(runId);
+ try {
+ const allowed = await store.startImportRecord(runId, projectId, {
+ kind: 'package-import', packageHash: pkg.revisionHash, executed: false,
+ effective: null, stageRunIds: {}, totalBytes, ownedRevisionId: revisionId,
+ relativePath: `code-animations/projects/${projectId}/revisions/${revisionId}`,
+ });
+ if (!allowed) {
+ throw new ServerError('Package exceeds the project disk budget', { status: 409, code: 'CODE_ANIMATION_DISK_BUDGET' });
+ }
+ const storage = await stageProjectFiles(projectId, revisionId, pkg.files);
+ staged = true;
+ const revision = {
+ id: revisionId, packageHash: pkg.revisionHash,
+ sourceHash: createHash('sha256').update(canonicalStringify(pkg.files.map(({ path, sha256 }) => ({ path, sha256 })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0))).digest('hex'),
+ totalBytes, schemaVersion: pkg.schemaVersion, manifest: pkg.manifest,
+ files: pkg.files.map(({ content: _content, ...file }) => file),
+ storage, createdAt: new Date().toISOString(),
+ };
+ const saved = await store.commitImportRecord(projectId, revision, runId);
+ emitCodeAnimationChanged(projectId);
+ return { project: saved, revision, runId, executed: false };
+ } catch (error) {
+ // Keep accepted work and the failed run. A staged orphan is retained on DB
+ // failure, never mistaken for an accepted revision or automatically run.
+ await store.failImportRecord(runId, error.code || 'IMPORT_FAILED', !staged);
+ emitCodeAnimationChanged(projectId);
+ throw error;
+ } finally {
+ activeImports.delete(runId);
+ }
+}
+
+export async function acceptProductionSource(projectId, revisionId) {
+ const revision = await store.getRevisionRecord(projectId, revisionId);
+ if (!revision) throw new ServerError('Revision not found', { status: 404, code: 'NOT_FOUND' });
+ await readProjectFiles(projectId, revisionId, revision.files);
+ const project = await store.acceptProjectRevision(projectId, revisionId);
+ emitCodeAnimationChanged(projectId);
+ return project;
+}
+
+export async function exportProductionPackage(projectId, revisionId) {
+ const revision = await store.getRevisionRecord(projectId, revisionId);
+ if (!revision) throw new ServerError('Revision not found', { status: 404, code: 'NOT_FOUND' });
+ return validateRequest(codeAnimationPackageSchema, {
+ schemaVersion: revision.schemaVersion, manifest: revision.manifest,
+ files: await readProjectFiles(projectId, revisionId, revision.files),
+ revisionHash: revision.packageHash,
+ });
+}
+
+export async function exportProductionBrief(id) {
+ const { manifest, budgets } = await getProductionProject(id);
+ // Instance provider/connection ids, reference ids and managed paths stay local.
+ return { schemaVersion: 1, manifest: { ...manifest, execution: { requested: null, effective: null } }, budgets };
+}