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): measure reconstruction identity with a face embedding

nirholas08c082a3defa
diff --git a/.env.example b/.env.example
index ef90f1583..1d094dd95 100644
--- a/.env.example
+++ b/.env.example
@@ -448,6 +448,18 @@ X402_ASSET_MINT_SOLANA=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
X402_ASSET_ADDRESS_BASE=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
# Price in base units (USDC = 6 decimals; 1000 = 0.001 USDC).
X402_MAX_AMOUNT_REQUIRED=1000
+# Skill royalties (docs/skill-royalties.md). The platform's share of each paid
+# call to a marketplace skill, in basis points; the author keeps the rest and
+# wins the rounding. Defaults to 250 (2.5%, the marketplace fee rate) and is
+# clamped to 5000 in code, so a misconfig can never take more than half a call.
+X402_SKILL_ROYALTY_PLATFORM_BPS=250
+# The in-app runtime royalty lane settles through EIP-7710 delegated
+# permissions. Leave false: with it off, settleRoyalties and the daily
+# settle-royalties cron leave pending rows untouched and redeem nothing.
+# Turning it on starts moving real USDC on a schedule — read the activation
+# checklist in docs/skill-royalties.md first. The per-call x402 rail does NOT
+# depend on this flag; it pays authors at settlement either way.
+SKILL_ROYALTIES_EVM_7710_ENABLED=false
# USE-15 — TTL (seconds) for the payment-identifier idempotency cache.
# Same paymentId within the window returns the cached response without
# re-charging. Per-route override via paidEndpoint({ paymentIdentifier:
diff --git a/api/_lib/face-embed.js b/api/_lib/face-embed.js
new file mode 100644
index 000000000..afb7156ee
--- /dev/null
+++ b/api/_lib/face-embed.js
@@ -0,0 +1,395 @@
+// Face identity embedding: the measuring instrument behind the Phase 1 likeness
+// score (README Roadmap, "≥4/5 likeness score").
+//
+// Everything the platform measured about a reconstruction until now was either
+// realism (api/_lib/quality-bench.js: a Gemini vision judge scoring
+// photorealism / geometry / texture / prompt adherence) or face SHAPE
+// (workers/avatar-reconstruction/eval/identity_eval.py: ISE, a landmark
+// geometry distance that deliberately ignores texture). Neither answers the
+// question the roadmap actually gates on, which is whether a stranger looking
+// at the finished avatar would say it is the same person as the photos. That
+// question has one honest instrument: a face-recognition embedding, the same
+// class of model a phone uses to decide a face unlocks it.
+//
+// Two OSS models, both commercially clean, matching the reconstruction worker's
+// standing "Apache-2.0 / MIT only, no non-commercial 3DMM weights" rule:
+//
+// • YuNet (MIT, Shiqi Yu / OpenCV Zoo) — face detection plus the five
+// landmarks (eyes, nose tip, mouth corners) that identity models align on.
+// • SFace (Apache-2.0, Zhong & Deng / OpenCV Zoo) — 128-d identity
+// embedding, the model OpenCV's own FaceRecognizerSF ships.
+//
+// They run on onnxruntime-web's WASM backend (MIT) rather than
+// onnxruntime-node: the node binding's installer downloads CUDA provider
+// packages from NuGet at `npm install` time and fails outright on a machine
+// that has no GPU tree, which would make the whole repo uninstallable. WASM has
+// no native step, runs identically on a laptop and on Cloud Run, and scores a
+// face in tens of milliseconds, which is far below the cost of the render that
+// produced the image.
+//
+// Weights are NOT vendored: 39 MB of ONNX does not belong in git. They are
+// fetched once from a commit-pinned OpenCV Zoo URL, verified against a
+// hardcoded SHA-256, and cached on disk. A hash mismatch is fatal — a
+// silently-swapped identity model would corrupt every score in the table.
+//
+// Cosine similarity is the score. OpenCV publishes SFace's operating point as
+// 0.363 (same identity above, different identity below) on its own benchmark;
+// that constant is exported here rather than buried, because every downstream
+// interpretation of a number this module returns depends on it.
+
+import { createHash } from 'node:crypto';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+// Pinned to one opencv_zoo commit, not to `main`: a moving ref means a model
+// swap could land in a cron run nobody triggered, and every stored score before
+// it would silently stop being comparable.
+const ZOO_COMMIT = '47534e27c9851bb1128ccc0102f1145e27f23f98';
+const ZOO_RAW = `https://raw.githubusercontent.com/opencv/opencv_zoo/${ZOO_COMMIT}/models`;
+
+export const MODELS = {
+ detect: {
+ id: 'yunet_2023mar',
+ url: `${ZOO_RAW}/face_detection_yunet/face_detection_yunet_2023mar.onnx`,
+ sha256: '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4',
+ license: 'MIT',
+ },
+ embed: {
+ id: 'sface_2021dec',
+ url: `${ZOO_RAW}/face_recognition_sface/face_recognition_sface_2021dec.onnx`,
+ sha256: '0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79',
+ license: 'Apache-2.0',
+ },
+};
+
+// Bumped whenever anything that can move a number changes: a model swap, the
+// alignment template, the detector thresholds. Stored next to every score so a
+// row always says which instrument produced it and `where scorer_version <> $current`
+// is the re-score query.
+export const SCORER_VERSION = 'threews.likeness.sface.v1';
+
+// OpenCV's published SFace decision threshold on cosine similarity.
+export const SFACE_SAME_IDENTITY_COSINE = 0.363;
+
+// YuNet's detection head: one 640x640 input, three strides, and per-stride
+// classification / objectness / box / keypoint tensors on a plain grid prior.
+const DETECT_SIZE = 640;
+const STRIDES = [8, 16, 32];
+const DETECT_SCORE_THRESHOLD = 0.6;
+const DETECT_NMS_IOU = 0.3;
+
+// SFace's alignment template: the canonical 112x112 five-point layout every
+// ArcFace-family model was trained against, in YuNet's landmark order
+// (subject's right eye, left eye, nose tip, right mouth corner, left mouth
+// corner — "right" as the subject's, so it sits at the smaller x in frame).
+const ALIGN_SIZE = 112;
+const ALIGN_TEMPLATE = [
+ [38.2946, 51.6963],
+ [73.5318, 51.5014],
+ [56.0252, 71.7366],
+ [41.5493, 92.3655],
+ [70.7299, 92.2041],
+];
+
+function cacheDir() {
+ return process.env.FACE_MODEL_CACHE_DIR || path.join(os.tmpdir(), 'three-ws-face-models');
+}
+
+// Fetch-once, verify-always. A cached file that fails its hash is treated as a
+// corrupt download and re-fetched exactly once before giving up, so a truncated
+// write on a previous run heals itself instead of poisoning every later run.
+async function modelBytes(spec) {
+ const dir = cacheDir();
+ const file = path.join(dir, `${spec.id}.onnx`);
+ const cached = await readFile(file).catch(() => null);
+ if (cached && createHash('sha256').update(cached).digest('hex') === spec.sha256) return cached;
+
+ const res = await fetch(spec.url);
+ if (!res.ok) throw new Error(`face model ${spec.id} download failed: HTTP ${res.status}`);
+ const buf = Buffer.from(await res.arrayBuffer());
+ const got = createHash('sha256').update(buf).digest('hex');
+ if (got !== spec.sha256) {
+ throw new Error(`face model ${spec.id} hash mismatch: expected ${spec.sha256}, got ${got}`);
+ }
+ await mkdir(dir, { recursive: true });
+ await writeFile(file, buf);
+ return buf;
+}
+
+let _ort = null;
+async function ort() {
+ if (_ort) return _ort;
+ const mod = await import('onnxruntime-web');
+ const api = mod.default ?? mod;
+ // One thread and no SIMD-thread pool: Cloud Run gives this container a small,
+ // shared CPU budget and the scoring work is already dwarfed by the headless
+ // render in front of it. Spawning workers here only competes with the API.
+ api.env.wasm.numThreads = 1;
+ api.env.logLevel = 'error';
+ _ort = api;
+ return api;
+}
+
+const _sessions = new Map();
+async function session(spec) {
+ if (_sessions.has(spec.id)) return _sessions.get(spec.id);
+ const promise = (async () => {
+ const [api, bytes] = await Promise.all([ort(), modelBytes(spec)]);
+ return api.InferenceSession.create(bytes, { executionProviders: ['wasm'] });
+ })().catch((err) => {
+ _sessions.delete(spec.id);
+ throw err;
+ });
+ _sessions.set(spec.id, promise);
+ return promise;
+}
+
+// Decode any image the platform can hand us (PNG render, JPEG selfie, WebP
+// upload) into tightly-packed RGB bytes. sharp is already a dependency and is
+// the only decoder in the repo that handles all three without a browser.
+export async function decodeImage(buffer) {
+ const { default: sharp } = await import('sharp');
+ const { data, info } = await sharp(buffer)
+ .removeAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height };
+}
+
+// Letterbox into the detector's fixed 640x640 input rather than stretching:
+// YuNet regresses landmark offsets in its own input space, and a non-uniform
+// scale bends the five-point geometry that alignment then depends on. Returns
+// the scale/offset so detections map back to original-image coordinates.
+function letterbox(img) {
+ const scale = Math.min(DETECT_SIZE / img.width, DETECT_SIZE / img.height);
+ const w = Math.max(1, Math.round(img.width * scale));
+ const h = Math.max(1, Math.round(img.height * scale));
+ const dx = Math.floor((DETECT_SIZE - w) / 2);
+ const dy = Math.floor((DETECT_SIZE - h) / 2);
+ return { scale, w, h, dx, dy };
+}
+
+// YuNet consumes raw 0-255 BGR in NCHW, with no mean subtraction and no scaling
+// (this mirrors what cv2.FaceDetectorYN does internally).
+async function detectInputTensor(buffer, box) {
+ const { default: sharp } = await import('sharp');
+ const { data } = await sharp(buffer)
+ .removeAlpha()
+ .resize(box.w, box.h, { fit: 'fill' })
+ .extend({
+ top: box.dy,
+ bottom: DETECT_SIZE - box.h - box.dy,
+ left: box.dx,
+ right: DETECT_SIZE - box.w - box.dx,
+ background: { r: 0, g: 0, b: 0 },
+ })
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ const plane = DETECT_SIZE * DETECT_SIZE;
+ const out = new Float32Array(3 * plane);
+ for (let i = 0; i < plane; i += 1) {
+ out[i] = data[i * 3 + 2];
+ out[plane + i] = data[i * 3 + 1];
+ out[2 * plane + i] = data[i * 3];
+ }
+ return out;
+}
+
+function iou(a, b) {
+ const x1 = Math.max(a.x, b.x);
+ const y1 = Math.max(a.y, b.y);
+ const x2 = Math.min(a.x + a.w, b.x + b.w);
+ const y2 = Math.min(a.y + a.h, b.y + b.h);
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
+ if (inter <= 0) return 0;
+ return inter / (a.w * a.h + b.w * b.h - inter);
+}
+
+function nms(faces, threshold) {
+ const kept = [];
+ for (const face of [...faces].sort((p, q) => q.score - p.score)) {
+ if (kept.every((k) => iou(k, face) < threshold)) kept.push(face);
+ }
+ return kept;
+}
+
+// Decode YuNet's per-stride heads onto the grid prior. Cell (r, c) at stride s
+// carries a centre offset in cells, log-space width/height, and five landmark
+// offsets in the same units; the confidence is the geometric mean of the
+// classification and objectness scores.
+function decodeDetections(outputs, box) {
+ const faces = [];
+ for (const stride of STRIDES) {
+ const cls = outputs[`cls_${stride}`]?.data;
+ const obj = outputs[`obj_${stride}`]?.data;
+ const bbox = outputs[`bbox_${stride}`]?.data;
+ const kps = outputs[`kps_${stride}`]?.data;
+ if (!cls || !obj || !bbox || !kps) continue;
+ const cols = DETECT_SIZE / stride;
+ for (let idx = 0; idx < cls.length; idx += 1) {
+ const score = Math.sqrt(Math.max(0, cls[idx]) * Math.max(0, obj[idx]));
+ if (score < DETECT_SCORE_THRESHOLD) continue;
+ const r = Math.floor(idx / cols);
+ const c = idx % cols;
+ const cx = (c + bbox[idx * 4]) * stride;
+ const cy = (r + bbox[idx * 4 + 1]) * stride;
+ const w = Math.exp(bbox[idx * 4 + 2]) * stride;
+ const h = Math.exp(bbox[idx * 4 + 3]) * stride;
+ const landmarks = [];
+ for (let k = 0; k < 5; k += 1) {
+ landmarks.push([
+ ((c + kps[idx * 10 + k * 2]) * stride - box.dx) / box.scale,
+ ((r + kps[idx * 10 + k * 2 + 1]) * stride - box.dy) / box.scale,
+ ]);
+ }
+ faces.push({
+ score,
+ x: (cx - w / 2 - box.dx) / box.scale,
+ y: (cy - h / 2 - box.dy) / box.scale,
+ w: w / box.scale,
+ h: h / box.scale,
+ landmarks,
+ });
+ }
+ }
+ return nms(faces, DETECT_NMS_IOU);
+}
+
+// Every detected face in one image, highest confidence first, in the original
+// image's pixel coordinates.
+export async function detectFaces(buffer) {
+ const [api, sess, img] = await Promise.all([ort(), session(MODELS.detect), decodeImage(buffer)]);
+ const box = letterbox(img);
+ const input = await detectInputTensor(buffer, box);
+ const feeds = { [sess.inputNames[0]]: new api.Tensor('float32', input, [1, 3, DETECT_SIZE, DETECT_SIZE]) };
+ const outputs = await sess.run(feeds);
+ return decodeDetections(outputs, box);
+}
+
+// Closed-form least-squares similarity fit (Umeyama) from the detected five
+// points onto the canonical template. Similarity, not affine: identity must not
+// be recoverable by shearing a face into the template, and the closed form is
+// deterministic where OpenCV's RANSAC estimate is not, so the same image always
+// produces the same embedding.
+function similarityTransform(src, dst) {
+ const n = src.length;
+ let sx = 0;
+ let sy = 0;
+ let dx = 0;
+ let dy = 0;
+ for (let i = 0; i < n; i += 1) {
+ sx += src[i][0];
+ sy += src[i][1];
+ dx += dst[i][0];
+ dy += dst[i][1];
+ }
+ sx /= n;
+ sy /= n;
+ dx /= n;
+ dy /= n;
+
+ let varSrc = 0;
+ let a = 0;
+ let b = 0;
+ for (let i = 0; i < n; i += 1) {
+ const px = src[i][0] - sx;
+ const py = src[i][1] - sy;
+ const qx = dst[i][0] - dx;
+ const qy = dst[i][1] - dy;
+ varSrc += px * px + py * py;
+ a += px * qx + py * qy;
+ b += px * qy - py * qx;
+ }
+ if (varSrc <= 1e-9) throw new Error('degenerate landmark set: all five points coincide');
+ const scaleCos = a / varSrc;
+ const scaleSin = b / varSrc;
+ return {
+ m: [
+ [scaleCos, -scaleSin, dx - (scaleCos * sx - scaleSin * sy)],
+ [scaleSin, scaleCos, dy - (scaleSin * sx + scaleCos * sy)],
+ ],
+ };
+}
+
+// Invert the 2x3 similarity so the crop can be filled by pulling source pixels
+// (destination-driven sampling leaves no holes; source-driven scattering does).
+function invert(m) {
+ const det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
+ if (Math.abs(det) < 1e-12) throw new Error('non-invertible alignment transform');
+ const i00 = m[1][1] / det;
+ const i01 = -m[0][1] / det;
+ const i10 = -m[1][0] / det;
+ const i11 = m[0][0] / det;
+ return [
+ [i00, i01, -(i00 * m[0][2] + i01 * m[1][2])],
+ [i10, i11, -(i10 * m[0][2] + i11 * m[1][2])],
+ ];
+}
+
+// Bilinear-sample the aligned 112x112 crop straight into SFace's BGR NCHW
+// input. Edge coordinates clamp rather than wrap so a face that runs off the
+// frame contributes its border pixels instead of the opposite side of the image.
+function alignCrop(img, landmarks) {
+ const inv = invert(similarityTransform(landmarks, ALIGN_TEMPLATE).m);
+ const plane = ALIGN_SIZE * ALIGN_SIZE;
+ const out = new Float32Array(3 * plane);
+ const maxX = img.width - 1;
+ const maxY = img.height - 1;
+ for (let y = 0; y < ALIGN_SIZE; y += 1) {
+ for (let x = 0; x < ALIGN_SIZE; x += 1) {
+ const sxf = Math.min(maxX, Math.max(0, inv[0][0] * x + inv[0][1] * y + inv[0][2]));
+ const syf = Math.min(maxY, Math.max(0, inv[1][0] * x + inv[1][1] * y + inv[1][2]));
+ const x0 = Math.floor(sxf);
+ const y0 = Math.floor(syf);
+ const x1 = Math.min(maxX, x0 + 1);
+ const y1 = Math.min(maxY, y0 + 1);
+ const fx = sxf - x0;
+ const fy = syf - y0;
+ const o = y * ALIGN_SIZE + x;
+ for (let ch = 0; ch < 3; ch += 1) {
+ const p00 = img.data[(y0 * img.width + x0) * 3 + ch];
+ const p10 = img.data[(y0 * img.width + x1) * 3 + ch];
+ const p01 = img.data[(y1 * img.width + x0) * 3 + ch];
+ const p11 = img.data[(y1 * img.width + x1) * 3 + ch];
+ const top = p00 + (p10 - p00) * fx;
+ const bottom = p01 + (p11 - p01) * fx;
+ // RGB in, BGR out: channel 0 of the source lands in plane 2.
+ out[(2 - ch) * plane + o] = top + (bottom - top) * fy;
+ }
+ }
+ }
+ return out;
+}
+
+function l2Normalize(vec) {
+ let norm = 0;
+ for (const v of vec) norm += v * v;
+ norm = Math.sqrt(norm);
+ if (norm < 1e-9) throw new Error('degenerate embedding: zero-norm vector');
+ return Float32Array.from(vec, (v) => v / norm);
+}
+
+// The identity vector for the most confident face in an image, L2-normalized so
+// cosine similarity is a plain dot product. Returns null when no face clears
+// the detector threshold: an avatar whose head is not recognisable AS a face is
+// a real, reportable finding, never a fabricated score.
+export async function embedFace(buffer) {
+ const faces = await detectFaces(buffer);
+ if (!faces.length) return null;
+ const best = faces.reduce((a, b) => (b.score > a.score ? b : a));
+ const [api, sess, img] = await Promise.all([ort(), session(MODELS.embed), decodeImage(buffer)]);
+ const input = alignCrop(img, best.landmarks);
+ const feeds = { [sess.inputNames[0]]: new api.Tensor('float32', input, [1, 3, ALIGN_SIZE, ALIGN_SIZE]) };
+ const outputs = await sess.run(feeds);
+ const raw = outputs[sess.outputNames[0]].data;
+ return { embedding: l2Normalize(raw), detection: { score: best.score, box: [best.x, best.y, best.w, best.h] } };
+}
+
+// Cosine similarity of two L2-normalized embeddings, in [-1, 1].
+export function cosineSimilarity(a, b) {
+ if (!a || !b || a.length !== b.length) throw new Error('cosine similarity needs two equal-length vectors');
+ let dot = 0;
+ for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i];
+ return dot;
+}
diff --git a/contracts/program-tests/tests/agent_invocation.rs b/contracts/program-tests/tests/agent_invocation.rs
new file mode 100644
index 000000000..fc8f3d0a0
--- /dev/null
+++ b/contracts/program-tests/tests/agent_invocation.rs
@@ -0,0 +1,340 @@
+//! Invariant tests for the `agent_invocation` program.
+//!
+//! Proves `AI-1` .. `AI-4` of `specs/ECONOMY_CONTRACT_INVARIANTS.md` against the
+//! real compiled bytecode. Each invariant gets a positive case (the property
+//! holds when it should) and a negative case (a caller trying to break it is
+//! rejected).
+
+use litesvm::LiteSVM;
+use program_tests::*;
+use solana_sdk::instruction::{AccountMeta, Instruction};
+use solana_sdk::pubkey::Pubkey;
+use solana_sdk::signature::Keypair;
+use solana_sdk::signer::Signer;
+use solana_sdk::system_program;
+use solana_sdk::transaction::Transaction;
+
+const AGENT_SEED: &[u8] = b"agent";
+
+struct Harness {
+ svm: LiteSVM,
+ program_id: Pubkey,
+ invoker: Keypair,
+ target_authority: Pubkey,
+}
+
+impl Harness {
+ fn new() -> Self {
+ let mut svm = LiteSVM::new();
+ let program_id = pk(AGENT_INVOCATION_ID);
+ load_program(
+ &mut svm,
+ program_id,
+ "agent-invocation",
+ "agent_invocation.so",
+ );
+
+ let invoker = Keypair::new();
+ svm.airdrop(&invoker.pubkey(), 10_000_000_000).unwrap();
+
+ Self {
+ svm,
+ program_id,
+ invoker,
+ target_authority: Keypair::new().pubkey(),
+ }
+ }
+
+ fn agent_pda(&self, authority: &Pubkey) -> Pubkey {
+ Pubkey::find_program_address(&[AGENT_SEED, authority.as_ref()], &self.program_id).0
+ }
+
+ /// Build an `invoke_skill` instruction with every account overridable, so a
+ /// negative test can substitute exactly one wrong account.
+ fn invoke_ix(
+ &self,
+ invoker_agent: Pubkey,
+ invoker_authority: Pubkey,
+ invoker_signs: bool,
+ target_authority: Pubkey,
+ target_agent: Pubkey,
+ skill_name: &str,
+ parameters: &str,
+ ) -> Instruction {
+ let mut args = borsh_string(skill_name);
+ args.extend_from_slice(&borsh_string(parameters));
+ Instruction {
+ program_id: self.program_id,
+ accounts: vec![
+ AccountMeta::new_readonly(invoker_agent, false),
+ AccountMeta::new_readonly(invoker_authority, invoker_signs),
+ AccountMeta::new_readonly(target_authority, false),
+ AccountMeta::new_readonly(target_agent, false),
+ AccountMeta::new_readonly(system_program::id(), false),
+ ],
+ data: ix_data("invoke_skill", &args),
+ }
+ }
+
+ /// The happy-path instruction: both PDAs correct, invoker signing.
+ fn valid_ix(&self, skill_name: &str, parameters: &str) -> Instruction {
+ self.invoke_ix(
+ self.agent_pda(&self.invoker.pubkey()),
+ self.invoker.pubkey(),
+ true,
+ self.target_authority,
+ self.agent_pda(&self.target_authority),
+ skill_name,
+ parameters,
+ )
+ }
+
+ fn send(&mut self, ix: Instruction) -> Result<Vec<String>, Vec<String>> {
+ self.svm.expire_blockhash();
+ let tx = Transaction::new_signed_with_payer(
+ &[ix],
+ Some(&self.invoker.pubkey()),
+ &[&self.invoker],
+ self.svm.latest_blockhash(),
+ );
+ match self.svm.send_transaction(tx) {
+ Ok(meta) => Ok(meta.logs),
+ Err(failed) => Err(failed.meta.logs),
+ }
+ }
+
+ /// Send a transaction the invoker does NOT sign, using a separate fee payer.
+ fn send_unsigned_by_invoker(&mut self, ix: Instruction) -> Result<Vec<String>, String> {
+ let payer = Keypair::new();
+ self.svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap();
+ self.svm.expire_blockhash();
+ let tx = Transaction::new_signed_with_payer(
+ &[ix],
+ Some(&payer.pubkey()),
+ &[&payer],
+ self.svm.latest_blockhash(),
+ );
+ match self.svm.send_transaction(tx) {
+ Ok(meta) => Ok(meta.logs),
+ Err(failed) => Err(format!("{:?}", failed.err)),
+ }
+ }
+}
+
+// ── AI-1: the invoker must sign, and acts only as its own agent ──────────────
+
+/// AI-1 (positive): the authority signs and passes its own derived agent PDA,
+/// so the invocation is recorded and the event names that PDA.
+#[test]
+fn invoker_acting_as_own_agent_succeeds() {
+ let mut h = Harness::new();
+ let ix = h.valid_ix("summarize", "{\"url\":\"https://three.ws\"}");
+ let logs = h.send(ix).expect("valid invocation must succeed");
+
+ let expected = h.agent_pda(&h.invoker.pubkey()).to_string();
+ assert!(
+ logs.iter().any(|l| l.contains(&expected)),
+ "expected the invoker agent PDA in the program logs, got {logs:?}"
+ );
+ assert!(
+ logs.iter().any(|l| l.contains("invoked skill 'summarize'")),
+ "expected the skill name in the program logs, got {logs:?}"
+ );
+}
+
+/// AI-1 (negative): passing another authority's agent PDA while signing as
+/// yourself is rejected by the seeds constraint, so nobody can act as an agent
+/// they do not control.
+#[test]
+fn invoking_as_another_agent_is_rejected() {
+ let mut h = Harness::new();
+ let stranger = Keypair::new().pubkey();
+ let ix = h.invoke_ix(
+ h.agent_pda(&stranger),
+ h.invoker.pubkey(),
+ true,
+ h.target_authority,
+ h.agent_pda(&h.target_authority),
+ "summarize",
+ "{}",
+ );
+ let logs = h.send(ix).expect_err("a foreign invoker PDA must be rejected");
+ assert!(
+ logs_have_anchor_error(&logs, "ConstraintSeeds"),
+ "expected a seeds-constraint failure, got {logs:?}"
+ );
+}
+
+/// AI-1 (negative): the authority must actually sign. Without its signature the
+/// transaction never reaches the program body.
+#[test]
+fn unsigned_invoker_is_rejected() {
+ let mut h = Harness::new();
+ let ix = h.invoke_ix(
+ h.agent_pda(&h.invoker.pubkey()),
+ h.invoker.pubkey(),
+ false,
+ h.target_authority,
+ h.agent_pda(&h.target_authority),
+ "summarize",
+ "{}",
+ );
+ let err = h
+ .send_unsigned_by_invoker(ix)
+ .expect_err("an unsigned invoker must be rejected");
+ assert!(
+ err.contains("Signature") || err.contains("signer"),
+ "expected a missing-signature failure, got {err}"
+ );
+}
+
+// ── AI-2: the target must be the PDA of the presented target authority ───────
+
+/// AI-2 (positive): a target agent derived from its authority is accepted, and
+/// its PDA is what the event records.
+#[test]
+fn target_agent_derived_from_its_authority_is_accepted() {
+ let mut h = Harness::new();
+ let ix = h.valid_ix("render", "{}");
+ let logs = h.send(ix).expect("a correctly derived target must be accepted");
+ let expected = h.agent_pda(&h.target_authority).to_string();
+ assert!(
+ logs.iter().any(|l| l.contains(&expected)),
+ "expected the target agent PDA in the program logs, got {logs:?}"
+ );
+}
+
+/// AI-2 (negative): an arbitrary account cannot be presented as the target
+/// agent, so an indexer can never be told an invocation hit an agent that does
+/// not exist under this program.
+#[test]
+fn arbitrary_target_account_is_rejected() {
+ let mut h = Harness::new();
+ let arbitrary = Keypair::new().pubkey();
+ let ix = h.invoke_ix(
+ h.agent_pda(&h.invoker.pubkey()),
+ h.invoker.pubkey(),
+ true,
+ h.target_authority,
+ arbitrary,
+ "render",
+ "{}",
+ );
+ let logs = h.send(ix).expect_err("an arbitrary target account must be rejected");
+ assert!(
+ logs_have_anchor_error(&logs, "ConstraintSeeds"),
+ "expected a seeds-constraint failure, got {logs:?}"
+ );
+}
+
+// ── AI-3: input bounds ───────────────────────────────────────────────────────
+
+/// AI-3 (positive): both fields are accepted exactly at their documented
+/// maximum, so the bound is inclusive and the limits are usable.
+#[test]
+fn max_length_inputs_are_accepted() {
+ let mut h = Harness::new();
+ let name = "s".repeat(64);
+ let params = "p".repeat(512);
+ let ix = h.valid_ix(&name, &params);
+ h.send(ix).expect("64-byte name and 512-byte parameters must be accepted");
+}
+
+/// AI-3 (negative): an empty skill name is rejected.
+#[test]
+fn empty_skill_name_is_rejected() {
+ let mut h = Harness::new();
+ let ix = h.valid_ix("", "{}");
+ let logs = h.send(ix).expect_err("an empty skill name must be rejected");
+ assert!(
+ logs_have_anchor_error(&logs, "EmptySkillName"),
+ "expected EmptySkillName, got {logs:?}"
+ );
+}
+
+/// AI-3 (negative): one byte over the skill-name bound is rejected.
+#[test]
+fn oversized_skill_name_is_rejected() {
+ let mut h = Harness::new();
+ let name = "s".repeat(65);
+ let ix = h.valid_ix(&name, "{}");
+ let logs = h.send(ix).expect_err("a 65-byte skill name must be rejected");
+ assert!(
+ logs_have_anchor_error(&logs, "SkillNameTooLong"),
+ "expected SkillNameTooLong, got {logs:?}"
+ );
+}
+
+/// AI-3 (negative): one byte over the parameters bound is rejected.
+#[test]
+fn oversized_parameters_are_rejected() {
+ let mut h = Harness::new();
+ let params = "p".repeat(513);
+ let ix = h.valid_ix("summarize", &params);
+ let logs = h.send(ix).expect_err("a 513-byte parameter blob must be rejected");
+ assert!(
+ logs_have_anchor_error(&logs, "ParametersTooLong"),
+ "expected ParametersTooLong, got {logs:?}"
+ );
+}
+
+// ── AI-4: no funds move and no account is created ────────────────────────────
+
+/// AI-4 (positive): a successful invocation moves no lamports beyond the network
+/// fee the payer owes, and creates no account. The two agent PDAs stay
+/// nonexistent, so the program grants no capability and holds no state.
+#[test]
+fn invocation_moves_no_funds_and_creates_no_account() {
+ let mut h = Harness::new();
+ let invoker_agent = h.agent_pda(&h.invoker.pubkey());
+ let target_agent = h.agent_pda(&h.target_authority);
+
+ assert!(h.svm.get_account(&invoker_agent).is_none());
+ let before = h.svm.get_balance(&h.invoker.pubkey()).unwrap();
+
+ let ix = h.valid_ix("summarize", "{}");
+ h.send(ix).expect("valid invocation must succeed");
+
+ let after = h.svm.get_balance(&h.invoker.pubkey()).unwrap();
+ let fee = 5_000; // one signature at the default lamports-per-signature
+ assert_eq!(
+ before - after,
+ fee,
+ "the only lamports that may leave the invoker are the transaction fee"
+ );
+
+ for pda in [invoker_agent, target_agent] {
+ let acct = h.svm.get_account(&pda);
+ assert!(
+ acct.map(|a| a.lamports == 0 && a.data.is_empty()).unwrap_or(true),
+ "the program must not create or fund {pda}"
+ );
+ }
+ assert_eq!(
+ h.svm.get_balance(&h.target_authority).unwrap_or(0),
+ 0,
+ "the target authority must never be credited by an invocation"
+ );
+}
+
+/// AI-4 (negative): a rejected invocation is equally inert. The failed call
+/// leaves no account and no balance change other than the fee.
+#[test]
+fn rejected_invocation_leaves_no_trace() {
+ let mut h = Harness::new();
+ let before = h.svm.get_balance(&h.invoker.pubkey()).unwrap();
+
+ let ix = h.valid_ix("", "{}");
+ h.send(ix).expect_err("an empty skill name must be rejected");
+
+ let after = h.svm.get_balance(&h.invoker.pubkey()).unwrap();
+ assert!(
+ before - after <= 5_000,
+ "a rejected invocation must cost at most the transaction fee"
+ );
+ assert!(h
+ .svm
+ .get_account(&h.agent_pda(&h.invoker.pubkey()))
+ .map(|a| a.data.is_empty())
+ .unwrap_or(true));
+}
diff --git a/package-lock.json b/package-lock.json
index bd8c2ef80..a3b0aee25 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -179,6 +179,7 @@
"nanoid": "^3.3.11",
"nipplejs": "^1.0.4",
"node-html-parser": "^7.1.0",
+ "onnxruntime-web": "^1.22.0",
"p-limit": "^7.3.1",
"postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
@@ -24915,6 +24916,12 @@
"flat": "cli.js"
}
},
+ "node_modules/flatbuffers": {
+ "version": "25.9.23",
+ "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz",
+ "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==",
+ "license": "Apache-2.0"
+ },
"node_modules/flatted": {
"version": "3.4.2",
"dev": true,
@@ -25436,6 +25443,12 @@
"version": "3.15.0",
"license": "Standard 'no charge' license: https://gsap.com/standard-license."
},
+ "node_modules/guid-typescript": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz",
+ "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==",
+ "license": "ISC"
+ },
"node_modules/h3": {
"version": "1.15.11",
"license": "MIT",
@@ -31879,6 +31892,26 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/onnxruntime-common": {
+ "version": "1.22.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.22.0.tgz",
+ "integrity": "sha512-vcuaNWgtF2dGQu/EP5P8UI5rEPEYqXG2sPPe5j9lg2TY/biJF8eWklTMwlDO08iuXq48xJo0awqIpK5mPG+IxA==",
+ "license": "MIT"
+ },
+ "node_modules/onnxruntime-web": {
+ "version": "1.22.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.22.0.tgz",
+ "integrity": "sha512-Ud/+EBo6mhuaQWt/OjaOk0iNWjXqJoeeMFr6xQEERZdIZH2OWpGzuujz7lfuOBjUa6TEE/sc4nb7Da5dNL34fg==",
+ "license": "MIT",
+ "dependencies": {
+ "flatbuffers": "^25.1.24",
+ "guid-typescript": "^1.0.9",
+ "long": "^5.2.3",
+ "onnxruntime-common": "1.22.0",
+ "platform": "^1.3.6",
+ "protobufjs": "^7.2.4"
+ }
+ },
"node_modules/optionator": {
"version": "0.9.4",
"dev": true,
@@ -32462,6 +32495,12 @@
"pathe": "^2.0.1"
}
},
+ "node_modules/platform": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",
+ "license": "MIT"
+ },
"node_modules/playwright": {
"version": "1.60.0",
"dev": true,
diff --git a/package.json b/package.json
index 40b779bcb..94668f658 100644
--- a/package.json
+++ b/package.json
@@ -189,7 +189,7 @@
"audit:route-shadowing": "node scripts/audit-route-shadowing.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
"audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",
- "gate": "npm run check:conflicts && npm run check:claude && npm run check:event && npm run check:cron-syntax && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas",
+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:event && npm run check:cron-syntax && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas",
"test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js",
"audit:mcp-golden": "node scripts/audit-mcp-golden.mjs",
"audit:mcp-safety": "node scripts/audit-mcp-safety.mjs",
@@ -314,6 +314,7 @@
"check:claude": "node scripts/check-claude-md.mjs",
"verify:erc8004-validation": "node scripts/erc8004/verify-validation-registry.mjs",
"check:rules": "node scripts/check-rules.mjs",
+ "check:vendored": "node scripts/check-vendored-workers.mjs",
"check:secrets": "node scripts/check-secrets.mjs",
"check:gcloudignore": "node scripts/check-gcloudignore.mjs",
"check:evm-rpc": "node --env-file=.env scripts/probe-evm-rpc.mjs --chain 1 --ens",
@@ -487,6 +488,7 @@
"nanoid": "^3.3.11",
"nipplejs": "^1.0.4",
"node-html-parser": "^7.1.0",
+ "onnxruntime-web": "^1.22.0",
"p-limit": "^7.3.1",
"postprocessing": "^6.39.1",
"puppeteer-core": "^25.1.0",
diff --git a/tests/agent-index.test.js b/tests/agent-index.test.js
new file mode 100644
index 000000000..be4d729ec
--- /dev/null
+++ b/tests/agent-index.test.js
@@ -0,0 +1,362 @@
+// Regression cover for the cross-chain agent index (agent_onchain_events).
+//
+// Every case here was written against a defect measured on live chain data on
+// 2026-08-13, not against an imagined one. The fixtures are trimmed from real
+// mainnet transactions and logs, with the transaction signatures kept so any
+// claim below can be re-checked against the chain itself.
+
+import { describe, it, expect } from 'vitest';
+import {
+ agentTokenMintOf,
+ classifyAgentTx,
+ parsedInstructionsOf,
+ accountKeysOf,
+ memoPayloadOf,
+ transferRecipientOf,
+ WRAPPED_SOL_MINT,
+ SOLANA_SWEEP_BATCH,
+ SOLANA_SWEEP_PERIOD_MIN,
+} from '../api/_lib/solana-agent-events.js';
+import { normalizeEvent, toDate, agentRef, EVENT_CLASSES } from '../api/_lib/onchain-events.js';
+import { sweepCycleMin } from '../api/_lib/ops/index-lag.js';
+import { nextChunkSize, backoffChunkSize } from '../api/cron/[name].js';
+
+// ─── Fixtures ────────────────────────────────────────────────────────────────
+
+// Trimmed from mainnet transaction
+// 5WtcSn4jJubQnEu71nnjKZJZawtgGNeVayiDgG4QsDsCZreJN2W3MQiJpPWszCFcanFRDMVfojNwrPC7SBumRqw8
+// (slot 438961707): a SetAgentTokenV1 binding agent
+// ANeykUs3hCNb9B9hVx4sQg7D8hD6MzAyRPJ2M1ays18 to token
+// X8k6vcAvvmkavecwAGk7U4JVoKdntDSNfBZsq6KPLEX. The ONLY token balance the
+// transaction carries is wrapped SOL, which is why reading balances alone named
+// the wrong mint on every token_launch event the index recorded.
+const AGENT = 'ANeykUs3hCNb9B9hVx4sQg7D8hD6MzAyRPJ2M1ays18';
+const LAUNCHED_MINT = 'X8k6vcAvvmkavecwAGk7U4JVoKdntDSNfBZsq6KPLEX';
+const IDENTITY_PROGRAM = '1DREGFgysWYxLnRnKQnwrxnJQeSMk2HmGaC6whw2B2p';
+const CORE_PROGRAM = 'CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d';
+const SIGNER = '3NHMeZPXXZVgArbgE6hJU3fq72fR9UsgbmH9zFvQiGC1';
+
+function setAgentTokenTx() {
+ return {
+ transaction: {
+ message: {
+ accountKeys: [
+ { pubkey: SIGNER },
+ { pubkey: AGENT },
+ { pubkey: LAUNCHED_MINT },
+ { pubkey: IDENTITY_PROGRAM },
+ ],
+ instructions: [],
+ },
+ },
+ meta: {
+ err: null,
+ logMessages: ['Program log: Instruction: SetAgentTokenV1'],
+ preTokenBalances: [],
+ postTokenBalances: [
+ { accountIndex: 7, mint: WRAPPED_SOL_MINT, uiTokenAmount: { amount: '0' } },
+ ],
+ innerInstructions: [
+ {
+ index: 4,
+ instructions: [
+ {
+ program: 'spl-token',
+ parsed: {
+ type: 'setAuthority',
+ info: { authorityType: 'mintTokens', mint: LAUNCHED_MINT, newAuthority: null },
+ },
+ },
+ {
+ program: 'spl-token',
+ parsed: {
+ type: 'setAuthority',
+ info: { authorityType: 'freezeAccount', mint: LAUNCHED_MINT, newAuthority: null },
+ },
+ },
+ {
+ program: 'spl-token',
+ parsed: {
+ type: 'initializeAccount3',
+ info: { mint: WRAPPED_SOL_MINT, account: 'irrelevant' },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ };
+}
+
+// ─── agentTokenMintOf ────────────────────────────────────────────────────────
+
+describe('agentTokenMintOf', () => {
+ it('names the launched token, not the wrapped SOL that funded it', () => {
+ expect(agentTokenMintOf(setAgentTokenTx(), AGENT)).toBe(LAUNCHED_MINT);
+ });
+
+ it('prefers a mint the transaction initialized over one it only minted from', () => {
+ const tx = {
+ transaction: { message: { accountKeys: [], instructions: [] } },
+ meta: {
+ innerInstructions: [
+ {
+ index: 0,
+ instructions: [
+ { parsed: { type: 'mintTo', info: { mint: 'MintToOnly1111111111111111111111111111111111' } } },
+ { parsed: { type: 'initializeMint2', info: { mint: LAUNCHED_MINT } } },
+ ],
+ },
+ ],
+ },
+ };
+ expect(agentTokenMintOf(tx, AGENT)).toBe(LAUNCHED_MINT);
+ });
+
+ it('refuses to guess when one tier names two different mints', () => {
+ const tx = {
+ transaction: { message: { accountKeys: [], instructions: [] } },
+ meta: {
+ innerInstructions: [
+ {
+ index: 0,
+ instructions: [
+ { parsed: { type: 'initializeMint', info: { mint: 'AAA1111111111111111111111111111111111111111' } } },
+ { parsed: { type: 'initializeMint', info: { mint: 'BBB1111111111111111111111111111111111111111' } } },
+ { parsed: { type: 'mintTo', info: { mint: 'CCC1111111111111111111111111111111111111111' } } },
+ ],
+ },
+ ],
+ },
+ };
+ // Ambiguous at the initialize tier, so it falls through to the single
+ // unambiguous mintTo rather than picking one of the two arbitrarily.
+ expect(agentTokenMintOf(tx, AGENT)).toBe('CCC1111111111111111111111111111111111111111');
+ });
+
+ it('never returns the agent account itself', () => {
+ const tx = {
+ transaction: { message: { accountKeys: [], instructions: [] } },
+ meta: {
+ innerInstructions: [{ index: 0, instructions: [{ parsed: { type: 'initializeMint', info: { mint: AGENT } } }] }],
+ postTokenBalances: [{ mint: AGENT }],
+ },
+ };
+ expect(agentTokenMintOf(tx, AGENT)).toBe(null);
+ });
+
+ it('falls back to a non-quote token balance for a raw transaction', () => {
+ const tx = {
+ meta: { postTokenBalances: [{ mint: WRAPPED_SOL_MINT }, { mint: LAUNCHED_MINT }] },
+ };
+ expect(agentTokenMintOf(tx, AGENT)).toBe(LAUNCHED_MINT);
+ });
+
+ it('returns null rather than wrapped SOL when that is all there is', () => {
+ expect(agentTokenMintOf({ meta: { postTokenBalances: [{ mint: WRAPPED_SOL_MINT }] } }, AGENT)).toBe(null);
+ });
+});
+
+describe('parsedInstructionsOf', () => {
+ it('reads top-level and inner instructions, skipping unparsed ones', () => {
+ const tx = {
+ transaction: { message: { instructions: [{ parsed: { type: 'transfer', info: {} } }, { programId: 'x' }] } },
+ meta: { innerInstructions: [{ index: 0, instructions: [{ parsed: { type: 'mintTo', info: {} } }] }] },
+ };
+ expect(parsedInstructionsOf(tx).map((i) => i.parsed.type)).toEqual(['transfer', 'mintTo']);
+ });
+
+ it('tolerates a raw transaction with no parsed instructions at all', () => {
+ expect(parsedInstructionsOf({ meta: {} })).toEqual([]);
+ });
+});
+
+// ─── classifyAgentTx ─────────────────────────────────────────────────────────
+
+describe('classifyAgentTx', () => {
+ const base = { agentRef: AGENT, signature: 'sig1', slot: 438961707, blockTime: 1786600541, network: 'mainnet' };
+
+ it('emits a token_launch carrying the real mint', () => {
+ const [ev] = classifyAgentTx({ ...base, tx: setAgentTokenTx() });
+ expect(ev.eventClass).toBe('token_launch');
+ expect(ev.eventName).toBe('SetAgentTokenV1');
+ expect(ev.payload.mint).toBe(LAUNCHED_MINT);
+ expect(ev.occurredAt).toBe(1786600541);
+ });
+
+ it('ignores an instruction name whose owning program is absent', () => {
+ // TransferV1 belongs to Metaplex Core; without Core in the account keys
+ // the log line is some other program's and must not become a transfer.
+ const tx = {
+ transaction: { message: { accountKeys: [{ pubkey: SIGNER }], instructions: [] } },
+ meta: { logMessages: ['Program log: Instruction: TransferV1'] },
+ };
+ expect(classifyAgentTx({ ...base, tx })).toEqual([]);
+ });
+
+ it('classifies a Core transfer when Core is present', () => {
+ const tx = {
+ transaction: { message: { accountKeys: [{ pubkey: SIGNER }, { pubkey: 'Recip111111111111111111111111111111111111111' }, { pubkey: CORE_PROGRAM }], instructions: [] } },
+ meta: {
+ logMessages: ['Program log: Instruction: TransferV1'],
+ preBalances: [10, 0, 0],
+ postBalances: [5, 5, 0],
+ },
+ };
+ const [ev] = classifyAgentTx({ ...base, tx });
+ expect(ev.eventClass).toBe('transfer');
+ expect(ev.counterparty).toBe('Recip111111111111111111111111111111111111111');
+ });
+
+ it('turns a threews memo into a reputation event', () => {
+ const tx = {
+ transaction: { message: { accountKeys: [{ pubkey: SIGNER }], instructions: [] } },
+ meta: {
+ logMessages: ['Program log: Memo (len 42): "{\\"v\\":1,\\"kind\\":\\"threews.feedback.v1\\",\\"score\\":5}"'],
+ },
+ };
+ const [ev] = classifyAgentTx({ ...base, tx });
+ expect(ev.eventClass).toBe('reputation');
+ expect(ev.eventName).toBe('threews.feedback.v1');
+ expect(ev.payload.score).toBe(5);
+ });
+
+ it('drops a failed transaction entirely', () => {
+ expect(classifyAgentTx({ ...base, tx: { meta: { err: { InstructionError: [0, 'Custom'] } } } })).toEqual([]);
+ });
+
+ it('every emitted class is one the index recognizes', () => {
+ const evs = classifyAgentTx({ ...base, tx: setAgentTokenTx() });
+ for (const ev of evs) expect(EVENT_CLASSES).toContain(ev.eventClass);
+ });
+});
+
+describe('accountKeysOf', () => {
+ it('reads the parsed shape as well as the raw one', () => {
+ expect(accountKeysOf({ transaction: { message: { accountKeys: [{ pubkey: AGENT }] } } })).toEqual([AGENT]);
+ expect(accountKeysOf({ transaction: { message: { staticAccountKeys: [AGENT] } } })).toEqual([AGENT]);
+ });
+});
+
+describe('memoPayloadOf', () => {
+ it('returns null for a transaction with no memo', () => {
+ expect(memoPayloadOf({ meta: { logMessages: ['Program log: Instruction: Foo'] } })).toBe(null);
+ });
+});
+
+describe('transferRecipientOf', () => {
+ it('picks the largest gainer that is not the fee payer', () => {
+ const tx = { meta: { preBalances: [100, 0, 0], postBalances: [50, 10, 40] } };
+ expect(transferRecipientOf(tx, ['payer', 'small', 'big'])).toBe('big');
+ });
+
+ it('returns null when the balances do not say', () => {
+ expect(transferRecipientOf({ meta: {} }, ['a', 'b'])).toBe(null);
+ });
+});
+
+// ─── normalizeEvent ──────────────────────────────────────────────────────────
+
+describe('normalizeEvent', () => {
+ const good = {
+ chain: 'solana',
+ agentRef: AGENT,
+ eventClass: 'token_launch',
+ eventName: 'SetAgentTokenV1',
+ tx: 'sig',
+ occurredAt: 1786600541,
+ };
+
+ it('accepts a well-formed Solana event and forces chainId 0', () => {
+ const e = normalizeEvent(good);
+ expect(e.chainId).toBe(0);
+ expect(e.network).toBe('mainnet');
+ expect(e.occurredAt.toISOString()).toBe('2026-08-13T05:55:41.000Z');
+ });
+
+ it('rejects an event with no readable on-chain timestamp', () => {
+ // The alternative is stamping it with now(), which silently corrupts every
+ // timeline and every lag number computed from this table.
+ expect(normalizeEvent({ ...good, occurredAt: null })).toBe(null);
+ expect(normalizeEvent({ ...good, occurredAt: 'not a date' })).toBe(null);
+ });
+
+ it('rejects an unknown event class', () => {
+ expect(normalizeEvent({ ...good, eventClass: 'airdrop' })).toBe(null);
+ });
+});
+
+describe('toDate', () => {
+ it('reads unix seconds and milliseconds alike', () => {
+ expect(toDate(1786600541).toISOString()).toBe('2026-08-13T05:55:41.000Z');
+ expect(toDate(1786600541000).toISOString()).toBe('2026-08-13T05:55:41.000Z');
+ });
+
+ it('rejects values no agent registry could have produced', () => {
+ expect(toDate(1)).toBe(null);
+ expect(toDate(99999999999999)).toBe(null);
+ });
+});
+
+describe('agentRef', () => {
+ it('keys EVM agents by chain and id, Solana agents by account', () => {
+ expect(agentRef({ chain: 'evm', chainId: 8453, agentId: '63521' })).toBe('8453:63521');
+ expect(agentRef({ chain: 'solana', ref: AGENT })).toBe(AGENT);
+ });
+});
+
+// ─── EVM adaptive block window ───────────────────────────────────────────────
+
+describe('nextChunkSize', () => {
+ it('holds the window when the chain is caught up', () => {
+ expect(nextChunkSize({ stored: 1000, configured: null, behind: 40 })).toBe(1000);
+ });
+
+ it('grows while behind so a fast chain can actually catch up', () => {
+ // Arbitrum One consumes 1000 blocks per 251s of chain time against a
+ // 900s cron period, so a fixed window loses ground on every tick.
+ expect(nextChunkSize({ stored: 1000, configured: null, behind: 250_000 })).toBe(2000);
+ expect(nextChunkSize({ stored: 2000, configured: null, behind: 250_000 })).toBe(4000);
+ });
+
+ it('never overshoots the backlog or the provider ceiling', () => {
+ expect(nextChunkSize({ stored: 1000, configured: null, behind: 1500 })).toBe(1500);
+ expect(nextChunkSize({ stored: 8000, configured: null, behind: 10_000_000 })).toBe(8000);
+ });
+
+ it('seeds from the declared per-chain override on the first tick', () => {
+ expect(nextChunkSize({ stored: null, configured: 500, behind: 100 })).toBe(500);
+ });
+});
+
+describe('backoffChunkSize', () => {
+ it('halves the window when a provider rejects the range', () => {
+ expect(backoffChunkSize(4000)).toBe(2000);
+ expect(backoffChunkSize(1000)).toBe(500);
+ });
+
+ it('never falls below a window worth requesting', () => {
+ expect(backoffChunkSize(100)).toBe(100);
+ expect(backoffChunkSize(1)).toBe(100);
+ });
+});
+
+// ─── Sweep capacity ──────────────────────────────────────────────────────────
+
+describe('sweepCycleMin', () => {
+ it('reports the full-sweep time that sets the median lag floor', () => {
+ // The measured failure: 1,576 agents at 40 per 10-minute tick cycles in
+ // 400 minutes, which is exactly the ~200-minute median the status surface
+ // showed. The batch is the lever, so the cycle has to be visible.
+ expect(sweepCycleMin(1576)).toBe(Math.ceil(1576 / SOLANA_SWEEP_BATCH) * SOLANA_SWEEP_PERIOD_MIN);
+ });
+
+ it('keeps the median under the degraded threshold at the shipped batch size', () => {
+ // Median lag is half the cycle; SOLANA_LAG_DEGRADED_MIN is 90.
+ expect(sweepCycleMin(1576) / 2).toBeLessThan(90);
+ });
+
+ it('is null when nothing is queued', () => {
+ expect(sweepCycleMin(0)).toBe(null);
+ });
+});
diff --git a/tests/persona-interview.test.js b/tests/persona-interview.test.js
new file mode 100644
index 000000000..5a94c7900
--- /dev/null
+++ b/tests/persona-interview.test.js
@@ -0,0 +1,188 @@
+/**
+ * The onboarding interview contract.
+ *
+ * `src/agents/persona-interview.js` is the single source of truth shared by the
+ * browser (the create-agent wizard) and the server (POST /api/persona/interview
+ * and the per-agent extract route). Because both sides import it, a drift here
+ * shows up as the extractor being told a different question than the user was
+ * actually asked, which silently poisons the persona instead of erroring.
+ *
+ * The load-bearing property these pin is that the interview is OPTIONAL, question
+ * by question and as a whole: a skipped interview must still compile a real,
+ * complete persona prompt rather than leaving the agent voiceless. That is the
+ * behavior a user hits every time they click past the personality step, so it is
+ * pinned end to end here (defaultPersonaBase -> compilePersona), not just asserted
+ * as a non-empty string.
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ INTERVIEW_QUESTIONS,
+ INTERVIEW_QUESTION_IDS,
+ MAX_INTERVIEW_ANSWERS,
+ MIN_ANSWER_CHARS,
+ MAX_ANSWER_CHARS,
+ normalizeInterview,
+ interviewTranscript,
+ defaultPersonaBase,
+ hasInterviewSignal,
+} from '../src/agents/persona-interview.js';
+import {
+ compilePersona,
+ PERSONA_TRAITS,
+ bandIndex,
+ DEFAULT_TRAIT_VALUE,
+} from '../src/agents/persona-compile.js';
+
+describe('the question set', () => {
+ it('stays within the 5-to-8 question bound the extractor assumes', () => {
+ expect(INTERVIEW_QUESTIONS.length).toBeGreaterThanOrEqual(5);
+ expect(INTERVIEW_QUESTIONS.length).toBeLessThanOrEqual(MAX_INTERVIEW_ANSWERS);
+ });
+
+ it('gives every question a stable unique id and a real prompt', () => {
+ expect(new Set(INTERVIEW_QUESTION_IDS).size).toBe(INTERVIEW_QUESTIONS.length);
+ for (const q of INTERVIEW_QUESTIONS) {
+ expect(q.id).toMatch(/^[a-z][a-z0-9-]*$/);
+ expect(q.prompt.trim().length).toBeGreaterThan(10);
+ // The hint and placeholder are rendered to the user, never submitted.
+ expect(q.hint.trim()).not.toBe('');
+ expect(q.placeholder.trim()).not.toBe('');
+ }
+ });
+});
+
+describe('normalizeInterview', () => {
+ it('accepts the wizard map shape and carries the canonical question text', () => {
+ const rows = normalizeInterview({ purpose: 'Read Solana launches and call them.' });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe('purpose');
+ // The extractor is told the question EXACTLY as the user saw it.
+ expect(rows[0].question).toBe(INTERVIEW_QUESTIONS[0].prompt);
+ });
+
+ it('accepts the API array shape and backfills a known question from its id', () => {
+ const rows = normalizeInterview([{ id: 'sound', answer: 'Blunt, fast, a bit dry.' }]);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].question).toBe(INTERVIEW_QUESTIONS.find((q) => q.id === 'sound').prompt);
+ });
+
+ it('keeps a caller-supplied question for an id it does not know', () => {
+ const rows = normalizeInterview([
+ { id: 'not-a-real-question', question: 'What music does it like?', answer: 'Dub techno.' },
+ ]);
+ expect(rows).toEqual([
+ { id: 'not-a-real-question', question: 'What music does it like?', answer: 'Dub techno.' },
+ ]);
+ });
+
+ it('drops a row with an id it does not know and no question text', () => {
+ // Nothing to tell the model it was asked, so the answer is unusable.
+ expect(normalizeInterview([{ id: 'unknown', answer: 'Some answer here.' }])).toEqual([]);
+ });
+
+ it('treats blank and too-short answers as skips rather than errors', () => {
+ const rows = normalizeInterview({
+ purpose: 'Read Solana launches and call them.',
+ sound: ' ',
+ expertise: '',
+ sample: 'x'.repeat(MIN_ANSWER_CHARS - 1),
+ });
+ expect(rows.map((r) => r.id)).toEqual(['purpose']);
+ });
+
+ it('collapses whitespace so the transcript is stable', () => {
+ const [row] = normalizeInterview({ purpose: ' reads\n\n launches\tfast ' });
+ expect(row.answer).toBe('reads launches fast');
+ });
+
+ it('clamps a runaway answer instead of rejecting it', () => {
+ const [row] = normalizeInterview({ purpose: 'a'.repeat(MAX_ANSWER_CHARS + 500) });
+ expect(row.answer).toHaveLength(MAX_ANSWER_CHARS);
+ });
+
+ it('caps the number of answers so the prompt stays bounded', () => {
+ const many = Array.from({ length: MAX_INTERVIEW_ANSWERS + 6 }, (_, i) => ({
+ id: `q${i}`,
+ question: `Question number ${i}?`,
+ answer: `Answer number ${i}.`,
+ }));
+ expect(normalizeInterview(many)).toHaveLength(MAX_INTERVIEW_ANSWERS);
+ });
+
+ it('returns an empty list for junk input rather than throwing', () => {
+ for (const junk of [null, undefined, 42, 'a string', [null, 7, 'x'], {}]) {
+ expect(normalizeInterview(junk)).toEqual([]);
+ }
+ });
+});
+
+describe('interviewTranscript', () => {
+ it('is deterministic, so an extraction is reproducible', () => {
+ const rows = normalizeInterview({ purpose: 'Call launches.', sound: 'Blunt and dry.' });
+ expect(interviewTranscript(rows)).toBe(interviewTranscript(rows));
+ });
+
+ it('numbers every question and answer it was given', () => {
+ const rows = normalizeInterview({ purpose: 'Call launches.', sound: 'Blunt and dry.' });
+ const transcript = interviewTranscript(rows);
+ expect(transcript).toContain('Q1: ');
+ expect(transcript).toContain('A1: Call launches.');
+ expect(transcript).toContain('A2: Blunt and dry.');
+ // Only the answered questions reach the model; skips leave no trace.
+ expect(transcript).not.toContain('Q3: ');
+ });
+});
+
+describe('hasInterviewSignal', () => {
+ it('is true for a single answer and false for a full skip', () => {
+ expect(hasInterviewSignal(normalizeInterview({ purpose: 'Call launches.' }))).toBe(true);
+ expect(hasInterviewSignal(normalizeInterview({}))).toBe(false);
+ expect(hasInterviewSignal(null)).toBe(false);
+ });
+});
+
+describe('skipping the interview still leaves a working persona', () => {
+ it('builds a base from what the wizard already collected', () => {
+ const base = defaultPersonaBase({
+ name: 'Curve Reader',
+ description: 'reads a Solana token launch and tells you if it is worth your time',
+ greeting: 'Drop a mint and I will pull the curve.',
+ });
+ expect(base).toContain('Curve Reader');
+ expect(base).toContain('reads a Solana token launch');
+ expect(base).toContain('Drop a mint and I will pull the curve.');
+ });
+
+ it('still produces a real persona when the wizard collected nothing', () => {
+ const base = defaultPersonaBase({});
+ expect(base.trim().length).toBeGreaterThan(80);
+ expect(base).toContain('this agent');
+ // The safety floor a default voice must carry.
+ expect(base).toContain('Never give financial advice.');
+ });
+
+ it('compiles to a complete system prompt, not an empty shell', () => {
+ // This is the skip path exactly as the server runs it: no traits, no tone
+ // tags, no vocabulary, just the default base.
+ const prompt = compilePersona({
+ name: 'Curve Reader',
+ description: 'reads a Solana token launch',
+ base: defaultPersonaBase({ name: 'Curve Reader', description: 'reads a Solana token launch' }),
+ });
+ expect(prompt.trim().length).toBeGreaterThan(200);
+ expect(prompt).toContain('Curve Reader');
+ expect(prompt).toContain('How you communicate:');
+ // Every trait axis still lands a behavior line at its neutral default, so
+ // a skipped interview yields a fully specified voice rather than a prompt
+ // with holes in it where the unanswered questions would have gone.
+ for (const trait of PERSONA_TRAITS) {
+ expect(prompt).toContain(trait.bands[bandIndex(DEFAULT_TRAIT_VALUE)]);
+ }
+ });
+
+ it('does not fabricate a greeting the owner never wrote', () => {
+ expect(defaultPersonaBase({ name: 'Curve Reader' })).not.toContain('You open a conversation');
+ });
+});