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: produce revision-bound offline animation soundtracks (#9397)
[._.]/ Adam Eivy48559a16f311
diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsxindex 3c6ff02afe..408eef8ef5 100644--- a/client/src/components/codeAnimation/ProductionProjects.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.jsx@@ -126,7 +126,8 @@ export default function ProductionProjects() {</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>- <ProductionStageRuns project={project} runs={history.items.filter(isStageRun)} disabled={busy || dirty} />+ <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)])} /><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 037285f475..567dc1fe24 100644--- a/client/src/components/codeAnimation/ProductionProjects.test.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx@@ -51,6 +51,29 @@ beforeEach(() => {});describe('Production project rendered interactions', () => {+ it('starts from saved settings, immediately displays revision-bound audio, and keeps older evidence visibly stale', async () => {+ const user = userEvent.setup();+ api.listCodeAnimationProjectHistory.mockResolvedValue(page([{ id: 'example-sound-run', status: 'completed', data: {+ kind: 'production-stages', stages: [], soundtrack: { revisionId: 'old-revision', packageHash: 'example-bound-hash',+ artifact: { relativePath: 'code-animations/projects/example/runs/example/artifacts/sound-example.wav' },+ measured: { durationMs: 2000, sampleRate: 48000 }, events: [{ label: 'Impact', firstSeconds: 0.5, frame: 6 }],+ unverified: [{ dimension: 'hearing', reason: 'Listening quality is unverified.' }] },+ output: { path: '/data/videos/example.mp4', audioEvidence: { decodedDurationSeconds: 2 } },+ } }]));+ api.startCodeAnimationStageRun.mockResolvedValue({ id: 'example-live-run', status: 'running', kind: 'production-stages', stages: [] });+ api.preflightCodeAnimationProject.mockResolvedValue({ capabilities: {} });+ renderPage();+ expect(await screen.findByText('Sound evidence belongs to an older revision.')).toBeInTheDocument();+ expect(screen.getByLabelText('Production soundtrack preview')).toHaveAttribute('src', '/data/code-animations/projects/example/runs/example/artifacts/sound-example.wav');+ expect(screen.getByLabelText('Production final film')).toHaveAttribute('src', '/data/videos/example.mp4');+ expect(screen.getByText(/Final MP4 audio decoded and measured/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Run production stages' }));+ await user.click(await screen.findByRole('button', { name: 'Start run' }));+ expect(api.startCodeAnimationStageRun).toHaveBeenCalledWith(project.id, {}, { silent: true });+ expect(await screen.findByRole('button', { name: 'Cancel run' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Run production stages' })).toBeDisabled();+ });+it('opens a URL-selected detail and applies accepted-source responses immediately', async () => {const user = userEvent.setup();renderPage();diff --git a/client/src/components/codeAnimation/ProductionSoundEvidence.jsx b/client/src/components/codeAnimation/ProductionSoundEvidence.jsxnew file mode 100644index 0000000000..e4d6164936--- /dev/null+++ b/client/src/components/codeAnimation/ProductionSoundEvidence.jsx@@ -0,0 +1,18 @@+import { formatCount } from '../../utils/formatters';++export default function ProductionSoundEvidence({ run, currentRevisionId }) {+ const sound = run.data.soundtrack;+ const evidence = run.data.output?.audioEvidence;+ if (!sound) return null;+ const stale = currentRevisionId && currentRevisionId !== sound.revisionId;+ return <div className="min-w-0 space-y-2 text-sm">+ <p role="status">{stale ? 'Sound evidence belongs to an older revision.' : sound.intentional ? 'Intentionally silent soundtrack' : 'Offline soundtrack ready for preview'}</p>+ {sound.artifact && <audio aria-label="Production soundtrack preview" controls preload="none" src={`/data/${sound.artifact.relativePath}`} className="w-full min-w-0" />}+ {sound.measured && <p className="text-xs text-gray-400">Measured sound: {formatCount(sound.measured.durationMs / 1000, { maximumFractionDigits: 3 })} seconds · {formatCount(sound.measured.sampleRate)} Hz</p>}+ {sound.events?.map((event, index) => <p key={index} className="break-words text-xs text-gray-400">{event.label}: measured onset {formatCount(event.firstSeconds, { maximumFractionDigits: 3 })} seconds · frame {formatCount(event.frame)}</p>)}+ {evidence && <p role="status" className="text-xs">{evidence.intentional ? 'Final film intentionally silent' : `Final MP4 audio decoded and measured: ${formatCount(evidence.decodedDurationSeconds, { maximumFractionDigits: 3 })} seconds`}</p>}+ {run.data.output?.path && <video aria-label="Production final film" controls preload="none" src={run.data.output.path} className="w-full min-w-0 rounded" />}+ {sound.unverified?.map(item => <p key={item.dimension} className="break-words text-xs text-gray-400">Unverified: {item.reason}</p>)}+ <p className="break-all text-xs text-gray-400">Sound revision: {sound.packageHash}</p>+ </div>;+}diff --git a/client/src/components/codeAnimation/ProductionStageRuns.jsx b/client/src/components/codeAnimation/ProductionStageRuns.jsxindex 29fa55844e..40fe572778 100644--- a/client/src/components/codeAnimation/ProductionStageRuns.jsx+++ b/client/src/components/codeAnimation/ProductionStageRuns.jsx@@ -1,3 +1,4 @@+import ProductionSoundEvidence from './ProductionSoundEvidence';import { useState } from 'react';import { useAsyncAction } from '../../hooks/useAsyncAction';import {@@ -6,7 +7,7 @@ import {import { formatCount, formatRuntime, timeAgo } from '../../utils/formatters';const buttonClass = 'rounded border border-port-border px-3 py-2 text-sm hover:border-port-accent disabled:opacity-50';-const STAGE_LABELS = { 'style-frame': 'Style frames', pilot: 'Pilot', review: 'Visual review', inspect: 'Inspection', repair: 'Repair', final: 'Final render' };+const STAGE_LABELS = { 'style-frame': 'Style frames', pilot: 'Pilot', review: 'Visual review', inspect: 'Inspection', repair: 'Repair', soundtrack: 'Offline soundtrack', final: 'Final render' };const RESUMABLE = new Set(['interrupted', 'canceled', 'exhausted', 'failed']);export const isStageRun = run => run?.data?.kind === 'production-stages';@@ -21,7 +22,7 @@ function Verdict({ verdict, verified = [] }) {</div>;}-function StageRun({ run, busy, onResume, onCancel }) {+function StageRun({ run, busy, resumeDisabled, onResume, onCancel, currentRevisionId }) {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 || []);@@ -48,11 +49,12 @@ function StageRun({ run, busy, onResume, onCancel }) {{frames.length > 0 && <div className="flex flex-wrap gap-2">{frames.map(frame => <a key={frame.relativePath} href={`/data/${frame.relativePath}`} target="_blank" rel="noreferrer" className="text-xs underline">Style frame at {frame.atSeconds}s</a>)}</div>}+ <ProductionSoundEvidence run={run} currentRevisionId={currentRevisionId} />{data.output?.path && <a href={data.output.path} target="_blank" rel="noreferrer" className="block text-xs underline">Open final video</a>}{data.error && <p role="status" className="text-xs text-port-error">{data.error.message}</p>}<div className="flex flex-wrap gap-2">{running && <button type="button" className={buttonClass} disabled={busy} onClick={() => onCancel(run.id)}>Cancel run</button>}- {RESUMABLE.has(run.status) && data.resumable && <button type="button" className={buttonClass} disabled={busy} onClick={() => onResume(run.id)}>Resume run</button>}+ {RESUMABLE.has(run.status) && data.resumable && <button type="button" className={buttonClass} disabled={resumeDisabled} onClick={() => onResume(run.id)}>Resume run</button>}</div></li>;}@@ -62,7 +64,7 @@ function StageRun({ run, busy, onResume, onCancel }) {* list is the project's history (kept live by the code-animation:changed event* in the parent); nothing here polls and no provider is called before Start.*/-export default function ProductionStageRuns({ project, runs, disabled }) {+export default function ProductionStageRuns({ project, runs, disabled, onRunStarted }) {const [confirming, setConfirming] = useState(false);const [capabilities, setCapabilities] = useState(null);const [visualReview, setVisualReview] = useState(false);@@ -76,14 +78,15 @@ export default function ProductionStageRuns({ project, runs, disabled }) {setConfirming(true);});const start = input => act(async () => {- await startCodeAnimationStageRun(project.id, input, { silent: true });+ const run = await startCodeAnimationStageRun(project.id, input, { silent: true });+ onRunStarted?.(run);setConfirming(false);setVisualReview(false);});const canReview = Boolean(capabilities?.imageInputAccepted);return <section className="space-y-3 rounded border border-port-border p-3" aria-label="Production stages"><h3 className="text-sm font-semibold">Production stages</h3>- <p className="text-xs text-gray-400">Measures real style frames and a pilot, inspects the evidence, repairs measured errors through your saved authoring route, then renders the final video. Nothing runs until you start it.</p>+ <p className="text-xs text-gray-400">Measures real style frames and a pilot, inspects the evidence, repairs measured errors through your saved authoring route, produces the offline soundtrack, then renders and measures the final video audio. Nothing runs until you start it.</p>{!confirming && <button type="button" className={buttonClass} disabled={disabled || busy || live || !hasSource} onClick={openConfirm}>Run production stages</button>}{!hasSource && <p className="text-xs text-gray-400">Import a source package first.</p>}{confirming && <div role="group" aria-label="Confirm production run" className="space-y-2 rounded border border-port-border p-3 text-sm">@@ -96,12 +99,13 @@ export default function ProductionStageRuns({ project, runs, disabled }) {</div>: <p className="text-xs text-gray-400">This route does not accept images, so style fit stays unverified.</p>}<div className="flex flex-wrap gap-2">- <button type="button" className={buttonClass} disabled={busy} onClick={() => start(visualReview ? { visualReview: true } : {})}>Start run</button>+ <button type="button" className={buttonClass} disabled={disabled || busy || live} onClick={() => start(visualReview ? { visualReview: true } : {})}>Start run</button><button type="button" className={buttonClass} disabled={busy} onClick={() => setConfirming(false)}>Not now</button></div></div>}<ul className="space-y-2">- {runs.map(run => <StageRun key={run.id} run={run} busy={busy}+ {runs.map(run => <StageRun key={run.id} run={run} busy={busy} resumeDisabled={disabled || busy || live}+ currentRevisionId={project.candidateRevisionId || project.acceptedRevisionId}onCancel={runId => act(async () => cancelCodeAnimationStageRun(project.id, runId, { silent: true }))}onResume={runId => start({ resumeFromRunId: runId })} />)}</ul>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 746ed5b082..798005220b 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -160,3 +160,5 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `staleBuildToast.jsx` | Sticky toast shown when server's build id differs from client's. || `apiRigging.js` | Character rigging. `getRiggingReadiness()` (`GET /rigging/readiness`): whether this install's Blender runtime is provisioned, the resolved interpreter, the module version, the install command when it is not, and the auto-skin threshold defaults. `rigImageTo3dModel(id, body)` (`POST /rigging/models/:id`): auto-skin a rendered mesh behind the measured weight-coverage gate, resolving with the updated model record. `listRiggingClips()` (`GET /rigging/clips`): the locally-held animation clip library plus CoS-state coverage. `retargetImageTo3dModel(id, body)` (`POST /rigging/models/:id/retarget`): apply a clip to a published rig in `diagnostic` (measure only) or `write` mode, resolving with the updated model record. || `apiAvatar.js` | Avatar surfaces. `getRiggedAvatars()` (`GET /avatar/rigged`): the install's verified animated records, each with its `?variant=` spelling, serving URL, retargeted clip name, and server-computed CoS-state coverage. |++Production Code Animation also exposes explicit stage start/cancel and upload/library sound staging through `apiCodeAnimation.js`.diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 98ccedefdb..ca2b558e4f 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -70,3 +70,6 @@ export const cancelCodeAnimationStageRun = (id, runId, options) => request(`/codexport const getCodeAnimationExecution = (options) => request('/code-animation/execution', options);export const updateCodeAnimationExecutionTools = (tools, options) => request('/code-animation/execution/tools', { method: 'PUT', body: JSON.stringify(tools), ...options });export const probeCodeAnimationExecution = (options) => request('/code-animation/execution/probe', { method: 'POST', ...options });++// Explicit production workflows. Preview and final use the stored soundtrack artifact.+export const stageCodeAnimationSoundAsset = (id, input, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/sound-assets`, { method: 'POST', body: JSON.stringify(input), ...options });diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.mdindex 437428dc86..69992479fd 100644--- a/docs/CODE_ANIMATION_PACKAGES.md+++ b/docs/CODE_ANIMATION_PACKAGES.md@@ -180,3 +180,49 @@ limits: it runs inside the shared managed Chromium (Chromium's renderer sandboxcontains page code, not a PortOS-owned process group), with per-commandtimeouts and render cancellation but no per-render memory cap. Its boundarytests are `server/services/htmlComposition/index.test.js`.+++## Offline Production sound++Production stage runs produce sound only after an explicit **Run production stages** / **Start run** action. Packages with intentional `silence` remain silent.+Legacy `procedural` notes and unstaged `external` declarations fail visibly;+they do not earn a successful soundtrack verdict. Fast HTML export keeps its+existing procedural/upload limitation notes.++Package v1 remains readable. Package v2 introduces audio contract version 1:++```json+{"kind":"procedural","version":1,"events":[+ {"label":"Impact","atSeconds":0.5,"effect":"impact","durationSeconds":0.2,"gain":0.8},+ {"label":"Reveal","atSeconds":1.25,"effect":"reveal","durationSeconds":0.4,"gain":0.6}+]}+```++Times are seconds, rounded to the nearest film frame and then the 48,000 Hz+sample grid. Impact/reveal effects produce deterministic 16-bit mono WAV bytes.+The timeline is bounded to 128 events, four seconds per event and 180 seconds+of total synthesis work. Event durations must fit the film. Preview plays the+persisted WAV used by final muxing; a live Web Audio clock is never captured.++Portable `file` audio is normalized to this same grid (trimmed or padded, without+looping). `POST /api/code-animation/projects/:id/sound-assets` accepts an explicit+`revisionId`, `source` (`upload` or `library`) and existing audio `filename`+basename. It copies validated asset bytes into a new immutable package candidate;+there are no host-path inputs. The portable package limits still apply (2 MiB+per file, 8 MiB total). Importing or staging never calls a provider.++Sound artifacts and measured evidence live in the existing project run records+and managed run directories. Package, source, timeline and audio hashes bind+that evidence to its immutable revision. Failed/canceled candidates leave+accepted source and earlier sound artifacts intact. A restart marks stranded+runs interrupted; resume is an explicit action and sound is rebuilt/remeasured.+The disk, time and render budgets cover offline audio as well as visual work.++Final MP4 sound must pass real ffprobe stream/duration checks and bounded PCM+decode measurements, including synthetic event placement. Listening quality+remains unverified. A `generated` declaration (package v2, `version: 1`, `prompt`)+is distinct from procedural/file sound: a stage request requires explicit+`audioConsent`, `audioProviderId`, `audioModel` and a separate positive+`audioBudgetUsd`. No provider audio adapter is available yet, so even consented+requests fail before provider dispatch; stage externally produced bytes as a+portable file instead. There are no startup audio calls or automatic resumes.diff --git a/server/lib/README.md b/server/lib/README.mdindex 9c006136fd..73cec6e010 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -825,3 +825,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoNarrativeEvents.js` | Named narrative event kinds, absolute onset/word/frame resolution and deterministic silence/reactive state for composition documents. || `persistentMindContextEvents.js` | `selectPersistentMindContextEvents`, `renderPersistentMindContextEvent` — retain useful conversation evidence without diagnostic ledger noise. |++| `codeAnimationSound.js` | Versioned frame/sample timelines, deterministic impact/reveal WAV synthesis and decoded event measurements. |diff --git a/server/lib/codeAnimationPackage.js b/server/lib/codeAnimationPackage.jsindex 47509e3ade..a970d2ad19 100644--- a/server/lib/codeAnimationPackage.js+++ b/server/lib/codeAnimationPackage.js@@ -53,9 +53,16 @@ export const codeAnimationManifestSchema = z.object({label: text(200), startSeconds: z.number().nonnegative(), endSeconds: z.number().positive(),}).strict()).max(128),events: z.array(z.object({ label: text(200), atSeconds: z.number().nonnegative() }).strict()).max(512),- audio: z.discriminatedUnion('kind', [+ audio: z.union([z.object({ kind: z.literal('silence') }).strict(),z.object({ kind: z.literal('procedural'), notes: text(1500) }).strict(),+ // Audio contract v1 ships in package v2; legacy package v1 remains readable.+ z.object({ kind: z.literal('procedural'), version: z.literal(1), events: z.array(z.object({+ label: text(200), atSeconds: z.number().nonnegative(),+ effect: z.enum(['impact', 'reveal']), durationSeconds: z.number().min(0.02).max(4),+ gain: z.number().min(0.01).max(1),+ }).strict()).min(1).max(128) }).strict(),+ z.object({ kind: z.literal('generated'), version: z.literal(1), prompt: text(4000) }).strict(),// External audio is a declaration only: it contains no install-local URL/id.z.object({ kind: z.literal('external'), notes: text(1500) }).strict(),z.object({ kind: z.literal('file'), path: pathSchema }).strict(),@@ -79,7 +86,7 @@ const revisionHashOf = ({ schemaVersion, manifest, files }) => digest(canonicalS}));const shapeSchema = z.object({- schemaVersion: z.literal(1),+ schemaVersion: z.union([z.literal(1), z.literal(2)]),manifest: codeAnimationManifestSchema,files: z.array(fileSchema).min(1).max(L.files),revisionHash: hashSchema,@@ -125,6 +132,20 @@ export const codeAnimationPackageSchema = shapeSchema.superRefine((pkg, ctx) =>issue(['manifest', 'audio', 'path'], 'Audio file is missing');}const duration = pkg.manifest.format.durationSeconds;+ const audio = pkg.manifest.audio;+ if (audio.version && pkg.schemaVersion !== 2) issue(['schemaVersion'], 'Versioned audio requires package v2');+ if (audio.kind === 'procedural' && audio.version === 1) {+ if (audio.events.reduce((sum, event) => sum + event.durationSeconds, 0) > 180) {+ issue(['manifest', 'audio', 'events'], 'Sound synthesis exceeds the bounded event workload');+ }+ const fps = pkg.manifest.format.fps;+ for (const [index, event] of audio.events.entries()) {+ const start = Math.round(event.atSeconds * fps) / fps;+ if (start + event.durationSeconds > Math.round(duration * fps) / fps + 1e-9) {+ issue(['manifest', 'audio', 'events', index], 'Sound event must fit within the film frame grid');+ }+ }+ }for (const [index, shot] of pkg.manifest.shots.entries()) {if (shot.endSeconds <= shot.startSeconds || shot.endSeconds > duration) {issue(['manifest', 'shots', index], 'Shot must have positive length within the film');@@ -139,7 +160,7 @@ export const codeAnimationPackageSchema = shapeSchema.superRefine((pkg, ctx) =>/** Build a package from explicit metadata and text/binary file bytes. */export function createCodeAnimationPackage(manifest, files) {const payload = {- schemaVersion: 1,+ schemaVersion: manifest.audio.version ? 2 : 1,manifest,files: files.map(({ path, content, encoding = 'utf8' }) => ({path, content, encoding, sha256: digest(Buffer.from(content, encoding === 'base64' ? 'base64' : 'utf8')),diff --git a/server/lib/codeAnimationProjects.js b/server/lib/codeAnimationProjects.jsindex 0dbb9ae1dc..f5d987b5aa 100644--- a/server/lib/codeAnimationProjects.js+++ b/server/lib/codeAnimationProjects.js@@ -44,4 +44,8 @@ export const codeAnimationStageRunSchema = z.object({resumeFromRunId: z.string().uuid().optional(),// Opt-in: ask the project's vision-capable authoring route to review the style frames.visualReview: z.boolean().optional(),+ audioConsent: z.boolean().default(false),+ audioProviderId: z.string().trim().min(1).max(128).optional(),+ audioModel: z.string().trim().min(1).max(256).optional(),+ audioBudgetUsd: z.number().positive().max(1000).optional(),}).strict().refine(value => !(value.revisionId && value.resumeFromRunId), 'Choose a revision or a run to resume, not both');diff --git a/server/lib/codeAnimationSound.js b/server/lib/codeAnimationSound.jsnew file mode 100644index 0000000000..699f26b40e--- /dev/null+++ b/server/lib/codeAnimationSound.js@@ -0,0 +1,63 @@+/** Bounded, deterministic offline sound; no browser clock or authored code execution. */+import { createHash } from 'crypto';+import { canonicalStringify } from './objects.js';+import { pcmToWavBuffer } from './chiptuneRender.js';++export const CODE_ANIMATION_SAMPLE_RATE = 48000;+export const soundHash = bytes => createHash('sha256').update(bytes).digest('hex');++/** Quantize seconds through whole film frames, then into a fixed PCM sample grid. */+export function soundTimeline(manifest) {+ const { fps, durationSeconds } = manifest.format;+ const frames = Math.round(durationSeconds * fps);+ const samples = Math.round(frames / fps * CODE_ANIMATION_SAMPLE_RATE);+ const events = manifest.audio.kind === 'procedural' && manifest.audio.version === 1+ ? manifest.audio.events.map(event => {+ const frame = Math.round(event.atSeconds * fps);+ const startSample = Math.round(frame / fps * CODE_ANIMATION_SAMPLE_RATE);+ return { ...event, frame, startSample, sampleCount: Math.round(event.durationSeconds * CODE_ANIMATION_SAMPLE_RATE) };+ }) : [];+ const timeline = { version: 1, sampleRate: CODE_ANIMATION_SAMPLE_RATE, fps, frames, samples, events };+ return { ...timeline, hash: soundHash(canonicalStringify({ timeline, audio: manifest.audio })) };+}++/** Original impact/reveal tones with fixed envelopes and pitch sweeps. */+export function synthesizeSoundtrack(timeline) {+ const pcm = new Float32Array(timeline.samples);+ for (const event of timeline.events) {+ for (let i = 0; i < event.sampleCount && event.startSample + i < pcm.length; i += 1) {+ const t = i / timeline.sampleRate;+ const duration = event.sampleCount / timeline.sampleRate;+ const attack = Math.min(0.005, duration / 4);+ const release = Math.min(0.03, duration / 4);+ const envelope = Math.min(1, t / attack, (duration - t) / release);+ const from = event.effect === 'impact' ? 160 : 300;+ const to = event.effect === 'impact' ? 45 : 900;+ const phase = from * t + (to - from) * t * t / (2 * duration);+ const decay = event.effect === 'impact' ? Math.exp(-t * 6 / duration) : 1;+ pcm[event.startSample + i] += 0.7 * event.gain * envelope * decay * Math.sin(2 * Math.PI * phase);+ }+ }+ for (let i = 0; i < pcm.length; i += 1) pcm[i] = Math.max(-1, Math.min(1, pcm[i]));+ return pcmToWavBuffer(pcm, { sampleRate: timeline.sampleRate });+}++/** Measure event windows in decoded mono s16 PCM (WAV or MP4 decode). */+export function measureSoundEvents(bytes, timeline) {+ return timeline.events.map(event => {+ let firstSample = null;+ let peak = 0;+ let squares = 0;+ const end = Math.min(bytes.length / 2, event.startSample + event.sampleCount);+ for (let i = Math.max(0, event.startSample - Math.round(0.05 * timeline.sampleRate)); i < end; i += 1) {+ const sample = bytes.readInt16LE(i * 2) / 32768;+ const magnitude = Math.abs(sample);+ if (firstSample === null && magnitude > 0.001) firstSample = i;+ peak = Math.max(peak, magnitude);+ squares += sample * sample;+ }+ return { label: event.label, frame: event.frame, startSample: event.startSample,+ firstSample, firstSeconds: firstSample === null ? null : firstSample / timeline.sampleRate,+ peak, rms: end > event.startSample ? Math.sqrt(squares / (end - event.startSample)) : 0 };+ });+}diff --git a/server/lib/index.js b/server/lib/index.jsindex e9c9b5e3df..70b7c5a3ac 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -810,3 +810,4 @@ export * from './musicVideoNarrativeEvents.js';export * from './persistentMindContextEvents.js';export * from './scheduleExecutionFieldsValidation.js';+export * from './codeAnimationSound.js';diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex 6235e2a2d9..fd0339590a 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -16,6 +16,7 @@*/import { Router } from 'express';+import { soundAssetSchema, stageProductionSoundAsset } from '../services/codeAnimation/soundAssets.js';import { preflightProductionProject } from '../services/codeAnimation/preflight.js';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -208,6 +209,10 @@ 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/sound-assets', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ res.status(201).json(await stageProductionSoundAsset(id, validateRequest(soundAssetSchema, 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);diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex c88ee323ba..a8395d0e46 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -239,7 +239,7 @@ describe('Code Animation portable packages', () => {});it.each([- ['unknown version', (v) => { v.schemaVersion = 2; }],+ ['unknown version', (v) => { v.schemaVersion = 3; }],['installation command', (v) => { v.manifest.renderer.command = 'example executable'; }],['case collision', (v) => { v.files.push({ ...v.files[0], path: 'SRC/scene.py' }); }],['duplicate path', (v) => { v.files.push({ ...v.files[0] }); }],diff --git a/server/services/codeAnimation/evidence.js b/server/services/codeAnimation/evidence.jsindex 768bd825c2..4be47e748f 100644--- a/server/services/codeAnimation/evidence.js+++ b/server/services/codeAnimation/evidence.js@@ -44,6 +44,7 @@ export function analyzeEvidence({ manifest, pilot, contract, review = null }) {if (Math.abs(contract.durationSec - durationSeconds) > 1 / fps + 1e-9) {add('duration-mismatch', 'error', `The film declares ${contract.durationSec}s but the brief asks for ${durationSeconds}s.`, { measured: { declared: contract.durationSec, expected: durationSeconds } });}+ if (contract.fps !== fps) add('frame-rate-mismatch', 'error', `The film renders ${contract.fps}fps but the sound timeline uses ${fps}fps.`, { measured: { declared: contract.fps, expected: fps } });if (contract.width !== width || contract.height !== height) {add('frame-size-mismatch', 'error', `The film renders ${contract.width}x${contract.height} but the brief asks for ${width}x${height}.`, { measured: { declared: `${contract.width}x${contract.height}`, expected: `${width}x${height}` } });}@@ -89,9 +90,9 @@ export function analyzeEvidence({ manifest, pilot, contract, review = null }) {* source), missing evidence and any error finding never pass; unverified* dimensions are listed, never counted as verified.*/-export function evaluateVerdict({ evidence, sourceHash, findings, unverified }) {+export function evaluateVerdict({ evidence, sourceHash, packageHash, findings, unverified }) {if (!evidence || !evidence.sourceHash) return { status: 'unverified', reason: 'No evidence was captured.', unverified };- if (evidence.sourceHash !== sourceHash) return { status: 'stale', reason: 'The evidence was captured against a different source revision.', unverified };+ if ((packageHash && evidence.packageHash !== packageHash) || evidence.sourceHash !== sourceHash) return { status: 'stale', reason: 'The evidence was captured against a different source revision.', unverified };if (findings.some(finding => finding.severity === 'error')) return { status: 'fail', reason: 'Measured errors remain.', unverified };return { status: 'pass', reason: null, unverified };}diff --git a/server/services/codeAnimation/evidence.test.js b/server/services/codeAnimation/evidence.test.jsindex f0977f6344..c6ba7fd72b 100644--- a/server/services/codeAnimation/evidence.test.js+++ b/server/services/codeAnimation/evidence.test.js@@ -20,6 +20,11 @@ describe('production evidence analysis', () => {.toEqual(['error:duration-mismatch', 'error:frame-size-mismatch']);});+ it('rejects a renderer using a different frame grid than the sound timeline', () => {+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b']) }, contract: { ...contract, fps: 24 } })))+ .toEqual(['error:frame-rate-mismatch']);+ });+it('flags a declared event with no visible change, and keeps unmeasured dimensions unverified', () => {const withEvent = manifest({ events: [{ label: 'Hop', atSeconds: 1.5 }], audio: { kind: 'external', notes: 'x' } });const result = analyzeEvidence({ manifest: withEvent, pilot: { samples: samples(['a', 'b', 'c', 'c', 'c', 'f']).map(sample => ({ ...sample, t: sample.t / 2 })) }, contract });diff --git a/server/services/codeAnimation/preflight.js b/server/services/codeAnimation/preflight.jsindex 9916ca4a98..9a665839a9 100644--- a/server/services/codeAnimation/preflight.js+++ b/server/services/codeAnimation/preflight.js@@ -49,7 +49,7 @@ export async function preflightProductionProject(id) {const result = { requested, resolved: null, effective: null, executed: false, problems,substitution: substitutionOf(requested), allowFallback: substitutionOf(requested) === 'allowed',capabilities: { packageImportExport: true, authoringDispatch: false, renderTools: false, imageInspection: false, research: false },- notes: ['Settings preview only. Authoring, rendering, visual inspection and research adapters are not connected; use package export/import.'],+ notes: ['This checks saved authoring settings only. Explicit production stages measure rendering, motion and sound; visual review and research remain unverified.'],};if (!requested.providerId) {problems.push('Select an authoring provider explicitly.');diff --git a/server/services/codeAnimation/projectFiles.js b/server/services/codeAnimation/projectFiles.jsindex 6dd07ebefa..3f2e73f28c 100644--- a/server/services/codeAnimation/projectFiles.js+++ b/server/services/codeAnimation/projectFiles.js@@ -149,3 +149,17 @@ export async function stageRenderSource(projectId, runId, revisionId, files, ent}return { directory: `code-animations/projects/${projectId}/runs/${runId}/render/${revisionId}` };}++/** Read a known sound artifact with the same directory/no-follow/hash guard as source. */+export async function readRunArtifact(projectId, runId, name, sha256) {+ if (!/^sound-[a-f0-9-]+\.wav$/.test(name)) throw unsafe();+ const dir = await runDirectory(projectId, runId, ['artifacts'], { create: false });+ const handle = await open(join(dir, name), constants.O_RDONLY | (constants.O_NOFOLLOW || 0));+ try {+ const info = await handle.stat();+ if (!info.isFile() || info.size > 44 + 180 * 48000 * 2) throw unsafe();+ const bytes = await handle.readFile();+ if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw unsafe();+ return bytes;+ } finally { await handle.close(); }+}diff --git a/server/services/codeAnimation/sound.db.test.js b/server/services/codeAnimation/sound.db.test.jsnew file mode 100644index 0000000000..58f06f5fdb--- /dev/null+++ b/server/services/codeAnimation/sound.db.test.js@@ -0,0 +1,168 @@+/** Public workflows pin revision/audio binding, restart/cancel and provider consent. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { mkdir, readFile, 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 original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-sound-') }));+vi.mock('../../lib/fileUtils.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('animation-sound-') }));+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));+vi.mock('./stageRender.js', () => ({+ sampleFilm: vi.fn(async (_, { times, captureTimes = [], signal }) => {+ signal.throwIfAborted();+ return { contract: { durationSec: 2, fps: 12, width: 1280, height: 720 },+ samples: times.map(t => ({ t, renderHash: String(t), mean: 80, deviation: 20 })),+ frames: captureTimes.map(t => ({ t, bytes: Buffer.from('png') })) };+ }),+ renderViaMediaQueue: vi.fn(async ({ signal }) => { signal.throwIfAborted(); throw new Error('Synthetic render failure'); }),+}));+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 { soundTimeline, synthesizeSoundtrack } from '../../lib/codeAnimationSound.js';+import { evaluateVerdict } from './evidence.js';+import { sampleFilm, renderViaMediaQueue } from './stageRender.js';+import { activeStageRunIds } from './stages.js';+import { muxSoundtrack } from './sound.js';+import { emitCodeAnimationChanged } from '../socket.js';+import routes from '../../routes/codeAnimation.js';++const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('codeAnimation/sound.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 audio = { kind: 'procedural', version: 1, events: [+ { label: 'Impact', atSeconds: 0.5, effect: 'impact', durationSeconds: 0.2, gain: 0.8 },+ { label: 'Reveal', atSeconds: 1.25, effect: 'reveal', durationSeconds: 0.4, gain: 0.6 },+] };+const manifest = (sound = audio) => ({+ 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: sound,+ execution: { requested: null, effective: null },+});+const packageOf = (sound = audio) => createCodeAnimationPackage(manifest(sound), [{ path: 'index.html', content: '<html><canvas></canvas></html>' }]);+async function create(sound = audio, budgets = {}) {+ const response = await post('/projects', { manifest: manifest(sound), budgets });+ expect(response.status).toBe(201); ids.push(response.body.id);+ const imported = await post(`/projects/${response.body.id}/import`, packageOf(sound));+ expect(imported.status).toBe(201);+ return { project: response.body, revision: imported.body.revision };+}+// Wait for the persisted terminal event, never a fixed-duration polling retry.+async function terminal(id, start) {+ let resolve;+ const done = new Promise(r => { resolve = r; });+ emitCodeAnimationChanged.mockImplementation(projectId => {+ if (projectId === id && !activeStageRunIds().length) resolve();+ });+ const response = await start();+ expect(response.status).toBe(202);+ await done;+ emitCodeAnimationChanged.mockReset();+ return (await get(`/projects/${id}/history`)).body.items.find(run => run.id === response.body.id);+}++describe.skipIf(!ready)('Revision-bound sound public workflows', () => {+ it('keeps v1 packages compatible and validates versioned sound timelines at the public import boundary', async () => {+ expect((await post('/packages/validate', packageOf({ kind: 'silence' }))).body.schemaVersion).toBe(1);+ const versioned = packageOf();+ expect((await post('/packages/validate', versioned)).body.schemaVersion).toBe(2);+ expect((await post('/packages/validate', { ...versioned, schemaVersion: 1 })).status).toBe(400);+ const outside = structuredClone(versioned);+ outside.manifest.audio.events[0].atSeconds = 2;+ expect((await post('/packages/validate', outside)).status).toBe(400);+ });++ it('persists deterministic audio despite render failure, and rejects stale event/revision evidence with identical source bytes', async () => {+ const { project, revision } = await create();+ await post(`/projects/${project.id}/accept`, { revisionId: revision.id });+ const run = await terminal(project.id, () => post(`/projects/${project.id}/stage-runs`, {}));+ expect(run.status).toBe('failed');+ expect(run.data.output).toBeNull();+ const sound = run.data.soundtrack;+ const wav = await readFile(join(PATHS.data, sound.artifact.relativePath));+ expect(wav.equals(synthesizeSoundtrack(soundTimeline(revision.manifest)))).toBe(true);+ expect(run.data.reservedBytes).toBeGreaterThan(wav.length);+ const changed = { ...audio, events: audio.events.map(event => ({ ...event, atSeconds: event.atSeconds + 0.1 })) };+ const imported = await post(`/projects/${project.id}/import`, packageOf(changed));+ const next = imported.body.revision;+ expect(next.sourceHash).toBe(revision.sourceHash);+ expect(next.packageHash).not.toBe(revision.packageHash);+ expect(soundTimeline(next.manifest).hash).not.toBe(sound.timelineHash);+ expect(evaluateVerdict({ evidence: run.data.stages.find(stage => stage.key === 'inspect').evidence,+ sourceHash: next.sourceHash, packageHash: next.packageHash, findings: [], unverified: [] }).status).toBe('stale');+ await expect(muxSoundtrack({ projectId: project.id, revision: next, soundtrack: sound, result: {}, signal: new AbortController().signal }))+ .rejects.toMatchObject({ code: 'CODE_ANIMATION_SOUND_STALE' });+ expect((await get(`/projects/${project.id}`)).body.acceptedRevisionId).toBe(revision.id);+ expect(await readFile(join(PATHS.data, sound.artifact.relativePath))).toEqual(wav);+ });++ it('stages upload/library bytes through portable candidates, then normalizes both without live path references', async () => {+ const { project, revision } = await create();+ const wav = synthesizeSoundtrack(soundTimeline(revision.manifest));+ for (const source of ['upload', 'library']) {+ const root = source === 'upload' ? PATHS.uploads : PATHS.music;+ await mkdir(root, { recursive: true }); await writeFile(join(root, 'example.wav'), wav);+ const response = await post(`/projects/${project.id}/sound-assets`, { revisionId: revision.id, source, filename: 'example.wav' });+ expect(response.status).toBe(201);+ const exported = (await get(`/projects/${project.id}/revisions/${response.body.revision.id}/package`)).body;+ expect(exported.manifest.audio).toEqual({ kind: 'file', path: 'audio/soundtrack.wav' });+ // Once staged, the original is irrelevant to offline production.+ await writeFile(join(root, 'example.wav'), 'replaced');+ const run = await terminal(project.id, () => post(`/projects/${project.id}/stage-runs`, {}));+ expect(run.data.soundtrack).toMatchObject({ kind: 'file', measured: { durationMs: 2000, frames: 96000 } });+ }+ expect((await post(`/projects/${project.id}/sound-assets`, { revisionId: revision.id, source: 'upload', filename: '/private/example.wav' })).status).toBe(400);+ });++ it('requires new explicit consent and an independent audio budget; refuses unsupported declarations before any provider call', async () => {+ const { project } = await create({ kind: 'generated', version: 1, prompt: 'Original reveal score' });+ expect((await post(`/projects/${project.id}/stage-runs`, {})).body.code).toBe('CODE_ANIMATION_AUDIO_CONSENT_REQUIRED');+ expect((await post(`/projects/${project.id}/stage-runs`, { audioConsent: true, audioProviderId: 'example', audioModel: 'example-model', audioBudgetUsd: 1 })).body.code).toBe('CODE_ANIMATION_AUDIO_PROVIDER_UNSUPPORTED');+ expect((await get(`/projects/${project.id}/history`)).body.items.filter(run => run.data.kind === 'production-stages')).toEqual([]);+ const legacy = await create({ kind: 'procedural', notes: 'Web Audio' });+ const run = await terminal(legacy.project.id, () => post(`/projects/${legacy.project.id}/stage-runs`, {}));+ expect(run).toMatchObject({ status: 'failed', data: { soundtrack: null, output: null, error: { code: 'CODE_ANIMATION_SOUND_UNSUPPORTED' } } });+ });++ it('keeps accepted work on audio budget exhaustion and cancellation, and restart never resumes sound automatically', async () => {+ const { project, revision } = await create(audio, { diskBytes: 10000 });+ await post(`/projects/${project.id}/accept`, { revisionId: revision.id });+ const exhausted = await terminal(project.id, () => post(`/projects/${project.id}/stage-runs`, {}));+ expect(exhausted).toMatchObject({ status: 'exhausted', data: { stopReason: 'disk', output: null } });+ expect((await get(`/projects/${project.id}`)).body.acceptedRevisionId).toBe(revision.id);+ const normal = await create();+ let rendering;+ const renderingStarted = new Promise(resolve => { rendering = resolve; });+ renderViaMediaQueue.mockImplementationOnce(async ({ signal }) => {+ rendering(); await new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));+ });+ const done = terminal(normal.project.id, () => post(`/projects/${normal.project.id}/stage-runs`, {}));+ await renderingStarted;+ const live = (await get(`/projects/${normal.project.id}/history`)).body.items.find(run => run.status === 'running');+ expect((await post(`/projects/${normal.project.id}/stage-runs/${live.id}/cancel`, {})).status).toBe(200);+ const canceled = await done;+ expect(canceled.status).toBe('canceled');+ const persisted = await readFile(join(PATHS.data, canceled.data.soundtrack.artifact.relativePath));+ const strandedId = randomUUID();+ await query("INSERT INTO code_animation_project_runs (id, project_id, revision_id, status, data) VALUES ($1,$2,$3,'running',$4)",+ [strandedId, normal.project.id, normal.revision.id, { kind: 'production-stages', soundtrack: canceled.data.soundtrack }]);+ sampleFilm.mockClear(); renderViaMediaQueue.mockClear();+ const history = (await get(`/projects/${normal.project.id}/history`)).body.items;+ expect(history.find(run => run.id === strandedId).status).toBe('interrupted');+ expect(sampleFilm).not.toHaveBeenCalled(); expect(renderViaMediaQueue).not.toHaveBeenCalled();+ expect(await readFile(join(PATHS.data, canceled.data.soundtrack.artifact.relativePath))).toEqual(persisted);+ }, 30000);+});diff --git a/server/services/codeAnimation/sound.js b/server/services/codeAnimation/sound.jsnew file mode 100644index 0000000000..5e5d13cfda--- /dev/null+++ b/server/services/codeAnimation/sound.js@@ -0,0 +1,125 @@+/** Revision-bound offline soundtrack artifacts and measured final mux evidence. */+import { createReadStream } from 'fs';+import { stat } from 'fs/promises';+import { createHash } from 'crypto';+import { canonicalStringify } from '../../lib/objects.js';+import { promisify } from 'util';+import { extname, join } from 'path';+import { execFile } from '../../lib/childProcess.js';+import { ServerError } from '../../lib/errorHandler.js';+import { findFfmpeg, findFfprobe, safeUnder } from '../../lib/ffmpeg.js';+import { PATHS } from '../../lib/paths.js';+import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';+import { measureWavAudio } from '../../lib/wavAudioFile.js';+import { CODE_ANIMATION_SAMPLE_RATE, measureSoundEvents, soundHash, soundTimeline, synthesizeSoundtrack } from '../../lib/codeAnimationSound.js';+import { muxVoLines } from '../pipeline/audioMux.js';+import { readRunArtifact, writeRunArtifact } from './projectFiles.js';++const exec = promisify(execFile);+const fail = (message, code = 'CODE_ANIMATION_SOUND_UNVERIFIED') => new ServerError(message, { status: 409, code });+const DEMUXERS = { '.wav': 'wav', '.mp3': 'mp3', '.m4a': 'mov', '.ogg': 'ogg', '.flac': 'flac', '.aac': 'aac' };++async function decode(path, timeline, signal, { demuxer, pad = false } = {}) {+ const bin = await findFfmpeg();+ if (!bin) throw fail('ffmpeg is required to measure and produce a soundtrack');+ signal.throwIfAborted();+ const { stdout } = await exec(bin, ['-v', 'error', '-nostdin', '-protocol_whitelist', 'file,pipe',+ ...(demuxer ? ['-f', demuxer] : []), '-i', path, '-map', '0:a:0',+ ...(pad ? ['-af', 'apad'] : []), '-t', String(timeline.samples / timeline.sampleRate + (pad ? 0 : 0.1)),+ '-ar', String(timeline.sampleRate), '-ac', '1', '-f', 's16le', 'pipe:1'],+ { encoding: 'buffer', maxBuffer: (timeline.samples + timeline.sampleRate) * 2, timeout: 30000, signal });+ signal.throwIfAborted();+ return stdout;+}++/** No provider adapter is implied by a declaration; fail before any possible call. */+export function checkSoundConsent(audio, request) {+ if (audio.kind !== 'generated') return;+ if (!request.audioConsent || !request.audioProviderId || !request.audioModel || !(request.audioBudgetUsd > 0)) {+ throw fail('Generated audio needs explicit consent, provider/model selection and a separate positive audio budget', 'CODE_ANIMATION_AUDIO_CONSENT_REQUIRED');+ }+ throw fail('Provider-generated sound has no offline adapter yet. Stage provider output as a portable audio file.', 'CODE_ANIMATION_AUDIO_PROVIDER_UNSUPPORTED');+}++export async function produceSoundtrack({ projectId, runId, revision, signal, reserve }) {+ const { audio } = revision.manifest;+ const timeline = soundTimeline(revision.manifest);+ const binding = { revisionId: revision.id, sourceHash: revision.sourceHash, packageHash: revision.packageHash, timelineHash: timeline.hash };+ if (audio.kind === 'silence') return { ...binding, version: 1, kind: 'silence', intentional: true, timeline,+ verified: ['intentional-silence'], unverified: [] };+ if (audio.kind !== 'file' && !(audio.kind === 'procedural' && audio.version === 1)) {+ throw fail('Authored sound has no supported offline timeline or staged audio file; the film was not declared silent.', 'CODE_ANIMATION_SOUND_UNSUPPORTED');+ }+ signal.throwIfAborted();+ await reserve(44 + timeline.samples * 2);+ let wav;+ if (audio.kind === 'procedural') wav = synthesizeSoundtrack(timeline);+ else {+ const demuxer = DEMUXERS[extname(audio.path).toLowerCase()];+ if (!demuxer) throw fail('Unsupported staged audio format', 'CODE_ANIMATION_SOUND_UNSUPPORTED');+ // Revision bytes have just been integrity checked and snapshotted; only a+ // portable asset inside that copy is decoded, never a host path from a request.+ const pcm = await decode(join(PATHS.data, revision.staged, audio.path), timeline, signal, { demuxer, pad: true });+ if (pcm.length !== timeline.samples * 2) throw fail('Staged audio could not fill the film sample grid');+ const samples = new Float32Array(timeline.samples);+ for (let i = 0; i < samples.length; i += 1) samples[i] = pcm.readInt16LE(i * 2) / 32768;+ wav = pcmToWavBuffer(samples, { sampleRate: CODE_ANIMATION_SAMPLE_RATE });+ }+ signal.throwIfAborted();+ const measured = measureWavAudio(wav);+ const events = measureSoundEvents(wav.subarray(44), timeline);+ if (!measured || measured.nonFinite || measured.frames !== timeline.samples || measured.rms === 0 || events.some(event => event.firstSample === null)) {+ throw fail('Soundtrack samples did not contain the authored sound');+ }+ const name = `sound-${revision.id}.wav`;+ const artifact = await writeRunArtifact(projectId, runId, name, wav);+ signal.throwIfAborted();+ const evidenceHash = soundHash(canonicalStringify({ ...binding, audioHash: artifact.sha256, measured, events }));+ return { ...binding, evidenceHash, version: 1, kind: audio.kind, timeline, artifact: { ...artifact, runId, name }, measured, events,+ verified: ['audio-duration', ...(events.length ? ['audio-event-placement'] : [])],+ unverified: [{ dimension: 'hearing', reason: 'Decoded samples measure placement and duration; listening quality has no reviewer.' }] };+}++export async function muxSoundtrack({ projectId, revision, soundtrack, result, signal, reserve }) {+ if (soundtrack.packageHash !== revision.packageHash || soundtrack.revisionId !== revision.id+ || soundtrack.timelineHash !== soundTimeline(revision.manifest).hash) throw fail('Sound evidence belongs to another revision', 'CODE_ANIMATION_SOUND_STALE');+ if (soundtrack.kind === 'silence') return { intentional: true, verified: ['intentional-silence'] };+ const { artifact, timeline } = soundtrack;+ const bytes = await readRunArtifact(projectId, artifact.runId, artifact.name, artifact.sha256);+ const audioPath = join(PATHS.data, artifact.relativePath);+ const videoPath = safeUnder(PATHS.videos, result.filename);+ if (!videoPath) throw fail('The render did not return a managed video');+ signal.throwIfAborted();+ // Account for the newly rendered candidate and the second-pass mux scratch.+ if (reserve) await reserve((await stat(videoPath)).size * 2 + soundtrack.artifact.bytes);+ const mux = await muxVoLines(videoPath, { voLines: [{ path: audioPath, offsetSec: 0 }], signal });+ if (!mux.ok) throw fail(`Soundtrack mux failed: ${mux.reason}`);+ signal.throwIfAborted();+ const probe = await findFfprobe();+ if (!probe) throw fail('ffprobe is required to verify the muxed soundtrack');+ const { stdout } = await exec(probe, ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name,sample_rate,channels,duration', '-of', 'json', videoPath],+ { timeout: 10000, maxBuffer: 65536, signal });+ const stream = JSON.parse(stdout).streams?.[0];+ const duration = Number(stream?.duration);+ const expected = timeline.samples / timeline.sampleRate;+ if (!stream || !Number.isFinite(duration) || Math.abs(duration - expected) > 0.06) throw fail('Muxed audio stream duration did not match the film');+ const decoded = await decode(videoPath, timeline, signal);+ if (Math.abs(decoded.length / 2 / timeline.sampleRate - expected) > 0.06) throw fail('Decoded mux duration did not match the film');+ const events = measureSoundEvents(decoded, timeline);+ const reference = measureSoundEvents(bytes.subarray(44), timeline);+ if (events.some((event, index) => event.firstSample === null || Math.abs(event.firstSeconds - reference[index].firstSeconds) > 0.02)) {+ throw fail('Decoded mux did not preserve authored event placement');+ }+ // Also reject a silent decode for file audio, which has no synthetic events.+ let peak = 0;+ for (let i = 0; i < decoded.length; i += 2) peak = Math.max(peak, Math.abs(decoded.readInt16LE(i)) / 32768);+ if (!peak) throw fail('Muxed audio decoded to silence');+ const videoDigest = createHash('sha256');+ for await (const chunk of createReadStream(videoPath, { signal })) videoDigest.update(chunk);+ signal.throwIfAborted();+ const videoHash = videoDigest.digest('hex');+ return { version: 1, videoHash, evidenceHash: soundHash(canonicalStringify({ packageHash: revision.packageHash, audioHash: artifact.sha256, videoHash, decodedHash: soundHash(decoded) })), revisionId: revision.id, packageHash: revision.packageHash, audioHash: soundHash(bytes),+ timelineHash: timeline.hash, stream, decodedSamples: decoded.length / 2, decodedDurationSeconds: decoded.length / 2 / timeline.sampleRate,+ decodedHash: soundHash(decoded), peak, events, verified: ['audio-stream', 'audio-duration', ...(events.length ? ['audio-event-placement'] : [])],+ unverified: soundtrack.unverified };+}diff --git a/server/services/codeAnimation/soundAssets.js b/server/services/codeAnimation/soundAssets.jsnew file mode 100644index 0000000000..5604925bf3--- /dev/null+++ b/server/services/codeAnimation/soundAssets.js@@ -0,0 +1,48 @@+/** Copy validated upload/library bytes into a new portable source candidate. */+import { constants } from 'fs';+import { open } from 'fs/promises';+import { extname } from 'path';+import { z } from 'zod';+import { PATHS } from '../../lib/paths.js';+import { makePathResolver } from '../../lib/pathSafety.js';+import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';+import { createCodeAnimationPackage, CODE_ANIMATION_PACKAGE_LIMITS } from '../../lib/codeAnimationPackage.js';+import { validateRequest } from '../../lib/validation.js';+import { ServerError } from '../../lib/errorHandler.js';+import { SUPPORTED_AUDIO_EXTENSIONS, statMusicTrack } from '../pipeline/musicLibrary.js';+import { exportProductionPackage, importProductionPackage } from './projects.js';++export const soundAssetSchema = z.object({+ revisionId: z.string().uuid(), source: z.enum(['upload', 'library']),+ filename: z.string().min(1).max(256).regex(/^[^/\\]+$/),+}).strict();+const upload = makePathResolver(() => PATHS.uploads, { extensions: UPLOAD_AUDIO_EXTENSIONS });+const library = makePathResolver(() => PATHS.music, { extensions: SUPPORTED_AUDIO_EXTENSIONS });++export async function stageProductionSoundAsset(projectId, input) {+ const request = validateRequest(soundAssetSchema, input);+ const pkg = await exportProductionPackage(projectId, request.revisionId);+ if (request.source === 'library' && !await statMusicTrack(request.filename)) {+ throw new ServerError('Library sound is missing', { status: 404, code: 'AUDIO_NOT_FOUND' });+ }+ const path = (request.source === 'upload' ? upload : library)(request.filename);+ if (!path) throw new ServerError('Sound asset is missing or unsupported', { status: 404, code: 'AUDIO_NOT_FOUND' });+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));+ let bytes;+ try {+ const info = await handle.stat();+ if (!info.isFile() || info.size > CODE_ANIMATION_PACKAGE_LIMITS.fileBytes) {+ throw new ServerError('Sound asset exceeds the portable package file limit', { status: 400, code: 'CODE_ANIMATION_AUDIO_SIZE' });+ }+ // Read at most the package limit even if another upload grows the file.+ bytes = Buffer.alloc(info.size);+ const read = await handle.read(bytes, 0, bytes.length, 0);+ if (read.bytesRead !== bytes.length) throw new ServerError('Sound asset changed while staging', { status: 409, code: 'CODE_ANIMATION_AUDIO_CHANGED' });+ } finally { await handle.close(); }+ const target = `audio/soundtrack${extname(request.filename).toLowerCase()}`;+ const files = pkg.files.filter(file => file.path !== target);+ files.push({ path: target, content: bytes.toString('base64'), encoding: 'base64' });+ return importProductionPackage(projectId, createCodeAnimationPackage({ ...pkg.manifest,+ audio: { kind: 'file', path: target }, assets: [...new Set([...pkg.manifest.assets, target])],+ }, files));+}diff --git a/server/services/codeAnimation/stages.db.test.js b/server/services/codeAnimation/stages.db.test.jsindex 6045c12d14..be4bb8d4ad 100644--- a/server/services/codeAnimation/stages.db.test.js+++ b/server/services/codeAnimation/stages.db.test.js@@ -72,7 +72,7 @@ describe.skipIf(!ready)('Production stage runs', () => {expect(saved).toMatchObject({ id: run.id, status: 'completed' });const data = saved.data;expect(data.stages.map(stage => `${stage.key}:${stage.revisionId === revision.id ? 'v1' : 'v2'}`))- .toEqual(['style-frame:v1', 'pilot:v1', 'inspect:v1', 'repair:v1', 'style-frame:v2', 'pilot:v2', 'inspect:v2', 'final:v2']);+ .toEqual(['style-frame:v1', 'pilot:v1', 'inspect:v1', 'repair:v1', 'style-frame:v2', 'pilot:v2', 'inspect:v2', 'soundtrack:v2', 'final:v2']);expect(new Set(data.stages.map(stage => stage.stageRunId)).size).toBe(data.stages.length);const [first, second] = data.stages.filter(stage => stage.key === 'inspect');expect(first.findings.some(finding => finding.kind === 'frozen-film' && finding.sourceHash === revision.sourceHash && finding.capturedAt)).toBe(true);@@ -92,7 +92,7 @@ describe.skipIf(!ready)('Production stage runs', () => {// Render only after passing evidence, from this run's own copy of the repaired revision.expect(render).toHaveBeenCalledTimes(1);expect(render.mock.calls[0][0].directory).toContain(`/runs/${run.id}/render/${current.candidateRevisionId}`);- expect(data.output).toMatchObject({ jobId: 'media-job', revisionId: current.candidateRevisionId, verifiedDimensions: expect.arrayContaining(['visual-motion', 'audio']) });+ expect(data.output).toMatchObject({ jobId: 'media-job', revisionId: current.candidateRevisionId, verifiedDimensions: expect.arrayContaining(['visual-motion', 'intentional-silence']) });expect(data.spent).toMatchObject({ iterations: 1, tokens: 100 });for (const artifact of data.stages.find(stage => stage.key === 'style-frame').artifacts) {expect(await exists(join(PATHS.data, artifact.relativePath))).toBe(true);diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.jsindex 533a2a7440..a0dfbde0e0 100644--- a/server/services/codeAnimation/stages.js+++ b/server/services/codeAnimation/stages.js@@ -23,6 +23,7 @@ import { analyzeEvidence, evaluateVerdict } from './evidence.js';import { buildExportShim, injectExportShim } from './export.js';import * as store from './projectStore.js';import { readProjectFiles, sourceHashOf, stageProjectFiles, stageRenderSource, writeRunArtifact } from './projectFiles.js';+import { checkSoundConsent, produceSoundtrack, muxSoundtrack } from './sound.js';import { renderViaMediaQueue, sampleFilm } from './stageRender.js';export const STAGE_RUN_KIND = 'production-stages';@@ -88,6 +89,7 @@ function checkBudget(ctx) {async function reserve(ctx, bytes) {if (!await store.reserveRunBytes(ctx.runId, ctx.projectId, bytes)) throw exhausted('disk');ctx.state.spent.diskBytes += bytes;+ ctx.state.reservedBytes += bytes;}/**@@ -96,7 +98,7 @@ async function reserve(ctx, bytes) {*/async function runStage(ctx, key, revision, body, { renders = false } = {}) {checkBudget(ctx);- const entry = { key, stageRunId: randomUUID(), revisionId: revision.id, sourceHash: revision.sourceHash, status: 'running', startedAt: iso() };+ const entry = { key, stageRunId: randomUUID(), revisionId: revision.id, sourceHash: revision.sourceHash, packageHash: revision.packageHash, status: 'running', startedAt: iso() };ctx.state.stages.push(entry);await persist(ctx);const { ms, dimension } = remainingMs(ctx);@@ -119,7 +121,7 @@ async function runStage(ctx, key, revision, body, { renders = false } = {}) {}const reusable = (ctx, key, revision) => ctx.prior.find(stage => stage.key === key && stage.revisionId === revision.id- && stage.sourceHash === revision.sourceHash && stage.status === 'completed');+ && stage.sourceHash === revision.sourceHash && stage.packageHash === revision.packageHash && stage.status === 'completed');/** Build the immutable, staged browser copy of a revision once per run. */async function stageRevision(ctx, revision) {@@ -230,7 +232,7 @@ async function reviewStage(ctx, revision, style) {function inspectStage(ctx, revision, style, pilot, review = null) {return runStage(ctx, 'inspect', revision, async () => {// Each piece of evidence names the source it measured; a mismatch is stale.- const evidence = { sourceHash: style.sourceHash === pilot.sourceHash ? style.sourceHash : null, styleStageRunId: style.stageRunId, pilotStageRunId: pilot.stageRunId };+ const evidence = { packageHash: revision.packageHash, sourceHash: style.sourceHash === pilot.sourceHash ? style.sourceHash : null, styleStageRunId: style.stageRunId, pilotStageRunId: pilot.stageRunId };let analysis;if (style.filmError) {analysis = { findings: [{ kind: 'film-error', severity: 'error', detail: `The film did not run: ${style.filmError}`, measured: { error: style.filmError } }], verified: [], unverified: [{ dimension: 'visual-motion', reason: 'The film did not render.' }] };@@ -246,7 +248,7 @@ function inspectStage(ctx, revision, style, pilot, review = null) {const capturedAt = iso();const advisory = (review?.reviewFindings || []).map(item => ({ kind: 'visual-review', severity: 'warning', detail: item.detail, atSeconds: item.atSeconds, measured: { reviewer: review.reviewer } }));const findings = [...analysis.findings, ...advisory].map(finding => ({ ...finding, sourceHash: revision.sourceHash, revisionId: revision.id, evidenceStageRunIds: [style.stageRunId, pilot.stageRunId], capturedAt }));- const verdict = evaluateVerdict({ evidence, sourceHash: revision.sourceHash, findings, unverified: analysis.unverified });+ const verdict = evaluateVerdict({ evidence, packageHash: revision.packageHash, sourceHash: revision.sourceHash, findings, unverified: analysis.unverified });return { evidence, findings, verified: analysis.verified, verdict };});}@@ -324,15 +326,17 @@ async function repairStage(ctx, revision, findings) {return created;}-async function finalStage(ctx, revision, verdictStage) {+async function finalStage(ctx, revision, verdictStage, soundtrack) {// Re-evaluate against the revision about to render: stale or failed evidence never reaches the renderer.- const verdict = evaluateVerdict({ evidence: verdictStage.evidence, sourceHash: revision.sourceHash, findings: verdictStage.findings, unverified: verdictStage.verdict.unverified });+ const verdict = evaluateVerdict({ evidence: verdictStage.evidence, packageHash: revision.packageHash, sourceHash: revision.sourceHash, findings: verdictStage.findings, unverified: verdictStage.verdict.unverified });if (verdict.status !== 'pass') throw new ServerError(`The final render needs passing evidence (${verdict.status})`, { status: 409, code: 'CODE_ANIMATION_EVIDENCE_NOT_PASSING' });const stage = await runStage(ctx, 'final', revision, async ({ signal }) => {const result = await ctx.deps.render({ directory: revision.staged, signal });- return { output: { jobId: result.jobId ?? null, videoId: result.id ?? null, filename: result.filename ?? null, path: result.path ?? null, revisionId: revision.id, sourceHash: revision.sourceHash } };+ signal.throwIfAborted();+ const audioEvidence = await ctx.deps.mux({ projectId: ctx.projectId, revision, soundtrack, result, signal, reserve: bytes => reserve(ctx, bytes) });+ return { audioEvidence, output: { packageHash: revision.packageHash, audioHash: soundtrack.artifact?.sha256 ?? null, jobId: result.jobId ?? null, videoId: result.id ?? null, filename: result.filename ?? null, path: result.path ?? null, revisionId: revision.id, sourceHash: revision.sourceHash } };}, { renders: true });- ctx.state.output = { ...stage.output, stageRunId: stage.stageRunId, verifiedDimensions: verdictStage.verified, unverified: verdict.unverified };+ ctx.state.output = { ...stage.output, stageRunId: stage.stageRunId, audioEvidence: stage.audioEvidence, soundtrack, verifiedDimensions: [...verdictStage.verified.filter(key => key !== 'audio'), ...stage.audioEvidence.verified], unverified: [...verdict.unverified.filter(item => item.dimension !== 'audio'), ...soundtrack.unverified] };}async function execute(ctx, start) {@@ -345,7 +349,14 @@ async function execute(ctx, start) {const inspected = await inspectStage(ctx, revision, style, pilot, review);ctx.state.findings = inspected.findings;ctx.state.verdict = { ...inspected.verdict, revisionId: revision.id, sourceHash: revision.sourceHash };- if (inspected.verdict.status === 'pass') return finalStage(ctx, revision, inspected);+ if (inspected.verdict.status === 'pass') {+ const soundtrack = await runStage(ctx, 'soundtrack', revision, ({ signal }) => ctx.deps.sound({+ projectId: ctx.projectId, runId: ctx.runId, revision, signal, reserve: bytes => reserve(ctx, bytes),+ }), { renders: true });+ ctx.state.soundtrack = soundtrack;+ ctx.state.verdict = { ...ctx.state.verdict, unverified: [...ctx.state.verdict.unverified.filter(item => item.dimension !== 'audio'), ...soundtrack.unverified] };+ return finalStage(ctx, revision, inspected, soundtrack);+ }revision = await repairStage(ctx, revision, inspected.findings);}}@@ -373,7 +384,7 @@ async function finish(ctx, run) {return status;}-const defaultDeps = { sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute, review: reviewViaAuthoringRoute };+const defaultDeps = { sound: produceSoundtrack, mux: muxSoundtrack, sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute, review: reviewViaAuthoringRoute };/*** Start a user-requested production run. Resolves with the persisted run once@@ -396,6 +407,7 @@ export async function startProductionStageRun(projectId, input, deps = {}) {if (record.manifest.renderer.kind !== 'browser') {throw new ServerError('Only browser-rendered projects can run these stages', { status: 409, code: 'CODE_ANIMATION_RENDERER_UNSUPPORTED' });}+ checkSoundConsent(record.manifest.audio, request);const revision = { ...record };const runId = randomUUID();const priorSpent = prior?.data.spent;@@ -404,7 +416,7 @@ export async function startProductionStageRun(projectId, input, deps = {}) {budgets: project.budgets, requested: project.localSettings, effective: null, reservedBytes: 0,spent: { iterations: priorSpent?.iterations ?? 0, tokens: priorSpent?.tokens ?? 0, renderMs: priorSpent?.renderMs ?? 0, diskBytes: 0, elapsedMs: 0, priorElapsedMs: priorSpent?.elapsedMs ?? 0 },visualReview: request.visualReview ?? prior?.data.visualReview ?? false,- stages: [], findings: [], verdict: null, output: null, repairs: prior?.data.repairs ?? [],+ stages: [], findings: [], verdict: null, soundtrack: null, output: null, repairs: prior?.data.repairs ?? [],resumedFrom: prior?.id ?? null, stopReason: null, resumable: false, executed: true,};const ctx = {diff --git a/server/services/codeAnimation/stages.realBrowser.db.test.js b/server/services/codeAnimation/stages.realBrowser.db.test.jsindex 2e96c84807..39c043e725 100644--- a/server/services/codeAnimation/stages.realBrowser.db.test.js+++ b/server/services/codeAnimation/stages.realBrowser.db.test.js@@ -3,8 +3,9 @@// new revision, and finally encoded by the real renderer and ffmpeg. PostgreSQL// (portos_test) holds the project and run records; no provider is called.import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { createHash } from 'node:crypto';import { existsSync } from 'node:fs';-import { readFile } from 'node:fs/promises';+import { readFile, mkdir, writeFile } from 'node:fs/promises';import { execFileSync, spawn } from 'node:child_process';import { join } from 'node:path';import { chromium } from 'playwright-core';@@ -56,7 +57,10 @@ const manifest = {styleGuide: 'Flat shapes', renderer: { kind: 'browser', version: 'synthetic-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 },+ audio: { kind: 'procedural', version: 1, events: [+ { label: 'Impact', atSeconds: 0.5, effect: 'impact', durationSeconds: 0.2, gain: 0.8 },+ { label: 'Reveal', atSeconds: 1.25, effect: 'reveal', durationSeconds: 0.4, gain: 0.6 },+ ] }, execution: { requested: null, effective: null },};let proc;@@ -118,5 +122,43 @@ describe.skipIf(!dbReady || !chrome || !ffmpeg || !ffprobe)('Production stages wconst frames = Number(execFileSync(ffprobe, ['-v', 'error', '-select_streams', 'v:0', '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', video]).toString().trim());expect(frames).toBe(24);expect(data.output.revisionId).toBe(data.currentRevisionId);+ const sound = data.soundtrack;+ expect(sound.measured).toMatchObject({ sampleRate: 48000, frames: 96000, durationMs: 2000, nonFinite: 0 });+ const wav = await readFile(join(PATHS.data, sound.artifact.relativePath));+ const { synthesizeSoundtrack } = await import('../../lib/codeAnimationSound.js');+ expect(wav.equals(synthesizeSoundtrack(sound.timeline))).toBe(true);+ expect(createHash('sha256').update(wav).digest('hex')).toBe(data.output.audioHash);+ expect(data.output.audioEvidence).toMatchObject({ packageHash: sound.packageHash,+ stream: { codec_name: 'aac', sample_rate: '48000' }, verified: expect.arrayContaining(['audio-stream', 'audio-duration', 'audio-event-placement']) });+ const decoded = execFileSync(ffmpeg, ['-v', 'error', '-i', video, '-map', '0:a:0', '-ar', '48000', '-ac', '1', '-f', 's16le', 'pipe:1'], { maxBuffer: 1024 * 1024 });+ expect(decoded.length / 2 / 48000).toBeCloseTo(2, 1);+ for (const expected of [0.5, 1.25]) {+ // Independent decode: energy before the onset is silent, the authored window contains the event.+ let quietPeak = 0; let activePeak = 0;+ for (let i = Math.round((expected - 0.15) * 48000); i < Math.round((expected - 0.05) * 48000); i++) quietPeak = Math.max(quietPeak, Math.abs(decoded.readInt16LE(i * 2)));+ for (let i = Math.round(expected * 48000); i < Math.round((expected + 0.1) * 48000); i++) activePeak = Math.max(activePeak, Math.abs(decoded.readInt16LE(i * 2)));+ expect(quietPeak).toBeLessThan(100);+ expect(activePeak).toBeGreaterThan(1000);+ }+ expect(data.output.unverified.map(item => item.dimension)).toContain('hearing');+ // Renderer-independent library/upload snapshots survive a real final mux;+ // changing the original asset after staging cannot change the candidate.+ const { stageProductionSoundAsset } = await import('./soundAssets.js');+ for (const source of ['upload', 'library']) {+ const root = source === 'upload' ? PATHS.uploads : PATHS.music;+ await mkdir(root, { recursive: true });+ await writeFile(join(root, 'example.wav'), wav);+ const staged = await stageProductionSoundAsset(projectId, { revisionId: data.currentRevisionId, source, filename: 'example.wav' });+ await writeFile(join(root, 'example.wav'), 'replaced');+ const next = await startProductionStageRun(projectId, { revisionId: staged.revision.id }, {+ render: ({ directory }) => renderComposition({ directory, jobId: `sound-${source}-acceptance` }),+ });+ expect(await next.done).toBe('completed');+ const saved = (await getProductionHistory(projectId, { limit: 1, offset: 0 })).items[0].data;+ expect(saved.soundtrack.kind).toBe('file');+ expect(saved.output.audioEvidence.peak).toBeGreaterThan(0.1);+ expect(saved.output.audioEvidence.decodedDurationSeconds).toBeCloseTo(2, 1);+ expect(saved.output.audioEvidence.packageHash).toBe(staged.revision.packageHash);+ }}, 180000);});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 5cebf21473..f00bf04cae 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -21,6 +21,7 @@ export const DB_TEST_INCLUDE = ['services/appQuality.db.test.js','**/db.test.js','services/codeAnimation/stages.db.test.js',+ 'services/codeAnimation/sound.db.test.js','services/codeAnimation/stages.realBrowser.db.test.js','services/mediaAssetIndex/galleryCollections.db.test.js','services/dbAdmin.db.test.js',