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(scripts): run the likeness eval by hand for backfills and on-demand proofs

nirholas839fe3ead0d9
diff --git a/scripts/likeness-eval.mjs b/scripts/likeness-eval.mjs
new file mode 100644
index 000000000..dcf6178bf
--- /dev/null
+++ b/scripts/likeness-eval.mjs
@@ -0,0 +1,374 @@
+#!/usr/bin/env node
+// Likeness eval runner: the by-hand half of the Phase 1 likeness harness.
+//
+// /api/cron/likeness-eval is the bounded weekly sweep that keeps the score
+// table current. This is the tool for the jobs a 300-second cron cannot do:
+// backfilling a whole scorer version, and proving the instrument end to end on
+// real reconstructions produced on demand.
+//
+// Two modes.
+//
+// --backfill[=N] Score reconstructions the current scorer version has not
+// measured yet, straight from the database, and file the
+// results. Needs DATABASE_URL. This is the same work the
+// cron does, without the budget ceiling.
+//
+// --live=N Run N reconstructions through the REAL production
+// pipeline (sign in, POST /api/avatars/reconstruct, poll to
+// done) and score each finished avatar against the exact
+// reference image the pipeline built it from. Needs
+// AUDIT_EMAIL / AUDIT_PASSWORD. This is the mode that
+// answers "does the number mean anything" on a deployment
+// where the operator has no database access, because every
+// artifact in it is real and produced during the run.
+//
+// Live mode uses SYNTHESISED subjects, never real people's photos: each
+// reconstruction starts from a text description drawn from the platform's own
+// diversity matrix, which the pipeline turns into a frontal reference image and
+// then reconstructs. That keeps real biometrics out of a benchmark that gets
+// re-run and copied between machines, the same reasoning
+// workers/avatar-reconstruction/eval/make_refs.py applies to its reference set.
+//
+// A cross-subject control runs in both modes: every avatar is also scored
+// against every OTHER subject's captures. A likeness number is only meaningful
+// if the same instrument scores the wrong person materially lower, and the
+// separation between the two distributions is printed with the results.
+//
+// Usage:
+// node --env-file=.env scripts/likeness-eval.mjs --live=10
+// node --env-file=.env scripts/likeness-eval.mjs --backfill=25
+// node --env-file=.env scripts/likeness-eval.mjs --live=4 --out=reports/run.json
+
+import { writeFile, mkdir } from 'node:fs/promises';
+import path from 'node:path';
+import { cosineSimilarity, embedFace } from '../api/_lib/face-embed.js';
+import {
+ LIKENESS_VIEWS,
+ SCORER_VERSION,
+ SFACE_SAME_IDENTITY_COSINE,
+ cosineToScore5,
+ scoreLikeness,
+} from '../api/_lib/likeness-score.js';
+import {
+ likenessStoreEnabled,
+ recordLikenessScore,
+ unscoredReconstructions,
+} from '../api/_lib/likeness-store.js';
+
+const args = process.argv.slice(2);
+const flag = (name) => args.find((a) => a === `--${name}` || a.startsWith(`--${name}=`));
+const value = (name, fallback = null) => {
+ const found = flag(name);
+ if (!found) return fallback;
+ const eq = found.indexOf('=');
+ return eq < 0 ? true : found.slice(eq + 1);
+};
+
+const BASE_URL = String(value('base-url', process.env.BASE_URL || 'https://three.ws')).replace(/\/$/, '');
+const OUT = value('out', null);
+
+// The subject set for live mode: one line each, spanning skin tone, age, face
+// shape, facial hair, glasses, head covering and lighting, because a mean taken
+// over a narrow set hides exactly the failures that matter most. Ten entries so
+// `--live=10` needs no repeats.
+const LIVE_SUBJECTS = [
+ 'a woman in her twenties with deep brown skin, short natural curls and round cheeks',
+ 'a man in his sixties with pale skin, a full grey beard and deep-set eyes',
+ 'a woman in her forties with olive skin, straight dark hair and rectangular glasses',
+ 'a man in his thirties with light brown skin, a shaved head and a broad jaw',
+ 'a woman in her fifties with fair freckled skin and shoulder-length auburn hair',
+ 'a man in his twenties with dark brown skin, short twists and a narrow face',
+ 'a woman in her thirties with light skin, a black headscarf and thin eyebrows',
+ 'a man in his forties with tan skin, a thick moustache and heavy round glasses',
+ 'a woman in her sixties with light brown skin, silver hair in a bun and soft features',
+ 'a man in his fifties with pale skin, thinning blond hair and a long straight nose',
+];
+
+function log(...parts) {
+ console.log(...parts);
+}
+
+// ── live mode: drive the real reconstruction pipeline ────────────────────────
+
+async function login() {
+ const email = process.env.AUDIT_EMAIL;
+ const password = process.env.AUDIT_PASSWORD;
+ if (!email || !password) {
+ throw new Error('--live needs AUDIT_EMAIL and AUDIT_PASSWORD (they live in .env)');
+ }
+ const res = await fetch(`${BASE_URL}/api/auth/login`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ email, password }),
+ });
+ if (!res.ok) throw new Error(`login failed: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);
+ const cookies = typeof res.headers.getSetCookie === 'function' ? res.headers.getSetCookie() : [];
+ const jar = cookies.map((c) => c.split(';')[0]).join('; ');
+ if (!jar) throw new Error('login returned no session cookie');
+ return jar;
+}
+
+async function submitReconstruction(jar, subject, index) {
+ const res = await fetch(`${BASE_URL}/api/avatars/reconstruct`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', cookie: jar },
+ body: JSON.stringify({
+ name: `Likeness eval subject ${index + 1}`,
+ prompt: subject,
+ visibility: 'private',
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(`reconstruct submit ${res.status}: ${(data.message || data.error || '').slice(0, 200)}`);
+ }
+ return data;
+}
+
+async function pollReconstruction(jar, jobId, { timeoutMs = 10 * 60 * 1000, intervalMs = 6000 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const res = await fetch(`${BASE_URL}/api/avatars/regenerate-status?jobId=${encodeURIComponent(jobId)}`, {
+ headers: { cookie: jar },
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(`poll ${res.status}: ${(data.message || data.error || '').slice(0, 200)}`);
+ if (data.status === 'done') return data;
+ if (data.status === 'failed') throw new Error(`reconstruction failed: ${data.error || 'unknown'}`);
+ await new Promise((r) => setTimeout(r, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));
+ }
+ throw new Error(`reconstruction timed out after ${timeoutMs}ms`);
+}
+
+// The reference image the pipeline actually reconstructed from. The status
+// endpoint reports it for prompt-sourced jobs; without it there is no input
+// capture and the subject cannot be scored, which is a reported outcome rather
+// than a substituted one.
+function captureFrom(status) {
+ const meta = status?.avatar?.source_meta || status?.source_meta || {};
+ const params = status?.params || {};
+ const candidates = [
+ params.referenceImageUrl,
+ meta.referenceImageUrl,
+ meta.reference_image_url,
+ status?.referenceImageUrl,
+ ...(Array.isArray(params.images) ? params.images : []),
+ ];
+ return candidates.filter((v) => typeof v === 'string' && v);
+}
+
+function glbFrom(status) {
+ return (
+ status?.avatar?.glb_url ||
+ status?.avatar?.url ||
+ status?.result_glb_url ||
+ status?.glbUrl ||
+ null
+ );
+}
+
+async function runLive(count) {
+ const jar = await login();
+ const subjects = LIVE_SUBJECTS.slice(0, count);
+ log(`▶ live mode: ${subjects.length} reconstructions through ${BASE_URL}\n`);
+
+ const built = [];
+ for (const [i, subject] of subjects.entries()) {
+ try {
+ const submitted = await submitReconstruction(jar, subject, i);
+ log(` [${i + 1}/${subjects.length}] submitted ${submitted.jobId} (${submitted.provider})`);
+ const status = await pollReconstruction(jar, submitted.jobId);
+ const glbUrl = glbFrom(status);
+ const captures = captureFrom(status);
+ if (!glbUrl) throw new Error('finished job carried no GLB url');
+ if (!captures.length) throw new Error('finished job carried no reference image to score against');
+ built.push({ index: i, subject, jobId: submitted.jobId, glbUrl, captures, avatarId: status?.avatar?.id ?? null });
+ log(` [${i + 1}/${subjects.length}] done, ${captures.length} capture(s)`);
+ } catch (err) {
+ log(` [${i + 1}/${subjects.length}] FAILED: ${err.message}`);
+ built.push({ index: i, subject, error: String(err.message) });
+ }
+ }
+ return built.filter((b) => b.glbUrl);
+}
+
+// ── backfill mode: score what the database says is unmeasured ────────────────
+
+async function runBackfill(limit) {
+ if (!likenessStoreEnabled()) throw new Error('--backfill needs DATABASE_URL');
+ const subjects = await unscoredReconstructions({ limit });
+ log(`▶ backfill mode: ${subjects.length} unscored reconstruction(s) for ${SCORER_VERSION}\n`);
+ return subjects.map((s, i) => ({ ...s, index: i, subject: `creation ${s.creationId}` }));
+}
+
+// ── scoring + the cross-subject control ──────────────────────────────────────
+
+// Every avatar scored against every OTHER subject's captures. Without this the
+// headline numbers are unfalsifiable: a scorer that returned 0.8 for any two
+// faces would look identical to a working one on the matched pairs alone.
+async function crossControl(scored) {
+ const usable = scored.filter((s) => s.headOnEmbedding && s.captureEmbeddings?.length);
+ const sims = [];
+ for (const a of usable) {
+ for (const b of usable) {
+ if (a.index === b.index) continue;
+ const best = Math.max(...b.captureEmbeddings.map((e) => cosineSimilarity(a.headOnEmbedding, e)));
+ sims.push(best);
+ }
+ }
+ return sims;
+}
+
+// Re-derive the head-on embedding and the capture embeddings for the control.
+// scoreLikeness deliberately does not return embeddings (they are biometric and
+// must never reach a stored report), so the control computes its own inside
+// this process and lets them fall out of scope with it.
+async function embeddingsFor(subject) {
+ const { renderAvatarScene, SCENE_PRESETS } = await import('../api/_lib/avatar-render.js');
+ const headOn = LIKENESS_VIEWS.find((v) => v.label === 'head-on');
+ try {
+ const { png } = await renderAvatarScene({
+ glbUrl: subject.glbUrl,
+ width: 768,
+ height: 768,
+ background: '#14151a',
+ cameraOrbit: { theta: headOn.theta, phi: 86 },
+ scenePreset: SCENE_PRESETS.headshot,
+ });
+ const rendered = await embedFace(png);
+ const captures = [];
+ for (const capture of subject.captures) {
+ const res = await fetch(capture);
+ if (!res.ok) continue;
+ const embedded = await embedFace(Buffer.from(await res.arrayBuffer()));
+ if (embedded) captures.push(embedded.embedding);
+ }
+ return { headOnEmbedding: rendered?.embedding ?? null, captureEmbeddings: captures };
+ } catch {
+ return { headOnEmbedding: null, captureEmbeddings: [] };
+ }
+}
+
+function stats(values) {
+ if (!values.length) return null;
+ const sorted = [...values].sort((a, b) => a - b);
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
+ return {
+ n: values.length,
+ min: sorted[0],
+ median: sorted[Math.floor(sorted.length / 2)],
+ mean,
+ max: sorted[sorted.length - 1],
+ };
+}
+
+function fmt(n, digits = 3) {
+ return Number.isFinite(n) ? n.toFixed(digits) : ' n/a';
+}
+
+async function main() {
+ const liveArg = value('live', null);
+ const backfillArg = value('backfill', null);
+ if (!liveArg && !backfillArg) {
+ console.error('Usage: node --env-file=.env scripts/likeness-eval.mjs --live=10 | --backfill[=25]');
+ process.exitCode = 2;
+ return;
+ }
+
+ const subjects = liveArg
+ ? await runLive(Math.max(1, Math.min(LIVE_SUBJECTS.length, Number(liveArg) || 10)))
+ : await runBackfill(Math.max(1, Math.min(100, Number(backfillArg) || 25)));
+
+ if (!subjects.length) {
+ log('nothing to score');
+ return;
+ }
+
+ log(`\n▶ scoring ${subjects.length} subject(s) with ${SCORER_VERSION}\n`);
+ const scored = [];
+ for (const subject of subjects) {
+ const result = await scoreLikeness({ glbUrl: subject.glbUrl, captures: subject.captures });
+ const control = await embeddingsFor(subject);
+ let stored = false;
+ if (subject.creationId && likenessStoreEnabled()) {
+ stored = await recordLikenessScore({
+ creationId: subject.creationId,
+ avatarId: subject.avatarId,
+ jobId: subject.jobId,
+ result,
+ });
+ }
+ scored.push({ ...subject, result, ...control, stored });
+ const views = result.views
+ .map((v) => `${v.view}=${v.status === 'ok' ? fmt(v.cosine) : v.status}`)
+ .join(' ');
+ log(
+ ` [${subject.index + 1}] ${result.status.padEnd(18)} ` +
+ `score=${fmt(result.likenessScore, 2)} cos=${fmt(result.identityCosine)} ` +
+ `falloff=${fmt(result.turnFalloff)} ${stored ? 'stored' : 'not-stored'}\n` +
+ ` ${views}`,
+ );
+ }
+
+ const ok = scored.filter((s) => s.result.status === 'ok');
+ const matched = ok.map((s) => s.result.identityCosine);
+ const control = await crossControl(scored);
+
+ const matchedStats = stats(matched);
+ const controlStats = stats(control);
+ const scores = ok.map((s) => s.result.likenessScore);
+ const atGate = scores.filter((s) => s >= 4).length;
+
+ log('\n── results ──────────────────────────────────────────────');
+ log(`subjects scored ${ok.length} / ${subjects.length}`);
+ if (matchedStats) {
+ log(`matched cosine min=${fmt(matchedStats.min)} median=${fmt(matchedStats.median)} mean=${fmt(matchedStats.mean)} max=${fmt(matchedStats.max)}`);
+ }
+ if (controlStats) {
+ log(`cross-subject control min=${fmt(controlStats.min)} median=${fmt(controlStats.median)} mean=${fmt(controlStats.mean)} max=${fmt(controlStats.max)}`);
+ }
+ if (matchedStats && controlStats) {
+ log(`separation (mean) ${fmt(matchedStats.mean - controlStats.mean)}`);
+ }
+ log(`same-identity threshold ${fmt(SFACE_SAME_IDENTITY_COSINE)} (score 3.0)`);
+ log(`gate 4.0 corresponds to cosine ${fmt(cosineFor(4))}`);
+ if (scores.length) {
+ log(`likeness score min=${fmt(Math.min(...scores), 2)} mean=${fmt(scores.reduce((a, b) => a + b, 0) / scores.length, 2)} max=${fmt(Math.max(...scores), 2)}`);
+ log(`at or above 4/5 gate ${atGate} / ${scores.length}`);
+ }
+
+ if (OUT) {
+ const file = path.resolve(String(OUT));
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(
+ file,
+ `${JSON.stringify(
+ {
+ scorerVersion: SCORER_VERSION,
+ baseUrl: BASE_URL,
+ mode: liveArg ? 'live' : 'backfill',
+ subjects: scored.map((s) => ({ index: s.index, subject: s.subject, stored: s.stored, result: s.result })),
+ matched: matchedStats,
+ control: controlStats,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ log(`\nreport written to ${file}`);
+ }
+}
+
+// Inverse of cosineToScore5 at a given score, so the report can state the
+// cosine the gate actually demands instead of leaving a reader to derive it.
+function cosineFor(score5) {
+ if (score5 <= 3) return ((score5 - 1) / 2) * SFACE_SAME_IDENTITY_COSINE;
+ return SFACE_SAME_IDENTITY_COSINE + ((score5 - 3) / 2) * (1 - SFACE_SAME_IDENTITY_COSINE);
+}
+
+main().catch((err) => {
+ console.error(`✗ ${err?.message || err}`);
+ process.exitCode = 1;
+});
+
+export { cosineFor, cosineToScore5 };