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: bounded Code Animation stage runs — measured style frame, pilot, inspection, repair and final render (#9389)
[._.]/ Adam Eivy1ebbd1158499
diff --git a/server/lib/codeAnimationProjects.js b/server/lib/codeAnimationProjects.jsindex c06442a2f1..09a32ae832 100644--- a/server/lib/codeAnimationProjects.js+++ b/server/lib/codeAnimationProjects.js@@ -36,3 +36,10 @@ export const codeAnimationProjectSchema = z.object({}).strict();export const codeAnimationProjectPatchSchema = partialWithoutDefaults(codeAnimationProjectSchema);++// POST /projects/:id/stage-runs. Starting is an explicit user action; the body+// can only name which stored revision to work from or which stopped run to resume.+export const codeAnimationStageRunSchema = z.object({+ revisionId: z.string().uuid().optional(),+ resumeFromRunId: z.string().uuid().optional(),+}).strict().refine(value => !(value.revisionId && value.resumeFromRunId), 'Choose a revision or a run to resume, not both');diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex f169fe468c..6235e2a2d9 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -11,6 +11,8 @@* POST /api/code-animation/:id/export queue a frame-exact MP4 render → 202 media job* GET /api/code-animation/:id/package download a portable source package* 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*/import { Router } from 'express';@@ -32,7 +34,8 @@ import {import { startCodeAnimationExport } from '../services/codeAnimation/export.js';import { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';-import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema } from '../lib/codeAnimationProjects.js';+import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema, codeAnimationStageRunSchema } from '../lib/codeAnimationProjects.js';+import { startProductionStageRun, cancelProductionStageRun } from '../services/codeAnimation/stages.js';import {createProductionProject, getProductionProject, patchProductionProject,listProductionProjects, getProductionHistory, importProductionPackage,@@ -210,6 +213,17 @@ router.post('/projects/:id/accept', asyncHandler(async (req, res) => {const { revisionId } = validateRequest(z.object({ revisionId: z.string().uuid() }).strict(), req.body);res.json(await acceptProductionSource(id, revisionId));}));+// An explicit, user-started stage run (style frame → pilot → inspect → repair → final).+// 202: the run continues in the background; progress arrives as code-animation:changed.+router.post('/projects/:id/stage-runs', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ const { run } = await startProductionStageRun(id, validateRequest(codeAnimationStageRunSchema, req.body ?? {}));+ res.status(202).json(run);+}));+router.post('/projects/:id/stage-runs/:runId/cancel', asyncHandler(async (req, res) => {+ const { id, runId } = validateRequest(z.object({ id: z.string().uuid(), runId: z.string().uuid() }).strict(), req.params);+ res.json(cancelProductionStageRun(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/evidence.js b/server/services/codeAnimation/evidence.jsnew file mode 100644index 0000000000..0ef3998da2--- /dev/null+++ b/server/services/codeAnimation/evidence.js@@ -0,0 +1,95 @@+/**+ * Measured evidence for Code Animation production stages (#9389). Pure: it+ * turns sampled renders into findings and a verdict. Nothing here calls a+ * provider; a dimension no measurement covers is reported `unverified` and can+ * never contribute to a pass.+ */++// A frozen span at least this long (or this share of the film) is a defect.+const FROZEN_MIN_SECONDS = 2;+const FROZEN_ERROR_SHARE = 0.5;+const BLANK_MEAN_LUMA = 2;+const BLANK_DEVIATION = 1;+// Frames a declared event may take to show any visual change.+const EVENT_WINDOW_BEFORE = 0.25;+const EVENT_WINDOW_AFTER = 0.75;++const round = value => Math.round(value * 1000) / 1000;++/** Longest run of consecutive samples sharing one render hash. */+function frozenSpans(samples) {+ const spans = [];+ let start = 0;+ for (let i = 1; i <= samples.length; i += 1) {+ if (i === samples.length || samples[i].renderHash !== samples[start].renderHash) {+ if (i - 1 > start) spans.push({ fromSeconds: samples[start].t, toSeconds: samples[i - 1].t, samples: i - start });+ start = i;+ }+ }+ return spans;+}++/**+ * Findings and verified/unverified dimensions from the style-frame and pilot+ * samples. `pilot.samples` is `[{ t, renderHash, mean, deviation }]` where mean+ * and deviation are null when the film canvas could not be read back.+ */+export function analyzeEvidence({ manifest, pilot, contract }) {+ const findings = [];+ const { durationSeconds, width, height, fps } = manifest.format;+ const add = (kind, severity, detail, extra = {}) => findings.push({ kind, severity, detail, ...extra });++ if (contract) {+ 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.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}` } });+ }+ }++ const samples = pilot.samples;+ const unreadable = samples.every(sample => sample.mean === null);+ if (!unreadable && samples.every(sample => sample.mean < BLANK_MEAN_LUMA || sample.deviation < BLANK_DEVIATION)) {+ add('blank-film', 'error', 'Every sampled frame is blank or a single flat color.', { measured: { maxMean: round(Math.max(...samples.map(sample => sample.mean))) } });+ }+ const distinct = new Set(samples.map(sample => sample.renderHash)).size;+ if (samples.length > 1 && distinct === 1) {+ add('frozen-film', 'error', 'Every sampled frame is pixel-identical: nothing moves.', { atSeconds: 0, measured: { samples: samples.length } });+ } else {+ for (const span of frozenSpans(samples)) {+ const length = span.toSeconds - span.fromSeconds;+ if (length >= FROZEN_MIN_SECONDS || length >= durationSeconds * FROZEN_ERROR_SHARE) {+ add('frozen-span', length >= durationSeconds * FROZEN_ERROR_SHARE ? 'error' : 'warning',+ `Nothing changes from ${span.fromSeconds}s to ${span.toSeconds}s.`, { atSeconds: span.fromSeconds, measured: span });+ }+ }+ }+ for (const event of manifest.events) {+ const near = samples.filter(sample => sample.t >= event.atSeconds - EVENT_WINDOW_BEFORE && sample.t <= event.atSeconds + EVENT_WINDOW_AFTER);+ if (near.length > 1 && new Set(near.map(sample => sample.renderHash)).size === 1) {+ add('event-without-change', 'warning', `Nothing visibly changes around the "${event.label}" event.`, { atSeconds: event.atSeconds, measured: { label: event.label, samples: near.length } });+ }+ }++ const verified = ['frame-size', 'timing', 'visual-motion'];+ if (!unreadable) verified.push('blank-frame');+ const unverified = [];+ if (unreadable) unverified.push({ dimension: 'blank-frame', reason: 'The film canvas could not be read back, so blankness was not measured.' });+ if (manifest.audio.kind === 'silence') verified.push('audio');+ else unverified.push({ dimension: 'audio', reason: 'Temporal audio and sound sync are not measured by this stage.' });+ unverified.push({ dimension: 'semantic-visual', reason: 'No visual reviewer is wired; style fit and composition quality are not judged.' });+ return { findings, verified, unverified };+}++/**+ * Whether the evidence may pass. Stale evidence (captured against a different+ * source), missing evidence and any error finding never pass; unverified+ * dimensions are listed, never counted as verified.+ */+export function evaluateVerdict({ evidence, sourceHash, 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 (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.jsnew file mode 100644index 0000000000..f0977f6344--- /dev/null+++ b/server/services/codeAnimation/evidence.test.js@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';+import { analyzeEvidence, evaluateVerdict } from './evidence.js';++const manifest = (overrides = {}) => ({+ format: { width: 1280, height: 720, fps: 12, durationSeconds: 6 }, events: [], audio: { kind: 'silence' }, ...overrides,+});+const contract = { durationSec: 6, fps: 12, width: 1280, height: 720 };+const samples = (hashes, { mean = 80, deviation = 20 } = {}) => hashes.map((renderHash, index) => ({ t: index, renderHash, mean, deviation }));+const kinds = result => result.findings.map(finding => `${finding.severity}:${finding.kind}`);++describe('production evidence analysis', () => {+ it('reports what the samples measure and nothing more', () => {+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b', 'c', 'd']) }, contract }))).toEqual([]);+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'a', 'a', 'a']) }, contract }))).toEqual(['error:frozen-film']);+ // A 3s freeze in a 6s film is half the film: an error. A 2s one is a warning.+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b', 'b', 'b', 'c', 'd']) }, contract }))).toEqual(['warning:frozen-span']);+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b', 'b', 'b', 'b', 'c']) }, contract }))).toEqual(['error:frozen-span']);+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b', 'c', 'd'], { mean: 0.5 }) }, contract }))).toEqual(['error:blank-film']);+ expect(kinds(analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b']) }, contract: { ...contract, durationSec: 9, width: 640 } })))+ .toEqual(['error:duration-mismatch', 'error:frame-size-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 });+ expect(kinds(result)).toEqual(['warning:event-without-change']);+ expect(result.verified).not.toContain('audio');+ expect(result.unverified.map(item => item.dimension)).toEqual(['audio', 'semantic-visual']);+ // A canvas that cannot be read back is unverified, never "not blank".+ const unreadable = analyzeEvidence({ manifest: manifest(), pilot: { samples: samples(['a', 'b'], { mean: null, deviation: null }) }, contract });+ expect(unreadable.verified).not.toContain('blank-frame');+ expect(unreadable.unverified.map(item => item.dimension)).toContain('blank-frame');+ });+});++describe('production verdict', () => {+ const evidence = { sourceHash: 'h1' };+ it('passes only fresh, error-free evidence', () => {+ expect(evaluateVerdict({ evidence, sourceHash: 'h1', findings: [{ severity: 'warning' }], unverified: [] }).status).toBe('pass');+ expect(evaluateVerdict({ evidence, sourceHash: 'h1', findings: [{ severity: 'error' }], unverified: [] }).status).toBe('fail');+ expect(evaluateVerdict({ evidence, sourceHash: 'h2', findings: [], unverified: [] }).status).toBe('stale');+ expect(evaluateVerdict({ evidence: { sourceHash: null }, sourceHash: 'h1', findings: [], unverified: [] }).status).toBe('unverified');+ expect(evaluateVerdict({ evidence: null, sourceHash: 'h1', findings: [], unverified: [] }).status).toBe('unverified');+ });+});diff --git a/server/services/codeAnimation/export.js b/server/services/codeAnimation/export.jsindex 8f6d855a2d..f2d0d75549 100644--- a/server/services/codeAnimation/export.js+++ b/server/services/codeAnimation/export.js@@ -48,7 +48,7 @@ const scriptLiteral = (value) => JSON.stringify(value).replace(/</g, '\\u003c');* grid of the attached Music-library track (or null), exposed as* window.ANIMATION_SONG (CODE_ANIMATION_SONG_GLOBAL) so audio-reactive films can stay a function of t.*/-function buildExportShim({ maxDurationSec = EXPORT_MAX_DURATION_SEC, song = null } = {}) {+export function buildExportShim({ maxDurationSec = EXPORT_MAX_DURATION_SEC, song = null } = {}) {return `(() => {const nativeRaf = window.requestAnimationFrame.bind(window);${song ? `window[${scriptLiteral(CODE_ANIMATION_SONG_GLOBAL)}] = ${scriptLiteral(song)};` : ''}@@ -92,7 +92,7 @@ function buildExportShim({ maxDurationSec = EXPORT_MAX_DURATION_SEC, song = null}/** The stored HTML with the shim inserted as the first script of the document. */-function injectExportShim(html, shim) {+export function injectExportShim(html, shim) {const tag = `<script>${shim}</script>`;const head = html.match(/<head[^>]*>/i);if (!head) return `${tag}${html}`;diff --git a/server/services/codeAnimation/projectFiles.js b/server/services/codeAnimation/projectFiles.jsindex aebd865e20..6dd07ebefa 100644--- a/server/services/codeAnimation/projectFiles.js+++ b/server/services/codeAnimation/projectFiles.js@@ -5,6 +5,11 @@ import { join } from 'path';import { createHash } from 'crypto';import { PATHS } from '../../lib/paths.js';import { ServerError } from '../../lib/errorHandler.js';+import { canonicalStringify } from '../../lib/objects.js';++/** Identity of a source: its file paths and content hashes, independent of file order. */+export const sourceHashOf = files => createHash('sha256').update(canonicalStringify(+ files.map(({ path, sha256 }) => ({ path, sha256 })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0))).digest('hex');const unsafe = () => new ServerError('Managed revision storage is not a regular directory or file', {status: 409, code: 'CODE_ANIMATION_UNSAFE_STORAGE',@@ -79,3 +84,68 @@ export async function readProjectFiles(projectId, revisionId, files) {}return result;}++// Stage-run output lives beside, never inside, the immutable revision bytes:+// data/code-animations/projects/<project>/runs/<run>/…, one exclusive+// directory per run so two runs can never write the same path.+async function runDirectory(projectId, runId, tail, { create, exclusive = false }) {+ let path = PATHS.data;+ await directory(path, false);+ const parts = ['code-animations', 'projects', projectId, 'runs', runId, ...tail];+ for (const [index, part] of parts.entries()) {+ path = join(path, part);+ if (exclusive && create && index === parts.length - 1) await mkdir(path, { mode: 0o700 });+ else await directory(path, create);+ }+ return path;+}++async function writeOwnedFile(path, bytes) {+ const handle = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0), 0o444);+ try {+ await handle.writeFile(bytes);+ await handle.sync();+ } finally { await handle.close(); }+}++/**+ * Write one run artifact (a captured frame) under the run's own directory.+ * Never overwrites: a name collision is a bug in the caller.+ */+export async function writeRunArtifact(projectId, runId, name, bytes) {+ const dir = await runDirectory(projectId, runId, ['artifacts'], { create: true });+ await writeOwnedFile(join(dir, name), bytes);+ return {+ relativePath: `code-animations/projects/${projectId}/runs/${runId}/artifacts/${name}`,+ sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.length,+ };+}++/**+ * Stage one revision for the browser: a private, write-once copy where the+ * entrypoint becomes index.html (transformed by `prepareEntry`). The renderer's+ * snapshot reads this copy; the revision's own bytes are never modified.+ */+export async function stageRenderSource(projectId, runId, revisionId, files, entryPath, prepareEntry) {+ if (entryPath !== 'index.html' && files.some(file => file.path === 'index.html')) {+ throw new ServerError('The entrypoint is not index.html and another index.html exists', { status: 409, code: 'CODE_ANIMATION_ENTRY_CONFLICT' });+ }+ const owned = await runDirectory(projectId, runId, ['render', revisionId], { create: true, exclusive: true });+ try {+ for (const file of files) {+ const bytes = Buffer.from(file.content, file.encoding === 'base64' ? 'base64' : 'utf8');+ const isEntry = file.path === entryPath;+ let parent = owned;+ const target = isEntry ? 'index.html' : file.path;+ for (const part of target.split('/').slice(0, -1)) {+ parent = join(parent, part);+ await directory(parent, true);+ }+ await writeOwnedFile(join(owned, target), isEntry ? Buffer.from(prepareEntry(bytes.toString('utf8'))) : bytes);+ }+ } catch (error) {+ await rm(owned, { recursive: true, force: true });+ throw error;+ }+ return { directory: `code-animations/projects/${projectId}/runs/${runId}/render/${revisionId}` };+}diff --git a/server/services/codeAnimation/projectStore.js b/server/services/codeAnimation/projectStore.jsindex 3dcfc652d9..9b5f700a6a 100644--- a/server/services/codeAnimation/projectStore.js+++ b/server/services/codeAnimation/projectStore.js@@ -110,3 +110,75 @@ export async function interruptImports(projectId, activeIds) {await query(`UPDATE code_animation_project_runs SET status = 'interrupted', completed_at = NOW()WHERE project_id = $1 AND status = 'staging' AND NOT (id = ANY($2::text[]))`, [projectId, activeIds]);}++// ---- Stage runs (#9389): one active run per project, durable status ----++const RUN_ACTIVE = 'running';++/**+ * Insert a running stage run. Rows left `running` by a previous process (not in+ * `activeIds`) are marked interrupted first, so a restart never blocks the+ * project and never silently resumes. Another live run is a conflict.+ */+export async function startStageRun(id, projectId, data, activeIds) {+ return withTransaction(async client => {+ const project = await client.query('SELECT data FROM code_animation_projects WHERE id = $1 FOR UPDATE', [projectId]);+ if (!project.rows[0]) throw missing();+ await client.query(`UPDATE code_animation_project_runs SET status = 'interrupted',+ data = data || '{"resumable":true}'::jsonb, completed_at = NOW()+ WHERE project_id = $1 AND status = $2 AND data->>'kind' = 'production-stages' AND NOT (id = ANY($3::text[]))`,+ [projectId, RUN_ACTIVE, activeIds]);+ const live = await client.query(`SELECT id FROM code_animation_project_runs+ WHERE project_id = $1 AND status = $2 AND data->>'kind' = 'production-stages' LIMIT 1`, [projectId, RUN_ACTIVE]);+ if (live.rows[0]) {+ throw new ServerError('A production run is already active for this project', { status: 409, code: 'CODE_ANIMATION_RUN_ACTIVE' });+ }+ await client.query(`INSERT INTO code_animation_project_runs (id, project_id, revision_id, status, data)+ VALUES ($1, $2, $3, $4, $5)`, [id, projectId, data.sourceRevisionId, RUN_ACTIVE, data]);+ });+}++export async function saveStageRun(id, status, data, { revisionId = null, completed = false } = {}) {+ await query(`UPDATE code_animation_project_runs SET status = $2, data = $3,+ revision_id = COALESCE($4, revision_id), completed_at = CASE WHEN $5 THEN NOW() ELSE completed_at END WHERE id = $1`,+ [id, status, data, revisionId, completed]);+}++export async function getRunRecord(projectId, runId) {+ const { rows } = await query(`SELECT id, status, revision_id AS "revisionId", data, created_at AS "createdAt",+ completed_at AS "completedAt" FROM code_animation_project_runs WHERE project_id = $1 AND id = $2`, [projectId, runId]);+ return rows[0] || null;+}++/** Add `bytes` to a run's disk reservation unless it would exceed the project budget. */+export async function reserveRunBytes(runId, projectId, bytes) {+ return withTransaction(async client => {+ const project = await client.query('SELECT data FROM code_animation_projects WHERE id = $1 FOR UPDATE', [projectId]);+ if (!project.rows[0]) throw missing();+ const used = await client.query("SELECT COALESCE(SUM((data->>'reservedBytes')::bigint), 0) AS bytes FROM code_animation_project_runs WHERE project_id = $1", [projectId]);+ if (Number(used.rows[0].bytes) + bytes > project.rows[0].data.budgets.diskBytes) return false;+ await client.query(`UPDATE code_animation_project_runs SET data = jsonb_set(data, '{reservedBytes}',+ to_jsonb(COALESCE((data->>'reservedBytes')::bigint, 0) + $2::bigint)) WHERE id = $1`, [runId, bytes]);+ return true;+ });+}++/** A repaired source is a new immutable candidate revision; the accepted one is untouched. */+export async function commitRepairRevision(projectId, revision) {+ return withTransaction(async client => {+ const { rows } = await client.query(`SELECT ${columns} FROM code_animation_projects WHERE id = $1 FOR UPDATE`, [projectId]);+ if (!rows[0]) throw missing();+ await client.query(`INSERT INTO code_animation_project_revisions+ (id, project_id, package_hash, source_hash, total_bytes, data) VALUES ($1, $2, $3, $4, $5, $6)`,+ [revision.id, projectId, revision.packageHash, revision.sourceHash, revision.totalBytes, revision]);+ const saved = await client.query(`UPDATE code_animation_projects SET candidate_revision_id = $2, updated_at = NOW()+ WHERE id = $1 RETURNING ${columns}`, [projectId, revision.id]);+ return present(saved.rows[0]);+ });+}++export async function interruptStageRuns(projectId, activeIds) {+ await query(`UPDATE code_animation_project_runs SET status = 'interrupted',+ 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]);+}diff --git a/server/services/codeAnimation/projects.js b/server/services/codeAnimation/projects.jsindex 5c4fb27f65..2f07141878 100644--- a/server/services/codeAnimation/projects.js+++ b/server/services/codeAnimation/projects.js@@ -1,13 +1,13 @@/** Production persistence is data-only; later stages own contained execution. */-import { randomUUID, createHash } from 'crypto';-import { canonicalStringify } from '../../lib/objects.js';+import { randomUUID } from 'crypto';import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema } from '../../lib/codeAnimationProjects.js';import { validateRequest } from '../../lib/validation.js';import { ServerError } from '../../lib/errorHandler.js';import { emitCodeAnimationChanged } from '../socket.js';import * as store from './projectStore.js';-import { stageProjectFiles, readProjectFiles } from './projectFiles.js';+import { stageProjectFiles, readProjectFiles, sourceHashOf } from './projectFiles.js';+import { activeStageRunIds } from './stages.js';const activeImports = new Set();@@ -33,6 +33,7 @@ export const listProductionProjects = page => store.pageProjectRecords(page);export async function getProductionHistory(id, page) {await getProductionProject(id);await store.interruptImports(id, [...activeImports]);+ await store.interruptStageRuns(id, activeStageRunIds());return store.pageProjectHistory(id, page);}@@ -57,7 +58,7 @@ export async function importProductionPackage(projectId, input) {staged = true;const revision = {id: revisionId, packageHash: pkg.revisionHash,- sourceHash: createHash('sha256').update(canonicalStringify(pkg.files.map(({ path, sha256 }) => ({ path, sha256 })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0))).digest('hex'),+ sourceHash: sourceHashOf(pkg.files),totalBytes, schemaVersion: pkg.schemaVersion, manifest: pkg.manifest,files: pkg.files.map(({ content: _content, ...file }) => file),storage, createdAt: new Date().toISOString(),diff --git a/server/services/codeAnimation/stageRender.js b/server/services/codeAnimation/stageRender.jsnew file mode 100644index 0000000000..f4e50bac84--- /dev/null+++ b/server/services/codeAnimation/stageRender.js@@ -0,0 +1,114 @@+/**+ * Real-browser and media-queue adapters for the Code Animation production+ * stages (#9389). Both run the staged, write-once copy of a revision inside the+ * HTML-composition renderer's sandbox (no network, disposable context); neither+ * calls a provider.+ */+import { createHash } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { openComposition } from '../htmlComposition/browser.js';++const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');+const SAMPLE_SCALE = 0.25;++// Down-sample the film canvas to 16x9 and report luma statistics. WebGL and+// other non-2d canvases cannot be read back reliably after the paint, so they+// report null (unverified) instead of a false "blank".+const MEASURE = `(() => {+ const film = [...document.querySelectorAll('canvas')].sort((a, b) => (b.width * b.height) - (a.width * a.height))[0];+ if (!film) return null;+ try {+ if (!film.getContext('2d')) return null;+ const probe = document.createElement('canvas');+ probe.width = 16; probe.height = 9;+ const context = probe.getContext('2d', { willReadFrequently: true });+ context.drawImage(film, 0, 0, 16, 9);+ const data = context.getImageData(0, 0, 16, 9).data;+ let sum = 0; let squares = 0;+ for (let i = 0; i < data.length; i += 4) {+ const luma = 0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2];+ sum += luma; squares += luma * luma;+ }+ const mean = sum / 144;+ return { mean, deviation: Math.sqrt(Math.max(0, squares / 144 - mean * mean)) };+ } catch { return null; }+})()`;++/**+ * Seek the staged film to each of `times` and measure it. `captureTimes` also+ * return a full-size PNG. Every sample's `renderHash` is taken from the same+ * down-scaled screenshot, so adjacent samples are comparable.+ */+export async function sampleFilm(directory, { times, captureTimes = [], signal }) {+ const page = await openComposition(directory, { signal });+ const samples = [];+ const frames = [];+ let contract;+ try {+ contract = await page.evaluate(`(() => {+ const c = globalThis.portosComposition;+ if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');+ return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height };+ })()`);+ const { width, height } = contract;+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ page.check();+ const capture = new Set(captureTimes);+ for (const t of [...new Set([...times, ...captureTimes])].sort((a, b) => a - b)) {+ page.check();+ try {+ await page.evaluate(`globalThis.portosComposition.seek(${t})`);+ } catch (error) {+ throw new ServerError(`The film failed at ${t}s: ${error.message}`, { status: 422, code: 'CODE_ANIMATION_FILM_FAILED' });+ }+ page.check();+ const small = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false,+ clip: { x: 0, y: 0, width, height, scale: SAMPLE_SCALE } });+ const measured = await page.evaluate(MEASURE);+ if (times.includes(t)) samples.push({ t, renderHash: sha256(Buffer.from(small.data, 'base64')), mean: measured?.mean ?? null, deviation: measured?.deviation ?? null });+ if (capture.has(t)) {+ const full = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });+ frames.push({ t, bytes: Buffer.from(full.data, 'base64') });+ }+ page.check();+ }+ await page.close({ verify: true });+ } catch (error) {+ await page.close();+ throw error;+ }+ return { contract, samples, frames };+}++/**+ * Queue the final render on the shared media queue and wait for it. The queue+ * owns the work, so abort (cancel, time budget) cancels the queued/running job.+ */+export async function renderViaMediaQueue({ directory, signal }) {+ const { enqueueJob, cancelJob, mediaJobEvents } = await import('../mediaJobQueue/index.js');+ return new Promise((resolve, reject) => {+ let jobId = null;+ const finish = (fn, value) => {+ for (const [state, listener] of listeners) mediaJobEvents.off(state, listener);+ signal?.removeEventListener('abort', onAbort);+ fn(value);+ };+ const mine = job => job?.kind === 'html-composition' && job.params?.directory === directory;+ const listeners = ['completed', 'failed', 'canceled'].map(state => [state, job => {+ if (!mine(job)) return;+ if (state === 'completed') finish(resolve, { jobId: job.id, ...(job.result || {}) });+ else finish(reject, new ServerError(job.error || `The render ${state}`, { status: 502, code: 'CODE_ANIMATION_RENDER_FAILED' }));+ }]);+ const onAbort = () => {+ const reason = signal.reason;+ const cancel = jobId ? cancelJob(jobId).catch(() => {}) : Promise.resolve();+ cancel.finally(() => finish(reject, reason));+ };+ for (const [state, listener] of listeners) mediaJobEvents.on(state, listener);+ signal?.addEventListener('abort', onAbort, { once: true });+ enqueueJob({ kind: 'html-composition', params: { directory } }).then(+ queued => { jobId = queued.jobId; if (signal?.aborted) onAbort(); },+ error => finish(reject, error),+ );+ });+}diff --git a/server/services/codeAnimation/stages.db.test.js b/server/services/codeAnimation/stages.db.test.jsnew file mode 100644index 0000000000..e09c53b72b--- /dev/null+++ b/server/services/codeAnimation/stages.db.test.js@@ -0,0 +1,182 @@+/** Bounded production stages → PostgreSQL → managed files; synthetic renders, no provider. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { access, readFile } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';+import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';+vi.mock('../../lib/paths.js', async importOriginal =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('code-animation-stages-') }));+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';+import { requireDbOrSkip } from '../../lib/dbTestGate.js';+import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';+import { PATHS } from '../../lib/paths.js';+import {+ createProductionProject, exportProductionPackage, getProductionHistory, getProductionProject, importProductionPackage,+ patchProductionProject,+} from './projects.js';+import { cancelProductionStageRun, startProductionStageRun } from './stages.js';++const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));+const ready = requireDbOrSkip('codeAnimation/stages.db.test', health.connected, health.error);+if (ready) await ensureSchema();+const ids = [];+afterAll(async () => {+ if (ready && ids.length) await query('DELETE FROM code_animation_projects WHERE id = ANY($1::text[])', [ids]);+ await close(); cleanupTempDataRoots('code-animation-stages-');+});++const manifest = (audio = { kind: 'silence' }) => ({+ title: 'Synthetic film', brief: { concept: 'A cube hops over a cone.', cast: '', onScreenText: '' },+ styleGuide: 'Graphic shapes', renderer: { kind: 'browser', version: 'synthetic-v1', engine: null },+ format: { width: 1280, height: 720, fps: 12, durationSeconds: 4 }, seed: 1,+ entrypoints: [{ role: 'preview', path: 'src/index.html' }], assets: [], shots: [], events: [],+ audio, execution: { requested: null, effective: null },+});+const pkg = (source, audio) => createCodeAnimationPackage(manifest(audio), [{ path: 'src/index.html', content: source }]);+const project = async (budgets = {}, audio) => {+ const created = await createProductionProject({ manifest: manifest(audio), budgets });+ ids.push(created.id);+ const { revision } = await importProductionPackage(created.id, pkg('<html><canvas></canvas>FROZEN</html>', audio));+ return { id: created.id, revision };+};++// A deterministic stand-in for the browser: a FROZEN source never changes, any+// other source differs at every time. It reads the staged copy the renderer would.+const sample = async (directory, { times, captureTimes = [], signal }) => {+ signal.throwIfAborted();+ const html = await readFile(join(PATHS.data, directory, 'index.html'), 'utf8');+ expect(html).toContain('portosComposition');+ const hash = t => createHash('sha256').update(html.includes('FROZEN') ? 'same' : `t${t}`).digest('hex');+ return {+ contract: { durationSec: 4, fps: 12, width: 1280, height: 720 },+ samples: times.map(t => ({ t, renderHash: hash(t), mean: 80, deviation: 20 })),+ frames: captureTimes.map(t => ({ t, bytes: Buffer.from(`png-${t}`) })),+ };+};+const unfreeze = vi.fn(async ({ files, entryPath }) => ({+ files: [{ path: entryPath, content: files.find(file => file.path === entryPath).content.replace('FROZEN', 'MOVING') }], tokens: 100,+}));+const render = vi.fn(async () => ({ jobId: 'media-job', id: 'video-1', filename: 'composition-media-job.mp4', path: '/data/videos/composition-media-job.mp4' }));+const exists = path => access(path).then(() => true, () => false);++describe.skipIf(!ready)('Production stage runs', () => {+ it('measures a real render, repairs it into a new immutable revision, and renders final only from passing evidence', async () => {+ const { id, revision } = await project();+ unfreeze.mockClear(); render.mockClear();+ const { run, done } = await startProductionStageRun(id, {}, { sample, repair: unfreeze, render });+ expect(run).toMatchObject({ status: 'running', sourceRevisionId: revision.id });+ expect(await done).toBe('completed');++ const [saved] = (await getProductionHistory(id, { limit: 5, offset: 0 })).items;+ 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']);+ 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);+ expect(first.verdict.status).toBe('fail');+ expect(second.verdict.status).toBe('pass');+ expect(second.findings).toEqual([]);++ // The repair is a new candidate lineage entry; the original bytes and the accepted pointer are untouched.+ const current = await getProductionProject(id);+ expect(current.candidateRevisionId).toBe(data.currentRevisionId);+ expect(current.candidateRevisionId).not.toBe(revision.id);+ expect(current.acceptedRevisionId).toBeNull();+ expect((await exportProductionPackage(id, revision.id)).files[0].content).toContain('FROZEN');+ expect((await exportProductionPackage(id, current.candidateRevisionId)).files[0].content).toContain('MOVING');+ expect(data.repairs).toEqual([expect.objectContaining({ fromRevisionId: revision.id, revisionId: current.candidateRevisionId, findingKinds: ['frozen-film'] })]);++ // 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.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);+ }+ });++ it('never passes unmeasured or unrepairable evidence: exhausted iterations keep artifacts, skip the render, and report audio as unverified', async () => {+ const { id } = await project({ iterations: 1 }, { kind: 'external', notes: 'Separate track' });+ render.mockClear();+ const stillFrozen = vi.fn(async ({ files, entryPath }) => ({+ files: [{ path: entryPath, content: `${files.find(file => file.path === entryPath).content}<!-- FROZEN again -->` }],+ }));+ const { done, run } = await startProductionStageRun(id, {}, { sample, repair: stillFrozen, render });+ expect(await done).toBe('exhausted');+ expect(render).not.toHaveBeenCalled();+ const [saved] = (await getProductionHistory(id, { limit: 1, offset: 0 })).items;+ expect(saved.data).toMatchObject({ stopReason: 'iterations', resumable: true, output: null, verdict: { status: 'fail' } });+ expect(saved.data.verdict.unverified.map(item => item.dimension)).toEqual(expect.arrayContaining(['audio', 'semantic-visual']));+ expect(saved.data.verdict.unverified.map(item => item.dimension)).not.toContain('visual-motion');+ expect(saved.id).toBe(run.id);+ });++ it('keeps one live run per project, cancels owned work, retains accepted artifacts, and resumes without re-measuring the style frame', async () => {+ const { id } = await project();+ let pilotStarted;+ const started = new Promise(resolve => { pilotStarted = resolve; });+ const blocking = vi.fn(async (directory, options) => {+ if (!options.times.length) return sample(directory, options);+ pilotStarted();+ await new Promise((_, reject) => options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true }));+ });+ const first = await startProductionStageRun(id, {}, { sample: blocking, repair: unfreeze, render });+ await started;+ await expect(startProductionStageRun(id, {}, { sample, repair: unfreeze, render })).rejects.toMatchObject({ code: 'CODE_ANIMATION_RUN_ACTIVE' });+ cancelProductionStageRun(id, first.run.id);+ expect(await first.done).toBe('canceled');++ const [canceled] = (await getProductionHistory(id, { limit: 1, offset: 0 })).items;+ expect(canceled).toMatchObject({ status: 'canceled', data: { resumable: true, stopReason: 'canceled' } });+ const style = canceled.data.stages.find(stage => stage.key === 'style-frame');+ expect(style.status).toBe('completed');+ expect(canceled.data.stages.find(stage => stage.key === 'pilot').status).toBe('canceled');+ expect(await exists(join(PATHS.data, style.artifacts[0].relativePath))).toBe(true);++ const counting = vi.fn(sample);+ render.mockClear();+ const resumed = await startProductionStageRun(id, { resumeFromRunId: first.run.id }, { sample: counting, repair: unfreeze, render });+ expect(await resumed.done).toBe('completed');+ // The first revision's style frame was reused (only its pilot re-ran); the repaired revision is measured in full.+ expect(counting.mock.calls.map(([, options]) => [options.times.length > 0, (options.captureTimes ?? []).length])).toEqual([[true, 0], [false, 3], [true, 0]]);+ const [after] = (await getProductionHistory(id, { limit: 1, offset: 0 })).items;+ expect(after.data.stages.find(stage => stage.key === 'style-frame')).toMatchObject({ reusedFrom: first.run.id });+ // The two runs wrote to separate directories; the canceled run's frames are still there.+ expect(await exists(join(PATHS.data, style.artifacts[0].relativePath))).toBe(true);+ expect(render.mock.calls[0][0].directory).toContain(`/runs/${resumed.run.id}/`);+ });++ it('stops on the disk budget and on the render budget, preserving what was accepted', async () => {+ const small = await project({ diskBytes: 1500 });+ const bigFrames = async (directory, options) => ({ ...(await sample(directory, options)), frames: options.captureTimes.map(t => ({ t, bytes: Buffer.alloc(800) })) });+ const diskRun = await startProductionStageRun(small.id, {}, { sample: bigFrames, repair: unfreeze, render });+ expect(await diskRun.done).toBe('exhausted');+ expect((await getProductionHistory(small.id, { limit: 1, offset: 0 })).items[0].data.stopReason).toBe('disk');++ const slow = await project({ renderSeconds: 1 });+ const hang = vi.fn(async (directory, options) => {+ if (!options.times.length) return sample(directory, options);+ await new Promise((_, reject) => options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true }));+ });+ const renderRun = await startProductionStageRun(slow.id, {}, { sample: hang, repair: unfreeze, render });+ expect(await renderRun.done).toBe('exhausted');+ const [saved] = (await getProductionHistory(slow.id, { limit: 1, offset: 0 })).items;+ expect(saved.data).toMatchObject({ stopReason: 'render', resumable: true });+ expect((await patchProductionProject(slow.id, { budgets: { renderSeconds: 60 } })).budgets.renderSeconds).toBe(60);+ }, 20000);++ it('marks a stranded run interrupted on restart and never calls a provider or render for it', async () => {+ const { id, revision } = await project();+ await query("INSERT INTO code_animation_project_runs (id, project_id, revision_id, status, data) VALUES ($1, $2, $3, 'running', $4)",+ ['00000000-0000-4000-8000-000000000001', id, revision.id, { kind: 'production-stages', currentRevisionId: revision.id, stages: [] }]);+ unfreeze.mockClear(); render.mockClear();+ const history = await getProductionHistory(id, { limit: 5, offset: 0 });+ expect(history.items.find(item => item.id === '00000000-0000-4000-8000-000000000001')).toMatchObject({ status: 'interrupted', data: { resumable: true } });+ expect(unfreeze).not.toHaveBeenCalled();+ expect(render).not.toHaveBeenCalled();+ });+});diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.jsnew file mode 100644index 0000000000..ac1fb8371a--- /dev/null+++ b/server/services/codeAnimation/stages.js@@ -0,0 +1,367 @@+/**+ * Bounded Code Animation production stages (#9389):+ *+ * style-frame → pilot → inspect → (repair → …) → final render+ *+ * A run starts only from an explicit user request, works on immutable stored+ * revisions, and measures real renders in the HTML-composition sandbox before+ * anything is judged. Every stage records the source hash it measured, a stage+ * run id and timestamps; evidence from another source never passes. Budgets+ * (iterations, time, tokens, render time, disk) stop the run with a resumable+ * status that keeps accepted artifacts. Nothing runs at boot and a restart+ * marks a stranded run interrupted without calling a provider.+ */+import { randomUUID } from 'crypto';+import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';+import { codeAnimationStageRunSchema } from '../../lib/codeAnimationProjects.js';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';+import { htmlCompositionContractSchema, validateRequest } from '../../lib/validation.js';+import { emitCodeAnimationChanged } from '../socket.js';+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 { renderViaMediaQueue, sampleFilm } from './stageRender.js';++export const STAGE_RUN_KIND = 'production-stages';+const STYLE_POINTS = [0.1, 0.5, 0.9];+const PILOT_MAX_FPS = 6;+const PILOT_MAX_SAMPLES = 240;+const RESUMABLE = new Set(['interrupted', 'canceled', 'exhausted', 'failed']);+const BUDGET_CODE = 'CODE_ANIMATION_BUDGET_EXHAUSTED';+const CANCEL_CODE = 'CODE_ANIMATION_RUN_CANCELED';++const activeRuns = new Map();+export const activeStageRunIds = () => [...activeRuns.keys()];++const exhausted = dimension => new ServerError(`Production budget exhausted: ${dimension}`, { status: 409, code: BUDGET_CODE, context: { dimension } });+const canceledError = () => new ServerError('Production run canceled', { status: 409, code: CANCEL_CODE });+const iso = () => new Date().toISOString();+const round3 = value => Math.round(value * 1000) / 1000;++const entryOf = manifest => manifest.entrypoints.find(item => item.role === 'preview')+ || manifest.entrypoints.find(item => item.role === 'render') || manifest.entrypoints[0];++/** The page gets the renderer's clock; a film that already defines portosComposition is left alone. */+function prepareEntry(manifest) {+ const { width, height, fps, durationSeconds } = manifest.format;+ const defaults = `window.ANIMATION_META = ${JSON.stringify({ title: manifest.title, duration: durationSeconds, fps, width, height }).replace(/</g, '\\u003c')};`;+ return html => /portosComposition/.test(html) ? html : injectExportShim(html, `${defaults}\n${buildExportShim({ maxDurationSec: durationSeconds })}`);+}++const sampleTimes = ({ durationSeconds, fps }, pilotFps) => {+ const step = 1 / pilotFps;+ const last = durationSeconds - 1 / fps;+ const times = [];+ for (let t = 0; t < durationSeconds && times.length < PILOT_MAX_SAMPLES; t += step) times.push(round3(Math.min(t, last)));+ return [...new Set(times)];+};+const styleTimes = ({ durationSeconds, fps }) => [...new Set(STYLE_POINTS.map(point => round3(Math.min(point * durationSeconds, durationSeconds - 1 / fps))))];++function snapshot(ctx) {+ const { state } = ctx;+ return { ...state, spent: { ...state.spent, elapsedMs: Date.now() - ctx.startedAt + state.spent.priorElapsedMs } };+}++async function persist(ctx, status = 'running', { completed = false, revisionId = null } = {}) {+ ctx.state.spent.elapsedMs = Date.now() - ctx.startedAt + ctx.state.spent.priorElapsedMs;+ await store.saveStageRun(ctx.runId, status, snapshot(ctx), { completed, revisionId });+ emitCodeAnimationChanged(ctx.projectId);+}++function remainingMs(ctx) {+ const { budgets, spent } = ctx.state;+ const time = budgets.timeSeconds * 1000 - (Date.now() - ctx.startedAt + spent.priorElapsedMs);+ const render = budgets.renderSeconds * 1000 - spent.renderMs;+ return render <= time ? { ms: render, dimension: 'render' } : { ms: time, dimension: 'time' };+}++function checkBudget(ctx) {+ ctx.controller.signal.throwIfAborted();+ const { ms, dimension } = remainingMs(ctx);+ if (ms <= 0) throw exhausted(dimension);+ if (ctx.state.spent.tokens >= ctx.state.budgets.tokens) throw exhausted('tokens');+}++async function reserve(ctx, bytes) {+ if (!await store.reserveRunBytes(ctx.runId, ctx.projectId, bytes)) throw exhausted('disk');+ ctx.state.spent.diskBytes += bytes;+}++/**+ * Run one stage body under the run's cancel signal and the tighter of the time+ * and render budgets. The stage's own record carries the evidence either way.+ */+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() };+ ctx.state.stages.push(entry);+ await persist(ctx);+ const { ms, dimension } = remainingMs(ctx);+ const signal = AbortSignal.any([ctx.controller.signal, AbortSignal.timeout(ms)]);+ const began = Date.now();+ try {+ Object.assign(entry, await body({ signal, entry }), { status: 'completed', completedAt: iso() });+ } catch (error) {+ const canceled = ctx.controller.signal.aborted;+ const outOfBudget = !canceled && signal.aborted;+ Object.assign(entry, { status: canceled ? 'canceled' : outOfBudget ? 'exhausted' : 'failed', completedAt: iso(), error: error.code || error.message });+ if (canceled) throw canceledError();+ if (outOfBudget) throw exhausted(dimension);+ throw error;+ } finally {+ if (renders) ctx.state.spent.renderMs += Date.now() - began;+ await persist(ctx).catch(error => console.error(`❌ Code Animation stage ${key} status could not be saved: ${error.message}`));+ }+ return entry;+}++const reusable = (ctx, key, revision) => ctx.prior.find(stage => stage.key === key && stage.revisionId === revision.id+ && stage.sourceHash === revision.sourceHash && stage.status === 'completed');++/** Build the immutable, staged browser copy of a revision once per run. */+async function stageRevision(ctx, revision) {+ const files = await readProjectFiles(ctx.projectId, revision.id, revision.files);+ await reserve(ctx, revision.totalBytes);+ const entryPath = entryOf(revision.manifest).path;+ const staged = await stageRenderSource(ctx.projectId, ctx.runId, revision.id, files, entryPath, prepareEntry(revision.manifest));+ return { ...revision, files, staged: staged.directory, entryPath };+}++async function styleFrameStage(ctx, revision) {+ const prior = reusable(ctx, 'style-frame', revision);+ if (prior) { ctx.state.stages.push({ ...prior, reusedFrom: ctx.resumedFrom }); return prior; }+ return runStage(ctx, 'style-frame', revision, async ({ signal }) => {+ const times = styleTimes(revision.manifest.format);+ try {+ const { frames, contract } = await ctx.deps.sample(revision.staged, { times: [], captureTimes: times, signal });+ const artifacts = [];+ for (const frame of frames) {+ await reserve(ctx, frame.bytes.length);+ const written = await writeRunArtifact(ctx.projectId, ctx.runId, `style-${revision.id.slice(0, 8)}-${String(frame.t).replace('.', '_')}.png`, frame.bytes);+ artifacts.push({ atSeconds: frame.t, ...written });+ }+ return { contract, artifacts };+ } catch (error) {+ if (signal.aborted || error.code === 'CODE_ANIMATION_UNSAFE_STORAGE' || error.code === BUDGET_CODE) throw error;+ return { artifacts: [], filmError: String(error.message).slice(0, 500) };+ }+ }, { renders: true });+}++async function pilotStage(ctx, revision, style) {+ const prior = reusable(ctx, 'pilot', revision);+ if (prior) { ctx.state.stages.push({ ...prior, reusedFrom: ctx.resumedFrom }); return prior; }+ if (style.filmError) {+ return runStage(ctx, 'pilot', revision, async () => ({ samples: [], skipped: 'The film did not run, so no pilot was measured.' }));+ }+ const { fps } = revision.manifest.format;+ const pilotFps = Math.min(PILOT_MAX_FPS, fps);+ return runStage(ctx, 'pilot', revision, async ({ signal }) => {+ const { samples, contract } = await ctx.deps.sample(revision.staged, { times: sampleTimes(revision.manifest.format, pilotFps), signal });+ return { pilotFps, contract, samples, capturedAt: iso() };+ }, { renders: true });+}++function inspectStage(ctx, revision, style, pilot) {+ 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 };+ 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.' }] };+ } else {+ analysis = analyzeEvidence({ manifest: revision.manifest, pilot, contract: pilot.contract });+ // The final render must be accepted by the same contract the renderer enforces; find that now, not at the end.+ const accepted = htmlCompositionContractSchema.safeParse(pilot.contract);+ if (!accepted.success) {+ const detail = accepted.error.issues.map(issue => issue.message).join('; ');+ analysis.findings.push({ kind: 'renderer-contract', severity: 'error', detail: `The renderer would refuse this film: ${detail}`, measured: { contract: pilot.contract } });+ }+ }+ const capturedAt = iso();+ const findings = analysis.findings.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 });+ return { evidence, findings, verified: analysis.verified, verdict };+ });+}++const repairPrompt = ({ manifest, files, entryPath, findings }) => [+ 'You repair a browser animation. Return the complete corrected HTML document only, in one ```html fence.',+ 'Keep window.ANIMATION_META and window.renderFrame(t): the film must stay a pure function of t on a single <canvas>. No network, fetch or timers for animation.',+ `Brief: ${manifest.brief.concept}`,+ `Format: ${manifest.format.width}x${manifest.format.height}, ${manifest.format.fps}fps, ${manifest.format.durationSeconds}s.`,+ 'Measured findings to fix:',+ ...findings.map(finding => `- [${finding.severity}] ${finding.kind}: ${finding.detail} ${finding.atSeconds != null ? `(at ${finding.atSeconds}s)` : ''}`),+ `Current source (${entryPath}):`, files.find(file => file.path === entryPath).content,+].join('\n');++/**+ * The explicit authoring route: preflight the project's saved provider+ * settings, run one prompt, and reject a substituted route unless the user+ * allowed it. Only reached from a user-started run.+ */+export async function repairViaAuthoringRoute({ project, manifest, files, entryPath, findings }) {+ const [{ preflightProductionProject, _recordEffectiveRoute }, { runPromptThroughProvider }, { getProviderById }, { extractAnimationHtml }] = await Promise.all([+ import('./preflight.js'), import('../promptRunner.js'), import('../providers.js'), import('./prompt.js'),+ ]);+ const preflight = await preflightProductionProject(project.id);+ if (!preflight.resolved || preflight.problems.length) {+ throw new ServerError(`The authoring route is not ready: ${preflight.problems.join(' ') || 'select a provider'}`, { status: 409, code: 'CODE_ANIMATION_AUTHORING_UNAVAILABLE' });+ }+ const provider = await getProviderById(preflight.resolved.providerId);+ const prompt = repairPrompt({ manifest, files, entryPath, findings });+ const result = await runPromptThroughProvider({+ provider, model: preflight.resolved.model, effort: preflight.resolved.effort || undefined, prompt,+ source: 'code-animation-repair', cwd: PATHS.data, allowFallback: preflight.allowFallback,+ });+ const route = _recordEffectiveRoute(preflight.resolved, project.localSettings, result);+ const html = extractAnimationHtml(result.text);+ if (!html) throw new ServerError('The model response did not contain an HTML document', { status: 422, code: 'CODE_ANIMATION_REPAIR_INVALID' });+ return { files: [{ path: entryPath, content: html, encoding: 'utf8' }], tokens: Math.ceil((prompt.length + result.text.length) / 4), effective: route };+}++async function repairStage(ctx, revision, findings) {+ const { spent, budgets } = ctx.state;+ if (spent.iterations >= budgets.iterations) throw exhausted('iterations');+ const errors = findings.filter(finding => finding.severity === 'error');+ let created = null;+ await runStage(ctx, 'repair', revision, async ({ signal, entry }) => {+ const intent = { findingKinds: [...new Set(errors.map(finding => finding.kind))], fromRevisionId: revision.id };+ const out = await ctx.deps.repair({ project: ctx.project, manifest: revision.manifest, files: revision.files, entryPath: revision.entryPath, findings: errors, signal });+ spent.tokens += out.tokens || 0;+ spent.iterations += 1;+ if (out.effective) ctx.state.effective = out.effective;+ const merged = new Map(revision.files.map(file => [file.path, file]));+ for (const file of out.files || []) merged.set(file.path, { path: file.path, content: file.content, encoding: file.encoding || 'utf8' });+ let pkg;+ try {+ pkg = createCodeAnimationPackage(revision.manifest, [...merged.values()]);+ } catch (error) {+ throw new ServerError(`The repaired source is not a valid package: ${error.issues?.[0]?.message || error.message}`, { status: 422, code: 'CODE_ANIMATION_REPAIR_INVALID' });+ }+ const sourceHash = sourceHashOf(pkg.files);+ if (sourceHash === revision.sourceHash) throw new ServerError('The repair did not change the source', { status: 422, code: 'CODE_ANIMATION_REPAIR_NOOP' });+ const totalBytes = pkg.files.reduce((sum, file) => sum + Buffer.byteLength(file.content, file.encoding === 'base64' ? 'base64' : 'utf8'), 0);+ await reserve(ctx, totalBytes);+ const id = randomUUID();+ const storage = await stageProjectFiles(ctx.projectId, id, pkg.files);+ created = {+ id, packageHash: pkg.revisionHash, sourceHash, totalBytes, schemaVersion: pkg.schemaVersion, manifest: pkg.manifest,+ files: pkg.files.map(({ content: _content, ...file }) => file), storage, createdAt: iso(),+ parentRevisionId: revision.id, repair: { runId: ctx.runId, stageRunId: entry.stageRunId, intent },+ };+ await store.commitRepairRevision(ctx.projectId, created);+ ctx.state.repairs.push({ revisionId: id, fromRevisionId: revision.id, sourceHash, findingKinds: intent.findingKinds, tokens: out.tokens || 0 });+ ctx.state.currentRevisionId = id;+ return { intent, toRevisionId: id, toSourceHash: sourceHash };+ });+ return created;+}++async function finalStage(ctx, revision, verdictStage) {+ // 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 });+ 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 } };+ }, { renders: true });+ ctx.state.output = { ...stage.output, stageRunId: stage.stageRunId, verifiedDimensions: verdictStage.verified, unverified: verdict.unverified };+}++async function execute(ctx, start) {+ let revision = start;+ for (;;) {+ revision = await stageRevision(ctx, revision);+ const style = await styleFrameStage(ctx, revision);+ const pilot = await pilotStage(ctx, revision, style);+ const inspected = await inspectStage(ctx, revision, style, pilot);+ 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);+ revision = await repairStage(ctx, revision, inspected.findings);+ }+}++async function finish(ctx, run) {+ let status = 'completed';+ let outcome = null;+ try {+ await run();+ } catch (error) {+ if (error.code === CANCEL_CODE) { status = 'canceled'; outcome = { stopReason: 'canceled' }; }+ else if (error.code === BUDGET_CODE) { status = 'exhausted'; outcome = { stopReason: error.context?.dimension || 'budget' }; }+ else {+ status = 'failed';+ outcome = { stopReason: 'failed', error: { code: error.code || 'RUN_FAILED', message: String(error.message).slice(0, 500) } };+ console.error(`❌ Code Animation production run ${ctx.runId.slice(0, 8)} failed: ${error.message}`);+ }+ }+ Object.assign(ctx.state, outcome || { stopReason: null }, { resumable: status !== 'completed' });+ activeRuns.delete(ctx.runId);+ await persist(ctx, status, { completed: true, revisionId: ctx.state.currentRevisionId }).catch(error => {+ console.error(`❌ Code Animation production run ${ctx.runId.slice(0, 8)} final status could not be saved: ${error.message}`);+ });+ console.log(`🎞️ Code Animation production run ${ctx.runId.slice(0, 8)} ${status}${ctx.state.stopReason ? ` (${ctx.state.stopReason})` : ''}`);+ return status;+}++const defaultDeps = { sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute };++/**+ * Start a user-requested production run. Resolves with the persisted run once+ * it is `running`; `done` settles with the terminal status (tests await it, the+ * route does not). The project may have only one live run.+ */+export async function startProductionStageRun(projectId, input, deps = {}) {+ const request = validateRequest(codeAnimationStageRunSchema, input ?? {});+ const project = await store.getProjectRecord(projectId);+ if (!project) throw new ServerError('Production project not found', { status: 404, code: 'NOT_FOUND' });+ let prior = null;+ if (request.resumeFromRunId) {+ prior = await store.getRunRecord(projectId, request.resumeFromRunId);+ if (!prior || prior.data.kind !== STAGE_RUN_KIND) throw new ServerError('Run not found', { status: 404, code: 'NOT_FOUND' });+ if (!RESUMABLE.has(prior.status) || !prior.data.resumable) throw new ServerError('Only a stopped run can be resumed', { status: 409, code: 'CODE_ANIMATION_RUN_NOT_RESUMABLE' });+ }+ const revisionId = prior ? prior.data.currentRevisionId : request.revisionId || project.candidateRevisionId || project.acceptedRevisionId;+ const record = revisionId ? await store.getRevisionRecord(projectId, revisionId) : null;+ if (!record) throw new ServerError('Import a source revision before running production stages', { status: 409, code: 'CODE_ANIMATION_NO_REVISION' });+ if (record.manifest.renderer.kind !== 'browser') {+ throw new ServerError('Only browser-rendered projects can run these stages', { status: 409, code: 'CODE_ANIMATION_RENDERER_UNSUPPORTED' });+ }+ const revision = { ...record };+ const runId = randomUUID();+ const priorSpent = prior?.data.spent;+ const state = {+ kind: STAGE_RUN_KIND, sourceRevisionId: revision.id, currentRevisionId: revision.id, sourceHash: revision.sourceHash,+ 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 },+ stages: [], findings: [], verdict: null, output: null, repairs: prior?.data.repairs ?? [],+ resumedFrom: prior?.id ?? null, stopReason: null, resumable: false, executed: true,+ };+ const ctx = {+ runId, projectId, project, state, deps: { ...defaultDeps, ...deps }, controller: new AbortController(),+ startedAt: Date.now(), prior: prior?.data.stages ?? [], resumedFrom: prior?.id ?? null,+ };+ await store.startStageRun(runId, projectId, snapshot(ctx), activeStageRunIds());+ activeRuns.set(runId, { controller: ctx.controller, projectId });+ emitCodeAnimationChanged(projectId);+ console.log(`🎞️ Code Animation production run ${runId.slice(0, 8)} started on revision ${revision.id.slice(0, 8)}`);+ // Process boundary: nothing may reject unhandled out of the background run.+ const done = finish(ctx, () => execute(ctx, revision)).catch(error => {+ console.error(`❌ Code Animation production run ${runId.slice(0, 8)} crashed: ${error.message}`);+ activeRuns.delete(runId);+ return 'failed';+ });+ return { run: { id: runId, status: 'running', ...snapshot(ctx) }, done };+}++/** Stop an active run: owned renders are cancelled and accepted artifacts stay. */+export function cancelProductionStageRun(projectId, runId) {+ const active = activeRuns.get(runId);+ if (!active || active.projectId !== projectId) throw new ServerError('That run is not active', { status: 409, code: 'CODE_ANIMATION_RUN_NOT_ACTIVE' });+ active.controller.abort(canceledError());+ return { id: runId, canceling: true };+}diff --git a/server/services/codeAnimation/stages.realBrowser.db.test.js b/server/services/codeAnimation/stages.realBrowser.db.test.jsnew file mode 100644index 0000000000..2e96c84807--- /dev/null+++ b/server/services/codeAnimation/stages.realBrowser.db.test.js@@ -0,0 +1,122 @@+// Real-browser acceptance for the bounded production stages (#9389): a synthetic+// original short is staged, rendered and measured by real Chrome, repaired into a+// 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 { existsSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import { execFileSync, spawn } from 'node:child_process';+import { join } from 'node:path';+import { chromium } from 'playwright-core';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';+import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';+import { _cleanupTestBrowser, _waitForTestChrome } from '../htmlComposition/testBrowserCleanup.js';++let endpoint;+vi.mock('../browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));+vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-code-animation-stages-'),+}));+vi.mock('../../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-code-animation-stages-'),+}));++const { checkHealth, ensureSchema, query, close } = await import('../../lib/db.js');+const { requireDbOrSkip } = await import('../../lib/dbTestGate.js');+const { createCodeAnimationPackage } = await import('../../lib/codeAnimationPackage.js');+const { createProductionProject, getProductionHistory, importProductionPackage } = await import('./projects.js');+const { startProductionStageRun } = await import('./stages.js');+const { renderComposition } = await import('../htmlComposition/index.js');+const { PATHS } = await import('../../lib/fileUtils.js');++const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));+const dbReady = requireDbOrSkip('codeAnimation/stages.realBrowser.db.test', health.connected, health.error);+if (dbReady) await ensureSchema();++const chrome = [process.env.CHROME_PATH, chromium.executablePath(),+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+].find(path => path && existsSync(path));+const ffmpeg = await findFfmpeg();+const ffprobe = await findFfprobe();++const FILM = motion => `<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0">+<canvas id="film" width="1280" height="720"></canvas><script>+window.ANIMATION_META = { title: 'Original short', duration: 2, fps: 12, width: 1280, height: 720 };+const MOVE = ${motion};+window.renderFrame = (t) => {+ const context = document.getElementById('film').getContext('2d');+ context.fillStyle = '#223'; context.fillRect(0, 0, 1280, 720);+ context.fillStyle = '#fc3'; context.fillRect(20 + (MOVE ? t * 200 : 0), 120, 80, 80);+};+</script></body></html>`;+const manifest = {+ title: 'Original short', brief: { concept: 'A square slides across a dark field.', cast: '', onScreenText: '' },+ 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 },+};++let proc;+let browser;+let projectId;++describe.skipIf(!dbReady || !chrome || !ffmpeg || !ffprobe)('Production stages with real Chrome and ffmpeg', () => {+ beforeAll(async () => {+ const profile = join(lazyTempDataRoot('portos-code-animation-stages-'), 'chrome-test-profile');+ proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });+ try {+ const ws = await _waitForTestChrome(proc);+ endpoint = new URL(ws).origin.replace('ws:', 'http:');+ browser = await chromium.connectOverCDP(endpoint);+ } catch (error) {+ await _cleanupTestBrowser({ browser, proc, cleanup: cleanupTempDataRoots });+ proc = undefined;+ throw error;+ }+ }, 30000);++ afterAll(async () => {+ if (projectId) await query('DELETE FROM code_animation_projects WHERE id = $1', [projectId]);+ await _cleanupTestBrowser({ browser, proc, cleanup: cleanupTempDataRoots });+ await close();+ });++ it('turns a frozen original into measured findings, a repaired revision and a real MP4, with a real style frame and pilot', async () => {+ projectId = (await createProductionProject({ manifest })).id;+ await importProductionPackage(projectId, createCodeAnimationPackage(manifest, [{ path: 'index.html', content: FILM(false) }]));+ const repair = vi.fn(async ({ files, entryPath }) => ({+ files: [{ path: entryPath, content: files.find(file => file.path === entryPath).content.replace('const MOVE = false;', 'const MOVE = true;') }],+ }));+ const { done } = await startProductionStageRun(projectId, {}, {+ repair, render: ({ directory }) => renderComposition({ directory, jobId: 'stages-acceptance' }),+ });+ expect(await done).toBe('completed');++ const [{ data }] = (await getProductionHistory(projectId, { limit: 1, offset: 0 })).items;+ const inspections = data.stages.filter(stage => stage.key === 'inspect');+ expect(inspections[0].findings.map(finding => finding.kind)).toContain('frozen-film');+ expect(inspections[0].verdict.status).toBe('fail');+ expect(inspections[1]).toMatchObject({ findings: [], verdict: { status: 'pass' } });+ expect(repair).toHaveBeenCalledTimes(1);++ // Real, measured evidence: three distinct style frames and a pilot of distinct renders.+ const styleFrame = data.stages.filter(stage => stage.key === 'style-frame')[1];+ expect(styleFrame.artifacts).toHaveLength(3);+ for (const artifact of styleFrame.artifacts) {+ const bytes = await readFile(join(PATHS.data, artifact.relativePath));+ expect([...bytes.subarray(1, 4)].map(byte => String.fromCharCode(byte)).join('')).toBe('PNG');+ }+ expect(new Set(styleFrame.artifacts.map(artifact => artifact.sha256)).size).toBe(3);+ const pilot = data.stages.filter(stage => stage.key === 'pilot')[1];+ expect(new Set(pilot.samples.map(sample => sample.renderHash)).size).toBe(pilot.samples.length);++ // The final output is a real H.264 file of exactly duration × fps frames.+ const video = join(PATHS.videos, data.output.filename);+ const 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);+ }, 180000);+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex b409e7dac4..5cebf21473 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -20,6 +20,8 @@ export const DB_TEST_INCLUDE = ['../scripts/perf/collectionFixture.db.test.js','services/appQuality.db.test.js','**/db.test.js',+ 'services/codeAnimation/stages.db.test.js',+ 'services/codeAnimation/stages.realBrowser.db.test.js','services/mediaAssetIndex/galleryCollections.db.test.js','services/dbAdmin.db.test.js','services/backup.db.test.js',