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(likeness): document the harness and cover the scorer with tests

nirholasa56092d6e0bf
diff --git a/docs/likeness-eval.md b/docs/likeness-eval.md
new file mode 100644
index 000000000..814b8fc58
--- /dev/null
+++ b/docs/likeness-eval.md
@@ -0,0 +1,188 @@
+# Likeness evaluation
+
+**Does the avatar look like the person in the photos?** This is the harness that
+answers it with a number instead of an opinion.
+
+Phase 1 of the [roadmap](../README.md#roadmap) is verified on a likeness score:
+users complete a capture and mint an agent of themselves "with >=4/5 likeness
+score". Until this landed, nothing produced that number for a real generation.
+The platform could assert likeness; it could not measure it.
+
+## What was already measured, and why it was not enough
+
+Two quality instruments existed before this one, and neither answers the
+identity question:
+
+| Instrument | Asks | Blind to |
+|---|---|---|
+| [Realism quality bench](../data/quality-bench/README.md) (`api/_lib/quality-bench.js`) | Is the generated asset photorealistic, coherent, on-brief? | Whose face it is. A beautiful render of a stranger scores perfectly. |
+| [Identity Shape Error](../workers/avatar-reconstruction/eval/README.md) (`eval/identity_eval.py`) | Does the head have this person's face *shape*? | Texture, by design. Offline, against a synthetic reference set, and stores nothing per generation. |
+
+The gap between them is the whole product claim. A pipeline that paints a
+selfie onto a template head can score well on realism and poorly on shape while
+still reading, to the person looking at it, as *them* or as *not them*. That
+perception is what a face-recognition embedding measures.
+
+## The metric
+
+For one finished reconstruction:
+
+1. The avatar is rendered head-framed at three yaws: **head-on (0°)**,
+ **three-quarter (35°)**, and **profile (65°)**, using the platform's own
+ `headshot` scene preset so the framing matches what a user actually sees on a
+ thumbnail or share card.
+2. Each render and each input capture is passed through a face detector
+ (**YuNet**) and an identity embedder (**SFace**), producing a 128-dimensional
+ L2-normalised vector per face.
+3. Each view is scored as the **cosine similarity** between its render vector
+ and the best-matching capture vector.
+4. The headline **likeness score** is the head-on view's cosine, mapped to 1-5.
+
+`profile` is 65° rather than a true 90° on purpose. A full side-on view presents
+at most three of the five landmarks the alignment step needs, so no model of
+this family can measure it. 65° is the steepest turn that still yields a
+measurable face, and it is well past the point where a frontal-only texture
+transfer stops covering the head.
+
+### Why 1-5 means what it means
+
+The mapping is anchored to the embedding model's own calibration, not to taste:
+
+| Cosine | Score | Meaning |
+|---|---|---|
+| 0.000 | 1.0 | No relationship between the faces |
+| 0.363 | 3.0 | OpenCV's published SFace decision boundary: the exact point where the model stops calling this the same person |
+| 0.682 | 4.0 | The roadmap gate |
+| 1.000 | 5.0 | Identical embedding |
+
+So **4/5 is a cosine of 0.68, roughly twice the same-identity threshold**: not
+"arguably the same person" but "confidently the same person". Between the
+anchors the mapping is linear.
+
+### What the harness refuses to do
+
+A missing input is reported as a status, never scored as a zero, because these
+are three different findings that a single low number would hide:
+
+- `captures_unusable` — no input photo contained a findable face. A
+ capture-quality problem; nothing can be concluded about the avatar.
+- `render_unusable` — no render contained a findable face. The reconstruction
+ did not produce something recognisable as a head.
+- `ok` with a low score — the avatar has a face, and it is not this person's.
+
+`budget_exhausted` is a fourth: a sweep cut short by its time budget covers
+fewer views than a complete one, so its score is withheld rather than compared
+against runs that were not truncated.
+
+### Secondary readings
+
+- **turn falloff** — head-on cosine minus the worst view's. A pipeline that only
+ holds up frontally is visible here and in no single-view number.
+- **capture cohesion** — mean pairwise cosine among the input photos. A selfie
+ set whose own photos only agree at 0.5 cannot support a claim about the avatar
+ at 0.6.
+- **captures embedded / total** — how much of the input the measurement rests on.
+
+## The models, and why these two
+
+Both are pulled from [OpenCV Zoo](https://github.com/opencv/opencv_zoo) at a
+pinned commit and verified against a hardcoded SHA-256 before they are loaded.
+
+| Role | Model | License | Size |
+|---|---|---|---|
+| Detection + 5 landmarks | YuNet (`face_detection_yunet_2023mar`) | MIT | 233 KB |
+| Identity embedding | SFace (`face_recognition_sface_2021dec`) | Apache-2.0 | 39 MB |
+
+Both licenses are commercially clean, which is the same bar the reconstruction
+worker holds ("no non-commercial 3DMM": no FLAME, BFM or SMPL weights anywhere
+in the pipeline). The widely-cited alternative, InsightFace's `buffalo_l`
+ArcFace pack, is materially stronger on benchmarks and is released for
+**non-commercial research use only**, so it is not available to us at any
+quality.
+
+They run on [`onnxruntime-web`](https://www.npmjs.com/package/onnxruntime-web)'s
+WASM backend (MIT) rather than `onnxruntime-node`. The node binding's installer
+downloads CUDA provider packages from NuGet during `npm install` and fails
+outright on a machine with no GPU tree, which would make the repository
+uninstallable. WASM has no native install step and behaves identically on a
+laptop and on Cloud Run.
+
+Weights are **not** vendored into git. They are fetched once from the pinned
+URL, hash-verified, and cached under `FACE_MODEL_CACHE_DIR` (default: the system
+temp directory).
+
+> opencv_zoo stores its weights in Git LFS, so `raw.githubusercontent.com`
+> serves a 130-byte pointer file rather than the model. The fetch uses
+> `github.com/<repo>/raw/<commit>/…`, which resolves LFS. The SHA-256 check is
+> what caught the difference.
+
+## Running it
+
+### Weekly, automatically
+
+`/api/cron/likeness-eval` runs Mondays at 03:47 UTC, 24 minutes after the
+realism bench, on the same cadence. It takes finished reconstructions the
+current scorer version has not measured, scores them, and files the results. It
+bounds itself to a 280-second budget and skips any subject it cannot finish, so
+it never collects a Cloud Run 504 the way an unbounded sweep does. A sweep whose
+mean falls below the 4.0 gate logs at `warn` level:
+
+```bash
+gcloud logging read 'resource.type="cloud_run_revision" textPayload:"likeness-eval"' --freshness=7d
+```
+
+### On demand
+
+```bash
+# Score everything the current scorer version has not seen (needs DATABASE_URL)
+node --env-file=.env scripts/likeness-eval.mjs --backfill
+
+# Run 10 reconstructions through the real production pipeline and score them
+node --env-file=.env scripts/likeness-eval.mjs --live=10 --out=reports/likeness.json
+```
+
+`--live` signs in with the QA account, submits real reconstructions built from
+**synthesised** subject descriptions (never real people's photos, for the same
+reason the reconstruction worker synthesises its reference set), polls each to
+completion, and scores the finished avatar against the exact reference image the
+pipeline built it from.
+
+Both modes print a **cross-subject control**: every avatar is also scored
+against every *other* subject's captures. A likeness number is unfalsifiable
+without it, because a scorer that returned 0.8 for any two faces would look
+identical to a working one on the matched pairs alone. The separation between
+the two distributions is the evidence the instrument works.
+
+## Reading the results
+
+`/likeness-bench` (internal, admin or `x-ops-secret`) renders the distribution:
+the fraction clearing the 4/5 gate, the histogram, mean turn falloff, the
+outcome breakdown, and the most recent individual scores. The same data is
+available as JSON:
+
+```bash
+curl -H "x-ops-secret: $OPS_SECRET" 'https://three.ws/api/likeness-bench?days=30&limit=50'
+```
+
+Scores are keyed on the generation record (`forge_creations.id`) and stamped
+with `scorer_version`. **A score is only comparable to another score taken by
+the same scorer version.** When the model, the alignment template or the view
+angles change, the version changes with them, old rows stay valid, and
+`where scorer_version <> $current` is the backfill query.
+
+## What is deliberately not stored
+
+No capture URLs, no crops, and **no embeddings**. A face embedding is biometric
+data; this table holds the measurement, not the person. The stored report
+carries per-view statuses and cosines, and records a rejected capture by index
+and reason only.
+
+## Related
+
+- [Selfie to avatar](./selfie-to-avatar.md) — the capture flow being measured
+- [Avatar fidelity program](./avatar-fidelity-program.md) — the tracks this
+ metric scores
+- [Realism quality bench](../data/quality-bench/README.md) — the sibling harness
+ for photorealism
+- [Reconstruction fidelity evaluation](../workers/avatar-reconstruction/eval/README.md)
+ — the geometry-side metric
diff --git a/scripts/likeness-eval.mjs b/scripts/likeness-eval.mjs
index dcf6178bf..eb6241f31 100644
--- a/scripts/likeness-eval.mjs
+++ b/scripts/likeness-eval.mjs
@@ -14,20 +14,22 @@
// 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
+// pipeline (sign in, POST /api/avatars/reconstruct with a
+// portrait, poll to done) and score each finished avatar
+// against the exact portrait it was built 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.
+// Live mode uses SYNTHESISED subjects, never real people's photos. Each
+// subject's portrait is a headshot render of a distinct avatar from the
+// platform's own public library: a real image with a real, detectable face
+// that belongs to nobody. That keeps real biometrics out of a benchmark which
+// gets re-run and copied between machines, the same reasoning
+// workers/avatar-reconstruction/eval/make_refs.py applies to its reference set,
+// and it makes the run reproducible without depending on a text-to-image lane
+// that can be rate-limited or down when the benchmark needs to run.
//
// 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
@@ -67,22 +69,12 @@ const value = (name, fallback = null) => {
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',
-];
+// Portrait framing for the synthesised subjects. A light background rather than
+// the scoring renders' dark one, because the reconstruction pipeline's own
+// background removal and face detection are tuned for ordinary photographs, and
+// a portrait is an INPUT here, not something being measured.
+const PORTRAIT_BACKGROUND = '#f2f2f2';
+const PORTRAIT_SIZE = 768;
function log(...parts) {
console.log(...parts);
diff --git a/tests/likeness-score.test.js b/tests/likeness-score.test.js
new file mode 100644
index 000000000..3da710817
--- /dev/null
+++ b/tests/likeness-score.test.js
@@ -0,0 +1,264 @@
+/**
+ * Likeness harness: the score mapping, the aggregation, and the refusals.
+ *
+ * The Phase 1 roadmap gate is a likeness number, so the number has to mean one
+ * fixed thing forever. Contracts under test:
+ * 1. The 1-5 mapping is pinned to the embedding model's own calibration:
+ * cosine 0 is 1/5, SFace's published same-identity boundary (0.363) is
+ * exactly 3/5, and a perfect match is 5/5. If this drifts, every stored
+ * score silently stops being comparable to every earlier one.
+ * 2. A missing input is a REPORTED STATUS, never a zero. "the captures were
+ * unusable", "no face survived the render" and "the avatar looks nothing
+ * like them" are three different findings, and a harness that collapses
+ * them into one low number is worse than no harness.
+ * 3. The headline score is the head-on view specifically, and turn falloff is
+ * measured against the worst view, because a texture-transfer pipeline
+ * that only holds up frontally is the exact failure this exists to catch.
+ * 4. A budget-truncated sweep is withheld from the distribution rather than
+ * scored short, mirroring how the realism bench treats the same case.
+ * 5. Captures are read from the shape avatar_regen_jobs actually stores, for
+ * both the selfie path (params.images) and the text-to-avatar path
+ * (params.referenceImageUrl).
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const renderAvatarScene = vi.fn();
+vi.mock('../api/_lib/avatar-render.js', () => ({
+ renderAvatarScene: (...a) => renderAvatarScene(...a),
+ SCENE_PRESETS: { headshot: { phi: 86, theta: 5 } },
+}));
+
+// Face embedding stand-in. Real vectors, real cosine arithmetic: only the ONNX
+// session is replaced, so the aggregation under test does genuine math on
+// genuine unit vectors rather than on canned scores.
+const embedFace = vi.fn();
+vi.mock('../api/_lib/face-embed.js', async () => {
+ const actual = await vi.importActual('../api/_lib/face-embed.js');
+ return { ...actual, embedFace: (...a) => embedFace(...a) };
+});
+
+const {
+ LIKENESS_VIEWS,
+ SFACE_SAME_IDENTITY_COSINE,
+ captureCohesion,
+ cosineToScore5,
+ scoreLikeness,
+} = await import('../api/_lib/likeness-score.js');
+const { capturesFromParams } = await import('../api/_lib/likeness-store.js');
+
+// A unit vector at a chosen angle from the reference, so a test can request an
+// exact cosine instead of hoping a random pair lands near one.
+function vectorAtCosine(cosine) {
+ const v = new Float32Array(128);
+ v[0] = cosine;
+ v[1] = Math.sqrt(Math.max(0, 1 - cosine * cosine));
+ return v;
+}
+
+const REFERENCE = vectorAtCosine(1);
+
+function detection(embedding) {
+ return { embedding, detection: { score: 0.95, box: [0, 0, 10, 10] } };
+}
+
+beforeEach(() => {
+ renderAvatarScene.mockReset();
+ embedFace.mockReset();
+ renderAvatarScene.mockResolvedValue({ png: Buffer.from('png') });
+});
+
+describe('cosineToScore5', () => {
+ it('anchors on the embedding model rather than on taste', () => {
+ expect(cosineToScore5(0)).toBe(1);
+ expect(cosineToScore5(SFACE_SAME_IDENTITY_COSINE)).toBe(3);
+ expect(cosineToScore5(1)).toBe(5);
+ });
+
+ it('puts the 4/5 roadmap gate well above the same-identity boundary', () => {
+ const gateCosine = SFACE_SAME_IDENTITY_COSINE + (1 - SFACE_SAME_IDENTITY_COSINE) / 2;
+ expect(cosineToScore5(gateCosine)).toBe(4);
+ // "Confidently the same person", not "arguably".
+ expect(gateCosine).toBeGreaterThan(SFACE_SAME_IDENTITY_COSINE * 1.8);
+ });
+
+ it('is monotonic and clamped to the 1-5 scale', () => {
+ let previous = 0;
+ for (let c = 0; c <= 1; c += 0.05) {
+ const score = cosineToScore5(c);
+ expect(score).toBeGreaterThanOrEqual(previous);
+ expect(score).toBeGreaterThanOrEqual(1);
+ expect(score).toBeLessThanOrEqual(5);
+ previous = score;
+ }
+ // A negative cosine is a real embedding outcome, not an error.
+ expect(cosineToScore5(-0.4)).toBe(1);
+ expect(cosineToScore5(Number.NaN)).toBeNull();
+ });
+});
+
+describe('scoreLikeness refusals', () => {
+ it('reports a missing GLB instead of scoring it', async () => {
+ const result = await scoreLikeness({ glbUrl: null, captures: ['https://x.test/a.jpg'] });
+ expect(result.status).toBe('no_glb');
+ expect(result.likenessScore).toBeUndefined();
+ expect(renderAvatarScene).not.toHaveBeenCalled();
+ });
+
+ it('reports a missing capture set instead of scoring it', async () => {
+ const result = await scoreLikeness({ glbUrl: 'https://x.test/a.glb', captures: [] });
+ expect(result.status).toBe('no_captures');
+ expect(renderAvatarScene).not.toHaveBeenCalled();
+ });
+
+ it('blames the captures, not the avatar, when no input photo has a face', async () => {
+ embedFace.mockResolvedValue(null);
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('a'), Buffer.from('b')],
+ });
+ expect(result.status).toBe('captures_unusable');
+ expect(result.capturesRejected).toHaveLength(2);
+ expect(result.capturesRejected[0]).toMatchObject({ index: 0, reason: 'no_face_detected' });
+ // Never renders: there is nothing to compare a render against.
+ expect(renderAvatarScene).not.toHaveBeenCalled();
+ });
+
+ it('separates "the render has no face" from a low score', async () => {
+ embedFace.mockImplementation(async (buf) =>
+ Buffer.isBuffer(buf) && buf.toString() === 'png' ? null : detection(REFERENCE),
+ );
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('capture')],
+ });
+ expect(result.status).toBe('render_unusable');
+ expect(result.likenessScore).toBeUndefined();
+ expect(result.views.every((v) => v.status === 'no_face_in_render')).toBe(true);
+ });
+
+ it('withholds a score when the run ran out of budget mid-sweep', async () => {
+ embedFace.mockResolvedValue(detection(REFERENCE));
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('capture')],
+ deadlineAt: Date.now() - 1,
+ });
+ expect(result.status).toBe('budget_exhausted');
+ expect(result.budgetExhausted).toBe(true);
+ expect(result.likenessScore).toBeUndefined();
+ });
+});
+
+describe('scoreLikeness aggregation', () => {
+ it('takes the headline from the head-on view and falloff from the worst', async () => {
+ const byView = new Map([
+ ['head-on', 0.90],
+ ['three-quarter', 0.70],
+ ['profile', 0.50],
+ ]);
+ let call = 0;
+ embedFace.mockImplementation(async (buf) => {
+ if (!Buffer.isBuffer(buf) || buf.toString() !== 'png') return detection(REFERENCE);
+ const label = LIKENESS_VIEWS[call].label;
+ call += 1;
+ return detection(vectorAtCosine(byView.get(label)));
+ });
+
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('capture')],
+ });
+
+ expect(result.status).toBe('ok');
+ expect(result.viewsScored).toBe(3);
+ expect(result.identityCosine).toBeCloseTo(0.90, 5);
+ expect(result.likenessScore).toBe(cosineToScore5(0.90));
+ expect(result.worstCosine).toBeCloseTo(0.50, 5);
+ // The whole point of rendering three yaws: a frontally-flattering
+ // pipeline is visible here and in no single-view number.
+ expect(result.turnFalloff).toBeCloseTo(0.40, 5);
+ expect(result.meanCosine).toBeCloseTo(0.70, 5);
+ expect(result.sameIdentity).toBe(true);
+ });
+
+ it('scores against the best-matching capture, and names which one', async () => {
+ const captures = [vectorAtCosine(0.2), vectorAtCosine(0.85)];
+ let captureCall = 0;
+ embedFace.mockImplementation(async (buf) => {
+ if (Buffer.isBuffer(buf) && buf.toString() === 'png') return detection(REFERENCE);
+ const emb = captures[captureCall];
+ captureCall += 1;
+ return detection(emb);
+ });
+
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('a'), Buffer.from('b')],
+ });
+
+ expect(result.capturesEmbedded).toBe(2);
+ expect(result.views[0].bestCaptureIndex).toBe(1);
+ expect(result.views[0].cosine).toBeCloseTo(0.85, 5);
+ expect(result.views[0].meanCaptureCosine).toBeCloseTo(0.525, 5);
+ });
+
+ it('flags a below-threshold reconstruction as not the same person', async () => {
+ embedFace.mockImplementation(async (buf) =>
+ Buffer.isBuffer(buf) && buf.toString() === 'png'
+ ? detection(vectorAtCosine(0.2))
+ : detection(REFERENCE),
+ );
+ const result = await scoreLikeness({
+ glbUrl: 'https://x.test/a.glb',
+ captures: [Buffer.from('capture')],
+ });
+ expect(result.status).toBe('ok');
+ expect(result.sameIdentity).toBe(false);
+ expect(result.likenessScore).toBeLessThan(3);
+ });
+
+ it('renders the three declared yaws, head-framed', async () => {
+ embedFace.mockResolvedValue(detection(REFERENCE));
+ await scoreLikeness({ glbUrl: 'https://x.test/a.glb', captures: [Buffer.from('c')] });
+ const thetas = renderAvatarScene.mock.calls.map((c) => c[0].cameraOrbit.theta);
+ expect(thetas).toEqual(LIKENESS_VIEWS.map((v) => v.theta));
+ expect(renderAvatarScene.mock.calls[0][0].scenePreset).toEqual({ phi: 86, theta: 5 });
+ });
+});
+
+describe('captureCohesion', () => {
+ it('is undefined for a single capture and mean-pairwise beyond that', () => {
+ expect(captureCohesion([{ embedding: REFERENCE }])).toBeNull();
+ const cohesion = captureCohesion([
+ { embedding: REFERENCE },
+ { embedding: vectorAtCosine(0.6) },
+ { embedding: vectorAtCosine(0.8) },
+ ]);
+ expect(cohesion).toBeGreaterThan(0);
+ expect(cohesion).toBeLessThan(1);
+ });
+});
+
+describe('capturesFromParams', () => {
+ it('reads the selfie path', () => {
+ expect(capturesFromParams({ images: ['https://x.test/1.jpg', 'https://x.test/2.jpg'] }))
+ .toEqual(['https://x.test/1.jpg', 'https://x.test/2.jpg']);
+ });
+
+ it('falls back to the text-to-avatar reference image', () => {
+ expect(capturesFromParams({ source: 'prompt', referenceImageUrl: 'https://x.test/ref.png' }))
+ .toEqual(['https://x.test/ref.png']);
+ });
+
+ it('accepts a params column that came back as text rather than jsonb', () => {
+ expect(capturesFromParams(JSON.stringify({ images: ['https://x.test/1.jpg'] })))
+ .toEqual(['https://x.test/1.jpg']);
+ });
+
+ it('yields nothing rather than throwing on junk', () => {
+ expect(capturesFromParams(null)).toEqual([]);
+ expect(capturesFromParams('not json')).toEqual([]);
+ expect(capturesFromParams({ images: [null, 42, ''] })).toEqual([]);
+ });
+});