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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add wallet access rules, public proof page, and anomaly tests
nirholas36c14dc73dec
diff --git a/api/_lib/spend-policy-rules.js b/api/_lib/spend-policy-rules.jsindex ab7f1740b..566874469 100644--- a/api/_lib/spend-policy-rules.js+++ b/api/_lib/spend-policy-rules.js@@ -335,10 +335,13 @@ function describeClause(c) {if (c.op === 'in') return `the asset is one of ${c.value.join(', ')}`;if (c.op === 'not_in') return `the asset is not ${c.value.join(', ')}`;return `the asset is ${c.op === 'neq' ? 'not ' : ''}${c.value}`;- case 'category':- if (c.op === 'in') return `it is a ${c.value.join(' or ')}`;- if (c.op === 'not_in') return `it is not a ${c.value.join(' or ')}`;- return `it is ${c.op === 'neq' ? 'not ' : ''}a ${c.value}`;+ case 'category': {+ const noun = { trade: 'trade', snipe: 'snipe', x402: 'x402 payment', withdraw: 'withdrawal' };+ const phrase = (v) => `${/^[aeiou]/i.test(noun[v] || v) ? 'an' : 'a'} ${noun[v] || v}`;+ if (c.op === 'in') return `it is ${c.value.map(phrase).join(' or ')}`;+ if (c.op === 'not_in') return `it is not ${c.value.map(phrase).join(' or ')}`;+ return `it is ${c.op === 'neq' ? 'not ' : ''}${phrase(c.value)}`;+ }case 'counterparty':if (c.op === 'in') return `the recipient is a known address`;if (c.op === 'not_in') return `the recipient is not an approved address`;diff --git a/api/_lib/trust/access.js b/api/_lib/trust/access.jsnew file mode 100644index 000000000..01f393686--- /dev/null+++ b/api/_lib/trust/access.js@@ -0,0 +1,174 @@+// Wallet access — the SERVER-AUTHORITATIVE enforcement of reputation unlocks.+//+// src/shared/wallet-access-rules.js holds the pure rule catalog (shared with the+// client for display). This module is where those rules become real gates: it+// computes the unlock state from a server-side reputation result (which the client+// cannot forge — every input is a real DB/on-chain read) and enforces ownership ++// requirements before granting any real capability.+//+// • getAgentUnlocks(agentId) — an agent's unlock state (public trust signal).+// • requireUnlock(req, opts) — gate a capability: re-checks ownership AND the+// requirement server-side, throws on failure.+// • claimUnlock / listClaimed — persist an unlocked cosmetic to the agent's+// record (a real, owner-only state change), only+// when the server confirms the unlock.++import { sql } from '../db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../auth.js';+import { getEffectiveReputation } from './reputation-store.js';+import { REPUTATION_VERSION } from './wallet-reputation.js';+import {+ ACCESS_RULES,+ evaluateAllAccess,+ evaluateAccessKey,+ buildAccessContext,+} from '../../../src/shared/wallet-access-rules.js';++// Only cosmetic unlocks can be "claimed" into the agent record — world-area gates+// are evaluated live at entry, not owned.+const CLAIMABLE_SURFACES = new Set(['cosmetic']);++class AccessError extends Error {+ constructor(code, message, status) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++/**+ * Resolve the authenticated user id from a session cookie or bearer token.+ * Returns null for an anonymous caller.+ */+export async function resolveUserId(req) {+ try {+ const session = await getSessionUser(req);+ if (session) return session.id;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return bearer.userId;+ } catch {+ /* anonymous */+ }+ return null;+}++/**+ * The full unlock state for an agent, derived from its server-computed reputation.+ * Public: an agent's tier and what it has unlocked is a trust signal others rely+ * on. Includes the claimed-cosmetic set so the UI knows what's already owned.+ *+ * @param {string} agentId+ * @returns {Promise<object>} { agent_id, tier, score, isNew, context, unlocks[], claimed[], version, computed_at, partial }+ */+export async function getAgentUnlocks(agentId) {+ const rep = await getEffectiveReputation(agentId);+ const context = buildAccessContext(rep);+ const claimed = await listClaimed(agentId);+ const claimedSet = new Set(claimed);+ const unlocks = evaluateAllAccess(context).map((u) => ({+ ...u,+ claimable: CLAIMABLE_SURFACES.has(u.surface),+ claimed: claimedSet.has(u.key),+ }));+ return {+ agent_id: agentId,+ tier: rep.tier,+ tierLabel: rep.tierLabel,+ score: rep.score,+ isNew: rep.isNew,+ accent: rep.accent,+ context,+ unlocks,+ claimed,+ version: REPUTATION_VERSION,+ computed_at: rep.computed_at,+ partial: Boolean(rep.partial),+ };+}++/**+ * Gate a real capability behind an unlock. Re-checks server-side that:+ * 1. the caller is authenticated,+ * 2. the caller OWNS the agent the check is for (ownership is server-truth,+ * never a client flag), and+ * 3. that agent's live reputation actually meets the unlock requirement.+ * Throws AccessError (with .status) on any failure; returns the evaluation on+ * success. This is the only correct way to grant access to a protected capability.+ *+ * @param {object} req+ * @param {object} opts { agentId, key }+ * @returns {Promise<{ unlock: object, rep: object, userId: string }>}+ */+export async function requireUnlock(req, { agentId, key }) {+ const rule = ACCESS_RULES.find((r) => r.key === key);+ if (!rule) throw new AccessError('unknown_unlock', `unknown unlock: ${key}`, 400);++ const userId = await resolveUserId(req);+ if (!userId) throw new AccessError('unauthenticated', 'sign in to use this', 401);++ const [owned] = await sql`+ select 1 from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null limit 1+ `.catch(() => []);+ if (!owned) throw new AccessError('not_owner', 'you do not own this agent', 403);++ const rep = await getEffectiveReputation(agentId);+ const unlock = evaluateAccessKey(key, buildAccessContext(rep));+ if (!unlock?.unlocked) {+ throw new AccessError(+ 'locked',+ unlock?.nextHint ? `Locked — ${unlock.nextHint}` : 'reputation requirement not met',+ 403,+ );+ }+ return { unlock, rep, userId };+}++/**+ * Persist a claimed cosmetic unlock onto the agent record (meta.unlocks[]). A real,+ * owner-only capability — guarded by requireUnlock, so the server has already+ * confirmed ownership AND that the cosmetic is genuinely unlocked. Idempotent.+ *+ * @param {object} req+ * @param {object} opts { agentId, key }+ * @returns {Promise<{ claimed: string[], unlock: object }>}+ */+export async function claimUnlock(req, { agentId, key }) {+ const rule = ACCESS_RULES.find((r) => r.key === key);+ if (!rule) throw new AccessError('unknown_unlock', `unknown unlock: ${key}`, 400);+ if (!CLAIMABLE_SURFACES.has(rule.surface)) {+ throw new AccessError('not_claimable', 'this unlock is granted live, not claimed', 400);+ }+ // Re-authorizes ownership + requirement server-side.+ const { unlock } = await requireUnlock(req, { agentId, key });++ // Append the key to meta.unlocks (a jsonb array) without clobbering other meta.+ await sql`+ update agent_identities+ set meta = jsonb_set(+ coalesce(meta, '{}'::jsonb),+ '{unlocks}',+ coalesce(meta->'unlocks', '[]'::jsonb) ||+ case when coalesce(meta->'unlocks', '[]'::jsonb) @> ${JSON.stringify([key])}::jsonb+ then '[]'::jsonb else ${JSON.stringify([key])}::jsonb end+ )+ where id = ${agentId} and deleted_at is null+ `;+ const claimed = await listClaimed(agentId);+ return { claimed, unlock };+}++/** The cosmetic unlock keys an agent has claimed (meta.unlocks). */+export async function listClaimed(agentId) {+ try {+ const [row] = await sql`+ select coalesce(meta->'unlocks', '[]'::jsonb) as unlocks+ from agent_identities where id = ${agentId} and deleted_at is null limit 1+ `;+ const arr = row?.unlocks;+ return Array.isArray(arr) ? arr.filter((k) => typeof k === 'string') : [];+ } catch {+ return [];+ }+}++export { AccessError };diff --git a/pages/proof.html b/pages/proof.htmlnew file mode 100644index 000000000..a37cd48f8--- /dev/null+++ b/pages/proof.html@@ -0,0 +1,48 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Verify Custody · three.ws</title>+ <meta name="description" content="Verify your three.ws agent wallet's custody yourself — recompute your Merkle leaf, walk the path, and confirm it against the root anchored on Solana, entirely in your browser. Don't trust, verify." />+ <meta name="robots" content="noindex, follow" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Verify Custody · three.ws" />+ <meta property="og:description" content="Recompute your Merkle leaf, walk the path, and confirm it against the on-chain root — entirely in your browser." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <style>+ .poc-shell { max-width: 760px; margin: 0 auto; padding: clamp(20px, 5vw, 44px) 18px 80px; }+ .poc-hero { margin-bottom: 22px; }+ .poc-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: .72rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 10px; }+ .poc-kicker::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80); box-shadow: 0 0 8px color-mix(in srgb, var(--success,#4ade80) 60%, transparent); }+ .poc-title { font-family: var(--font-display, system-ui); font-size: clamp(1.6rem, 4vw, 2.2rem); font-weight: 700; color: var(--ink-bright, #fff); margin: 0 0 8px; line-height: 1.1; }+ .poc-sub { color: var(--ink-dim, #888); font-size: .95rem; line-height: 1.6; margin: 0; max-width: 60ch; }+ .poc-sub a { color: var(--ink, #e8e8e8); }+ #poc-root { margin-top: 8px; }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="poc-shell">+ <section class="poc-hero">+ <p class="poc-kicker">Don't trust · verify</p>+ <h1 class="poc-title">Verify your custody</h1>+ <p class="poc-sub">Your wallet's balance and authorized-state are committed to a Merkle tree whose root is anchored on Solana. This page recomputes your leaf, walks the path to that root, and reads the anchor straight off-chain — all in your browser. We never tell you it's fine; you check it. See the platform-wide picture on the <a href="/integrity">public integrity page</a>.</p>+ </section>+ <div id="poc-root" aria-live="polite"></div>+ </main>++ <script type="module" src="/src/proof.js"></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex 3a1f0f601..1e2771771 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -863,10 +863,15 @@ export class AgentAvatar {this._targetTilt = -0.06; // look slightly down when thinking / waiting}+ // Sustained mood nudges the gaze (elated lifts it, subdued lowers it).+ if (this._mood.active) this._targetTilt += this._moodTilt || 0;+this._currentTilt = _lerp(this._currentTilt, this._targetTilt, dt * 3.0);// ── Forward lean (curiosity leans in, patience leans back) ────────this._targetLean = w.curiosity * 0.03 - w.patience * 0.02;+ // Sustained mood leans the body in when up-and-alert, back when subdued.+ if (this._mood.active) this._targetLean += this._moodLean || 0;const _followMode = this.viewer.state?.followMode;if (_followMode === 'mouse') {// Mouse Y: -1 = top of canvas (look up), +1 = bottom (look down)@@ -899,6 +904,53 @@ export class AgentAvatar {if (!(name in this._morphCurrent)) this._morphCurrent[name] = 0;}+ /** Add to an already-set morph target (used to layer mood over emotion). */+ _addMorph(name, delta) {+ if (!delta) return;+ this._setMorphTarget(name, (this._morphTarget[name] || 0) + delta);+ }++ /**+ * Apply the sustained mood as a continuous facial bias. Lerps the applied+ * mood toward the target so a mood change drifts in over ~1s rather than+ * snapping. Arousal is read relative to the calm baseline (~0.4): above it+ * the eyes widen and brows lift (alert); below it the lids grow heavy+ * (relaxed). Valence sets the mouth: a soft smile when positive, a frown ++ * inner-brow worry when negative.+ */+ _applyMoodLayer(dt) {+ const m = this._moodApplied;+ const k = Math.min(1, dt * 1.2);+ m.valence += (this._mood.valence - m.valence) * k;+ m.arousal += (this._mood.arousal - m.arousal) * k;++ const pos = Math.max(0, m.valence);+ const neg = Math.max(0, -m.valence);+ const act = Math.max(0, m.arousal - 0.4); // alertness above baseline+ const rest = Math.max(0, 0.4 - m.arousal); // drowsiness below baseline++ this._addMorph('mouthSmile', pos * 0.4);+ this._addMorph('cheekSquintLeft', pos * 0.18);+ this._addMorph('cheekSquintRight', pos * 0.18);+ this._addMorph('mouthFrown', neg * 0.4);+ this._addMorph('browInnerUp', neg * 0.4);+ this._addMorph('eyeWideLeft', act * 0.5);+ this._addMorph('eyeWideRight', act * 0.5);+ this._addMorph('browOuterUpLeft', act * 0.28);+ this._addMorph('browOuterUpRight', act * 0.28);+ this._addMorph('eyesClosed', rest * 0.3);++ // Posture: mood leans the body in/out and lifts/drops the gaze. Dropped+ // under prefers-reduced-motion — the facial cue above still carries it.+ if (!this._mood.reduced) {+ this._moodTilt = pos * act * 0.04 - neg * rest * 0.06;+ this._moodLean = pos * act * 0.03 - neg * rest * 0.02;+ } else {+ this._moodTilt = 0;+ this._moodLean = 0;+ }+ }+/*** Resolve canonical ARKit-52 names to their concrete mesh slots once per* content load. The resolver understands the canonical names plus thediff --git a/src/mind-palace.js b/src/mind-palace.jsindex 2227658c3..bda4d0f50 100644--- a/src/mind-palace.js+++ b/src/mind-palace.js@@ -1068,6 +1068,20 @@ class MindPalace {this.removeCardFor(node);this.rebuildRoster();}++ // Permanently drop a node (hard delete / bus forget): remove it from the model+ // and rebuild so its instance slot + edges are reclaimed. Soft-forget does NOT+ // call this — that path keeps the node so undo can restore it.+ dropNode(node) {+ const i = this.nodes.indexOf(node);+ if (i >= 0) this.nodes.splice(i, 1);+ this.byId.delete(node.mem.id);+ this.computeEdges();+ if (this.mode === '3d' && this.scene) this.rebuildInstances();+ this.rebuild2D();+ this.rebuildRoster();+ this.updateStat();+ }restoreNodeToScene(node) {node.bornAt = this._reduce ? 0 : now();node._colorDirty = true;diff --git a/src/proof.js b/src/proof.jsnew file mode 100644index 000000000..475dbc325--- /dev/null+++ b/src/proof.js@@ -0,0 +1,77 @@+/**+ * Standalone /proof page — an owner verifies one agent wallet's custody.+ *+ * Reads ?agent=<id>, fetches the owner-gated inclusion proof, and hands it to the+ * shared renderer, which auto-runs the independent in-browser verifier. With no+ * ?agent it explains how to get here from the wallet hub. A non-owner (or signed-+ * out) visitor is told the per-wallet proof is private and pointed at the public+ * /integrity page, which anyone can verify.+ */++import { apiFetch } from './api.js';+import { renderProofUI, injectProofStyle } from './proof-of-custody/ui.js';+import { verifyInclusionProof } from './proof-of-custody/verifier.js';++const root = document.getElementById('poc-root');++function card(html) {+ return `<div class="awh-proof"><div class="awh-proof-card">${html}</div></div>`;+}++async function main() {+ injectProofStyle();+ const agentId = new URLSearchParams(location.search).get('agent');++ if (!agentId) {+ root.innerHTML = card(`+ <h2>Open from your wallet</h2>+ <p class="awh-proof-lead">To verify a specific wallet, open its <strong>Proof of Custody</strong> tab in the wallet hub, or append <code>?agent=<your-agent-id></code> to this URL. Want the platform-wide view instead?</p>+ <div class="awh-proof-actions" style="margin-top:12px">+ <a class="awh-proof-btn" href="/agents">My agents</a>+ <a class="awh-proof-btn ghost" href="/integrity">Public integrity page ↗</a>+ </div>`);+ return;+ }++ root.innerHTML = `<div class="awh-proof awh-proof-skel" aria-busy="true"><span style="height:64px"></span><span style="height:120px"></span><span style="height:90px"></span></div>`;++ let proof;+ try {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/proof`, { allowAnonymous: true });+ if (res.status === 401) {+ root.innerHTML = card(`+ <h2>This proof is private</h2>+ <p class="awh-proof-lead">Per-wallet custody proofs are only shown to the wallet's owner, so we never expose another owner's data. Sign in if this is your wallet — or verify the platform's on-chain custody, which anyone can do.</p>+ <div class="awh-proof-actions" style="margin-top:12px">+ <a class="awh-proof-btn" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a>+ <a class="awh-proof-btn ghost" href="/integrity">Verify platform custody ↗</a>+ </div>`);+ return;+ }+ if (res.status === 403) {+ root.innerHTML = card(`+ <h2>Not your wallet</h2>+ <p class="awh-proof-lead">You're signed in, but this wallet belongs to another owner. You can still verify the platform's on-chain custody on the public integrity page.</p>+ <div class="awh-proof-actions" style="margin-top:12px"><a class="awh-proof-btn" href="/integrity">Public integrity page ↗</a></div>`);+ return;+ }+ if (res.status === 404) {+ root.innerHTML = card(`<h2>Agent not found</h2><p class="awh-proof-lead">No agent matches that id.</p>`);+ return;+ }+ if (!res.ok) throw new Error(`proof request failed (${res.status})`);+ proof = (await res.json())?.data;+ } catch (err) {+ root.innerHTML = card(`<h2>Couldn't load your proof</h2><p class="awh-proof-lead">${escapeHtml(err.message)}</p><div class="awh-proof-actions" style="margin-top:12px"><button class="awh-proof-btn" type="button" id="poc-retry">Try again</button></div>`);+ document.getElementById('poc-retry')?.addEventListener('click', main);+ return;+ }++ renderProofUI(root, { proof, verify: verifyInclusionProof, shareBase: '/proof', origin: location.origin });+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++main();diff --git a/src/shared/wallet-access-rules.js b/src/shared/wallet-access-rules.jsnew file mode 100644index 000000000..47bf90a3a--- /dev/null+++ b/src/shared/wallet-access-rules.js@@ -0,0 +1,207 @@+// Wallet access rules — the single, pure source of truth for what an agent's+// reputation unlocks across three.ws.+//+// Reputation is only meaningful if it is a KEY: it should open worlds, grant+// cosmetics, and signal trust. This module turns a server-computed reputation+// result into a transparent set of unlocks. It is intentionally PURE (no I/O):+// • the server (api/_lib/trust/access.js) evaluates it authoritatively to gate+// real capabilities — a tampered client can never flip an unlock here, because+// the inputs (tier, score, $THREE held + duration) are all server-computed;+// • the client (src/shared/wallet-access.js) evaluates the SAME rules to reflect+// state and render a "what unlocks next" tracker, but the server enforces.+//+// Every unlock can be reached MORE THAN ONE way — typically "earn the tier" OR+// "hold $THREE" — so reputation and conviction in the platform coin are both real+// keys. Each condition is fully explainable: the UI shows exactly what's required,+// what the viewer has, and how close they are.++import { TIERS } from './agent-financial-reputation.js';++// Low → high. Mirrors the reputation tier ladder; `new` is the resting state.+export const TIER_ORDER = ['new', 'emerging', 'established', 'trusted', 'elite'];++export function tierRank(tier) {+ return TIERS[tier]?.rank ?? 0;+}++/**+ * The unlock catalog. Order is display order. `requires` is an array of+ * CONDITIONS; the unlock is granted if ANY one condition is fully met. Each+ * condition is an object of thresholds that are ANDed together, so e.g.+ * `{ minThreeUsd: 250, minThreeHoldDays: 14 }` means "hold $250 of $THREE for 14+ * days", while a sibling `{ minTier: 'trusted' }` offers the tier path instead.+ */+export const ACCESS_RULES = [+ {+ key: 'arena-elite-floor',+ label: 'Arena Elite Floor',+ blurb: "Stand on the arena's elite floor — a world area reserved for wallets the network already trusts.",+ surface: 'world',+ icon: '🏛',+ accent: '#fbbf24',+ requires: [{ minTier: 'trusted' }, { minThreeUsd: 250, minThreeHoldDays: 14 }],+ },+ {+ key: 'cosmetic-trusted-aura',+ label: 'Trusted Aura',+ blurb: 'A living violet aura on your avatar that signals a trusted wallet at a glance.',+ surface: 'cosmetic',+ icon: '✦',+ accent: '#a78bfa',+ requires: [{ minTier: 'trusted' }, { minThreeUsd: 100, minThreeHoldDays: 30 }],+ },+ {+ key: 'cosmetic-elite-finish',+ label: 'Elite Card Finish',+ blurb: 'The gold elite finish on your wallet trading card and profile.',+ surface: 'cosmetic',+ icon: '👑',+ accent: '#fbbf24',+ requires: [{ minTier: 'elite' }],+ },+ {+ key: 'world-holder-lounge',+ label: 'Holder Lounge',+ blurb: "A $THREE-holder-only world space — hold the coin to keep the key. Sell it all and the lounge locks again.",+ surface: 'world',+ icon: '🪙',+ accent: '#c4b5fd',+ requires: [{ minThreeUsd: 50 }, { minTier: 'elite' }],+ },+];++const clamp01 = (n) => Math.max(0, Math.min(1, n));++function fmtUsdShort(n) {+ n = Number(n) || 0;+ if (n >= 1000) return `$${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`;+ return `$${n < 10 ? n.toFixed(2) : Math.round(n)}`;+}+function fmtDays(d) {+ d = Math.round(Number(d) || 0);+ return d === 1 ? '1 day' : `${d} days`;+}++// Evaluate one threshold-set condition against the viewer context. Returns the+// per-requirement parts (each explainable), whether the whole condition is met,+// and a 0..1 progress driven by the BINDING (least-satisfied) requirement.+function evaluateCondition(cond, ctx) {+ const parts = [];+ if (cond.minTier != null) {+ const need = tierRank(cond.minTier);+ const have = ctx.tierRank;+ parts.push({+ kind: 'tier',+ label: `Reach ${TIERS[cond.minTier]?.label || cond.minTier} tier`,+ met: have >= need,+ have: TIERS[ctx.tier]?.label || ctx.tier,+ need: TIERS[cond.minTier]?.label || cond.minTier,+ progress: need <= 0 ? 1 : clamp01(have / need),+ });+ }+ if (cond.minScore != null) {+ parts.push({+ kind: 'score',+ label: `Score ${cond.minScore}+`,+ met: ctx.score >= cond.minScore,+ have: `${Math.round(ctx.score)}`,+ need: `${cond.minScore}`,+ progress: clamp01(ctx.score / cond.minScore),+ });+ }+ if (cond.minThreeUsd != null) {+ parts.push({+ kind: 'three_usd',+ label: `Hold ${fmtUsdShort(cond.minThreeUsd)} of $THREE`,+ met: ctx.threeUsd >= cond.minThreeUsd,+ have: fmtUsdShort(ctx.threeUsd),+ need: fmtUsdShort(cond.minThreeUsd),+ progress: clamp01(ctx.threeUsd / cond.minThreeUsd),+ });+ }+ if (cond.minThreeHoldDays != null) {+ parts.push({+ kind: 'three_days',+ label: `Hold $THREE for ${fmtDays(cond.minThreeHoldDays)}`,+ met: ctx.threeHoldDays >= cond.minThreeHoldDays,+ have: fmtDays(ctx.threeHoldDays),+ need: fmtDays(cond.minThreeHoldDays),+ progress: clamp01(ctx.threeHoldDays / cond.minThreeHoldDays),+ });+ }+ const met = parts.length > 0 && parts.every((p) => p.met);+ const progress = parts.length ? Math.min(...parts.map((p) => p.progress)) : 0;+ return { met, progress, parts };+}++/**+ * Evaluate one unlock rule against the viewer context.+ *+ * @param {object} rule one ACCESS_RULES entry+ * @param {object} ctx { tier, tierRank, score, isNew, threeUsd, threeHoldDays }+ * @returns {object} { key, label, blurb, surface, icon, accent, unlocked,+ * conditions[], progress, nextHint }+ */+export function evaluateAccess(rule, ctx) {+ const conditions = rule.requires.map((cond) => evaluateCondition(cond, ctx));+ const unlocked = conditions.some((c) => c.met);+ // The most-complete path the viewer is on (for "what unlocks next").+ const best = conditions.reduce((a, b) => (b.progress > a.progress ? b : a), conditions[0] || { progress: 0, parts: [] });+ const progress = unlocked ? 1 : best.progress;+ let nextHint = null;+ if (!unlocked && best?.parts?.length) {+ const blocker = best.parts.find((p) => !p.met);+ if (blocker) nextHint = `${blocker.label} (you're at ${blocker.have})`;+ }+ return {+ key: rule.key,+ label: rule.label,+ blurb: rule.blurb,+ surface: rule.surface,+ icon: rule.icon,+ accent: rule.accent,+ unlocked,+ progress,+ conditions,+ nextHint,+ };+}++/** Evaluate every rule. Returns an array in catalog order. */+export function evaluateAllAccess(ctx) {+ const c = normalizeContext(ctx);+ return ACCESS_RULES.map((rule) => evaluateAccess(rule, c));+}++/** Look up + evaluate a single rule by key. Returns null for an unknown key. */+export function evaluateAccessKey(key, ctx) {+ const rule = ACCESS_RULES.find((r) => r.key === key);+ if (!rule) return null;+ return evaluateAccess(rule, normalizeContext(ctx));+}++/**+ * Build the viewer access context from a reputation result (the object returned by+ * getAgentReputation / the /reputation endpoint). All inputs are server-computed.+ */+export function buildAccessContext(rep) {+ return normalizeContext({+ tier: rep?.tier || 'new',+ score: rep?.score || 0,+ isNew: Boolean(rep?.isNew),+ threeUsd: rep?.totals?.three_usd || 0,+ threeHoldDays: rep?.totals?.three_hold_days || 0,+ });+}++function normalizeContext(ctx = {}) {+ const tier = ctx.tier || 'new';+ return {+ tier,+ tierRank: ctx.tierRank != null ? ctx.tierRank : tierRank(tier),+ score: Number(ctx.score) || 0,+ isNew: Boolean(ctx.isNew),+ threeUsd: Math.max(0, Number(ctx.threeUsd) || 0),+ threeHoldDays: Math.max(0, Number(ctx.threeHoldDays) || 0),+ };+}diff --git a/tests/wallet-anomaly.test.js b/tests/wallet-anomaly.test.jsnew file mode 100644index 000000000..7e5356276--- /dev/null+++ b/tests/wallet-anomaly.test.js@@ -0,0 +1,211 @@+// Unit tests for api/_lib/wallet-anomaly.js — the pure behavioral-anomaly engine.+//+// Covers baseline math, each scoring dimension (size, new-counterparty, velocity,+// off-hours, new-asset), the noisy-OR combination + critical override, the+// low-history widened-tolerance path, sensitivity thresholds, config normalization,+// totality (never throws on garbage), and approve-teaches-the-baseline.++import { describe, it, expect } from 'vitest';+import {+ computeBaseline, scoreOutbound, applyApproval, normalizeAnomalyConfig,+ getAnomalyConfig, summarize, sensitivityPreset, MIN_HISTORY, SENSITIVITY_PRESETS,+} from '../api/_lib/wallet-anomaly.js';++const HOUR = 3_600_000;+const T0 = Date.parse('2026-06-01T12:00:00Z'); // 12:00 UTC++// Build a history of priced spends to one known address at a steady noon-ish hour.+function history(n, { usd = 5, dest = 'KNOWNaddr1111111111111111111111111111111', asset = 'USDC', startHour = 12 } = {}) {+ const out = [];+ for (let i = 0; i < n; i++) {+ const ms = Date.parse(`2026-05-${String((i % 27) + 1).padStart(2, '0')}T${String(startHour).padStart(2, '0')}:00:00Z`);+ out.push({ usd, destination: dest, asset, category: 'x402', created_at: new Date(ms).toISOString() });+ }+ return out;+}++const KNOWN = 'KNOWNaddr1111111111111111111111111111111';+const NEW = 'NEWaddrZZZZ2222222222222222222222222222222';++describe('computeBaseline', () => {+ it('learns size, counterparties, assets and active hours from history', () => {+ const b = computeBaseline(history(10, { usd: 5 }), T0);+ expect(b.n).toBe(10);+ expect(b.total_events).toBe(10);+ expect(b.usd.max).toBe(5);+ expect(b.usd.mean).toBeCloseTo(5, 5);+ expect(b.counterparties).toContain(KNOWN);+ expect(b.counterparty_count).toBe(1);+ expect(b.assets).toEqual(['USDC']);+ expect(b.active_hours).toEqual([12]);+ });++ it('handles empty / non-array input without throwing', () => {+ expect(computeBaseline([], 0).n).toBe(0);+ expect(computeBaseline(null, 0).n).toBe(0);+ expect(computeBaseline(undefined, 0).counterparties).toEqual([]);+ });++ it('ignores unpriced rows in the usd distribution but keeps their destination', () => {+ const b = computeBaseline([+ { usd: null, destination: KNOWN, asset: 'SOL', category: 'withdraw', created_at: new Date(T0).toISOString() },+ { usd: 10, destination: KNOWN, asset: 'USDC', category: 'x402', created_at: new Date(T0).toISOString() },+ ], T0);+ expect(b.n).toBe(1);+ expect(b.usd.max).toBe(10);+ expect(b.counterparty_count).toBe(1);+ });+});++describe('scoreOutbound — dimensions', () => {+ const baseline = computeBaseline(history(12, { usd: 10 }), T0); // max $10, known addr, hour 12+ const cfg = normalizeAnomalyConfig({ sensitivity: 'balanced' });+ const calm = { count_1min: 1, count_10min: 1 };++ it('allows a normal spend (known addr, normal size, normal hour) with no factors', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 8, destination: KNOWN, asset: 'USDC', category: 'x402', atMs: T0 }, recent: calm });+ expect(v.decision).toBe('allow');+ expect(v.factors).toHaveLength(0);+ expect(v.score).toBe(0);+ });++ it('flags an oversized spend (size dimension)', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 80, destination: KNOWN, asset: 'USDC', category: 'trade', atMs: T0 }, recent: calm });+ const f = v.factors.find((x) => x.key === 'size');+ expect(f).toBeTruthy();+ expect(f.label).toMatch(/largest-ever/);+ });++ it('flags a first-ever destination and treats a high-value new dest as critical → freeze', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 60, destination: NEW, asset: 'USDC', category: 'x402', atMs: T0 }, recent: calm });+ const f = v.factors.find((x) => x.key === 'new_counterparty');+ expect(f).toBeTruthy();+ expect(v.critical).toBe(true);+ expect(v.decision).toBe('freeze');+ });++ it('flags a hard velocity burst as critical even for a tiny, known-address spend', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 1, destination: KNOWN, asset: 'USDC', category: 'x402', atMs: T0 }, recent: { count_1min: 10, count_10min: 12 } });+ const f = v.factors.find((x) => x.key === 'velocity');+ expect(f).toBeTruthy();+ expect(f.severity).toBe('critical');+ expect(v.decision).toBe('freeze');+ });++ it('flags activity outside the agent’s usual hours', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 8, destination: KNOWN, asset: 'USDC', category: 'x402', atMs: T0 + 11 * HOUR }, recent: calm });+ expect(v.factors.some((x) => x.key === 'off_hours')).toBe(true);+ });++ it('flags a never-before-moved asset', () => {+ const v = scoreOutbound({ baseline, config: cfg, action: { usdValue: 8, destination: KNOWN, asset: 'BONKmint', category: 'trade', atMs: T0 }, recent: calm });+ expect(v.factors.some((x) => x.key === 'new_asset')).toBe(true);+ });+});++describe('scoreOutbound — sensitivity', () => {+ const baseline = computeBaseline(history(12, { usd: 10 }), T0);+ // A moderate-but-not-critical signal: ~1.6× the largest spend to a KNOWN address,+ // at an off-hour. Lands the combined score between the strict and relaxed thresholds.+ const action = { usdValue: 16, destination: KNOWN, asset: 'USDC', category: 'trade', atMs: T0 + 11 * HOUR };+ const calm = { count_1min: 1, count_10min: 1 };++ it('strict freezes where relaxed allows the same moderate anomaly', () => {+ const strict = scoreOutbound({ baseline, config: { sensitivity: 'strict' }, action, recent: calm });+ const relaxed = scoreOutbound({ baseline, config: { sensitivity: 'relaxed' }, action, recent: calm });+ expect(strict.threshold).toBe(SENSITIVITY_PRESETS.strict.threshold);+ expect(relaxed.threshold).toBe(SENSITIVITY_PRESETS.relaxed.threshold);+ // Same score, different verdict driven purely by the threshold.+ expect(strict.score).toBe(relaxed.score);+ expect(strict.decision).toBe('freeze');+ expect(relaxed.decision).toBe('allow');+ });++ it('never freezes when the guard is disabled', () => {+ const v = scoreOutbound({ baseline, config: { sensitivity: 'strict', enabled: false }, action: { usdValue: 1000, destination: NEW, category: 'x402', atMs: T0 }, recent: { count_1min: 30, count_10min: 50 } });+ expect(v.decision).toBe('allow');+ });+});++describe('scoreOutbound — low history widens tolerances', () => {+ const thin = computeBaseline(history(2, { usd: 5 }), T0); // < MIN_HISTORY+ const cfg = normalizeAnomalyConfig({ sensitivity: 'balanced' });+ const calm = { count_1min: 1, count_10min: 1 };++ it('marks lowHistory and lets a small first-time spend through', () => {+ const v = scoreOutbound({ baseline: thin, config: cfg, action: { usdValue: 3, destination: NEW, asset: 'USDC', category: 'x402', atMs: T0 }, recent: calm });+ expect(v.lowHistory).toBe(true);+ expect(v.decision).toBe('allow');+ });++ it('still catches a materially large brand-new spend even with thin history', () => {+ const v = scoreOutbound({ baseline: thin, config: cfg, action: { usdValue: 400, destination: NEW, asset: 'USDC', category: 'withdraw', atMs: T0 }, recent: calm });+ expect(v.factors.some((x) => x.key === 'new_counterparty')).toBe(true);+ expect(v.score).toBeGreaterThanOrEqual(0.5);+ });+});++describe('scoreOutbound — totality (never throws)', () => {+ it('returns a safe allow verdict on garbage input', () => {+ for (const bad of [undefined, {}, { action: null }, { baseline: 42, action: 'x', recent: 7 }]) {+ const v = scoreOutbound(bad);+ expect(v.decision === 'allow' || v.decision === 'freeze').toBe(true);+ expect(Array.isArray(v.factors)).toBe(true);+ expect(v.score).toBeGreaterThanOrEqual(0);+ }+ });+});++describe('applyApproval — teaches the baseline', () => {+ it('blesses the destination, raises the size ceiling, and adds the hour so it won’t re-trip', () => {+ const base = computeBaseline(history(12, { usd: 10 }), T0);+ const cfg = normalizeAnomalyConfig({ sensitivity: 'balanced' });+ const action = { usdValue: 60, destination: NEW, asset: 'USDC', category: 'x402', atMs: T0 + 11 * HOUR };++ const before = scoreOutbound({ baseline: base, config: cfg, action, recent: { count_1min: 1, count_10min: 1 } });+ expect(before.decision).toBe('freeze');++ const taught = applyApproval(cfg, { destination: NEW, usd: 60, hour_utc: new Date(action.atMs).getUTCHours() });+ expect(taught.allow_destinations).toContain(NEW);+ expect(taught.size_ceiling_usd).toBe(60);++ const after = scoreOutbound({ baseline: base, config: taught, action, recent: { count_1min: 1, count_10min: 1 } });+ expect(after.decision).toBe('allow');+ expect(after.factors.some((x) => x.key === 'new_counterparty')).toBe(false);+ });++ it('approving a known pattern still leaves velocity protection intact', () => {+ const base = computeBaseline(history(12, { usd: 10 }), T0);+ const taught = applyApproval(normalizeAnomalyConfig({}), { destination: NEW, usd: 60, hour_utc: 12 });+ const v = scoreOutbound({ baseline: base, config: taught, action: { usdValue: 1, destination: NEW, category: 'x402', atMs: T0 }, recent: { count_1min: 12, count_10min: 14 } });+ expect(v.decision).toBe('freeze'); // velocity still trips+ });+});++describe('normalizeAnomalyConfig', () => {+ it('clamps invalid input to safe defaults', () => {+ const c = normalizeAnomalyConfig({ sensitivity: 'bogus', extra_hours: [25, -1, 5, 5], size_ceiling_usd: -3, safe_address: ' ' });+ expect(c.sensitivity).toBe('balanced');+ expect(c.extra_hours).toEqual([5]);+ expect(c.size_ceiling_usd).toBe(null);+ expect(c.safe_address).toBe(null);+ expect(c.enabled).toBe(true);+ });++ it('getAnomalyConfig reads from a meta blob', () => {+ expect(getAnomalyConfig({ anomaly: { sensitivity: 'strict' } }).sensitivity).toBe('strict');+ expect(getAnomalyConfig(null).sensitivity).toBe('balanced');+ });+});++describe('summarize + presets', () => {+ it('summarizes the top factor and counts the rest', () => {+ expect(summarize({ factors: [] })).toMatch(/nothing/i);+ expect(summarize({ factors: [{ label: 'A' }] })).toBe('A');+ expect(summarize({ factors: [{ label: 'A' }, { label: 'B' }] })).toMatch(/\+1 more/);+ });+ it('sensitivityPreset falls back to balanced', () => {+ expect(sensitivityPreset('nope').key).toBe('balanced');+ expect(MIN_HISTORY).toBeGreaterThan(0);+ });+});