Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: compare Code Animation production evidence and reuse accepted outputs (#9392)
[._.]/ Adam Eivy1ccaaacf4d45
diff --git a/client/src/components/codeAnimation/ProductionAcceptance.jsx b/client/src/components/codeAnimation/ProductionAcceptance.jsxnew file mode 100644index 0000000000..6042f593ce--- /dev/null+++ b/client/src/components/codeAnimation/ProductionAcceptance.jsx@@ -0,0 +1,67 @@+import { useSearchParams } from 'react-router';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import { useSocketResource } from '../../hooks/useSocketResource';+import { acceptCodeAnimationOutput, getCodeAnimationAcceptance } from '../../services/apiCodeAnimation';+import { timeAgo } from '../../utils/formatters';+import ProductionRunComparison, { EvidenceGrid } from './ProductionRunComparison';++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';+const MAX_COMPARE = 2;++/**+ * The accepted output, its frozen evidence, and run comparison. Accepted playback is+ * read separately from the run list, so a newer failed run never hides it.+ */+export default function ProductionAcceptance({ projectId, disabled, onProject, onDownloadSource }) {+ const [params, setParams] = useSearchParams();+ const [act, busy] = useAsyncAction(async operation => operation());+ const resource = useSocketResource(({ signal }) => getCodeAnimationAcceptance(projectId, { signal, silent: true }), {+ namespace: 'code-animation', events: EVENTS, resourceKey: projectId, matchesEvent: payload => payload?.id === projectId,+ });+ const data = resource.data;+ if (!data) return resource.error ? <p role="alert" className="text-xs text-port-error">{resource.error.message}</p> : null;+ const { accepted, runs } = data;+ const chosen = (params.get('compare') || '').split(',').filter(Boolean);+ const selected = chosen.map(id => runs.find(run => run.runId === id)).filter(Boolean);+ const toggle = runId => {+ const next = new URLSearchParams(params);+ const ids = chosen.includes(runId) ? chosen.filter(id => id !== runId) : [...chosen, runId].slice(-MAX_COMPARE);+ if (ids.length) next.set('compare', ids.join(',')); else next.delete('compare');+ setParams(next, { replace: true });+ };+ const promote = runId => act(async () => {+ onProject(await acceptCodeAnimationOutput(projectId, runId, { silent: true }));+ await resource.refetch();+ });+ return <section className="space-y-3 rounded border border-port-border p-3" aria-label="Production acceptance">+ <h3 className="text-sm font-semibold">Accepted output</h3>+ {accepted ? <div className="min-w-0 space-y-2">+ <video aria-label="Accepted final video" controls preload="none" src={accepted.path} className="w-full min-w-0 rounded" />+ <p className="text-xs text-gray-400">Accepted {timeAgo(accepted.acceptedAt)} from run {accepted.runId.slice(0, 8)} · frozen to source {accepted.sourceHash.slice(0, 12)}, render {accepted.renderHash.slice(0, 12)}{accepted.audioHash ? `, audio ${accepted.audioHash.slice(0, 12)}` : ', silent audio'}</p>+ {!accepted.fresh && <div role="alert" className="space-y-1 rounded border border-port-warning p-2 text-xs text-port-warning">+ <p>Earlier passing evidence is stale. The accepted video still plays, but it is no longer verified.</p>+ {accepted.stale.map(item => <p key={item.dimension}>{item.reason}</p>)}+ </div>}+ <EvidenceGrid evidence={accepted.evidence} />+ <div className="flex flex-wrap gap-2">+ <button type="button" className={buttonClass} disabled={disabled || busy} onClick={() => onDownloadSource(accepted.revisionId)}>Download source bundle</button>+ <a className={`${buttonClass} inline-block`} href={accepted.path} download>Download accepted MP4</a>+ </div>+ <p className="text-xs text-gray-400">This video is in Media History as <code>{accepted.videoId}</code>; Music Video Studio and Creative Director can use it without a song or episode project.</p>+ </div> : <p className="text-xs text-gray-400">No output has been accepted. Accept a passing run below; failed runs never replace an accepted output.</p>}+ <h3 className="text-sm font-semibold">Runs to compare</h3>+ {runs.length === 0 && <p className="text-xs text-gray-400">Run production stages to produce evidence.</p>}+ <ul className="space-y-2">+ {runs.map(run => <li key={run.runId} className="flex flex-wrap items-center justify-between gap-2 text-xs">+ <label htmlFor={`cap-compare-${run.runId}`} className="flex min-w-0 items-center gap-2">+ <input id={`cap-compare-${run.runId}`} type="checkbox" checked={chosen.includes(run.runId)} onChange={() => toggle(run.runId)} />+ <span className="min-w-0 break-words">Run {run.runId.slice(0, 8)} · {run.status} · verdict {run.verdict?.status || 'none'} · {timeAgo(run.createdAt)}{run.accepted ? ' · accepted' : ''}</span>+ </label>+ {run.acceptable && !run.accepted && <button type="button" className={buttonClass} disabled={disabled || busy} onClick={() => promote(run.runId)}>Accept output of run {run.runId.slice(0, 8)}</button>}+ </li>)}+ </ul>+ <p className="text-xs text-gray-400">Choose up to two runs to compare.</p>+ <ProductionRunComparison runs={selected} />+ </section>;+}diff --git a/client/src/components/codeAnimation/ProductionAcceptance.test.jsx b/client/src/components/codeAnimation/ProductionAcceptance.test.jsxnew file mode 100644index 0000000000..7b26e28adf--- /dev/null+++ b/client/src/components/codeAnimation/ProductionAcceptance.test.jsx@@ -0,0 +1,58 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));+vi.mock('../../services/apiCodeAnimation', () => ({ getCodeAnimationAcceptance: vi.fn(), acceptCodeAnimationOutput: vi.fn() }));+import * as api from '../../services/apiCodeAnimation';+import ProductionAcceptance from './ProductionAcceptance';++const dim = (status, extra = {}) => ({ status, verified: [], unverified: [], findings: [], ...extra });+const evidence = { technical: dim('verified', { verified: ['frame-size'] }), visual: dim('partial', { verified: ['visual-motion'], unverified: [{ dimension: 'semantic-visual', reason: 'No reviewer ran.' }] }), temporal: dim('verified', { verified: ['timing'] }), sound: dim('unverified', { unverified: [{ dimension: 'hearing', reason: 'No listening review ran.' }] }) };+const run = (id, overrides = {}) => ({+ runId: id, status: 'completed', createdAt: new Date().toISOString(), accepted: false, acceptable: true,+ settings: { requested: { providerId: 'example', model: 'example-model', effort: 'high' }, effective: { providerId: 'example', model: 'example-model', effort: 'high' }, renderer: null },+ budgets: { iterations: 8, tokens: 1000, renderSeconds: 60 }, spend: { repairs: 2, tokens: 300, renderMs: 4000, elapsedMs: 9000, diskBytes: 2048 },+ verdict: { status: 'pass' }, reviewer: null, evidence, findings: [{ kind: 'event-without-change', severity: 'warning', detail: 'Quiet beat.', atSeconds: 1.5 }],+ repairs: [], frames: [], pilots: [], output: { path: `/data/videos/${id}.mp4` }, error: null, ...overrides,+});+const frozen = { runId: 'aaaaaaaa-1', videoId: 'video-1', revisionId: 'rev-1', path: '/data/videos/a.mp4', acceptedAt: new Date().toISOString(), sourceHash: 's'.repeat(64), renderHash: 'r'.repeat(64), audioHash: null, evidence, fresh: true, stale: [] };+const Location = () => <p data-testid="search">{useLocation().search}</p>;+const renderIt = props => render(<MemoryRouter initialEntries={['/p']}><Routes><Route path="/p" element={<><ProductionAcceptance projectId="p1" onProject={vi.fn()} onDownloadSource={vi.fn()} {...props} /><Location /></>} /></Routes></MemoryRouter>);+beforeEach(() => vi.resetAllMocks());++describe('Production acceptance', () => {+ it('keeps accepted playback beside a stale warning and a failed newer run', async () => {+ api.getCodeAnimationAcceptance.mockResolvedValue({+ accepted: { ...frozen, fresh: false, stale: [{ dimension: 'source', reason: 'The source files changed after it was accepted.' }] },+ runs: [run('bbbbbbbb-2', { status: 'failed', acceptable: false, verdict: { status: 'fail' } }), run('aaaaaaaa-1', { accepted: true })],+ });+ renderIt();+ expect(await screen.findByLabelText('Accepted final video')).toHaveAttribute('src', '/data/videos/a.mp4');+ expect(screen.getByRole('alert')).toHaveTextContent('The source files changed after it was accepted.');+ expect(screen.getByText(/Run bbbbbbbb · failed · verdict fail/)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Accept output of run bbbbbbbb/ })).not.toBeInTheDocument();+ expect(screen.getAllByText(/Unverified: No listening review ran\./).length).toBeGreaterThan(0);+ });++ it('compares two runs from the URL, showing effective route and budgets, and promotes one explicitly', async () => {+ const user = userEvent.setup();+ const low = run('cccccccc-3', { settings: { requested: { providerId: 'example', model: 'example-model', effort: 'low' }, effective: { providerId: 'example', model: 'example-model', effort: 'low' }, renderer: null }, spend: { repairs: 5, tokens: 900, renderMs: 4000, elapsedMs: 9000, diskBytes: 2048 } });+ api.getCodeAnimationAcceptance.mockResolvedValue({ accepted: null, runs: [run('dddddddd-4'), low] });+ api.acceptCodeAnimationOutput.mockResolvedValue({ id: 'p1' });+ renderIt();+ await user.click(await screen.findByLabelText(/Run dddddddd/));+ await user.click(screen.getByLabelText(/Run cccccccc/));+ expect(new URLSearchParams(screen.getByTestId('search').textContent).get('compare')).toBe('dddddddd-4,cccccccc-3');+ const columns = screen.getAllByRole('article');+ expect(columns).toHaveLength(2);+ expect(within(columns[0]).getByText(/2 repairs · 300 tokens/)).toBeInTheDocument();+ expect(within(columns[1]).getByText(/5 repairs · 900 tokens/)).toBeInTheDocument();+ // Model effort is labelled as an authoring budget, never as render samples or a repair count.+ expect(within(columns[1]).getByText(/low \(authoring reasoning budget\)/)).toBeInTheDocument();+ expect(within(columns[0]).getByLabelText('Timestamped findings')).toHaveTextContent('1.5s');+ await user.click(screen.getByRole('button', { name: /Accept output of run cccccccc/ }));+ expect(api.acceptCodeAnimationOutput).toHaveBeenCalledWith('p1', 'cccccccc-3', { silent: true });+ });+});diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsxindex 3c5d034822..656b87ad7c 100644--- a/client/src/components/codeAnimation/ProductionProjects.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.jsx@@ -16,6 +16,7 @@ import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';import ProductionProjectForm from './ProductionProjectForm';import ProductionPreflight from './ProductionPreflight';import ProductionContainment from './ProductionContainment';+import ProductionAcceptance from './ProductionAcceptance';import ProductionStageRuns, { isStageRun } from './ProductionStageRuns';const EVENTS = ['code-animation:changed'];@@ -138,6 +139,7 @@ export default function ProductionProjects() {<p className="text-xs text-gray-400">Requested model: {project.localSettings?.model || 'Unspecified'} · Mode: {project.localSettings?.mode || 'Unspecified'}</p><ProductionStageRuns project={project} runs={history.items.filter(isStageRun)} disabled={busy || dirty}onRunStarted={run => history.setItems(previous => [{ id: run.id, status: run.status, data: run, createdAt: new Date().toISOString() }, ...previous.filter(item => item.id !== run.id)])} />+ <ProductionAcceptance key={project.id} projectId={project.id} disabled={busy || dirty} onProject={applyProject} onDownloadSource={download} /><ul className="space-y-2">{history.items.filter(run => !isStageRun(run)).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>diff --git a/client/src/components/codeAnimation/ProductionProjects.test.jsx b/client/src/components/codeAnimation/ProductionProjects.test.jsxindex e714ee7c1b..f2401b5af6 100644--- a/client/src/components/codeAnimation/ProductionProjects.test.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx@@ -12,6 +12,7 @@ vi.mock('../../services/apiCodeAnimation', () => ({updateCodeAnimationProject: vi.fn(), importCodeAnimationPackage: vi.fn(), acceptCodeAnimationSource: vi.fn(),getCodeAnimationProjectBrief: vi.fn(), getCodeAnimationRevisionPackage: vi.fn(), listCodeAnimationProjectHistory: vi.fn(),startCodeAnimationStageRun: vi.fn(), cancelCodeAnimationStageRun: vi.fn(),+ getCodeAnimationAcceptance: vi.fn(), acceptCodeAnimationOutput: vi.fn(),}));import * as api from '../../services/apiCodeAnimation';import socket from '../../services/socket';@@ -49,6 +50,7 @@ beforeEach(() => {api.getCodeAnimationProject.mockResolvedValue(project);api.listCodeAnimationProjectHistory.mockResolvedValue(page());api.getCodeAnimationExecution.mockResolvedValue(execution());+ api.getCodeAnimationAcceptance.mockResolvedValue({ accepted: null, runs: [] });});describe('Production project rendered interactions', () => {diff --git a/client/src/components/codeAnimation/ProductionRunComparison.jsx b/client/src/components/codeAnimation/ProductionRunComparison.jsxnew file mode 100644index 0000000000..287008c32e--- /dev/null+++ b/client/src/components/codeAnimation/ProductionRunComparison.jsx@@ -0,0 +1,66 @@+import { formatBytes, formatCount, formatRuntime } from '../../utils/formatters';++const DIMENSIONS = [['technical', 'Technical'], ['visual', 'Visual'], ['temporal', 'Temporal'], ['sound', 'Sound']];+const STATUS_STYLE = { verified: 'text-port-success', partial: 'text-port-warning', failed: 'text-port-error', unverified: 'text-gray-400' };++/** Four evidence dimensions, drawn apart: a partial or unverified dimension never reads as a pass. */+export function EvidenceGrid({ evidence }) {+ return <dl className="grid grid-cols-1 gap-2 sm:grid-cols-2" aria-label="Evidence">+ {DIMENSIONS.map(([key, label]) => {+ const entry = evidence[key];+ return <div key={key} className="min-w-0 rounded border border-port-border p-2 text-xs">+ <dt className="flex justify-between gap-2"><span className="font-medium">{label}</span><span className={STATUS_STYLE[entry.status]}>{entry.status}</span></dt>+ <dd className="space-y-1 text-gray-400">+ {entry.verified.length > 0 && <p>Measured: {entry.verified.join(', ')}</p>}+ {entry.findings.map((finding, index) => <p key={index} className={finding.severity === 'error' ? 'text-port-error' : 'text-port-warning'}>[{finding.severity}] {finding.detail}</p>)}+ {entry.unverified.map(item => <p key={item.dimension} className="border-l border-dashed border-port-warning pl-2">Unverified: {item.reason}</p>)}+ </dd>+ </div>;+ })}+ </dl>;+}++const route = settings => settings ? [settings.providerId, settings.model].filter(Boolean).join(' · ') || 'Unspecified' : 'Not recorded';++function RunColumn({ run }) {+ const first = run.frames[0]?.revisionId;+ const before = run.frames.filter(frame => frame.revisionId === first);+ const after = run.frames.filter(frame => frame.revisionId !== first);+ const pilot = run.pilots.at(-1);+ return <article className="min-w-0 space-y-3 rounded border border-port-border p-3" aria-label={`Run ${run.runId.slice(0, 8)}`}>+ <h4 className="text-sm font-medium">Run {run.runId.slice(0, 8)} · {run.status}{run.accepted ? ' · accepted' : ''}</h4>+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">+ <dt className="text-gray-400">Requested route</dt><dd className="min-w-0 break-words">{route(run.settings.requested)}</dd>+ <dt className="text-gray-400">Effective route</dt><dd className="min-w-0 break-words">{route(run.settings.effective)}</dd>+ <dt className="text-gray-400">Model effort</dt><dd>{run.settings.effective?.effort || run.settings.requested?.effort || 'unspecified'} (authoring reasoning budget)</dd>+ {run.settings.renderer && <><dt className="text-gray-400">Renderer</dt><dd className="min-w-0 break-words">Blender {run.settings.renderer.version} · {run.settings.renderer.engine} · {run.settings.renderer.device}</dd></>}+ <dt className="text-gray-400">Budgets</dt><dd>{run.budgets ? `${formatCount(run.budgets.iterations)} repairs · ${formatCount(run.budgets.tokens)} tokens · ${formatCount(run.budgets.renderSeconds)}s render` : 'Not recorded'}</dd>+ <dt className="text-gray-400">Spent</dt><dd>{formatCount(run.spend.repairs)} repairs · {formatCount(run.spend.tokens)} tokens · {formatRuntime(run.spend.renderMs)} render · {formatRuntime(run.spend.elapsedMs)} elapsed · {formatBytes(run.spend.diskBytes)}</dd>+ <dt className="text-gray-400">Verdict</dt><dd>{run.verdict?.status || 'none'}{run.reviewer ? ` · reviewed by ${run.reviewer.providerId}` : ''}</dd>+ </dl>+ <EvidenceGrid evidence={run.evidence} />+ {run.findings.length > 0 && <ol className="space-y-1 text-xs" aria-label="Timestamped findings">+ {run.findings.map((finding, index) => <li key={index} className={finding.severity === 'error' ? 'text-port-error' : 'text-port-warning'}>+ <span className="tabular-nums">{finding.atSeconds != null ? `${formatCount(finding.atSeconds, { maximumFractionDigits: 2 })}s` : 'whole film'}</span> · {finding.kind}: {finding.detail}+ </li>)}+ </ol>}+ {run.repairs.length > 0 && <p className="text-xs text-gray-400">{formatCount(run.repairs.length)} repair revision{run.repairs.length === 1 ? '' : 's'}: {run.repairs.map(repair => repair.findingKinds.join('+')).join(' → ')}</p>}+ {before.length > 0 && <div className="space-y-1 text-xs"><p className="text-gray-400">{after.length ? 'Before repair' : 'Style frames'}</p>+ <div className="flex flex-wrap gap-2">{before.map(frame => <img key={frame.path} src={frame.path} alt={`Style frame at ${frame.atSeconds}s`} className="h-20 w-auto max-w-full rounded border border-port-border" />)}</div></div>}+ {after.length > 0 && <div className="space-y-1 text-xs"><p className="text-gray-400">After repair</p>+ <div className="flex flex-wrap gap-2">{after.map(frame => <img key={frame.path} src={frame.path} alt={`Repaired style frame at ${frame.atSeconds}s`} className="h-20 w-auto max-w-full rounded border border-port-border" />)}</div></div>}+ {pilot?.video+ ? <video aria-label={`Motion pilot for run ${run.runId.slice(0, 8)}`} controls preload="none" src={pilot.video} className="w-full min-w-0 rounded" />+ : pilot && <p className="text-xs text-gray-400">The browser pilot measured {formatCount(pilot.samples)} sampled frames; it produces no video to play.</p>}+ {run.output?.path && <video aria-label={`Final video for run ${run.runId.slice(0, 8)}`} controls preload="none" src={run.output.path} className="w-full min-w-0 rounded" />}+ {run.error && <p role="status" className="text-xs text-port-error">{run.error.message}</p>}+ </article>;+}++/** One or two selected runs, side by side. The selection lives in the URL, so a comparison can be shared. */+export default function ProductionRunComparison({ runs }) {+ if (!runs.length) return null;+ return <section aria-label="Run comparison" className={`grid grid-cols-1 gap-3 ${runs.length > 1 ? 'lg:grid-cols-2' : ''}`}>+ {runs.map(run => <RunColumn key={run.runId} run={run} />)}+ </section>;+}diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex c8daae43ca..d235d14096 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -74,3 +74,10 @@ export const probeCodeAnimationExecution = (options) => request('/code-animation// Explicit production workflows. Preview and final use the stored soundtrack artifact.export const getCodeAnimationBlenderStarter = options => request('/code-animation/packages/starter/blender', options);++// Production acceptance (#9392): the accepted output with live freshness, side-by-side run+// evidence, explicit promotion of one passing run, and the shorts downstream tools can pick.+export const getCodeAnimationAcceptance = (id, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/acceptance`, options);+export const acceptCodeAnimationOutput = (id, runId, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/accepted-output`, { method: 'POST', body: JSON.stringify({ runId }), ...options });+export const listCodeAnimationAcceptedAssets = ({ cursor, signal, limit = 50 } = {}) =>+ request(`/code-animation/accepted-assets?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`, { signal, silent: true });diff --git a/server/lib/README.md b/server/lib/README.mdindex 8bce276f72..a97a8de62a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -27,6 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. || `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |+| `codeAnimationAcceptance.js` | Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure. || `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. || `codeAnimationPackage.js` | Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, `createCodeAnimationPackage` and `summarizeCodeAnimationPackage`; validation never executes or stages code. || `socketEventContracts.js` | Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots. |diff --git a/server/lib/codeAnimationAcceptance.js b/server/lib/codeAnimationAcceptance.jsnew file mode 100644index 0000000000..4afe52006f--- /dev/null+++ b/server/lib/codeAnimationAcceptance.js@@ -0,0 +1,110 @@+/**+ * Code Animation production acceptance (#9392). Pure: it separates the+ * measured evidence of a finished run into technical, visual, temporal and+ * sound dimensions, decides whether a run may be promoted, and detects when an+ * accepted output no longer matches the source, audio and render it was frozen+ * against. A dimension nothing measured is `unverified` and never a pass.+ */++export const ACCEPTANCE_DIMENSIONS = ['technical', 'visual', 'temporal', 'sound'];++const CHECK_DIMENSION = {+ 'frame-size': 'technical', 'blank-frame': 'technical', 'renderer-runtime': 'technical', 'baked-scene': 'technical',+ 'visual-motion': 'visual', 'semantic-visual': 'visual',+ timing: 'temporal', 'stepped-transform-cadence': 'temporal', 'continuous-camera': 'temporal', 'audio-event-placement': 'temporal',+ audio: 'sound', 'audio-stream': 'sound', 'audio-duration': 'sound',+};+const FINDING_DIMENSION = {+ 'duration-mismatch': 'temporal', 'frame-rate-mismatch': 'temporal', 'frozen-film': 'temporal', 'frozen-span': 'temporal', 'event-without-change': 'temporal',+ 'visual-review': 'visual',+};++export const dimensionOfCheck = name => CHECK_DIMENSION[name] || (/audio|sound|hear/.test(name) ? 'sound' : 'technical');+export const dimensionOfFinding = kind => FINDING_DIMENSION[kind] || 'technical';++// Nothing in the pipeline listens to the film; these stay unverified until a reviewer says otherwise.+const ALWAYS_UNVERIFIED = [+ { dimension: 'hearing', reason: 'No listening review ran; how the sound feels against the picture is not measured.' },+ { dimension: 'temporal-sync', reason: 'Pacing and sound sync beyond the declared events are not measured.' },+];++/** `{ technical, visual, temporal, sound }`, each `{ status, verified, unverified, findings }`. */+export function acceptanceEvidence({ findings = [], verified = [], unverified = [] }) {+ const result = Object.fromEntries(ACCEPTANCE_DIMENSIONS.map(key => [key, { status: 'unverified', verified: [], unverified: [], findings: [] }]));+ for (const check of verified) result[dimensionOfCheck(check)].verified.push(check);+ for (const item of [...unverified, ...ALWAYS_UNVERIFIED]) {+ result[item.dimension === 'temporal-sync' ? 'temporal' : dimensionOfCheck(item.dimension)].unverified.push({ dimension: item.dimension, reason: item.reason });+ }+ for (const finding of findings) result[dimensionOfFinding(finding.kind)].findings.push(finding);+ for (const entry of Object.values(result)) {+ entry.status = entry.findings.some(finding => finding.severity === 'error') ? 'failed'+ : !entry.verified.length ? 'unverified' : entry.unverified.length ? 'partial' : 'verified';+ }+ return result;+}++/** Why a finished run cannot be promoted to the accepted output, or null when it can. */+export function acceptanceProblem(run) {+ const data = run?.data;+ if (!data || data.kind !== 'production-stages') return 'That is not a production run.';+ if (run.status !== 'completed' || !data.output?.videoId) return 'Only a completed run with a final video can be accepted.';+ if (data.verdict?.status !== 'pass') return `The run's evidence did not pass (${data.verdict?.status || 'none'}).`;+ if (data.verdict.revisionId !== data.output.revisionId || data.verdict.sourceHash !== data.output.sourceHash) {+ return 'The final video was rendered from a different source than the evidence measured.';+ }+ if (!/^[A-Za-z0-9._-]+\.mp4$/.test(data.output.filename || '')) return 'The final video has no managed file.';+ return null;+}++/** The immutable record promotion stores. `renderHash` is measured by the caller from the file on disk. */+export function freezeAcceptance({ run, project, renderHash, now = new Date().toISOString() }) {+ const { data } = run;+ const { output } = data;+ return {+ version: 1, runId: run.id, stageRunId: output.stageRunId ?? null, revisionId: output.revisionId,+ sourceHash: output.sourceHash, packageHash: output.packageHash, audioHash: output.audioHash ?? null, renderHash,+ videoId: output.videoId, filename: output.filename, path: output.path, jobId: output.jobId ?? null,+ title: project.title, format: project.manifest.format, acceptedAt: now,+ evidence: acceptanceEvidence({ findings: data.findings, verified: output.verifiedDimensions, unverified: output.unverified }),+ };+}++/** Compare a frozen acceptance with what is on disk now. Any unreadable or different hash is stale. */+export function acceptanceFreshness(frozen, current) {+ const stale = [];+ const compare = (dimension, label) => {+ if (current[`${dimension}Hash`] !== frozen[`${dimension}Hash`]) {+ stale.push({ dimension, reason: current[`${dimension}Hash`] === 'unreadable' ? `The ${label} could not be read back.` : `The ${label} changed after it was accepted.` });+ }+ };+ compare('source', 'source files');+ compare('audio', 'soundtrack');+ compare('render', 'rendered video');+ return { fresh: stale.length === 0, stale };+}++/** One run as the comparison view needs it: settings, budgets, spend and evidence side by side. */+export function summarizeRunForComparison(run, acceptedRunId = null) {+ const { data } = run;+ const inspect = [...(data.stages || [])].reverse().find(stage => stage.key === 'inspect' && stage.status === 'completed');+ const frames = (data.stages || []).filter(stage => stage.key === 'style-frame')+ .flatMap(stage => (stage.artifacts || []).map(artifact => ({ revisionId: stage.revisionId, atSeconds: artifact.atSeconds, path: `/data/${artifact.relativePath}` })));+ const pilots = (data.stages || []).filter(stage => stage.key === 'pilot' && stage.status === 'completed')+ .map(stage => ({ revisionId: stage.revisionId, video: stage.sequence?.artifact ? `/data/${stage.sequence.artifact.relativePath}` : null, samples: stage.samples?.length ?? 0 }));+ const reviewer = [...(data.stages || [])].reverse().find(stage => stage.key === 'review' && stage.reviewer)?.reviewer ?? null;+ return {+ runId: run.id, status: run.status, createdAt: run.createdAt, accepted: run.id === acceptedRunId,+ revisionId: data.currentRevisionId, sourceRevisionId: data.sourceRevisionId,+ // Model effort is the authoring route's reasoning budget; it is not GPU samples or a repair count.+ settings: { requested: data.requested ?? null, effective: data.effective ?? null, renderer: data.renderer ?? null },+ budgets: data.budgets ?? null,+ spend: { repairs: data.spent?.iterations ?? 0, tokens: data.spent?.tokens ?? 0, renderMs: data.spent?.renderMs ?? 0, elapsedMs: data.spent?.elapsedMs ?? 0, diskBytes: data.spent?.diskBytes ?? 0 },+ verdict: data.verdict ?? null, reviewer,+ evidence: acceptanceEvidence({ findings: data.findings, verified: data.output?.verifiedDimensions ?? inspect?.verified ?? [], unverified: data.output?.unverified ?? data.verdict?.unverified ?? [] }),+ findings: [...(data.findings || [])].sort((a, b) => (a.atSeconds ?? -1) - (b.atSeconds ?? -1)),+ repairs: data.repairs ?? [], frames, pilots,+ output: data.output ? { videoId: data.output.videoId, path: data.output.path, revisionId: data.output.revisionId, sourceHash: data.output.sourceHash } : null,+ acceptable: acceptanceProblem(run) === null,+ error: data.error ?? null,+ };+}diff --git a/server/lib/codeAnimationAcceptance.test.js b/server/lib/codeAnimationAcceptance.test.jsnew file mode 100644index 0000000000..f57ad96807--- /dev/null+++ b/server/lib/codeAnimationAcceptance.test.js@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { acceptanceEvidence, acceptanceFreshness, acceptanceProblem } from './codeAnimationAcceptance.js';++describe('acceptanceEvidence', () => {+ it('keeps the four dimensions apart and never turns an unmeasured dimension into a pass', () => {+ const evidence = acceptanceEvidence({+ verified: ['frame-size', 'timing', 'visual-motion'],+ unverified: [{ dimension: 'semantic-visual', reason: 'No reviewer ran.' }],+ findings: [{ kind: 'frozen-span', severity: 'error', detail: 'x' }],+ });+ expect(evidence.technical.status).toBe('verified');+ expect(evidence.visual.status).toBe('partial');+ expect(evidence.temporal.status).toBe('failed');+ expect(evidence.sound).toMatchObject({ status: 'unverified', verified: [] });+ expect(evidence.sound.unverified.map(item => item.dimension)).toContain('hearing');+ });+});++describe('acceptanceFreshness', () => {+ const frozen = { sourceHash: 's', audioHash: 'a', renderHash: 'r' };+ it('is fresh only when source, audio and render all match', () => {+ expect(acceptanceFreshness(frozen, { sourceHash: 's', audioHash: 'a', renderHash: 'r' }).fresh).toBe(true);+ const stale = acceptanceFreshness(frozen, { sourceHash: 's2', audioHash: 'unreadable', renderHash: 'r' });+ expect(stale.stale.map(item => item.dimension)).toEqual(['source', 'audio']);+ });+});++describe('acceptanceProblem', () => {+ const run = { status: 'completed', data: { kind: 'production-stages', verdict: { status: 'pass', revisionId: 'v', sourceHash: 'h' }, output: { videoId: 'x', revisionId: 'v', sourceHash: 'h', filename: 'a.mp4' } } };+ it('refuses an output rendered from a different source than the evidence measured', () => {+ expect(acceptanceProblem(run)).toBeNull();+ expect(acceptanceProblem({ ...run, data: { ...run.data, output: { ...run.data.output, sourceHash: 'other' } } })).toMatch(/different source/);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex f1a52ad605..05758fb7cf 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -20,6 +20,7 @@ export * from './appPromptPlaceholders.js';export * from './appDeployFlags.js';export * from './apiContractSchemas.js';export * from './codeAnimationPackage.js';+export * from './codeAnimationAcceptance.js';export * from './codeAnimationContainment.js';export * from './autonomousJobTask.js';export * from './asyncApiSpec.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 4a85eb1bc7..2802533c5d 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -55,7 +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.code-animation.production', path: '/code-animation/production', label: 'Code Animation Production', section: 'Create', aliases: ['code-animation-production', 'animation-production', 'production-animation'], keywords: ['film projects', 'accepted output', 'compare runs', 'evidence', '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/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex c43fcda37a..7b1c062217 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -13,6 +13,9 @@* POST /api/code-animation/packages/validate check package data/integrity only* POST /api/code-animation/projects/:id/stage-runs start a bounded production run → 202* POST /api/code-animation/projects/:id/stage-runs/:runId/cancel stop an active run+ * GET /api/code-animation/projects/:id/acceptance accepted output + freshness + run comparison+ * POST /api/code-animation/projects/:id/accepted-output promote a passing run's video+ * GET /api/code-animation/accepted-assets accepted shorts for downstream tools*/import { Router } from 'express';@@ -37,6 +40,7 @@ import { getBlenderStarterPackage } from '../services/codeAnimation/blenderStartimport { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema, codeAnimationStageRunSchema } from '../lib/codeAnimationProjects.js';+import { acceptProductionOutput, getProductionAcceptance, listAcceptedAssets } from '../services/codeAnimation/acceptance.js';import { startProductionStageRun, cancelProductionStageRun } from '../services/codeAnimation/stages.js';import {createProductionProject, getProductionProject, patchProductionProject,@@ -230,6 +234,19 @@ router.post('/projects/:id/stage-runs/:runId/cancel', asyncHandler(async (req, rconst { id, runId } = validateRequest(z.object({ id: z.string().uuid(), runId: z.string().uuid() }).strict(), req.params);res.json(cancelProductionStageRun(id, runId));}));+router.get('/accepted-assets', asyncHandler(async (req, res) => {+ res.json(await listAcceptedAssets(projectPage(req.query)));+}));+router.get('/projects/:id/acceptance', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ res.json(await getProductionAcceptance(id));+}));+// Explicit promotion of one finished run's video; frozen to its source/audio/render hashes.+router.post('/projects/:id/accepted-output', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ const { runId } = validateRequest(z.object({ runId: z.string().uuid() }).strict(), req.body);+ res.json(await acceptProductionOutput(id, runId));+}));router.get('/projects/:id/brief', asyncHandler(async (req, res) => {const { id } = validateRequest(exportParamsSchema, req.params);res.attachment(`code-animation-brief-${id}.json`);diff --git a/server/services/codeAnimation/acceptance.db.test.js b/server/services/codeAnimation/acceptance.db.test.jsnew file mode 100644index 0000000000..cf1324a24b--- /dev/null+++ b/server/services/codeAnimation/acceptance.db.test.js@@ -0,0 +1,142 @@+/** Public acceptance routes: frozen promotion, stale detection, failed-run isolation and downstream discovery. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { chmod, mkdir, readFile, writeFile } from 'fs/promises';+import { createHash, randomUUID } from 'crypto';+import { join } from 'path';+import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';+vi.mock('../../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-acceptance-') }));+vi.mock('../../lib/fileUtils.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-acceptance-') }));+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';+import { requireDbOrSkip } from '../../lib/dbTestGate.js';+import { errorMiddleware } from '../../lib/errorHandler.js';+import { request } from '../../lib/testHelper.js';+import { PATHS } from '../../lib/paths.js';+import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';+import { emitCodeAnimationChanged } from '../socket.js';+import { loadHistory, saveHistory } from '../videoGen/history.js';+import routes from '../../routes/codeAnimation.js';++const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('codeAnimation/acceptance.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();+});+const app = express(); app.use(express.json({ limit: '55mb' })); app.use('/animation', routes); app.use(errorMiddleware);+const post = (path, body) => request(app).post(`/animation${path}`).send(body);+const get = path => request(app).get(`/animation${path}`);+const sha = bytes => createHash('sha256').update(bytes).digest('hex');++const manifest = {+ title: 'Example short', brief: { concept: 'An original reveal', cast: '', onScreenText: '' }, styleGuide: 'Flat shapes',+ renderer: { kind: 'browser', version: 'example-v1', engine: null }, format: { width: 1280, height: 720, fps: 12, durationSeconds: 2 }, seed: 1,+ entrypoints: [{ role: 'preview', path: 'index.html' }], assets: [], shots: [], events: [], audio: { kind: 'silence' },+ execution: { requested: null, effective: null },+};++async function project() {+ const created = await post('/projects', { manifest });+ ids.push(created.body.id);+ const imported = await post(`/projects/${created.body.id}/import`, createCodeAnimationPackage(manifest, [{ path: 'index.html', content: '<html><canvas></canvas></html>' }]));+ return { id: created.body.id, revision: imported.body.revision };+}++/** A finished run as the stage pipeline persists it; the pipeline itself is covered by stages.db.test. */+async function finishedRun({ id, revision }, { verdict = 'pass', bytes = 'example-mp4-bytes', settings = {}, spent = {} } = {}) {+ const runId = randomUUID();+ const videoId = randomUUID();+ const filename = `composition-${runId}.mp4`;+ await mkdir(PATHS.videos, { recursive: true });+ await writeFile(join(PATHS.videos, filename), bytes);+ const history = await loadHistory().catch(() => []);+ await saveHistory([{ id: videoId, filename, prompt: 'Example short', createdAt: new Date().toISOString() }, ...history]);+ const failed = verdict !== 'pass';+ await query(`INSERT INTO code_animation_project_runs (id, project_id, revision_id, status, data, completed_at) VALUES ($1,$2,$3,$4,$5,NOW())`,+ [runId, id, revision.id, failed ? 'failed' : 'completed', {+ kind: 'production-stages', currentRevisionId: revision.id, sourceRevisionId: revision.id,+ requested: { providerId: 'example', model: 'example-model', effort: 'high', ...settings.requested }, effective: settings.effective ?? null,+ budgets: { iterations: 8, tokens: 1000 }, spent: { iterations: 1, tokens: 200, renderMs: 5000, elapsedMs: 9000, diskBytes: 100, ...spent },+ stages: [{ key: 'style-frame', revisionId: revision.id, status: 'completed', artifacts: [{ atSeconds: 0.5, relativePath: 'code-animations/example.png' }] }],+ findings: failed ? [{ kind: 'frozen-film', severity: 'error', detail: 'Nothing moves.', atSeconds: 0 }] : [{ kind: 'event-without-change', severity: 'warning', detail: 'Quiet beat.', atSeconds: 1.5 }],+ verdict: { status: verdict, revisionId: revision.id, sourceHash: revision.sourceHash, unverified: [{ dimension: 'semantic-visual', reason: 'No reviewer ran.' }] },+ soundtrack: { artifact: null, unverified: [] }, repairs: [],+ output: failed ? null : {+ revisionId: revision.id, sourceHash: revision.sourceHash, packageHash: revision.packageHash, audioHash: null, videoId, filename, path: `/data/videos/${filename}`,+ audioEvidence: { videoHash: sha(bytes) }, verifiedDimensions: ['frame-size', 'timing', 'visual-motion', 'audio'], unverified: [{ dimension: 'semantic-visual', reason: 'No reviewer ran.' }],+ },+ }]);+ return { runId, videoId, filename };+}++describe.skipIf(!ready)('Production acceptance', () => {+ it('promotes a passing run, separates evidence dimensions, marks Media History and lists the short downstream', async () => {+ const p = await project();+ const run = await finishedRun(p);+ const accepted = await post(`/projects/${p.id}/accepted-output`, { runId: run.runId });+ expect(accepted.status).toBe(200);+ expect(accepted.body).toMatchObject({ acceptedRevisionId: p.revision.id, candidateRevisionId: null, acceptedOutput: { runId: run.runId, videoId: run.videoId, sourceHash: p.revision.sourceHash, renderHash: sha('example-mp4-bytes') } });+ expect(emitCodeAnimationChanged).toHaveBeenCalledWith(p.id);++ const view = (await get(`/projects/${p.id}/acceptance`)).body;+ expect(view.accepted).toMatchObject({ fresh: true, stale: [], path: `/data/videos/${run.filename}` });+ expect(view.accepted.evidence).toMatchObject({+ technical: { status: 'verified' }, visual: { status: 'partial' }, temporal: { status: 'partial' }, sound: { status: 'partial' },+ });+ // Nothing listened to the film: hearing stays unverified rather than passing.+ expect(view.accepted.evidence.sound.unverified.map(item => item.dimension)).toContain('hearing');++ expect((await loadHistory()).find(entry => entry.id === run.videoId).codeAnimation.acceptance).toMatchObject({ projectId: p.id, runId: run.runId });+ const assets = (await get('/accepted-assets')).body.items.find(item => item.projectId === p.id);+ expect(assets).toMatchObject({ videoId: run.videoId, sourceHash: p.revision.sourceHash, packageUrl: `/api/code-animation/projects/${p.id}/revisions/${p.revision.id}/package` });+ });++ it('refuses a failing run and keeps the accepted playback when a later candidate fails', async () => {+ const p = await project();+ const good = await finishedRun(p);+ await post(`/projects/${p.id}/accepted-output`, { runId: good.runId });+ const bad = await finishedRun(p, { verdict: 'fail' });+ const refused = await post(`/projects/${p.id}/accepted-output`, { runId: bad.runId });+ expect(refused).toMatchObject({ status: 409, body: { code: 'CODE_ANIMATION_OUTPUT_NOT_ACCEPTABLE' } });+ const view = (await get(`/projects/${p.id}/acceptance`)).body;+ expect(view.accepted).toMatchObject({ runId: good.runId, fresh: true, path: `/data/videos/${good.filename}` });+ expect(view.runs.map(item => [item.runId, item.accepted, item.acceptable])).toEqual(expect.arrayContaining([[good.runId, true, true], [bad.runId, false, false]]));+ expect(view.runs.find(item => item.runId === bad.runId).evidence.temporal.status).toBe('failed');+ });++ it('invalidates the earlier passing review when the rendered video or the source bytes change', async () => {+ const p = await project();+ const run = await finishedRun(p);+ await post(`/projects/${p.id}/accepted-output`, { runId: run.runId });+ await writeFile(join(PATHS.videos, run.filename), 'a different render');+ const rendered = (await get(`/projects/${p.id}/acceptance`)).body.accepted;+ expect(rendered).toMatchObject({ fresh: false, path: `/data/videos/${run.filename}` });+ expect(rendered.stale.map(item => item.dimension)).toEqual(['render']);++ const sourceFile = join(PATHS.data, p.revision.storage.relativePath, 'index.html');+ await chmod(sourceFile, 0o600);+ await writeFile(sourceFile, '<html>tampered</html>');+ expect((await get(`/projects/${p.id}/acceptance`)).body.accepted.stale.map(item => item.dimension)).toEqual(expect.arrayContaining(['source', 'render']));+ // A changed render cannot be promoted in the first place.+ const other = await project();+ const changed = await finishedRun(other);+ await writeFile(join(PATHS.videos, changed.filename), 'swapped before acceptance');+ expect((await post(`/projects/${other.id}/accepted-output`, { runId: changed.runId })).body.code).toBe('CODE_ANIMATION_RENDER_CHANGED');+ });++ it('compares two same-brief runs by requested and effective route, budgets and spend without conflating effort', async () => {+ const p = await project();+ const a = await finishedRun(p, { settings: { effective: { providerId: 'example', model: 'example-model', effort: 'high' } }, spent: { iterations: 1, tokens: 200 } });+ const b = await finishedRun(p, { settings: { requested: { effort: 'low' }, effective: { providerId: 'example', model: 'example-model', effort: 'low' } }, spent: { iterations: 4, tokens: 900 } });+ const { runs } = (await get(`/projects/${p.id}/acceptance`)).body;+ const [left, right] = [a, b].map(item => runs.find(entry => entry.runId === item.runId));+ expect([left.settings.effective.effort, right.settings.effective.effort]).toEqual(['high', 'low']);+ expect([left.spend.repairs, right.spend.repairs]).toEqual([1, 4]);+ expect([left.spend.tokens, right.spend.tokens]).toEqual([200, 900]);+ expect(left.budgets).toEqual(right.budgets);+ expect(await readFile(join(PATHS.videos, a.filename), 'utf8')).toBe('example-mp4-bytes');+ });+});diff --git a/server/services/codeAnimation/acceptance.js b/server/services/codeAnimation/acceptance.jsnew file mode 100644index 0000000000..62583b6e02--- /dev/null+++ b/server/services/codeAnimation/acceptance.js@@ -0,0 +1,103 @@+/**+ * Accepted Code Animation output (#9392). Promotion is explicit and frozen to+ * the source, audio and rendered-video hashes; reading it back recomputes all+ * three from disk, so any change makes earlier passing evidence stale while the+ * accepted video stays playable. Newer failed runs never replace it.+ */+import { createHash } from 'crypto';+import { createReadStream } from 'fs';+import { join } from 'path';+import { acceptanceFreshness, acceptanceProblem, freezeAcceptance, summarizeRunForComparison } from '../../lib/codeAnimationAcceptance.js';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';+import { emitCodeAnimationChanged } from '../socket.js';+import { mutateVideoHistory } from '../videoGen/history.js';+import * as store from './projectStore.js';+import { getProductionProject } from './projects.js';+import { readProjectFiles, readRunArtifact, sourceHashOf } from './projectFiles.js';+import { STAGE_RUN_KIND } from './stages.js';++const RECENT_RUNS = 30;+const UNREADABLE = 'unreadable';++const hashVideo = filename => new Promise(resolve => {+ const digest = createHash('sha256');+ createReadStream(join(PATHS.videos, filename))+ .on('data', chunk => digest.update(chunk))+ .on('end', () => resolve(digest.digest('hex')))+ .on('error', () => resolve(UNREADABLE));+});++const call = async fn => { try { return await fn(); } catch { return UNREADABLE; } };++/** What the frozen record's source, audio and render hash to on disk right now. */+async function currentHashes(projectId, frozen, run) {+ const revision = await store.getRevisionRecord(projectId, frozen.revisionId);+ const artifact = run?.data.soundtrack?.artifact ?? null;+ return {+ sourceHash: revision ? await call(async () => sourceHashOf(await readProjectFiles(projectId, revision.id, revision.files))) : UNREADABLE,+ audioHash: artifact ? await call(async () => { await readRunArtifact(projectId, run.id, artifact.name, artifact.sha256); return artifact.sha256; }) : (run ? null : UNREADABLE),+ renderHash: await hashVideo(frozen.filename),+ };+}++export async function acceptProductionOutput(projectId, runId) {+ const project = await getProductionProject(projectId);+ const run = await store.getRunRecord(projectId, runId);+ if (!run || run.data.kind !== STAGE_RUN_KIND) throw new ServerError('Run not found', { status: 404, code: 'NOT_FOUND' });+ const problem = acceptanceProblem(run);+ if (problem) throw new ServerError(problem, { status: 409, code: 'CODE_ANIMATION_OUTPUT_NOT_ACCEPTABLE' });+ const renderHash = await hashVideo(run.data.output.filename);+ const measured = run.data.output.audioEvidence?.videoHash;+ if (renderHash === UNREADABLE || (measured && measured !== renderHash)) {+ throw new ServerError('The rendered video is missing or changed since the run measured it', { status: 409, code: 'CODE_ANIMATION_RENDER_CHANGED' });+ }+ const frozen = freezeAcceptance({ run, project, renderHash });+ const current = await currentHashes(projectId, frozen, run);+ const freshness = acceptanceFreshness(frozen, current);+ if (!freshness.fresh) {+ throw new ServerError(`The run's source or audio changed since it was measured: ${freshness.stale.map(item => item.reason).join(' ')}`, { status: 409, code: 'CODE_ANIMATION_EVIDENCE_STALE' });+ }+ const saved = await store.setAcceptedOutput(projectId, frozen);+ // Media History carries the accepted marker so Music Video Studio and Creative+ // Director can pick the short by its ordinary history id, with no song or episode project.+ await mutateVideoHistory(history => {+ for (const entry of history) {+ if (entry?.codeAnimation?.acceptance?.projectId === projectId && entry.id !== frozen.videoId) delete entry.codeAnimation.acceptance;+ if (entry?.id === frozen.videoId) {+ entry.codeAnimation = { ...(entry.codeAnimation || {}), revisionId: frozen.revisionId, sourceHash: frozen.sourceHash,+ acceptance: { projectId, runId, sourceHash: frozen.sourceHash, audioHash: frozen.audioHash, renderHash, acceptedAt: frozen.acceptedAt } };+ }+ }+ return history;+ });+ emitCodeAnimationChanged(projectId);+ return saved;+}++/** The accepted output with live freshness, plus recent runs summarized for side-by-side comparison. */+export async function getProductionAcceptance(projectId) {+ const project = await getProductionProject(projectId);+ const { items } = await store.pageProjectHistory(projectId, { limit: RECENT_RUNS, offset: 0 });+ const runs = items.filter(item => item.data?.kind === STAGE_RUN_KIND);+ const frozen = project.acceptedOutput ?? null;+ let accepted = null;+ if (frozen) {+ const source = runs.find(run => run.id === frozen.runId) ?? await store.getRunRecord(projectId, frozen.runId);+ accepted = { ...frozen, ...acceptanceFreshness(frozen, await currentHashes(projectId, frozen, source)) };+ }+ return { accepted, runs: runs.map(run => summarizeRunForComparison(run, frozen?.runId ?? null)) };+}++/** Accepted shorts as downstream tools consume them: a Media History id and a source package, nothing else required. */+export async function listAcceptedAssets(page) {+ const { items, nextCursor } = await store.pageAcceptedOutputs(page);+ return {+ items: items.map(({ id, title, accepted }) => ({+ projectId: id, title, videoId: accepted.videoId, filename: accepted.filename, path: accepted.path, format: accepted.format,+ sourceHash: accepted.sourceHash, audioHash: accepted.audioHash, renderHash: accepted.renderHash, acceptedAt: accepted.acceptedAt,+ packageUrl: `/api/code-animation/projects/${id}/revisions/${accepted.revisionId}/package`,+ })),+ nextCursor,+ };+}diff --git a/server/services/codeAnimation/projectStore.js b/server/services/codeAnimation/projectStore.jsindex 9b5f700a6a..ef1c673dc5 100644--- a/server/services/codeAnimation/projectStore.js+++ b/server/services/codeAnimation/projectStore.js@@ -182,3 +182,29 @@ export async function interruptStageRuns(projectId, activeIds) {data = data || '{"resumable":true}'::jsonb, completed_at = NOW()WHERE project_id = $1 AND status = 'running' AND data->>'kind' = 'production-stages' AND NOT (id = ANY($2::text[]))`, [projectId, activeIds]);}++// ---- Accepted output (#9392): a frozen record beside, never inside, the run history ----++/**+ * Store the accepted output on the project. A later failed or stale run never+ * touches it. When the output's revision is the current candidate, accepting+ * the output also accepts that source in the same transaction.+ */+export async function setAcceptedOutput(projectId, accepted) {+ 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();+ const promoteSource = rows[0].candidateRevisionId === accepted.revisionId;+ const result = await client.query(`UPDATE code_animation_projects SET data = data || jsonb_build_object('acceptedOutput', $2::jsonb),+ accepted_revision_id = CASE WHEN $4 THEN $3 ELSE accepted_revision_id END,+ candidate_revision_id = CASE WHEN $4 THEN NULL ELSE candidate_revision_id END, updated_at = NOW()+ WHERE id = $1 RETURNING ${columns}`, [projectId, JSON.stringify(accepted), accepted.revisionId, promoteSource]);+ return present(result.rows[0]);+ });+}++export async function pageAcceptedOutputs({ limit, offset }) {+ const { rows } = await query(`SELECT id, title, data->'acceptedOutput' AS accepted FROM code_animation_projects+ WHERE data ? 'acceptedOutput' ORDER BY data->'acceptedOutput'->>'acceptedAt' DESC, id DESC LIMIT $1 OFFSET $2`, [limit + 1, offset]);+ return { items: rows.slice(0, limit), nextCursor: rows.length > limit ? String(offset + limit) : null };+}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex cef6bf8fbc..4d6b0e986d 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -22,6 +22,7 @@ export const DB_TEST_INCLUDE = ['**/db.test.js','services/codeAnimation/stages.db.test.js','services/codeAnimation/sound.db.test.js',+ 'services/codeAnimation/acceptance.db.test.js','services/codeAnimation/stages.realBrowser.db.test.js','services/mediaAssetIndex/galleryCollections.db.test.js','services/dbAdmin.db.test.js',