Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(runs): add signed run receipts that compare expected and observed results per stage, with a /runs page and MCP Studio tools

nirholasa83f8e8ce212
diff --git a/api/_lib/migrations/20261014000000_run_receipts.sql b/api/_lib/migrations/20261014000000_run_receipts.sql
new file mode 100644
index 000000000..ac84bcf34
--- /dev/null
+++ b/api/_lib/migrations/20261014000000_run_receipts.sql
@@ -0,0 +1,22 @@
+-- Run receipts: one signed record per Studio generation, stating what each stage
+-- was expected to do, what it actually did, and a verdict.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261014000000_run_receipts.sql
+-- Idempotent and additive. Writers: api/_lib/run-receipt-store.js. Docs: docs/run-receipts.md.
+
+CREATE TABLE IF NOT EXISTS run_receipts (
+ id text PRIMARY KEY,
+ tool text NOT NULL,
+ outcome text NOT NULL,
+ -- sha256 prefix of the job handle, so check_job can complete a pending
+ -- receipt without the handle itself ever being stored.
+ job_ref text,
+ body jsonb NOT NULL,
+ sha256 text NOT NULL,
+ signature text,
+ signer text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS run_receipts_created_idx ON run_receipts (created_at DESC);
+CREATE INDEX IF NOT EXISTS run_receipts_job_ref_idx ON run_receipts (job_ref) WHERE job_ref IS NOT NULL;
diff --git a/api/_lib/run-receipt-store.js b/api/_lib/run-receipt-store.js
new file mode 100644
index 000000000..b7852af67
--- /dev/null
+++ b/api/_lib/run-receipt-store.js
@@ -0,0 +1,294 @@
+// Run receipts: the I/O half. Signing key, persistence, rig inspection, stats.
+// The pure record (stages, verdicts, canonical bytes, signature) lives in
+// run-receipt.js; this module is everything that touches the network, the
+// database or the environment.
+//
+// Fail-open throughout, like every other forge instrumentation module: a
+// receipt is a record OF the run, never a gate ON it. No database, no signing
+// key, an unreadable file, a slow write: each degrades to a receipt that says
+// so (unsigned, unstored, "could not verify"), and the generation the caller
+// asked for is returned exactly as before.
+//
+// Schema: api/_lib/migrations/20261014000000_run_receipts.sql.
+
+import { sql } from './db.js';
+import { BACKENDS } from './forge-tiers.js';
+import { analyzeGlb } from '../../src/rig-report.js';
+import { isReceiptId, signReceipt, receiptHash, verifyReceipt } from './run-receipt.js';
+
+// A write gets this long before the tool answers without waiting for it. The
+// row still lands; the caller just does not sit behind a slow database.
+const WRITE_WAIT_MS = 2_500;
+// The glTF JSON chunk sits at the head of the file. 512 KB covers it for every
+// rigged avatar the pipeline produces; anything larger is read in full up to
+// the cap below.
+const RIG_PREFIX_BYTES = 512 * 1024;
+const RIG_MAX_BYTES = 48 * 1024 * 1024;
+const RIG_INSPECT_TIMEOUT_MS = 10_000;
+
+// ── signing ──────────────────────────────────────────────────────────────────
+
+// The same issuer key that signs 3D provenance credentials. Run receipts carry
+// their own domain tag (three-run-receipt/v1), so a signature from one scheme
+// can never be replayed as the other. Loaded lazily: the decoder lives beside
+// the Solana attestation stack, which no generation should pay to import.
+let keyPromise;
+function signingKey() {
+ if (!keyPromise) {
+ keyPromise = (async () => {
+ const raw = process.env.ATTEST_AGENT_SECRET_KEY || '';
+ if (!raw.trim()) return null;
+ try {
+ const { decodeAttesterSecret } = await import('./attest-event.js');
+ return decodeAttesterSecret(raw);
+ } catch (err) {
+ console.warn('[run-receipt] signing key unreadable, receipts ship unsigned:', err?.message || err);
+ return null;
+ }
+ })();
+ }
+ return keyPromise;
+}
+
+/** Test seam: forget the cached key so a test can swap the env. */
+export function resetSigningKeyCache() {
+ keyPromise = undefined;
+}
+
+/** Seal a finished receipt: signed when the issuer key is configured, hashed always. */
+export async function sealReceipt(receipt) {
+ const key = await signingKey();
+ if (key) {
+ try {
+ return signReceipt(receipt, key);
+ } catch (err) {
+ console.warn('[run-receipt] sign failed, sealing unsigned:', err?.message || err);
+ }
+ }
+ return { receipt, sha256: receiptHash(receipt), signature: null, signer: null };
+}
+
+/** The public half of the issuer key, for pinning. Null when unsigned. */
+export async function receiptSignerPublicKey() {
+ const key = await signingKey();
+ if (!key) return null;
+ const { ed25519 } = await import('@noble/curves/ed25519.js');
+ const bs58 = (await import('bs58')).default;
+ return bs58.encode(ed25519.getPublicKey(key.slice(0, 32)));
+}
+
+// ── persistence ──────────────────────────────────────────────────────────────
+
+function bounded(promise, ms) {
+ let timer;
+ return Promise.race([
+ promise.then(
+ () => true,
+ (err) => {
+ console.warn('[run-receipt] write failed:', err?.message || err);
+ return false;
+ },
+ ),
+ new Promise((resolve) => {
+ timer = setTimeout(() => resolve(false), ms);
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+/**
+ * Upsert a sealed receipt. Resolves true once stored, false when the database
+ * is absent, failed, or slower than the wait budget (the write keeps going).
+ */
+export function saveReceipt(envelope, { jobRef = null } = {}) {
+ const r = envelope?.receipt;
+ if (!r || !isReceiptId(r.id)) return Promise.resolve(false);
+ const write = sql`
+ insert into run_receipts (id, tool, outcome, job_ref, body, sha256, signature, signer)
+ values (
+ ${r.id}, ${r.tool}, ${r.outcome}, ${jobRef},
+ ${JSON.stringify(r)}::jsonb, ${envelope.sha256},
+ ${envelope.signature}, ${envelope.signer}
+ )
+ on conflict (id) do update set
+ outcome = excluded.outcome,
+ job_ref = coalesce(excluded.job_ref, run_receipts.job_ref),
+ body = excluded.body,
+ sha256 = excluded.sha256,
+ signature = excluded.signature,
+ signer = excluded.signer,
+ updated_at = now()
+ `;
+ return bounded(write, WRITE_WAIT_MS);
+}
+
+function rowToEnvelope(row) {
+ if (!row) return null;
+ const receipt = typeof row.body === 'string' ? JSON.parse(row.body) : row.body;
+ return { receipt, sha256: row.sha256, signature: row.signature || null, signer: row.signer || null };
+}
+
+export async function loadReceipt(id) {
+ if (!isReceiptId(id)) return null;
+ const [row] = await sql`select body, sha256, signature, signer from run_receipts where id = ${id} limit 1`;
+ return rowToEnvelope(row);
+}
+
+/**
+ * The receipt of the tool call that handed out this job: still pending (so
+ * check_job completes it) or already completed by an earlier check (so a repeat
+ * check links the same record instead of losing it).
+ */
+export async function loadReceiptForJob(ref) {
+ if (!ref) return null;
+ try {
+ const [row] = await sql`
+ select body, sha256, signature, signer from run_receipts
+ where job_ref = ${ref}
+ order by created_at desc limit 1
+ `;
+ return rowToEnvelope(row);
+ } catch (err) {
+ console.warn('[run-receipt] pending lookup failed:', err?.message || err);
+ return null;
+ }
+}
+
+/** Re-check a stored envelope with the pure verifier, pinned to our live key when we have one. */
+export async function verifyStoredReceipt(envelope) {
+ const trustedSigner = await receiptSignerPublicKey();
+ return verifyReceipt(envelope, trustedSigner ? { trustedSigner } : {});
+}
+
+export const STATS_MIN_DAYS = 1;
+export const STATS_MAX_DAYS = 90;
+
+/**
+ * Aggregate view across every receipt in the window: outcomes per tool,
+ * verdicts per stage, and the most common causes behind a recovered or missed
+ * stage. Counts only; no prompt, file or id leaves this query.
+ */
+export async function receiptStats({ days = 7 } = {}) {
+ const d = Math.min(STATS_MAX_DAYS, Math.max(STATS_MIN_DAYS, Math.floor(Number(days)) || 7));
+ const since = new Date(Date.now() - d * 86_400_000).toISOString();
+ const [outcomes, stages, causes] = await Promise.all([
+ sql`
+ select tool, outcome, count(*)::int as n,
+ count(*) filter (where jsonb_array_length(coalesce(body->'issues', '[]'::jsonb)) = 0)::int as clean
+ from run_receipts where created_at >= ${since}
+ group by tool, outcome
+ `,
+ sql`
+ select s->>'id' as stage, s->>'label' as label, s->>'verdict' as verdict, count(*)::int as n
+ from run_receipts, jsonb_array_elements(body->'stages') s
+ where created_at >= ${since}
+ group by 1, 2, 3
+ `,
+ sql`
+ select s->>'id' as stage, s->>'label' as label, s->>'verdict' as verdict, s->>'cause' as cause, count(*)::int as n
+ from run_receipts, jsonb_array_elements(body->'stages') s
+ where created_at >= ${since} and s->>'verdict' in ('missed', 'recovered') and s->>'cause' is not null
+ group by 1, 2, 3, 4
+ order by n desc
+ limit 12
+ `,
+ ]);
+ return summarizeStats({ days: d, outcomes, stages, causes });
+}
+
+// Stage display order follows the pipeline, so the page reads top to bottom
+// the way a run actually happens.
+const STAGE_ORDER = ['input', 'subject', 'brief', 'mesh', 'geometry', 'visual', 'rig', 'delivery'];
+
+/** Pure reshaping of the three stat queries. Exported for tests. */
+export function summarizeStats({ days, outcomes = [], stages = [], causes = [] }) {
+ const total = outcomes.reduce((s, r) => s + r.n, 0);
+ const byOutcome = {};
+ const byTool = {};
+ // A clean run delivered with no stage recovered or missed. The `delivered`
+ // outcome alone still allows a named fallback, so it is not the same thing.
+ let clean = 0;
+ for (const r of outcomes) {
+ if (r.outcome === 'delivered') clean += r.clean ?? r.n;
+ byOutcome[r.outcome] = (byOutcome[r.outcome] || 0) + r.n;
+ byTool[r.tool] ??= { total: 0, outcomes: {} };
+ byTool[r.tool].total += r.n;
+ byTool[r.tool].outcomes[r.outcome] = (byTool[r.tool].outcomes[r.outcome] || 0) + r.n;
+ }
+ const stageMap = new Map();
+ for (const r of stages) {
+ const s = stageMap.get(r.stage) || { id: r.stage, label: r.label, total: 0, verdicts: {} };
+ s.total += r.n;
+ s.verdicts[r.verdict] = (s.verdicts[r.verdict] || 0) + r.n;
+ stageMap.set(r.stage, s);
+ }
+ const rank = (id) => {
+ const i = STAGE_ORDER.indexOf(id);
+ return i < 0 ? STAGE_ORDER.length : i;
+ };
+ const stageList = [...stageMap.values()].sort((a, b) => rank(a.id) - rank(b.id));
+ const ran = stageList.map((s) => {
+ const judged = s.total - (s.verdicts.skipped || 0) - (s.verdicts.pending || 0);
+ return {
+ ...s,
+ judged,
+ met_rate: judged ? Math.round(((s.verdicts.met || 0) / judged) * 1000) / 1000 : null,
+ };
+ });
+ const delivered = (byOutcome.delivered || 0) + (byOutcome.delivered_with_issues || 0) + (byOutcome.partial || 0);
+ const finished = total - (byOutcome.pending || 0) - (byOutcome.refused || 0);
+ return {
+ days,
+ total,
+ outcomes: byOutcome,
+ delivery_rate: finished ? Math.round((delivered / finished) * 1000) / 1000 : null,
+ clean_rate: finished ? Math.round((clean / finished) * 1000) / 1000 : null,
+ tools: byTool,
+ stages: ran,
+ top_causes: causes.map((c) => ({ stage: c.stage, label: c.label, verdict: c.verdict, cause: c.cause, count: c.n })),
+ };
+}
+
+// ── observation helpers ──────────────────────────────────────────────────────
+
+/** Public catalog label for an engine id; unknown ids get a neutral name, never the raw id. */
+export function engineLabel(backendId) {
+ const b = backendId ? BACKENDS[backendId] : null;
+ return b?.label || 'a backup engine';
+}
+
+async function readHead(url, bytes) {
+ const res = await fetch(url, {
+ headers: { Range: `bytes=0-${bytes - 1}` },
+ signal: AbortSignal.timeout(RIG_INSPECT_TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`the file answered ${res.status}`);
+ const len = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(len) && len > RIG_MAX_BYTES) throw new Error('the file is too large to inspect');
+ return res.arrayBuffer();
+}
+
+/**
+ * Read the delivered rigged file and run Rig Doctor's analysis on it. Only the
+ * glTF JSON chunk is needed, so a ranged read normally suffices; when the
+ * chunk is longer than the first read, exactly enough more is fetched.
+ *
+ * @returns {Promise<{ report: object|null, error: string|null, ms: number }>}
+ */
+export async function inspectRiggedGlb(url) {
+ const t0 = Date.now();
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return { report: null, error: 'no file URL to inspect', ms: 0 };
+ try {
+ let buf = await readHead(url, RIG_PREFIX_BYTES);
+ const view = buf.byteLength >= 20 ? new DataView(buf) : null;
+ const need = view ? 20 + view.getUint32(12, true) + 8 : 0;
+ if (view && need > buf.byteLength && need <= RIG_MAX_BYTES) buf = await readHead(url, need);
+ return { report: analyzeGlb(buf), error: null, ms: Date.now() - t0 };
+ } catch (err) {
+ return { report: null, error: err?.message || String(err), ms: Date.now() - t0 };
+ }
+}
+
+/** The public page for one receipt. */
+export function receiptUrl(base, id) {
+ return `${base}/runs/${encodeURIComponent(id)}`;
+}
diff --git a/api/_lib/run-receipt.js b/api/_lib/run-receipt.js
new file mode 100644
index 000000000..a60120f40
--- /dev/null
+++ b/api/_lib/run-receipt.js
@@ -0,0 +1,599 @@
+// Run receipts: for every generation, a written record of what each stage was
+// expected to do, what it actually did, and the verdict, signed so it cannot be
+// edited after the fact.
+//
+// The pipeline already defends itself at every stage: a fail-soft prompt
+// director with a fixed full-body brief behind it, a tier that degrades instead
+// of failing, lane failover, a deterministic geometry score, a vision QA pass, a
+// rig the platform can drive. What it never did was write any of that down for
+// the person who asked. A fallback that carried a run was invisible, a quiet
+// tier downgrade looked identical to the tier that was requested, and a failure
+// was one sentence of copy. A run receipt is that record, stage by stage:
+//
+// expected the plain-language contract for the stage ("a 52-bone humanoid
+// skeleton with torso, arms and legs mapped")
+// observed what the stage measurably produced, read from the job frame or the
+// delivered file, never from the stage's own say-so
+// verdict met | recovered | missed | skipped | pending
+// cause for anything but `met`, the reason in plain words
+//
+// `issues` then restates every recovered or missed stage as "expected X,
+// observed Y, because Z": exactly what went wrong and what was expected.
+//
+// Pure core: no fetch, no DB, no env. The I/O (rig inspection, persistence,
+// signing key) lives in run-receipt-store.js; the wiring lives in the studio
+// tool handlers. Signatures are ed25519 over domain-tagged canonical JSON, the
+// same construction as inference receipts (inference-settlement.js) and 3D
+// provenance credentials (provenance-3d.js), under a tag of its own so no other
+// three.ws signature can be replayed as a run receipt.
+//
+// Docs: docs/run-receipts.md. Tests: tests/run-receipt.test.js.
+
+import { randomBytes } from 'node:crypto';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+import { sha256Hex } from './provenance-3d.js';
+
+export const RUN_RECEIPT_TYPE = 'three-run-receipt/v1';
+const TAG = Buffer.from(`${RUN_RECEIPT_TYPE}\n`, 'utf8');
+
+export const VERDICTS = Object.freeze(['met', 'recovered', 'missed', 'skipped', 'pending']);
+export const OUTCOMES = Object.freeze(['delivered', 'delivered_with_issues', 'partial', 'pending', 'refused', 'failed']);
+
+// What each outcome means, in the words the receipt page and the tool text use.
+export const OUTCOME_LABELS = Object.freeze({
+ delivered: 'Delivered as expected',
+ delivered_with_issues: 'Delivered, with issues noted',
+ partial: 'Partly delivered',
+ pending: 'Still running',
+ refused: 'Refused before any work ran',
+ failed: 'Not delivered',
+});
+
+// A prompt is stored so the receipt can be read on its own, but never a novel.
+const MAX_PROMPT_CHARS = 500;
+const MAX_TEXT_CHARS = 400;
+
+const ID_RE = /^rr_[1-9A-HJ-NP-Za-km-z]{16,32}$/;
+
+/** A fresh public receipt id. 16 random bytes: unguessable, so the id is the capability. */
+export function newReceiptId() {
+ return `rr_${bs58.encode(randomBytes(16))}`;
+}
+
+export function isReceiptId(id) {
+ return typeof id === 'string' && ID_RE.test(id);
+}
+
+/**
+ * Stable reference to a job handle. Handles are signed tokens that grant a poll;
+ * the receipt keeps only their hash, which is enough to find the receipt again
+ * when check_job collects the job and useless for anything else.
+ */
+export function jobRef(jobId) {
+ return typeof jobId === 'string' && jobId ? sha256Hex(Buffer.from(jobId, 'utf8')).slice(0, 40) : null;
+}
+
+function clip(value, max = MAX_TEXT_CHARS) {
+ if (value == null) return null;
+ const s = String(value).replace(/\s+/g, ' ').trim();
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
+}
+
+function finite(n) {
+ const v = Number(n);
+ return Number.isFinite(v) ? v : null;
+}
+
+// ── the receipt ─────────────────────────────────────────────────────────────
+
+/**
+ * Start a receipt for one tool call.
+ *
+ * @param {{ tool: string, prompt?: string, hasImage?: boolean, id?: string, now?: number }} args
+ */
+export function startReceipt({ tool, prompt, hasImage = false, id, now = Date.now() }) {
+ if (!tool || typeof tool !== 'string') throw new Error('startReceipt: tool is required');
+ return {
+ type: RUN_RECEIPT_TYPE,
+ id: id && isReceiptId(id) ? id : newReceiptId(),
+ tool,
+ started_at: new Date(now).toISOString(),
+ input: {
+ prompt: prompt ? clip(prompt, MAX_PROMPT_CHARS) : null,
+ reference_image: Boolean(hasImage),
+ },
+ stages: [],
+ };
+}
+
+/**
+ * Record one stage. Replaces an earlier entry with the same id, so a pending
+ * mesh stage completed later by check_job reads as one stage, not two.
+ */
+export function addStage(receipt, stage) {
+ if (!stage || !stage.id) throw new Error('addStage: stage.id is required');
+ if (!VERDICTS.includes(stage.verdict)) throw new Error(`addStage: unknown verdict "${stage.verdict}"`);
+ const entry = {
+ id: stage.id,
+ label: stage.label || stage.id,
+ expected: clip(stage.expected),
+ observed: clip(stage.observed),
+ verdict: stage.verdict,
+ ...(stage.cause ? { cause: clip(stage.cause) } : {}),
+ ...(stage.metrics && Object.keys(stage.metrics).length ? { metrics: stage.metrics } : {}),
+ ...(finite(stage.ms) != null ? { ms: Math.max(0, Math.round(stage.ms)) } : {}),
+ };
+ const at = receipt.stages.findIndex((s) => s.id === entry.id);
+ if (at >= 0) receipt.stages[at] = entry;
+ else receipt.stages.push(entry);
+ return entry;
+}
+
+/** Every stage that did not simply meet its contract, restated as one line of fact each. */
+export function receiptIssues(receipt) {
+ return receipt.stages
+ .filter((s) => s.verdict === 'missed' || s.verdict === 'recovered')
+ .map((s) => ({
+ stage: s.id,
+ label: s.label,
+ verdict: s.verdict,
+ expected: s.expected,
+ observed: s.observed,
+ ...(s.cause ? { cause: s.cause } : {}),
+ }));
+}
+
+/**
+ * Close the receipt. The outcome is derived from the stages unless the caller
+ * states it (a refusal, a partial delivery): a derived outcome can never claim
+ * more than the stages show.
+ */
+export function finishReceipt(receipt, { outcome, glbUrl, viewerUrl, now = Date.now() } = {}) {
+ const issues = receiptIssues(receipt);
+ let derived;
+ if (receipt.stages.some((s) => s.verdict === 'pending')) derived = 'pending';
+ else if (!glbUrl) derived = 'failed';
+ else if (issues.some((i) => i.verdict === 'missed')) derived = 'delivered_with_issues';
+ else derived = 'delivered';
+ // A caller may state a WORSE outcome than the stages imply (partial, refused),
+ // never a better one.
+ const rank = { delivered: 0, delivered_with_issues: 1, partial: 2, pending: 2, refused: 3, failed: 3 };
+ const final = outcome && OUTCOMES.includes(outcome) && rank[outcome] >= rank[derived] ? outcome : derived;
+ const started = Date.parse(receipt.started_at);
+ return {
+ ...receipt,
+ finished_at: final === 'pending' ? null : new Date(now).toISOString(),
+ duration_ms: final === 'pending' || !Number.isFinite(started) ? null : Math.max(0, now - started),
+ outcome: final,
+ summary: summarize(final, issues),
+ issues,
+ output: glbUrl ? { glb_url: glbUrl, ...(viewerUrl ? { viewer_url: viewerUrl } : {}) } : null,
+ };
+}
+
+function summarize(outcome, issues) {
+ const missed = issues.filter((i) => i.verdict === 'missed');
+ const recovered = issues.filter((i) => i.verdict === 'recovered');
+ const parts = [OUTCOME_LABELS[outcome] || outcome];
+ if (missed.length) parts.push(`${missed.length} stage${missed.length === 1 ? '' : 's'} missed (${missed.map((i) => i.label).join(', ')})`);
+ if (recovered.length) parts.push(`${recovered.length} carried by a fallback (${recovered.map((i) => i.label).join(', ')})`);
+ if (!missed.length && !recovered.length && outcome === 'delivered') parts.push('every stage met its contract');
+ return `${parts.join('. ')}.`;
+}
+
+// ── stage builders: observed facts in, one stage out ───────────────────────
+// Each takes what the pipeline actually reported and nothing else. None of
+// them can mark a stage met without the measurement that proves it.
+
+export function inputStage({ allowed, message, hasPrompt, hasImage }) {
+ const given = [hasPrompt ? 'a text prompt' : null, hasImage ? 'a reference image' : null].filter(Boolean).join(' and ');
+ if (!hasPrompt && !hasImage) {
+ return {
+ id: 'input',
+ label: 'Input',
+ expected: 'A text prompt or a reference image to work from.',
+ observed: 'Neither was provided.',
+ verdict: 'missed',
+ cause: 'Nothing to generate from.',
+ };
+ }
+ return {
+ id: 'input',
+ label: 'Input',
+ expected: 'A request that passes the content-safety check.',
+ observed: allowed ? `Received ${given}; it passed the safety check.` : `Received ${given}; it was declined by the safety check.`,
+ verdict: allowed ? 'met' : 'missed',
+ ...(allowed ? {} : { cause: message || 'Declined by the content-safety check.' }),
+ };
+}
+
+export function subjectGateStage({ hasImage, givenMesh, nonHumanoid, override }) {
+ const expected = 'A humanoid subject, because auto-rigging builds a two-legged skeleton.';
+ if (givenMesh) {
+ return {
+ id: 'subject',
+ label: 'Subject check',
+ expected,
+ observed: 'The mesh was rigged as given; whether it depicts a humanoid figure was not checked.',
+ verdict: 'skipped',
+ cause: 'The rig check verifies the skeleton structure, not that the body it is bound to is a character. A non-humanoid mesh still receives a humanoid skeleton.',
+ };
+ }
+ if (hasImage) {
+ return { id: 'subject', label: 'Subject check', expected, observed: 'A reference image was supplied, so the subject was taken as given.', verdict: 'skipped' };
+ }
+ if (nonHumanoid && override) {
+ return {
+ id: 'subject',
+ label: 'Subject check',
+ expected,
+ observed: 'The prompt reads as an object or animal, and the caller chose to rig it anyway.',
+ verdict: 'recovered',
+ cause: 'Override requested (allow_non_humanoid), so the rig may not map cleanly.',
+ };
+ }
+ if (nonHumanoid) {
+ return {
+ id: 'subject',
+ label: 'Subject check',
+ expected,
+ observed: 'The prompt reads as an object or animal, not a character.',
+ verdict: 'missed',
+ cause: 'Turned away before any GPU time was spent. Use the mesh generator for objects, or set allow_non_humanoid.',
+ };
+ }
+ return { id: 'subject', label: 'Subject check', expected, observed: 'The prompt reads as a character.', verdict: 'met' };
+}
+
+/**
+ * The prompt rewrite. `kind` is 'avatar' (a full-body brief is required, with a
+ * fixed one as the fallback) or 'mesh' (an optional enrichment; the raw prompt
+ * is a valid brief on its own).
+ */
+export function briefStage({ kind, hasImage, directed, knownMark = false, ms }) {
+ if (hasImage) {
+ return { id: 'brief', label: 'Brief', expected: 'A brief for the reference picture.', observed: 'A reference image was supplied, so it was used directly.', verdict: 'skipped', ms };
+ }
+ if (knownMark) {
+ return {
+ id: 'brief',
+ label: 'Brief',
+ expected: 'A precise brief for a known mark.',
+ observed: 'Matched a known mark; its fixed specification was used.',
+ verdict: 'met',
+ ms,
+ };
+ }
+ if (kind === 'avatar') {
+ const expected = 'A director-written brief that frames the whole figure head to toe in a neutral A-pose.';
+ return directed
+ ? { id: 'brief', label: 'Brief', expected, observed: 'The director rewrote the prompt into a full-body brief.', verdict: 'met', ms }
+ : {
+ id: 'brief',
+ label: 'Brief',
+ expected,
+ observed: 'The fixed full-body brief was appended to the prompt as written.',
+ verdict: 'recovered',
+ cause: 'The director model did not return a usable brief in time; the fixed brief keeps the framing.',
+ ms,
+ };
+ }
+ const expected = 'A director-written brief that turns the idea into a single-subject 3D specification.';
+ return directed
+ ? { id: 'brief', label: 'Brief', expected, observed: 'The director rewrote the prompt into a 3D specification.', verdict: 'met', ms }
+ : {
+ id: 'brief',
+ label: 'Brief',
+ expected,
+ observed: 'The prompt was used as written.',
+ verdict: 'recovered',
+ cause: 'The director model did not return a usable brief in time.',
+ ms,
+ };
+}
+
+/**
+ * The mesh. `frame` is the terminal poll payload; `labelFor(backendId)` turns
+ * an engine id into its public catalog label.
+ */
+export function meshStage({ frame, expectedTier, error, timedOut, ms, labelFor = (b) => b }) {
+ const tierWord = (t) => (t === 'high' ? 'high-detail' : t === 'draft' ? 'draft' : 'standard');
+ const expected = `A textured 3D mesh from the ${tierWord(expectedTier)} tier.`;
+ if (timedOut) {
+ return {
+ id: 'mesh',
+ label: 'Mesh',
+ expected,
+ observed: 'Still rendering when the inline wait ended; the job keeps running and can be collected.',
+ verdict: 'pending',
+ ms,
+ };
+ }
+ if (error || !frame?.glb_url) {
+ return {
+ id: 'mesh',
+ label: 'Mesh',
+ expected,
+ observed: 'No mesh was produced.',
+ verdict: 'missed',
+ cause: clip(error) || 'The generator returned no model.',
+ ms,
+ };
+ }
+ const engine = frame.backend ? labelFor(frame.backend) : null;
+ const tier = frame.tier || null;
+ const metrics = {
+ ...(tier ? { tier } : {}),
+ ...(engine ? { engine } : {}),
+ ...(frame.cached ? { cached: true } : {}),
+ };
+ const on = engine ? ` on ${engine}` : '';
+ if (expectedTier && tier && tier !== expectedTier) {
+ return {
+ id: 'mesh',
+ label: 'Mesh',
+ expected,
+ observed: `A mesh from the ${tierWord(tier)} tier${on}.`,
+ verdict: 'recovered',
+ cause: `The ${tierWord(expectedTier)} lane did not accept the job, so it ran on the ${tierWord(tier)} tier instead of failing.`,
+ metrics,
+ ms,
+ };
+ }
+ return {
+ id: 'mesh',
+ label: 'Mesh',
+ expected,
+ observed: `A mesh${tier ? ` from the ${tierWord(tier)} tier` : ''}${on}.`,
+ verdict: 'met',
+ metrics,
+ ms,
+ };
+}
+
+/** The deterministic geometry score (glb-quality.js) the frame already carries. */
+export function geometryStage({ quality, retried }) {
+ const expected = 'A valid GLB with real, textured geometry (not an empty or degenerate shell).';
+ if (!quality || typeof quality !== 'object') {
+ return { id: 'geometry', label: 'Geometry check', expected, observed: 'No geometry score was reported for this file.', verdict: 'skipped' };
+ }
+ const m = quality.metrics || {};
+ const metrics = {
+ ...(finite(m.triangleCount) != null ? { triangles: finite(m.triangleCount) } : {}),
+ ...(finite(m.vertexCount) != null ? { vertices: finite(m.vertexCount) } : {}),
+ ...(typeof m.hasTextures === 'boolean' ? { textured: m.hasTextures } : {}),
+ ...(finite(quality.score) != null ? { score: finite(quality.score) } : {}),
+ ...(finite(m.sizeBytes) != null ? { bytes: finite(m.sizeBytes) } : {}),
+ };
+ const facts = [
+ metrics.triangles != null ? `${metrics.triangles.toLocaleString('en-US')} triangles` : null,
+ metrics.vertices != null ? `${metrics.vertices.toLocaleString('en-US')} vertices` : null,
+ metrics.textured === true ? 'textured' : metrics.textured === false ? 'untextured' : null,
+ metrics.score != null ? `score ${metrics.score}` : null,
+ ].filter(Boolean);
+ const reasons = Array.isArray(quality.reasons) ? quality.reasons.filter((r) => typeof r === 'string') : [];
+ const bad = quality.valid === false || quality.flag === 'invalid' || quality.flag === 'degenerate' || quality.flag === 'low';
+ if (bad) {
+ return {
+ id: 'geometry',
+ label: 'Geometry check',
+ expected,
+ observed: `${facts.join(', ') || 'Scored below the floor'}.`,
+ verdict: 'missed',
+ cause: reasons.length ? `Flagged: ${reasons.join(', ').replace(/_/g, ' ')}.` : `Flagged ${quality.flag || 'invalid'}.`,
+ metrics,
+ };
+ }
+ if (retried) {
+ return {
+ id: 'geometry',
+ label: 'Geometry check',
+ expected,
+ observed: `${facts.join(', ')}, after one automatic regeneration.`,
+ verdict: 'recovered',
+ cause: 'The first result scored below the floor, so it was regenerated once automatically.',
+ metrics,
+ };
+ }
+ return { id: 'geometry', label: 'Geometry check', expected, observed: `${facts.join(', ') || 'Passed'}.`, verdict: 'met', metrics };
+}
+
+/** The vision QA verdict (forge-quality-gate.js) the frame carries on gated tiers. */
+export function visualQaStage({ gate }) {
+ const expected = 'A render of the model that reads as a complete, clean subject matching the prompt.';
+ if (!gate || typeof gate !== 'object') {
+ return { id: 'visual', label: 'Visual check', expected, observed: 'This tier does not run the vision check.', verdict: 'skipped' };
+ }
+ if (gate.qa_available === false) {
+ return {
+ id: 'visual',
+ label: 'Visual check',
+ expected,
+ observed: 'The vision check could not run, so the model shipped without it.',
+ verdict: 'skipped',
+ cause: 'The vision model was unavailable. A QA outage never withholds a finished model.',
+ };
+ }
+ const score = finite(gate.score);
+ const defects = Array.isArray(gate.defects) ? gate.defects.filter((d) => typeof d === 'string').slice(0, 6) : [];
+ const metrics = {
+ ...(score != null ? { score } : {}),
+ ...(finite(gate.realism) != null ? { realism: finite(gate.realism) } : {}),
+ ...(finite(gate.completeness) != null ? { completeness: finite(gate.completeness) } : {}),
+ ...(defects.length ? { defects } : {}),
+ };
+ const scored = score != null ? `Scored ${score}` : 'Scored';
+ const said = defects.map((d) => d.replace(/_/g, ' ')).join(', ');
+ if (gate.pass) {
+ return {
+ id: 'visual',
+ label: 'Visual check',
+ expected,
+ observed: `${scored} and passed${defects.length ? `; minor notes: ${said}` : ''}.`,
+ verdict: 'met',
+ metrics,
+ };
+ }
+ return {
+ id: 'visual',
+ label: 'Visual check',
+ expected,
+ observed: `${scored} and did not pass${defects.length ? `: ${said}` : ''}.`,
+ verdict: 'missed',
+ cause: clip(gate.reason) || 'The render did not read as a clean, complete subject.',
+ metrics,
+ };
+}
+
+/**
+ * The skeleton, verified from the rigged file itself with the same analysis
+ * Rig Doctor runs (src/rig-report.js analyzeGlb), not from the rigger's report.
+ * `report` is analyzeGlb's output, or null with `inspectError` when the file
+ * could not be read.
+ */
+export function rigStage({ report, error, inspectError, timedOut, ms }) {
+ const expected = 'A skinned humanoid skeleton the animation library can drive: torso, arms and legs mapped.';
+ if (timedOut) {
+ return { id: 'rig', label: 'Rig', expected, observed: 'Still rigging when the inline wait ended; the job keeps running and can be collected.', verdict: 'pending', ms };
+ }
+ if (error) {
+ return { id: 'rig', label: 'Rig', expected, observed: 'No rigged file was produced.', verdict: 'missed', cause: clip(error), ms };
+ }
+ if (!report) {
+ return {
+ id: 'rig',
+ label: 'Rig',
+ expected,
+ observed: 'A rigged file was delivered but could not be read back to verify the skeleton.',
+ verdict: 'skipped',
+ cause: clip(inspectError) || 'The file could not be read for inspection.',
+ ms,
+ };
+ }
+ const sk = report.skeleton || {};
+ const groups = Array.isArray(sk.groups) ? sk.groups : [];
+ const needed = groups.filter((g) => g.id === 'torso' || g.id === 'arms' || g.id === 'legs');
+ const undriven = needed.filter((g) => !g.driven);
+ const metrics = {
+ skinned: Boolean(sk.skinned),
+ joints: finite(sk.jointCount) ?? 0,
+ mapped: finite(sk.mapped) ?? 0,
+ ...(sk.convention?.label ? { convention: sk.convention.label } : {}),
+ groups: Object.fromEntries(groups.map((g) => [g.id, g.driven ? 'driven' : `${g.have}/${g.total}`])),
+ };
+ const conv = sk.convention?.label ? ` (${sk.convention.label})` : '';
+ if (!sk.skinned) {
+ return { id: 'rig', label: 'Rig', expected, observed: 'The file has no skinned mesh, so no clip can move it.', verdict: 'missed', cause: 'The rigger returned a file without skin weights.', metrics, ms };
+ }
+ if (undriven.length) {
+ return {
+ id: 'rig',
+ label: 'Rig',
+ expected,
+ observed: `${metrics.joints} joints${conv}; ${undriven.map((g) => g.label.toLowerCase()).join(' and ')} not mapped.`,
+ verdict: 'missed',
+ cause: `Missing key bones: ${undriven.flatMap((g) => g.missingKey || []).join(', ') || 'unmapped limb group'}.`,
+ metrics,
+ ms,
+ };
+ }
+ return {
+ id: 'rig',
+ label: 'Rig',
+ expected,
+ observed: `${metrics.joints} joints${conv}, ${metrics.mapped} mapped to the canonical skeleton; torso, arms and legs all driven.`,
+ verdict: 'met',
+ metrics,
+ ms,
+ };
+}
+
+/** Delivery: the file is on our storage, not a provider link that expires in an hour. */
+export function deliveryStage({ frame }) {
+ const expected = 'A permanent first-party link to the finished file.';
+ if (!frame?.glb_url) return { id: 'delivery', label: 'Delivery', expected, observed: 'Nothing to deliver.', verdict: 'missed', cause: 'No file was produced.' };
+ if (frame.durable === false) {
+ return {
+ id: 'delivery',
+ label: 'Delivery',
+ expected,
+ observed: "The file was served from the engine's own temporary link.",
+ verdict: 'recovered',
+ cause: 'Copying the file to permanent storage did not complete, so the engine link was handed over instead. It can expire.',
+ };
+ }
+ return { id: 'delivery', label: 'Delivery', expected, observed: 'Stored permanently and served first-party.', verdict: 'met' };
+}
+
+// ── canonical bytes, hash, signature ───────────────────────────────────────
+
+// Deterministic JSON: keys sorted recursively so signer and verifier produce
+// byte-identical messages. Same algorithm as inference-settlement.js.
+function canonicalize(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value === undefined ? null : value);
+}
+
+export function canonicalReceiptBytes(receipt) {
+ return Buffer.from(canonicalize(receipt), 'utf8');
+}
+
+/** sha256 (hex) of the canonical receipt: its content address. */
+export function receiptHash(receipt) {
+ return sha256Hex(canonicalReceiptBytes(receipt));
+}
+
+/**
+ * Sign a finished receipt with an ed25519 key (64-byte secret key or 32-byte
+ * seed). Returns the envelope { receipt, sha256, signature, signer }.
+ */
+export function signReceipt(receipt, secretKey) {
+ if (!secretKey || secretKey.length < 32) throw new Error('signReceipt: a 32-byte seed or 64-byte secret key is required');
+ const seed = secretKey.slice(0, 32);
+ const msg = Buffer.concat([TAG, canonicalReceiptBytes(receipt)]);
+ return {
+ receipt,
+ sha256: receiptHash(receipt),
+ signature: bs58.encode(ed25519.sign(msg, seed)),
+ signer: bs58.encode(ed25519.getPublicKey(seed)),
+ };
+}
+
+/**
+ * Verify an envelope offline. Pure. `trustedSigner` pins the issuer key; without
+ * it the check proves only that the receipt is internally consistent and was
+ * signed by the key it names.
+ *
+ * @returns {{ ok: boolean, checks: Array<{ name: string, ok: boolean, detail?: string }> }}
+ */
+export function verifyReceipt(envelope, { trustedSigner } = {}) {
+ const checks = [];
+ const check = (name, ok, detail) => {
+ checks.push(detail ? { name, ok, detail } : { name, ok });
+ return ok;
+ };
+ const r = envelope?.receipt;
+ if (!check('shape', Boolean(r && typeof r === 'object' && r.type === RUN_RECEIPT_TYPE && isReceiptId(r.id) && Array.isArray(r.stages)), 'a three-run-receipt/v1 object')) {
+ return { ok: false, checks };
+ }
+ check('hash', receiptHash(r) === envelope.sha256, 'sha256 of the canonical receipt matches');
+ if (!envelope.signature || !envelope.signer) {
+ check('signature', false, 'the receipt is unsigned');
+ return { ok: false, checks };
+ }
+ let sigOk = false;
+ try {
+ sigOk = ed25519.verify(bs58.decode(envelope.signature), Buffer.concat([TAG, canonicalReceiptBytes(r)]), bs58.decode(envelope.signer));
+ } catch {
+ sigOk = false;
+ }
+ check('signature', sigOk, 'ed25519 signature over the tagged canonical bytes');
+ if (trustedSigner) check('signer', envelope.signer === trustedSigner, 'signed by the pinned three.ws key');
+ return { ok: checks.every((c) => c.ok), checks };
+}
diff --git a/api/_mcp-studio/receipts.js b/api/_mcp-studio/receipts.js
new file mode 100644
index 000000000..dab5b2083
--- /dev/null
+++ b/api/_mcp-studio/receipts.js
@@ -0,0 +1,183 @@
+// Studio wiring for run receipts (api/_lib/run-receipt.js): one receipt per
+// generating tool call, stating what each stage was expected to do, what it
+// actually did, and the verdict, then sealed, stored and linked from the result.
+//
+// A receipt never changes what a tool returns, only adds to it: a
+// `structuredContent.receipt` block and one closing line of text. Every step
+// here fails open. If sealing, storing or the rig read-back fails, the model
+// still goes out exactly as before, just with a receipt that says so (or, with
+// no database, an inline receipt and no link).
+//
+// Data minimization: the receipt id is a fresh random public handle, the same
+// footing as the job handle a pending result already carries. The job handle
+// itself is never stored, only its hash (jobRef), which is how check_job finds
+// the pending receipt it should complete.
+
+import {
+ startReceipt,
+ addStage,
+ finishReceipt,
+ jobRef,
+ inputStage,
+ subjectGateStage,
+ briefStage,
+ meshStage,
+ geometryStage,
+ visualQaStage,
+ rigStage,
+ deliveryStage,
+} from '../_lib/run-receipt.js';
+import {
+ sealReceipt,
+ saveReceipt,
+ loadReceiptForJob,
+ inspectRiggedGlb,
+ engineLabel,
+ receiptUrl,
+} from '../_lib/run-receipt-store.js';
+
+export { inputStage, subjectGateStage, briefStage, rigStage, deliveryStage, inspectRiggedGlb };
+
+/** A request turned away at the input boundary for a reason other than safety. */
+export function inputRejected({ expected, message }) {
+ return { id: 'input', label: 'Input', expected, observed: 'The input was rejected before any work ran.', verdict: 'missed', cause: message };
+}
+
+/**
+ * Open a receipt for one tool call. `plan` is what the caller asked for in
+ * pipeline terms (the tier, whether a rig follows), kept on the receipt so a
+ * job collected later by check_job is judged against the same contract.
+ */
+export function openRun(tool, { prompt, hasImage = false, tier = null, rig = false } = {}) {
+ const receipt = startReceipt({ tool, prompt, hasImage });
+ receipt.plan = { tier, rig: Boolean(rig) };
+ return runFor(receipt);
+}
+
+function runFor(receipt) {
+ return {
+ receipt,
+ add(stage) {
+ try {
+ addStage(receipt, stage);
+ } catch (err) {
+ console.warn('[run-receipt] stage dropped:', err?.message || err);
+ }
+ },
+ /** Mesh, geometry score and vision verdict, all read off one terminal job frame. */
+ mesh(frame, { error, timedOut, ms } = {}) {
+ this.add(meshStage({ frame, expectedTier: receipt.plan.tier, error, timedOut, ms, labelFor: engineLabel }));
+ if (frame?.glb_url && !error && !timedOut) {
+ this.add(geometryStage({ quality: frame.quality, retried: frame.quality_retried === true }));
+ this.add(visualQaStage({ gate: frame.quality_gate }));
+ }
+ },
+ };
+}
+
+function compactIssues(issues) {
+ return issues.map((i) => ({
+ stage: i.stage,
+ label: i.label,
+ verdict: i.verdict,
+ expected: i.expected,
+ observed: i.observed,
+ ...(i.cause ? { cause: i.cause } : {}),
+ }));
+}
+
+/** Add the receipt to a tool result without disturbing anything already in it. */
+export function attachReceipt(result, receipt, url) {
+ if (!result || !receipt) return result;
+ const block = {
+ id: receipt.id,
+ outcome: receipt.outcome,
+ summary: receipt.summary,
+ issues: compactIssues(receipt.issues || []),
+ ...(url ? { url } : {}),
+ };
+ const line = url
+ ? `Run receipt (what each stage was expected to do and what it did): ${url}`
+ : `Run receipt: ${receipt.summary}`;
+ const content = Array.isArray(result.content) ? [...result.content] : [];
+ const at = content.findIndex((c) => c?.type === 'text');
+ if (at >= 0) content[at] = { ...content[at], text: `${content[at].text}\n${line}` };
+ else content.push({ type: 'text', text: line });
+ return { ...result, content, structuredContent: { ...(result.structuredContent || {}), receipt: block } };
+}
+
+/**
+ * Finish, seal, store and attach. `jobId` marks a pending run so check_job can
+ * complete it; `redactPrompt` drops the prompt from a refusal's record.
+ */
+export async function closeRun(run, result, { base, outcome, jobId, redactPrompt = false } = {}) {
+ try {
+ if (redactPrompt) run.receipt.input.prompt = null;
+ const sc = result?.structuredContent || {};
+ const glbUrl = result?.isError ? null : sc.glbUrl || sc.glb_url || null;
+ const finished = finishReceipt(run.receipt, { outcome, glbUrl, viewerUrl: glbUrl ? sc.viewer_url || sc.viewerUrl : undefined });
+ const envelope = await sealReceipt(finished);
+ const stored = await saveReceipt(envelope, { jobRef: jobRef(jobId) });
+ return attachReceipt(result, envelope.receipt, stored ? receiptUrl(base, finished.id) : null);
+ } catch (err) {
+ console.warn('[run-receipt] not attached:', err?.message || err);
+ return result;
+ }
+}
+
+// The fields finishReceipt adds; stripped before a pending receipt is re-opened.
+const FINISH_FIELDS = ['finished_at', 'duration_ms', 'outcome', 'summary', 'issues', 'output'];
+
+/**
+ * check_job collected a job some tool call left pending. Find that call's
+ * receipt, record what the job actually produced against the same contract,
+ * and re-seal it. `data` is the terminal poll payload; `failure` is the copy for
+ * a failed job. Resolves to the result with the receipt attached, or the result
+ * untouched when the job has no pending receipt.
+ */
+export async function completeRun(result, { base, jobId, data, failure }) {
+ try {
+ const ref = jobRef(jobId);
+ const envelope = await loadReceiptForJob(ref);
+ if (!envelope) return result;
+ if (envelope.receipt.outcome !== 'pending') return attachReceipt(result, envelope.receipt, receiptUrl(base, envelope.receipt.id));
+ const receipt = { ...envelope.receipt, stages: [...(envelope.receipt.stages || [])] };
+ for (const f of FINISH_FIELDS) delete receipt[f];
+ receipt.plan = receipt.plan || { tier: null, rig: false };
+ const run = runFor(receipt);
+ const pendingStage = receipt.stages.find((s) => s.verdict === 'pending');
+ const elapsedMs = Number.isFinite(Number(data?.elapsed_seconds)) ? Number(data.elapsed_seconds) * 1000 : undefined;
+ let outcome;
+ if (failure) {
+ const id = pendingStage?.id || 'mesh';
+ run.add(id === 'rig' ? rigStage({ error: failure, ms: elapsedMs }) : meshStage({ error: failure, expectedTier: receipt.plan.tier, ms: elapsedMs }));
+ } else if (pendingStage?.id === 'rig') {
+ const inspected = await inspectRiggedGlb(data.glb_url);
+ run.add(rigStage({ report: inspected.report, inspectError: inspected.error, ms: elapsedMs }));
+ run.add(deliveryStage({ frame: data }));
+ } else {
+ run.mesh(data, { ms: elapsedMs });
+ if (receipt.plan.rig) {
+ run.add({
+ id: 'rig',
+ label: 'Rig',
+ expected: 'A skinned humanoid skeleton the animation library can drive: torso, arms and legs mapped.',
+ observed: 'The mesh outlived the inline wait, so rigging moved to a follow-up rig_mesh call (the viewer starts it automatically).',
+ verdict: 'skipped',
+ cause: 'Not rigged inside this run.',
+ });
+ outcome = 'partial';
+ }
+ run.add(deliveryStage({ frame: data }));
+ }
+ const sc = result?.structuredContent || {};
+ const glbUrl = failure ? null : sc.glbUrl || sc.glb_url || data?.glb_url || null;
+ const finished = finishReceipt(receipt, { outcome, glbUrl, viewerUrl: glbUrl ? sc.viewer_url || sc.viewerUrl : undefined });
+ const sealed = await sealReceipt(finished);
+ const stored = await saveReceipt(sealed, { jobRef: ref });
+ return attachReceipt(result, sealed.receipt, stored ? receiptUrl(base, finished.id) : null);
+ } catch (err) {
+ console.warn('[run-receipt] completion not attached:', err?.message || err);
+ return result;
+ }
+}
diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.js
index 0f0dee09e..c183c513b 100644
--- a/api/_mcp-studio/tools.js
+++ b/api/_mcp-studio/tools.js
@@ -18,7 +18,9 @@
// stripped, per OpenAI's data-minimization policy. One deliberate exception:
// a job that outlives the inline wait budget returns its PUBLIC poll handle
// (the same job token the auth-free /api/forge REST lane hands any anonymous
-// caller); without it the still-running work would be unreachable.
+// caller); without it the still-running work would be unreachable. Each
+// generation also links its run receipt (./receipts.js): a random public id for
+// the record of what every stage was expected to do and what it did.
// Every model-bearing result also carries the four agent-first links from
// ./asset-links.js (viewer_url, glb_url, poster_png_url, embed_html), stated in
// the first lines of its text too, for clients that render no widget.
@@ -48,6 +50,18 @@ import {
directPrompt,
} from './gpt-forge-client.js';
import { COMPONENT_URI } from './component.js';
+import {
+ openRun,
+ closeRun,
+ completeRun,
+ inputStage,
+ inputRejected,
+ subjectGateStage,
+ briefStage,
+ rigStage,
+ deliveryStage,
+ inspectRiggedGlb,
+} from './receipts.js';
import { assetLinks, assetLinksText } from './asset-links.js';
import { runOnce, normalizeKey, argsDigest } from '../_lib/idempotency.js';
import { renderTurntable, describeGeometry, fetchGeometryStats } from '../_lib/3d-vision.js';
@@ -403,8 +417,6 @@ async function handleForgeFree(args, _auth, req, ctx = {}) {
const base = originFromReq(req);
const prompt = String(args.prompt || '').trim();
if (prompt.length < 3) return toolError('Provide a text prompt of at least 3 characters.');
- const safety = checkPromptSafety(prompt);
- if (!safety.allowed) return toolError(safety.message);
// Standard by default, and every doc describing this tool says exactly that.
// The high tier is a real, working option, not a stub: it runs on our own
// async Hunyuan3D worker (GCP_HUNYUAN3D_URL) behind a genuine poll handle,
@@ -418,6 +430,10 @@ async function handleForgeFree(args, _auth, req, ctx = {}) {
// standard on a 402 or submit timeout, and a job that outlives
// STUDIO_FORGE_TIMEOUT_MS comes back as a pollable handle, never an error.
const tier = VALID_TIER.has(args.tier) ? args.tier : 'standard';
+ const run = openRun('forge_free', { prompt, tier });
+ const safety = checkPromptSafety(prompt);
+ run.add(inputStage({ allowed: safety.allowed, message: safety.message, hasPrompt: true }));
+ if (!safety.allowed) return closeRun(run, toolError(safety.message), { base, outcome: 'refused', redactPrompt: true });
// Known brand marks resolve deterministically; everything else runs the
// subject-classified Granite director (fail-soft: original prompt on any
// failure) so this free lane gets the same photoreal-reference treatment as
@@ -428,25 +444,63 @@ async function handleForgeFree(args, _auth, req, ctx = {}) {
if (knownMark) {
effective = knownMark.prompt;
if (knownMark.imagePath) markImageUrls = [`${base}${knownMark.imagePath}`];
+ run.add(briefStage({ kind: 'mesh', knownMark: true }));
} else {
+ const t0 = Date.now();
const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt);
if (directed) effective = directed;
+ run.add(briefStage({ kind: 'mesh', directed: Boolean(directed), ms: Date.now() - t0 }));
}
+ return finishMesh(run, {
+ base,
+ ctx,
+ submit: markImageUrls
+ ? { prompt: effective, imageUrls: markImageUrls, tier, internal: true, director: false }
+ : { prompt: effective, path: 'image', tier, internal: true, director: false },
+ pending: (job) => pendingResult({ base, jobId: job.job_id, what: 'model', prompt, ...pendingTiming(job) }),
+ done: (job) => ok({ glbUrl: job.glb_url, base, kind: 'model', prompt, referenceImageUrl: job.preview_image_url }),
+ });
+}
+
+// The shared tail of every single-stage generator: run the mesh, record what
+// came back, and close the receipt on whichever of the four endings occurred.
+async function finishMesh(run, { base, ctx, submit, pending, done, timeoutEnv = 'STUDIO_FORGE_TIMEOUT_MS', slowCopy }) {
+ const t0 = Date.now();
let job;
try {
- job = await generate(
- base,
- markImageUrls
- ? { prompt: effective, imageUrls: markImageUrls, tier, internal: true, director: false }
- : { prompt: effective, path: 'image', tier, internal: true, director: false },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll },
- );
+ job = await generate(base, submit, { timeoutEnv, deadline: ctx.deadline, onPoll: ctx.onPoll });
} catch (err) {
- return toolError(failureMessage(err));
+ run.mesh(null, { error: failureMessage(err), ms: Date.now() - t0 });
+ return closeRun(run, toolError(failureMessage(err)), { base });
+ }
+ const ms = Date.now() - t0;
+ if (job._timedOut && job.job_id) {
+ run.mesh(job, { timedOut: true, ms });
+ return closeRun(run, pending(job), { base, jobId: job.job_id });
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'model', prompt, ...pendingTiming(job) });
- if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
- return ok({ glbUrl: job.glb_url, base, kind: 'model', prompt, referenceImageUrl: job.preview_image_url });
+ if (job._timedOut || !job.glb_url) {
+ run.mesh(null, { error: 'The inline wait ended before the job returned a handle to collect it with.', ms });
+ return closeRun(run, toolError(slowCopy || 'Generation is taking longer than expected. Please try again.'), { base });
+ }
+ run.mesh(job, { ms });
+ run.add(deliveryStage({ frame: job }));
+ return closeRun(run, done(job), { base });
+}
+
+// Shared input boundary for the generators that take a prompt and/or an image.
+// Returns a closed refusal receipt to hand straight back, or null to proceed.
+async function admitInput(run, { base, prompt, imageUrl }) {
+ const safety = prompt ? checkPromptSafety(prompt) : { allowed: true };
+ run.add(inputStage({ allowed: safety.allowed, message: safety.message, hasPrompt: Boolean(prompt), hasImage: Boolean(imageUrl) }));
+ if (!safety.allowed) return closeRun(run, toolError(safety.message), { base, outcome: 'refused', redactPrompt: true });
+ try {
+ await guardImage(imageUrl);
+ } catch (err) {
+ const message = err.userMessage ? err.message : 'That image URL could not be used.';
+ run.add(inputRejected({ expected: 'A public image URL the generator can fetch.', message }));
+ return closeRun(run, toolError(message), { base, outcome: 'refused' });
+ }
+ return null;
}
async function handleTextToAvatar(args, _auth, req, ctx = {}) {
@@ -454,37 +508,29 @@ async function handleTextToAvatar(args, _auth, req, ctx = {}) {
const prompt = String(args.prompt || '').trim();
const imageUrl = args.image_url ? String(args.image_url).trim() : '';
if (!prompt && !imageUrl) return toolError('Provide a text prompt or a reference image_url.');
- if (prompt) {
- const safety = checkPromptSafety(prompt);
- if (!safety.allowed) return toolError(safety.message);
- }
- try {
- await guardImage(imageUrl);
- } catch (err) {
- return toolError(err.userMessage ? err.message : 'That image URL could not be used.');
- }
+ const run = openRun('text_to_avatar', { prompt, hasImage: Boolean(imageUrl), tier: AVATAR_TIER });
+ const refused = await admitInput(run, { base, prompt, imageUrl });
+ if (refused) return refused;
// Granite avatar director (text mode only, fail-soft): without this the raw
// words reconstructed straight into TRELLIS/Hunyuan3D with no photoreal
// reference-image briefing at all — the realism gap forge_avatar already closes.
let effective = prompt;
if (prompt && !imageUrl) {
const subject = classifySubject(prompt) === 'animal' ? 'animal' : 'person';
+ const t0 = Date.now();
const directed = await directPrompt(avatarDirectorFor(subject), prompt);
effective = directed || avatarFallbackBrief(prompt, subject);
+ run.add(briefStage({ kind: 'avatar', directed: Boolean(directed), ms: Date.now() - t0 }));
+ } else {
+ run.add(briefStage({ kind: 'avatar', hasImage: true }));
}
- let job;
- try {
- job = await generate(
- base,
- { prompt: effective || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: AVATAR_TIER, internal: true, director: false },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll },
- );
- } catch (err) {
- return toolError(failureMessage(err));
- }
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, ...pendingTiming(job) });
- if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
- return ok({ glbUrl: job.glb_url, base, kind: 'avatar', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });
+ return finishMesh(run, {
+ base,
+ ctx,
+ submit: { prompt: effective || undefined, imageUrls: imageUrl ? [imageUrl] : undefined, aspect: '1:1', tier: AVATAR_TIER, internal: true, director: false },
+ pending: (job) => pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, ...pendingTiming(job) }),
+ done: (job) => ok({ glbUrl: job.glb_url, base, kind: 'avatar', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url }),
+ });
}
async function handleMeshForge(args, _auth, req, ctx = {}) {
@@ -492,15 +538,9 @@ async function handleMeshForge(args, _auth, req, ctx = {}) {
const prompt = String(args.prompt || '').trim();
const imageUrl = args.image_url ? String(args.image_url).trim() : '';
if (!prompt && !imageUrl) return toolError('Provide a text prompt or a reference image_url.');
- if (prompt) {
- const safety = checkPromptSafety(prompt);
- if (!safety.allowed) return toolError(safety.message);
- }
- try {
- await guardImage(imageUrl);
- } catch (err) {
- return toolError(err.userMessage ? err.message : 'That image URL could not be used.');
- }
+ const run = openRun('mesh_forge', { prompt, hasImage: Boolean(imageUrl), tier: 'standard' });
+ const refused = await admitInput(run, { base, prompt, imageUrl });
+ if (refused) return refused;
// Known brand marks resolve deterministically (no LLM knows a niche mark's
// geometry; the lexicon spec is already tight, so a rewrite could only hurt)
// and, when a pre-rendered reference view ships with the mark, go image→3D
@@ -513,51 +553,75 @@ async function handleMeshForge(args, _auth, req, ctx = {}) {
if (knownMark) {
effective = knownMark.prompt;
if (knownMark.imagePath) markImageUrls = [`${base}${knownMark.imagePath}`];
+ run.add(briefStage({ kind: 'mesh', knownMark: true }));
} else {
+ const t0 = Date.now();
const directed = await directPrompt(meshDirectorFor(meshSubjectClass(prompt)), prompt);
if (directed) effective = directed;
+ run.add(briefStage({ kind: 'mesh', directed: Boolean(directed), ms: Date.now() - t0 }));
}
+ } else {
+ run.add(briefStage({ kind: 'mesh', hasImage: true }));
}
- let job;
- try {
- job = await generate(
- base,
- {
- prompt: effective || undefined,
- imageUrls: imageUrl ? [imageUrl] : markImageUrls,
- aspect: '1:1',
- tier: 'standard',
- internal: true,
- director: false,
- },
- { timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll },
- );
- } catch (err) {
- return toolError(failureMessage(err));
- }
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, ...pendingTiming(job) });
- if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
- return ok({ glbUrl: job.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });
+ return finishMesh(run, {
+ base,
+ ctx,
+ submit: {
+ prompt: effective || undefined,
+ imageUrls: imageUrl ? [imageUrl] : markImageUrls,
+ aspect: '1:1',
+ tier: 'standard',
+ internal: true,
+ director: false,
+ },
+ pending: (job) => pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, ...pendingTiming(job) }),
+ done: (job) => ok({ glbUrl: job.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url }),
+ });
}
async function handleRigMesh(args, _auth, req, ctx = {}) {
const base = originFromReq(req);
const glbUrl = String(args.glb_url || '').trim();
if (!/^https?:\/\//i.test(glbUrl)) return toolError('Provide an http(s) URL to a GLB mesh to rig.');
+ const run = openRun('rig_mesh', { rig: true });
try {
await guardImage(glbUrl);
} catch (err) {
- return toolError(err.userMessage ? err.message : 'That GLB URL could not be used.');
+ const message = err.userMessage ? err.message : 'That GLB URL could not be used.';
+ run.add(inputRejected({ expected: 'A public GLB URL the rigger can fetch.', message }));
+ return closeRun(run, toolError(message), { base, outcome: 'refused' });
}
+ run.add({ id: 'input', label: 'Input', expected: 'A public GLB URL the rigger can fetch.', observed: 'Received a public GLB URL.', verdict: 'met' });
+ run.add(subjectGateStage({ givenMesh: true }));
+ return finishRig(run, { base, ctx, meshUrl: glbUrl, done: (job) => ok({ glbUrl: job.glb_url, base, kind: 'rigged model', rigged: true }) });
+}
+
+// Rig a mesh, then read the delivered file back and verify the skeleton with
+// Rig Doctor's analysis rather than taking the rigger's word for it. `partial`
+// builds the envelope for a rig failure when there is a mesh worth handing back.
+async function finishRig(run, { base, ctx, meshUrl, done, partial, what = 'rigged model', prompt }) {
+ const t0 = Date.now();
let job;
try {
- job = await rig(base, glbUrl, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll });
+ job = await rig(base, meshUrl, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll });
} catch (err) {
- return toolError(failureMessage(err));
+ run.add(rigStage({ error: failureMessage(err), ms: Date.now() - t0 }));
+ if (partial) return closeRun(run, partial(err), { base, outcome: 'partial' });
+ return closeRun(run, toolError(failureMessage(err)), { base });
+ }
+ if (job._timedOut && job.job_id) {
+ run.add(rigStage({ timedOut: true, ms: Date.now() - t0 }));
+ return closeRun(run, pendingResult({ base, jobId: job.job_id, what, prompt, ...pendingTiming(job), stage: 'rig' }), { base, jobId: job.job_id });
+ }
+ if (job._timedOut || !job.glb_url) {
+ run.add(rigStage({ error: 'The inline wait ended before the rig job returned a handle to collect it with.', ms: Date.now() - t0 }));
+ return closeRun(run, toolError('Rigging is taking longer than expected. Please try again.'), { base });
}
- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'rigged model', ...pendingTiming(job), stage: 'rig' });
- if (job._timedOut || !job.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');
- return ok({ glbUrl: job.glb_url, base, kind: 'rigged model', rigged: true });
+ const rigMs = Date.now() - t0;
+ const inspected = await inspectRiggedGlb(job.glb_url);
+ run.add(rigStage({ report: inspected.report, inspectError: inspected.error, ms: rigMs }));
+ run.add(deliveryStage({ frame: job }));
+ return closeRun(run, done(job), { base });
}
async function handleForgeAvatar(args, _auth, req, ctx = {}) {
@@ -565,27 +629,40 @@ async function handleForgeAvatar(args, _auth, req, ctx = {}) {
const prompt = String(args.prompt || '').trim();
const imageUrl = args.image_url ? String(args.image_url).trim() : '';
if (!prompt && !imageUrl) return toolError('Provide a text prompt or a reference image_url.');
- if (prompt) {
- const safety = checkPromptSafety(prompt);
- if (!safety.allowed) return toolError(safety.message);
- }
- if (prompt && !imageUrl && args.allow_non_humanoid !== true && looksNonHumanoid(prompt)) {
- return toolError(
- 'That looks like an object rather than a character. Auto-rigging needs a humanoid figure. Use the 3D mesh generator for objects, or set allow_non_humanoid to override.',
+ const run = openRun('forge_avatar', { prompt, hasImage: Boolean(imageUrl), tier: AVATAR_TIER, rig: true });
+ const safety = prompt ? checkPromptSafety(prompt) : { allowed: true };
+ run.add(inputStage({ allowed: safety.allowed, message: safety.message, hasPrompt: Boolean(prompt), hasImage: Boolean(imageUrl) }));
+ if (!safety.allowed) return closeRun(run, toolError(safety.message), { base, outcome: 'refused', redactPrompt: true });
+ const nonHumanoid = Boolean(prompt && !imageUrl && looksNonHumanoid(prompt));
+ run.add(subjectGateStage({ hasImage: Boolean(imageUrl), nonHumanoid, override: args.allow_non_humanoid === true }));
+ if (nonHumanoid && args.allow_non_humanoid !== true) {
+ return closeRun(
+ run,
+ toolError(
+ 'That looks like an object rather than a character. Auto-rigging needs a humanoid figure. Use the 3D mesh generator for objects, or set allow_non_humanoid to override.',
+ ),
+ { base, outcome: 'refused' },
);
}
try {
await guardImage(imageUrl);
} catch (err) {
- return toolError(err.userMessage ? err.message : 'That image URL could not be used.');
+ const message = err.userMessage ? err.message : 'That image URL could not be used.';
+ run.add(inputRejected({ expected: 'A public image URL the generator can fetch.', message }));
+ return closeRun(run, toolError(message), { base, outcome: 'refused' });
}
// Stage 1 — generate the mesh (Granite director in text mode, fail-soft).
let effective = prompt;
if (prompt && !imageUrl) {
const subject = classifySubject(prompt) === 'animal' ? 'animal' : 'person';
+ const t0 = Date.now();
const directed = await directPrompt(avatarDirectorFor(subject), prompt);
effective = directed || avatarFallbackBrief(prompt, subject);
+ run.add(briefStage({ kind: 'avatar', directed: Boolean(directed), ms: Date.now() - t0 }));
+ } else {
+ run.add(briefStage({ kind: 'avatar', hasImage: true }));
}
+ const t0 = Date.now();
let gen;
try {
gen = await generate(
@@ -594,16 +671,31 @@ async function handleForgeAvatar(args, _auth, req, ctx = {}) {
{ timeoutEnv: 'STUDIO_FORGE_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll },
);
} catch (err) {
- return toolError(failureMessage(err));
+ run.mesh(null, { error: failureMessage(err), ms: Date.now() - t0 });
+ return closeRun(run, toolError(failureMessage(err)), { base });
+ }
+ if (gen._timedOut && gen.job_id) {
+ run.mesh(gen, { timedOut: true, ms: Date.now() - t0 });
+ return closeRun(
+ run,
+ pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, ...pendingTiming(gen), stage: 'mesh', next: 'rig' }),
+ { base, jobId: gen.job_id },
+ );
+ }
+ if (gen._timedOut || !gen.glb_url) {
+ run.mesh(null, { error: 'The inline wait ended before the job returned a handle to collect it with.', ms: Date.now() - t0 });
+ return closeRun(run, toolError('Generation is taking longer than expected. Please try again.'), { base });
}
- if (gen._timedOut && gen.job_id) return pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, ...pendingTiming(gen), stage: 'mesh', next: 'rig' });
- if (gen._timedOut || !gen.glb_url) return toolError('Generation is taking longer than expected. Please try again.');
+ run.mesh(gen, { ms: Date.now() - t0 });
- // Stage 2 — auto-rig the generated mesh.
- let rigged;
- try {
- rigged = await rig(base, gen.glb_url, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll });
- } catch (err) {
+ // Stage 2: auto-rig the generated mesh, verified from the delivered file.
+ return finishRig(run, {
+ base,
+ ctx,
+ meshUrl: gen.glb_url,
+ what: 'avatar rig',
+ prompt: prompt || undefined,
+ done: (rigged) => ok({ glbUrl: rigged.glb_url, base, kind: 'avatar', prompt: prompt || undefined, rigged: true, referenceImageUrl: gen.preview_image_url }),
// Generation succeeded but rigging failed: hand back the (unrigged) mesh so
// the work isn't lost, and say so plainly.
// It rides the SAME ok() envelope as every other success, because this
@@ -612,22 +704,22 @@ async function handleForgeAvatar(args, _auth, req, ctx = {}) {
// sandbox, so this path error-stated instead of showing the mesh it just
// saved), the AR launch link, and the Spatial MCP artifact. Only the
// narration differs, so a partial result stays as usable as a whole one.
- const partial = ok({ glbUrl: gen.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: gen.preview_image_url });
- return {
- ...partial,
- content: [
- {
- type: 'text',
- text:
- `Generated the mesh but auto-rigging failed (${failureMessage(err)}). The model itself is fine and ready to use.\n` +
- partial.content[0].text,
- },
- ],
- };
- }
- if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, ...pendingTiming(rigged), stage: 'rig' });
- if (rigged._timedOut || !rigged.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');
- return ok({ glbUrl: rigged.glb_url, base, kind: 'avatar', prompt: prompt || undefined, rigged: true, referenceImageUrl: gen.preview_image_url });
+ partial: (err) => {
+ run.add(deliveryStage({ frame: gen }));
+ const result = ok({ glbUrl: gen.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: gen.preview_image_url });
+ return {
+ ...result,
+ content: [
+ {
+ type: 'text',
+ text:
+ `Generated the mesh but auto-rigging failed (${failureMessage(err)}). The model itself is fine and ready to use.\n` +
+ result.content[0].text,
+ },
+ ],
+ };
+ },
+ });
}
// Rebuild a client-supplied lineage (refine_model's parent_lineage, or the
@@ -702,43 +794,42 @@ async function handleRefineModel(args, _auth, req, ctx = {}) {
}
}
- let job;
- try {
- job = await generate(
- base,
- refImageUrl
- ? { prompt: composed, imageUrls: [refImageUrl], aspect: '1:1', tier: 'standard', internal: true }
- : { prompt: composed, tier: 'standard', internal: true },
- { timeoutEnv: 'STUDIO_REFINE_TIMEOUT_MS', deadline: ctx.deadline, onPoll: ctx.onPoll },
- );
- } catch (err) {
- return toolError(failureMessage(err));
- }
- if (job._timedOut && job.job_id)
- return pendingResult({
- base,
- jobId: job.job_id,
- what: 'refined model',
- prompt: composed || undefined,
- ...pendingTiming(job),
- refine: {
- lineage: baseLineage,
+ const run = openRun('refine_model', { prompt: composed, hasImage: Boolean(refImageUrl), tier: 'standard' });
+ run.add(inputStage({ allowed: true, hasPrompt: true, hasImage: Boolean(refImageUrl) }));
+ return finishMesh(run, {
+ base,
+ ctx,
+ timeoutEnv: 'STUDIO_REFINE_TIMEOUT_MS',
+ slowCopy: 'Refinement is taking longer than expected. Please try again.',
+ submit: refImageUrl
+ ? { prompt: composed, imageUrls: [refImageUrl], aspect: '1:1', tier: 'standard', internal: true }
+ : { prompt: composed, tier: 'standard', internal: true },
+ pending: (job) =>
+ pendingResult({
+ base,
+ jobId: job.job_id,
+ what: 'refined model',
+ prompt: composed || undefined,
+ ...pendingTiming(job),
+ refine: {
+ lineage: baseLineage,
+ instruction,
+ refKind: refImageUrl ? 'image' : 'text',
+ ...(parentIndex !== undefined ? { parentIndex } : {}),
+ },
+ }),
+ done: (job) => {
+ const lineage = appendVersion(baseLineage, {
+ glbUrl: job.glb_url,
+ viewerUrl: viewerUrl(base, job.glb_url),
+ prompt: composed,
instruction,
refKind: refImageUrl ? 'image' : 'text',
...(parentIndex !== undefined ? { parentIndex } : {}),
- },
- });
- if (job._timedOut || !job.glb_url) return toolError('Refinement is taking longer than expected. Please try again.');
-
- const lineage = appendVersion(baseLineage, {
- glbUrl: job.glb_url,
- viewerUrl: viewerUrl(base, job.glb_url),
- prompt: composed,
- instruction,
- refKind: refImageUrl ? 'image' : 'text',
- ...(parentIndex !== undefined ? { parentIndex } : {}),
+ });
+ return refineOk({ glbUrl: job.glb_url, base, prompt: composed, instruction, lineage, activeIndex: lineage.length - 1 });
+ },
});
- return refineOk({ glbUrl: job.glb_url, base, prompt: composed, instruction, lineage, activeIndex: lineage.length - 1 });
}
// A refinement collected by check_job joins the version history its pending
@@ -810,14 +901,16 @@ async function collectJob(args, req) {
prompt: typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined,
referenceImageUrl: data.preview_image_url,
});
- return { result, job: { status: 'done' } };
+ // The tool call that handed out this job left its receipt pending; record
+ // what the job actually produced and link it.
+ return { result: await completeRun(result, { base, jobId, data }), job: { status: 'done' } };
}
if (data.status === 'failed') {
// data.error is already sanitized server-side (sanitizeJobError): safe copy.
const message = data.error ? `Generation failed: ${data.error}` : failureMessage({ code: 'generation_failed' });
const backends = Array.isArray(data.retry_backends) ? data.retry_backends : [];
return {
- result: toolError(message),
+ result: await completeRun(toolError(message), { base, jobId, data, failure: message }),
job: {
status: 'failed',
retryable: true,
diff --git a/api/runs.js b/api/runs.js
new file mode 100644
index 000000000..db0a04aa9
--- /dev/null
+++ b/api/runs.js
@@ -0,0 +1,36 @@
+// GET /api/runs?id=rr_… one run receipt, its signed envelope, and a fresh server-side verification
+// GET /api/runs?stats=1&days=7 aggregate outcomes and stage verdicts across every receipt in the window
+//
+// Run receipts are the per-generation record of what each Studio stage was
+// expected to do, what it actually did, and the verdict (api/_lib/run-receipt.js).
+// A receipt is reachable only by its unguessable id, the same footing as the
+// result it was attached to; the stats view is counts only, with no prompt, file
+// or id in it. Public and read-only, so open CORS: anyone handed a receipt link
+// can check it, and the offline verifier (scripts/run-receipt-verify.mjs) needs
+// nothing but this JSON.
+
+import { cors, method, wrap, json, error } from './_lib/http.js';
+import { isReceiptId } from './_lib/run-receipt.js';
+import { loadReceipt, receiptStats, verifyStoredReceipt, receiptSignerPublicKey, STATS_MAX_DAYS } from './_lib/run-receipt-store.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS', payments: false })) return;
+ if (!method(req, res, ['GET'])) return;
+ const q = new URL(req.url, 'http://localhost').searchParams;
+
+ if (q.get('stats')) {
+ const days = Number(q.get('days')) || 7;
+ const stats = await receiptStats({ days });
+ const signer = await receiptSignerPublicKey();
+ return json(res, 200, { ...stats, max_days: STATS_MAX_DAYS, signer }, { 'cache-control': 'public, max-age=60, s-maxage=60' });
+ }
+
+ const id = q.get('id') || '';
+ if (!isReceiptId(id)) return error(res, 400, 'invalid_id', 'Pass ?id= with a run receipt id (rr_…), or ?stats=1 for the aggregate view.');
+ const envelope = await loadReceipt(id);
+ if (!envelope) return error(res, 404, 'not_found', 'No run receipt with that id.');
+ const verification = await verifyStoredReceipt(envelope);
+ // A pending receipt changes when its job is collected; a finished one never does.
+ const cache = envelope.receipt.outcome === 'pending' ? 'no-store' : 'public, max-age=300, s-maxage=3600';
+ return json(res, 200, { ...envelope, verification }, { 'cache-control': cache });
+});
diff --git a/docs/mcp-studio.md b/docs/mcp-studio.md
index 26c6d4c85..5885fb93d 100644
--- a/docs/mcp-studio.md
+++ b/docs/mcp-studio.md
@@ -192,6 +192,30 @@ Rigged avatars additionally carry `irlUrl`, the living-agent handoff into
Every result also includes a `spatial` field, the open Spatial MCP artifact
(`specs/SPATIAL_MCP.md`) so any Spatial-MCP renderer can display the model.
+### Run receipts
+
+Every generation, rig and refinement also carries a **run receipt**, the
+pipeline's own signed record of what each stage was expected to do, what it
+actually did, and the verdict (`met`, `recovered`, `missed`, `skipped`,
+`pending`), with the cause whenever a stage fell short:
+
+```json
+"receipt": {
+ "id": "rr_88WfvqBfKtWPnaiT6S8NDb",
+ "outcome": "delivered",
+ "summary": "Delivered as expected. 1 carried by a fallback (Brief).",
+ "issues": [{ "stage": "brief", "verdict": "recovered", "expected": "…", "observed": "The prompt was used as written.", "cause": "The director model did not return a usable brief in time." }],
+ "url": "https://three.ws/runs/rr_88WfvqBfKtWPnaiT6S8NDb"
+}
+```
+
+The result text ends with the same link, so an agent that reads only text can
+still tell its user what fell back and why. A receipt that was still running
+when the tool answered is completed by `check_job`. Refusals are receipted too
+(outcome `refused`, prompt not stored). The rig stage is verified by reading
+the delivered file back, not by trusting the rigger. Full reference:
+[Run receipts](./run-receipts.md).
+
### Links for agents that render no widget
ChatGPT and Claude draw the viewer widget from the camelCase fields above. An
diff --git a/docs/run-receipts.md b/docs/run-receipts.md
new file mode 100644
index 000000000..93b351ad7
--- /dev/null
+++ b/docs/run-receipts.md
@@ -0,0 +1,135 @@
+# Run receipts: what each stage was expected to do, and what it did
+
+Every generation the free 3D Studio runs (`forge_avatar`, `text_to_avatar`, `mesh_forge`, `forge_free`, `rig_mesh`, `refine_model`) writes a **run receipt**. A receipt walks the pipeline stage by stage. For each stage it records:
+
+- the **expected** result
+- the **observed** result
+- a **verdict**
+- the **cause** whenever the verdict is not a clean pass
+
+The finished record is hashed and signed with ed25519, so it cannot be edited after the fact without the edit showing.
+
+Browse them at [three.ws/runs](https://three.ws/runs). Each receipt has its own page, `/runs/rr_…`, and every Studio result links to its receipt in the text and in `structuredContent.receipt`.
+
+## Why this exists
+
+A generation pipeline that answers "here is your model" and nothing else hides everything that matters when a result is disappointing. When the director model timed out, the prompt went in as written. When the high-detail lane was full, the job ran on the standard tier. When the rigger returned a skeleton with no legs, the walk cycle can never play. A receipt makes each of those visible as it happens, in the same response, written by the pipeline itself rather than reconstructed afterwards.
+
+## Verdicts
+
+| Verdict | Meaning |
+| --- | --- |
+| `met` | The stage did what it was expected to do. |
+| `recovered` | The stage did not do the expected thing, but a named fallback carried the run (a different tier, the prompt used as written, an automatic regeneration). |
+| `missed` | The stage did not do what was expected, and the receipt says why (`cause`). |
+| `skipped` | The stage did not apply to this run (a reference image skips the brief; draft tiers skip the vision check). |
+| `pending` | The stage was still running when the tool answered. `check_job` completes the receipt. |
+
+## Stages
+
+| Stage | Expected | How it is observed |
+| --- | --- | --- |
+| Input | A prompt or reference image that passes the content-safety check. | The safety check and image guard. A refused prompt is not stored. |
+| Subject check | (`forge_avatar` only) A prompt that reads as a character, since rigging assumes a humanoid. | The same humanoid classifier the tool already gates on. |
+| Brief | A director-written 3D specification. | Whether the director answered in time, or a known-mark brief applied. |
+| Mesh | A textured mesh from the requested tier. | The engine and tier that actually ran, from the terminal job frame. |
+| Geometry check | A valid GLB with real, textured geometry. | The deterministic geometry score the forge computes on every file (triangles, vertices, textures). |
+| Visual check | A render that reads as a clean, complete subject. | The vision QA gate's verdict, score and defects, where the tier runs it. |
+| Rig | A skinned humanoid skeleton with torso, arms and legs mapped. | **Read back from the delivered file**, using the same analysis as Rig Doctor ([src/rig-report.js](../src/rig-report.js)), not taken from the rigger's own report. |
+| Delivery | A permanent first-party link. | Whether the file landed on three.ws storage or only on the engine's temporary link. |
+
+Each run's overall outcome is one of the following:
+
+- `delivered`
+- `delivered_with_issues`
+- `partial` (for example the mesh shipped but the rig failed)
+- `pending`
+- `refused`
+- `failed`
+
+The outcome is derived from the stages. A tool can only state a worse outcome than the stages imply, never a better one.
+
+## The receipt object
+
+```json
+{
+ "type": "three-run-receipt/v1",
+ "id": "rr_88WfvqBfKtWPnaiT6S8NDb",
+ "tool": "forge_free",
+ "started_at": "2026-10-11T17:02:11.418Z",
+ "finished_at": "2026-10-11T17:13:40.902Z",
+ "duration_ms": 689484,
+ "input": { "prompt": "a weathered brass ship lantern with a glass chimney", "reference_image": false },
+ "stages": [
+ { "id": "input", "label": "Input", "expected": "A request that passes the content-safety check.", "observed": "Received a text prompt; it passed the safety check.", "verdict": "met" },
+ { "id": "brief", "label": "Brief", "expected": "A director-written brief that turns the idea into a single-subject 3D specification.", "observed": "The prompt was used as written.", "verdict": "recovered", "cause": "The director model did not return a usable brief in time." }
+ ],
+ "outcome": "delivered",
+ "summary": "Delivered as expected. 1 carried by a fallback (Brief).",
+ "issues": [ { "stage": "brief", "verdict": "recovered", "expected": "…", "observed": "…", "cause": "…" } ],
+ "output": { "glb_url": "https://three.ws/cdn/forge/…glb", "viewer_url": "https://three.ws/viewer?src=…" }
+}
+```
+
+It is stored inside a signed envelope:
+
+```json
+{ "receipt": { … }, "sha256": "<hex of the canonical bytes>", "signature": "<base58 ed25519>", "signer": "<base58 public key>" }
+```
+
+The signature covers `three-run-receipt/v1` + `\n` + the canonical JSON of the receipt (keys sorted, no whitespace).
+
+## Verify one yourself
+
+The server verifies every receipt it serves, but you do not have to trust it:
+
+```bash
+node scripts/run-receipt-verify.mjs rr_88WfvqBfKtWPnaiT6S8NDb
+node scripts/run-receipt-verify.mjs https://three.ws/runs/rr_88WfvqBfKtWPnaiT6S8NDb --signer <pinned key>
+node scripts/run-receipt-verify.mjs ./downloaded-receipt.json --json
+```
+
+The verifier fetches the envelope (or reads a downloaded file). It then recomputes the hash and checks the ed25519 signature locally, and optionally checks the signer against a key you pinned. It prints every stage and exits non-zero on any failed check. Changing one character of any stage breaks it.
+
+The signing key is the platform attestation key (`ATTEST_AGENT_SECRET_KEY`). Its public half is returned as `signer` by `GET /api/runs?stats=1`. A deployment without the key still writes receipts, hashed but marked unsigned, and the page says so.
+
+## API
+
+| Call | Returns |
+| --- | --- |
+| `GET /api/runs?id=rr_…` | The envelope plus a fresh server-side `verification` (`{ ok, checks[] }`). 400 for a malformed id, 404 if unknown. |
+| `GET /api/runs?stats=1&days=7` | Aggregate counts over 1 to 90 days: outcomes, delivery rate, clean rate, per-tool totals, per-stage verdict counts and met rate, and the most common causes. Counts only; no prompts. |
+
+Both are public, CORS-open and keyless.
+
+## Privacy
+
+- A receipt id is an unguessable handle (`rr_` plus 16 random bytes in base58). Receipts are not listed individually anywhere. Only the person holding the link can open one.
+- The job handle is stored only as a one-way hash, so a receipt never exposes a job token.
+- A prompt refused by the safety check is not stored.
+- The aggregate view at `/runs` shows counts and causes, never prompts.
+
+## Failure behavior
+
+A receipt never changes a tool's result; it only adds to it.
+
+- If the database is unreachable, the tool still answers and carries the receipt inline, without a link.
+- Saving waits at most 2.5 s.
+- Reading the rig back has a 10 s budget. If it fails, the rig stage is `skipped` with the cause, never a guess.
+- A link is only attached once the receipt is actually stored, so a receipt link never 404s.
+
+## Code
+
+- Core (stages, verdicts, signing, verification): [api/_lib/run-receipt.js](../api/_lib/run-receipt.js)
+- Storage, stats, and rig read-back: [api/_lib/run-receipt-store.js](../api/_lib/run-receipt-store.js)
+- Table: [api/_lib/migrations/20261014000000_run_receipts.sql](../api/_lib/migrations/20261014000000_run_receipts.sql)
+- Studio wiring: [api/_mcp-studio/receipts.js](../api/_mcp-studio/receipts.js), [api/_mcp-studio/tools.js](../api/_mcp-studio/tools.js)
+- API: [api/runs.js](../api/runs.js)
+- Page: [pages/runs.html](../pages/runs.html), [src/runs.js](../src/runs.js)
+- Offline verifier: [scripts/run-receipt-verify.mjs](../scripts/run-receipt-verify.mjs)
+- Tests: [tests/run-receipt.test.js](../tests/run-receipt.test.js)
+
+## Related
+
+- [3D Studio MCP](mcp-studio.md): the tools that write receipts
+- [Reasoning Ledger](reasoning-ledger.md): the same idea for agent decisions
diff --git a/pages/runs.html b/pages/runs.html
new file mode 100644
index 000000000..f012e439f
--- /dev/null
+++ b/pages/runs.html
@@ -0,0 +1,52 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot, no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Run Receipts · three.ws</title>
+ <meta name="description" content="Every 3D generation on three.ws writes down what each stage was expected to do, what it actually did, and the verdict, signed so it cannot be edited after the fact." />
+ <link rel="canonical" href="https://three.ws/runs" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/runs" />
+ <meta property="og:title" content="Run Receipts · three.ws" />
+ <meta property="og:description" content="Expected vs observed, stage by stage, for every 3D generation. Signed, public, verifiable offline." />
+ <meta property="og:image" content="https://three.ws/api/page-og?t=Run+Receipts&amp;d=Expected+vs+observed%2C+stage+by+stage%2C+for+every+3D+generation.&amp;p=%2Fruns" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Run Receipts · three.ws" />
+ <meta name="twitter:description" content="Expected vs observed, stage by stage, for every 3D generation. Signed, public, verifiable offline." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?t=Run+Receipts&amp;d=Expected+vs+observed%2C+stage+by+stage%2C+for+every+3D+generation.&amp;p=%2Fruns" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/src/runs.css" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="rr-shell">
+ <section class="rr-hero">
+ <p class="rr-kicker">Run receipts</p>
+ <h1 class="rr-title" id="rr-title">Every generation writes down what happened.</h1>
+ <p class="rr-sub" id="rr-sub">
+ Each 3D Studio run records, stage by stage, what was expected, what was observed, and a verdict. Fallbacks are
+ named, misses carry their cause, and the record is signed so it cannot be edited after the fact.
+ <a href="/docs/run-receipts">How it works</a>.
+ </p>
+ </section>
+ <div id="rr-root" aria-live="polite"></div>
+ </main>
+
+ <script type="module" src="/src/runs.js"></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/scripts/run-receipt-verify.mjs b/scripts/run-receipt-verify.mjs
new file mode 100644
index 000000000..4f0b97af3
--- /dev/null
+++ b/scripts/run-receipt-verify.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+// Verify a three.ws run receipt offline, then print it stage by stage.
+//
+// node scripts/run-receipt-verify.mjs rr_… fetch from three.ws and verify
+// node scripts/run-receipt-verify.mjs https://three.ws/runs/rr_…
+// node scripts/run-receipt-verify.mjs ./receipt.json a saved envelope, no network at all
+// --signer <base58> pin the issuer key (fails unless the receipt was signed by it)
+// --base <origin> fetch from another deployment (default https://three.ws)
+// --json print the verification result as JSON
+//
+// The check runs locally with the same pure verifier the server uses
+// (api/_lib/run-receipt.js verifyReceipt): sha256 of the canonical receipt, then
+// the ed25519 signature over the domain-tagged bytes. The server's own
+// `verification` field is ignored; the point is not to take its word for it.
+// Exit code 0 when every check passes, 1 otherwise.
+
+import { readFileSync, existsSync } from 'node:fs';
+import { verifyReceipt } from '../api/_lib/run-receipt.js';
+
+const argv = process.argv.slice(2);
+const flag = (name) => {
+ const i = argv.indexOf(name);
+ return i >= 0 ? argv.splice(i, 2)[1] : undefined;
+};
+const asJson = argv.includes('--json') ? (argv.splice(argv.indexOf('--json'), 1), true) : false;
+const signer = flag('--signer');
+const base = (flag('--base') || 'https://three.ws').replace(/\/$/, '');
+const target = argv[0];
+
+if (!target) {
+ console.error('usage: node scripts/run-receipt-verify.mjs <rr_id | receipt URL | envelope.json> [--signer <base58>] [--base <origin>] [--json]');
+ process.exit(2);
+}
+
+async function loadEnvelope(t) {
+ if (existsSync(t)) return JSON.parse(readFileSync(t, 'utf8'));
+ const id = /rr_[1-9A-HJ-NP-Za-km-z]{16,32}/.exec(t)?.[0];
+ if (!id) throw new Error(`"${t}" is not a receipt id, a receipt URL, or a file`);
+ const origin = /^https?:\/\//.test(t) ? new URL(t).origin : base;
+ const res = await fetch(`${origin}/api/runs?id=${id}`, { signal: AbortSignal.timeout(15_000) });
+ if (!res.ok) throw new Error(`${origin} answered ${res.status} for ${id}`);
+ return res.json();
+}
+
+const MARK = { met: 'MET ', recovered: 'RECOVERED', missed: 'MISSED ', skipped: 'SKIPPED ', pending: 'PENDING ' };
+
+try {
+ const envelope = await loadEnvelope(target);
+ const { receipt, sha256, signature, signer: signedBy } = envelope;
+ const result = verifyReceipt({ receipt, sha256, signature, signer: signedBy }, signer ? { trustedSigner: signer } : {});
+ if (asJson) {
+ console.log(JSON.stringify({ id: receipt?.id, outcome: receipt?.outcome, signer: signedBy, ...result }, null, 2));
+ } else {
+ console.log(`${receipt.id} ${receipt.tool} ${receipt.outcome}`);
+ console.log(receipt.summary);
+ if (receipt.input?.prompt) console.log(`prompt: ${receipt.input.prompt}`);
+ console.log('');
+ for (const s of receipt.stages) {
+ const ms = Number.isFinite(s.ms) ? ` (${(s.ms / 1000).toFixed(1)}s)` : '';
+ console.log(`${MARK[s.verdict] || s.verdict} ${s.label}${ms}`);
+ console.log(` expected: ${s.expected}`);
+ console.log(` observed: ${s.observed}`);
+ if (s.cause) console.log(` cause: ${s.cause}`);
+ }
+ console.log('');
+ for (const c of result.checks) console.log(`${c.ok ? 'ok ' : 'FAIL'} ${c.name}${c.detail ? `: ${c.detail}` : ''}`);
+ console.log(result.ok ? `\nVerified. Signed by ${signedBy}.` : '\nNot verified.');
+ }
+ process.exit(result.ok ? 0 : 1);
+} catch (err) {
+ console.error(err.message || err);
+ process.exit(1);
+}
diff --git a/src/runs.css b/src/runs.css
new file mode 100644
index 000000000..21c30e292
--- /dev/null
+++ b/src/runs.css
@@ -0,0 +1,627 @@
+/* Run receipts (/runs, /runs/:id): expected vs observed, stage by stage.
+ Leans on the global tokens from /tokens.css (pulled in by nav.css), with
+ fallbacks so the page still reads if the theme sheet is late. */
+
+:root {
+ --rr-card: var(--surface-1, rgba(255, 255, 255, 0.03));
+ --rr-card-2: var(--surface-2, rgba(255, 255, 255, 0.06));
+ --rr-line: var(--line, rgba(255, 255, 255, 0.1));
+ --rr-ink: var(--ink, #e8e8e8);
+ --rr-dim: var(--ink-dim, rgba(232, 232, 232, 0.62));
+ --rr-bright: var(--ink-bright, #fff);
+ --rr-met: var(--success, #4ade80);
+ --rr-recovered: var(--warn, #fbbf24);
+ --rr-missed: var(--danger, #f87171);
+ --rr-skipped: color-mix(in srgb, var(--rr-ink) 40%, transparent);
+ --rr-pending: #60a5fa;
+ --rr-mono: var(--font-mono, ui-monospace, 'SF Mono', Menlo, monospace);
+ --rr-r: 14px;
+}
+
+body {
+ background: var(--bg-0, #0a0a0a);
+}
+
+.rr-shell {
+ max-width: 960px;
+ margin: 0 auto;
+ padding: clamp(16px, 4vw, 40px) 16px 80px;
+ color: var(--rr-ink);
+ font-family: var(--font-body, 'Inter', system-ui, sans-serif);
+}
+.rr-shell button,
+.rr-shell input {
+ font-family: inherit;
+}
+
+/* hero */
+.rr-kicker {
+ margin: 0 0 8px;
+ font: 600 12px/1 var(--rr-mono);
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--rr-dim);
+}
+.rr-title {
+ margin: 0 0 12px;
+ font-family: var(--font-display, inherit);
+ font-size: clamp(28px, 5vw, 44px);
+ line-height: 1.08;
+ color: var(--rr-bright);
+}
+.rr-sub {
+ max-width: 68ch;
+ margin: 0 0 28px;
+ color: var(--rr-dim);
+ line-height: 1.6;
+}
+.rr-sub a,
+.rr-back a,
+.rr-state a:not(.rr-btn) {
+ color: var(--rr-bright);
+ text-underline-offset: 3px;
+}
+
+/* tones */
+.rr-tone--met { --tone: var(--rr-met); }
+.rr-tone--recovered { --tone: var(--rr-recovered); }
+.rr-tone--missed { --tone: var(--rr-missed); }
+.rr-tone--skipped { --tone: var(--rr-skipped); }
+.rr-tone--pending { --tone: var(--rr-pending); }
+
+.rr-verdict {
+ display: inline-flex;
+ align-items: center;
+ padding: 3px 10px;
+ border-radius: 999px;
+ font: 600 12px/1.4 var(--rr-mono);
+ color: var(--tone);
+ background: color-mix(in srgb, var(--tone) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--tone) 40%, transparent);
+ white-space: nowrap;
+}
+
+/* buttons, inputs */
+.rr-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ min-height: 40px;
+ padding: 0 16px;
+ border-radius: 10px;
+ border: 1px solid var(--rr-line);
+ background: var(--rr-card-2);
+ color: var(--rr-ink);
+ font: 500 14px/1 inherit;
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, transform 0.08s;
+}
+.rr-btn:hover {
+ background: color-mix(in srgb, var(--rr-ink) 12%, transparent);
+ border-color: color-mix(in srgb, var(--rr-ink) 30%, transparent);
+}
+.rr-btn:active {
+ transform: translateY(1px);
+}
+.rr-btn:focus-visible,
+.rr-chip:focus-visible,
+.rr-input:focus-visible,
+.rr-shell a:focus-visible {
+ outline: 2px solid var(--rr-pending);
+ outline-offset: 2px;
+}
+.rr-btn--primary {
+ background: var(--rr-bright);
+ color: #0a0a0a;
+ border-color: var(--rr-bright);
+}
+.rr-btn--primary:hover {
+ background: color-mix(in srgb, var(--rr-bright) 86%, transparent);
+}
+.rr-btn--small {
+ min-height: 32px;
+ padding: 0 12px;
+ font-size: 13px;
+}
+
+.rr-lookup {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+.rr-input {
+ flex: 1 1 260px;
+ min-height: 40px;
+ padding: 0 14px;
+ border-radius: 10px;
+ border: 1px solid var(--rr-line);
+ background: var(--rr-card);
+ color: var(--rr-ink);
+ font: 14px var(--rr-mono);
+}
+.rr-input:hover {
+ border-color: color-mix(in srgb, var(--rr-ink) 25%, transparent);
+}
+.rr-hint {
+ min-height: 1.4em;
+ margin: 6px 0 0;
+ font-size: 13px;
+ color: var(--rr-missed);
+}
+
+.rr-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ margin: 20px 0 16px;
+}
+.rr-h2 {
+ margin: 0;
+ font-size: 20px;
+ color: var(--rr-bright);
+}
+.rr-h3 {
+ margin: 0 0 6px;
+ font-size: 16px;
+ color: var(--rr-bright);
+}
+.rr-days {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+.rr-chip {
+ min-height: 34px;
+ padding: 0 12px;
+ border-radius: 999px;
+ border: 1px solid var(--rr-line);
+ background: transparent;
+ color: var(--rr-dim);
+ font: 500 13px/1 inherit;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+.rr-chip:hover {
+ color: var(--rr-ink);
+ background: var(--rr-card-2);
+}
+.rr-chip.is-active {
+ color: #0a0a0a;
+ background: var(--rr-bright);
+ border-color: var(--rr-bright);
+}
+
+/* cards */
+.rr-card {
+ margin: 0 0 16px;
+ padding: clamp(16px, 3vw, 24px);
+ border: 1px solid var(--rr-line);
+ border-radius: var(--rr-r);
+ background: var(--rr-card);
+}
+.rr-muted {
+ margin: 0 0 12px;
+ color: var(--rr-dim);
+ font-size: 14px;
+ line-height: 1.5;
+}
+.rr-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ margin-top: 12px;
+}
+
+/* KPIs */
+.rr-kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 12px;
+ margin-bottom: 16px;
+}
+.rr-kpi {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-height: 96px;
+ padding: 18px;
+ border: 1px solid var(--rr-line);
+ border-radius: var(--rr-r);
+ background: var(--rr-card);
+}
+.rr-kpi__n {
+ font: 700 clamp(26px, 4vw, 34px) / 1 var(--font-display, inherit);
+ color: var(--rr-bright);
+ font-variant-numeric: tabular-nums;
+}
+.rr-kpi__l {
+ color: var(--rr-dim);
+ font-size: 14px;
+}
+
+/* stage bars */
+.rr-stage-list,
+.rr-causes,
+.rr-tools,
+.rr-steps,
+.rr-issues,
+.rr-checks {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+.rr-stage-row {
+ padding: 12px 0;
+ border-top: 1px solid var(--rr-line);
+}
+.rr-stage-row:first-child {
+ border-top: 0;
+}
+.rr-stage-row__head {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 8px;
+}
+.rr-stage-row__name {
+ font-weight: 600;
+}
+.rr-stage-row__rate {
+ font: 13px var(--rr-mono);
+ color: var(--rr-dim);
+ font-variant-numeric: tabular-nums;
+}
+.rr-bar {
+ display: flex;
+ height: 10px;
+ border-radius: 999px;
+ overflow: hidden;
+ background: var(--rr-card-2);
+ gap: 2px;
+}
+.rr-bar__seg {
+ background: var(--tone);
+ min-width: 4px;
+}
+.rr-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ margin-top: 8px;
+ font-size: 12px;
+ color: var(--rr-dim);
+}
+.rr-legend__item {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+.rr-legend__item i {
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ background: var(--tone);
+}
+
+/* causes, tools */
+.rr-causes li,
+.rr-tools li {
+ display: flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ padding: 10px 0;
+ border-top: 1px solid var(--rr-line);
+}
+.rr-causes li:first-child,
+.rr-tools li:first-child {
+ border-top: 0;
+}
+.rr-causes__stage,
+.rr-tools__name {
+ font-weight: 600;
+}
+.rr-causes__text {
+ flex: 1 1 240px;
+ color: var(--rr-dim);
+ overflow-wrap: anywhere;
+}
+.rr-causes__n,
+.rr-tools__n {
+ font: 13px var(--rr-mono);
+ font-variant-numeric: tabular-nums;
+}
+.rr-tools code {
+ font: 12px var(--rr-mono);
+ color: var(--rr-dim);
+}
+.rr-tools .rr-muted {
+ flex-basis: 100%;
+ margin: 0;
+}
+.rr-signer code,
+.rr-ids code,
+.rr-cmd code {
+ font: 12px var(--rr-mono);
+ overflow-wrap: anywhere;
+}
+
+/* receipt head */
+.rr-back {
+ margin: 0 0 12px;
+ font-size: 14px;
+}
+.rr-outcome {
+ border-color: color-mix(in srgb, var(--tone) 35%, var(--rr-line));
+}
+.rr-outcome__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ margin-bottom: 14px;
+}
+.rr-outcome__tool {
+ font: 12px var(--rr-mono);
+ color: var(--rr-dim);
+}
+.rr-prompt {
+ margin: 0 0 14px;
+ padding: 12px 16px;
+ border-left: 3px solid var(--rr-line);
+ background: var(--rr-card-2);
+ border-radius: 0 10px 10px 0;
+ color: var(--rr-bright);
+ font-size: 16px;
+ line-height: 1.5;
+ overflow-wrap: anywhere;
+}
+.rr-outcome__summary {
+ margin: 0 0 8px;
+ font-size: 16px;
+ line-height: 1.5;
+}
+.rr-pending {
+ margin-top: 14px;
+ padding: 12px 14px;
+ border-radius: 10px;
+ background: color-mix(in srgb, var(--rr-pending) 10%, transparent);
+}
+.rr-pending p {
+ margin: 0 0 10px;
+ font-size: 14px;
+}
+
+.rr-issues li {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 6px 10px;
+ padding: 10px 0;
+ border-top: 1px solid var(--rr-line);
+ line-height: 1.5;
+}
+.rr-issues li:first-child {
+ border-top: 0;
+}
+.rr-issues li > span:last-child {
+ flex-basis: 100%;
+ color: var(--rr-dim);
+}
+
+/* stage timeline */
+.rr-steps {
+ position: relative;
+ margin-top: 12px;
+}
+.rr-step {
+ position: relative;
+ display: grid;
+ grid-template-columns: 32px 1fr;
+ gap: 14px;
+ padding-bottom: 20px;
+}
+.rr-step:not(:last-child)::before {
+ content: '';
+ position: absolute;
+ left: 15px;
+ top: 32px;
+ bottom: 0;
+ width: 2px;
+ background: var(--rr-line);
+}
+.rr-step__dot {
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ font: 600 13px var(--rr-mono);
+ color: var(--tone);
+ border: 2px solid var(--tone);
+ background: var(--bg-0, #0a0a0a);
+}
+.rr-step__head {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ min-height: 32px;
+ margin-bottom: 8px;
+}
+.rr-step__name {
+ margin: 0;
+ font-size: 16px;
+ color: var(--rr-bright);
+}
+.rr-step__time {
+ margin-left: auto;
+ font: 12px var(--rr-mono);
+ color: var(--rr-dim);
+}
+.rr-eo {
+ display: grid;
+ grid-template-columns: 84px 1fr;
+ gap: 6px 12px;
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.5;
+}
+.rr-eo dt {
+ color: var(--rr-dim);
+ font: 600 12px/1.9 var(--rr-mono);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+}
+.rr-eo dd {
+ margin: 0;
+ overflow-wrap: anywhere;
+}
+.rr-eo__cause {
+ color: var(--tone);
+}
+.rr-metrics {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin: 10px 0 0;
+}
+.rr-metric {
+ padding: 6px 10px;
+ border-radius: 8px;
+ background: var(--rr-card-2);
+ font-size: 12px;
+}
+.rr-metric dt {
+ color: var(--rr-dim);
+ font-family: var(--rr-mono);
+}
+.rr-metric dd {
+ margin: 2px 0 0;
+ font-family: var(--rr-mono);
+ overflow-wrap: anywhere;
+}
+
+/* verification */
+.rr-verify.is-ok {
+ border-color: color-mix(in srgb, var(--rr-met) 35%, var(--rr-line));
+}
+.rr-verify.is-bad {
+ border-color: color-mix(in srgb, var(--rr-recovered) 35%, var(--rr-line));
+}
+.rr-checks {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 14px;
+}
+.rr-checks li {
+ display: inline-flex;
+ gap: 6px;
+ padding: 4px 10px;
+ border-radius: 8px;
+ background: var(--rr-card-2);
+ font-size: 13px;
+}
+.rr-checks li.is-ok span { color: var(--rr-met); }
+.rr-checks li.is-bad span { color: var(--rr-missed); }
+.rr-ids {
+ display: grid;
+ grid-template-columns: 70px 1fr;
+ gap: 4px 12px;
+ margin: 0 0 14px;
+ font-size: 13px;
+}
+.rr-ids dt {
+ color: var(--rr-dim);
+}
+.rr-ids dd {
+ margin: 0;
+}
+.rr-cmd {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ background: var(--rr-card-2);
+}
+.rr-cmd code {
+ flex: 1;
+}
+
+/* states */
+.rr-state {
+ padding: 40px 24px;
+ text-align: center;
+ border: 1px dashed var(--rr-line);
+ border-radius: var(--rr-r);
+ margin-bottom: 16px;
+}
+.rr-state h2 {
+ margin: 0 0 8px;
+ font-size: 20px;
+ color: var(--rr-bright);
+}
+.rr-state p {
+ max-width: 52ch;
+ margin: 0 auto 16px;
+ color: var(--rr-dim);
+ line-height: 1.6;
+}
+.rr-state .rr-actions {
+ justify-content: center;
+}
+.rr-state--error {
+ border-style: solid;
+ border-color: color-mix(in srgb, var(--rr-missed) 40%, var(--rr-line));
+}
+
+/* skeletons */
+.rr-shimmer {
+ background: linear-gradient(90deg, var(--rr-card) 0%, var(--rr-card-2) 50%, var(--rr-card) 100%);
+ background-size: 200% 100%;
+ animation: rr-shimmer 1.4s ease-in-out infinite;
+ border-radius: var(--rr-r);
+}
+.rr-skel .rr-kpi {
+ border: 0;
+}
+.rr-skel-row {
+ height: 64px;
+ margin-bottom: 10px;
+}
+.rr-skel-head {
+ height: 180px;
+ margin-bottom: 16px;
+}
+@keyframes rr-shimmer {
+ from { background-position: 200% 0; }
+ to { background-position: -200% 0; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .rr-shimmer { animation: none; }
+ .rr-btn { transition: none; }
+}
+
+@media (max-width: 560px) {
+ .rr-eo {
+ grid-template-columns: 1fr;
+ gap: 2px;
+ }
+ .rr-eo dd {
+ margin-bottom: 8px;
+ }
+ .rr-step__time {
+ margin-left: 0;
+ }
+ .rr-cmd {
+ flex-direction: column;
+ align-items: stretch;
+ }
+}
diff --git a/src/runs.js b/src/runs.js
new file mode 100644
index 000000000..8defb5887
--- /dev/null
+++ b/src/runs.js
@@ -0,0 +1,388 @@
+// /runs and /runs/:id: run receipts, the per-generation record of what each
+// Studio stage was expected to do, what it actually did, and the verdict.
+//
+// /runs aggregate view across every receipt in a window (GET /api/runs?stats=1)
+// /runs/:id one receipt as a stage timeline, plus its signature check (GET /api/runs?id=)
+//
+// Everything a receipt says is rendered with textContent: prompts and causes are
+// user and pipeline text, never markup.
+
+const root = document.getElementById('rr-root');
+const DAY_CHOICES = [1, 7, 30, 90];
+const VERDICT_LABEL = { met: 'Met', recovered: 'Recovered', missed: 'Missed', skipped: 'Skipped', pending: 'Pending' };
+const OUTCOME_LABEL = {
+ delivered: 'Delivered as expected',
+ delivered_with_issues: 'Delivered, with issues noted',
+ partial: 'Partly delivered',
+ pending: 'Still running',
+ refused: 'Refused before any work ran',
+ failed: 'Not delivered',
+};
+const OUTCOME_TONE = { delivered: 'met', delivered_with_issues: 'missed', partial: 'recovered', pending: 'pending', refused: 'skipped', failed: 'missed' };
+const TOOL_LABEL = {
+ forge_avatar: 'Rigged avatar',
+ text_to_avatar: 'Avatar',
+ mesh_forge: 'Mesh',
+ forge_free: 'Model',
+ rig_mesh: 'Rig a mesh',
+ refine_model: 'Refinement',
+};
+const ID_RE = /rr_[1-9A-HJ-NP-Za-km-z]{16,32}/;
+
+function el(tag, attrs = {}, ...children) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v === true ? '' : v);
+ }
+ for (const c of children.flat()) if (c != null && c !== false) node.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ return node;
+}
+
+const pct = (n) => (n == null ? 'n/a' : `${Math.round(n * 1000) / 10}%`);
+const secs = (ms) => (Number.isFinite(ms) ? (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s` : `${(ms / 1000).toFixed(1)}s`) : null);
+const when = (iso) => {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? '' : d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
+};
+
+async function getJson(url) {
+ const res = await fetch(url, { headers: { accept: 'application/json' } });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw Object.assign(new Error(body?.error_description || body?.message || `The server answered ${res.status}.`), { status: res.status });
+ return body;
+}
+
+function errorState(title, message, retry) {
+ return el(
+ 'div',
+ { class: 'rr-state rr-state--error', role: 'alert' },
+ el('h2', { text: title }),
+ el('p', { text: message }),
+ retry ? el('button', { class: 'rr-btn', type: 'button', onclick: retry, text: 'Try again' }) : null,
+ );
+}
+
+function lookupForm() {
+ const input = el('input', {
+ class: 'rr-input',
+ type: 'text',
+ name: 'receipt',
+ placeholder: 'Paste a receipt link or id (rr_…)',
+ 'aria-label': 'Receipt link or id',
+ autocomplete: 'off',
+ spellcheck: 'false',
+ });
+ const hint = el('p', { class: 'rr-hint', 'aria-live': 'polite' });
+ const form = el(
+ 'form',
+ {
+ class: 'rr-lookup',
+ onsubmit: (e) => {
+ e.preventDefault();
+ const id = ID_RE.exec(input.value)?.[0];
+ if (!id) {
+ hint.textContent = 'That is not a receipt id. They start with rr_ and come at the end of every Studio result.';
+ input.focus();
+ return;
+ }
+ history.pushState(null, '', `/runs/${id}`);
+ route();
+ },
+ },
+ input,
+ el('button', { class: 'rr-btn rr-btn--primary', type: 'submit', text: 'Open receipt' }),
+ );
+ return el('div', {}, form, hint);
+}
+
+// ── index: the aggregate view ───────────────────────────────────────────────
+
+function skeletonIndex() {
+ return el(
+ 'div',
+ { class: 'rr-skel', 'aria-busy': 'true', 'aria-label': 'Loading run statistics' },
+ el('div', { class: 'rr-kpis' }, [0, 1, 2].map(() => el('div', { class: 'rr-kpi rr-shimmer' }))),
+ [0, 1, 2, 3, 4].map(() => el('div', { class: 'rr-skel-row rr-shimmer' })),
+ );
+}
+
+function verdictBar(verdicts, total) {
+ const bar = el('div', { class: 'rr-bar', role: 'img', 'aria-label': Object.entries(verdicts).map(([v, n]) => `${VERDICT_LABEL[v] || v} ${n}`).join(', ') });
+ for (const v of ['met', 'recovered', 'missed', 'skipped', 'pending']) {
+ const n = verdicts[v] || 0;
+ if (!n) continue;
+ bar.append(el('span', { class: `rr-bar__seg rr-tone--${v}`, style: `flex-grow:${n}`, title: `${VERDICT_LABEL[v]}: ${n} of ${total}` }));
+ }
+ return bar;
+}
+
+async function renderIndex(days) {
+ document.title = 'Run Receipts · three.ws';
+ const picker = el(
+ 'div',
+ { class: 'rr-days', role: 'group', 'aria-label': 'Time window' },
+ DAY_CHOICES.map((d) =>
+ el('button', {
+ type: 'button',
+ class: `rr-chip${d === days ? ' is-active' : ''}`,
+ 'aria-pressed': String(d === days),
+ text: d === 1 ? '24 hours' : `${d} days`,
+ onclick: () => {
+ history.replaceState(null, '', d === 7 ? '/runs' : `/runs?days=${d}`);
+ renderIndex(d);
+ },
+ }),
+ ),
+ );
+ const body = el('div', {}, skeletonIndex());
+ root.replaceChildren(lookupForm(), el('div', { class: 'rr-toolbar' }, el('h2', { class: 'rr-h2', text: 'Across every run' }), picker), body);
+
+ let stats;
+ try {
+ stats = await getJson(`/api/runs?stats=1&days=${days}`);
+ } catch (err) {
+ body.replaceChildren(errorState('Could not load run statistics', `${err.message} Your receipt links still work; this only affects the summary.`, () => renderIndex(days)));
+ return;
+ }
+ if (!stats.total) {
+ body.replaceChildren(
+ el(
+ 'div',
+ { class: 'rr-state' },
+ el('h2', { text: `No runs in the last ${days === 1 ? '24 hours' : `${days} days`}` }),
+ el('p', { text: 'Receipts appear here as soon as anyone generates a model, an avatar, or a rig through the free 3D Studio MCP server, including npm create @three-ws/agent.' }),
+ el('div', { class: 'rr-actions' }, el('a', { class: 'rr-btn rr-btn--primary', href: '/docs/mcp-studio', text: 'Connect the 3D Studio' }), days < 90 ? el('button', { class: 'rr-btn', type: 'button', text: 'Widen to 90 days', onclick: () => renderIndex(90) }) : null),
+ ),
+ );
+ return;
+ }
+
+ const kpis = el(
+ 'div',
+ { class: 'rr-kpis' },
+ el('div', { class: 'rr-kpi' }, el('span', { class: 'rr-kpi__n', text: stats.total.toLocaleString() }), el('span', { class: 'rr-kpi__l', text: 'runs recorded' })),
+ el('div', { class: 'rr-kpi' }, el('span', { class: 'rr-kpi__n', text: pct(stats.delivery_rate) }), el('span', { class: 'rr-kpi__l', text: 'delivered a file' })),
+ el('div', { class: 'rr-kpi' }, el('span', { class: 'rr-kpi__n', text: pct(stats.clean_rate) }), el('span', { class: 'rr-kpi__l', text: 'ran clean: no fallback, no miss' })),
+ );
+
+ const stageRows = stats.stages.map((s) =>
+ el(
+ 'li',
+ { class: 'rr-stage-row' },
+ el('div', { class: 'rr-stage-row__head' }, el('span', { class: 'rr-stage-row__name', text: s.label }), el('span', { class: 'rr-stage-row__rate', text: s.met_rate == null ? 'not judged' : `${pct(s.met_rate)} met` })),
+ verdictBar(s.verdicts, s.total),
+ el(
+ 'div',
+ { class: 'rr-legend' },
+ Object.entries(s.verdicts).map(([v, n]) => el('span', { class: `rr-legend__item rr-tone--${v}` }, el('i', { 'aria-hidden': 'true' }), `${VERDICT_LABEL[v] || v} ${n}`)),
+ ),
+ ),
+ );
+
+ const causes = stats.top_causes.length
+ ? el(
+ 'ol',
+ { class: 'rr-causes' },
+ stats.top_causes.map((c) =>
+ el(
+ 'li',
+ {},
+ el('span', { class: `rr-verdict rr-tone--${c.verdict}`, text: VERDICT_LABEL[c.verdict] || c.verdict }),
+ el('span', { class: 'rr-causes__stage', text: c.label }),
+ el('span', { class: 'rr-causes__text', text: c.cause }),
+ el('span', { class: 'rr-causes__n', text: `×${c.count}` }),
+ ),
+ ),
+ )
+ : el('p', { class: 'rr-muted', text: 'No stage needed a fallback or missed its contract in this window.' });
+
+ const tools = el(
+ 'ul',
+ { class: 'rr-tools' },
+ Object.entries(stats.tools)
+ .sort((a, b) => b[1].total - a[1].total)
+ .map(([tool, t]) =>
+ el(
+ 'li',
+ {},
+ el('span', { class: 'rr-tools__name', text: TOOL_LABEL[tool] || tool }),
+ el('code', { text: tool }),
+ el('span', { class: 'rr-tools__n', text: `${t.total} run${t.total === 1 ? '' : 's'}` }),
+ el('span', { class: 'rr-muted', text: Object.entries(t.outcomes).map(([o, n]) => `${n} ${(OUTCOME_LABEL[o] || o).toLowerCase()}`).join(' · ') }),
+ ),
+ ),
+ );
+
+ body.replaceChildren(
+ kpis,
+ el('section', { class: 'rr-card' }, el('h3', { class: 'rr-h3', text: 'Stage by stage' }), el('p', { class: 'rr-muted', text: 'Skipped and still-running stages are left out of the met rate.' }), el('ul', { class: 'rr-stage-list' }, stageRows)),
+ el('section', { class: 'rr-card' }, el('h3', { class: 'rr-h3', text: 'Most common causes' }), causes),
+ el('section', { class: 'rr-card' }, el('h3', { class: 'rr-h3', text: 'By tool' }), tools),
+ stats.signer ? el('p', { class: 'rr-muted rr-signer' }, 'Receipts are signed by ', el('code', { text: stats.signer }), '.') : null,
+ );
+}
+
+// ── detail: one receipt ─────────────────────────────────────────────────────
+
+function metricsList(metrics) {
+ if (!metrics) return null;
+ const items = [];
+ for (const [k, v] of Object.entries(metrics)) {
+ if (v == null) continue;
+ const value = Array.isArray(v) ? v.join(', ') : typeof v === 'object' ? Object.entries(v).map(([a, b]) => `${a} ${b}`).join(' · ') : typeof v === 'number' ? v.toLocaleString() : String(v);
+ items.push(el('div', { class: 'rr-metric' }, el('dt', { text: k.replace(/_/g, ' ') }), el('dd', { text: value })));
+ }
+ return items.length ? el('dl', { class: 'rr-metrics' }, items) : null;
+}
+
+function stageCard(s, i) {
+ const time = secs(s.ms);
+ return el(
+ 'li',
+ { class: `rr-step rr-tone--${s.verdict}` },
+ el('div', { class: 'rr-step__dot', 'aria-hidden': 'true', text: String(i + 1) }),
+ el(
+ 'div',
+ { class: 'rr-step__body' },
+ el(
+ 'div',
+ { class: 'rr-step__head' },
+ el('h3', { class: 'rr-step__name', text: s.label }),
+ el('span', { class: `rr-verdict rr-tone--${s.verdict}`, text: VERDICT_LABEL[s.verdict] || s.verdict }),
+ time ? el('span', { class: 'rr-step__time', text: time }) : null,
+ ),
+ el('dl', { class: 'rr-eo' }, el('dt', { text: 'Expected' }), el('dd', { text: s.expected || '' }), el('dt', { text: 'Observed' }), el('dd', { text: s.observed || '' }), s.cause ? [el('dt', { text: 'Cause' }), el('dd', { class: 'rr-eo__cause', text: s.cause })] : null),
+ metricsList(s.metrics),
+ ),
+ );
+}
+
+function copyButton(label, value) {
+ const btn = el('button', {
+ class: 'rr-btn rr-btn--small',
+ type: 'button',
+ text: label,
+ onclick: async () => {
+ try {
+ await navigator.clipboard.writeText(value);
+ btn.textContent = 'Copied';
+ } catch {
+ btn.textContent = 'Copy failed: select the text instead';
+ }
+ setTimeout(() => (btn.textContent = label), 1600);
+ },
+ });
+ return btn;
+}
+
+function verificationPanel(data) {
+ const v = data.verification || { ok: false, checks: [] };
+ const r = data.receipt;
+ const cmd = `node scripts/run-receipt-verify.mjs ${r.id}${data.signer ? ` --signer ${data.signer}` : ''}`;
+ const download = () => {
+ const blob = new Blob([JSON.stringify({ receipt: data.receipt, sha256: data.sha256, signature: data.signature, signer: data.signer }, null, 2)], { type: 'application/json' });
+ const a = el('a', { href: URL.createObjectURL(blob), download: `${r.id}.json` });
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+ };
+ return el(
+ 'section',
+ { class: `rr-card rr-verify ${v.ok ? 'is-ok' : 'is-bad'}` },
+ el('h3', { class: 'rr-h3', text: v.ok ? 'Signature verified' : data.signature ? 'Signature did not verify' : 'Unsigned receipt' }),
+ el(
+ 'p',
+ { class: 'rr-muted', text: v.ok ? 'This record is exactly what the pipeline wrote when the run finished. Changing any word in it breaks the signature.' : data.signature ? 'The stored record no longer matches its signature. Treat its contents as unverified.' : 'This deployment had no signing key configured when the run finished, so the record is hashed but not signed.' },
+ ),
+ el('ul', { class: 'rr-checks' }, v.checks.map((c) => el('li', { class: c.ok ? 'is-ok' : 'is-bad' }, el('span', { 'aria-hidden': 'true', text: c.ok ? '✓' : '✕' }), el('strong', { text: c.name }), c.detail ? ` ${c.detail}` : ''))),
+ el('dl', { class: 'rr-ids' }, el('dt', { text: 'sha256' }), el('dd', {}, el('code', { text: data.sha256 })), data.signer ? [el('dt', { text: 'signer' }), el('dd', {}, el('code', { text: data.signer }))] : null),
+ el('p', { class: 'rr-muted', text: 'Check it yourself, without trusting this page:' }),
+ el('div', { class: 'rr-cmd' }, el('code', { text: cmd }), copyButton('Copy', cmd)),
+ el('div', { class: 'rr-actions' }, el('button', { class: 'rr-btn', type: 'button', text: 'Download JSON', onclick: download }), el('a', { class: 'rr-btn', href: `/api/runs?id=${encodeURIComponent(r.id)}`, target: '_blank', rel: 'noopener', text: 'Raw API response' })),
+ );
+}
+
+async function renderReceipt(id) {
+ root.replaceChildren(el('div', { class: 'rr-skel', 'aria-busy': 'true', 'aria-label': 'Loading receipt' }, el('div', { class: 'rr-skel-head rr-shimmer' }), [0, 1, 2, 3, 4].map(() => el('div', { class: 'rr-skel-row rr-shimmer' }))));
+ let data;
+ try {
+ data = await getJson(`/api/runs?id=${encodeURIComponent(id)}`);
+ } catch (err) {
+ root.replaceChildren(
+ err.status === 404
+ ? errorState('No receipt with that id', 'Check the link was copied in full. Receipt ids start with rr_ and are case-sensitive.', null)
+ : errorState('Could not load this receipt', err.message, () => renderReceipt(id)),
+ el('p', {}, el('a', { href: '/runs', text: 'Back to all runs' })),
+ );
+ return;
+ }
+ const r = data.receipt;
+ const tone = OUTCOME_TONE[r.outcome] || 'skipped';
+ document.title = `${OUTCOME_LABEL[r.outcome] || r.outcome} · Run receipt · three.ws`;
+ document.getElementById('rr-title').textContent = `${TOOL_LABEL[r.tool] || r.tool} run`;
+
+ const facts = [
+ when(r.started_at),
+ secs(r.duration_ms) ? `took ${secs(r.duration_ms)}` : null,
+ r.input?.reference_image ? 'from a reference image' : null,
+ ].filter(Boolean);
+
+ const head = el(
+ 'section',
+ { class: `rr-card rr-outcome rr-tone--${tone}` },
+ el('div', { class: 'rr-outcome__row' }, el('span', { class: `rr-verdict rr-tone--${tone}`, text: OUTCOME_LABEL[r.outcome] || r.outcome }), el('code', { class: 'rr-outcome__tool', text: r.tool })),
+ r.input?.prompt ? el('blockquote', { class: 'rr-prompt', text: r.input.prompt }) : el('p', { class: 'rr-muted', text: r.outcome === 'refused' ? 'The prompt is not kept on a refused request.' : 'No text prompt.' }),
+ el('p', { class: 'rr-outcome__summary', text: r.summary }),
+ el('p', { class: 'rr-muted', text: facts.join(' · ') }),
+ r.output?.glb_url
+ ? el('div', { class: 'rr-actions' }, el('a', { class: 'rr-btn rr-btn--primary', href: r.output.viewer_url || `/viewer?src=${encodeURIComponent(r.output.glb_url)}`, text: 'Open the model' }), el('a', { class: 'rr-btn', href: r.output.glb_url, text: 'Download GLB' }))
+ : null,
+ r.outcome === 'pending'
+ ? el('div', { class: 'rr-pending' }, el('p', { text: 'A stage was still running when the tool answered. This receipt completes when the job is collected (check_job, or the viewer link from the result).' }), el('button', { class: 'rr-btn', type: 'button', text: 'Refresh', onclick: () => renderReceipt(id) }))
+ : null,
+ );
+
+ const issues = (r.issues || []).length
+ ? el(
+ 'section',
+ { class: 'rr-card' },
+ el('h3', { class: 'rr-h3', text: 'What did not go as expected' }),
+ el(
+ 'ul',
+ { class: 'rr-issues' },
+ r.issues.map((i) =>
+ el('li', {}, el('span', { class: `rr-verdict rr-tone--${i.verdict}`, text: VERDICT_LABEL[i.verdict] }), el('strong', { text: i.label }), el('span', { text: ` Expected ${lc(i.expected)} Observed ${lc(i.observed)}${i.cause ? ` Because: ${lc(i.cause)}` : ''}` })),
+ ),
+ ),
+ )
+ : null;
+
+ root.replaceChildren(
+ el('p', { class: 'rr-back' }, el('a', { href: '/runs', text: '← All runs' })),
+ head,
+ issues,
+ el('section', { class: 'rr-card' }, el('h3', { class: 'rr-h3', text: 'Every stage' }), el('ol', { class: 'rr-steps' }, r.stages.map(stageCard))),
+ verificationPanel(data),
+ );
+}
+
+const lc = (s) => (s ? s.charAt(0).toLowerCase() + s.slice(1) : '');
+
+function route() {
+ const m = /^\/runs\/([^/]+)\/?$/.exec(location.pathname);
+ if (m && ID_RE.test(decodeURIComponent(m[1]))) return renderReceipt(decodeURIComponent(m[1]));
+ if (m) {
+ root.replaceChildren(errorState('That is not a receipt link', 'Receipt ids start with rr_. Paste the full link from the Studio result.', null), lookupForm());
+ return;
+ }
+ const days = Number(new URLSearchParams(location.search).get('days'));
+ return renderIndex(DAY_CHOICES.includes(days) ? days : 7);
+}
+
+window.addEventListener('popstate', route);
+route();
diff --git a/tests/run-receipt.test.js b/tests/run-receipt.test.js
new file mode 100644
index 000000000..59069b19c
--- /dev/null
+++ b/tests/run-receipt.test.js
@@ -0,0 +1,391 @@
+// Run receipts: the per-generation record of what each stage was expected to
+// do, what it actually did, and the verdict. Pins the pure core (verdicts,
+// outcome derivation, signing), the stat reshaping, the rig read-back against
+// a real GLB, and the studio wiring end to end through dispatch.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { ed25519 } from '@noble/curves/ed25519.js';
+
+import {
+ RUN_RECEIPT_TYPE,
+ newReceiptId,
+ isReceiptId,
+ jobRef,
+ startReceipt,
+ addStage,
+ finishReceipt,
+ inputStage,
+ subjectGateStage,
+ briefStage,
+ meshStage,
+ geometryStage,
+ visualQaStage,
+ rigStage,
+ deliveryStage,
+ signReceipt,
+ verifyReceipt,
+ receiptHash,
+} from '../api/_lib/run-receipt.js';
+import { summarizeStats, inspectRiggedGlb, engineLabel, sealReceipt, resetSigningKeyCache } from '../api/_lib/run-receipt-store.js';
+import { attachReceipt } from '../api/_mcp-studio/receipts.js';
+import { dispatch } from '../api/_mcp-studio/dispatch.js';
+
+// A real binary glTF: header, JSON chunk, no BIN chunk. analyzeGlb only reads
+// the JSON, which is exactly what the rig read-back fetches.
+function buildGlb(json) {
+ let text = JSON.stringify(json);
+ while (Buffer.byteLength(text) % 4) text += ' ';
+ const body = Buffer.from(text, 'utf8');
+ const out = Buffer.alloc(12 + 8 + body.length);
+ out.write('glTF', 0, 'ascii');
+ out.writeUInt32LE(2, 4);
+ out.writeUInt32LE(out.length, 8);
+ out.writeUInt32LE(body.length, 12);
+ out.writeUInt32LE(0x4e4f534a, 16);
+ body.copy(out, 20);
+ return out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
+}
+
+const MIXAMO = [
+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',
+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+];
+
+function riggedGlb(bones = MIXAMO, { skinned = true } = {}) {
+ const joints = bones.map((b) => ({ name: `mixamorig:${b}` }));
+ const nodes = [...joints, { name: 'Body', mesh: 0, ...(skinned ? { skin: 0 } : {}) }];
+ return buildGlb({
+ asset: { version: '2.0', generator: 'test' },
+ nodes,
+ meshes: [{ primitives: [{ attributes: {} }] }],
+ skins: [{ joints: joints.map((_, i) => i) }],
+ });
+}
+
+function glbResponse(buf) {
+ return {
+ ok: true,
+ status: 206,
+ headers: { get: (h) => (h.toLowerCase() === 'content-length' ? String(buf.byteLength) : null) },
+ arrayBuffer: async () => buf,
+ };
+}
+
+describe('run receipt core', () => {
+ it('mints unguessable public ids and hashes job handles instead of storing them', () => {
+ const a = newReceiptId();
+ expect(isReceiptId(a)).toBe(true);
+ expect(a).not.toBe(newReceiptId());
+ expect(isReceiptId('rr_short')).toBe(false);
+ expect(isReceiptId('../etc/passwd')).toBe(false);
+ const ref = jobRef('job-token-abc');
+ expect(ref).toMatch(/^[0-9a-f]{40}$/);
+ expect(ref).not.toContain('job-token');
+ expect(jobRef('')).toBeNull();
+ });
+
+ it('records a clean run as delivered, every stage met', () => {
+ const r = startReceipt({ tool: 'forge_avatar', prompt: 'a knight in silver armor', now: 1000 });
+ addStage(r, inputStage({ allowed: true, hasPrompt: true }));
+ addStage(r, briefStage({ kind: 'avatar', directed: true }));
+ addStage(r, meshStage({ frame: { glb_url: 'https://x/a.glb', tier: 'high', backend: 'hunyuan3d' }, expectedTier: 'high', labelFor: engineLabel }));
+ addStage(r, deliveryStage({ frame: { glb_url: 'https://x/a.glb', durable: true } }));
+ const done = finishReceipt(r, { glbUrl: 'https://x/a.glb', now: 4000 });
+ expect(done.type).toBe(RUN_RECEIPT_TYPE);
+ expect(done.outcome).toBe('delivered');
+ expect(done.issues).toEqual([]);
+ expect(done.duration_ms).toBe(3000);
+ expect(done.summary).toMatch(/every stage met its contract/);
+ expect(done.stages.find((s) => s.id === 'mesh').observed).toMatch(/high-detail tier on Hunyuan3D/);
+ });
+
+ it('names a quiet tier downgrade as recovered, with the cause', () => {
+ const s = meshStage({ frame: { glb_url: 'https://x/a.glb', tier: 'standard', backend: 'trellis_selfhost' }, expectedTier: 'high', labelFor: engineLabel });
+ expect(s.verdict).toBe('recovered');
+ expect(s.expected).toMatch(/high-detail/);
+ expect(s.observed).toMatch(/standard tier/);
+ expect(s.cause).toMatch(/did not accept the job/);
+ });
+
+ it('names the fixed fallback brief as recovered, not met', () => {
+ const s = briefStage({ kind: 'avatar', directed: false });
+ expect(s.verdict).toBe('recovered');
+ expect(s.cause).toMatch(/fixed brief/);
+ expect(briefStage({ kind: 'avatar', hasImage: true }).verdict).toBe('skipped');
+ expect(briefStage({ kind: 'mesh', knownMark: true }).verdict).toBe('met');
+ });
+
+ it('turns away a non-humanoid avatar before spending GPU time, and says so', () => {
+ const s = subjectGateStage({ nonHumanoid: true });
+ expect(s.verdict).toBe('missed');
+ expect(subjectGateStage({ nonHumanoid: true, override: true }).verdict).toBe('recovered');
+ expect(subjectGateStage({ hasImage: true }).verdict).toBe('skipped');
+ });
+
+ it('says plainly that a caller-supplied mesh was never checked for being a body', () => {
+ // The rigger fits a full humanoid template to anything (a lantern came back
+ // with 52 Mixamo joints), so a passing rig check alone would overstate it.
+ const s = subjectGateStage({ givenMesh: true });
+ expect(s.verdict).toBe('skipped');
+ expect(s.observed).toMatch(/not checked/i);
+ expect(s.cause).toMatch(/skeleton.*not.*character|structure/i);
+ });
+
+ it('reads geometry and vision scores off the frame, never inventing them', () => {
+ const good = geometryStage({ quality: { valid: true, flag: 'ok', score: 0.92, metrics: { triangleCount: 48211, vertexCount: 25000, hasTextures: true } } });
+ expect(good.verdict).toBe('met');
+ expect(good.observed).toMatch(/48,211 triangles/);
+ expect(geometryStage({ quality: { valid: true, score: 0.8, metrics: {} }, retried: true }).verdict).toBe('recovered');
+ const bad = geometryStage({ quality: { valid: false, flag: 'degenerate', reasons: ['too_few_triangles'] } });
+ expect(bad.verdict).toBe('missed');
+ expect(bad.cause).toMatch(/too few triangles/);
+ expect(geometryStage({}).verdict).toBe('skipped');
+
+ expect(visualQaStage({ gate: { pass: true, score: 8 } }).verdict).toBe('met');
+ const failed = visualQaStage({ gate: { pass: false, score: 3, defects: ['missing hands'], reason: 'hands cropped' } });
+ expect(failed.verdict).toBe('missed');
+ expect(failed.cause).toBe('hands cropped');
+ expect(visualQaStage({ gate: { qa_available: false } }).verdict).toBe('skipped');
+ expect(visualQaStage({}).verdict).toBe('skipped');
+ });
+
+ it('marks an expiring engine link as recovered delivery', () => {
+ expect(deliveryStage({ frame: { glb_url: 'https://x', durable: false } }).verdict).toBe('recovered');
+ expect(deliveryStage({ frame: {} }).verdict).toBe('missed');
+ });
+
+ it('restates every miss as expected vs observed vs cause, and never claims better than the stages', () => {
+ const r = startReceipt({ tool: 'forge_avatar', prompt: 'p' });
+ addStage(r, rigStage({ error: 'Rigging failed for this mesh.' }));
+ const done = finishReceipt(r, { glbUrl: 'https://x/a.glb', outcome: 'delivered' });
+ expect(done.outcome).toBe('delivered_with_issues');
+ expect(done.issues).toEqual([
+ expect.objectContaining({ stage: 'rig', verdict: 'missed', expected: expect.stringMatching(/skinned humanoid/), cause: 'Rigging failed for this mesh.' }),
+ ]);
+ expect(finishReceipt(r, { glbUrl: 'https://x/a.glb', outcome: 'partial' }).outcome).toBe('partial');
+ expect(finishReceipt(r, {}).outcome).toBe('failed');
+ });
+
+ it('stays pending while any stage is pending', () => {
+ const r = startReceipt({ tool: 'mesh_forge', prompt: 'p' });
+ addStage(r, meshStage({ timedOut: true, expectedTier: 'standard' }));
+ const done = finishReceipt(r, {});
+ expect(done.outcome).toBe('pending');
+ expect(done.finished_at).toBeNull();
+ // The collected job replaces the pending stage rather than adding a second one.
+ addStage(r, meshStage({ frame: { glb_url: 'https://x', tier: 'standard' }, expectedTier: 'standard' }));
+ expect(r.stages).toHaveLength(1);
+ expect(r.stages[0].verdict).toBe('met');
+ });
+
+ it('signs, verifies, pins the issuer, and catches tampering', () => {
+ const seed = ed25519.utils.randomSecretKey();
+ const r = finishReceipt(startReceipt({ tool: 'mesh_forge', prompt: 'p' }), {});
+ const env = signReceipt(r, seed);
+ expect(env.sha256).toBe(receiptHash(r));
+ expect(verifyReceipt(env).ok).toBe(true);
+ expect(verifyReceipt(env, { trustedSigner: env.signer }).ok).toBe(true);
+ expect(verifyReceipt(env, { trustedSigner: 'someoneElse' }).ok).toBe(false);
+
+ const tampered = { ...env, receipt: { ...env.receipt, outcome: 'delivered' } };
+ const v = verifyReceipt(tampered);
+ expect(v.ok).toBe(false);
+ expect(v.checks.find((c) => c.name === 'hash').ok).toBe(false);
+ expect(v.checks.find((c) => c.name === 'signature').ok).toBe(false);
+
+ const unsigned = { ...env, signature: null, signer: null };
+ expect(verifyReceipt(unsigned).ok).toBe(false);
+ });
+});
+
+describe('run receipt store', () => {
+ const saved = process.env.ATTEST_AGENT_SECRET_KEY;
+ afterEach(() => {
+ if (saved === undefined) delete process.env.ATTEST_AGENT_SECRET_KEY;
+ else process.env.ATTEST_AGENT_SECRET_KEY = saved;
+ resetSigningKeyCache();
+ });
+
+ it('seals honestly unsigned when no issuer key is configured', async () => {
+ delete process.env.ATTEST_AGENT_SECRET_KEY;
+ resetSigningKeyCache();
+ const r = finishReceipt(startReceipt({ tool: 'mesh_forge', prompt: 'p' }), {});
+ const env = await sealReceipt(r);
+ expect(env.signature).toBeNull();
+ expect(env.signer).toBeNull();
+ expect(env.sha256).toBe(receiptHash(r));
+ });
+
+ it('maps engine ids to their public label and hides unknown ones', () => {
+ expect(engineLabel('hunyuan3d')).toBe('Hunyuan3D');
+ expect(engineLabel('some_internal_lane')).toBe('a backup engine');
+ expect(engineLabel(null)).toBe('a backup engine');
+ });
+
+ it('reshapes the stat queries into rates in pipeline order', () => {
+ const s = summarizeStats({
+ days: 7,
+ outcomes: [
+ // One of the six delivered runs leaned on a fallback brief, so it is not clean.
+ { tool: 'forge_avatar', outcome: 'delivered', n: 6, clean: 5 },
+ { tool: 'forge_avatar', outcome: 'delivered_with_issues', n: 2, clean: 0 },
+ { tool: 'mesh_forge', outcome: 'failed', n: 1 },
+ { tool: 'mesh_forge', outcome: 'refused', n: 1 },
+ ],
+ stages: [
+ { stage: 'rig', label: 'Rig', verdict: 'met', n: 6 },
+ { stage: 'rig', label: 'Rig', verdict: 'missed', n: 2 },
+ { stage: 'brief', label: 'Brief', verdict: 'met', n: 7 },
+ { stage: 'brief', label: 'Brief', verdict: 'recovered', n: 1 },
+ { stage: 'brief', label: 'Brief', verdict: 'skipped', n: 2 },
+ ],
+ causes: [{ stage: 'rig', label: 'Rig', verdict: 'missed', cause: 'Missing key bones: LeftUpLeg.', n: 2 }],
+ });
+ expect(s.total).toBe(10);
+ // Refusals are not deliveries that failed; they are excluded from the rate.
+ expect(s.delivery_rate).toBeCloseTo(8 / 9, 3);
+ // Clean means delivered with no stage recovered or missed, not merely "delivered".
+ expect(s.clean_rate).toBeCloseTo(5 / 9, 3);
+ expect(s.stages.map((x) => x.id)).toEqual(['brief', 'rig']);
+ expect(s.stages[0].judged).toBe(8);
+ expect(s.stages[0].met_rate).toBeCloseTo(7 / 8, 3);
+ expect(s.top_causes[0]).toEqual({ stage: 'rig', label: 'Rig', verdict: 'missed', cause: 'Missing key bones: LeftUpLeg.', count: 2 });
+ });
+
+ describe('rig read-back', () => {
+ let realFetch;
+ beforeEach(() => {
+ realFetch = globalThis.fetch;
+ });
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ it('verifies a full humanoid rig from the delivered file', async () => {
+ globalThis.fetch = vi.fn(async () => glbResponse(riggedGlb()));
+ const { report, error } = await inspectRiggedGlb('https://three.ws/cdn/rigged.glb');
+ expect(error).toBeNull();
+ const s = rigStage({ report });
+ expect(s.verdict).toBe('met');
+ expect(s.metrics.convention).toBe('Mixamo');
+ expect(s.metrics.joints).toBe(MIXAMO.length);
+ expect(s.observed).toMatch(/torso, arms and legs all driven/);
+ // Only the head of the file is requested.
+ expect(globalThis.fetch.mock.calls[0][1].headers.Range).toMatch(/^bytes=0-/);
+ });
+
+ it('catches a rig with no legs: the avatar would slide instead of walk', async () => {
+ const noLegs = MIXAMO.filter((b) => !/Leg|Foot|Toe/.test(b));
+ globalThis.fetch = vi.fn(async () => glbResponse(riggedGlb(noLegs)));
+ const { report } = await inspectRiggedGlb('https://three.ws/cdn/rigged.glb');
+ const s = rigStage({ report });
+ expect(s.verdict).toBe('missed');
+ expect(s.observed).toMatch(/legs not mapped/);
+ expect(s.cause).toMatch(/LeftUpLeg/);
+ });
+
+ it('catches a skeleton with no skin weights', async () => {
+ globalThis.fetch = vi.fn(async () => glbResponse(riggedGlb(MIXAMO, { skinned: false })));
+ const { report } = await inspectRiggedGlb('https://three.ws/cdn/rigged.glb');
+ expect(rigStage({ report }).verdict).toBe('missed');
+ });
+
+ it('says it could not verify rather than guessing when the file is unreadable', async () => {
+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 404 }));
+ const { report, error } = await inspectRiggedGlb('https://three.ws/cdn/gone.glb');
+ expect(report).toBeNull();
+ const s = rigStage({ report, inspectError: error });
+ expect(s.verdict).toBe('skipped');
+ expect(s.cause).toMatch(/404/);
+ });
+ });
+});
+
+describe('studio wiring', () => {
+ const auth = { userId: null, rateKey: '127.0.0.1', scope: '' };
+ const mkReq = () => ({ headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } });
+ let realFetch;
+ beforeEach(() => {
+ realFetch = globalThis.fetch;
+ });
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ it('attaches a receipt without disturbing the result it rides on', () => {
+ const result = { content: [{ type: 'text', text: 'Generated a 3D model.' }], structuredContent: { glbUrl: 'https://x' } };
+ const r = finishReceipt(startReceipt({ tool: 'mesh_forge', prompt: 'p' }), { glbUrl: 'https://x' });
+ const out = attachReceipt(result, r, 'https://three.ws/runs/' + r.id);
+ expect(out.structuredContent.glbUrl).toBe('https://x');
+ expect(out.structuredContent.receipt).toMatchObject({ id: r.id, outcome: 'delivered', url: `https://three.ws/runs/${r.id}` });
+ expect(out.content[0].text).toMatch(/^Generated a 3D model\.\nRun receipt/);
+ expect(result.content[0].text).toBe('Generated a 3D model.');
+ });
+
+ it('records a full forge_avatar run: fallback brief, tier downgrade, and a rig verified from the file', async () => {
+ const rigged = riggedGlb();
+ globalThis.fetch = vi.fn(async (url, init) => {
+ const u = String(url);
+ if (u.endsWith('/rigged.glb')) return glbResponse(rigged);
+ if (/\/api\/(gpt-)?forge/.test(u)) {
+ // The rig submit is ?action=rig; its job polls back as R1.
+ const isRig = /action=rig|job=R1/.test(u);
+ return {
+ ok: true,
+ status: 200,
+ json: async () =>
+ isRig
+ ? { status: 'done', glb_url: 'https://three.ws/cdn/rigged.glb', job_id: 'R1', durable: true }
+ : {
+ status: 'done',
+ glb_url: 'https://three.ws/cdn/mesh.glb',
+ job_id: 'M1',
+ tier: 'standard',
+ backend: 'trellis_selfhost',
+ durable: true,
+ quality: { valid: true, flag: 'ok', score: 0.9, metrics: { triangleCount: 40000, hasTextures: true } },
+ },
+ };
+ }
+ // The director's LLM chain answers unusably: the fixed brief carries the run.
+ return { ok: false, status: 503, json: async () => ({}), text: async () => '' };
+ });
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'forge_avatar', arguments: { prompt: 'a knight in silver plate armor' } } },
+ auth,
+ mkReq(),
+ );
+ const sc = r.result.structuredContent;
+ expect(sc.rigged).toBe(true);
+ const receipt = sc.receipt;
+ expect(isReceiptId(receipt.id)).toBe(true);
+ const byStage = Object.fromEntries(receipt.issues.map((i) => [i.stage, i]));
+ expect(byStage.brief.verdict).toBe('recovered');
+ expect(byStage.mesh.verdict).toBe('recovered');
+ expect(byStage.mesh.observed).toMatch(/standard tier on TRELLIS/);
+ expect(byStage.rig).toBeUndefined();
+ // Recovered stages are named but the run still delivered what was asked.
+ expect(receipt.outcome).toBe('delivered');
+ expect(receipt.summary).toMatch(/carried by a fallback \(Brief, Mesh\)/);
+ // No database in tests, so the receipt is reported inline with no dead link.
+ expect(receipt.url).toBeUndefined();
+ expect(r.result.content[0].text).toMatch(/Run receipt: Delivered as expected/);
+ });
+
+ it('records a refusal with the prompt redacted', async () => {
+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 503, json: async () => ({}) }));
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'forge_avatar', arguments: { prompt: 'a wooden chair' } } },
+ auth,
+ mkReq(),
+ );
+ expect(r.result.isError).toBe(true);
+ expect(r.result.structuredContent.receipt.outcome).toBe('refused');
+ expect(r.result.structuredContent.receipt.issues[0]).toMatchObject({ stage: 'subject', verdict: 'missed' });
+ // The forge was never called: the gate fires before any GPU time.
+ expect(globalThis.fetch.mock.calls.some(([u]) => /\/api\/(gpt-)?forge/.test(String(u)))).toBe(false);
+ });
+});