Skip to content

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

feat: Production stage-run UI and optional visual-reviewer pass for Code Animation (#9434)

[._.]/ Adam Eivy7ea611f021dd
diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsx
index 7ed026c705..3c6ff02afe 100644
--- a/client/src/components/codeAnimation/ProductionProjects.jsx
+++ b/client/src/components/codeAnimation/ProductionProjects.jsx
@@ -16,6 +16,7 @@ import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
import ProductionProjectForm from './ProductionProjectForm';
import ProductionPreflight from './ProductionPreflight';
import ProductionContainment from './ProductionContainment';
+import ProductionStageRuns, { isStageRun } from './ProductionStageRuns';
const EVENTS = ['code-animation:changed'];
const buttonClass = 'rounded border border-port-border px-3 py-2 text-sm hover:border-port-accent disabled:opacity-50';
@@ -125,8 +126,9 @@ 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} />
<ul className="space-y-2">
- {history.items.map(run => <li key={run.id} className="min-w-0 space-y-1 rounded border border-port-border p-3">
+ {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>
<p className="break-all text-xs text-gray-400">{run.data.packageHash}</p>
<p className="text-xs text-gray-400">{formatBytes(run.data.totalBytes || 0)} · Source execution: {run.data.executed ? 'Recorded' : 'None'}</p>
diff --git a/client/src/components/codeAnimation/ProductionProjects.test.jsx b/client/src/components/codeAnimation/ProductionProjects.test.jsx
index 04ae3aa7d5..037285f475 100644
--- a/client/src/components/codeAnimation/ProductionProjects.test.jsx
+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx
@@ -11,6 +11,7 @@ vi.mock('../../services/apiCodeAnimation', () => ({
listCodeAnimationProjects: vi.fn(), createCodeAnimationProject: vi.fn(), getCodeAnimationProject: vi.fn(),
updateCodeAnimationProject: vi.fn(), importCodeAnimationPackage: vi.fn(), acceptCodeAnimationSource: vi.fn(),
getCodeAnimationProjectBrief: vi.fn(), getCodeAnimationRevisionPackage: vi.fn(), listCodeAnimationProjectHistory: vi.fn(),
+ startCodeAnimationStageRun: vi.fn(), cancelCodeAnimationStageRun: vi.fn(),
}));
import * as api from '../../services/apiCodeAnimation';
import ProductionProjects from './ProductionProjects';
@@ -86,6 +87,36 @@ describe('Production project rendered interactions', () => {
expect(api.importCodeAnimationPackage).toHaveBeenCalledWith(project.id, source, { silent: true });
});
+ it('confirms before starting a stage run, then shows live stages, unverified dimensions, cancel and resume', async () => {
+ const user = userEvent.setup();
+ const stage = (key, extra = {}) => ({ key, stageRunId: key + '-id', status: 'completed', ...extra });
+ const runData = (overrides = {}) => ({
+ kind: 'production-stages', spent: { elapsedMs: 2000, iterations: 0 }, budgets: project.budgets, resumable: false, findings: [],
+ stages: [stage('style-frame', { artifacts: [{ atSeconds: 1, relativePath: 'code-animations/example/style.png' }] }), stage('inspect', { verified: ['audio'] })],
+ verdict: { status: 'pass', reason: null, unverified: [{ dimension: 'semantic-visual', reason: 'No visual reviewer pass ran.' }] },
+ ...overrides,
+ });
+ const stopped = { id: 'run-stopped', status: 'canceled', createdAt: '2026-01-01T00:00:00Z', data: runData({ resumable: true, stopReason: 'canceled' }) };
+ api.listCodeAnimationProjectHistory.mockResolvedValue(page([stopped]));
+ api.preflightCodeAnimationProject.mockResolvedValue({ problems: [], capabilities: { imageInputAccepted: true } });
+ api.startCodeAnimationStageRun.mockResolvedValue({ id: 'run-new' });
+ renderPage();
+ expect(await screen.findByText(/Unverified: semantic-visual/)).toBeInTheDocument();
+ expect(screen.getByText('Verified: audio')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Style frame at 1s' })).toHaveAttribute('href', '/data/code-animations/example/style.png');
+
+ await user.click(screen.getByRole('button', { name: 'Run production stages' }));
+ expect(api.startCodeAnimationStageRun).not.toHaveBeenCalled();
+ expect(await screen.findByText(/A repair calls/)).toHaveTextContent('example-provider');
+ await user.click(screen.getByLabelText(/visual review/));
+ await user.click(screen.getByRole('button', { name: 'Start run' }));
+ await waitFor(() => expect(api.startCodeAnimationStageRun).toHaveBeenCalledWith(project.id, { visualReview: true }, { silent: true }));
+
+ await user.click(screen.getByRole('button', { name: 'Resume run' }));
+ await waitFor(() => expect(api.startCodeAnimationStageRun).toHaveBeenCalledWith(project.id, { resumeFromRunId: 'run-stopped' }, { silent: true }));
+ expect(screen.queryByText(/Package import/)).toBeNull();
+ });
+
it('preserves the authoring pin across renderer edits and checks only saved settings', async () => {
const user = userEvent.setup();
renderPage();
diff --git a/client/src/components/codeAnimation/ProductionStageRuns.jsx b/client/src/components/codeAnimation/ProductionStageRuns.jsx
new file mode 100644
index 0000000000..29fa55844e
--- /dev/null
+++ b/client/src/components/codeAnimation/ProductionStageRuns.jsx
@@ -0,0 +1,109 @@
+import { useState } from 'react';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import {
+ cancelCodeAnimationStageRun, preflightCodeAnimationProject, startCodeAnimationStageRun,
+} from '../../services/apiCodeAnimation';
+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 RESUMABLE = new Set(['interrupted', 'canceled', 'exhausted', 'failed']);
+
+export const isStageRun = run => run?.data?.kind === 'production-stages';
+
+/** Verified and unverified dimensions are drawn differently on purpose: unverified is never a pass. */
+function Verdict({ verdict, verified = [] }) {
+ if (!verdict) return null;
+ return <div className="space-y-1 text-xs">
+ <p>Verdict: <strong>{verdict.status}</strong>{verdict.reason ? ` — ${verdict.reason}` : ''}</p>
+ {verified.length > 0 && <p className="text-port-success">Verified: {verified.join(', ')}</p>}
+ {(verdict.unverified || []).map(item => <p key={item.dimension} className="rounded border border-dashed border-port-warning px-2 py-1 text-port-warning">Unverified: {item.dimension} — {item.reason}</p>)}
+ </div>;
+}
+
+function StageRun({ run, busy, onResume, onCancel }) {
+ 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 || []);
+ const reviewer = [...data.stages].reverse().find(stage => stage.key === 'review' && stage.reviewer)?.reviewer;
+ const running = run.status === 'running';
+ return <li className="min-w-0 space-y-2 rounded border border-port-border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
+ <span>Production run · <strong>{run.status}</strong>{data.stopReason ? ` (${data.stopReason})` : ''}</span>
+ <span className="text-xs text-gray-400">{timeAgo(run.createdAt)} · {formatRuntime(data.spent?.elapsedMs || 0)} · {formatCount(data.spent?.iterations || 0)}/{formatCount(data.budgets?.iterations || 0)} repairs</span>
+ </div>
+ <ol className="space-y-1 text-xs" aria-label="Stages">
+ {data.stages.map(stage => <li key={stage.stageRunId} className="flex flex-wrap justify-between gap-2">
+ <span>{STAGE_LABELS[stage.key] || stage.key}{stage.reusedFrom ? ' (reused)' : ''}</span>
+ <span className={stage.status === 'failed' || stage.status === 'exhausted' ? 'text-port-error' : 'text-gray-400'}>{stage.status}{stage.error ? ` · ${stage.error}` : ''}</span>
+ </li>)}
+ </ol>
+ {reviewer && <p className="text-xs text-gray-400">Reviewed by {reviewer.providerId} · {reviewer.model || 'default model'}</p>}
+ <Verdict verdict={data.verdict} verified={inspect?.verified} />
+ {data.findings?.length > 0 && <ul className="space-y-1 text-xs" aria-label="Findings">
+ {data.findings.map((finding, index) => <li key={index} className={finding.severity === 'error' ? 'text-port-error' : 'text-port-warning'}>
+ [{finding.severity}] {finding.kind}: {finding.detail}{finding.atSeconds != null ? ` (at ${finding.atSeconds}s)` : ''} <span className="text-gray-400">· {timeAgo(finding.capturedAt)}</span>
+ </li>)}
+ </ul>}
+ {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>}
+ {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>}
+ </div>
+ </li>;
+}
+
+/**
+ * Starts, watches, cancels and resumes bounded production stage runs. The run
+ * 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 }) {
+ const [confirming, setConfirming] = useState(false);
+ const [capabilities, setCapabilities] = useState(null);
+ const [visualReview, setVisualReview] = useState(false);
+ const [act, busy] = useAsyncAction(async operation => operation());
+ const live = runs.some(run => run.status === 'running');
+ const settings = project.localSettings || {};
+ const hasSource = Boolean(project.candidateRevisionId || project.acceptedRevisionId);
+
+ const openConfirm = () => act(async () => {
+ setCapabilities((await preflightCodeAnimationProject(project.id, { silent: true })).capabilities || null);
+ setConfirming(true);
+ });
+ const start = input => act(async () => {
+ await startCodeAnimationStageRun(project.id, input, { silent: true });
+ 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>
+ {!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">
+ <p>A repair calls <strong>{settings.providerId || 'no provider selected'}</strong> · {settings.model || 'default model'} · effort {settings.effort || 'unspecified'}.</p>
+ <p className="text-xs text-gray-400">Budgets: {formatCount(project.budgets.iterations)} repairs · {formatCount(project.budgets.timeSeconds)}s · {formatCount(project.budgets.tokens)} tokens · {formatCount(project.budgets.renderSeconds)}s render.</p>
+ {canReview
+ ? <div className="flex items-center gap-2">
+ <input id="cap-visual-review" type="checkbox" checked={visualReview} onChange={event => setVisualReview(event.target.checked)} />
+ <label htmlFor="cap-visual-review" className="text-sm">Also send the style frames to this route for a visual review (advisory)</label>
+ </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={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}
+ onCancel={runId => act(async () => cancelCodeAnimationStageRun(project.id, runId, { silent: true }))}
+ onResume={runId => start({ resumeFromRunId: runId })} />)}
+ </ul>
+ </section>;
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 6d50e5823f..746ed5b082 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -115,7 +115,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). |
| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |
-| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, portable package download, and opt-in Production project settings, immutable candidate/accepted source imports, brief handoff and paged run history. |
+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, portable package download, and opt-in Production project settings, immutable candidate/accepted source imports, brief handoff paged run history, and bounded production stage runs (start, cancel, resume). |
| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. |
| `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. |
| `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |
diff --git a/server/lib/codeAnimationProjects.js b/server/lib/codeAnimationProjects.js
index 09a32ae832..0dbb9ae1dc 100644
--- a/server/lib/codeAnimationProjects.js
+++ b/server/lib/codeAnimationProjects.js
@@ -42,4 +42,6 @@ export const codeAnimationProjectPatchSchema = partialWithoutDefaults(codeAnimat
export const codeAnimationStageRunSchema = z.object({
revisionId: z.string().uuid().optional(),
resumeFromRunId: z.string().uuid().optional(),
+ // Opt-in: ask the project's vision-capable authoring route to review the style frames.
+ visualReview: z.boolean().optional(),
}).strict().refine(value => !(value.revisionId && value.resumeFromRunId), 'Choose a revision or a run to resume, not both');
diff --git a/server/services/codeAnimation/evidence.js b/server/services/codeAnimation/evidence.js
index 0ef3998da2..768bd825c2 100644
--- a/server/services/codeAnimation/evidence.js
+++ b/server/services/codeAnimation/evidence.js
@@ -34,7 +34,8 @@ function frozenSpans(samples) {
* 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 }) {
+/** `review` is the reviewer stage record when a visual reviewer pass ran; otherwise semantic-visual stays unverified. */
+export function analyzeEvidence({ manifest, pilot, contract, review = null }) {
const findings = [];
const { durationSeconds, width, height, fps } = manifest.format;
const add = (kind, severity, detail, extra = {}) => findings.push({ kind, severity, detail, ...extra });
@@ -78,7 +79,8 @@ export function analyzeEvidence({ manifest, pilot, contract }) {
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.' });
+ if (review) verified.push('semantic-visual');
+ else unverified.push({ dimension: 'semantic-visual', reason: 'No visual reviewer pass ran; style fit and composition quality are not judged.' });
return { findings, verified, unverified };
}
diff --git a/server/services/codeAnimation/stages.db.test.js b/server/services/codeAnimation/stages.db.test.js
index e09c53b72b..b7efa80992 100644
--- a/server/services/codeAnimation/stages.db.test.js
+++ b/server/services/codeAnimation/stages.db.test.js
@@ -99,6 +99,24 @@ describe.skipIf(!ready)('Production stage runs', () => {
}
});
+ it('records an opt-in visual review as advisory evidence and only then reports semantic-visual verified', async () => {
+ const { id } = await project();
+ const review = vi.fn(async ({ artifacts }) => ({ findings: [{ detail: 'Palette ignores the style guide.', atSeconds: 1 }], tokens: 10, reviewer: { providerId: 'example-provider', model: 'example-model' }, seen: artifacts.length }));
+ const moving = vi.fn(async ({ files, entryPath }) => ({ files: [{ path: entryPath, content: files.find(file => file.path === entryPath).content.replace('FROZEN', 'MOVING') }], tokens: 1 }));
+ const off = await startProductionStageRun(id, {}, { sample, repair: moving, render, review });
+ expect(await off.done).toBe('completed');
+ expect(review).not.toHaveBeenCalled();
+
+ const second = await project();
+ const on = await startProductionStageRun(second.id, { visualReview: true }, { sample, repair: moving, render, review });
+ expect(await on.done).toBe('completed');
+ expect(review).toHaveBeenCalled();
+ const [saved] = (await getProductionHistory(second.id, { limit: 1, offset: 0 })).items;
+ expect(saved.data.stages.find(stage => stage.key === 'review').reviewer).toEqual({ providerId: 'example-provider', model: 'example-model' });
+ expect(saved.data.findings.some(finding => finding.kind === 'visual-review' && finding.severity === 'warning')).toBe(true);
+ expect(saved.data.verdict.unverified.map(item => item.dimension)).not.toContain('semantic-visual');
+ });
+
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();
diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.js
index 0d2314c1ff..2ca6265f32 100644
--- a/server/services/codeAnimation/stages.js
+++ b/server/services/codeAnimation/stages.js
@@ -1,7 +1,7 @@
/**
* Bounded Code Animation production stages (#9389):
*
- * style-frame → pilot → inspect → (repair → …) → final render
+ * style-frame → pilot → [review] → 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
@@ -12,6 +12,7 @@
* marks a stranded run interrupted without calling a provider.
*/
import { randomUUID } from 'crypto';
+import { join } from 'path';
import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
import { codeAnimationStageRunSchema } from '../../lib/codeAnimationProjects.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -164,7 +165,63 @@ async function pilotStage(ctx, revision, style) {
}, { renders: true });
}
-function inspectStage(ctx, revision, style, pilot) {
+const reviewPrompt = ({ manifest, artifacts }) => [
+ 'You review still frames of a generated browser animation against its brief. Judge style fit and composition only; do not suggest code.',
+ `Brief: ${manifest.brief.concept}`,
+ `Style guide: ${manifest.styleGuide || 'unspecified'}`,
+ `Frames, in order, are at seconds: ${artifacts.map(item => item.atSeconds).join(', ')}.`,
+ 'Reply with JSON only: {"findings":[{"detail":"<one sentence>","atSeconds":<number|null>}]}. An empty list means the frames fit the brief.',
+].join('\n');
+
+/** The explicit vision route: the project's own saved authoring settings, images attached, no fallback unless the user allowed it. */
+async function reviewViaAuthoringRoute({ project, manifest, artifacts }) {
+ const [{ preflightProductionProject, _recordEffectiveRoute }, { runPromptThroughProvider }, { getProviderById }] = await Promise.all([
+ import('./preflight.js'), import('../promptRunner.js'), import('../providers.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' });
+ }
+ if (!preflight.capabilities.imageInputAccepted) {
+ throw new ServerError('The authoring route cannot receive images, so it cannot review frames.', { status: 409, code: 'CODE_ANIMATION_REVIEW_UNSUPPORTED' });
+ }
+ const provider = await getProviderById(preflight.resolved.providerId);
+ const prompt = reviewPrompt({ manifest, artifacts });
+ const result = await runPromptThroughProvider({
+ provider, model: preflight.resolved.model, effort: preflight.resolved.effort || undefined, prompt,
+ screenshots: artifacts.map(item => join(PATHS.data, item.relativePath)),
+ source: 'code-animation-review', cwd: PATHS.data, allowFallback: preflight.allowFallback, toolFree: true,
+ });
+ const route = _recordEffectiveRoute(preflight.resolved, project.localSettings, result);
+ const parsed = parseReviewFindings(result.text);
+ if (!parsed) throw new ServerError('The reviewer response was not valid JSON findings', { status: 422, code: 'CODE_ANIMATION_REVIEW_INVALID' });
+ return { findings: parsed, tokens: Math.ceil((prompt.length + result.text.length) / 4), reviewer: { providerId: route.effective.providerId, model: route.effective.model }, effective: route };
+}
+
+/** Pull `{findings:[…]}` out of a reply that may be fenced or wrapped in prose; null when it carries none. */
+function parseReviewFindings(text) {
+ const match = String(text ?? '').match(/\{[\s\S]*\}/);
+ if (!match) return null;
+ let value;
+ try { value = JSON.parse(match[0]); } catch { return null; }
+ if (!Array.isArray(value?.findings)) return null;
+ return value.findings.filter(item => typeof item?.detail === 'string' && item.detail.trim()).slice(0, 10)
+ .map(item => ({ detail: item.detail.trim().slice(0, 500), atSeconds: Number.isFinite(item.atSeconds) ? item.atSeconds : null }));
+}
+
+async function reviewStage(ctx, revision, style) {
+ const prior = reusable(ctx, 'review', revision);
+ if (prior) { ctx.state.stages.push({ ...prior, reusedFrom: ctx.resumedFrom }); return prior; }
+ if (!style.artifacts?.length) return null;
+ return runStage(ctx, 'review', revision, async () => {
+ const out = await ctx.deps.review({ project: ctx.project, manifest: revision.manifest, artifacts: style.artifacts });
+ ctx.state.spent.tokens += out.tokens || 0;
+ if (out.effective) ctx.state.effective = out.effective;
+ return { reviewer: out.reviewer, reviewFindings: out.findings, evaluatedStageRunId: style.stageRunId };
+ });
+}
+
+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 };
@@ -172,7 +229,7 @@ function inspectStage(ctx, revision, style, pilot) {
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 });
+ analysis = analyzeEvidence({ manifest: revision.manifest, pilot, contract: pilot.contract, review });
// 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) {
@@ -181,7 +238,8 @@ function inspectStage(ctx, revision, style, pilot) {
}
}
const capturedAt = iso();
- const findings = analysis.findings.map(finding => ({ ...finding, sourceHash: revision.sourceHash, revisionId: revision.id, evidenceStageRunIds: [style.stageRunId, pilot.stageRunId], capturedAt }));
+ 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 });
return { evidence, findings, verified: analysis.verified, verdict };
});
@@ -277,7 +335,8 @@ async function execute(ctx, start) {
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);
+ const review = ctx.state.visualReview ? await reviewStage(ctx, revision, style) : null;
+ 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);
@@ -308,7 +367,7 @@ async function finish(ctx, run) {
return status;
}
-const defaultDeps = { sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute };
+const defaultDeps = { sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute, review: reviewViaAuthoringRoute };
/**
* Start a user-requested production run. Resolves with the persisted run once
@@ -338,6 +397,7 @@ export async function startProductionStageRun(projectId, input, deps = {}) {
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 },
+ visualReview: request.visualReview === true,
stages: [], findings: [], verdict: null, output: null, repairs: prior?.data.repairs ?? [],
resumedFrom: prior?.id ?? null, stopReason: null, resumable: false, executed: true,
};