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.

Add mood embodiment, integrity client, rate-limit and policy refinements

nirholas5d4afe51afd5
diff --git a/api/_lib/anomaly-events.js b/api/_lib/anomaly-events.js
index 38a3d9735..d1c7ccb40 100644
--- a/api/_lib/anomaly-events.js
+++ b/api/_lib/anomaly-events.js
@@ -261,13 +261,15 @@ export async function guardOutboundAnomaly({
};
}
- // Allowed (or a withdraw we only record). Persist if notable. A withdraw that
- // scored a freeze is recorded as 'flagged' for the timeline but never blocked.
- anomalyId = await recordAnomalyEvent({ agentId, userId, network, action, verdict, custodyEventId }).catch((e) => {
+ // Allowed (or a withdraw we only observe). Persist if notable. A withdraw is the
+ // owner's escape hatch — even a freeze-scoring one is recorded as 'allowed' (never
+ // a held flag), since we don't act on it; its factors still show in the timeline.
+ const recordVerdict = enforce ? verdict : { ...verdict, decision: 'allow' };
+ anomalyId = await recordAnomalyEvent({ agentId, userId, network, action, verdict: recordVerdict, custodyEventId }).catch((e) => {
console.warn('[anomaly] record failed', e?.message);
return null;
});
- return { decision: verdict.decision === 'freeze' ? 'freeze' : 'allow', verdict, anomalyId, froze };
+ return { decision: 'allow', verdict, anomalyId, froze };
}
/** Real owner notification for an auto-freeze (in-app + push, gated by prefs). */
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index eab4eb040..c4015ae26 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -438,6 +438,9 @@ export const limits = {
}).limit('global'),
avatarPatch: (userId) => getLimiter('avatar:patch', { limit: 20, window: '1 h' }).limit(userId),
prefsWrite: (userId) => getLimiter('prefs:write', { limit: 30, window: '1 h' }).limit(userId),
+ // Claiming a reputation-unlocked cosmetic onto an agent (api/agents/:id/unlocks).
+ // A low-frequency owner action; this just bounds abusive retries.
+ unlockClaim: (userId) => getLimiter('unlock:claim', { limit: 40, window: '1 h' }).limit(userId),
// Per-user budget for the embeddings endpoint (api/agents/:id/embed — free
// NVIDIA NIM lane first, paid Voyage fallback). Keyed by userId (not IP) so
// the shared platform keys/quotas can't be drained by one account rotating
diff --git a/api/_lib/spend-policy-rules.js b/api/_lib/spend-policy-rules.js
index 566874469..62b98ef10 100644
--- a/api/_lib/spend-policy-rules.js
+++ b/api/_lib/spend-policy-rules.js
@@ -337,7 +337,10 @@ function describeClause(c) {
return `the asset is ${c.op === 'neq' ? 'not ' : ''}${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}`;
+ // "an x402" — the leading letter is sounded (ex-four-oh-two), so treat an
+ // initial vowel OR an x-followed-by-digit as taking "an".
+ const article = (w) => (/^[aeiou]/i.test(w) || /^x\d/i.test(w) ? 'an' : 'a');
+ const phrase = (v) => `${article(noun[v] || v)} ${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)}`;
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 747af852c..83c73468e 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -232,6 +232,11 @@ export default wrap(async function handler(req, res) {
return mod.handleReputation(req, res, id);
}
+ if (sub === 'unlocks') {
+ const mod = await import('./_id/unlocks.js');
+ return mod.handleUnlocks(req, res, id, action);
+ }
+
if (sub === 'memory-seed') {
const mod = await import('./_id/memory-seed.js');
return mod.default(req, res, id);
diff --git a/api/agents/_id/unlocks.js b/api/agents/_id/unlocks.js
index fda8f519f..153b363d7 100644
--- a/api/agents/_id/unlocks.js
+++ b/api/agents/_id/unlocks.js
@@ -61,7 +61,7 @@ export const handleUnlocks = wrap(async (req, res, agentId, action) => {
if (!session) return error(res, 401, 'unauthenticated', 'sign in to claim unlocks');
if (!(await requireCsrf(req, res, session.id))) return;
- const rl = await limits.user(session.id);
+ const rl = await limits.unlockClaim(session.id);
if (!rl.success) return rateLimited(res, rl);
const body = await readJson(req).catch(() => ({}));
diff --git a/api/agents/capabilities.js b/api/agents/capabilities.js
index 62dce762a..82f82d446 100644
--- a/api/agents/capabilities.js
+++ b/api/agents/capabilities.js
@@ -172,22 +172,21 @@ async function handleRevokeAll(req, res, id, userId) {
export default async function handler(req, res, id, action, parts = []) {
if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;
- // Rate-limit reads + writes per IP (shared bucket with other agent endpoints).
- const ip = clientIp(req);
- const rl = await limits.api(ip);
- if (!rl.success) return rateLimited(res, rl);
-
// GET list — owner-gated, no CSRF.
if (req.method === 'GET' && !action) {
const owned = await loadOwner(req, res, id);
if (!owned) return;
+ const rl = await limits.walletRead(owned.auth.userId);
+ if (!rl.success) return rateLimited(res, rl);
try { return await handleList(req, res, id); } catch (e) { return sendErr(res, e); }
}
- // All mutations: owner-gated + CSRF.
+ // All mutations: owner-gated + CSRF + a per-IP critical-action limit.
if (req.method === 'POST' || req.method === 'PUT') {
const owned = await loadOwner(req, res, id);
if (!owned) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
const userId = owned.auth.userId;
try {
diff --git a/data/changelog.json b/data/changelog.json
index 0ca122b97..42ff9b11a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-23",
+ "title": "Proof-of-Custody: verify your agent wallet's custody on-chain yourself",
+ "summary": "Custodial means we hold your wallet's keys and sign for you — so now we make that custody provable instead of asking you to take our word for it. Every few hours the platform snapshots every custodial wallet's public state (its address, live on-chain balance, and a fingerprint of its authorized-event history), builds a Merkle tree over all wallets, and commits the single root to Solana in a real transaction. Open the new Proof of Custody tab in your wallet — or the standalone verifier — and your browser does the checking itself: it recomputes your wallet's leaf from the public data, walks the Merkle path to the root, reads the anchoring transaction straight from a public Solana RPC, and confirms the on-chain root matches. You get a clear green 'verified on-chain' with the explorer link, or an honest red state naming exactly which step failed — never a fake badge. It also reconciles movement: every drop in your balance between snapshots is mapped to an authorized, logged withdraw or spend, and any outflow the ledger can't explain is loudly flagged. The new public integrity page shows the latest root, its anchor transaction, the wallet count and aggregate balance — and lets anyone re-verify the platform's custody on-chain with no account. Don't trust, verify.",
+ "tags": [
+ "security",
+ "feature"
+ ],
+ "link": "/integrity"
+ },
{
"date": "2026-06-23",
"title": "Every agent wallet now has a living trading card you can share",
diff --git a/data/pages.json b/data/pages.json
index b045b7e97..3aad6e2ff 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -643,6 +643,24 @@
"changefreq": "hourly",
"added": "2026-06-15"
},
+ {
+ "path": "/integrity",
+ "title": "Custody Integrity",
+ "description": "Provable, on-chain-anchored custody for every three.ws agent wallet. The platform commits a Merkle root over every wallet's on-chain state to Solana — verify the latest root yourself, no account required.",
+ "priority": 0.7,
+ "changefreq": "hourly",
+ "added": "2026-06-23"
+ },
+ {
+ "path": "/proof",
+ "title": "Verify Custody",
+ "description": "Verify your own three.ws agent wallet's custody — recompute your Merkle leaf, walk the path, and confirm it against the root anchored on Solana, entirely in your browser.",
+ "priority": 0.5,
+ "changefreq": "weekly",
+ "indexable": false,
+ "auth": "required",
+ "added": "2026-06-23"
+ },
{
"path": "/labor-market",
"title": "Agent Labor Market",
diff --git a/src/agents/mood-embodiment.js b/src/agents/mood-embodiment.js
new file mode 100644
index 000000000..1f42f8a9d
--- /dev/null
+++ b/src/agents/mood-embodiment.js
@@ -0,0 +1,148 @@
+// Mood embodiment — the bridge from the mood engine to the body.
+//
+// Subscribes to `mood:changed` (and a couple of real micro-signals) and
+// re-expresses every live surface of the active agent:
+// • each <agent-3d> for the active agent → sustained setMood() (resting face +
+// posture) plus a one-shot expressEmotion() beat on a real spike;
+// • the site-wide walk companion → a mood-coloured presence aura + a
+// breathing-rate shift, and a celebratory wave on a strong positive beat.
+//
+// It owns no mood logic — it only maps the engine's state onto the existing
+// animation/morph API. Importing it boots the mood engine (side-effect) so any
+// page that wants a living body just imports this one module.
+
+import { moodEngine } from './mood-engine.js';
+import { agentBus, EVENTS } from './agent-bus.js';
+
+const REDUCE_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const STYLE_ID = 'mood-embodiment-style';
+
+function injectStyle() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const css = `
+ .walk-companion-host[data-mood], [data-walk-companion][data-mood] {
+ transition: filter 1.2s ease, box-shadow 1.2s ease;
+ }
+ .mood-aura {
+ position: absolute; inset: 0; pointer-events: none; border-radius: 50%;
+ opacity: var(--mood-strength, 0); transition: opacity 1.2s ease, background 1.2s ease;
+ background: radial-gradient(closest-side, var(--mood-color, transparent) 0%, transparent 72%);
+ mix-blend-mode: screen;
+ animation: mood-breathe var(--mood-breathe, 6s) ease-in-out infinite;
+ }
+ @keyframes mood-breathe {
+ 0%, 100% { transform: scale(0.92); }
+ 50% { transform: scale(1.06); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .mood-aura { animation: none; }
+ }
+ `;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = css;
+ document.head.appendChild(el);
+}
+
+// Resolve the <agent-3d> elements that represent the agent this mood belongs to.
+// We only drive avatars explicitly bound to that agent — never impose one agent's
+// mood on an unrelated embed.
+function avatarsFor(agentId) {
+ if (typeof document === 'undefined') return [];
+ const all = Array.from(document.querySelectorAll('agent-3d'));
+ return all.filter((el) => {
+ const bound = el.getAttribute('agent-id') || el.getAttribute('agent_id');
+ return bound && agentId && bound === agentId;
+ });
+}
+
+function applyToAvatars(payload) {
+ const els = avatarsFor(payload.agentId);
+ for (const el of els) {
+ try {
+ el.setMood?.(payload.valence, payload.arousal, { reducedMotion: REDUCE_MOTION });
+ // A real spike (a strong, signal-driven transition) plays a one-shot
+ // emotional beat on top of the new resting expression.
+ if (payload.beat && payload.mood?.trigger) {
+ el.expressEmotion?.(payload.mood.trigger, payload.mood.intensity ?? 0.6);
+ }
+ } catch { /* element not ready — it'll pick up the next emit */ }
+ }
+}
+
+// ── Walk companion presence ──────────────────────────────────────────────────
+
+function companionRoot() {
+ if (typeof document === 'undefined') return null;
+ const host =
+ (typeof window !== 'undefined' && window.__walkCompanion?.instance?.host) ||
+ document.querySelector('.walk-companion-host, [data-walk-companion]');
+ return host || null;
+}
+
+function applyToCompanion(payload) {
+ const host = companionRoot();
+ if (!host) return;
+ const color = payload.mood?.color || '#7c93b3';
+ // Strength scales with how far the mood is from the neutral resting point:
+ // a calm agent glows faintly, an elated/agitated one clearly.
+ const intensity = Math.min(1, Math.abs(payload.valence) * 0.9 + Math.abs(payload.arousal - 0.35) * 0.8);
+ const strength = (0.12 + intensity * 0.5).toFixed(3);
+ // Arousal drives the breathing rate — calm breathes slow, alert breathes fast.
+ const breathe = REDUCE_MOTION ? '0s' : `${(7.5 - payload.arousal * 4).toFixed(2)}s`;
+
+ host.dataset.mood = payload.mood?.key || 'calm';
+ host.style.position = host.style.position || 'relative';
+ host.style.setProperty('--mood-color', color);
+ host.style.filter = REDUCE_MOTION ? '' : `drop-shadow(0 0 ${(intensity * 14).toFixed(1)}px ${color})`;
+
+ let aura = host.querySelector(':scope > .mood-aura');
+ if (!aura) {
+ aura = document.createElement('div');
+ aura.className = 'mood-aura';
+ aura.setAttribute('aria-hidden', 'true');
+ host.appendChild(aura);
+ }
+ aura.style.setProperty('--mood-color', color);
+ aura.style.setProperty('--mood-strength', strength);
+ aura.style.setProperty('--mood-breathe', breathe);
+
+ // A strong positive spike makes the companion wave — a real celebratory beat.
+ if (payload.beat && payload.valence > 0.3) {
+ try { window.__walkCompanion?.instance?.controller?.playWave?.(); } catch { /* no controller */ }
+ }
+}
+
+let _started = false;
+
+export function startMoodEmbodiment() {
+ if (_started || typeof window === 'undefined') return;
+ _started = true;
+ injectStyle();
+
+ const onMood = (payload) => {
+ if (!payload?.agentId) return;
+ applyToAvatars(payload);
+ applyToCompanion(payload);
+ };
+ // `replay: true` re-expresses the current mood the instant a surface mounts.
+ agentBus.on(EVENTS.MOOD_CHANGED, onMood, { replay: true });
+
+ // Involuntary micro-expression: a brief flicker of recognition when the agent
+ // recalls a memory mid-conversation — grounded in the real recall event, not a
+ // timer. Independent of mood magnitude so it reads even on a stoic agent.
+ agentBus.on(EVENTS.MEMORY_RECALLED, (p) => {
+ if (REDUCE_MOTION) return;
+ for (const el of avatarsFor(p?.agentId)) {
+ try { el.expressEmotion?.('curiosity', 0.22); } catch { /* not ready */ }
+ }
+ });
+}
+
+// Boot the engine + the binder on import.
+moodEngine.start();
+startMoodEmbodiment();
+
+export default startMoodEmbodiment;
diff --git a/src/integrity.js b/src/integrity.js
new file mode 100644
index 000000000..c264aa8a2
--- /dev/null
+++ b/src/integrity.js
@@ -0,0 +1,167 @@
+/**
+ * Public /integrity page — the platform-wide face of provable custody.
+ *
+ * Fetches the no-auth aggregate (latest epoch, Merkle root, on-chain anchor,
+ * wallet count, aggregate SOL) and then VERIFIES the latest root on-chain right
+ * here: it reads the anchor transaction straight from a public Solana RPC and
+ * confirms the committed root matches what the API reported. Anyone — no account —
+ * gets a green "verified on-chain" or an honest red/pending state. Never shows
+ * per-wallet private data.
+ */
+
+import { readOnchainAnchor } from './proof-of-custody/verifier.js';
+
+const root = document.getElementById('intg-root');
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function short(s, h = 10, t = 10) {
+ const v = String(s || '');
+ return v.length > h + t + 1 ? `${v.slice(0, h)}…${v.slice(-t)}` : v;
+}
+function fmtTime(iso) {
+ if (!iso) return '—';
+ try { return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }); } catch { return String(iso); }
+}
+function fmtSol(lamports) {
+ const n = Number(BigInt(String(lamports || '0'))) / 1e9;
+ return n.toLocaleString(undefined, { maximumFractionDigits: 4 });
+}
+
+async function main() {
+ root.innerHTML = `<div class="intg-card intg-skel" aria-busy="true"><span style="height:70px"></span><span style="height:120px"></span><span style="height:200px"></span></div>`;
+
+ let data;
+ try {
+ const res = await fetch('/api/custody/integrity', { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`integrity request failed (${res.status})`);
+ data = (await res.json())?.data;
+ } catch (err) {
+ root.innerHTML = `<div class="intg-card"><h2 class="intg-h2">Couldn't load integrity data</h2><p class="intg-p">${esc(err.message)}</p><button class="intg-btn" id="intg-retry" type="button">Try again</button></div>`;
+ document.getElementById('intg-retry')?.addEventListener('click', main);
+ return;
+ }
+
+ const latest = data?.latest;
+ if (!latest) {
+ root.innerHTML = `<div class="intg-card">
+ <h2 class="intg-h2">No attestations yet</h2>
+ <p class="intg-p">The first custody attestation epoch hasn't been committed yet. Once the snapshot job runs, the latest Merkle root and its on-chain anchor will appear here, verifiable by anyone.</p>
+ ${explainBlock()}
+ </div>`;
+ return;
+ }
+
+ root.innerHTML = `
+ <div class="intg-card">
+ <div class="intg-status is-pending" id="intg-status">
+ <div class="intg-seal" id="intg-seal"><span class="intg-spin" aria-hidden="true"></span></div>
+ <div class="intg-status-main">
+ <div class="intg-status-title" id="intg-status-title">Verifying the latest root on-chain…</div>
+ <div class="intg-status-sub" id="intg-status-sub">Reading the anchor transaction directly from a public Solana RPC.</div>
+ </div>
+ </div>
+ <div class="intg-grid">
+ <div class="intg-stat"><div class="intg-stat-k">Latest epoch</div><div class="intg-stat-v">#${esc(latest.epoch)}</div></div>
+ <div class="intg-stat"><div class="intg-stat-k">Wallets attested</div><div class="intg-stat-v">${esc(latest.wallet_count)}</div></div>
+ <div class="intg-stat"><div class="intg-stat-k">Aggregate balance</div><div class="intg-stat-v">${esc(fmtSol(latest.total_lamports))} SOL</div></div>
+ <div class="intg-stat"><div class="intg-stat-k">Snapshot</div><div class="intg-stat-v" style="font-size:.8rem">${esc(fmtTime(latest.created_at))}</div></div>
+ <div class="intg-stat"><div class="intg-stat-k">Merkle root</div><div class="intg-stat-v" style="font-size:.78rem" title="${esc(latest.merkle_root)}">${esc(short(latest.merkle_root))}</div></div>
+ <div class="intg-stat"><div class="intg-stat-k">On-chain anchor</div><div class="intg-stat-v" style="font-size:.8rem">${latest.anchor_explorer
+ ? `<a href="${esc(latest.anchor_explorer)}" target="_blank" rel="noopener" title="${esc(latest.anchor_sig)}">${esc(short(latest.anchor_sig, 8, 8))} ↗</a>`
+ : `<span class="intg-pill ${esc(latest.anchor_status)}">${esc(latest.anchor_status)}</span>`}</div></div>
+ </div>
+ </div>
+
+ <div class="intg-card">
+ <h2 class="intg-h2">How verification works</h2>
+ <p class="intg-p">No trust required. The check above ran in your browser; here's exactly what it did.</p>
+ ${explainBlock()}
+ </div>
+
+ ${recentBlock(data.recent, latest.epoch)}
+
+ <div class="intg-card">
+ <h2 class="intg-h2">Own an agent wallet?</h2>
+ <p class="intg-p">Verify your own wallet's inclusion proof — recompute your leaf and confirm it sits under this anchored root.</p>
+ <a class="intg-btn" href="/proof">Verify my custody →</a>
+ </div>
+ `;
+
+ verifyLatest(latest);
+}
+
+async function verifyLatest(latest) {
+ const statusEl = document.getElementById('intg-status');
+ const seal = document.getElementById('intg-seal');
+ const title = document.getElementById('intg-status-title');
+ const sub = document.getElementById('intg-status-sub');
+ const set = (cls, ico, t, s) => {
+ statusEl.className = `intg-status ${cls}`;
+ seal.innerHTML = ico;
+ title.textContent = t;
+ sub.innerHTML = s;
+ };
+
+ if (!latest.anchor_sig) {
+ set('is-pending', '◷', `Epoch #${latest.epoch} not yet anchored`,
+ `The latest snapshot is recorded but its root hasn't been committed on-chain yet (status: ${esc(latest.anchor_status)}). It will be anchored shortly.`);
+ return;
+ }
+
+ try {
+ const onchain = await readOnchainAnchor(latest.anchor_sig, latest.anchor_network || 'devnet');
+ const apiRoot = String(latest.merkle_root || '').toLowerCase();
+ const match = onchain.root === apiRoot && Number(onchain.epoch) === Number(latest.epoch);
+ if (match) {
+ set('is-verified', '✓', `Custody verified on-chain · epoch #${latest.epoch}`,
+ `The Merkle root reported here exactly matches the root committed in <a href="${esc(latest.anchor_explorer)}" target="_blank" rel="noopener">the anchor transaction</a> on Solana ${esc(latest.anchor_network || 'devnet')}. Verified ${esc(fmtTime(new Date().toISOString()))}.`);
+ } else {
+ set('is-failed', '✕', 'Root mismatch',
+ `The root committed on-chain (${esc(short(onchain.root))}) does not match the reported root. This should never happen — do not trust until resolved.`);
+ }
+ } catch (err) {
+ set('is-pending', '◷', 'Could not read the anchor on-chain',
+ `We couldn't independently fetch the anchor transaction right now (${esc(err.message)}). Treating as unverified rather than trusting the server — retry shortly.`);
+ }
+}
+
+function explainBlock() {
+ return `<div class="intg-explain">
+ <div class="intg-step"><div class="intg-step-n">01</div><div class="intg-step-t">Snapshot</div><div class="intg-step-d">Every wallet's address, live on-chain balance and authorized-state head are hashed into a leaf.</div></div>
+ <div class="intg-step"><div class="intg-step-n">02</div><div class="intg-step-t">Merkle root</div><div class="intg-step-d">All leaves are folded into one root — a single fingerprint of every wallet's state this epoch.</div></div>
+ <div class="intg-step"><div class="intg-step-n">03</div><div class="intg-step-t">Anchor on Solana</div><div class="intg-step-d">The root is committed in a signed transaction on-chain, where it can't be altered after the fact.</div></div>
+ <div class="intg-step"><div class="intg-step-n">04</div><div class="intg-step-t">Verify</div><div class="intg-step-d">Your browser reads that transaction straight from a public RPC and confirms the root matches.</div></div>
+ </div>`;
+}
+
+function recentBlock(recent, latestEpoch) {
+ if (!Array.isArray(recent) || recent.length === 0) return '';
+ const rows = recent.map((e) => {
+ const sig = e.anchor_sig
+ ? `<a href="${esc(explorer(e.anchor_sig, e.anchor_network))}" target="_blank" rel="noopener">${esc(short(e.anchor_sig, 6, 6))} ↗</a>`
+ : `<span class="intg-pill ${esc(e.anchor_status)}">${esc(e.anchor_status)}</span>`;
+ return `<tr>
+ <td>#${esc(e.epoch)}${Number(e.epoch) === Number(latestEpoch) ? ' <span class="intg-pill anchored" style="margin-left:4px">latest</span>' : ''}</td>
+ <td>${esc(e.wallet_count)}</td>
+ <td>${esc(fmtSol(e.total_lamports))}</td>
+ <td>${esc(short(e.merkle_root, 6, 6))}</td>
+ <td>${sig}</td>
+ <td style="font-size:.74rem">${esc(fmtTime(e.created_at))}</td>
+ </tr>`;
+ }).join('');
+ return `<div class="intg-card">
+ <h2 class="intg-h2">Attestation history</h2>
+ <p class="intg-p">Epochs are monotonic and append-only, so a rollback or replay is detectable. Each root is independently anchored.</p>
+ <table class="intg-table">
+ <thead><tr><th>Epoch</th><th>Wallets</th><th>Agg. SOL</th><th>Root</th><th>Anchor</th><th>Snapshot</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>`;
+}
+
+function explorer(sig, network) {
+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';
+ return `https://solscan.io/tx/${sig}${cluster}`;
+}
+
+main();
diff --git a/tests/spend-policy-compiler.test.js b/tests/spend-policy-compiler.test.js
new file mode 100644
index 000000000..c3729e4c7
--- /dev/null
+++ b/tests/spend-policy-compiler.test.js
@@ -0,0 +1,99 @@
+/**
+ * Natural-language → spend-policy compiler — the deterministic parser path.
+ *
+ * The compiler prefers the platform LLM but degrades to a real intent parser, so
+ * the feature compiles with no model configured. These tests exercise that parser
+ * (no network) and assert the README's worked example maps to the exact enforceable
+ * rules — the compiler must never silently produce nothing for a clear instruction,
+ * and everything it emits is hard-validated by the same normalizer the engine uses.
+ *
+ * Assertions check rule SHAPE (action + clause), which both the parser and a
+ * well-behaved model satisfy, so the suite is robust whether or not a key is set.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { compilePolicyFromText } from '../api/_lib/spend-policy-compiler.js';
+
+// Find a rule containing a clause matching field (+optional op/value/action).
+function hasRule(policy, { action, field, op, value } = {}) {
+ return (policy?.rules || []).some((r) =>
+ (action == null || r.action === action) &&
+ (r.when || []).some((c) =>
+ (field == null || c.field === field) &&
+ (op == null || c.op === op) &&
+ (value == null || c.value === value)));
+}
+
+describe('compilePolicyFromText — worked example', () => {
+ it('compiles "block any payment over $50"', async () => {
+ const r = await compilePolicyFromText('Block any payment over $50.');
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'block', field: 'amount_usd', op: 'gt', value: 50 })).toBe(true);
+ expect(Array.isArray(r.readback)).toBe(true);
+ expect(r.readback.length).toBeGreaterThan(0);
+ });
+
+ it('compiles "up to $50 a day" to a daily-total block', async () => {
+ const r = await compilePolicyFromText('Let it trade up to $50 a day.');
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'block', field: 'daily_total_usd' })).toBe(true);
+ });
+
+ it('compiles "only trade tokens at least a day old"', async () => {
+ const r = await compilePolicyFromText('Only trade tokens at least a day old.');
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'block', field: 'token_age_hours', op: 'lt' })).toBe(true);
+ });
+
+ it('compiles "never spend my last 1 SOL"', async () => {
+ const r = await compilePolicyFromText('Never spend my last 1 SOL.');
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'block', field: 'sol_reserve_after', op: 'lt', value: 1 })).toBe(true);
+ });
+
+ it('compiles "stop everything if a trade drops more than 30%" to a freeze', async () => {
+ const r = await compilePolicyFromText('Stop everything if a single trade drops more than 30%.');
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'freeze', field: 'trade_pnl_pct', op: 'lt', value: -30 })).toBe(true);
+ });
+
+ it('compiles "only ever pay services I\'ve used before"', async () => {
+ const r = await compilePolicyFromText("Only ever pay services I've used before.");
+ expect(r.ok).toBe(true);
+ expect(hasRule(r.policy, { action: 'block', field: 'counterparty_seen_before', op: 'is', value: false })).toBe(true);
+ });
+
+ it('compiles the full README sentence into multiple rules', async () => {
+ const r = await compilePolicyFromText(
+ 'Let it trade up to $50/day on tokens at least a day old, never spend my last 1 SOL, stop everything if a single trade drops more than 30%, and only ever pay services I\'ve used before.',
+ );
+ expect(r.ok).toBe(true);
+ expect(r.policy.rules.length).toBeGreaterThanOrEqual(3);
+ expect(hasRule(r.policy, { field: 'sol_reserve_after' })).toBe(true);
+ expect(hasRule(r.policy, { action: 'freeze' })).toBe(true);
+ });
+});
+
+describe('compilePolicyFromText — refusal / empty', () => {
+ it('refuses an empty input', async () => {
+ const r = await compilePolicyFromText(' ');
+ expect(r.ok).toBe(false);
+ expect(r.error).toBe('empty');
+ });
+
+ it('reports unparseable rather than inventing a rule', async () => {
+ const r = await compilePolicyFromText('the quick brown fox jumps over the lazy dog');
+ // No concrete spend rule → not ok, with an actionable message.
+ expect(r.ok).toBe(false);
+ expect(typeof r.message).toBe('string');
+ });
+
+ it('every compiled rule is hard-validated (enforceable)', async () => {
+ const r = await compilePolicyFromText('Block any payment over $5 and freeze if a trade drops 50%.');
+ expect(r.ok).toBe(true);
+ for (const rule of r.policy.rules) {
+ expect(['allow', 'block', 'require_step_up', 'freeze']).toContain(rule.action);
+ expect(rule.when.length).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index 165f15e55..c5a740a58 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -281,6 +281,8 @@ const appConfig = {
'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),
i18n: resolve(__dirname, 'src/i18n.js'),
app: resolve(__dirname, 'pages/app.html'),
+ proof: resolve(__dirname, 'pages/proof.html'),
+ integrity: resolve(__dirname, 'pages/integrity.html'),
'app-demo': resolve(__dirname, 'pages/app-demo.html'),
'app-next': resolve(__dirname, 'pages/app-next.html'),
home: resolve(__dirname, 'pages/home.html'),
@@ -799,6 +801,10 @@ support: resolve(__dirname, 'pages/support.html'),
'/watchlist/': resolve(root, 'pages/watchlist.html'),
'/leaderboard': resolve(root, 'pages/leaderboard.html'),
'/leaderboard/': resolve(root, 'pages/leaderboard.html'),
+ '/proof': resolve(root, 'pages/proof.html'),
+ '/proof/': resolve(root, 'pages/proof.html'),
+ '/integrity': resolve(root, 'pages/integrity.html'),
+ '/integrity/': resolve(root, 'pages/integrity.html'),
'/labor-market': resolve(root, 'pages/labor-market.html'),
'/labor-market/': resolve(root, 'pages/labor-market.html'),
'/vaults': resolve(root, 'pages/vaults.html'),