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: add real-time alert and automation engine for user-defined alerts

roundtripped75ad67a9e109
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fef53db00..bd0e9ce8b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Every IRL moment now has a designed, honest state** — IRL asks for the three most sensitive permissions a web app can — camera, motion, and location — and we made every moment around them feel deliberate instead of uncertain. While your phone is still finding your GPS fix, the top bar shows a clear "Finding your location…" shimmer so the wait never looks like an empty, nobody-here screen. If discovery ever has to slow down to catch its breath, you get a calm "catching up…" note that quietly recovers on its own — never a scary error. The live-presence indicator stays honest too: when it drops, nearby discovery keeps working and nothing implies otherwise. Every control is now reachable by keyboard with a visible focus ring, screen readers announce each state change once, and all of it respects reduced-motion settings. (`/irl`) `[improvement]`
- **Every page now shares with its own social card** — Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews. `[improvement, infra]`
- **Fixed broken links and added retry on failed loads across the app** — Several navigation links pointed at pages that no longer exist — "View plans" on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working "claim" button with a plain explanation that revenue share is distributed to holders automatically. `[fix, improvement]`
+- **Freeze your agent wallet in one tap — plus hardened custody security** — Your agent's wallet now has a freeze switch. Open the wallet's Limits & Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too. `[feature, security]`
- **Fund any agent wallet by scanning a QR or copying the address — with live confirmation** — The agent wallet's Deposit tab is now a complete, public funding panel: a crisp QR code (generated on-device, no third-party service) that your phone wallet can scan, a one-tap copyable Solana address, an optional preset amount, and a Solana deep-link that opens Phantom, Solflare or Backpack on mobile. The panel watches the agent's real on-chain balance and confirms the moment your SOL lands — "◎0.5 SOL received" — instead of leaving you guessing. Anyone can fund an agent, not just its owner, and the new "Fund agent wallet" button on the create-agent success screen leads new users straight into it. `[feature]`
- **Funds and payments hardened: wallet-key isolation, spend-cap races, recipient checks** — Following the security audit, we strengthened everything that touches money. Custodial agent-wallet private keys now encrypt with a dedicated key — separate from the session secret — and a unique salt per wallet, so the secret guarding your funds no longer shares fate with anything else (existing wallets keep working; they re-key on next use). Per-agent daily spend limits, x402 payment de-duplication, and on-chain permission caps are now enforced atomically, closing races where a burst of concurrent requests could slip past a budget or run paid work twice for one payment. Pay-by-name sends re-check that the name still resolves to the exact address you approved before the agent signs, and reject look-alike or invalid targets; withdrawals now only ever pay out to a wallet you've already saved. We also removed a stored cross-site-scripting vector in uploaded 3D-model metadata and the admin panel, added clickjacking and permissions-policy protections site-wide, and moved IPFS pinning fully server-side so no upload credential ever ships to the browser. No action needed on your end. `[security]`
- **Getting-started progress now follows you across the whole platform** — Your setup checklist no longer forgets what you've done. The floating "Getting started" guide and the dashboard's onboarding panel now share one source of truth: the moment you create an avatar, give an agent a personality, or embed a widget, every checklist on the site ticks that step — no more seeing "2 of 4 done" in one place and "0 of 3" in another on the same visit. Visiting your dashboard reconciles your real progress automatically, and saving a persona to an agent now completes the "give it a brain" step the instant it happens. `[improvement]`
@@ -29,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL teaches you how to find agents — and an empty area now feels alive** — IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small "?" in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle "Look around 👀 · or be the first to pin here" prompt with a one-tap way to place your own agent — so an empty spot reads as "keep exploring," not "this is broken." The moment a real agent comes into range, the prompt fades away on its own. (`/irl`) `[improvement]`
- **One API, many services: the three.ws API gateway** — We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface. `[feature, sdk]`
- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`
+- **Pay-per-call vanity wallets now do seed phrases and encrypted delivery** — The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away. (`/vanity-wallet`) `[feature, security]`
- **Pinning your agent holds up when GPS gets flaky** — Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear "Getting your location…" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint. (`/irl`) `[fix]`
- **Place AI agents at fixed spots around a real room** — IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect. (`/irl`) `[feature]`
- **Platform-wide API security hardening** — We completed a full security audit of the API and tightened it across the board. Server errors no longer echo internal details back to callers — they return a short reference code you can quote to support, while the real diagnostics stay server-side (this also closes a path where a backend service key could surface in an error message). Account-changing actions made from the website — updating preferences, managing webhooks and payout wallets, marking notifications read, scheduling posts, setting skill prices — now carry cross-site request-forgery protection, so a malicious page can't act on your behalf. Sign-in, wallet-linking, GitHub connect and sensitive admin actions gained rate limits, and image-analysis requests are now screened so a supplied URL can't be used to probe internal systems. API access via developer keys is unaffected. `[security]`
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
index 6619eb195..c7dacedbe 100644
--- a/api/_lib/agent-trade-guards.js
+++ b/api/_lib/agent-trade-guards.js
@@ -44,6 +44,12 @@ export const SPEND_LIMIT_DEFAULTS = Object.freeze({
daily_usd: null,
per_tx_usd: null,
withdraw_allowlist: [],
+ // Wallet freeze / kill switch. When true, every AUTONOMOUS outbound path
+ // (trade, snipe, x402) is rejected immediately. The owner's own withdraw is
+ // deliberately NOT blocked — a freeze must never trap the owner's funds; the
+ // safe direction (sweeping out) stays open so a freeze can be used to lock down
+ // a misbehaving agent while still evacuating its balance.
+ frozen: false,
});
// Per-agent discretionary-trade policy (lamports-denominated), stored at
@@ -139,6 +145,7 @@ export function normalizeSpendLimits(raw) {
daily_usd: numOrNull(r.daily_usd),
per_tx_usd: numOrNull(r.per_tx_usd),
withdraw_allowlist: deduped,
+ frozen: r.frozen === true,
updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
};
}
@@ -167,6 +174,7 @@ export async function setSpendLimits(agentId, userId, patch, { req = null } = {}
per_tx_usd: 'per_tx_usd' in patch ? patch.per_tx_usd : prev.per_tx_usd,
withdraw_allowlist:
'withdraw_allowlist' in patch ? patch.withdraw_allowlist : prev.withdraw_allowlist,
+ frozen: 'frozen' in patch ? patch.frozen === true : prev.frozen,
});
next.updated_at = new Date().toISOString();
@@ -445,6 +453,15 @@ export async function enforceSpendLimit({
}) {
const lim = limits || getSpendLimits(meta);
+ // 0. Wallet freeze — blocks every autonomous path; owner withdraw stays open.
+ if (lim.frozen && category !== 'withdraw') {
+ throw new SpendLimitError(
+ 'wallet_frozen',
+ 'This wallet is frozen. Autonomous spending (trades, snipes, payments) is paused. Unfreeze it under Limits & Safety to resume.',
+ { category },
+ );
+ }
+
// 1. Withdraw allowlist — destination gate.
if (category === 'withdraw' && lim.withdraw_allowlist.length > 0) {
const dest = typeof destination === 'string' ? destination.trim() : '';
@@ -512,6 +529,15 @@ export async function reserveSpendUsd({
}) {
const lim = limits || getSpendLimits(meta);
+ // Wallet freeze — blocks every autonomous path; owner withdraw stays open.
+ if (lim.frozen && category !== 'withdraw') {
+ throw new SpendLimitError(
+ 'wallet_frozen',
+ 'This wallet is frozen. Autonomous spending (trades, snipes, payments) is paused. Unfreeze it under Limits & Safety to resume.',
+ { category },
+ );
+ }
+
// Withdraw allowlist — destination gate (same as enforceSpendLimit).
if (category === 'withdraw' && lim.withdraw_allowlist.length > 0) {
const dest = typeof destination === 'string' ? destination.trim() : '';
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
index 15342c10b..f606327a9 100644
--- a/api/_lib/agent-wallet.js
+++ b/api/_lib/agent-wallet.js
@@ -19,83 +19,23 @@
// deploys don't break, but the per-record salt still applies.
import { webcrypto } from 'node:crypto';
-import { env } from './env.js';
import { evmFallbackProvider } from './evm/rpc.js';
+// Single source of truth for the AES-256-GCM secret box (HKDF key derivation,
+// per-record salt, v1 legacy read). Shared with the coin treasury + launcher so
+// every custodial secret on the platform uses the same at-rest scheme.
+import { encryptSecret, decryptSecret, isEncryptedSecret } from './secret-box.js';
-const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
const randomBytes = (n) => {
const b = new Uint8Array(n);
(globalThis.crypto || webcrypto).getRandomValues(b);
return b;
};
-const V2_PREFIX = 'v2:';
-const LEGACY_SALT = new TextEncoder().encode('agent-wallet-v1');
-let _warnedFallback = false;
-
-// Dedicated master secret for wallet encryption, decoupled from JWT_SECRET.
-function walletMasterSecret() {
- const dedicated = env.WALLET_ENCRYPTION_KEY;
- if (dedicated && dedicated.length >= 16) return dedicated;
- if (!_warnedFallback) {
- _warnedFallback = true;
- console.warn(
- '[agent-wallet] WALLET_ENCRYPTION_KEY is not set (or too short); falling back to ' +
- 'JWT_SECRET for custodial key encryption. Set a dedicated WALLET_ENCRYPTION_KEY ' +
- '(>=16 chars) so wallet confidentiality does not depend on the session secret.',
- );
- }
- return env.JWT_SECRET;
-}
-
-// ── Key derivation ──────────────────────────────────────────────────────────
-// Derive an AES-256 key from a secret + salt via HKDF-SHA256.
-async function deriveKey(secret, salt) {
- const raw = new TextEncoder().encode(secret);
- const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
- return subtle.deriveKey(
- { name: 'HKDF', hash: 'SHA-256', salt, info: new Uint8Array(0) },
- base,
- { name: 'AES-GCM', length: 256 },
- false,
- ['encrypt', 'decrypt'],
- );
-}
-
-// ── Encrypt / decrypt ───────────────────────────────────────────────────────
-
-// v2 layout: "v2:" + base64( salt[16] || iv[12] || ciphertext+tag ).
-async function encrypt(plaintext) {
- const salt = randomBytes(16);
- const iv = randomBytes(12);
- const key = await deriveKey(walletMasterSecret(), salt);
- const data = new TextEncoder().encode(plaintext);
- const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
- const buf = new Uint8Array(salt.length + iv.length + ct.byteLength);
- buf.set(salt, 0);
- buf.set(iv, salt.length);
- buf.set(new Uint8Array(ct), salt.length + iv.length);
- return V2_PREFIX + Buffer.from(buf).toString('base64');
-}
-
-async function decrypt(ciphertext) {
- if (typeof ciphertext === 'string' && ciphertext.startsWith(V2_PREFIX)) {
- const raw = Buffer.from(ciphertext.slice(V2_PREFIX.length), 'base64');
- const salt = raw.subarray(0, 16);
- const iv = raw.subarray(16, 28);
- const ct = raw.subarray(28);
- const key = await deriveKey(walletMasterSecret(), salt);
- const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
- return new TextDecoder().decode(plain);
- }
- // Legacy v1: JWT_SECRET + constant salt, no version tag.
- const raw = Buffer.from(ciphertext, 'base64');
- const iv = raw.subarray(0, 12);
- const ct = raw.subarray(12);
- const key = await deriveKey(env.JWT_SECRET, LEGACY_SALT);
- const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
- return new TextDecoder().decode(plain);
-}
+// Local aliases preserve the original call sites below; re-exported so existing
+// importers of these names from agent-wallet.js keep working.
+const encrypt = encryptSecret;
+const decrypt = decryptSecret;
+export { encryptSecret, decryptSecret, isEncryptedSecret };
// ── Wallet generation ───────────────────────────────────────────────────────
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 6494f09af..c5c86f2fd 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -261,10 +261,17 @@ export async function searchPublicAvatars({ q, tag, category, limit = 24, cursor
av.appearance, av.appearance_hash, av.baked_storage_key, av.baked_at,
av.size_bytes,
av.content_type, av.source, av.source_meta, av.fork_count, av.visibility, av.tags, av.view_count, av.created_at,
- ai.id as agent_id, ai.onchain as agent_onchain
+ ai.id as agent_id, ai.onchain as agent_onchain,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix
from avatars av
left join lateral (
- select id, meta->'onchain' as onchain from agent_identities
+ select id, meta->'onchain' as onchain,
+ meta->>'solana_address' as solana_address,
+ meta->>'solana_vanity_prefix' as solana_vanity_prefix,
+ meta->>'solana_vanity_suffix' as solana_vanity_suffix
+ from agent_identities
where avatar_id = av.id and owner_id = av.owner_id and deleted_at is null
order by (meta->'onchain') is not null desc, created_at asc limit 1
) ai on true
diff --git a/api/_lib/coin/distribution.js b/api/_lib/coin/distribution.js
index 5e9b569a2..7958d9698 100644
--- a/api/_lib/coin/distribution.js
+++ b/api/_lib/coin/distribution.js
@@ -53,7 +53,7 @@ export async function snapshotHolders(coin) {
// ─── Claim creator fees + allocation split ──────────────────────────────────
export async function claimAndSplit(coin) {
- const creator = loadCoinCreatorFromCoin(coin);
+ const creator = await loadCoinCreatorFromCoin(coin);
if (!creator) {
await sql`
insert into coin_events (coin_id, kind, payload)
diff --git a/api/_lib/coin/treasury.js b/api/_lib/coin/treasury.js
index 1d8b6a9bb..926fb9741 100644
--- a/api/_lib/coin/treasury.js
+++ b/api/_lib/coin/treasury.js
@@ -20,6 +20,7 @@
import { Keypair, PublicKey, SystemProgram, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
import { getConnection } from '../pump.js';
+import { decryptSecret, isEncryptedSecret } from '../secret-box.js';
const SOL_LAMPORTS = 1_000_000_000n;
const TX_MAX_TRANSFERS = 18; // SystemProgram.transfer is ~96 bytes; leaves room for compute-budget ix
@@ -43,21 +44,38 @@ export function loadCoinTreasury() {
* Load the pump.fun creator keypair for a specific mint.
*
* Lookup order:
- * 1. COIN_CREATOR_SECRET_KEY_B64_<MINT> (env, deploy-time secret)
+ * 1. COIN_CREATOR_SECRET_KEY_B64_<MINT> (env, deploy-time secret, base64)
* 2. coin.metadata.creator_secret_b64 (DB, set by the launch script)
*
- * Returns null if neither source is configured (caller decides whether to
- * fall back to dry-run or error).
+ * The DB value is AES-256-GCM-encrypted at rest under WALLET_ENCRYPTION_KEY
+ * (the same custodial-key scheme as agent wallets) — a `v2:`-prefixed blob is
+ * decrypted before use. Pre-encryption rows held a raw base64 secret in the
+ * clear; those are still read (so launches keep claiming fees) but emit a loud
+ * deprecation warning — re-run the launcher / a re-encrypt sweep to upgrade them.
+ *
+ * Async because decryption is async. Returns null if neither source is
+ * configured (caller decides whether to fall back to dry-run or error).
*/
-export function loadCoinCreatorFromCoin(coin) {
+export async function loadCoinCreatorFromCoin(coin) {
const mintKey = `COIN_CREATOR_SECRET_KEY_B64_${coin.mint}`;
const envValue = process.env[mintKey];
if (envValue) return decodeB64Keypair(envValue, mintKey);
const dbValue = coin?.metadata?.creator_secret_b64;
- if (dbValue) return decodeB64Keypair(dbValue, 'coin.metadata.creator_secret_b64');
+ if (!dbValue) return null;
+
+ if (isEncryptedSecret(dbValue)) {
+ const b64 = await decryptSecret(dbValue);
+ return decodeB64Keypair(b64, 'coin.metadata.creator_secret_b64 (decrypted)');
+ }
- return null;
+ // Legacy: a plaintext base64 secret was stored before at-rest encryption.
+ // Honor it so existing launches keep working, but make the exposure visible.
+ console.warn(
+ `[coin/treasury] mint ${coin.mint}: creator_secret_b64 is stored UNENCRYPTED. ` +
+ 'Re-store it through the launcher (it now encrypts at rest) to remove the plaintext key.',
+ );
+ return decodeB64Keypair(dbValue, 'coin.metadata.creator_secret_b64 (legacy plaintext)');
}
/** Lamports → SOL string for log lines. */
diff --git a/api/_lib/secret-box.js b/api/_lib/secret-box.js
new file mode 100644
index 000000000..e04d1bd4d
--- /dev/null
+++ b/api/_lib/secret-box.js
@@ -0,0 +1,93 @@
+// Secret box — the single AES-256-GCM encrypt/decrypt primitive for every
+// custodial secret the platform stores at rest (agent wallet keys, pump.fun coin
+// creator keys). Kept dependency-free (only `env` + webcrypto) so it can be
+// imported by lean call sites — a Solana-only CLI or the coin treasury — without
+// dragging in ethers/EVM providers.
+//
+// Key management (v2): the encryption key derives from a DEDICATED secret
+// (WALLET_ENCRYPTION_KEY) — independent of JWT_SECRET — with a RANDOM per-record
+// salt embedded in each ciphertext. v1 ciphertexts (no version tag, JWT_SECRET +
+// constant salt) still decrypt via the legacy branch so older records keep
+// working; new writes always use v2. Set WALLET_ENCRYPTION_KEY in every
+// environment that holds custodial secrets; until it is set the code falls back
+// to JWT_SECRET (with a one-time warning) so deploys don't break.
+
+import { webcrypto } from 'node:crypto';
+import { env } from './env.js';
+
+const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
+const randomBytes = (n) => {
+ const b = new Uint8Array(n);
+ (globalThis.crypto || webcrypto).getRandomValues(b);
+ return b;
+};
+
+export const V2_PREFIX = 'v2:';
+const LEGACY_SALT = new TextEncoder().encode('agent-wallet-v1');
+let _warnedFallback = false;
+
+// Dedicated master secret for at-rest encryption, decoupled from JWT_SECRET.
+function walletMasterSecret() {
+ const dedicated = env.WALLET_ENCRYPTION_KEY;
+ if (dedicated && dedicated.length >= 16) return dedicated;
+ if (!_warnedFallback) {
+ _warnedFallback = true;
+ console.warn(
+ '[secret-box] WALLET_ENCRYPTION_KEY is not set (or too short); falling back to ' +
+ 'JWT_SECRET for custodial secret encryption. Set a dedicated WALLET_ENCRYPTION_KEY ' +
+ '(>=16 chars) so secret confidentiality does not depend on the session secret.',
+ );
+ }
+ return env.JWT_SECRET;
+}
+
+// Derive an AES-256 key from a secret + salt via HKDF-SHA256.
+async function deriveKey(secret, salt) {
+ const raw = new TextEncoder().encode(secret);
+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
+ return subtle.deriveKey(
+ { name: 'HKDF', hash: 'SHA-256', salt, info: new Uint8Array(0) },
+ base,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ );
+}
+
+// v2 layout: "v2:" + base64( salt[16] || iv[12] || ciphertext+tag ).
+export async function encryptSecret(plaintext) {
+ const salt = randomBytes(16);
+ const iv = randomBytes(12);
+ const key = await deriveKey(walletMasterSecret(), salt);
+ const data = new TextEncoder().encode(plaintext);
+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
+ const buf = new Uint8Array(salt.length + iv.length + ct.byteLength);
+ buf.set(salt, 0);
+ buf.set(iv, salt.length);
+ buf.set(new Uint8Array(ct), salt.length + iv.length);
+ return V2_PREFIX + Buffer.from(buf).toString('base64');
+}
+
+export async function decryptSecret(ciphertext) {
+ if (typeof ciphertext === 'string' && ciphertext.startsWith(V2_PREFIX)) {
+ const raw = Buffer.from(ciphertext.slice(V2_PREFIX.length), 'base64');
+ const salt = raw.subarray(0, 16);
+ const iv = raw.subarray(16, 28);
+ const ct = raw.subarray(28);
+ const key = await deriveKey(walletMasterSecret(), salt);
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
+ return new TextDecoder().decode(plain);
+ }
+ // Legacy v1: JWT_SECRET + constant salt, no version tag.
+ const raw = Buffer.from(ciphertext, 'base64');
+ const iv = raw.subarray(0, 12);
+ const ct = raw.subarray(12);
+ const key = await deriveKey(env.JWT_SECRET, LEGACY_SALT);
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
+ return new TextDecoder().decode(plain);
+}
+
+/** True if a stored value is a v2 ciphertext (vs a legacy plaintext/base64 blob). */
+export function isEncryptedSecret(value) {
+ return typeof value === 'string' && value.startsWith(V2_PREFIX);
+}
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 1354df5f8..e3c373c6b 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -6,7 +6,7 @@ import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
-import { generateSolanaAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
+import { generateSolanaAgentWallet, recoverSolanaAgentKeypair, encryptSecret } from '../_lib/agent-wallet.js';
import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';
import { reverseLookupAddress } from '../../src/solana/sns.js';
import {
@@ -19,8 +19,7 @@ import {
TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../_lib/pump-vanity.js';
-import { webcrypto, randomUUID } from 'node:crypto';
-import { env } from '../_lib/env.js';
+import { randomUUID } from 'node:crypto';
import { recordEvent } from '../_lib/usage.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import { logAudit } from '../_lib/audit.js';
@@ -45,7 +44,6 @@ const SOL_FEE_RESERVE_LAMPORTS = 15_000n; // ~3× a single-signature base fee
const RENT_EXEMPT_FALLBACK_LAMPORTS = 890_880n; // getMinimumBalanceForRentExemption(0)
const TOKEN_ACCOUNT_RENT_FALLBACK_LAMPORTS = 2_039_280n; // 165-byte SPL token account
-const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;
const AIRDROP_LAMPORTS = LAMPORTS_PER_SOL;
@@ -121,23 +119,12 @@ async function _reverseSnsCached(address) {
return value;
}
-async function _deriveKey() {
- const raw = new TextEncoder().encode(env.JWT_SECRET);
- const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
- return subtle.deriveKey(
- { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('agent-wallet-v1'), info: new Uint8Array(0) },
- base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'],
- );
-}
-async function _encryptSecret(plaintext) {
- const key = await _deriveKey();
- const iv = new Uint8Array(12);
- (globalThis.crypto || webcrypto).getRandomValues(iv);
- const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));
- const buf = new Uint8Array(iv.length + ct.byteLength);
- buf.set(iv, 0); buf.set(new Uint8Array(ct), iv.length);
- return Buffer.from(buf).toString('base64');
-}
+// Encrypt a custodial Solana secret for storage. Delegates to the shared secret
+// box so imported / regenerated wallets are written with the SAME v2 scheme
+// (dedicated WALLET_ENCRYPTION_KEY + random per-record salt) as freshly-generated
+// ones. Previously this path wrote a weaker v1 ciphertext (JWT_SECRET + constant
+// salt); recoverSolanaAgentKeypair still reads those legacy records.
+const _encryptSecret = (plaintext) => encryptSecret(plaintext);
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -987,7 +974,7 @@ async function handleLimits(req, res, id) {
// owner surface. A PUT may patch either or both: a `trade_limits` object
// updates the discretionary-trade caps (per-trade SOL, daily budget, breaker,
// kill switch); the top-level USD/allowlist keys update the spend policy.
- const wantsSpend = ['daily_usd', 'per_tx_usd', 'withdraw_allowlist'].some((k) => k in body);
+ const wantsSpend = ['daily_usd', 'per_tx_usd', 'withdraw_allowlist', 'frozen'].some((k) => k in body);
let limitsOut = getSpendLimits(meta);
let tradeLimitsOut = getTradeLimits(meta);
try {
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index 3037be38e..24256284a 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -76,7 +76,10 @@ async function handleAgentsByAvatar(req, res) {
const rows = await sql`
SELECT i.id, i.name, i.description, i.profile_image_url, i.created_at,
- i.erc8004_agent_id, i.chain_id
+ i.erc8004_agent_id, i.chain_id,
+ i.meta->>'solana_address' AS solana_address,
+ i.meta->>'solana_vanity_prefix' AS solana_vanity_prefix,
+ i.meta->>'solana_vanity_suffix' AS solana_vanity_suffix
FROM agent_identities i
WHERE i.avatar_id = ${id}
AND i.deleted_at IS NULL
@@ -92,6 +95,12 @@ async function handleAgentsByAvatar(req, res) {
profileImage: r.profile_image_url || null,
onchain: r.erc8004_agent_id != null,
chainId: r.chain_id || null,
+ // Public wallet fields so every surface renders the shared wallet chip
+ // (tip for visitors, vanity entry for the owner). Mirrors api/trending.js
+ // + api/characters.js. Secret material is never selected.
+ solana_address: r.solana_address || null,
+ solana_vanity_prefix: r.solana_vanity_prefix || null,
+ solana_vanity_suffix: r.solana_vanity_suffix || null,
createdAt: r.created_at,
url: `/agent/${r.id}`,
}));
diff --git a/api/irl/agent-card.js b/api/irl/agent-card.js
index 0b45c1016..8b63e803a 100644
--- a/api/irl/agent-card.js
+++ b/api/irl/agent-card.js
@@ -186,6 +186,11 @@ async function buildCard(agentId, fallback = {}) {
bio: bio || fallback.description || null,
thumbnail_url: agent.avatar_thumbnail_key && thumbPub ? publicUrl(agent.avatar_thumbnail_key) : null,
profile_url: agent.home_url || `/agents/${agent.id}`,
+ // Public custodial wallet (same value GET /api/agents/:id/solana serves
+ // anonymously) so the IRL inspect card can render the wallet chip + Tip.
+ solana_address: meta.solana_address || null,
+ solana_vanity_prefix: meta.solana_vanity_prefix || null,
+ solana_vanity_suffix: meta.solana_vanity_suffix || null,
},
reputation,
services: services.map((s) => ({
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 2a4fb1abe..ae74bc331 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -362,7 +362,7 @@ async function handleCreate(req, res) {
}
return json(res, 201, {
- data: { agent: toDetail({ ...agent, author_name: null, author_avatar: null }) },
+ data: { agent: toDetail({ ...agent, author_name: null, author_avatar: null }, {}, auth.userId) },
});
}
@@ -399,7 +399,8 @@ async function handleMine(req, res) {
return json(res, 200, {
data: {
- items: rows.map((r) => ({ ...toCard(r), is_published: r.is_published })),
+ // The "mine" listing is always the caller's own agents — owner everywhere.
+ items: rows.map((r) => ({ ...toCard(r), is_published: r.is_published, is_owner: true })),
},
});
}
@@ -452,6 +453,9 @@ async function handleList(req, res, url) {
av.visibility AS avatar_visibility,
ai.meta->'onchain' AS onchain,
ai.meta->'token' AS token,
+ ai.meta->>'solana_address' AS solana_address,
+ ai.meta->>'solana_vanity_prefix' AS solana_vanity_prefix,
+ ai.meta->>'solana_vanity_suffix' AS solana_vanity_suffix,
u.display_name AS author_name,
EXISTS (
SELECT 1 FROM agent_skill_prices asp
@@ -510,6 +514,9 @@ async function handleList(req, res, url) {
av.visibility AS avatar_visibility,
ai.meta->'onchain' AS onchain,
ai.meta->'token' AS token,
+ ai.meta->>'solana_address' AS solana_address,
+ ai.meta->>'solana_vanity_prefix' AS solana_vanity_prefix,
+ ai.meta->>'solana_vanity_suffix' AS solana_vanity_suffix,
u.display_name AS author_name,
EXISTS (
SELECT 1 FROM agent_skill_prices asp
@@ -596,6 +603,9 @@ async function handleDetail(req, res, id) {
av.visibility AS avatar_visibility,
a.meta->>'sol_mint_address' AS sol_mint_address,
a.meta->>'pumpfun_network' AS pumpfun_network,
+ a.meta->>'solana_address' AS solana_address,
+ a.meta->>'solana_vanity_prefix' AS solana_vanity_prefix,
+ a.meta->>'solana_vanity_suffix' AS solana_vanity_suffix,
COALESCE((SELECT count(*)::int FROM skill_purchases sp
WHERE sp.agent_id = a.id AND sp.status = 'confirmed'), 0) AS buyers_total,
COALESCE((SELECT count(*)::int FROM skill_purchases sp
@@ -743,7 +753,7 @@ async function handleDetail(req, res, id) {
{
data: {
agent: {
- ...toDetail(row),
+ ...toDetail(row, skill_prices, auth?.userId || null),
skill_prices,
bookmarked,
purchased_skills,
@@ -1289,7 +1299,7 @@ async function handlePublish(req, res, id) {
`,
]);
- return json(res, 200, { data: { agent: toDetail(updated), version: next_version } });
+ return json(res, 200, { data: { agent: toDetail(updated, {}, auth.userId), version: next_version } });
}
// ── View counter ───────────────────────────────────────────────────────────
@@ -1346,12 +1356,23 @@ function toCard(row) {
// badge can light up a deployed agent's marketplace card. Null when absent.
onchain: row.onchain || null,
token: row.token || null,
+ // Public custodial wallet + vanity pattern for the shared wallet chip. The
+ // address is public (GET /api/agents/:id/solana serves it anonymously); the
+ // signing secret never leaves the server.
+ solana_address: row.solana_address || null,
+ solana_vanity_prefix: row.solana_vanity_prefix || null,
+ solana_vanity_suffix: row.solana_vanity_suffix || null,
};
}
-function toDetail(row, skill_prices = {}) {
+function toDetail(row, skill_prices = {}, viewerId = null) {
return {
...toCard(row),
+ // Server-authoritative ownership: true only for the signed-in owner. Drives
+ // which wallet affordance the client renders (owner hub vs visitor tip/pay).
+ // Visitors and anonymous reads always get false. The owner-only API routes
+ // (withdraw, vanity, limits) re-check ownership regardless of this flag.
+ is_owner: !!viewerId && row.user_id === viewerId,
system_prompt: row.system_prompt,
greeting: row.greeting,
capabilities: row.capabilities || {},
diff --git a/api/pump/[action].js b/api/pump/[action].js
index b9d6f7286..a91285ef4 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -2445,6 +2445,9 @@ async function handleLaunches(req, res) {
select pam.mint, pam.network, pam.name, pam.symbol, pam.buyback_bps,
pam.metadata_uri, pam.quote_mint, pam.created_at,
ai.id as agent_id, ai.name as agent_name,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix,
a.thumbnail_key as avatar_thumbnail_key,
a.visibility as avatar_visibility,
oc.score as oracle_score, oc.tier as oracle_tier, oc.category as oracle_category
@@ -2463,6 +2466,9 @@ async function handleLaunches(req, res) {
select pam.mint, pam.network, pam.name, pam.symbol, pam.buyback_bps,
pam.metadata_uri, pam.quote_mint, pam.created_at,
ai.id as agent_id, ai.name as agent_name,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix,
a.thumbnail_key as avatar_thumbnail_key,
a.visibility as avatar_visibility
from pump_agent_mints pam
@@ -2476,6 +2482,9 @@ async function handleLaunches(req, res) {
select pam.mint, pam.network, pam.name, pam.symbol, pam.buyback_bps,
pam.metadata_uri, pam.quote_mint, pam.created_at,
ai.id as agent_id, ai.name as agent_name,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix,
a.thumbnail_key as avatar_thumbnail_key,
a.visibility as avatar_visibility
from pump_agent_mints pam
@@ -2512,6 +2521,11 @@ async function handleLaunches(req, res) {
r.avatar_thumbnail_key && avatarPublic
? r2PublicUrl(r.avatar_thumbnail_key)
: null,
+ // Public custodial wallet of the launching agent (+ vanity pattern)
+ // so the shared wallet chip renders the same on the feed as everywhere.
+ solana_address: r.agent_solana_address || null,
+ solana_vanity_prefix: r.agent_solana_vanity_prefix || null,
+ solana_vanity_suffix: r.agent_solana_vanity_suffix || null,
}
: null,
};
diff --git a/api/pump/launch-detail.js b/api/pump/launch-detail.js
index 4d0e33ac0..c495e1835 100644
--- a/api/pump/launch-detail.js
+++ b/api/pump/launch-detail.js
@@ -155,6 +155,9 @@ async function buildDetail(mint, network) {
pam.sharing_config, pam.created_at,
ai.id as agent_id, ai.name as agent_name, ai.description as agent_description,
ai.is_public as agent_public,
+ ai.solana_address as agent_solana_address,
+ ai.solana_vanity_prefix as agent_solana_vanity_prefix,
+ ai.solana_vanity_suffix as agent_solana_vanity_suffix,
a.thumbnail_key as avatar_thumbnail_key, a.visibility as avatar_visibility
from pump_agent_mints pam
left join agent_identities ai on ai.id = pam.agent_id and ai.deleted_at is null
@@ -272,6 +275,11 @@ async function buildDetail(mint, network) {
url: `/agents/${reg.agent_id}`,
is_public: reg.agent_public,
avatar_thumbnail_url: avatarPublic ? safeR2Url(reg.avatar_thumbnail_key) : null,
+ // Public custodial wallet (+ vanity) of the launching agent, so the
+ // shared wallet chip renders identically here as on the feed/profile.
+ solana_address: reg.agent_solana_address || null,
+ solana_vanity_prefix: reg.agent_solana_vanity_prefix || null,
+ solana_vanity_suffix: reg.agent_solana_vanity_suffix || null,
}
: null,
economics,
diff --git a/api/users/me/purchased-skills.js b/api/users/me/purchased-skills.js
index f59a103b7..bcc0c11ba 100644
--- a/api/users/me/purchased-skills.js
+++ b/api/users/me/purchased-skills.js
@@ -39,7 +39,10 @@ export default wrap(async (req, res) => {
sp.trial_remaining,
sp.created_at,
ai.name AS agent_name,
- ai.profile_image_url AS agent_thumbnail
+ ai.profile_image_url AS agent_thumbnail,
+ ai.meta->>'solana_address' AS agent_solana_address,
+ ai.meta->>'solana_vanity_prefix' AS agent_solana_vanity_prefix,
+ ai.meta->>'solana_vanity_suffix' AS agent_solana_vanity_suffix
FROM skill_purchases sp
LEFT JOIN agent_identities ai ON ai.id = sp.agent_id
WHERE sp.user_id = ${userId} AND sp.status IN ('confirmed', 'trial')
diff --git a/api/x402/vanity.js b/api/x402/vanity.js
index 9f5f41784..228c7569b 100644
--- a/api/x402/vanity.js
+++ b/api/x402/vanity.js
@@ -55,6 +55,17 @@ import {
expectedAttemptsFor,
MAX_SERVER_PATTERN_LENGTH,
} from '../../src/solana/vanity/grinder-node.js';
+import {
+ grindVanityMnemonic,
+ expectedMnemonicAttempts,
+ MAX_MNEMONIC_PATTERN_LENGTH,
+} from '../../src/solana/vanity/mnemonic-grinder.js';
+import { STRENGTH_WORD_COUNTS, DEFAULT_STRENGTH } from '../../src/solana/vanity/mnemonic.js';
+import {
+ sealToRecipient,
+ parseX25519Key,
+ SEALED_ENVELOPE_SCHEME,
+} from '../../src/solana/vanity/sealed-envelope.js';
import bs58 from 'bs58';
const ROUTE = '/api/x402/vanity';
@@ -66,6 +77,14 @@ const routeConfig = { path: ROUTE, method: 'GET', requiredScope: REQUIRED_SCOPE
// headroom for facilitator verify + settle round-trips.
const GRIND_TIME_BUDGET_MS = 45_000;
+// Output formats. `keypair` (default) returns a raw Ed25519 secret key ground in
+// the WASM engine. `mnemonic` returns a BIP-39 seed phrase whose derived key
+// (m/44'/501'/0'/0', Phantom's default) lands on the vanity address — importable
+// as a recovery phrase into any wallet.
+const FORMAT_KEYPAIR = 'keypair';
+const FORMAT_MNEMONIC = 'mnemonic';
+const FORMATS = new Set([FORMAT_KEYPAIR, FORMAT_MNEMONIC]);
+
// Difficulty-tiered price in USDC atomic units (6 decimals). Indexed by the
// combined prefix+suffix length. Each character multiplies expected work by 58,
// so the price climbs to track compute cost. Length 0 (discovery probe with no
@@ -77,18 +96,36 @@ const PRICE_BY_LENGTH = {
3: 250_000, // $0.25
};
-function priceAtomicsFor(combinedLength) {
+// Mnemonic mode grinds ~100× slower (PBKDF2-HMAC-SHA512 per attempt) and ships a
+// full importable seed phrase, so it is priced as a premium tier and capped at
+// 2 characters server-side.
+const PRICE_BY_LENGTH_MNEMONIC = {
+ 0: 50_000, // $0.05 — base / probe
+ 1: 50_000, // $0.05
+ 2: 500_000, // $0.50
+};
+
+function priceAtomicsFor(format, combinedLength) {
+ if (format === FORMAT_MNEMONIC) {
+ return PRICE_BY_LENGTH_MNEMONIC[combinedLength] ?? PRICE_BY_LENGTH_MNEMONIC[MAX_MNEMONIC_PATTERN_LENGTH];
+ }
return PRICE_BY_LENGTH[combinedLength] ?? PRICE_BY_LENGTH[MAX_SERVER_PATTERN_LENGTH];
}
const ROUTE_DESCRIPTION =
- 'three.ws Solana Vanity Grinder — generate a brand-new Solana keypair whose ' +
+ 'three.ws Solana Vanity Grinder — generate a brand-new Solana wallet whose ' +
'Base58 address starts with your chosen prefix and/or ends with your chosen ' +
- 'suffix. Returns the public address and its secret key (Base58 + 64-byte array) ' +
- 'so you can import it into any Solana wallet. The key is ground fresh per ' +
- 'request in a Rust/WASM ed25519 engine and never stored. Price scales with ' +
- 'pattern difficulty ($0.01–$0.25); combined pattern capped at 3 Base58 ' +
- 'characters. Pay-per-call in USDC on Base or Solana mainnet — no API keys.';
+ 'suffix. Two output formats: format=keypair (default) returns the public ' +
+ 'address and its secret key (Base58 + 64-byte array), ground in a Rust/WASM ' +
+ 'ed25519 engine — capped at 3 Base58 chars, priced $0.01–$0.25. format=mnemonic ' +
+ 'returns a BIP-39 seed phrase (12 or 24 words) whose derived key at ' +
+ "m/44'/501'/0'/0' lands on the vanity address, importable as a recovery phrase " +
+ 'into Phantom / Solflare / the Solana CLI — capped at 2 chars (~100× slower to ' +
+ 'grind), priced $0.05–$0.50. Nothing is ever stored; the secret exists only in ' +
+ 'the response, served once over TLS. Optional sealTo=<X25519 public key> seals the ' +
+ 'secret to you (ECIES) so the plaintext never appears in the response or any log — ' +
+ 'open it client-side with the matching private key. Pay-per-call in USDC on Base or ' +
+ 'Solana mainnet — no API keys, no accounts.';
// Base58 excludes 0/O/I/l. Note also that an address is 32 random bytes
// Base58-encoded, so its LEADING characters are not uniformly distributed —
@@ -117,6 +154,26 @@ const DISCOVERY_INPUT_SCHEMA = {
description:
'When 1/true, match the pattern case-insensitively (faster, less specific).',
},
+ format: {
+ type: 'string',
+ enum: ['keypair', 'mnemonic'],
+ description:
+ 'keypair (default): return a raw 64-byte Ed25519 secret key, up to 3 chars. ' +
+ 'mnemonic: return a BIP-39 seed phrase importable into any wallet, up to 2 chars.',
+ },
+ strength: {
+ type: 'string',
+ enum: ['128', '256'],
+ description:
+ 'Mnemonic mode only. 128 → 12 words (default), 256 → 24 words. Ignored for keypair format.',
+ },
+ sealTo: {
+ type: 'string',
+ description:
+ 'Optional. Your 32-byte X25519 public key (Base58, Base64url, or hex). When set, ' +
+ 'the secret is sealed to it (x25519-hkdf-sha256-aes256gcm) and the plaintext secret ' +
+ 'is omitted from the response — open it client-side with the matching private key.',
+ },
},
};
@@ -129,12 +186,16 @@ const DISCOVERY_OUTPUT_EXAMPLE = {
prefix: 'So',
suffix: null,
ignoreCase: false,
+ format: 'keypair',
secretKeyBase58: '<example-only — the live endpoint returns the ground secret key here>',
secretKey: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
],
+ mnemonic: null,
+ wordCount: null,
+ derivationPath: null,
attempts: 160000,
durationMs: 6030,
expectedAttempts: 3364,
@@ -151,10 +212,12 @@ const DISCOVERY_OUTPUT_SCHEMA = {
prefix: { type: ['string', 'null'] },
suffix: { type: ['string', 'null'] },
ignoreCase: { type: 'boolean' },
+ format: { type: 'string', enum: ['keypair', 'mnemonic'] },
secretKeyBase58: {
type: 'string',
description:
- 'Base58-encoded 64-byte Ed25519 secret key (import into Phantom/Solflare).',
+ 'Base58-encoded 64-byte Ed25519 secret key (import into Phantom/Solflare). ' +
+ 'Present in both formats — in mnemonic mode it is the key derived from the phrase.',
},
secretKey: {
type: 'array',
@@ -163,6 +226,34 @@ const DISCOVERY_OUTPUT_SCHEMA = {
maxItems: 64,
description: '64-byte secret key as an int array — save as a Solana CLI keypair JSON.',
},
+ mnemonic: {
+ type: ['string', 'null'],
+ description:
+ 'mnemonic format only: BIP-39 seed phrase (12/24 words). Type it into any wallet ' +
+ 'to recover this address. null in keypair format.',
+ },
+ wordCount: { type: ['integer', 'null'], description: 'mnemonic format only: 12 or 24.' },
+ derivationPath: {
+ type: ['string', 'null'],
+ description: "mnemonic format only: BIP-44 path, e.g. m/44'/501'/0'/0'.",
+ },
+ sealed: {
+ type: 'boolean',
+ description:
+ 'Present and true only when sealTo was supplied. The plaintext secret fields ' +
+ '(secretKeyBase58/secretKey/mnemonic) are then omitted in favor of sealedSecret.',
+ },
+ sealedSecret: {
+ type: 'object',
+ description:
+ 'sealTo only: ECIES envelope { scheme, epk, nonce, ciphertext, recipient }. Open it ' +
+ 'with the X25519 private key matching sealTo to recover a JSON bundle of the secret.',
+ },
+ sealedFields: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'sealTo only: the field names contained in the decrypted JSON bundle.',
+ },
attempts: { type: 'integer', description: 'Keypairs tried before the match.' },
durationMs: { type: 'number' },
expectedAttempts: {
@@ -227,6 +318,25 @@ function parsePattern(req) {
const suffix = typeof q.suffix === 'string' ? q.suffix.trim() : '';
const ignoreCase = q.ignoreCase === '1' || q.ignoreCase === 'true';
+ const format = typeof q.format === 'string' ? q.format.trim().toLowerCase() : FORMAT_KEYPAIR;
+ if (!FORMATS.has(format)) {
+ throw Object.assign(new Error(`invalid format '${format}' — use keypair or mnemonic`), {
+ status: 400,
+ code: 'validation_error',
+ });
+ }
+
+ let strength = DEFAULT_STRENGTH;
+ if (q.strength != null && q.strength !== '') {
+ strength = Number(q.strength);
+ if (!STRENGTH_WORD_COUNTS[strength]) {
+ throw Object.assign(
+ new Error(`invalid strength '${q.strength}' — use 128 (12 words) or 256 (24 words)`),
+ { status: 400, code: 'validation_error' },
+ );
+ }
+ }
+
for (const [label, pattern] of [
['prefix', prefix],
['suffix', suffix],
@@ -240,41 +350,125 @@ function parsePattern(req) {
});
}
}
+
+ const maxLength = format === FORMAT_MNEMONIC ? MAX_MNEMONIC_PATTERN_LENGTH : MAX_SERVER_PATTERN_LENGTH;
const combinedLength = prefix.length + suffix.length;
- if (combinedLength > MAX_SERVER_PATTERN_LENGTH) {
+ if (combinedLength > maxLength) {
+ const reason =
+ format === FORMAT_MNEMONIC
+ ? `seed-phrase grinding is ~100× slower; drop format=mnemonic for up to ${MAX_SERVER_PATTERN_LENGTH} chars, ` +
+ `or grind longer mnemonic patterns on your own machine`
+ : 'grind longer patterns in the browser at /vanity';
throw Object.assign(
new Error(
- `combined pattern length ${combinedLength} exceeds the server limit of ` +
- `${MAX_SERVER_PATTERN_LENGTH} characters — grind longer patterns in the browser at /vanity`,
+ `combined pattern length ${combinedLength} exceeds the ${format} server limit of ` +
+ `${maxLength} characters — ${reason}`,
),
{ status: 400, code: 'pattern_too_long' },
);
}
- return { prefix, suffix, ignoreCase, combinedLength };
+
+ // Optional confidential delivery: an X25519 public key the secret is sealed
+ // to. Validate the key shape up front so a malformed key is a clean 400
+ // before the buyer ever pays. parseX25519Key throws status/code on bad input.
+ let sealTo = null;
+ if (typeof q.sealTo === 'string' && q.sealTo.trim()) {
+ sealTo = q.sealTo.trim();
+ parseX25519Key(sealTo, 'sealTo');
+ }
+
+ return { prefix, suffix, ignoreCase, combinedLength, format, strength, sealTo };
}
-function grindAndShape({ prefix, suffix, ignoreCase }) {
- const result = grindVanityNode({
- prefix,
- suffix,
- ignoreCase,
- timeBudgetMs: GRIND_TIME_BUDGET_MS,
- });
+// Confidential delivery: when the caller supplies an X25519 public key, encrypt
+// the secret material to it (ECIES sealed envelope) so the plaintext secret
+// never appears in the response body, a proxy log, or the idempotency cache.
+// The address + grind metadata stay in the clear; only the secret is sealed.
+async function sealSecret(result, sealTo) {
+ const bundle =
+ result.format === FORMAT_MNEMONIC
+ ? {
+ format: FORMAT_MNEMONIC,
+ mnemonic: result.mnemonic,
+ wordCount: result.wordCount,
+ derivationPath: result.derivationPath,
+ secretKeyBase58: result.secretKeyBase58,
+ secretKey: result.secretKey,
+ }
+ : {
+ format: FORMAT_KEYPAIR,
+ secretKeyBase58: result.secretKeyBase58,
+ secretKey: result.secretKey,
+ };
+ const sealedSecret = await sealToRecipient(JSON.stringify(bundle), sealTo);
+ // Strip every plaintext secret field; keep public metadata.
+ const { secretKeyBase58, secretKey, mnemonic, ...clear } = result;
return {
- address: result.publicKey,
- prefix: prefix || null,
- suffix: suffix || null,
- ignoreCase,
- secretKeyBase58: bs58.encode(result.secretKey),
- secretKey: Array.from(result.secretKey),
- attempts: result.attempts,
- durationMs: Math.round(result.durationMs),
- expectedAttempts: expectedAttemptsFor(prefix, suffix),
- network: 'solana',
- explorerUrl: `https://solscan.io/account/${result.publicKey}`,
+ ...clear,
+ sealed: true,
+ sealedScheme: SEALED_ENVELOPE_SCHEME,
+ sealedContentType: 'application/json',
+ sealedFields: Object.keys(bundle),
+ sealedSecret,
};
}
+async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, sealTo }) {
+ let shaped;
+ if (format === FORMAT_MNEMONIC) {
+ const result = grindVanityMnemonic({
+ prefix,
+ suffix,
+ ignoreCase,
+ strength,
+ timeBudgetMs: GRIND_TIME_BUDGET_MS,
+ });
+ shaped = {
+ address: result.publicKey,
+ prefix: prefix || null,
+ suffix: suffix || null,
+ ignoreCase,
+ format: FORMAT_MNEMONIC,
+ secretKeyBase58: bs58.encode(result.secretKey),
+ secretKey: Array.from(result.secretKey),
+ mnemonic: result.mnemonic,
+ wordCount: result.wordCount,
+ derivationPath: result.derivationPath,
+ attempts: result.attempts,
+ durationMs: Math.round(result.durationMs),
+ expectedAttempts: Math.round(expectedMnemonicAttempts(prefix, suffix, ignoreCase)),
+ network: 'solana',
+ explorerUrl: `https://solscan.io/account/${result.publicKey}`,
+ };
+ } else {
+ const result = grindVanityNode({
+ prefix,
+ suffix,
+ ignoreCase,
+ timeBudgetMs: GRIND_TIME_BUDGET_MS,
+ });
+ shaped = {
+ address: result.publicKey,
+ prefix: prefix || null,
+ suffix: suffix || null,
+ ignoreCase,
+ format: FORMAT_KEYPAIR,
+ secretKeyBase58: bs58.encode(result.secretKey),
+ secretKey: Array.from(result.secretKey),
+ mnemonic: null,
+ wordCount: null,
+ derivationPath: null,
+ attempts: result.attempts,
+ durationMs: Math.round(result.durationMs),
+ expectedAttempts: expectedAttemptsFor(prefix, suffix),
+ network: 'solana',
+ explorerUrl: `https://solscan.io/account/${result.publicKey}`,
+ };
+ }
+
+ return sealTo ? sealSecret(shaped, sealTo) : shaped;
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (req.method !== 'GET') {
@@ -297,11 +491,11 @@ export default wrap(async (req, res) => {
}
const resourceUrl = resolveResourceUrl(req, ROUTE);
- const priceAtomics = priceAtomicsFor(pattern.combinedLength);
+ const priceAtomics = priceAtomicsFor(pattern.format, pattern.combinedLength);
const requirements = buildRequirements(resourceUrl, priceAtomics);
const service = withService({
serviceName: 'three.ws Solana Vanity Grinder',
- tags: ['solana', 'vanity', 'keypair', 'wallet', 'address'],
+ tags: ['solana', 'vanity', 'keypair', 'wallet', 'address', 'mnemonic', 'seed-phrase', 'bip39'],
});
const challenge = {
resourceUrl,
@@ -331,7 +525,7 @@ export default wrap(async (req, res) => {
if (acResult?.grantAccess) {
let result;
try {
- result = grindAndShape(pattern);
+ result = await grindAndShape(pattern);
} catch (err) {
return error(res, err.status || 500, err.code || 'internal_error', err.message);
}
@@ -382,9 +576,11 @@ export default wrap(async (req, res) => {
// Grind AFTER verify but BEFORE settle: an invalid pattern or exhausted
// budget throws here, and settlement never runs, so the buyer isn't charged.
+ // grindAndShape is async (it may seal the secret to the buyer's key), so it
+ // must be awaited — otherwise the body serializes an unresolved Promise.
let result;
try {
- result = grindAndShape(pattern);
+ result = await grindAndShape(pattern);
} catch (err) {
return error(res, err.status || 500, err.code || 'grind_failed', err.message);
}
diff --git a/data/changelog.json b/data/changelog.json
index 80af4cfe7..bfb9a143a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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-19",
+ "title": "Pay-per-call vanity wallets now do seed phrases and encrypted delivery",
+ "summary": "The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away.",
+ "tags": [
+ "feature",
+ "security"
+ ],
+ "link": "/vanity-wallet"
+ },
+ {
+ "date": "2026-06-19",
+ "title": "Freeze your agent wallet in one tap — plus hardened custody security",
+ "summary": "Your agent's wallet now has a freeze switch. Open the wallet's Limits & Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too.",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-06-19",
"title": "Vanity wallets for every agent — opt-in, owned per user",
diff --git a/docs/internal/AGENT-WALLET-CUSTODY.md b/docs/internal/AGENT-WALLET-CUSTODY.md
index a23eeb2f9..36fa1a00c 100644
--- a/docs/internal/AGENT-WALLET-CUSTODY.md
+++ b/docs/internal/AGENT-WALLET-CUSTODY.md
@@ -44,7 +44,22 @@ the platform to be able to sign. The controls below make that trustworthy.
The audit `git grep` that gates this (see "Verifying" below) must stay clean.
The only endpoint that returns a raw secret key is `api/x402/vanity.js`, which
returns the **user's own freshly-ground** keypair at provisioning time — that is
-not a custodial agent secret and is by design.
+not a custodial agent secret and is by design. That endpoint never persists the
+secret (`cache-control: no-store`, no DB write, no log line); it exists only in
+the response body for one TLS-protected delivery. It offers two delivery
+hardening options for buyers who don't want the plaintext to touch the wire:
+
+- `format=mnemonic` returns a BIP-39 seed phrase instead of a raw key — the
+ recoverable form for consumer wallets — derived at `m/44'/501'/0'/0'`.
+- `sealTo=<X25519 public key>` seals the secret to a key the buyer controls via
+ an ECIES envelope (`x25519-hkdf-sha256-aes256gcm`, see
+ `src/solana/vanity/sealed-envelope.js`). When set, the plaintext secret is
+ **omitted** from the response entirely — only `sealedSecret` is returned, so
+ the cleartext never appears in the body, a proxy log, or the idempotency
+ cache. The buyer opens it client-side with `openSealed` and the matching
+ private key. The ephemeral server-side secret is discarded immediately, so the
+ envelope is forward-secret with respect to the platform. This is the only
+ custody-relevant secret path that can be made zero-plaintext end-to-end.
## Decryption is gated + audited
@@ -193,5 +208,70 @@ Run as a one-shot, reversible migration with **both** secrets available:
must show only at-rest storage, the internal recover/generate helpers, and
validation-message strings — never a value in a response, log, or error.
- **Tests:** withdraw (SOL + SPL, Max rent/fee reserve, idempotency), spend-limit
- enforcement (per-tx, daily, allowlist), and address validation are covered in
- `tests/agent-custody-guards.test.js` and `tests/agent-wallet-withdraw.test.js`.
+ enforcement (per-tx, daily, allowlist, **freeze**), and address validation are
+ covered in `tests/agent-custody-guards.test.js` and
+ `tests/agent-wallet-withdraw.test.js`. CSRF gates on the fund-moving endpoints
+ are covered in `tests/api/security-csrf-gates.test.js`.
+
+---
+
+## Security hardening pass — 2026-06-19
+
+This supersedes parts of the description above; the older sections describe the
+original v1 scheme for historical context.
+
+**The secret box is now one module.** All at-rest encryption lives in
+`api/_lib/secret-box.js` (`encryptSecret` / `decryptSecret` / `isEncryptedSecret`),
+imported by `agent-wallet.js`, the coin treasury, and the coin launcher. There is
+a single implementation — no per-call-site crypto.
+
+- **v2 scheme (current):** AES-256-GCM with a key derived (HKDF-SHA256) from a
+ **dedicated `WALLET_ENCRYPTION_KEY`**, decoupled from `JWT_SECRET`, with a
+ **random per-record salt** and a `v2:` version prefix. New writes are always v2.
+- **Legacy read:** v1 ciphertext (no prefix; `JWT_SECRET` + constant salt) still
+ decrypts via the fallback branch so existing rows keep working.
+- **Fixed regression:** imported / regenerated Solana wallets in
+ `api/agents/solana-wallet.js` used to write the weaker v1 ciphertext directly.
+ They now go through the shared `encryptSecret` (v2) like generated wallets.
+
+**Coin creator keys are encrypted at rest.** `coin.metadata.creator_secret_b64`
+was previously stored as plaintext base64 — a DB read yielded a usable signing
+key. The launcher (`scripts/coin-cli.mjs`) now encrypts it with the same secret
+box; the treasury loader (`loadCoinCreatorFromCoin`, now async) decrypts `v2:`
+blobs and reads legacy plaintext with a loud deprecation warning.
+
+**CSRF on every custodial money path.** `requireCsrf` now gates withdraw, both
+trade endpoints, and x402-pay (settle path; preview/quote stay exempt to avoid
+burning single-use tokens). Bearer/API-key callers remain exempt — the token is
+itself proof of intent. Frontend mutating clients send `x-csrf-token` via
+`consumeCsrfToken()`.
+
+**Wallet freeze (kill switch).** `meta.spend_limits.frozen` is enforced in the
+shared spend policy (`enforceSpendLimit` + `reserveSpendUsd`), so a single flag
+pauses **every autonomous path** (trade, snipe, x402) uniformly. The owner's own
+**withdraw is deliberately never blocked** — a freeze locks down a misbehaving
+agent without trapping its funds. Toggle: owner-only, one tap, under the wallet
+hub's *Limits & Safety*.
+
+### Remaining follow-ups (prioritized)
+
+1. **KMS / HSM envelope encryption.** Generate a per-record data key, encrypt the
+ wallet secret with it, and wrap the data key with a managed KMS key (AWS KMS
+ `GenerateDataKey`, GCP Cloud KMS, or Vault transit). Decryption then requires
+ an online, auditable, revocable KMS call — a raw DB dump no longer yields
+ plaintext, and master-key rotation becomes a KMS operation instead of a
+ re-encrypt-every-row migration. **This is the highest-value remaining item:**
+ today a single `WALLET_ENCRYPTION_KEY` leak still decrypts every wallet.
+2. **Automated rotation / re-encrypt sweep.** Add `scripts/reencrypt-agent-wallets.mjs`
+ that decrypts each record and rewrites it as v2 under a new key — the same
+ keypair/address, so no funds move. Then a forced `WALLET_ENCRYPTION_KEY`
+ rotation becomes a one-command operation, and v1 records can finally be retired.
+3. **Bind `agent_id` as AES-GCM `additionalData` (AAD).** Today a ciphertext is
+ not bound to its agent, so a DB-write attacker could swap one agent's encrypted
+ key into another. AAD = `utf8(agentId)` on encrypt + decrypt makes a swapped
+ ciphertext fail to decrypt. Requires a re-encrypt pass (item 2) to apply to
+ existing rows.
+4. **Drop the `JWT_SECRET` legacy read** once item 2 has migrated every record to
+ v2, and fail closed in production when `WALLET_ENCRYPTION_KEY` is unset (today
+ it warns and falls back). This finally decouples session-secret rotation from
+ custody entirely.
diff --git a/docs/ux-flows/01-onboarding-creation.md b/docs/ux-flows/01-onboarding-creation.md
new file mode 100644
index 000000000..e33574fae
--- /dev/null
+++ b/docs/ux-flows/01-onboarding-creation.md
@@ -0,0 +1,199 @@
+# Onboarding & Agent Creation
+
+> UX Flow Atlas — Cluster 01. Traced from real source. Route → source mapping resolved via `vercel.json` `routes[]` (Vite serves `pages/*.html` directly in dev; prod rewrites the clean route to the same HTML file).
+
+---
+
+### Onboarding Wizard — `/start`
+- **Source:** `pages/start.html` + `src/start.js` (imports `src/shared/usd-price.js`, `src/templates.js`, `src/shared/log.js`)
+- **Entry point:** Marketing/nav CTAs and `getting-started.js` discovery layer. Returned-to as a round-trip target from `/create/selfie` and `/create` (those flows pass `?wizard=1&next=<return to /start?from=...>`). Also accepts deep-links `/start?template=<id>` and resumes via `sessionStorage` key `wz:state`.
+- **Prerequisites / gates:** None to start (anonymous-friendly). Auth is hit lazily at deploy: every `apiPost` first fetches `/api/csrf-token` (`credentials: include`) — an unauthenticated user fails at Step 4 (deploy) with a server error toast. No wallet connect, no $THREE gate.
+- **Steps (N):**
+ 1. Land on `/start`; the **template gallery** screen renders (`initTemplateGallery`). If `?template=<id>` matches, it auto-applies and jumps to Step 2 (skips gallery). If a saved `wz:state` exists, gallery is bypassed and the wizard resumes.
+ 2. (optional) Click a template card → `applyTemplate` prefills description/skills/model/cryptoMode and advances to wizard Step 2; OR click "Start from scratch" (`#btn-blank-start`) → reveals blank wizard at Step 1.
+ 3. **Wizard Step 1 — Avatar.** Choose an avatar method: "Selfie" (`#btn-selfie`) → navigates to `/create/selfie?wizard=1&next=<return>`; "Editor" (`#btn-editor`) → `/create?wizard=1&next=<return>`; "Upload" (`#btn-upload`) → opens file picker.
+ 4. (optional) For Upload: select a `.glb`/`.gltf` ≤ 50 MB → POST `/api/avatars` (multipart, with CSRF) → on success the avatar thumbnail/name render in the Step-1 preview.
+ 5. (optional) Click "Skip" (`#btn-skip-step`) on Step 1 to advance avatar-less to Step 2.
+ 6. **Step 2 — Name & Brain.** Type agent name (required) and bio/description; optionally click a personality preset (researcher/support/podcast/artist/assistant/crypto/community/defi) to fill the bio; pick a model (`data-model`). Click "Continue" → `validateStep` requires a non-empty name (else toast "Please give your agent a name.").
+ 7. (optional) Toggle **Crypto mode** (`#crypto-toggle`) to reveal crypto personality + crypto skills sections.
+ 8. **Step 3 — Skills.** Toggle skill cards (`data-skill`: memory/think/pumpfun/solana/x402/web). Click "Continue to deploy".
+ 9. **Step 4 — Deploy.** `startDeploy()` runs automatically: (a) POST `/api/agents` (name, description, resolved skills via `SKILL_MAP` + `BASE_SKILLS`, optional `avatar_id`); (b) POST `/api/widgets` (type `talking-agent`, config.agent_id); (c) builds embed `<script>` snippet + live URL `/agent/<id>`. Shows live status labels per phase.
+ 10. On deploy success: success panel shows "<name> is live", live URL link, and an embed code block. (optional) Click "Copy" (`#copy-embed`) to copy the embed snippet. Click "Continue".
+ 11. **Step 5 — Earn (conditional).** If crypto skills were selected: enter a per-call price (USDC, shown as USD-equivalent hint) and a payout wallet (chain auto-detected SOL vs ETH/BASE). Click "Save & finish" → `saveEarnSettings()` POSTs `/api/agents/:id/skills/set-price` (USDC mint) and `/api/billing/payout-wallets`, then clears state and redirects to `/dashboard?welcome=1`. If no crypto skills: a "skip" panel shows and the button reads "Go to dashboard" → straight to `/dashboard?welcome=1`.
+- **Decision points / branches:** template vs blank start; resume saved session vs fresh; avatar method (selfie / editor / upload / skip); crypto-mode on/off → governs whether Step 5 is the Earn panel (price+wallet) or the Skip panel; deploy success vs failure (retry button injected).
+- **External calls / dependencies:** `GET /api/csrf-token`; `POST /api/avatars` (upload); `POST /api/agents`; `POST /api/widgets`; `POST /api/agents/:id/skills/set-price`; `POST /api/billing/payout-wallets`. No on-chain txn from this page (wallet address is just registered as a payout target).
+- **Success state:** A real deployed agent + public widget, an embeddable `<script>` snippet, a live `/agent/<id>` URL, optional monetization configured; user lands on `/dashboard?welcome=1`.
+- **Empty / error states:** Toast (`#wz-toast`) for validation ("Please give your agent a name.", file-too-large). Deploy failure recolors the status label red and injects a "Try again" button that re-runs `startDeploy()`. Upload errors restore the card label.
+- **Step count:** 6 required (gallery → name → skills → deploy auto → deploy success → finish) + ~5 optional (template apply, avatar upload, skip avatar, crypto toggle, earn setup).
+
+---
+
+### Avatar Method Picker — `/create`
+- **Source:** `pages/create.html` + `src/create.js` (imports `src/account.js`, `src/avatar-creator.js`, `src/guest-avatar.js`, `src/shared/template-picker.js`, `src/shared/crypto-optional.js`, `src/wallet-auth.js` inline)
+- **Entry point:** Nav/landing CTA; reached from `/start` Step 1 "Editor" with `?wizard=1&next=`. Also handles `?fork=<avatarId>` deep-links (remix an existing avatar).
+- **Prerequisites / gates:** Anonymous-friendly for the default editor / customize / studio / direct GLB upload (guest avatar staged in IndexedDB; auth deferred to `/create-review`). **Auth-gated paths:** Selfie card (`requireAuthForSelfie` → redirect `/login?next=/create/selfie`) and Prompt card (redirect `/login?next=/create/prompt`). Signed-in users also hit an avatar-quota check (`/api/usage/summary`) before opening a creator. No wallet/$THREE gate.
+- **Steps (N):**
+ 1. Land on `/create`. `boot()` probes `/api/config` for the `videoAvatar` feature flag (greys out the video card if off) and, for signed-in users with avatars, loads `/api/avatars` to render a "Start from one of yours" remix strip.
+ 2. (optional) If `?fork=<id>` present: `handleFork` runs immediately — POST `/api/avatars/fork` (signed-in → owned copy → redirect `/avatars/<id>`); on 401/403 falls back to fetching the source, downloading its GLB, staging a guest copy, and redirecting to `/create-review`.
+ 3. Choose a creation method card: **Default editor** (`AvatarCreator.openDefaultEditor`), **Customize** (`createFromTemplate`), **Agent Studio** (→ `/create/studio`), **Selfie** (→ `/create/selfie`, auth-gated), **Prompt** (→ `/create/prompt`, auth-gated), **Talking avatar video** (→ `/create/video`, feature-flagged + auth-gated), or **Upload GLB** (`#glb-input`).
+ 4. (optional) Upload path: pick a `.glb`; `handleGlbFile` validates the GLB magic bytes, then `stageAndReview` stashes the blob via `guest-avatar.js` (IndexedDB) and navigates to `/create-review`.
+ 5. (optional) Editor/Customize path: the in-page `AvatarCreator` produces a GLB blob → `stageAndReview` → `/create-review`.
+ 6. (optional) Remix strip: click a saved avatar thumbnail → `handleFork(av.id)` (same fork path as step 2).
+- **Decision points / branches:** fork vs fresh; six creation methods (editor / customize / studio / selfie / prompt / video / upload); anonymous (stage→review) vs signed-in (direct save/fork); video flag on/off; avatar-quota reached vs not.
+- **External calls / dependencies:** `GET /api/config`; `GET /api/avatars`; `GET /api/usage/summary`; `POST /api/avatars/fork`; `GET /api/avatars/:id` + raw GLB fetch (guest fork). Avaturn / Ready Player Me iframes loaded by `AvatarCreator`.
+- **Success state:** A staged or owned avatar; the user is forwarded to `/create-review` (anonymous) or `/avatars/<id>` (forked) — onward to agent creation.
+- **Empty / error states:** `status-toast` for invalid GLB, fork failure, quota-limit; video card shows "coming soon" when flag off; save overlay (`#save-loading`) covers staging. Remix strip stays hidden for anonymous users / users with no avatars.
+- **Step count:** 2 required (land → pick a method) + ~4 optional (fork, upload, editor produce, remix).
+
+---
+
+### Agent Creation Wizard — `/create-agent`
+- **Source:** `pages/create-agent.html` + `src/create-agent.js` (imports `src/api.js`, `src/account.js`, `src/shared/log.js`, `src/shared/glb-magic.js`)
+- **Entry point:** Nav/landing CTA, marketplace "create your own" links.
+- **Prerequisites / gates:** **Auth required.** `boot()` calls `getMe()`; if no user, the form is hidden and an auth gate (`#auth-gate` → `/login?next=/create-agent`) is shown. Each agent gets a wallet, so the whole flow is account-gated. No $THREE gate.
+- **Steps (N):**
+ 1. Land; `boot()` resolves auth. Signed-out → auth gate (stop). Signed-in → Step 0 (Basics) shown.
+ 2. **Step 0 — Basics.** Enter name (required, ≤60), description (≤280), and tags (≤8, Enter/comma to add). Click "Next" → validates name present.
+ 3. **Step 1 — Model.** Choose a body via one of four tabs: **Starter** (4 shipped GLBs: Vern/CZ/Saga/Boss with `model-viewer` previews), **Library** (your owned avatars, paginated via `GET /api/avatars`, filtered to avatar/creature categories), **Upload** (drag-drop `.glb` ≤16 MB, validated by GLB magic), or **Add later** (must tick the `#f-skip-ack` confirm box → default starter assigned at create). Selected model renders in the live preview. Click "Next" → requires a starter/upload/library pick or acknowledged skip.
+ 4. **Step 2 — Skills.** Five core skills (greet/present-model/validate-model/remember/think) are locked on; toggle optional skills (wave/dance/pump-fun/explain-gltf/web-search). Click "Next".
+ 5. **Step 3 — Personality.** Pick category (14 marketplace categories), greeting (≤200), profile/system prompt (≤2000), voice (browser/custom). Click "Next" (soft tip if publishing without category+prompt).
+ 6. **Step 4 — Review.** Editable summary grid (each row jumps back to its step). Toggle "Publish to marketplace" (`#f-publish`). Click "Create".
+ 7. `submit()`: (a) resolves the body to a real owned avatar — `saveRemoteGlbToAccount` for starter URL or uploaded file (with upload % progress), library = connect directly, none = assign default starter; (b) POST `/api/agents` (name, description, skills, avatar_id, meta with greeting/voice/tags); (c) if publish opted-in AND category+prompt present → POST `/api/marketplace/agents/:id/publish`.
+ 8. Success panel: "<name> is ready", 3D preview if public, and buttons — Open (`/agent/<id>`), Edit (`/agent/<id>/edit`), Fund wallet (`/agent/<id>/wallet#deposit`).
+- **Decision points / branches:** auth gate vs proceed; model tab (starter/library/upload/skip); publish on/off and whether publish prerequisites are met (publishes vs creates private with a soft warning); name conflict (409 → bounce to Step 0 to rename); per-step jump-back via stepper pips and review "Edit" buttons.
+- **External calls / dependencies:** `getMe()` (account.js); `GET /api/avatars` (library tab); `saveRemoteGlbToAccount` (account.js → presign + R2 upload + commit); `POST /api/agents`; `POST /api/marketplace/agents/:id/publish`.
+- **Success state:** A real agent with its own wallet/on-chain identity, a guaranteed 3D body, optionally listed on the marketplace; success card links to view/edit/fund.
+- **Empty / error states:** Auth gate for signed-out; library tab has loading / error (with "Try again") / empty (no character models) states; per-step inline validation via `#foot-msg`; 409 name conflict bounces back; publish failure is non-fatal (soft warning, agent still created); submit failure re-enables the form with an error message.
+- **Step count:** 6 required (Basics → Model → Skills → Personality → Review → Create) + ~2 optional (tags, optional skills/customizing voice).
+
+---
+
+### Prompt → Avatar — `/create/prompt` (create-prompt)
+- **Source:** `pages/create-prompt.html` + `src/create-prompt.js` (imports `src/shared/log.js`)
+- **Entry point:** The "Prompt" card on `/create` (`/create` redirects signed-out users to `/login?next=/create/prompt`). Also reachable directly.
+- **Prerequisites / gates:** **Auth required** — the submit endpoint returns 401 → page redirects to `/login?next=/create/prompt` (also enforced upstream by `/create`). No wallet/$THREE gate.
+- **Steps (N):**
+ 1. Land on the **compose** step; type a text prompt (3–600 chars; live counter). (optional) Click an example chip to fill the prompt.
+ 2. Click "Generate" (or Cmd/Ctrl+Enter). `start()` → switches to the **building** step, starts the elapsed clock, sets progress to 8%.
+ 3. POST `/api/avatars/reconstruct` `{ name (derived from prompt), prompt, visibility: 'private' }`. Server renders a reference image (Flux) then runs reconstruct→auto-rig. Returns `{ jobId }`.
+ 4. `pollUntilDone(jobId)` polls `GET /api/avatars/regenerate-status?jobId=...` every 3s (8-min timeout), advancing the progress bar by phase (queued→running→rigging).
+ 5. On `{ status: 'done', resultAvatarId }`: `renderDone` fetches `GET /api/avatars/:id`, sets the `model-viewer` src, and tags it (Animation-ready / static, Private). Shows the **done** step with "Open in editor" (`/avatars/<id>/edit`) and "Make another"; dispatches `tws:feature-done` for the cross-feature discovery layer. If the finished avatar has no model URL yet, it redirects straight to the editor.
+- **Decision points / branches:** compose vs building vs done; success vs failure (`mapSubmitError`/`friendlyJobError` map codes to human messages — rate-limited, unconfigured→suggest selfie, no-face, NSFW, timeout, OOM); 401 mid-flow → login redirect; "Make another" resets to compose.
+- **External calls / dependencies:** `POST /api/avatars/reconstruct`; `GET /api/avatars/regenerate-status`; `GET /api/avatars/:id`. Backend uses a text-to-image (Flux) + reconstruct/rig pipeline.
+- **Success state:** A private, riggable 3D avatar previewed in-page with an "Open in editor" path.
+- **Empty / error states:** Compose: inline `#compose-error` if prompt < 3 chars. Building: `#build-error` with a "Back" button to return to compose; friendly mapping of provider errors; 8-min timeout message suggesting the dashboard. Generate button disabled until prompt ≥ 3 chars.
+- **Step count:** 3 required (compose → generate/build → done) + 1 optional (example chip).
+
+---
+
+### Selfie → Avatar — `/create/selfie` (create-selfie)
+- **Source:** `pages/create-selfie.html` (inline `<script type="module">`) + `src/selfie-capture.js` + `src/selfie-pipeline.js` (pipeline imports `src/avatar-face-capture.js`, `src/shared/log.js`)
+- **Entry point:** The "Selfie" card on `/create` (auth-gated redirect there); `/start` Step 1 "Selfie" with `?wizard=1&next=`; and `/scan` + `/features/scan` redirect/link here. Reachable directly.
+- **Prerequisites / gates:** **Auth required** for platform-mode reconstruction (counts against plan quota; `/create` enforces `requireAuthForSelfie`; pipeline maps 401 → `/login?next=/create/selfie` and resumes the pending job after login). **BYOK mode** (`/api/config` → `features.avatarReconstructMode === 'byok'`): an API-key entry step (Meshy/Tripo) precedes capture; key is stored in `sessionStorage` only. No wallet/$THREE gate.
+- **Steps (N):**
+ 1. Land; inline boot fetches `/api/config` to pick platform vs BYOK mode and dynamically imports the capture UI + pipeline.
+ 2. (optional, BYOK only) **api-key step:** pick provider (Meshy/Tripo), paste key (>8 chars), submit → `storeByokKey` → advance to capture.
+ 3. **capture step:** capture or upload a **frontal** photo (required) via camera overlay (`selfie-capture.js`, with face-oval guidance) or file upload; optionally add **left/right** angle photos (fidelity boost).
+ 4. Click "Build my avatar" (`#submit-btn`) → dispatches `selfie:submit`. Pipeline downscales photos (≤1024px JPEG), runs a local MediaPipe face check, then dispatches `selfie:preview` (shows the user's own photo on a placeholder).
+ 5. POST `/api/avatars/reconstruct` `{ name, photos[], visibility: 'private', params:{bodyType,style}, optional provider_key/provider_name }` → `{ jobId }`. Stashes `selfie:pendingJobId` in sessionStorage (for resume across login). Dispatches `selfie:building` → shows the **building** step (and requests Notification permission).
+ 6. `pollUntilDone` polls `GET /api/avatars/regenerate-status?jobId=...` (1.5s first, then 3s w/ backoff, 8–10 min timeout), dispatching `selfie:progress` labels (mesh → geometry → rigging → finishing).
+ 7. On done: `selfie:done` fires; the page fetches `GET /api/avatars/:id`, renders the model in the **done** viewer, prefills the name. If the tab is hidden, flashes the title + fires an OS notification.
+ 8. **done step** actions: "Save" (`#done-save-btn`, optional PATCH name → `/avatars/<id>`), "List" (`#done-list-btn`, PATCH name + visibility public → `/marketplace/avatars/<id>`), "Open in editor" (`#done-editor-btn` → `/avatars/<id>/edit`), or "Make another" (`#done-regen-btn`, reset to capture).
+- **Decision points / branches:** platform vs BYOK mode (key step or not); camera vs upload; frontal-only vs +side angles; mid-flow 401 → login + job resume; done vs build-error (per-slot error highlighting, retry); resume-pending-job on reload.
+- **External calls / dependencies:** `GET /api/config`; `POST /api/avatars/reconstruct`; `GET /api/avatars/regenerate-status`; `GET /api/avatars/:id`; `PATCH /api/avatars/:id` (save/list). MediaPipe (client face detect); camera `getUserMedia`; optional Meshy/Tripo BYOK providers.
+- **Success state:** A private, rigged 3D avatar (reconstructed from the selfie), previewed in-page with save/list/edit paths.
+- **Empty / error states:** `selfie:needs-byok` → key-entry form ("No API key found"); local face-check failure highlights the offending slot with guidance; `selfie:build-error` recolors the building step, shows tips, and a "Try again" → capture; rate-limit cooldown with a live countdown; viewer load failure marks the preview `.failed`; 8-min timeout message.
+- **Step count:** 4 required (capture frontal → build → poll → done) + ~4 optional (BYOK key step, side angles, upload-vs-camera, save/list/edit/make-another).
+
+---
+
+### Agent Editor / New Agent — `/agent/new`
+- **Source:** `pages/agent-edit.html` + `src/agent-edit.js` (vercel route `/agent/new` → `/agent-edit.html`; imports `src/avatar-creator.js`, `src/account.js`, `src/api.js`, `src/avatar-gallery-picker.js`, `src/shared/agent-wallet-chip.js`, `src/shared/glb-magic.js`)
+- **Entry point:** "New agent" nav/dashboard buttons. Also the editor target for existing agents at `/agent/<uuid>(/edit)` and the create-from-avatar handoff `/agent/new?avatar_id=&avatar_glb=&avatar_name=` (marketplace "Start an agent with this avatar").
+- **Prerequisites / gates:** **Auth required.** `resolveAgentIdFromUrl()` finds no id for `/agent/new`, so `loadAgent()` calls `createDraftAgent()` which POSTs `/api/agents` immediately; a 401 stashes `login_redirect` and redirects to `/login`. Each agent provisions a wallet. No $THREE gate.
+- **Steps (N):**
+ 1. Navigate to `/agent/new`. With no id in the URL, `createDraftAgent()` shows a "Creating a new agent…" overlay and POSTs `/api/agents` `{ name: 'Untitled Agent' }` (or "<avatar> Agent" when arriving from an avatar handoff).
+ 2. (optional) If `?avatar_id` present, PUT `/api/agents/:id` to attach that avatar to the draft.
+ 3. The new agent id is adopted and the full editor renders (`render()`): identity (name/description), 3D body (starter/library picker/upload via `avatar-gallery-picker.js` + `AvatarCreator`), skills, animations, voice, wallet chip, and the embed/manifest panels.
+ 4. Edit any field → changes persist through the same verified endpoints (PUT `/api/agents/:id`, animations endpoint, etc.).
+- **Decision points / branches:** new draft vs existing agent (URL id) vs create-from-avatar handoff; signed-out → login; avatar attach vs leave default.
+- **External calls / dependencies:** `POST /api/agents` (draft); `GET /api/agents/:id`; `PUT /api/agents/:id`; `PUT /api/agents/:id/animations`; `GET /api/agents/:id/manifest`; avatar APIs via `saveRemoteGlbToAccount` / gallery picker.
+- **Success state:** A live draft agent (with wallet) loaded into the full editor for fine-grained configuration; URL becomes the canonical agent edit URL.
+- **Empty / error states:** Loading overlay during draft creation; `showError(...)` for load/create failures; 401 → login redirect with return.
+- **Step count:** 1 required (navigate → draft auto-created → editor) + 1 optional (avatar attach) — the editor itself is open-ended.
+
+---
+
+### Import Avatar (URL / Upload) — `/import/rpm` (import-rpm)
+- **Source:** `pages/import-rpm.html` (inline `<script type="module">`) + `src/account.js` (`saveRemoteGlbToAccount`)
+- **Entry point:** Direct link / docs / nav. "Import any GLB or glTF avatar … and give it an agent brain."
+- **Prerequisites / gates:** **Auth required at import time** — `saveRemoteGlbToAccount` presigns/commits against the user's account; a `not_signed_in`/401 redirects to `/login?return=<here>`. No wallet/$THREE gate. (The page itself loads anonymously.)
+- **Steps (N):**
+ 1. Land; two tabs — **Import from URL** and **Upload file**.
+ 2. URL tab: paste an `http(s)` GLB URL (validated), optionally a name → click "Import".
+ 3. (alt) File tab: drag-drop or pick a `.glb` ≤100 MB (validated by extension + size), optionally a name → click "Upload".
+ 4. `runImport(...)` → `saveRemoteGlbToAccount(source, { name, visibility:'public', tags:['rpm','imported'], source:'rpm_import', source_meta })` with progress callbacks (Fetching → Normalizing bones → Uploading → Saving), showing a live progress bar.
+ 5. On success: `showSuccess(avatar)` swaps in the success card with "<name> is ready" and a link to `/avatars/<id>`.
+- **Decision points / branches:** URL vs file upload; signed-out (401) → login round-trip; success vs error (friendly mapping by `err.code`/`err.stage`: fetch / presign / commit / upload_blocked / size_mismatch).
+- **External calls / dependencies:** `saveRemoteGlbToAccount` (account.js — presign + remote GLB fetch/normalize + R2 upload + commit). Source URL is fetched server-side.
+- **Success state:** An owned, public avatar in the user's library, linked at `/avatars/<id>` (ready to attach an agent brain).
+- **Empty / error states:** Per-tab `status-msg` (invalid file type, too large, invalid URL, fetch/upload failures); progress wrap during import; auth redirect on 401.
+- **Step count:** 2 required (choose source → import) + 1 optional (custom name).
+
+---
+
+### 3D Scanner (redirect) — `/scan`
+- **Source:** `pages/scan.html` (inline `<script type="module">`; dynamically imports `src/selfie-capture.js` + `src/selfie-pipeline.js`)
+- **Entry point:** `/features/scan` CTAs ("Start scanning →"), direct links, marketing.
+- **Prerequisites / gates:** N/A — **the page immediately redirects.** The first line of the inline module runs `window.location.replace('/create/selfie' + window.location.search)`, preserving `?next`/`?from` query params. The legacy scan capture/build/done code below the redirect is therefore **dead/unreachable** (superseded by `/create/selfie`, which adds BYOK key entry).
+- **Steps (N):**
+ 1. Land on `/scan` → instant `location.replace` to `/create/selfie` (query string carried over). User experiences the **`/create/selfie` flow** (see that entry) — there is no distinct `/scan` UX anymore.
+- **Decision points / branches:** None — unconditional redirect.
+- **External calls / dependencies:** None reached on `/scan` itself (redirect fires before any fetch). The vestigial code referenced `GET /api/avatars/:id` + the selfie pipeline endpoints, but they never run.
+- **Success state:** User arrives at `/create/selfie` (selfie pipeline success state applies there).
+- **Empty / error states:** None on this page (redirect-only).
+- **Step count:** 0 required on `/scan` itself (1 implicit redirect) — the real flow is `/create/selfie`.
+
+---
+
+### Scan Landing Page — `/features/scan`
+- **Source:** `pages/features/scan.html` (static marketing page; loads `/nav.js`, `/footer.js` — no inline flow logic)
+- **Entry point:** `/features` index, marketing nav.
+- **Prerequisites / gates:** None — public landing page.
+- **Steps (N):**
+ 1. Land on the feature landing page ("Your face in 3D. In 60 seconds.") — hero, explainer sections, a `model-viewer` demo.
+ 2. Click a primary CTA "Start scanning →" → navigates to `/scan` (which redirects to `/create/selfie`). Secondary CTAs link to `/features`, `/features/forge`.
+- **Decision points / branches:** CTA choice — start scanning (`/scan` → `/create/selfie`) vs "Try Forge instead" (`/features/forge`) vs "All features" (`/features`).
+- **External calls / dependencies:** None (static page; model-viewer loaded from CDN for the demo GLB `/animations/soldier.glb`).
+- **Success state:** User is routed into the selfie/scan creation flow.
+- **Empty / error states:** N/A — static content, no data fetching.
+- **Step count:** 1 required (land → click CTA). No optional steps.
+
+---
+
+### Voice Lab — `/voice`
+- **Source:** `pages/voice.html` + `src/voice-lab.js`
+- **Entry point:** Nav/feature links; used to mint a cloned voice that agents/avatars can speak with.
+- **Prerequisites / gates:** Microphone permission (`getUserMedia`). The clone endpoint is called with `credentials: 'include'` — auth/credit limits are enforced server-side (a failure surfaces as a "Clone failed" status). No wallet/$THREE gate. Cloned-voice library is stored in `localStorage` (`voicelab_voices_v1`).
+- **Steps (N):**
+ 1. Land; a reading script is shown (cycle with "Next script"). Voice library + playground voice dropdown render from `localStorage`.
+ 2. Click "Record" (`#btnRecord`) → `getUserMedia` (mono, 48kHz, with AGC/NS/EC), live waveform + level meter, max 60s (recommended 20–30s).
+ 3. Click "Stop" (`#btnStop`) → builds a recorded Blob; rejects clips < 3s; on success shows the **review** state with an audio preview.
+ 4. (optional) "Re-record" (`#btnRerecord`) to discard and try again.
+ 5. Enter a voice name (required) and click "Clone" (`#btnClone`) → POST `/api/tts/eleven-clone` (multipart audio + name).
+ 6. On success: stores `{ voiceId, name, status }` in `localStorage`, shows the **done** state ("<name> cloned successfully"), re-renders the library + playground voice list.
+ 7. (optional) "Try in playground" (`#btnTryPlayground`): pick a voice, type text, click "Speak" → POST `/api/tts/eleven` `{ voiceId, text }` to synthesize and play. "Play sample" on a library card does the same with a canned line. "Record another" loops back.
+- **Decision points / branches:** record vs re-record; clone success vs failure (mic denied, recording too short, network error, server HTTP error); playground speak vs library sample playback; delete voice from library.
+- **External calls / dependencies:** `POST /api/tts/eleven-clone` (clone); `POST /api/tts/eleven` (TTS playback/sample). ElevenLabs via the server proxy. Browser `getUserMedia` / `MediaRecorder` / Web Audio.
+- **Success state:** A cloned voice ID saved to the local library, immediately usable in the in-page TTS playground (and selectable elsewhere for agent speech).
+- **Empty / error states:** Library empty state ("No cloned voices yet"); status banner (`setStatus`) for mic-denied, recorder-init failure, too-short clip, network/HTTP clone errors, name-required; playground/sample buttons surface synth errors inline.
+- **Step count:** 4 required (record → stop → name → clone) + ~3 optional (cycle script, re-record, playground speak/sample).
+
+---
+
+## Notes on routing resolution
+- `/start`, `/create`, `/create-agent`, `/import/rpm`, `/scan`, `/features/scan`, `/voice` all resolve via explicit `vercel.json` `routes[]` rewrites to their `*.html` files.
+- `/create/prompt` → `create-prompt.html`, `/create/selfie` → `create-selfie.html`.
+- `/agent/new` → `agent-edit.html` (shared with the existing-agent editor at `/agent/<uuid>`).
+- `/scan` is a **redirect shell** to `/create/selfie`; its in-page flow code is dead.
+- `/features/scan` is a **static landing page** with no flow logic — its CTA bounces to `/scan` → `/create/selfie`.
diff --git a/docs/ux-flows/02-forge-text-to-3d.md b/docs/ux-flows/02-forge-text-to-3d.md
new file mode 100644
index 000000000..45a6c22f4
--- /dev/null
+++ b/docs/ux-flows/02-forge-text-to-3d.md
@@ -0,0 +1,163 @@
+# Text & Image to 3D (Forge)
+
+This atlas entry traces the "Text/Image-to-3D (Forge)" cluster end-to-end from real source. Routes are resolved through `vercel.json` rewrites (not the default `pages/<route>.html` convention in every case).
+
+Routing facts (from `vercel.json`):
+- `/forge` → `pages/forge.html` (loads `src/forge.js` + 12 sibling `forge-*` modules).
+- `/features/forge` → `pages/features/forge.html` (static marketing landing, no app module).
+- `/create/prompt` → `pages/create-prompt.html` → `src/create-prompt.js` (text → **rigged avatar**, a different backend from Forge).
+- `/tutorials/text-to-3d` and `/tutorials/image-to-3d` → `pages/tutorial.html` (one shared template) which `fetch`es `/docs/tutorials/<slug>.md` and renders it with marked.js. Read-only content pages.
+
+---
+
+### Forge (Text / Photos / Sketch → 3D) — `/forge`
+
+- **Source:**
+ - `pages/forge.html` (3177 lines — full composer/stage markup + styles)
+ - `src/forge.js` (2445 lines — main controller: catalog, engine/tier selection, job submit, polling, result, gating)
+ - `src/forge-prompt-studio.js` (Surprise-me + prompt coach), `src/forge-enhance.js` (AI prompt rewrite → `/api/forge-enhance`)
+ - `src/forge-dropzone.js` (paste/drop image handling), `src/forge-reveal.js` (WebGL "materialize" dissolve overlay)
+ - `src/forge-refine.js` (in-browser geometry refine, no API), `src/forge-stylize.js` (→ `/api/forge-stylize`), `src/forge-optimize.js` (→ `/api/forge-remesh`), `src/forge-gameready.js` (→ `/api/forge-gameready`)
+ - `src/forge-export.js` (in-browser OBJ/STL/PLY/USDZ export), `src/forge-embed-panel.js`, `src/forge-ar.js`, `src/forge-showcase.js` (community feed)
+ - `src/forge-pay.js` (pay-per-generation $THREE rail → `src/token-pay.js` → `/api/token/quote|settle`)
+- **Entry point:** Direct nav to `/forge`; CTAs from `/features/forge` ("Open Forge →"), the two tutorial pages, blog `text-to-3d-is-live`, gallery, and the `/forge` empty-state idle viewer. Also reachable as the "make an object/prop" alternative linked from `/create/prompt`.
+- **Prerequisites / gates:**
+ - **None for the default lane.** Draft/Standard tiers on the free NVIDIA-hosted engine require no auth, no wallet, no payment ("No account required for your first model").
+ - **BYOK engines** (Fast, Meshy, Tripo, Rodin, Stability, Replicate) require the user to paste their own provider API key (kept in-browser, sent as `x-forge-provider-key` header).
+ - **High quality tier** is gated: it is a `$THREE` holder perk (hold-OR-pay). A holder clears it with a tier pass (`attachTierPass`); a non-holder gets a `402 three_hold_required` and may **pay-per-generation in $THREE** via `forge-pay.js`, or hold $THREE. BYOK High is server-exempt (no pass needed).
+ - Rate limiting applies on the paid lane (server-side, surfaced as a recoverable `429` state).
+- **Steps (core text→3D path):**
+ 1. User lands on `/forge`; `forge.js` fetches the engine/tier catalog (`GET /api/forge?catalog=1`) and live backend health (`GET /api/forge?health=1`), then builds the tier buttons (Draft/Standard/High) and the per-mode engine selector. The empty stage (`#state-empty`) shows an idle community/sample model.
+ 2. Mode tab defaults to **Describe it** (text). Tabs: *Describe it*, *From photos*, *From a sketch* (the sketch tab stays `hidden` until the catalog reports a live TripoSG sketch engine).
+ 3. **(text)** User types a prompt in `#prompt` (max 1000 chars). Live: a character counter, a prompt **coach** grading the prompt (tip/warn/strong, from `forge-prompt-studio.js`), and example chips ("a low-poly red fox, sitting", etc.) with a "↻ More ideas" swap.
+ 4. (optional) User clicks **Surprise me** to fill a random vivid prompt, or **Enhance** (injected by `forge-enhance.js`) to rewrite their text via `POST /api/forge-enhance` into a sharper single-subject FLUX→TRELLIS prompt.
+ 5. (optional) User picks a **Quality tier** (Draft / Standard / High). Selecting High while locked reveals the in-place lock panel + holder note linking to `/three`; a wallet-aware perk line / "Connect wallet" chip may appear under Generate.
+ 6. (optional) User picks an **Engine**. Engines are filtered by mode (text/photo/sketch input). BYOK engines show a key glyph; choosing one reveals the `#byok-row` API-key input with a provider-specific hint. Health-degraded engines show an amber dot; down/unconfigured ones are disabled with the reason in the tooltip.
+ 7. (optional) User sets the reference-image **aspect ratio** (1:1 / 4:3 / 3:4 / 16:9) — shown only when relevant to the mode/engine. A live **estimate** line (`#estimate`) shows the catalog's real cost/time for the current tier+engine.
+ 8. User clicks **Generate** (or ⌘/Ctrl+Enter). `collectComposerCfg()` validates (text ≥ 3 chars). If High is locked and submitted via keyboard, the gate/upsell opens instead of firing.
+ 9. `startJob()` `POST`s to `/api/forge` with `{ prompt, aspect_ratio, path, tier, backend }` plus headers (client id, BYOK key if any, $THREE tier pass if eligible/needed — minted/awaited before the request when `highTierNeedsPass()`). Stage switches to `#state-generating`.
+ 10. **Generating state**: three labeled steps animate — *Painting reference image* → *Reconstructing textured mesh* → *Finalizing GLB* — with an honest elapsed-vs-typical progress bar (asymptotic, never fakes 100%, recolors amber past the catalog ETA). A **Cancel** button is available. When the submit response returns a `preview_image_url`, the reference image paints into the preview pane.
+ 11. If the engine is the synchronous free draft lane, the POST returns the finished `glb_url` directly; otherwise `forge.js` polls `GET /api/forge?job=<id>` every interval until `status:"done"` (with `glb_url`), `failed`, or timeout.
+ 12. On done: `showResult()` sets the `<model-viewer src>`, plays the WebGL **materialize** reveal (`forge-reveal.js`, skipped under reduced-motion), shows the result bar, wires the **Download GLB** anchor, and (if `creation_id`) shows a "Saved ✓" auto-save chip. Geometry-first/sketch results with no reference image get a captured **poster** frame (`POST /api/forge-poster`).
+ 13. (optional) User rates the model: **👍 Keep / 👎 Discard** (verdict) → `POST /api/forge-feedback`; or tags a category (Avatar/Creature/Item/Accessory/Scene/Vehicle) → `POST /api/forge-categorize`. (Data flywheel.)
+ 14. (optional) **Refine → <next tier>** — re-runs the exact same prompt/views one quality tier higher (re-enters step 9). Shown only when a higher tier exists and the job is re-runnable.
+ 15. (optional) **Refine** panel (`forge-refine.js`) — instant in-browser geometry passes (weld/smooth/relax/decimate/subdivide), non-destructive, no API call, no rate limit. Download the refined GLB.
+ 16. (optional) **Stylize** (`forge-stylize.js`) — voxels/bricks/lattice/low-poly geometric filters via `POST /api/forge-stylize` (worker job, polled), with a resolution slider, download, and revert.
+ 17. (optional) **Optimize topology** (`forge-optimize.js`) — tri/quad/low-poly remesh via `POST /api/forge-remesh` (polled).
+ 18. (optional) **Game-Ready** (`forge-gameready.js`) — retopologize to a poly budget and export a textured GLB + FBX for Unity/Unreal via `POST /api/forge-gameready` (polled), with budget slider + wireframe preview.
+ 19. (optional) **Split into parts** → links to `/segment?mesh=<glb>` (Parts Studio). **Compose** → `/compose?glb=<glb>` (Scene Composer / attach to avatar).
+ 20. (optional) **Export** (`forge-export.js`) — in-browser convert to OBJ / STL / PLY / USDZ (lazy three.js exporters, no upload).
+ 21. (optional) **Embed** (`forge-embed-panel.js`) — generate an embeddable web-component snippet for the model.
+ 22. (optional) **View in AR** (`forge-ar.js`) / model-viewer's `ar` (webxr/scene-viewer/quick-look) — place the model in the room.
+ 23. (optional) **Share** → `forge-share-btn` (share-link path), **Cinema** mode (fullscreen turntable for screen recording, F/Esc).
+ 24. User clicks **Download GLB** — anchor fetches + "stamps" the GLB (`#download[data-stamping]`), reports `downloaded:true` feedback, and saves the file. **OR** clicks **Make another** to reset to the idle composer.
+- **Photo / multi-view branch (steps 3–11 differ):** "From photos" tab shows up to 4 view slots (front/back/left/right) with a live "N of 4 views" counter + pips. Each photo is uploaded via presign `POST /api/forge-upload` → `PUT` to object storage; the public URL is recorded. Drag-to-reorder, paste (⌘V/Ctrl+V), drop, or click-to-browse (PNG/JPG/WebP, ≤8MB). An optional guidance prompt is allowed. Submit posts `{ image_urls, prompt?, ... }`. A server-side **vision pre-check** can reject an unusable photo (`422 image_not_usable`) → recoverable "Generate anyway" override.
+- **Sketch branch:** "From a sketch" tab (only when a live sketch engine exists) takes one drawing + a **required** description; outputs untextured geometry (user is told to Stylize/Retexture after).
+- **Decision points / branches:**
+ - Mode: text vs photos vs sketch (gates which engines/inputs are valid).
+ - Tier: Draft/Standard (free) vs High ($THREE hold-or-pay or BYOK-exempt).
+ - Engine: free NVIDIA lane vs BYOK engines (reveals key field; text-only engines disabled when photos are attached).
+ - High gate resolution: hold $THREE (tier pass) → pay-per-generation ($THREE via `forge-pay.js`) → drop to Draft/Standard.
+ - Sync draft (POST returns done) vs async poll loop.
+ - Post-result fork: Refine-tier / Refine-local / Stylize / Optimize / Game-Ready / Export / Embed / AR / Share / Compose / Segment / Download / Make another.
+- **External calls / dependencies:**
+ - Catalog/health: `GET /api/forge?catalog=1`, `GET /api/forge?health=1`
+ - Submit/poll: `POST /api/forge`, `GET /api/forge?job=<id>`
+ - Uploads: `POST /api/forge-upload` (presign) + `PUT` object storage
+ - Flywheel: `POST /api/forge-feedback`, `POST /api/forge-categorize`, `POST /api/forge-poster`
+ - Galleries: `GET /api/forge-gallery?limit=24` (your creations), `GET /api/forge-gallery?scope=community&limit=24` (showcase), `GET /api/forge-creation?id=` (share open)
+ - Post-processing jobs: `POST /api/forge-stylize`, `POST /api/forge-remesh`, `POST /api/forge-gameready`, `POST /api/forge-enhance` (all polled by `?job=`)
+ - Payment: `forge-pay.js` → `src/token-pay.js` → `/api/token/quote` + `/api/token/settle` ($THREE)
+ - Access/tier pass: `/api/three/access` (read) + tier-pass mint (referenced via `attachTierPass`/`getTierPass`)
+ - Generation engines: FLUX (image) → TRELLIS (mesh) free lane; BYOK Meshy / Tripo / Rodin / Stability / Replicate; Hunyuan3D / TripoSG (sketch). Hosted on NVIDIA NIM / providers; same pipeline exposed to agents over MCP at `/api/mcp-3d`.
+ - 3rd-party viewer: model-viewer 4.0.0 (googleapis CDN).
+- **Success state:** A textured **GLB** standing in the in-page `<model-viewer>` (orbit/AR), auto-saved to "Your creations", with a downloadable file and all post-processing/export/embed/share actions enabled. Optional converted formats (OBJ/STL/PLY/USDZ/FBX) and a community showcase entry.
+- **Empty / error states:**
+ - **Empty/idle** (`#state-empty`): isometric wireframe art + "Enter a prompt to generate", with a live sample/community model in the viewer.
+ - **Unconfigured** (`#state-unconfigured`): deployment missing `REPLICATE_API_TOKEN` — explains how to enable.
+ - **Generation failed** (`#state-error`): generic failure with "Try again", plus contextual recovery buttons: "Refine current model instead" (rate-limited fallback), "Generate anyway" (vision override).
+ - BYOK errors: `needs_key` / `invalid_key` reveal + focus the key field; `insufficient_credits` explains provider is out of credits.
+ - `429`/limiter-unavailable: countdown + local-refine escape hatch.
+ - High gate `402 three_hold_required`: designed upsell (held vs required, Get $THREE, Pay-per-use).
+ - Payment errors: `payment_invalid` / `payment_expired` re-offer Pay; `payment_already_used` clears the stale proof.
+ - Upload errors: per-slot states (503 uploads unavailable, 429 rate-limited, too-large/empty/wrong-type, network).
+ - Viewer load failure: `#viewer-load-error` overlay → "use the download button to save the file directly".
+- **Step count:** ~12 required (text path, entry → download) + ~12 optional (surprise/enhance, tier/engine/aspect choices, refine-tier, refine-local, stylize, optimize, game-ready, export, embed, AR, share/cinema/compose/segment/verdict/category).
+
+---
+
+### Forge marketing landing — `/features/forge`
+
+- **Source:** `pages/features/forge.html` (static; no app JS module — only nav/footer + an inline FAQ accordion script and model-viewer for the hero sample). Stylesheets: `features-landing.css`.
+- **Entry point:** `/features` index, SEO/search, social cards.
+- **Prerequisites / gates:** None — read-only marketing page.
+- **Steps (3):**
+ 1. User reads the hero ("Type a description. Get a 3D model." — Flux + TRELLIS) and orbits the sample GLB (`/animations/robotexpressive.glb`) in the hero model-viewer.
+ 2. User reads the "Three steps from prompt to model" how-it-works, the highlight cards (AR inspection, agent avatar, shareable link, data flywheel), and expands FAQ items (inline `aria-expanded` toggle script).
+ 3. User clicks **Open Forge →** (to `/forge`) or **Try Scan instead** (`/features/scan`).
+- **Decision points / branches:** Open Forge vs Try Scan vs All features; FAQ expand/collapse.
+- **External calls / dependencies:** model-viewer CDN only. No API calls. (FAQ schema mentions Flux + TRELLIS; advertises GLB output and commercial-use rights.)
+- **Success state:** User navigates into `/forge`.
+- **Empty / error states:** None (static content). FAQ items collapsed by default.
+- **Step count:** 3 required (read + click through) + 0 optional (FAQ expansion is incidental).
+
+---
+
+### Describe it to 3D (prompt → rigged avatar) — `/create/prompt`
+
+- **Source:** `pages/create-prompt.html` + `src/create-prompt.js`. **Overlap note:** this is the **onboarding/avatar-creation** cluster, not Forge. It shares the same conceptual "type a prompt → 3D" pattern but uses an entirely **different backend** — the selfie/avatar reconstruction + auto-rig pipeline, not the Forge engine catalog. It explicitly cross-links to `/forge` for "making an object, prop, or scene piece instead of a character." Entry points include `/create`, `/create-agent`, dashboard avatars/agents pages, and the gallery.
+- **Entry point:** From `/create` (and `create.js`), the create-agent flow, dashboard, and gallery "make one" CTAs.
+- **Prerequisites / gates:** **Sign-in required** ("Sign-in required" chip). A `401` on submit or poll redirects to `/login?next=/create/prompt`. No wallet / no $THREE gate. Avatars default to `private` visibility.
+- **Steps (3 stages):**
+ 1. **Compose:** User types a single-subject character description in `#prompt` (max 600; counter; Generate disabled under 3 chars). Optional example chips fill the box. Hint: "Single subject, full body works best." Cross-link offered to `/forge` for objects.
+ 2. User clicks **Generate avatar** (or ⌘/Ctrl+Enter). `start()` POSTs `/api/avatars/reconstruct` `{ name (derived from prompt), prompt, visibility:'private' }`. UI switches to the **Building** stage (spinning orb).
+ 3. **Building:** Live phased progress — *Rendering a reference image…* (Flux) → *Reconstructing it into 3D…* → *Adding a skeleton so it can move…* — with an elapsed clock. Polls `GET /api/avatars/regenerate-status?jobId=` every 3s (up to 8 min).
+ 4. **Done:** On `status:"done"` + `resultAvatarId`, fetches `GET /api/avatars/<id>`, previews the rigged GLB in the done model-viewer, shows tags (Animation-ready / Static mesh — riggable / Private to you). CTAs: **Open in editor** (`/avatars/<id>/edit`) and **Make another**. If no model URL yet, it redirects straight to the editor.
+- **Decision points / branches:** Signed-in vs not (login redirect); rigged vs static-mesh tag; open editor vs make another; (offered) divert to `/forge` for non-characters.
+- **External calls / dependencies:** `POST /api/avatars/reconstruct`, `GET /api/avatars/regenerate-status?jobId=`, `GET /api/avatars/<id>`. Flux text→image + reconstruct + auto-rig backend (shared with the selfie pipeline). model-viewer CDN. Dispatches `tws:feature-done` for the site discovery layer.
+- **Success state:** A **rigged GLB avatar** saved to the user's account, previewed, ready to open in the avatar editor.
+- **Empty / error states:** Compose inline error ("Add a few words…"). Build error box with friendly mappings: rate-limited (`txt2img_rate_limited`/429), unconfigured (`regen_unconfigured`/`txt2img_unconfigured` → suggests `/create/selfie`), provider billing, unreachable, render error, no-face-detected, NSFW-blocked, timeout, OOM; plus a "Back" recovery button. Poll timeout message points the user to their dashboard.
+- **Step count:** 3 required (compose → generate → done) + 1 optional (pick an example chip) — excludes downstream editor actions.
+
+---
+
+### Tutorial · Text Prompt to 3D Model — `/tutorials/text-to-3d`
+
+- **Source:** `pages/tutorial.html` (shared template, renders any `/tutorials/<slug>`) + content `docs/tutorials/text-to-3d.md`. Slug resolved client-side, markdown fetched from `/docs/tutorials/text-to-3d.md`, rendered with marked.js + highlight.js. Metadata/preview model come from `/tutorials-manifest.js` (`window.TUTORIALS`).
+- **Entry point:** `/tutorials` index, `/docs`, in-Forge "/docs" hint, blog, search, and cross-links from the image-to-3d and prompts-for-3d tutorials.
+- **Prerequisites / gates:** None — read-only content page. (The tutorial itself states: "no account, no wallet, no code.")
+- **Steps (read-only content page):**
+ 1. Read intro + hero; orbit the interactive preview model (`<model-viewer>` injected from the manifest's `previewModel`).
+ 2. Read the 6 tutorial steps: **Step 1** Open the Forge → **Step 2** Describe the object → **Step 3** Pick a quality tier → **Step 4** Generate → **Step 5** Inspect your model → **Step 6** Download or share it; plus "Didn't get what you wanted?" troubleshooting and "What's next".
+ 3. (optional) Use the auto-generated heading anchors / table of contents; follow inline links to `/forge`, `/tutorials/image-to-3d`, `/tutorials/prompts-for-3d`.
+ 4. (optional) Use the prev/next pager (built from `window.TUTORIALS`) to move between tutorials.
+- **Decision points / branches:** Navigate to `/forge` to actually do it, or to adjacent tutorials via inline links / pager.
+- **External calls / dependencies:** `GET /docs/tutorials/text-to-3d.md`; marked.js + highlight.js CDNs; model-viewer CDN; `/tutorials-manifest.js`; `/api/page-og` (OG image only).
+- **Success state:** User understands the text→3D flow (content consumed); typically clicks through to `/forge`.
+- **Empty / error states:** Template handles a missing/invalid slug (no entry → redirect/empty handling in `tutorial.html`); a failed markdown fetch leaves the article empty. No interactive failure modes.
+- **Step count:** 2 required (read content + follow the embedded steps) + 2 optional (TOC anchors, prev/next pager / cross-links). Content covers 6 in-doc instructional steps.
+
+---
+
+### Tutorial · Photos to 3D Model — `/tutorials/image-to-3d`
+
+- **Source:** `pages/tutorial.html` (same shared template) + content `docs/tutorials/image-to-3d.md`, fetched from `/docs/tutorials/image-to-3d.md`.
+- **Entry point:** `/tutorials` index, the text-to-3d tutorial's "What's next", Forge photo-mode help, search.
+- **Prerequisites / gates:** None — read-only content page ("A phone camera is plenty.").
+- **Steps (read-only content page):**
+ 1. Read intro + orbit the manifest preview model.
+ 2. Read the 5 tutorial steps: **Step 1** Take good photos (1 object, plain bg, even light, fill frame, 4 angles) → **Step 2** Open the Forge in photo mode → **Step 3** Add guidance (optional) → **Step 4** Pick a tier and generate → **Step 5** Inspect, download, share; plus Troubleshooting and "What's next".
+ 3. (optional) Follow inline links to `/forge` and adjacent tutorials; use the pager.
+- **Decision points / branches:** Go to `/forge` (From photos tab) to execute; navigate to adjacent tutorials.
+- **External calls / dependencies:** `GET /docs/tutorials/image-to-3d.md`; marked.js + highlight.js + model-viewer CDNs; `/tutorials-manifest.js`; `/api/page-og`.
+- **Success state:** User understands the photo/multi-view→3D flow; clicks through to `/forge` photo mode.
+- **Empty / error states:** Same template-level handling as the text-to-3d tutorial (missing slug, failed md fetch). No interactive failure modes.
+- **Step count:** 2 required (read + follow embedded steps) + 2 optional (anchors, pager / cross-links). Content covers 5 in-doc instructional steps.
+
+---
+
+## Notes
+
+- All five routes' sources were located and traced from real code. No missing sources.
+- `/create/prompt` is included here because it overlaps the "type a prompt → 3D" pattern, but it belongs to the **onboarding/avatar** cluster and uses the **avatar reconstruct + auto-rig** backend (`/api/avatars/*`), distinct from Forge's `/api/forge` engine catalog. It is the one route in this cluster that is auth-gated.
+- `/features/forge` is pure marketing (no app module); the two tutorials are read-only markdown rendered by one shared `tutorial.html` template.
diff --git a/docs/ux-flows/03-3d-editing-viewer.md b/docs/ux-flows/03-3d-editing-viewer.md
new file mode 100644
index 000000000..34a3a8b8f
--- /dev/null
+++ b/docs/ux-flows/03-3d-editing-viewer.md
@@ -0,0 +1,199 @@
+# 3D Editing, Viewing & Validation
+
+UX Flow Atlas — cluster "3D Editing, Viewing & Validation". Each entry is traced from real source code (file + symbol citations). Routing was resolved by reading `vite.config.js` dev-server rewrites and each page's `<script>` imports.
+
+Routing summary (from `vite.config.js`):
+
+| Route | Page HTML | Entry module |
+|---|---|---|
+| `/scene` | `pages/scene.html` | `src/scene-studio/main.js` (vendored three.js r184 editor) |
+| `/compose` | `pages/compose.html` | `src/scene-compose.js` |
+| `/pose` | `pages/pose.html` | `src/pose-studio.js` |
+| `/validation` | `public/validation/index.html` | `src/validation-ui.js` + `src/validation-page.js` (+ `src/validator.js`) |
+| `/app` | `pages/app.html` | `src/app.js` → `src/viewer.js`, `src/editor/index.js`, `src/validator.js` |
+| `/hydrate` | `public/hydrate/index.html` | inline module (no `src/` file) |
+| `/artifact` | `public/artifact/index.html` | inline module (no `src/` file) |
+| `/avatar-artifact` | `pages/avatar-artifact.html` | inline script (CDN three.js r128, fully procedural) |
+
+---
+
+### Scene Studio — `/scene`
+- **Source:** `pages/scene.html`, `src/scene-studio/main.js`, vendored editor under `src/scene-studio/vendor/js/` (`Editor.js`, `Viewport.js`, `Menubar.*.js`, `Sidebar.*.js`, commands), `src/scene-studio/studio.css`, `src/shared/scene-handoff.js`.
+- **Entry point:** `pages/scene.html` loads the CodeMirror/Draco vendor `<script>` chain, then `<script type="module" src="/src/scene-studio/main.js">` (scene.html:84). `main.js` constructs the vendored `Editor`, mounts Viewport/Toolbar/Script/Player/Sidebar/Menubar/Resizer/Animation panels into `#studio-app`, exposes `window.editor`/`window.THREE`, and inits IndexedDB-backed autosave/storage (`editor.storage.init`, main.js:36-144). The surface is dark-locked (`data-theme='dark'` re-pinned, main.js:11).
+- **Prerequisites / gates:** None. No auth, no wallet, no $THREE gate. Works fully anonymously; an empty default scene loads immediately. State persists locally via `editor.storage` (autosave to IndexedDB, debounced ~1s, main.js:111-143).
+- **Steps (N):**
+ 1. Arrive at `/scene`. Editor mounts; prior autosaved scene restored from IndexedDB, or `sceneEnvironmentChanged('Default')` fires for a fresh scene (main.js:89-97).
+ 2. (optional, deep-link) Arrive via `/scene?model=<glb_url>&name=<label>` (hand-off from Forge/Parts). `importModelFromQuery()` validates the URL is `https://` or same-origin relative, fetches the GLB, parses it with the Draco/KTX2/Meshopt-wired GLTFLoader, adds it via `AddObjectCommand`, selects it, and strips the query from the address bar (main.js:186-206).
+ 3. (optional, deep-link) Arrive via `/scene?handoff=1` (hand-off from Animation Studio `/pose`). `importHandoffAnimation()` reads the baked GLB from IndexedDB via `takeSceneHandoff()`, adds it, and attaches a `Play Animation` player script so the embedded clip plays live and records to video (main.js:208-251).
+ 4. Import a model: drag a GLB/glTF (or a folder of glTF+textures) anywhere on the page → `drop` handler routes to `editor.loader.loadItemList`/`loadFiles` (main.js:255-271); or use **File ▸ Import** file picker (`Menubar.File.js`:185-211).
+ 5. Add primitives/lights/cameras via the **Add** menu (`Menubar.Add.js`); add scripts via **Script** panel (CodeMirror).
+ 6. Select an object in the Viewport or the Outliner (Sidebar). The transform gizmo attaches.
+ 7. Transform with the gizmo — translate / rotate / scale (Toolbar mode buttons + Viewport `TransformControls`).
+ 8. Edit properties in the Sidebar: object transform, **Geometry**, **Material** (color/maps/roughness/metalness/etc.), **Scene** (background, environment, fog), per-light settings.
+ 9. (optional) Edit a script in the Script panel; (optional) press **Play** (`Player`) to run scene scripts/animations live.
+ 10. (optional) Keyframe/inspect animations in the Animation panel (timeline at bottom; `animationPanelChanged` resizes Viewport, main.js:70-85).
+ 11. (optional) **File ▸ New** (empty / templates) to reset; undo/redo via the command history.
+ 12. Export via **File ▸ Export** submenu: GLB, GLTF, OBJ, PLY (ASCII/binary), STL (ASCII/binary), USDZ, DRC/Draco (`Menubar.File.js`:212-435). A download is triggered (e.g. `scene.glb`, `scene.gltf`).
+ 13. (optional) **File ▸ Export Project** saves the editor scene as a `.json` project; **File ▸ Open** re-imports a `.json` project (`Menubar.File.js`:91-185).
+ 14. (optional) **Render** menu → render an image or video of the scene via `APP.Player` (`Menubar.Render.js`).
+- **Decision points / branches:** Fresh scene vs restored autosave (main.js:89-104). Deep-link arrival (`?model=` add, `?handoff=1` animation import) vs plain manual import. `#file=<url>` hash → prompts to open a remote `.json` project, replacing the scene (main.js:286-299). Drag of a folder (`DataTransferItemList`) vs single files.
+- **External calls / dependencies:** `fetch(modelUrl)` for `?model=` deep-link GLB (main.js:195); IndexedDB via `editor.storage` (autosave) and `src/shared/scene-handoff.js` (`takeSceneHandoff`, DB `three-ws-scene-handoff`); Draco decoder at `/scene-studio/draco/gltf/`, KTX2 transcoder at `/scene-studio/basis/` (main.js:163-165); local CodeMirror/esprima/acorn/tern vendor libs. Imports: glTF/GLB (+ companion textures), `.json` editor projects. Exports: GLB, GLTF, OBJ, PLY, STL, USDZ, DRC, JSON project, rendered image/video. No platform API calls.
+- **Success state:** Imported/transformed objects appear in the Viewport + Outliner; autosave indicator (`savingStarted`/`savingFinished`) confirms persistence; export triggers a file download.
+- **Empty / error states:** Empty default scene with grid + default environment when no autosave exists. `?model=` fetch failure → `alert('Could not load the handed-off model … drag the GLB file into the editor instead.')` (main.js:204). `?handoff=1` IndexedDB unavailable → silently no-ops; load failure → `alert('Could not load the animation … Try Export GLB on /pose and drag the file in instead.')` (main.js:248-249). No-GLB-in-drop handled by the vendored loader.
+- **Step count:** ~7 required (arrive → import → select → transform → edit material → edit scene → export) + ~7 optional (deep-link arrival, primitives/lights, scripts, Play, animation timeline, project save/open, render).
+
+---
+
+### Scene Composer — `/compose`
+- **Source:** `pages/compose.html`, `src/scene-compose.js`, `src/shared/log.js`.
+- **Entry point:** `<script type="module" src="/src/scene-compose.js">` (compose.html:377). Module sets up a Three.js renderer/scene/PMREM environment, OrbitControls, a `TransformControls` gizmo, undo/redo stack, then on IIFE boot reads URL params (`?glb=` / `?avatar=`) and renders the initial hierarchy (scene-compose.js:107-120, 940-964, 1343).
+- **Prerequisites / gates:** None to compose/forge/export. Forge ownership is auth-free via a generated `forge_client_key` in localStorage sent as the `x-forge-client` header (scene-compose.js:88-94). **Saving an outfit** requires an avatar loaded from `/api/avatars/<id>` (a real avatar id), otherwise it falls back to "Use Export GLB" (scene-compose.js:1318-1320). No wallet / $THREE gate.
+- **Steps (N):**
+ 1. Arrive at `/compose`. If `?glb=<url>` present → load that GLB as an item (scene-compose.js:940-942). If `?avatar=<id-or-url>` present → resolve via `/api/avatars/<id>` (or direct URL) and load as the avatar (scene-compose.js:948-960). Else show the avatar prompt / canvas hint.
+ 2. Choose a base avatar (optional): paste a URL and **Load** (`btn-load-url`, scene-compose.js:967-971); **Browse** opens a modal listing avatars from `/api/explore?type=avatar&limit=24` (scene-compose.js:980-999); or **Skip** to compose without an avatar (scene-compose.js:973).
+ 3. **Forge an item from text:** type a prompt, optionally pick an intent chip (accessory/item/scene/creature/vehicle — drives suggestion pills + `model_category`), press **Forge** (`startForge`, scene-compose.js:1071-1103). Live progress bar with staged labels; polls `/api/forge?job=<id>` every 3s until `done` (then adds the GLB to the scene) or `failed`/timeout (scene-compose.js:1105-1142).
+ 4. (optional) Import a local GLB/glTF via drag-drop on the drop zone or the file input (`loadFile`, scene-compose.js:1240-1260).
+ 5. Select an object by clicking it (or via the hierarchy list `#ol`). Inspector `#ins` shows transform + scale-lock chain.
+ 6. Transform: gizmo modes translate/rotate/scale (toolbar buttons), toggle world/local space (X key), grid snap (Ctrl+G), duplicate (Ctrl+D), frame/focus selected (F).
+ 7. (optional) Attach an item to an avatar bone: when an avatar with bones is loaded, the inspector shows a bone `<select>` grouped by region (Head/Torso/Arms/Legs); choosing a bone calls `attachToBone` which parents the item group under the bone (scene-compose.js:783-895).
+ 8. (optional) Rename objects (double-click in hierarchy), toggle visibility, delete (with geometry/material/texture disposal).
+ 9. (optional) Use camera presets (Front/Back/Left/Right/Top/Isometric) via the camera menu.
+ 10. (optional) **Screenshot** (Ctrl+P / button) → downloads `scene-compose.png` (scene-compose.js:1265-1279).
+ 11. **Export GLB** → bundles all visible, non-bone-attached objects into one group and downloads `scene-compose.glb` (scene-compose.js:1284-1305).
+ 12. **Save outfit** → requires a loaded avatar with bone-attached items; PATCHes `/api/avatars/<id>` with the `accessories` array (bone, glbUrl, name) (scene-compose.js:1310-1335).
+- **Decision points / branches:** Boot branch on `?glb=` vs `?avatar=` vs neither (scene-compose.js:940-963). Forge synchronous `done` vs async `job_id` poll (scene-compose.js:1088-1097). Export (all objects, any state) vs Save outfit (avatar + bone-attached items only; requires a `/api/avatars/<id>`-sourced avatar id). Bone-attach UI only appears for non-avatar items when an avatar with bones exists.
+- **External calls / dependencies:** `POST /api/forge` + `GET /api/forge?job=<id>` (text-to-3D, with `x-forge-client` header); `GET /api/forge-gallery?limit=24` (your forged creations, scene-compose.js:1175); `GET /api/explore?type=avatar&limit=24` (avatar browse modal); `GET /api/avatars/<id>` (resolve avatar by id); `PATCH /api/avatars/<id>` (save outfit accessories). Imports: GLB/glTF (URL or local file). Exports: GLB (`GLTFExporter`, binary), PNG screenshot.
+- **Success state:** Forged/loaded items appear in scene + hierarchy with toasts ("Added: …", "Loaded: …", "Attached to <bone>"); export/save flash "Exported ✓" / "Outfit saved ✓" (`flashSave`, scene-compose.js:1337-1341).
+- **Empty / error states:** Empty hierarchy → "No objects — load an avatar or forge an item." (scene-compose.js:604). Forge errors → red banner via `showForgeError` (auto-hides 6s); timeout → "Generation timed out. Try again." Avatar browse empty → "No avatars found. Forge one first." Export with nothing → toast "Nothing to export". Save outfit with no avatar → "Load an avatar first"; no attached items → "Attach at least one item to a bone first"; non-API avatar → "Use Export GLB to save this scene".
+- **Step count:** ~5 required (arrive → forge or import → select → transform → export) + ~7 optional (load/browse/skip avatar, intent chips, bone attach, rename/visibility, camera presets, screenshot, save outfit).
+
+---
+
+### Animation Studio — `/pose`
+- **Source:** `pages/pose.html`, `src/pose-studio.js` (entry), `src/pose-rig.js`, `src/pose-animation.js`, `src/pose-presets.js`, `src/pose-library.js`, `src/pose-share.js`, `src/animation-library.js`, `src/shared/scene-handoff.js`. (Note: `src/pose-mannequin.js` and `src/avatar-pose.js` exist but are **not** on the `/pose` load path — the studio's mannequin comes from `MannequinRig` in `pose-rig.js`.)
+- **Entry point:** `<script type="module" src="/src/pose-studio.js">` (pose.html:2082). `boot()` runs on `DOMContentLoaded` (pose-studio.js:361, 1634): builds the Three.js scene/renderer (`preserveDrawingBuffer` for screenshots), OrbitControls, a rotate `TransformControls` gizmo, lights/grid/prop layer, then immediately mounts the built-in `MannequinRig` (pose-studio.js:406-408) and starts `tick()` (423-436).
+- **Prerequisites / gates:** None to pose/keyframe/preview/export/screenshot/scene-handoff — the mannequin is mounted at boot, usable anonymously. **Save to account** and **sell** are auth-gated: `PoseLibrary.openSaveDialog` checks `getUser()` (`GET /api/auth/me`); if signed out it stashes the doc in sessionStorage and routes to `/login?next=/pose`, restoring on return (pose-library.js:85-129). The curated preset Animation Library and the AI text-to-motion generator **require a rigged GLB avatar** (mannequin shows a "Load a rigged avatar" empty state). No wallet / $THREE gate.
+- **Steps (N):**
+ 1. Arrive at `/pose`. Mannequin mounts with a starting pose (shared pose from `#p=`/`?p=` if present, else `contrapposto`, pose-studio.js:413-419). `?avatar=<id>` loads that avatar (falls back to mannequin on failure); `?anim=<id>` opens a saved clip into the editor (pose-studio.js:1608-1631).
+ 2. (optional) Choose the figure: **Load avatar** opens `AvatarGalleryPicker` → `loadAvatarFromUrl()` (GLTF load with % progress, builds rig via `makeGltfRig`, frames, writes `?avatar=`, pose-studio.js:775-862); or **Mannequin** to return to the primitive rig (`switchToMannequin`, 821).
+ 3. (optional) Tune model/scene: mannequin body type/skin tone/constraints (GLB-disabled); background color, FOV, floor grid, key-light azimuth/elevation/intensity, floor props (chair/stool/cube/ball/plinth) (pose-studio.js:937-1019).
+ 4. Select a bone: click the figure (`pickBoneAt`, 471-518), click the searchable bone list (699-732), or grab an IK handle (auto-selects).
+ 5. Pose with FK (default mode): rotate gizmo on the selected bone + X/Y/Z rotation sliders + "Reset this bone" (`renderControlsPanel`, 640-696).
+ 6. (optional) Pose with IK: toggle IK (top bar or **I** key; disabled if the rig exposes no limb chains) and drag a glowing cyan hand/foot handle → `rig.solveIK` (pose-studio.js:585-630). FK and IK are mutually exclusive.
+ 7. (optional) Apply a preset pose from the grouped grid (Standing/Action/Sitting/Expressive, `poseFromMannequinPreset`, pose-studio.js:734-758).
+ 8. (optional, rigged GLB only) Apply a curated motion clip or AI-generate one: `AnimationLibrary` cards from `/animations/manifest.json` retarget+play live; text box POSTs `/api/forge-motion` and polls for the clip (animation-library.js:27, 102, 541-560).
+ 9. Keyframe the timeline: pose, then **Add keyframe** / **K** (`captureKeyframe`, 1262-1273); drag diamonds to retime, set per-key easing, set name/duration/FPS/loop (pose-studio.js:1275-1394).
+ 10. Scrub / play: drag the track or arrow keys; transport play/pause (Space), stop, jump start/end (Home/End), loop toggle. Playback slerp-interpolates poses via `sampleAtTime` (pose-animation.js:136).
+ 11. (optional) Import a pose JSON (`#pose-import-json`) → applies a single static pose (pose-studio.js:917-934).
+ 12. Completion paths: **Export JSON** clip (`serializeClip`); **Export GLB** with embedded clip (`bakeAnimatedGlb`); **Record in Scene →** (bakes GLB, stashes in IndexedDB, navigates `/scene?handoff=1`); **Save** to account (Ctrl/Cmd+S → PoseLibrary dialog, POST/PATCH `/api/animations/clips`); **Export pose JSON** (single pose) / **PNG screenshot**; **Sell** a saved clip for USDC from the "My animations" drawer (pose-studio.js:1408-1491; pose-library.js). Export buttons disabled until ≥1 keyframe (`refreshExportEnabled`, 1206-1211).
+- **Decision points / branches:** Mannequin vs loaded GLB (changes bone-pick strategy, model-tuning availability, IK availability, preset/AI-library availability, and whether the saved clip links an `avatar_id`). Save vs Update vs Save-as-copy (PATCH existing clip vs POST new, pose-library.js:218-262). Four independent completion paths: Save (auth-gated) / Export / Sell (USDC) / Scene handoff. Boot branch on `?avatar=` and chained `?anim=`.
+- **External calls / dependencies:** `GET /api/avatars/:id`; `GET /api/auth/me`; clip CRUD `POST/PATCH/DELETE/GET /api/animations/clips[/:id]` (mine + `include_public=true&visibility=public`); `POST /api/animations/thumbnail`; sell flow `POST /api/animations/presign` → R2 `PUT upload_url` → `POST /api/animations/sell` (USDC on Base or Solana); AI/preset clips `GET /animations/manifest.json`, `POST /api/forge-motion` + poll. Imports: pose JSON. Exports: pose JSON, clip JSON, animated GLB (`GLTFExporter` binary), PNG. Scene handoff: `putSceneHandoff({glb,name})` to IndexedDB, then navigate `/scene?handoff=1` (shared/scene-handoff.js). URL pose codec `#p=`/`?p=` (pose-share.js).
+- **Success state:** HUD `#pose-status` confirmations ("Loaded …", "Keyframe added at Xs · N total", "Screenshot saved"); export buttons show busy → "Saved ✓"/"Opening ↗"; save → "Saved '…' to your account"; sell → "Listed '…' for N USDC".
+- **Empty / error states:** Timeline `#tl-empty` "Pose the figure, then press K…" until a keyframe exists; mode-aware no-selection hint; bone search "No bones match"; library drawer "No animations yet" / "Sign in to see your animations"; AnimationLibrary "Load a rigged avatar"/"can't be retargeted"; boot idle "Ready. Click a body part to pose, or load an avatar." Errors (red HUD): avatar load failure, "no recognizable humanoid skeleton", import parse failure, "Add a keyframe first, then play", export "… failed"; library/API errors show inline `.pl-dialog-err` + Retry; `?avatar=` boot failure falls back to mannequin with explanation.
+- **Step count:** ~6 required (arrive → select bone → FK pose → add keyframe → scrub/play → export) + ~7 optional (load/switch avatar, scene/model tuning, IK, preset pose, motion library/AI, import pose JSON, save/sell/scene-handoff/screenshot).
+
+---
+
+### glTF Validator — `/validation`
+- **Source:** `public/validation/index.html`, `src/validation-page.js`, `src/validation-ui.js`, `src/validator.js`, `src/gltf-inspect.js`, `src/components/validator-report.jsx`, `src/components/inspect-report.jsx`, `src/erc8004/validation-recorder.js`, `src/erc8004/agent-registry.js`.
+- **Entry point:** `public/validation/index.html` (module at lines 1040-1042) imports `ValidationDashboard` (validation-ui.js) and `ValidationPage` (validation-page.js); constructs the dashboard then the page (which references the dashboard for the on-chain hand-off). On construct, `ValidationPage` renders the Khronos sample chips, binds input events, and restores the active tab from the URL hash (validation-page.js:32-46).
+- **Prerequisites / gates:** None to validate/inspect — runs fully client-side in the browser. The **Records / "Pin & sign on-chain"** path requires an Ethereum wallet (`ensureWallet` via ethers / `window.ethereum`, validation-ui.js:12) to sign + submit an on-chain attestation; that is the only gated sub-flow. No $THREE gate.
+- **Steps (N):**
+ 1. Arrive at `/validation`. Three tabs: **Validate**, **Inspect**, **Records** (default `validate`, restored from `#validate|#inspect|#records`, validation-page.js:50-69).
+ 2. Provide a model — three input sources sharing one pipeline: drag-drop a GLB on the drop zone, pick a file via the file input, paste a URL and click the URL button (Enter also works), or click a Khronos sample chip (Box/Duck/BoomBox/DamagedHelmet/Avocado from jsdelivr) (validation-page.js:78-118).
+ 3. `_run(bytes, name)` fires both analyses in parallel (validation-page.js:145-189): the official Khronos validator (`Validator.validateBuffer` → `gltf-validator` `validateBytes`, validator.js:57-66) and the glTF-Transform inspector (`inspectModel` + `suggestOptimizations`).
+ 4. **Validate tab** renders the report (`ValidatorReport`) — error/warning/info/hint counts bucketed by severity, aggregated repeated codes, generator/asset metadata (validator.js:106-189; validation-page.js:191-198).
+ 5. **Inspect tab** renders glTF-Transform stats + optimization suggestions (`InspectReport`, validation-page.js:200-203).
+ 6. (optional) Download either report as JSON (`buildDownloadHref` data URI on each report panel).
+ 7. (optional) View the validation report in a standalone lightbox tab (`Validator.showLightbox`, validator.js:198-212).
+ 8. (optional, wallet) **Pin & sign on-chain**: `_handOffToDashboard` switches to the Records tab, opens the submit modal pre-filled with the in-memory report + its `hashReport` hash (no file re-pick), then `ValidationDashboard.submitReport` connects the wallet, pins to IPFS, and records the attestation (validation-page.js:221-242; validation-ui.js).
+ 9. **Records tab** (independent): enter agent id + chain id (or arrive via `?agent=&chain=`), **Load** past validation records (`getLatestValidation`), or **Submit** a new report by dropping/picking a report JSON file (validation-ui.js:33-79).
+- **Decision points / branches:** Input source (file / URL / sample) — all converge on `_run`. Validate vs Inspect (run together, two tabs). In-memory hand-off to Records vs manual report-file submission. Records load (`?agent=&chain=` auto-loads) vs manual entry. On-chain submit requires wallet; validation/inspection do not.
+- **External calls / dependencies:** `fetch(url)` for URL/sample inputs (validation-page.js:136); `gltf-validator` `validateBytes` (in-browser); `src/gltf-inspect.js` (glTF-Transform, in-browser). On-chain: IPFS pin (`pinFile`), `recordValidation`/`getLatestValidation` (validation-recorder.js), `ensureWallet`/ethers + `window.ethereum`. Inputs: GLB (and glTF + external resources resolved from the dropped asset map). The Validate tab can read the GLTFLoader-cached ArrayBuffer when invoked from the viewer (validator.js:26-34). Outputs: JSON report download, on-chain attestation.
+- **Success state:** Status line "Loaded <name> · <KB> · validated" (validation-page.js:184-187); rendered validate + inspect reports; **Pin & sign** button enabled once a report exists.
+- **Empty / error states:** Initial — three empty tab panels with sample chips inviting input. While running — "Validating…" / "Inspecting…" loading rows. File read error → "Could not read file: …"; fetch error → "Could not fetch <name>: HTTP <status>"; validator failure → "Validator failed: …" inline; inspector failure → "Inspector failed: …" inline (validation-page.js:122-217). On-chain hand-off with no report → toast "Run a validation first" (validation-page.js:222-224).
+- **Step count:** ~4 required (arrive → provide model → read Validate report → read Inspect report) + ~5 optional (download JSON, lightbox, pin & sign on-chain, browse records, submit report file).
+
+---
+
+### 3D Viewer / Editor (main app) — `/app`
+- **Source:** `pages/app.html`, `src/app.js`, `src/viewer.js`, `src/editor/index.js`, `src/validator.js`, `src/account.js`, `src/wallet.js`, `src/erc8004/*`, widget mounts under `src/widgets/*`, `src/components/screenshot-modal.js`, `src/next-layout.js`.
+- **Entry point:** `<script defer type="module" src="/src/app.js">` (app.html:57). `_bootApp()` constructs `new App(document.body, location)` and exposes `window.VIEWER.app` (app.js:2583-2596). The `App` constructor (app.js:162-401) parses hash + query into `this.options`, conditionally builds dropzone/avatar-creator/layout/nav, dispatches on route mode, then inits the agent system + widget bridge.
+- **Prerequisites / gates:** No hard gate blocks the viewer — the default CZ avatar (or `?model=`/`?agent=` target) loads for everyone, anonymous included. The "gate" is presentation-only: in `main` mode `_applyViewerMode` sets `data-authed` (`pending`/`false`) and CSS (`public/style.css`:6589-6606) overlays the `.auth-gate` card and hides the agent sidebar + dat.GUI editor for anonymous/pending users (app.js:614-629); `getMe()` (`GET /api/auth/me`) reconciles to the real state (app.js:681-695). A wallet button exists (`initWalletButton`, eager `eagerConnectWallet`) but connecting is never required. **No $THREE token gate.** "Save to account" and "Save edits" redirect to `/login` when signed out. The dat.GUI editor only exists once a model has loaded (built by the viewer on content load).
+- **Steps (N):**
+ 1. Arrive at `/app`. Constructor dispatches by mode; `_maybeResumeOrLoad(options)` runs for the default path (app.js:378, 408-458).
+ 2. A model auto-loads: `?resume=<token>` restores a stashed editor session (optional), else `options.model || '/avatars/cz.glb'`; the default CZ avatar crossfades into a "taunt" landing clip (app.js:451-486).
+ 3. Viewer renders via `view()` → WebGL check, `createViewer()`, `viewer.load(url, …)` with a progress callback, then attach avatar, notify editor, configure animations, set AR target, run validator (app.js:1783-1876).
+ 4. (optional) Load your own model — drag-drop a `.glb`/`.gltf` or folder anywhere on `.wrap` (`SimpleDropzone` → `load(files)`, app.js:1708-1776); or the `#file-input` picker; or `?model=<url>`/`#model=` (host-validated by `isSafeQueryModelUrl` for the deploy path, app.js:25-38); or `?agent=<uuid>`.
+ 5. (optional) Open the editor controls (dat.GUI / Next-layout drawer): **Display** (background, autoRotate, wireframe, skeleton, grid, point size, transparent bg, screenshot, model info, mesh labels), **Lighting** (IBL/envMap, exposure, tone mapping, punctual lights), **Light Probes**, **Animation**, **Morph Targets**, **Cameras**, **Agent** follow mode, **Performance** stats (viewer.js `addGUI`).
+ 6. (optional) Play animations — `_configureAnimations` fetches `/animations/manifest.json`, registers clips, honors `?anim=<name|uuid>`; Next-layout dock gives clip picker + play/pause + scrubber + loop (app.js:1921-1986).
+ 7. (optional) Edit environment / lights / camera / display via the GUI (`updateEnvironment`, `updateLights`, `setCamera`, `frameContent`, etc. in viewer.js).
+ 8. (optional) Edit materials / textures / scene via the `Editor` (`MaterialEditor`, `TextureInspector`, `SceneExplorer`, `MagicBrush`; rebuilt on each new model, editor/index.js:19-55).
+ 9. (optional) Take a screenshot → `viewer.captureScreenshot()` → `ScreenshotModal.show(blob)` (app.js:825-837).
+ 10. (optional) Export GLB → editor export folder → `exportEditedGLB(session)` → `downloadGLB(...)`; also a postMessage `exportGLB` bridge returns base64 GLB to a parent frame (editor/index.js:57-129; app.js:1498-1526).
+ 11. (optional) Save edits / save model to account — editor `_saveEdits` (R2 presign+upload+PATCH) or header "Save to account" (`_triggerSaveToAccount` → if signed out, stash + `/login?next=/app?pending=1`; if signed in, `_performSave` saves the GLB, creates/links an agent, redirects to `/agent/<id>`, app.js:839-974).
+ 12. (automatic) Validate — `validator.validate(...)` runs on every non-kiosk load; surfaces a `.validator-toggle` badge + lightbox (app.js:1872; validator.js).
+ 13. (optional) Cross-links — "Make this a widget" → `/studio?model=<url>`; "Open in Composer" → `/compose?glb=<url>`; "Deploy on Solana" → guided on-chain deploy agent `/app?agent=67bf6e67-…` (app.js:759-810).
+ 14. (optional) Chat with the agent — `_initNichAgent` mounts the NichAgent chat/voice UI + thought bubble (skipped in widget/kiosk/deploy/showcase, app.js:1633-1648).
+- **Decision points / branches:** Route mode dispatch (app.js:288-394): kiosk/embedChat (chromeless), `/deploy` (RegisterUI wizard), `/showcase` (marketplace grid), on-chain `/a/<chain>/<id>` (anonymous-safe), legacy `#agent=` embed, chat embed `/a/<uuid>?embed=1`, `#widget=<id>` (slim shell vs full SPA, type-specific mounts), `?agent=<uuid>` authenticated agent-edit, else default `_maybeResumeOrLoad`; `?pending=1` replays a stashed post-login save. Anonymous vs signed-in (auth-gate overlay + save gating only). Classic vs Next layout (localStorage toggle). File-drop vs URL vs agent vs on-chain model source.
+- **External calls / dependencies:** `GET /api/auth/me`, `POST /api/auth/logout`, `GET /api/avatars/<id>`, `GET /api/agents/<id>`, `GET /api/agents/me`, `POST /api/agents`, `PUT /api/agents/<id>`, `POST /api/avatars/thumbnail`, `POST /api/widgets/<id>/view`, `GET /animations/manifest.json` + `HEAD /animations/*.glb`; `saveRemoteGlbToAccount` (R2 presign/upload/commit); editor save (R2); on-chain dynamic imports (`erc8004/queries|abi|register-ui|showcase`) + Solana/ETH RPC; IPFS/Arweave URL resolution (`ipfs.js`). Imports: glTF/GLB (+ textures). Exports: binary GLB; PNG screenshot; AR uses USDZ (iOS) + GLB (Android). Validator: in-browser `gltf-validator`.
+- **Success state:** `LOAD_END(success)` fades the poster, hides the status overlay, fires `three-ws:first-frame`, runs first-time onboarding (agent-edit), backfills a missing thumbnail (app.js:2033-2066). Model renders, orbitable; editor + agent sidebar available for signed-in users.
+- **Empty / error states:** No true empty void — the CZ default always loads. Anonymous main mode shows the `.auth-gate` card ("Your agent lives here — Sign in…") with sidebar/GUI hidden; the dropzone invites upload/generate. Loading: spinner/determinate progress bar (`_showViewerLoading`/`_updateLoadProgress`) + poster thumbnail for agent-edit. Errors: `_classifyLoadError` → human message + Retry (`_showViewerError`, app.js:2090-2181); "No .gltf or .glb asset found." on bad drop; `_showWebglUnavailable` reload card; `_showWidgetError`; on-chain `_showOnChainError`/`_updateOnChainCard`.
+- **Step count:** ~3 required (arrive → model auto-loads → view/orbit) + ~11 optional (load own model, GUI controls, animations, env/lights/camera, material/texture editing, screenshot, export GLB, save to account, validate review, cross-links, agent chat).
+
+---
+
+### Hydrate (import on-chain agents) — `/hydrate`
+- **Source:** `public/hydrate/index.html` (self-contained inline module — no `src/` entry). NOTE: this is an on-chain agent **import** flow, not a 3D viewer/editor; it sits in this cluster only by route adjacency. Its product purpose is "attach a 3D body, voice, and skills to an existing on-chain agent."
+- **Entry point:** Inline `<script type="module">` at hydrate/index.html:334. On load, `loadAgents()` runs: `checkAuth()` (`GET /api/auth/wallets`) then `fetchDiscoveredAgents()` (`GET /api/erc8004/hydrate`).
+- **Prerequisites / gates:** **Wallet gate.** `checkAuth()` requires an authenticated session with ≥1 connected wallet; otherwise the auth prompt ("connect a wallet first" → `/dashboard/account#wallets`) is shown and no agents load (hydrate/index.html:378-417). No $THREE gate.
+- **Steps (N):**
+ 1. Arrive at `/hydrate`. `loadAgents()` runs.
+ 2. Auth/wallet check — `GET /api/auth/wallets`. If unauthenticated or no wallets → show auth prompt and stop.
+ 3. Loading state — "Fetching your agents…" while `GET /api/erc8004/hydrate` resolves the wallets' on-chain agents (hydrate/index.html:419-422).
+ 4. Discovered agents render as cards (image, name, chain badge, description, agent id) (hydrate/index.html:439-465).
+ 5. For each agent: if already imported → "Go to agent →" link to `/dashboard/?agent=<id>`; else an **Import** button.
+ 6. Click **Import** → `importAgent()` → `POST /api/erc8004/import` ({chainId, agentId}); on success the button is replaced with a "Go to agent →" link and a success alert shows (hydrate/index.html:475-491).
+- **Decision points / branches:** Authenticated+wallet vs not (auth prompt). API not running / non-JSON response → treated as unauthenticated (graceful, hydrate/index.html:389-393). Per-agent: already-imported (link) vs importable (button). Zero discovered agents → empty state.
+- **External calls / dependencies:** `GET /api/auth/wallets` (auth + wallet list), `GET /api/erc8004/hydrate` (discover on-chain agents), `POST /api/erc8004/import` (import one). No 3D asset loading on this page. Links to `/deploy`, `/dashboard/`.
+- **Success state:** Imported agent's button becomes "Go to agent →" + success alert "Successfully imported <name>!" (hydrate/index.html:487-491).
+- **Empty / error states:** Not authed / no wallets → auth prompt block. Zero agents → empty state "No on-chain agents found for your wallets." + register-at-`/deploy` hint. Discovery failure → red alert "Failed to load agents: …". Import failure → error alert from the API's `error_description`.
+- **Step count:** ~4 required (arrive → auth/wallet check → discover → import) + 0 optional (the "Go to agent" link is a navigation exit, not a step).
+
+---
+
+### Artifact Viewer (Claude artifact bundle preview) — `/artifact`
+- **Source:** `public/artifact/index.html` (self-contained inline module — no `src/` entry), backend `api/artifact`. NOTE: product purpose is "Embed your agent in Claude.ai" — it previews the standalone HTML artifact bundle that `/api/artifact` generates, not a glTF model.
+- **Entry point:** Inline `<script type="module">` at artifact/index.html:585. On load, `init()` reads `?agentId=` and, if present, auto-runs `generate()` (artifact/index.html:754-760).
+- **Prerequisites / gates:** None on the page. Validity depends on a real agent id resolving server-side at `/api/artifact`. No auth/wallet/$THREE gate on the page itself (`fetch(..., { credentials: 'omit' })`).
+- **Steps (N):**
+ 1. Arrive at `/artifact` (optionally with `?agentId=`).
+ 2. Enter an **Agent ID** (UUID or handle); optionally set theme (light), idle behavior, and a 6-hex background color (artifact/index.html:633-643).
+ 3. Click **Generate** (or Enter) → `buildUrl()` assembles `/api/artifact?agent=…&theme=…&idle=…&bg=…`, updates the address bar, and fetches the artifact HTML (artifact/index.html:652-687).
+ 4. On success: compute size, TTFP, and CSP-sandbox compliance (checks `frame-ancestors *` in the response CSP), show the stats panel (color-coded ok/warn/bad), and render the artifact via `iframe.srcdoc` (artifact/index.html:688-715).
+ 5. (optional) **Reload** re-fetches; **Copy URL**; **Copy raw HTML** (with byte size); **Open** in a new tab.
+ 6. (optional) The page fetches a reference CSP from `simonw/scrape-claude-artifacts` for the documented Claude.ai sandbox policy, with a documented fallback if unreachable (artifact/index.html:740-752).
+ 7. Copy the generated **Claude snippet** ("Here's my agent for this conversation:\n<url>") to paste into Claude.ai (artifact/index.html:713-714).
+- **Decision points / branches:** `?agentId=` present → auto-generate vs manual entry. Fetch network error vs non-OK HTTP vs success. Size/TTFP/sandbox stats branch into ok/warn/bad styling. CSP reference fetch success vs fallback copy.
+- **External calls / dependencies:** `GET /api/artifact?agent=…` (the artifact bundle, `credentials: 'omit'`); `GET` raw CSP doc from raw.githubusercontent.com (reference only). Output: the artifact HTML rendered in an iframe; copy-to-clipboard URL/HTML/snippet. No 3D file import/export.
+- **Success state:** Stats panel populated (size/TTFP/sandbox), artifact rendered in `#previewFrame`, action buttons enabled, snippet shown.
+- **Empty / error states:** Initial — "Enter an agent ID and press Generate" overlay; snippet placeholder "Generate to see the snippet…". No id → "Enter an agent ID first." error overlay. Network error → "Network error: <msg>". Non-OK → server `error_description`/`error`/`HTTP <status>` shown in the overlay. CSP fetch failure → documented fallback text.
+- **Step count:** ~3 required (arrive → enter agent id → Generate) + ~4 optional (theme/idle/bg options, reload, copy URL/HTML/snippet, open in tab).
+
+---
+
+### Avatar Artifact (standalone procedural avatar) — `/avatar-artifact`
+- **Source:** `pages/avatar-artifact.html` (fully self-contained; CDN Three.js r128 via cdnjs with SRI; no `src/` module, no model load, no API). NOTE: this is a "standalone Three.js viewer for avatar artifacts — embeddable and shareable without any wrapper page" (page OG meta). The geometry is procedurally built in-page (cylinders/spheres/boxes forming a stylized portrait), not loaded from a GLB.
+- **Entry point:** Inline `<script>` at avatar-artifact.html:271. After the CDN three.js `<script>` loads, the script guards on `window.THREE` + WebGL, then builds scene/camera/renderer/lights/materials and the procedural avatar group, and starts the `animate()` RAF loop (avatar-artifact.html:271-303, 603).
+- **Prerequisites / gates:** None. No auth, wallet, $THREE gate, model load, or API. Renders immediately on a successful runtime + WebGL context.
+- **Steps (N):**
+ 1. Arrive at `/avatar-artifact`. Loading overlay shows while the CDN three.js runtime loads.
+ 2. Runtime + WebGL guard — if three.js never arrives (`onerror`) or `window.THREE` is missing, or WebGL context creation throws, the designed error state is shown (`window.__avatarArtifactFailed`, avatar-artifact.html:257-298).
+ 3. On success the procedural avatar renders; the loading overlay fades out on first frame (avatar-artifact.html:663-669).
+ 4. Interact — the avatar's gaze follows the mouse (`mousemove`), touch drag (`touchmove`), or keyboard (arrow keys / WASD nudge the gaze; canvas is `tabIndex=0`, `role="img"`, ARIA-labeled, KEY_STEP 0.25) (avatar-artifact.html:543-589).
+ 5. The canvas continuously animates (idle motion, blink) and stays responsive to resize/orientation change (avatar-artifact.html:685-686).
+- **Decision points / branches:** Runtime available + WebGL OK (render) vs runtime/WebGL failure (error state). Coarse pointer (phones/tablets) → lighter render (lower DPR, no shadow pass, avatar-artifact.html:286-302). Pointer/touch input vs keyboard gaze control.
+- **External calls / dependencies:** CDN `three.min.js` r128 from cdnjs (with SRI integrity + `crossorigin`); `/api/page-og` for OG/Twitter share images (meta only). No model import/export, no platform API, no glTF validator.
+- **Success state:** Animated procedural avatar that tracks cursor/touch/keys; loading overlay faded out.
+- **Empty / error states:** Loading overlay (`#loading`) during runtime load; designed error overlay (`#error`) when the CDN runtime fails or WebGL is unavailable. No empty "no model" state — the avatar is always present once the runtime loads.
+- **Step count:** ~3 required (arrive → runtime/WebGL OK → avatar renders) + ~1 optional (interact via cursor/touch/keyboard).
diff --git a/docs/ux-flows/04-embed-widget-studio.md b/docs/ux-flows/04-embed-widget-studio.md
new file mode 100644
index 000000000..b9c90a370
--- /dev/null
+++ b/docs/ux-flows/04-embed-widget-studio.md
@@ -0,0 +1,169 @@
+# Embed, Widget & Studio
+
+UX Flow Atlas — Cluster 04. Traced end-to-end against real source in `/workspaces/three.ws`.
+
+Routing recap (from `vercel.json`):
+
+| Route | Serves |
+|---|---|
+| `/studio`, `/studio/` | `public/studio/index.html` (+ `studio.js`, `studio.css`, `launch-panel.js`, `knowledge-panel.js`) — **Widget Studio** |
+| `/widgets`, `/widgets/` | `public/widgets-gallery/index.html` (+ `gallery.js`, `showcase.json`) — **Widgets Gallery** |
+| `/features/studio` | `pages/features/studio.html` — marketing/feature landing for the Studio |
+| `/artifact`, `/artifact/` | `public/artifact/index.html` — **Claude.ai Artifact builder** |
+| `/avatar-studio`, `/create/studio` | `pages/avatar-studio.html` (+ `src/avatar-studio.js`) — **Avatar Studio** (appearance builder; feeds the embed flows) |
+| `/w/<id>` | saved widget page (live widget) |
+| `/widget`, `/widget.html` | slim viewer shell (`/src/app.js`) used as Studio/gallery preview iframe + script-tag embed target |
+| `/agent/<id>/embed`, `/embed/avatar/<handle>`, `/embed`, `/a-embed.html` | embed iframe targets |
+| `/embed.js`, `/embed-sdk.js`, `/artifact.js`, `/dist-lib/agent-3d.js` | embed loader / SDK / web-component scripts |
+
+> Naming note: the prompt's "avatar-studio embeddable AI widget builder" maps to the **Widget Studio** at `/studio` (the talking-agent widget type is the embeddable AI widget). `/avatar-studio` is the **appearance builder** — it produces the avatar that the Studio and embed panels then wrap. Both are documented below.
+
+---
+
+### Widget Studio — `/studio`
+- **Source:** `public/studio/index.html`, `public/studio/studio.js`, `public/studio/studio.css`, `public/studio/launch-panel.js`, `public/studio/knowledge-panel.js`. Preview iframe loads `/widget` (slim `src/app.js` shell). APIs: `/api/auth/me`, `/api/avatars`, `/api/avatars/public`, `/api/avatars/:id`, `/api/widgets`.
+- **Entry point:** Direct nav to `/studio`; "Create yours" / "Open the Studio" CTAs on `/widgets`; "Open Studio →" on `/features/studio`; "Open in Studio" links from gallery cards (`/studio?template=<id>`); deep links `?edit=<id>`, `?type=<type>`, `?model=<url>`, `?avatar=<id>`.
+- **Prerequisites / gates:** None to try — a built-in **demo avatar (CZ, `/avatars/cz.glb`)** is preloaded so an anonymous visitor can configure and preview. **Saving a draft / embedding a non-demo avatar requires sign-in** (`/login?next=/studio`) and an owned/public avatar. The demo avatar can generate an embed (pointing at a baked demo fixture, e.g. `wdgt_demo_talking`) but cannot save. No $THREE gate. ⚡ Launch tab can optionally launch the agent's coin via `launch-panel.js`.
+- **Steps (10):**
+ 1. Page boots → `fetchMe()` (`/api/auth/me`) resolves user; user menu renders (signed-out shows "Sign in"); 3-column layout unhides.
+ 2. System renders the **widget-type grid** (9 ready types: turntable, animation-gallery, talking-agent, passport, hotspot-tour, pumpfun-feed, kol-trades, live-trades-canvas, bonding-curve) and **avatar list** (`loadAvatars()` → demo avatar + `/api/avatars?limit=100` for signed-in users, with skeleton cards while loading).
+ 3. **Pick avatar** (step-1 panel): click an avatar card → `selectAvatar()`; or `(optional)` search public avatars (`/api/avatars/public?q=`) and pick one; demo avatar is selected automatically if none chosen.
+ 4. **Pick widget type** (step-2 panel): click a type card → `selectType()` rebuilds the type-specific config fields, preserving brand settings.
+ 5. System loads the **live preview** in the `/widget` iframe (`updatePreview()` builds `#model=…&kiosk=true&type=…`), posts the config via `postMessage({type:'widget:config'})`; status flips to "Live preview".
+ 6. **Configure Brand** (step-3): name, background color, accent, optional caption, show-controls, auto-rotate, environment preset, public toggle — every input debounces (`schedulePreview`, 200 ms) and re-posts config to the preview.
+ 7. `(optional)` **Configure type fields**: e.g. talking-agent gets agent name/title, greeting, system prompt, LLM provider (Anthropic/OpenAI/watsonx/Groq/OpenRouter/custom proxy), skills, voice in/out, rate limits, and a **Knowledge panel** (RAG docs) once saved; passport gets chain/agentId/wallet; mint-based types get a Solana mint address.
+ 8. `(optional)` **Frame the camera**: drag in the preview, click "Use current view" → reads `previewIfr.contentWindow.VIEWER.viewer.activeCamera`, stores `cameraPosition`. `(optional)` switch device frame (desktop/tablet/mobile).
+ 9. `(optional)` **Save draft** → POST/PATCH `/api/widgets` (requires sign-in + name); URL gets `?edit=<id>`, "View live" (`/w/<id>`) + "Delete" actions appear.
+ 10. **Generate embed** → saves (or, for demo avatar, resolves the baked fixture) then opens the **embed modal**: shareable URL `/w/<id>`, width/height inputs, per-type include toggles (animations / chat / controls), **iframe snippet**, and a **script-tag snippet** (`<script async src="/embed.js" data-widget="<id>">`). Copy → paste on any site. Done.
+- **Decision points / branches:**
+ - Demo avatar → embed allowed (baked fixture, tweaks not saved, modal shows "upload your own" note) but save blocked.
+ - Signed-out + non-demo save/generate → redirect to `/login?next=…`.
+ - `?edit=<id>` → `loadForEdit()` hydrates an existing widget (PATCH on save). `?template=<id>` → `cloneTemplate()` (config copied, avatar must be re-picked, POST creates new). `?model=<url>` / `?avatar=<id>` → preselect / auto-register R2 model (`autoRegisterAndSelect` HEADs the GLB then POSTs `/api/avatars`).
+ - Embed-modal include toggles add `noAnimations=1` / `noChat=1` / `noControls=1` to the URL.
+ - Right column tabs: **Brand** ↔ **⚡ Launch** (launch panel hides save/generate row).
+- **External calls / dependencies:** `/api/auth/me`, `/api/auth/logout`, `/api/avatars`, `/api/avatars/public`, `/api/avatars/:id` (POST to register), `/api/widgets` (GET/POST/PATCH/DELETE), preview iframe `/widget#…`, embed loader `/embed.js`, share/live `/w/<id>`, `/api/widgets/:id/og` (poster). Importmap loads `@solana/web3.js` + `@solana/spl-token` from esm.sh for the Launch tab.
+- **Success state:** Embed modal open with a copyable iframe + script snippet and a live shareable `/w/<id>` URL; "View live" opens it in a new tab. Toast "Saved" on draft save.
+- **Empty / error states:** No avatars → empty card with "Scan yourself to 3D →" / "AI selfie →". Avatar load failure → inline error card with **Retry**. Public search failure → status line shows reason. Save failure → `#form-error` text. Preview without a model → "Avatar has no public URL — make it public/unlisted to preview". Pre-selected avatar missing → toast + falls back to demo. Pending-status types show a "ships in a later prompt" banner (currently none — all 9 are `ready`).
+- **Step count:** 10 required (+5 optional)
+
+---
+
+### Widgets Gallery — `/widgets`
+- **Source:** `public/widgets-gallery/index.html`, `public/widgets-gallery/gallery.js`, `public/widgets-gallery/gallery.css`, `public/widgets-gallery/showcase.json`. Card iframes load `/widget#widget=<id>&kiosk=true…`.
+- **Entry point:** Direct nav to `/widgets`; nav links ("Widgets") across Studio/footer; `/features/studio`.
+- **Prerequisites / gates:** None. Fully public, read-only browsing. No auth, no avatar, no $THREE gate.
+- **Steps (6):**
+ 1. Page loads → 3 skeleton cards render (`showSkeleton`).
+ 2. `fetch('/widgets-gallery/showcase.json')` → builds **filter chips** (one per widget type + "All"), updates hero count, renders one **showcase card** per widget; cards fade in on scroll (IntersectionObserver).
+ 3. Each card auto-loads its preview iframe when 50% visible (or via the ▶ play button); `(optional)` toggle **Preview ↔ Code** tab to see the snippet in the frame area.
+ 4. **Customize** `(optional)`: open the Customize `<details>` and adjust Size (S/M/L), Accent color, and per-type knobs (mint for kol-trades/live-trades-canvas, kind for pumpfun-feed). Snippet + iframe update live (debounced 350 ms reload); "Reset" restores defaults.
+ 5. **Copy embed**: split-button copies the current snippet; `(optional)` use the format dropdown to switch **HTML iframe / JSX (React) / Share URL** before copying. Button flips to "Copied!".
+ 6. Paste the snippet on any site → renders the live widget. Done. (Or click **"Open in Studio"** → `/studio?template=<id>` to clone & customize fully — branches into the Widget Studio flow.)
+- **Decision points / branches:**
+ - Format dropdown: iframe (HTML), JSX (React inline-style iframe), URL.
+ - Customized state (size≠M, custom accent, non-default mint/kind) makes the "Share URL" output the `/widget#…` hash form (preserves overrides) instead of `/w/<id>`.
+ - Filter chips show/hide cards by type and re-index for the stagger animation.
+ - Preview iframe uses `reveal=interaction` + a `/api/widgets/<id>/og` poster to keep WebGL slots free on a dense page.
+- **External calls / dependencies:** `/widgets-gallery/showcase.json`, preview iframes at `/widget#widget=<id>…`, `/api/widgets/<id>/og` (poster), model-viewer 4.0.0 (footer avatar, from googleapis CDN with SRI). Mints used in defaults are SOL wrapped-mint and the `$THREE` CA.
+- **Success state:** Snippet copied to clipboard ("Copied!"); live preview rendered in card.
+- **Empty / error states:** Showcase fetch failure → error card "Could not load showcase config." with detail. Per-card iframe failure leaves the placeholder/play button. Hero count defaults to 8 in static HTML, overwritten by real count.
+- **Step count:** 6 required (+3 optional)
+
+---
+
+### Studio feature landing — `/features/studio`
+- **Source:** `pages/features/studio.html` (static marketing page; `style.css`, `nav.css`, `features-landing.css`). No JS module of its own.
+- **Entry point:** `/features` hub, marketing links, search/SEO. Title: "Studio — Build an Embeddable 3D AI Widget".
+- **Prerequisites / gates:** None (public marketing).
+- **Steps (2):**
+ 1. Visitor reads the value prop ("One script tag. 3D AI on any site.") and feature copy (configure avatar, voice, knowledge, tools).
+ 2. Click a CTA — **"Open Studio →"** (→ `/studio`, two on the page) or **"Deploy on-chain instead"** (→ `/features/deploy`) or "All features" (→ `/features`). Branches into the Widget Studio flow.
+- **Decision points / branches:** Open Studio vs. Deploy on-chain vs. browse all features.
+- **External calls / dependencies:** None at runtime beyond static assets + `/api/feature-og` for OG image.
+- **Success state:** User lands in `/studio`.
+- **Empty / error states:** N/A (static).
+- **Step count:** 2 required (+0 optional)
+
+---
+
+### Claude.ai Artifact builder — `/artifact`
+- **Source:** `public/artifact/index.html` (self-contained, inline module script), `public/artifact/README.md`, `public/artifact/snippet.html`. Backend: `GET /api/artifact` (returns one self-contained HTML doc; see `specs/CLAUDE_ARTIFACT.md`). Also a `/artifact.js` loader script for in-artifact `<div data-agent-id>` mounting.
+- **Entry point:** Direct nav to `/artifact`; deep link `?agentId=<id>` (auto-generates on load).
+- **Prerequisites / gates:** None to use the builder. To produce a working artifact you need a valid **agent ID/handle** (or whitelisted-CDN `model` URL). GLB must be **≤ 6 MB** (server returns 413 otherwise). No auth/$THREE gate on the page itself.
+- **Steps (6):**
+ 1. Visitor lands; the page fetches and shows the live Claude sandbox CSP (`raw.githubusercontent.com/simonw/scrape-claude-artifacts/…`) in a `<details>`.
+ 2. **Configure**: enter Agent ID; `(optional)` set Theme (dark/light), Idle clip name, Background hex.
+ 3. Click **Generate** (or Enter) → `buildUrl()` assembles `/api/artifact?agent=…&theme=…&idle=…&bg=…`; overlay shows "Fetching artifact…"; `history.replaceState` adds `?agentId=`.
+ 4. System fetches the artifact HTML, measures size + first-paint, checks the response CSP for `frame-ancestors *`, and renders it into a **sandboxed iframe** (`sandbox="allow-scripts"`, `srcdoc`). Stats panel fills in (Artifact size ok/warn/bad, First paint, Sandbox compliant/mismatch).
+ 5. **Copy** the result: **Copy URL** (the `/api/artifact?…` link), **Copy raw HTML** (the full self-contained doc), or **Open in tab**; `(optional)` expand the "Paste-into-Claude snippet" (`Here's my agent for this conversation:\n<url>`).
+ 6. Paste the URL into a Claude.ai conversation → Claude embeds the artifact and the 3D avatar renders inline (zero external fetches, CSP-compliant). Done.
+- **Decision points / branches:**
+ - `agent` vs. `model` source (README); theme/idle/bg are optional refinements.
+ - Size thresholds: >5 MB = warn, >8 MB = bad (server caps at 6 MB → 413).
+ - Two consumption paths: paste the **URL** directly, or paste the **raw HTML** / use the `/artifact.js` `<div data-agent-id>` snippet inside an existing artifact.
+- **External calls / dependencies:** `GET /api/artifact` (the bundle), Claude CSP mirror at `raw.githubusercontent.com/simonw/scrape-claude-artifacts/main/content-security-policy.txt`. Artifact bundle inlines three.js + GLTFLoader + GLB (~565 KB viewer overhead) — no runtime fetch.
+- **Success state:** Live preview renders in the CSP-mirrored sandbox; stats show "compliant"; URL/HTML copied.
+- **Empty / error states:** No agent ID → overlay "Enter an agent ID first." Network error / non-OK → overlay shows `error_description`/HTTP status. CSP mirror unreachable → falls back to a note pointing at `specs/CLAUDE_ARTIFACT.md`. Sandbox mismatch → stat shows "mismatch" (bad).
+- **Step count:** 6 required (+2 optional)
+
+---
+
+### Agent embed snippet (SharePanel / `<agent-3d>`) — share/embed panel flow
+- **Source:** `src/share-panel.js` (`SharePanel` class) + `src/share-panel-builders.js` (`buildEmbedUrl`, `buildIframeSnippet`, `buildWebComponentSnippet`) + `src/share-panel.css`. Mounted on the agent home page via `src/agent-home-orphans.js`; also referenced from `src/agent-detail.js` and `src/forge.js`. Embed targets: `/agent/<id>/embed` (CSP `frame-ancestors *`), web component `/dist-lib/agent-3d.js`. Preview iframe = same `/agent/<id>/embed?preview=1`.
+- **Entry point:** **Share** button on an agent profile/home page (`agent-home-orphans.js` injects it next to the title) → `new SharePanel({ agent }).open()`.
+- **Prerequisites / gates:** Must be on an **existing agent** (an `agent.id`/`slug`). No sign-in required to copy snippets — embedding is free ("no wallet or on-chain deployment required"). No $THREE gate.
+- **Steps (6):**
+ 1. Click **Share** → modal opens with the agent's permalink `/a/<slug|id>`, a live preview iframe, and pre-rendered snippets.
+ 2. `(optional)` **Copy link** or **Open ↗** the agent permalink.
+ 3. **Customise embed** `(optional)`: Background (transparent/dark/light), Name plate (on/off), Size (small 320×420 / medium 420×520 / large 520×680). Each toggle re-renders the snippets and reloads the live preview (`?preview=1` bypasses the embed origin allow-list).
+ 4. Choose a format and **Copy**: **iframe embed** (`<iframe src="/agent/<id>/embed?…">`) or **Web component** (`<script src="/dist-lib/agent-3d.js">` + `<agent-3d agent-id="…" background=… name-plate=off>`). Button flips to "Copied ✓".
+ 5. `(optional)` **OG preview** + copy the `/api/a-og?id=<id>` card URL; **QR code** of the permalink is rendered (canvas, SVG fallback).
+ 6. Paste the iframe or `<agent-3d>` snippet on any third-party site → the agent renders inline (the `/agent/<id>/embed` page runs `src/avatar-embed.js` / element runtime, exposing the `v1.avatar.*` postMessage bridge). Done.
+- **Decision points / branches:**
+ - iframe vs. web-component snippet (web component observes `background` / `name-plate` attrs).
+ - Default options (transparent bg, name on, medium) are omitted from the URL to keep it canonical/short.
+ - Separate, simpler embed entry points exist: **Agent Hub** "Embed" button → `AgentEmbedModal` (`src/agent-embed-modal.js`, iframe / `<agent-3d>` / SDK tabs with width×height); **Dashboard** avatar/agent "Embed" → `openAvatarEmbedModal` (`src/dashboard/dashboard.js`, `/a-embed.html?avatar=<id>` with size/bg/name presets). See variants below.
+- **External calls / dependencies:** `/agent/<id>/embed` (preview + final), `/dist-lib/agent-3d.js` (web component), `/api/a-og?id=<id>` (OG image), `/a/<slug|id>` (permalink). QR rendered locally (`src/erc8004/qr.js`).
+- **Success state:** Snippet copied ("Copied ✓"); live preview shows the agent in the chosen size/bg.
+- **Empty / error states:** Preview iframe failure leaves the framed area blank with the chosen bg color visible; OG image alt text shown if it fails to load; QR falls back canvas → SVG → plain link text.
+- **Step count:** 6 required (+3 optional)
+
+#### Variant — Agent Hub embed modal (`AgentEmbedModal`)
+- **Source:** `src/agent-embed-modal.js`, triggered from `src/agent-hub-actions.js` (hub "Embed" button) and `src/dashboard/dashboard.js` (`openAgentEmbedModal`).
+- **Steps (4):** (1) Click "Embed" on the agent hub → modal opens (default 420×520). (2) `(optional)` adjust Width/Height. (3) Switch tab: **iframe** (`/agent/<id>/embed`), **`<agent-3d>`** (`/dist-lib/agent-3d.js` web component), or **SDK** (`/embed-sdk.js` + `Agent3D.connect()` bridge example). (4) **Copy** → paste on site. Snippets are pure-string built from `origin` + `id` + `w` + `h`; note: "Free to embed — no wallet or on-chain deployment required."
+- **Step count:** 4 required (+1 optional)
+
+#### Variant — Dashboard avatar embed (`openAvatarEmbedModal`)
+- **Source:** `src/dashboard/dashboard.js` (`openAvatarEmbedModal`), embed target `/a-embed.html?avatar=<id>` (runtime `src/avatar-embed.js`).
+- **Steps (4):** (1) From the dashboard avatar/agent list click "Embed" (agent path requires a linked `avatar_id`, else toast "Link an avatar to the agent first"). (2) Pick a size preset (Square 480² / Portrait 360×540 / Banner 1200×400 / Custom W×H). (3) Set Background (transparent/dark/light) + name-plate + open-link toggles. (4) Copy the generated `/a-embed.html?avatar=…` iframe → paste. Builds `?bg=…&name=0&open-link=0` deviations from defaults.
+- **Step count:** 4 required (+0 optional)
+
+---
+
+### Avatar Studio (appearance builder) — `/avatar-studio` · `/create/studio`
+- **Source:** `pages/avatar-studio.html`, `src/avatar-studio.js` (+ `avatar-studio-utils.js`, `avatar-studio-optimize.js`, `avatar-sculpt.js`, `voice/talk-scene.js`, `agent-accessories.js`, `idle-animation.js`, `account.js`). Title: "Avatar Studio". Save path: `account.js` → `/api/avatars` (+ GLTFExporter snapshot upload).
+- **Entry point:** `/avatar-studio` or `/create/studio` (create from `default.glb`); `?edit=<id>` reloads a saved avatar.
+- **Prerequisites / gates:** Anyone can build/preview from the base template. **Saving requires sign-in** (so it persists to the account). No $THREE gate. This is the *upstream* builder — the avatar it produces becomes selectable in Widget Studio and embeddable via the SharePanel/embed modals.
+- **Steps (7):**
+ 1. Page boots → loads `BASE_GLB_URL` (`/avatars/default.glb`) into a `TalkScene` viewport with idle breathing/blinking; accessory presets load.
+ 2. `(optional)` In **edit mode** (`?edit=<id>`) the saved appearance (colors/morphs/accessories/hidden layers) is hydrated onto the model.
+ 3. **Customize**: switch tabs — Color (skin/hair/outfit swatches + hex), Hats, Glasses, Earrings (accessory presets), Face (sculpt morphs). Each change applies live to the scene graph; `(optional)` undo/redo (history up to 50).
+ 4. `(optional)` Show/hide garment layers; `(optional)` search accessories.
+ 5. **Save** → exports the live scene via GLTFExporter (colors/morphs/accessories already baked), optimizes/validates the GLB (`avatar-studio-optimize.js`), uploads via `account.js` (`/api/avatars`), and PATCHes the appearance JSON so it stays re-editable; uploads a snapshot thumbnail.
+ 6. The saved avatar now appears in the avatar library used by **Widget Studio** (`/studio` step 3) and the **embed/share panels**.
+ 7. Continue into an embed flow: open Widget Studio, the agent SharePanel, or a dashboard embed modal to generate the snippet. Done.
+- **Decision points / branches:** Create (from default) vs. Edit (`?edit=<id>`). Single-select tabs (hat/glasses) vs. multi (earrings). Save requires auth → otherwise prompts sign-in.
+- **External calls / dependencies:** `/avatars/default.glb`, accessory preset assets, `/api/avatars` (save/PATCH), avatar-snapshot upload, GLTFExporter. Hands off to `/studio`, SharePanel (`/agent/<id>/embed`), or `/a-embed.html`.
+- **Success state:** Avatar saved to account, re-editable, and selectable in the embed/Studio flows.
+- **Empty / error states:** Queued ops swallow + log failures (`queueOp`); GLB validation/optimize failures surface in the save path; signed-out save routes to login. Unsaved-changes tracking via `appearanceEqual`.
+- **Step count:** 7 required (+4 optional)
+
+---
+
+## Cross-flow notes
+- **`/widget` shell** is the shared render surface: Studio + gallery previews and the `/embed.js` script-tag embed all point at `/widget#widget=<id>&kiosk=true`.
+- **`embed.js`** (`public/embed.js`) is the script-tag loader: reads `data-widget` / `data-widget-url`, `data-width/height/radius/border`, `data-reveal`, `data-poster`, `data-priority`, `data-motion`, mounts a sandboxed iframe at the script position, and supports multiple embeds per page.
+- **Web component `<agent-3d>`** (`/dist-lib/agent-3d.js`) is the first-class embedding primitive surfaced by SharePanel and AgentEmbedModal; it observes `agent-id`, `background`, `name-plate` attributes.
+- **avatar-embed runtime** (`src/avatar-embed.js`) backs `/embed/avatar/<handle>`, `/a-embed.html`, and the agent embed; exposes the `v1.avatar.*` postMessage bridge (speak, emote, morphs, lookAt, mocap, idle, hotkeys, mic, state) plus RPM-compatible event aliases and a same-origin BroadcastChannel control surface.
+</content>
+</invoke>
diff --git a/docs/ux-flows/05-discovery-social.md b/docs/ux-flows/05-discovery-social.md
new file mode 100644
index 000000000..7b8780f70
--- /dev/null
+++ b/docs/ux-flows/05-discovery-social.md
@@ -0,0 +1,264 @@
+# Discovery & Social
+
+UX Flow Atlas — cluster "Discovery & Social". Each entry traces the real source end-to-end, from page entry to the feature's payoff.
+
+Routing recap (from `vercel.json`):
+
+| Route | Page HTML | Entry module |
+|---|---|---|
+| `/discover` | `public/discover/index.html` | `public/discover/discover.js` |
+| `/gallery` | `public/gallery/index.html` | `public/gallery/gallery.js` |
+| `/animations` | `pages/animations.html` | `src/animations-gallery.js` |
+| `/characters` | `public/characters.html` | `src/characters.js` |
+| `/community` | `pages/community.html` | (static content) |
+| `/walk` | `pages/walk.html` | `src/walk.js` (+ `src/community/coin-world-boot.js`) |
+| `/irl` | `pages/irl.html` | `src/irl.js` (+ `src/irl/*`, `src/irl-net.js`) |
+| `/irl-privacy` | `pages/irl-privacy.html` | (static content) |
+| `/reputation` | `public/reputation/index.html` | `public/reputation/reputation.js` |
+| `/lookup` | `public/lookup.html` | inline module in page |
+| `/agents` | `public/agents/index.html` | inline module in page |
+| `/my-agents` | `public/my-agents/index.html` | inline module in page |
+| `/sitemap` | `public/sitemap/index.html` | inline filter script in page |
+
+---
+
+### Discover — `/discover`
+- **Source:** `public/discover/index.html`, `public/discover/discover.js`, `public/discover/detail.{html,js,css}` (detail), `/api/explore`, `/api/discover-detail` (rewrite target for `/discover/a/...`)
+- **Entry point:** Page load auto-calls `loadPage()`. URL params hydrate filters (`?q=`, `?chain=`, `?source=`, `?only3d=`, `?sort=`). Default view (no params) is **3D-only**.
+- **Prerequisites / gates:** None to browse. Auth (`/api/auth/me`) only reveals the "View my agents" chip + nav link; no gate.
+- **Steps (8):**
+ 1. User lands on `/discover`. System fetches `/api/auth/me` (best effort) to maybe show the my-agents chip, populates the chain `<select>` (22 chains), reflects any URL params in controls, renders 12 skeleton cards, and calls `loadPage()`.
+ 2. System fetches `GET /api/explore?only3d=1&limit=48` (params from state), clears skeletons, renders cards (onchain / avatar / solana variants). Each card thumbnail prefers static image, else lazy `<model-viewer>` auto-rotate preview, else emoji. First page also renders directory totals.
+ 3. (optional) User types in the search box → 250ms debounce → `syncUrl()` + `resetAndLoad()` re-queries with `q`.
+ 4. (optional) User clicks a source filter (All / On-chain / Avatar / Solana) or the 3D / x402 filter chip → state updates, URL synced, grid reloads. x402 + sort overlays applied client-side.
+ 5. (optional) User picks a chain in the dropdown → reloads filtered to that chain.
+ 6. (optional) User scrolls; IntersectionObserver sentinel (`480px` rootMargin) auto-loads the next cursor page, or user clicks "Load more".
+ 7. (optional) User clicks a card's "Embed" button → embed modal opens with tabs (Web component / iframe / Link / Markdown / Farcaster), copy buttons; or "URI" button copies `agent://<chain>/<id>`.
+ 8. **Payoff:** User clicks a card → navigates to detail (`/discover/a/<chain>/<id>`, `/discover/a/sol/<asset>`, served by `/api/discover-detail`) or "View 3D" → opens the GLB viewer.
+- **Decision points / branches:** card kind (onchain / avatar / solana → different render + detail URL); 3D-only default vs `only3d=0` firehose; signed-in (chip shown) vs not; IntersectionObserver present vs manual button.
+- **External calls / dependencies:** `GET /api/explore`, `GET /api/auth/me`, `/api/discover-detail` (detail nav), `model-viewer` CDN, clipboard API.
+- **Success state:** Grid of agent cards with live/static thumbnails + totals line; deep-linkable filtered view via `replaceState`.
+- **Empty / error states:** Filtered-empty → "No agents match these filters yet" + Clear filters button. Unfiltered-empty → "No agents indexed yet… forge a 3D model." Fetch error → inline error with Retry button.
+- **Step count:** 2 required (+6 optional)
+
+---
+
+### Avatar Gallery — `/gallery`
+- **Source:** `public/gallery/index.html`, `public/gallery/gallery.js`, `public/gallery/gallery.css`, `/api/avatars/public`, `/api/forge-gallery`, `/api/avatars` (equip modal)
+- **Entry point:** Page load calls `renderCats()` then `resetAndLoad()`, then `loadForgeSection()`. Filters hydrate from URL (`?q=`, `?category=`, `?tag=`, `?sort=`).
+- **Prerequisites / gates:** None to browse. Auth (`/api/auth/me`) only reveals the "My avatars" chip. Equipping an accessory requires sign-in (gated inside the equip modal via `/api/avatars` 401).
+- **Steps (8):**
+ 1. User lands on `/gallery`. System fetches `/api/auth/me` (chip), renders 8 skeleton cards, calls `loadPage()`.
+ 2. System fetches `GET /api/avatars/public?limit=24&totals=1`, renders cards. Each thumbnail is a lazy auto-rotating `<model-viewer>` (poster = thumbnail) or an `<img>`. Tag chips, onchain badge, fork count rendered. Stat count + tag/category filter rows populated.
+ 3. (optional) Search box → 250ms debounce → reload with `q`.
+ 4. (optional) Click a category chip (Avatars / Accessories / Items / Scenes / Creatures) or a tag chip → reload filtered. Sort dropdown (newest / alpha) re-sorts.
+ 5. (optional) Scroll → IntersectionObserver auto-loads next cursor page, or "Load more" button.
+ 6. (optional) Click "Embed" on a card → avatar embed modal (Web component / iframe / Link / Markdown tabs, copy buttons).
+ 7. (optional) For accessory cards, click "Equip" → modal fetches `GET /api/avatars` (user's own); if 401, shows Sign-in CTA; else lists up to 12 avatars; choosing one navigates to `/avatars/:id/edit?equip-glb=…&equip-bone=Head`.
+ 8. **Payoff:** Click a card thumbnail → `/app#model=<glb>` (3D viewer); or "Use" → `/studio?avatar=<id>`; or "Animate" → `/pose?avatar=<id>`; or "View avatar" → `/avatars/<id>`. Below the grid, the **From the Forge** section renders community 3D models (`GET /api/forge-gallery?scope=community&limit=16`, deduped by prompt) with View/Remix actions.
+- **Decision points / branches:** accessory category → Equip flow vs Use/Animate; model_url present → model-viewer vs img; signed-in chip; forge section enabled vs hidden (additive, never blocks).
+- **External calls / dependencies:** `GET /api/avatars/public`, `GET /api/forge-gallery`, `GET /api/avatars` (equip), `GET /api/auth/me`, `model-viewer` CDN, `onchain-badge.js`, `template-picker.js`, clipboard API.
+- **Success state:** Grid of 3D avatar cards + total count + Forge community section.
+- **Empty / error states:** Filtered-empty → "No public avatars match your filters" + Clear filters + Upload CTA. Unfiltered-empty → "No public avatars yet" + Create-from-prompt / dashboard CTAs. Fetch error → "Failed to load avatars: <msg>". Forge section errors swallowed silently.
+- **Step count:** 2 required (+6 optional)
+
+---
+
+### Animation Gallery — `/animations`
+- **Source:** `pages/animations.html`, `src/animations-gallery.js`, `/api/animations/clips`, `/avatar-embed` (preview iframe), `/pose` (studio)
+- **Entry point:** Module runs `load(true)` on import. Query (`?q=`, `?filter=loop|once`) hydrates state and the search box.
+- **Prerequisites / gates:** None. Clips fetched with `credentials: 'include'` but public visibility is the query; no sign-in required to browse.
+- **Steps (5):**
+ 1. User lands on `/animations`. System shows loading state, calls `load(true)`.
+ 2. System fetches `GET /api/animations/clips?include_public=true&visibility=public&limit=24`, renders animation cards (thumbnail or 🎬 placeholder, loop/once badge, duration, optional price/tags).
+ 3. (optional) User types in search → 280ms debounce → `syncUrl()` + reload; or clicks a filter chip (loop / once) mapping to `kind=loop|animation`.
+ 4. (optional) User hovers/clicks/keys a card's preview zone → lazy-loads an `<iframe>` to `/avatar-embed?model=/avatars/cz.glb&anim=<id>` playing the clip on a live avatar; mouseleave hides it. Scroll sentinel infinite-loads more.
+ 5. **Payoff:** User clicks "Open in Studio" (or the implicit "use on my avatar") → navigates to `/pose?anim=<id>` to apply/remix the clip on an avatar.
+- **Decision points / branches:** thumbnail present vs placeholder; loop vs once filter (kind param); IntersectionObserver vs Load-more button; search/filter active → empty-search state.
+- **External calls / dependencies:** `GET /api/animations/clips`, `/avatar-embed` iframe (sandboxed), `/pose` nav.
+- **Success state:** Grid of animation cards each previewable in-place on a live avatar; "Open in Studio" reaches the editor.
+- **Empty / error states:** No results + no filter → empty state; with filter/query → empty-search state with the query echoed + Clear-search; fetch failure → error state with Retry.
+- **Step count:** 2 required (+3 optional)
+
+---
+
+### Characters — `/characters`
+- **Source:** `public/characters.html`, `src/characters.js`, `/api/characters`, links to `/character/:id`
+- **Entry point:** `init()` runs on import → calls `fetchCharacters(true)`.
+- **Prerequisites / gates:** None.
+- **Steps (4):**
+ 1. User lands on `/characters`. System renders 6 skeleton cards and fetches `GET /api/characters?limit=24&sort=new`.
+ 2. System renders character cards: avatar image (or color-hash placeholder), creator handle, description, chat-count / holders stats, optional `$`token block (symbol, market cap, 24h change), and a wallet chip if the character has a Solana address (`walletChipHTML`).
+ 3. (optional) User types in search → 300ms debounce → reload with `q`; or clicks a sort button (`data-sort`) → reload; or clicks "Load more" → paginates by cursor.
+ 4. **Payoff:** User clicks a card → navigates to `/character/:id` (character detail / chat).
+- **Decision points / branches:** has token block vs not; has Solana address → wallet chip; image URL valid http(s) vs placeholder; reset vs append render.
+- **External calls / dependencies:** `GET /api/characters`, `walletChipHTML` from `src/shared/agent-wallet-chip.js`.
+- **Success state:** Grid of character cards each linking to its detail page.
+- **Empty / error states:** Empty → "No characters found." Fetch error → "Failed to load characters. Please try again."
+- **Step count:** 1 required (+3 optional)
+
+---
+
+### Community — `/community`
+- **Source:** `pages/community.html` (static content + footer newsletter)
+- **Entry point:** Static page load. Read-only content page.
+- **Prerequisites / gates:** None.
+- **Steps (3):**
+ 1. User lands on `/community` and reads the hero ("Build with us.").
+ 2. (optional) User clicks a channel card: Follow on X (`@trythreews`), GitHub (`nirholas/three.ws`), Docs (`/docs`), Tutorials (`/tutorials`).
+ 3. (optional) User reads "Ways to get involved" (ship an agent at `/create`, report bugs on GitHub issues, share feedback to `[email protected]`) or subscribes via the footer newsletter form.
+- **Decision points / branches:** which outbound channel the user follows; newsletter subscribe vs not.
+- **External calls / dependencies:** External links (x.com, github.com), mailto, `footer-newsletter.js` (subscribe). No data fetch for content.
+- **Success state:** User reaches a community channel / submits the newsletter form.
+- **Empty / error states:** None (static content). Newsletter form handles its own submit feedback.
+- **Step count:** 1 required (+2 optional) — content page (read)
+
+---
+
+### Walk — `/walk`
+- **Source:** `pages/walk.html` (inline boot), `src/walk.js`, `src/community/coin-world-boot.js`
+- **Entry point:** `/src/walk.js` loaded as module. Splash overlay "Loading avatar…" shows while the scene boots. URL params: `?avatar=`, `?avatarUrl=`, `?name=`, `?coin=`, `?ui=hidden`, `?handle=`, `?agent=`.
+- **Prerequisites / gates:** None to play (solo mode works offline). **Camera permission** requested only on AR-button tap (`navigator.mediaDevices.getUserMedia`, not on load). Auth only needed to list personal avatars in the picker. No motion/geolocation. WebGL required for full render.
+- **Steps (6 required + many optional):**
+ 1. Page loads → avatar resolves (`?avatarUrl` direct, else `GET /api/avatars/{id}` for `?avatar`, else `/avatars/default.glb`); GLB loads via GLTFLoader; `GET /animations/manifest.json` preloads idle/walk/run; splash fades; status pill "Ready — drag to look around"; cosmetics + emote tray applied; Rapier physics WASM inits async (legacy movement until ready); multiplayer `startNet()` joins the Colyseus room best-effort.
+ 2. **Payoff (move):** On desktop, press **W/A/S/D / arrows** (Shift = run) to walk the avatar camera-relative; on mobile, drag the **left joystick** (nipplejs). Animation crossfades idle→walk→run to actual ground speed.
+ 3. Orbit camera — drag mouse / pointer-lock (desktop) or the right look-stick (mobile); scroll/pinch to zoom; Q/E snap-turn 45°.
+ 4. (optional) Set player name (`#walk-name-input`, persisted, broadcast); open Avatar picker → `GET /api/avatars?limit=20` (auth) → choose avatar (broadcast to room).
+ 5. (optional) Jump (Space / button), cycle camera mode C (follow/cinematic/firstperson/topdown), cycle environment V (rebuilds physics colliders), emote G + 1–9 (broadcast), minimap M, chat T/Enter (broadcast bubble), friends F, players-panel.
+ 6. (optional) **AR passthrough:** tap AR button/CTA → `getUserMedia({ video: { facingMode: { ideal: 'environment' } } })`; on grant the canvas goes transparent over the live rear-camera feed, terrain hides (shadow-catcher only), camera freezes in world space, blob shadow grounds the avatar; light estimation adapts intensities. (optional) Screenshot P, record 6s clip R (`MediaRecorder` → `navigator.share()` / download).
+- **Decision points / branches:** mobile (touch joysticks) vs desktop (WASD + mouse); avatar source param; coin community mode (`?coin=` spawns CoinTotem + trade polling) vs solo/lobby; physics ready (Rapier) vs legacy movement; AR on/off; camera permission granted/denied/unavailable; multiplayer connected vs solo; zen mode (`?ui=hidden`).
+- **External calls / dependencies:** `GET /api/avatars/{id}`, `GET /api/avatars?limit=20`, `GET /animations/manifest.json`, coin trades poll (`/api/pump/coin-trades?mint=` every 7s in coin mode), Colyseus WebSocket (multiplayer). Device APIs: `getUserMedia` (camera), `navigator.vibrate` (haptics), `navigator.share`, `requestPointerLock`, localStorage/sessionStorage.
+- **Success state:** Avatar driven smoothly around the world (joystick/WASD), camera follows; optionally on the real floor via AR; remote players + chat visible if multiplayer connected.
+- **Empty / error states:** Avatar load fail → error pill + "try the default avatar". Camera API absent → AR button disabled w/ tooltip. Camera denied → sticky "camera permission denied". Physics WASM fail → silent legacy fallback. Multiplayer offline → "unavailable", solo play continues. Recording unsupported → status error. Avatar picker w/o auth → "Sign in to use your avatars".
+- **Step count:** 3 required (load, move, orbit) (+ ~12 optional)
+
+---
+
+### IRL — `/irl`
+- **Source:** `pages/irl.html` (WebGL-gate inline boot), `src/irl.js`, `src/irl/*` (`onboarding.js`, `floor-anchor.js`, `room-anchor.js`, `room-session.js`, `tap-pick.js`, `gps-lifecycle.js`, `discovery.js`, `privacy-center.js`, `proximity-band.js`, `proximity-cue.js`, `sensor-fusion.js`, `share-frame.js`, `map-place.js`, `camera-fov.js`, `load-queue.js`, `perf-budget.js`), `src/irl-net.js`
+- **Entry point:** `pages/irl.html` runs an inline WebGL-support check; if supported it `import('/src/irl.js')`, else it renders a designed "This device can't run IRL AR" state with "Browse agents"/"Open marketplace" actions. URL param `?avatar=` chooses the placed agent.
+- **Prerequisites / gates:** No auth, no wallet (anonymous `irl_device_token` in localStorage). **WebGL** required (hard gate at HTML load). Requested progressively via `onboarding.ensurePermission(...)`: **camera** (`getUserMedia`) on first "Camera AR" tap; **motion** (`DeviceOrientationEvent.requestPermission` on iOS 13+) when locking; **geolocation** (`navigator.geolocation.watchPosition`, enableHighAccuracy) when locking/discovering. None are hard blockers — each has a designed fallback.
+- **Steps (7 required + optional):**
+ 1. Page loads (WebGL OK) → Three.js scene + default/`?avatar=` GLB; device token restored; onboarding/discovery initialized; subtitle "Turn on Camera AR, then tap Pin here to anchor your agent." Discovery empty-state CTA visible.
+ 2. User taps **Camera AR** → onboarding card → grant `getUserMedia({ video: { facingMode: 'environment' } })` → `enableAR()` shows the rear-camera feed, applies derived camera FOV, freezes the 3D camera so the phone gyro looks around the room.
+ 3. User taps **Pin here** → `setLocked(true)` requests **location** (`watchPosition`) and **motion** (iOS `DeviceOrientationEvent.requestPermission`), waits briefly for a compass sample, captures the gyro lock pose; if GPS not yet ready shows "Getting your location…".
+ 4. On first GPS fix → anchors the pin, begins 10s nearby polling, joins the IrlNet presence room (Colyseus, optional).
+ 5. User aims at the floor spot and **taps the canvas** → optional caption → Confirm → `commitPin()` → `POST /api/irl/pins` with `{ lat, lng, heading, caption, avatarUrl, avatarName, deviceToken, agentId, anchor: { yawDeg, source: 'gyro-gps'… } }`.
+ 6. System polls `GET /api/irl/pins?lat=&lng=&radius=60` every 10s; nearby agents spawn (LOD: dot → impostor → full mesh), name labels + confidence rings render; crossing the ~40m ENTER band fires the proximity-arrival cue (haptic + chime + directional glow). Tapping a nearby agent opens a bottom sheet → "View" (`GET /api/irl/agent-card`), "Pay" ($THREE x402), "Message"; interactions `POST /api/irl/interactions`.
+ 7. **Payoff:** The user's chosen agent is anchored and visible in AR on the real floor, persisted for nearby users to discover; the user can also discover and interact with other agents pinned around them.
+ 8. (optional alt placement) **Place on floor** WebXR (Android Chrome): `XRSession.requestSession('immersive-ar')` hit-test → `POST /api/irl/pins` with `anchor.quat` + shared room frame; iOS Safari → AR Quick Look (USDZ). **Place on map** (privacy-first): Leaflet picker → `commitMapPin()` `POST /api/irl/pins source:'map'`.
+ 9. (optional) Privacy center (`openPrivacyCenter`): geolocation precision Exact vs Nearby, "Appear nearby" ghost toggle. Share button flattens camera + canvas to PNG. "My pins" sheet → `GET /api/irl/pins/mine`, map + list, `DELETE /api/irl/pins?id=` or `?all=1`. Calibrate / refine-on-floor → `PATCH /api/irl/pins`.
+- **Decision points / branches:** WebGL supported vs fatal overlay; placement path (gyro-GPS / WebXR floor / iOS Quick Look / map); camera/motion/location granted vs denied (each → fallback); compass available (north-aligned) vs relative-only (`gyro-gps:rel`); GPS ready vs warm-up hold; agent crosses ENTER vs EXIT band; tap on mesh vs label vs background; precision Exact vs Nearby; room mode (shared frame) vs solo.
+- **External calls / dependencies:** `POST/PATCH/DELETE /api/irl/pins`, `GET /api/irl/pins` (+ `/mine`), `GET /api/irl/agent-card`, `POST /api/irl/interactions`, `GET /api/irl/interactions-stream` (SSE), `POST /api/irl/report`, `POST /api/irl/fix-token`. Device: `getUserMedia` (camera), `DeviceOrientationEvent.requestPermission` / `deviceorientation(absolute)` (motion), `navigator.geolocation.watchPosition`, `navigator.permissions.query`, `navigator.vibrate`, `AudioContext`, WebXR `immersive-ar`. Realtime: Colyseus WebSocket (`IrlNet`, room `irl_world`). Libs: GLTFLoader (+Draco/meshopt), Leaflet/CARTO, in-browser USDZ exporter.
+- **Success state:** Agent anchored to a real-world spot, visible in AR; nearby agents discovered by proximity (dots→impostors→meshes) with name labels, arrival cues, and an interaction sheet.
+- **Empty / error states:** WebGL unsupported → fatal designed overlay. Camera/motion/location denied → designed recovery cards with platform Settings steps + fallbacks. GPS warm-up → shimmer "Acquiring…". No nearby agents → calm "0 nearby" + "Place an agent here" CTA. Poll fail → amber "refresh failed" (15s retry). Rate-limited → calm blue chip, self-recovers. Avatar load fail → "Couldn't load this agent" + Retry. WebGL context lost → "AR paused" + Reload. Placement rejected (moderation/full/rate) → status message, lock released.
+- **Step count:** 7 required (+ several optional)
+
+---
+
+### IRL Location Privacy — `/irl-privacy`
+- **Source:** `pages/irl-privacy.html` (static content), `nav.js`, `footer.js`
+- **Entry point:** Static page load. Read-only policy/explainer page.
+- **Prerequisites / gates:** None.
+- **Steps (2):**
+ 1. User lands on `/irl-privacy` and reads how location works on IRL — placed agents are private by location (appear only to people physically near them, never on a map/list), what camera/motion/location are used for, and what is/isn't shared.
+ 2. (optional) User follows in-page links (e.g. back to `/irl`, footer links).
+- **Decision points / branches:** none.
+- **External calls / dependencies:** none for content (nav/footer scripts only).
+- **Success state:** User understands the IRL location-privacy model.
+- **Empty / error states:** none (static content).
+- **Step count:** 1 required (+1 optional) — content page (read)
+
+---
+
+### Reputation Explorer — `/reputation`
+- **Source:** `public/reputation/index.html`, `public/reputation/reputation.js`, `src/erc8004/{chain-meta,abi,reputation}.js`, EAS (Ethereum Attestation Service) EASScan GraphQL, EAS SDK + ethers
+- **Entry point:** On load the module parses URL params (`?address=`, `?chain=`, legacy `?agent=N:M`). With an address it renders a profile; without one it renders the search landing.
+- **Prerequisites / gates:** **Reading** attestations needs no wallet (EASScan GraphQL + public RPC). **Writing** a review requires an injected wallet (MetaMask) on the write chain (Base Sepolia by default) + gas.
+- **Steps (6):**
+ 1. User lands on `/reputation`. With no `?address`, system renders the search form (address / ENS input, chain select, example chips).
+ 2. User enters an address or ENS name (or clicks an example chip), submits → navigates to `?address=…&chain=…`.
+ 3. System resolves ENS if needed (public RPC), then fetches attestations via EASScan GraphQL (`fetchAttestations`) and the ERC-8004 on-chain reputation (`getReputation`) for the resolved address/chain.
+ 4. System renders the profile: aggregate score bar (color-coded), star ratings, tabbed review list (all / by category), copy-address + copy-share-link buttons.
+ 5. (optional) **Write a review:** click "Connect wallet to review" → `eth_requestAccounts`; pick a star score + comment; click "Sign & submit review" → switches/adds the write chain (`wallet_switchEthereumChain` / `wallet_addEthereumChain`), encodes the `address agent, uint8 score, string comment` schema, and calls `EAS.attest(...)`.
+ 6. **Payoff:** Transaction confirms → success card with "View transaction" (block explorer) + "View attestation" (EASScan) links; the on-chain review is now part of the agent's reputation.
+- **Decision points / branches:** address vs ENS vs legacy `agent=N:M` (→ `renderLegacyAgent`, resolves owner then redirects); supported EAS chain vs unsupported; wallet present vs absent; correct write chain vs needs switch/add; user-rejected tx vs failure.
+- **External calls / dependencies:** EASScan GraphQL per chain (Base/Ethereum/Optimism/Arbitrum/Polygon/Base Sepolia), public RPC for ENS + ERC-8004 reads, injected wallet (`window.ethereum`), EAS SDK `attest`. ERC-8004 helpers `getReputation`/`submitReputation`.
+- **Success state:** Reputation profile with score bar + reviews rendered; on write, a confirmed attestation with explorer/EASScan links.
+- **Empty / error states:** Unsupported network card; invalid address / ENS-not-found / ENS-failed cards (with "Search again"); no attestations → "Be the first to review!"; no wallet → "Install MetaMask…"; tx cancelled (4001) → "Cancelled by user"; tx failure → "Failed: <reason>".
+- **Step count:** 4 required (+2 optional write)
+
+---
+
+### Agent Lookup — `/lookup`
+- **Source:** `public/lookup.html` (inline module), `/api/registry/resolve`
+- **Entry point:** On load the inline module reads `?q=`, fills the input, and auto-runs `lookup()` if a query is present.
+- **Prerequisites / gates:** None.
+- **Steps (4):**
+ 1. User lands on `/lookup`. If `?q=` is present, the lookup runs immediately; otherwise the input is empty.
+ 2. User types a Solana asset mint / agent ID / avatar ID / slug into the input and presses Enter or clicks "go". System sets `?q=` via `replaceState`, disables the button, shows a skeleton.
+ 3. System fetches `GET /api/registry/resolve?q=<input>` and renders the result.
+ 4. **Payoff:** The resolved agent renders as an interactive `<model-viewer>` 3D avatar (or 🔒/🤖/image placeholder) alongside its identity card and on-chain panel (Active / x402 status, owner, collection, copy buttons, Metaplex / Solscan / Magic Eden links). "Share" copies the current URL.
+- **Decision points / branches:** has `modelUrl` → 3D viewer; `state === 'private'` → 🔒 placeholder; `imageUrl` → thumbnail; none → 🤖 placeholder; on-chain present vs "Not deployed on-chain yet".
+- **External calls / dependencies:** `GET /api/registry/resolve`, `model-viewer` CDN, clipboard API.
+- **Success state:** A single agent resolved and rendered with its 3D avatar + on-chain identity.
+- **Empty / error states:** No match → "No agent found" with a tip + link to the explore feed. Fetch error → "Something went wrong" with the error message.
+- **Step count:** 2 required (+2 optional)
+
+---
+
+### Agents Index — `/agents`
+- **Source:** `public/agents/index.html` (inline module), `/api/agents/public`, `public/agents/boot.js`
+- **Entry point:** Inline module runs `load(true)` on load.
+- **Prerequisites / gates:** None to browse.
+- **Steps (4):**
+ 1. User lands on `/agents`. System renders 8 skeleton cards and fetches `GET /api/agents/public?limit=24&sort=popular`.
+ 2. System renders agent cards: avatar thumbnail (or initial fallback), on-chain badge if registered, name + description, top skills, chat count. Count label shows total.
+ 3. (optional) Search box → 320ms debounce → reload with `q`; sort select (popular / newest / name) → reload; "On-chain only" checkbox → reload with `onchain=1`; "Load more" → cursor pagination (`before`).
+ 4. **Payoff:** Click a card → navigates to the agent's `home_url` (agent profile / chat). Hero CTAs link to `/create-agent` and `/marketplace`.
+- **Decision points / branches:** registered (on-chain badge) vs not; avatar thumbnail vs initial fallback; sort/onchain filters; has_more (Load more shown) vs not.
+- **External calls / dependencies:** `GET /api/agents/public`.
+- **Success state:** Grid of public 3D agents, each linking to its profile.
+- **Empty / error states:** Query-empty → "No agents found" for the term; unfiltered-empty → "No public agents yet" + create CTA; fetch error → "Couldn't load agents — Try refreshing."
+- **Step count:** 1 required (+3 optional)
+
+---
+
+### My Agents — `/my-agents`
+- **Source:** `public/my-agents/index.html` (inline module), `public/my-agents/my-agents.{js,css}`, `/api/agents`
+- **Entry point:** Inline module runs `load()` on load.
+- **Prerequisites / gates:** **Auth required** — `GET /api/agents` returning 401 renders a sign-in gate.
+- **Steps (4):**
+ 1. User lands on `/my-agents`. System renders 4 skeletons and fetches `GET /api/agents` with `credentials: 'include'`.
+ 2. If 401 → auth gate ("Sign in to manage your agents") with Sign-in (`/login?next=`) + Create-account links — flow stops here until signed in.
+ 3. On success, reveals the "+ Create agent" CTA and renders each owned agent as a row: thumbnail/initial, name, on-chain vs "not registered" badge, description, top skills.
+ 4. **Payoff:** Per-row actions — "View" (`home_url` or `/agent/:id`), "Edit" (`/agent/:id/edit`), and for unregistered agents a gold "Deploy" link to the edit page's deploy flow.
+- **Decision points / branches:** 401 (auth gate) vs authed; on-chain (badge + no Deploy) vs not registered (Deploy link); zero agents (empty state) vs populated.
+- **External calls / dependencies:** `GET /api/agents` (session cookie).
+- **Success state:** List of the signed-in user's agents with View / Edit / Deploy actions.
+- **Empty / error states:** 401 → sign-in gate; connection error → "Connection error — Check your network"; non-OK → "Failed to load agents"; zero agents → "No agents yet" + Create CTA.
+- **Step count:** 3 required (+1 optional, e.g. Deploy)
+
+---
+
+### Sitemap — `/sitemap`
+- **Source:** `public/sitemap/index.html` (static content + inline filter script), `nav.js`, `footer.js`
+- **Entry point:** Static page load; inline script wires the live filter. Read-only directory page.
+- **Prerequisites / gates:** None.
+- **Steps (3):**
+ 1. User lands on `/sitemap` and sees all pages grouped into sections (Main, Build, Labs, Crypto, Agent Tools, Account, Learn, Blog, Legal, Machine-readable) with per-section counts and a total ("N pages · M sections").
+ 2. (optional) User types in the filter input → inline script hides non-matching `<li>` items + sections live, updates the count, and shows an empty state echoing the query if nothing matches.
+ 3. (optional) User clicks a TOC anchor to jump to a section, or any page link to navigate. (The `/sitemap.xml` and `/sitemap/<type>.xml` machine-readable variants are served by `/api/sitemap`.)
+- **Decision points / branches:** filter query matches vs empty result; section visibility toggled by matches.
+- **External calls / dependencies:** none for content (purely client-side filter; nav/footer scripts).
+- **Success state:** User finds and navigates to the page they want via browse or filter.
+- **Empty / error states:** Filter with no matches → empty state with the query echoed.
+- **Step count:** 1 required (+2 optional) — content page (read)
+
+---
+
+## Notes
+- All listed sources were located and traced from real files; no source was missing.
+- `/characters` page HTML lives at `public/characters.html` (root-level dest in `vercel.json`), not under `pages/`.
+- `/agents`, `/my-agents`, and `/lookup` keep their grid/lookup logic in **inline `<script type="module">` blocks** within the page HTML rather than a separate `src/` module.
+- Detail pages reached from these routes (`/discover/a/...`, `/character/:id`, `/avatars/:id`, `/agent/:id`, agent profile `home_url`) are outside this cluster's scope but are the payoff destinations.
diff --git a/docs/ux-flows/06-marketplace-skills.md b/docs/ux-flows/06-marketplace-skills.md
new file mode 100644
index 000000000..b583dd2cc
--- /dev/null
+++ b/docs/ux-flows/06-marketplace-skills.md
@@ -0,0 +1,207 @@
+# Marketplace & Skills
+
+UX Flow Atlas — cluster 6. Traced against real source in `/workspaces/three.ws`. The marketplace is a path + query-param SPA served by one HTML shell (`marketplace.html`) driven by `src/marketplace.js` (8.4k lines). `/skills` is a redirect into that SPA. `/collection` and `/marketplace/analytics` are standalone pages. The critical path (browse → buy → unlock → collection) spans two purchase endpoints (`/api/marketplace/purchase` for individual skills, `/api/marketplace/buy-asset` for whole avatars/agents/plugins), both Solana-Pay-by-reference with optional gasless sponsorship and an EVM/USDC fallback.
+
+Routing facts confirmed in `vercel.json`:
+- `/marketplace`, `/marketplace/` → `/marketplace.html` (lines 1603-1610)
+- `/marketplace/(tools|skills|animations|onchain)/:id` → `/marketplace.html` (SPA handles detail; line 1611)
+- `/marketplace/agents/:id` → **301 redirect to `/agents/:id`** (canonical agent page; line 1615)
+- `/marketplace/avatars/:id` → **301 redirect to `/avatars/:id`** (line 1622)
+- `/marketplace/analytics` → `/pages/marketplace-analytics.html` (line 1595)
+- `/collection` → `/pages/collection.html` (line 1587)
+- `/skills` → `/skills.html` (line 1571), which client-redirects to `/marketplace?tab=skills`
+- `/api/marketplace/purchase/:ref/confirm` → `purchase.js?reference&op=confirm` (line 1555)
+- `/api/marketplace/buy-asset/:ref/confirm` → `buy-asset.js?reference&op=confirm` (line 1563)
+
+---
+
+### Marketplace browse & discovery — `/marketplace`
+- **Source:** `src/marketplace.js` (entry `init()` ~L7730), `pages/marketplace.html`, `src/marketplace-lobby.js` (3D hero podium), `src/marketplace-detail.js` (detail render/preview), backend `api/marketplace/[action].js`
+- **Entry point:** `init()` → `bindEvents()` → `loadCategories()` → `loadList(true)` → `loadTheme()` → `loadCurrentUser()` → `fetchUserPurchases()` → `render()`. Initial fetches: `/api/marketplace/categories`, `/api/marketplace/agents`, `/api/explore?source=avatar` and `?source=onchain`, `/api/marketplace/theme`, `/api/auth/me`, `/api/users/me/purchased-skills`.
+- **Prerequisites / gates:** None to browse. `/api/auth/me` is best-effort (anonymous users still browse; owner-only price-edit panels stay hidden). Wallet/auth only gate the purchase actions.
+- **Steps (N):**
+ 1. User opens `/marketplace`; SPA shell loads, skeleton cards render (`skeletonHTML(8)`).
+ 2. System fetches categories, agents, public avatars, onchain agents, weekly theme, current user, and the user's owned skills in parallel.
+ 3. Hero renders a 3D lobby (`marketplace-lobby.js` `mountLobby()`, max 5 featured avatars on a podium) auto-rotating every 8s; pauses on hover/focus.
+ 4. Weekly theme strip renders a horizontally-scrollable set of featured 3D picks.
+ 5. Main grid renders agent cards + avatar cards + onchain cards with section headers and counts.
+ 6. (optional) User clicks a category in the sidebar or a top-bar chip → `state.category` set → `loadList(true)` refetches `/api/marketplace/agents?category=…`.
+ 7. (optional) User types in the search box → debounced 250ms → `state.q` set → `loadList(true)` refetches with `?q=…` (also applied to `/api/explore` avatar/onchain calls).
+ 8. (optional) User changes the sort dropdown (recommended / newest / popular / trending) → `loadList(true)` with `?sort=…`.
+ 9. (optional) User clicks a Free/Paid price chip → `state.priceFilter` → refetch agents with `?pricing=free|paid` (avatars/onchain re-filtered client-side).
+ 10. (optional) User clicks a tag pill on a card → `navTo(/marketplace?tag=X)` → `render()` re-filters the in-memory grid.
+ 11. User scrolls to the grid bottom → IntersectionObserver fires `loadList(false)` (append) with `?cursor=…`; a manual "Load more" button maps to the same handler.
+ 12. User clicks a card → `navTo()`: agent → `/marketplace/agents/:id` (301 → `/agents/:id`), avatar → `/marketplace/avatars/:id` (301 → `/avatars/:id`), onchain → `/marketplace/onchain/:id` (SPA detail) or external fallback link.
+- **Decision points / branches:** filter type (All / Agents / Avatars / Onchain); price (Any / Free / Paid); 3D model category chips; sort mode; tab via `?tab=` (agents | avatars | onchain | skills | tools | memory | earn | purchases | mine).
+- **External calls / dependencies:** `api/marketplace/[action].js` (categories, agents, theme, agents/:id, /versions, /similar), `/api/explore`, `/api/auth/me`, `/api/users/me/purchased-skills`. 3D via model-viewer + Three.js (lobby).
+- **Success state:** Populated grid with featured 3D hero, theme strip, and per-section counts; cards navigable to detail.
+- **Empty / error states:** `renderEmptyState()` ("No results" + "Browse categories" CTA); `renderCategoriesError()` with retry in sidebar; `renderErrorState('agents'|'avatars'|'skills')` with retry; per-card model-viewer load error message.
+- **Step count:** 6 required (+6 optional)
+
+---
+
+### Agent / avatar listing detail — `/marketplace/agents/:id` (301 → `/agents/:id`), `/marketplace/avatars/:id` (301 → `/avatars/:id`)
+- **Source:** `src/marketplace.js` (`loadDetail()` ~L4581, `loadAvatarDetail()` ~L4717), `src/marketplace-detail.js` (3D stage, live chat preview, creator modal), canonical pages `/agents/:id` and `/avatars/:id` reuse `marketplace-detail.js`
+- **Entry point:** Card click in the grid, or direct URL. SPA path form renders inline via `loadDetail(id)`; canonical paths get a 301 redirect to the dedicated agent/avatar page. `loadDetail()` fetches `/api/marketplace/agents/:id`, plus best-effort `/api/marketplace/agents/:id/versions` and `/similar`.
+- **Prerequisites / gates:** None to view, preview-chat, or open the creator modal (all anonymous-friendly). Buying a skill or the whole asset requires auth + wallet (see purchase flows below).
+- **Steps (N):**
+ 1. User lands on detail; cached card renders optimistically, then full API data replaces it.
+ 2. 3D avatar renders in the hero (`renderDetailAvatar()`); a full-width interactive 3D model stage offers orbit, fullscreen, GLB download, and "Open in world".
+ 3. System lists the agent's skills with price/trial badges; owned skills show "Installed ✓", paid show "Unlock", trial-eligible show "Try free (N left)".
+ 4. (optional) User opens the live chat preview → `startPreviewSession()` POSTs an SSE stream to `/api/marketplace/agents/:id/preview` and streams the agent's reply.
+ 5. (optional) User clicks the creator name → `openCreatorModal()` fetches `/api/creators/:id` and shows the creator's agents/avatars.
+ 6. (optional) User starts a trial (see Trial flow), unlocks a skill (see Skill purchase flow), or buys the whole asset (see Asset purchase flow).
+ 7. (optional, owner only) If `currentUserId === agent.owner_id`, a price editor panel appears; save/clear posts to `/api/marketplace/asset-price`.
+- **Decision points / branches:** owner vs buyer view; skill is free / owned / paid / trial-eligible; asset is for-sale vs not.
+- **External calls / dependencies:** `/api/marketplace/agents/:id` (+ `/versions`, `/similar`, `/preview`), `/api/creators/:id`, `/api/avatars/:id` (avatar detail), `/api/marketplace/asset-price` (owner price edit).
+- **Success state:** Full detail with interactive 3D, skill list, live preview, and the correct action (Unlock / Buy / Try free / owner editor).
+- **Empty / error states:** `showDetailState('error'|'notfound')` overlay with retry; avatar detail "Avatar not found"; 3D stage "Couldn't load the 3D model." with a 15s "still loading" hint; preview errors surfaced in the chat footer.
+- **Step count:** 3 required (+4 optional)
+
+---
+
+### Skill purchase / unlock (critical path) — buy flow via `/api/marketplace/purchase`
+- **Source:** client `src/marketplace.js` (`openPurchaseFlow()` ~L6824, `createPendingPurchase()` ~L6872, `buildSplTransferWithReference()` ~L7258, `pollConfirm()` ~L7299) and the embed widget `src/payment-modal.js` (`SkillPaymentModal` / `PaymentChip`). Backend `api/marketplace/purchase.js` → `_lib/services/MonetizationService.js` (`preparePurchaseTransaction`, `confirmPurchase`), `_lib/solana/gasless-tx.js`, `_lib/resolve-recipient.js`. Access check `api/marketplace/check-skill-access.js`.
+- **Entry point:** "Unlock" button on a paid skill in the agent detail view (or the embedded agent widget's payment-required event, which opens `SkillPaymentModal`/`PaymentChip`).
+- **Prerequisites / gates:** Auth required (session cookie or bearer) — `/api/marketplace/purchase` returns 401 otherwise. CSRF token required (`requireCsrf`). Rate-limited (`limits.authIp`). A connected Solana wallet (Phantom et al.) is required to sign; sufficient USDC/`$THREE` balance for the price.
+- **Steps (N):**
+ 1. User clicks "Unlock" on a paid skill → `openPurchaseFlow(agentId, skill)` populates and shows the payment modal (skill name, agent name, price, status, QR slot).
+ 2. (optional) If no wallet is connected, modal shows "Connect Phantom" → `_connectWallet()` calls `window.solana.connect()`; if Phantom is absent, it links to phantom.app.
+ 3. User clicks "Confirm Purchase" → client POSTs `/api/marketplace/purchase` `{ agent_id, skill, [duration_hours], [buyer_public_key], [recipient (gift)] }`.
+ 4. Server (`MonetizationService.preparePurchaseTransaction`) resolves price, creator payout wallet, fee split, idempotent pending row, referrer attribution; returns a quote `{ reference, recipient, currency_mint, amount, creator_amount, mint_decimals, fee, chain }`. If `buyer_public_key` is supplied and chain is Solana, it also pre-builds a **gasless** fee-payer-sponsored `VersionedTransaction` (`buildGaslessPurchaseTx`).
+ 5. **Branch — already owned:** if `already_owned: true`, modal shows "✓ Already purchased — access granted." and resolves success without payment.
+ 6. Client builds the SPL transfer (`buildSplTransferWithReference`): from-ATA → creator-ATA for `creator_amount`, optional platform-fee leg to treasury, and pushes the `reference` pubkey as a read-only key so the server can find the tx on-chain. (Gasless path uses the server-prepared tx instead.)
+ 7. **Pre-flight balance check:** client reads the buyer's token ATA; if balance < required, it shows "Not enough USDC" + an "Add funds →" button (`showAddFunds`) and stops before prompting the wallet (insufficient-funds branch).
+ 8. Client sets recent blockhash, fee payer = buyer; calls `wallet.sendTransaction()` (desktop) or `signAndSendTransaction()` (mobile) → user approves in the wallet.
+ 9. Client waits for on-chain confirmation (`connection.confirmTransaction(txid, 'confirmed')`).
+ 10. Client polls `/api/marketplace/purchase/:reference/confirm` every 2.5s (60s timeout). Server (`confirmPurchase`) finds the tx by reference, validates amount + mint to the creator payout wallet, marks the row `confirmed`, records `agent_revenue_events`.
+ 11. **Branch — verification outcomes:** `confirmed` → success; `409 transfer_mismatch` (status `tipped` when a smaller-but-real transfer landed); `410 purchase_expired` for a stale pending row.
+ 12. On confirmed, modal renders a signed receipt (`buildReceiptHTML`) with a Solscan link, then resolves true.
+ 13. Client refreshes ownership: `fetchUserPurchases()` and reloads the detail (`loadDetail`) so the skill now shows "Installed ✓"; the purchase appears under the "My Purchases" tab and in `/collection`.
+- **Decision points / branches:** gasless (wallet connected, sponsored) vs buyer-pays vs mobile QR (Solana Pay); already-owned short-circuit; insufficient funds → Add funds; gift purchase (`recipient`) resolved server-side via `resolveRecipient`; verification mismatch (tipped) vs expired.
+- **External calls / dependencies:** `POST /api/marketplace/purchase`, `POST /api/marketplace/purchase/:ref/confirm`, `GET /api/marketplace/purchase/:ref` (status), `GET /api/marketplace/check-skill-access`, Solana RPC via `/api/solana-rpc`, `@solana/web3.js` + `@solana/spl-token` (lazy-loaded), `@solana/pay` (server `findReference`/`validateTransfer`), gasless tx builder, `/api/users/me/purchased-skills` (post-purchase refresh), `/api/billing/receipts` (receipt download in My Purchases).
+- **Success state:** Receipt with tx link; skill flips to owned; appears in My Purchases tab and `/collection`; `check-skill-access` returns `has_access: true`.
+- **Empty / error states:** cancelled connect/tx ("try again"), insufficient funds (Add funds button), `verification_failed` (paid but unverified — contact support), network error, expired pending row — all with the confirm button re-enabled for retry. Re-verify (no new tx) supported when a txid exists.
+- **Step count:** 9 required (+4 optional)
+
+---
+
+### Whole-asset purchase (avatar / agent / plugin) — buy flow via `/api/marketplace/buy-asset`
+- **Source:** client `src/marketplace.js` (`openAssetPurchaseFlow()` ~L6890, `createPendingAssetPurchase()` ~L6929, `pollAssetConfirm()` ~L6936; shared engine `src/shared/skill-purchase.js`). Backend `api/marketplace/buy-asset.js` (Solana Pay `findReference`/`validateTransfer`, gasless sponsorship, EVM/USDC fallback via `_lib/evm-payment-verify.js`, receipts + notifications).
+- **Entry point:** "Buy now with USDC" on an avatar modal / agent detail / plugin card.
+- **Prerequisites / gates:** Auth + CSRF + rate limit; asset must have an active `asset_prices` row; seller must have a configured payout wallet for the chain (else `412 creator_wallet_missing`); buyer must not be the owner (else `400 self_purchase`); connected wallet with sufficient balance.
+- **Steps (N):**
+ 1. User clicks "Buy now" → `openAssetPurchaseFlow({ item_type, item_id, label, price })` opens the payment modal in `mode='asset'`.
+ 2. (optional) Connect wallet if not connected.
+ 3. User confirms → POST `/api/marketplace/buy-asset` `{ item_type, item_id, [buyer_public_key] }`.
+ 4. Server validates price/seller/payout; **already-owned** confirmed purchase short-circuits with `already_owned: true`; otherwise reuses or inserts a pending `asset_purchases` row (30-min expiry) and returns `{ reference, recipient, amount, currency_mint, chain, mint_decimals }` (+ gasless block when applicable).
+ 5. **Branch — already owned:** modal jumps to the success screen, skips payment.
+ 6. Client builds + signs the full-amount SPL transfer (single leg, no platform fee) with the reference key; user approves in wallet.
+ 7. Client confirms on-chain, then polls `/api/marketplace/buy-asset/:reference/confirm` (2.5s, 60s).
+ 8. Server (Solana) `findReference` → `validateTransfer`; on success marks `confirmed`, writes a signed `asset_purchase_receipts` row, and notifies both seller (`asset_purchased`) and buyer (`asset_purchase_confirmed`).
+ 9. Modal renders the success card; primary CTA goes to `/dashboard/avatars`, `/dashboard/agents`, or `/dashboard` per asset type; `fetchUserPurchases()` refreshes ownership.
+- **Decision points / branches:** chain = Solana vs EVM (EVM confirm requires a submitted `tx_hash`, verified via `verifyEvmUsdcPayment` on Base; short transfer = `tipped` 409); gasless vs buyer-pays; already-owned; mismatch (tipped) vs expired (410).
+- **External calls / dependencies:** `POST /api/marketplace/buy-asset` (+ `/:ref` status, `/:ref/confirm`), Solana RPC w/ fallback, `@solana/pay`, EVM USDC verifier, `insertNotification`, receipt HMAC signing.
+- **Success state:** Asset confirmed and owned; receipt stored; both parties notified; CTA into the relevant dashboard; surfaced in `/collection`.
+- **Empty / error states:** `404 not for sale`, `412 creator_wallet_missing`, `400 self_purchase`, `409 transfer_mismatch` (tipped), `410 purchase_expired`; client retry/re-verify identical to the skill flow.
+- **Step count:** 7 required (+2 optional)
+
+---
+
+### Free trial unlock — `/api/marketplace/start-trial`
+- **Source:** `src/marketplace.js` (`openTrialFlow()` ~L6794), backend `api/marketplace/start-trial.js`
+- **Entry point:** "Try free (N left)" button on a trial-eligible paid skill (detail view or grid card).
+- **Prerequisites / gates:** Auth (button redirects to login on 401). No wallet/payment.
+- **Steps (N):**
+ 1. User clicks "Try free" → `openTrialFlow(agentId, skill, btn)`.
+ 2. Client POSTs `/api/marketplace/start-trial` `{ agent_id, skill }`.
+ 3. **Branch:** if already owned or trial already used, an alert explains and stops.
+ 4. On success, `fetchUserPurchases()` + `loadDetail()` refresh; the skill now shows in My Purchases with a "Trial (N left)" badge and works until uses are exhausted.
+- **Decision points / branches:** trial available vs already-owned vs trial-used.
+- **External calls / dependencies:** `POST /api/marketplace/start-trial`, `/api/users/me/purchased-skills`.
+- **Success state:** Trial grant visible in My Purchases / `/collection` with a remaining-uses badge.
+- **Empty / error states:** alert on already-owned / trial-used; auth redirect on 401.
+- **Step count:** 3 required (+1 optional)
+
+---
+
+### Skills marketplace (browse / install / rate) — `/skills` → `/marketplace?tab=skills`
+- **Source:** `pages/skills.html` (redirect shell), `src/marketplace.js` skills tab (`skillsState` ~L2128, `loadSkillsTab()`, `renderSkillsGrid()`/`renderSkillCard()` ~L2229, skill detail ~L2348, `toggleSkillInstall()` ~L2582). Backend `/api/skills`, `/api/skills/categories`, `/api/skills/:id`, `/api/skills/:id/install`, `/api/skills/:id/rate`. x402 per-call via `/api/x402/skill-call`. Runtime gate `src/skills/index.js`.
+- **Entry point:** `/skills` client-redirects (preserving `?q=`, `?category=`) to `/marketplace?tab=skills`; the SPA renders the skills grid.
+- **Prerequisites / gates:** Browse is open. Install and rate require auth (401 → `/login?next=…`). Installing is **free** — payment for skills is per-call via x402, separate from install.
+- **Steps (N):**
+ 1. SPA loads the skills tab → `GET /api/skills?limit=24&q=&category=&sort=&cursor=` and `/api/skills/categories`; renders skeletons then cards (name, price-per-call or "free", description, category pill, x402 badge for paid, install/tool counts, rating, "Installed ✓").
+ 2. (optional) User filters by category chip → `skillsState.category` → `loadSkillsTab(true)` refetch.
+ 3. (optional) User searches → `skillsState.q` → refetch; or toggles Free/Paid (client-side `isPaidSkill`).
+ 4. (optional) User scrolls → cursor pagination appends more cards.
+ 5. User clicks a card → `/marketplace/skills/:id` → `GET /api/skills/:id` renders the detail panel (header, meta pills, description, tool schemas, full content, related skills).
+ 6. User clicks "Install" → `toggleSkillInstall()` POSTs `/api/skills/:id/install` (DELETE to remove); 401 → login redirect; on success the detail + grid refetch and the button flips to "Installed ✓ — Remove".
+ 7. (optional) User rates 1–5 stars → `POST /api/skills/:id/rate { rating }` → detail refetches with updated counts.
+ 8. (optional, paid skills) Detail shows an x402 panel: endpoint `GET /api/x402/skill-call?skill=:slug`, price `$X.XXX/call`, and a copy-paste `@three-ws/x402-fetch` snippet — developers pay per call from their own wallet; the server settles to the author.
+- **Decision points / branches:** free vs paid (paid = x402 per-call, not an install purchase); installed vs not; authed vs anon (install/rate gated). Marketplace skills (community tool packs with schema/content) are distinct from built-in agent skills in `src/agent-skills*.js`.
+- **External calls / dependencies:** `/api/skills`, `/api/skills/categories`, `/api/skills/:id`, `/api/skills/:id/install` (POST/DELETE), `/api/skills/:id/rate`, `/api/x402/skill-call` (per-call payment), `/api/creators/:id` (author modal).
+- **Success state:** Skill installed (flips to "Installed ✓"), rating recorded, x402 snippet copyable; installs reflected on the user's agents.
+- **Empty / error states:** "No skills found" with Clear-filters / Publish-a-Skill CTAs; `renderErrorState('skills')` with retry; install button restores text + re-enables on error; auth redirect on 401.
+- **Step count:** 3 required (+5 optional)
+
+---
+
+### My Collection — `/collection`
+- **Source:** `pages/collection.html`, `src/collection.js`. Backend `/api/users/me/purchased-skills`, `/api/subscriptions`, `/api/billing/receipts`
+- **Entry point:** Direct nav to `/collection`; auto-runs `load()` on script load.
+- **Prerequisites / gates:** Auth required. Both data fetches returning 401 reveal the auth wall (`#col-auth-wall`).
+- **Steps (N):**
+ 1. Page loads → `load()` renders skeleton grids, then `Promise.all` fetches `/api/users/me/purchased-skills` and `/api/subscriptions` (both `credentials: include`).
+ 2. **Branch — 401:** auth wall shown ("Sign in to see your collection"); grids cleared.
+ 3. On success, stats render (skills count, active subscriptions, NFT-receipt count); the Skills panel renders owned/trial cards (thumbnail, skill name, agent, Owned/Trial badge, price, optional skill-NFT mint link to Solscan, purchase date, "View agent").
+ 4. The Subscriptions panel renders sub cards (Active/Expired badge, amount/period, renew/expiry date, "View agent").
+ 5. (optional) User switches between the Skills and Subscriptions tabs (counts shown in tab labels).
+ 6. (optional) "View agent" links navigate to `/marketplace/agents/:id` (→ `/agents/:id`).
+- **Decision points / branches:** authed vs auth-wall; skill (Owned) vs trial; subscription active vs expired; has NFT receipt vs not.
+- **External calls / dependencies:** `GET /api/users/me/purchased-skills`, `GET /api/subscriptions`, Solscan/Solana Explorer links, `/api/billing/receipts` (receipt download elsewhere in the purchase flow).
+- **Success state:** Populated Skills + Subscriptions grids with live stats and tab counts.
+- **Empty / error states:** Per-panel empty states ("No skills yet" → marketplace link; "No subscriptions"); `renderLoadError()` with a Retry button for network/HTTP/JSON failures; skeletons never linger.
+- **Step count:** 4 required (+2 optional)
+
+---
+
+### Marketplace analytics — `/marketplace/analytics`
+- **Source:** `pages/marketplace-analytics.html`, `src/marketplace-analytics.js`. Backend `/api/marketplace/analytics`
+- **Entry point:** Direct nav to `/marketplace/analytics`; auto-runs `load()`.
+- **Prerequisites / gates:** None — public aggregate stats.
+- **Steps (N):**
+ 1. Page loads → `load()` fetches `/api/marketplace/analytics`.
+ 2. Stat cards render: total skill sales, total volume, unique buyers, creators with sales, NFT receipts minted.
+ 3. A 30-day volume bar chart draws on a Canvas (no charting dependency; theme-aware colors, missing days zero-filled).
+ 4. Top Skills ranked list renders (skill, agent, sales count, revenue).
+ 5. Top Agents ranked list renders (agent, skill-sale count, net revenue).
+- **Decision points / branches:** has-data vs empty ("No sales yet." / "No agents yet."); dark vs light theme chart palette.
+- **External calls / dependencies:** `GET /api/marketplace/analytics` only.
+- **Success state:** Stats grid, volume chart, and both ranked lists populated.
+- **Empty / error states:** Fetch/parse failure → `#an-error` "Failed to load analytics. Please refresh." and all sections cleared; per-list empty placeholders.
+- **Step count:** 5 required (+0 optional)
+
+---
+
+### Marketplace feature landing — `/features/marketplace`
+- **Source:** `pages/features/marketplace.html` (static marketing page; `nav.js`, `footer.js`)
+- **Entry point:** Direct nav or the `/features` index.
+- **Prerequisites / gates:** None — public static page, no JS app, no API calls.
+- **Steps (N):**
+ 1. User lands on the page; breadcrumb (Home / Features / Marketplace), hero ("Agents built by the community."), and a "How it works" steps section render.
+ 2. (optional) User clicks "Browse agents →" (hero or bottom CTA) → navigates to `/marketplace`.
+ 3. (optional) User clicks "All features" → `/features`.
+- **Decision points / branches:** none (purely informational marketing).
+- **External calls / dependencies:** none.
+- **Success state:** Marketing content rendered; CTAs route into the live marketplace.
+- **Empty / error states:** none (fully static).
+- **Step count:** 1 required (+2 optional)
+
+---
+
+## Notes
+- `/marketplace/agents/:id` and `/marketplace/avatars/:id` are **301 redirects** to the canonical `/agents/:id` and `/avatars/:id` pages (vercel.json). Within the SPA, the same paths render inline via `loadDetail()`/`loadAvatarDetail()` before a hard navigation would redirect; `marketplace-detail.js` powers both the SPA detail and the canonical pages.
+- Two distinct purchase rails: **individual skills** (`/api/marketplace/purchase`, splits creator + platform fee, records `agent_revenue_events`) vs **whole assets** (`/api/marketplace/buy-asset`, single full-amount leg, no fee, EVM/USDC fallback). The embed widget (`payment-modal.js`) only drives the skill rail.
+- "Skills marketplace" (`/skills`, `/api/skills/*`) sells community tool packs — **install is free, payment is per-call via x402** — which is a different mechanism from the skill *unlock* purchase on an agent's detail page (`/api/marketplace/purchase`). Both can show under a user's owned items.
+- `src/marketplace-lobby.js` is not URL-routed; it's a Three.js scene mounted into the hero canvas with an `onSelect` callback back to `marketplace.js`.
+- Source coverage: all referenced files were located and read. No missing sources. Line numbers for `marketplace.js` are approximate anchors from a structural read of the 8.4k-line file, not exact-verified per line.
diff --git a/docs/ux-flows/07-crypto-trading-analytics.md b/docs/ux-flows/07-crypto-trading-analytics.md
new file mode 100644
index 000000000..a29e5e735
--- /dev/null
+++ b/docs/ux-flows/07-crypto-trading-analytics.md
@@ -0,0 +1,342 @@
+# Crypto Trading & Analytics
+
+UX Flow Atlas — Cluster 07. Read/monitor dashboards plus the interactive trading surfaces
+that sit on the pump.fun + Oracle + sniper data engines. Every route traced to real source.
+
+Routing convention in this repo: `/foo` is served from `pages/foo.html` (Vite multi-page input)
+or a pre-built `public/foo.html` (static), wired by `vercel.json` rewrites. Client logic is the
+inline `<script type="module">` and/or imported `src/*.js` modules. Watchlist state is a single
+shared `localStorage` key `ld_watchlist` used by oracle, radar, trades, watchlist, smart-money,
+coin-intel, pump-visualizer and pump-live — adding a coin on any surface shows up on `/watchlist`.
+
+---
+
+### Oracle — `/oracle`
+- **Source:** `pages/oracle.html`, `src/oracle.js` (1850 lines), lazy `src/oracle-graph.js` (3D force graph), `src/oracle-tape.js` (live trade tape in the coin drawer)
+- **Entry point:** nav link "Oracle"; direct URL; deep links `/oracle/coin/<mint>` open that coin's drawer; SEO/share links from `coinShareUrl()`.
+- **Prerequisites / gates:** Public dashboard for all read views (feed, movers, wallets, edge, proof, agents, activity, graph). The **Agent** (arm) tab requires sign-in + an existing 3D agent with a custodial Solana wallet; Live mode spends real (capped) SOL.
+- **Steps (N):**
+ 1. Arrive on `/oracle` → `boot()` populates category filter, binds tab/seg listeners, reads URL filters (`tier`, `category`, `minScore`, `view`), loads the **feed** view.
+ 2. System: `GET /api/oracle/feed?...` renders conviction cards (0–100 score, tier pill prime/strong/lean/watch/avoid). If backend not migrated → "Oracle is warming up" honest empty state.
+ 3. System: opens SSE `EventSource('/api/oracle/action-stream')` — new scored coins stream in live; "Live · fused conviction" / "Reconnecting…" indicator.
+ 4. (optional) Filter: click `#tierSeg` tier buttons / category select / min-score → `syncFilterUrl()` + `loadFeed()` (URL is shareable).
+ 5. (optional) Switch view tab: `movers`, `wallets` (reputation leaderboard), `edge` (tier backtest win-rate), `proof` (resolved wins), `agents` (agent win-rate ledger), `activity` (live agent actions), `graph` (3D force graph, lazy-imports oracle-graph.js).
+ 6. (optional) Click a coin card → `openDrawer(mint)` → `GET /api/oracle/coin?mint=...` renders the 4-pillar conviction breakdown (who/how/what/move); oracle-tape.js streams that coin's live trades.
+ 7. (optional) In the drawer: ☆/★ Watch (writes `ld_watchlist`), Copy mint, Copy link, Share to X.
+ 8. (optional, agents view) Follow an agent's signals: expand follow-panel → enter Telegram chat ID → `POST /api/oracle/follow`.
+ 9. **Arm payoff (gated):** open **Agent** tab → `loadAgentPanel()` → `GET /api/agents`. Pick agent, set Min conviction (Prime/Strong+/Lean+), Size/trade SOL, Max daily SOL, Max open, category filters, optional Telegram chat ID (Send test → server push), toggle Armed + Live/Simulate switches → **Save configuration** → `POST /api/oracle/watch` `{armed, mode, min_score, per_trade_sol, max_daily_sol, max_open, ...}`. Confirmation: "Armed in simulate/live mode. Your agent is watching the stream."
+- **Decision points / branches:** view tabs (9); feed warming vs populated vs filtered-empty; drawer coin scored vs "not scored yet"; agent has wallet vs needs creation (`/create/studio`); simulate vs live mode; signed-out → "Sign in and arm an agent".
+- **External calls / dependencies:** `/api/oracle/feed`, `/api/oracle/coin`, `/api/oracle/search`, `/api/oracle/movers`, `/api/oracle/categories`, `/api/oracle/backtest`, `/api/oracle/wins`, `/api/oracle/watch` (GET+POST), `/api/oracle/follow` (GET+POST), `/api/agents`; SSE `/api/oracle/action-stream`; oracle-tape live trade stream in drawer.
+- **Success state:** live conviction feed scoring every pump.fun launch in real time; coin drawer with pillar breakdown; armed agent acting on the stream (simulate logs / live spends capped SOL), actions graded into a win-rate ledger.
+- **Empty / error states:** "Oracle is warming up" (backend not live); "No launches clear your filters" + Reset; drawer "not scored"; "No ranked agents yet"; SSE auto-reconnects ("Reconnecting…"); `api()` returns `{ok:false}` on timeout (12s abort) and degrades gracefully.
+- **Step count:** 3 required (arrive → feed → live stream, all automatic) + ~6 optional read interactions, + a 6-field gated arm flow (steps 8–9).
+
+---
+
+### Agent Activity — `/activity`
+- **Source:** `pages/activity.html` (self-contained; inline module, no `src/*` import)
+- **Entry point:** nav; "Copy trades →" CTAs link to `/trader/<agent_id>`; linked from oracle activity view.
+- **Prerequisites / gates:** None — public live monitor.
+- **Steps (N):**
+ 1. Arrive → inline module sets `API='/api/oracle/activity'`, `STREAM_API='/api/oracle/action-stream'`, loads first page.
+ 2. System: `GET /api/oracle/activity?...` renders rows (agent, verb closed↑/↓/entered, $symbol, tier pill, sim/live tag, outcome win/loss/flat/open, PnL) + summary KPIs.
+ 3. System: opens SSE `/api/oracle/action-stream` — new agent actions prepend live.
+ 4. (optional) Filter by tier chip, mode pill (sim/live), or outcome → re-fetch with `?tier=&mode=&outcome=`.
+ 5. (optional) Load more (cursor pagination).
+ 6. (optional) Click "Copy trades →" on a winning/open row → navigate to that agent's trader profile (`/trader/<id>`).
+- **Decision points / branches:** filter combinations; win/open rows show Copy CTA, losses don't; stale badge + retry if a background refresh fails while rows are on screen.
+- **External calls / dependencies:** `GET /api/oracle/activity`; SSE `/api/oracle/action-stream`.
+- **Success state:** real-time trading floor of every agent's Oracle-driven move, outcomes graded, winners copyable.
+- **Empty / error states:** empty feed placeholder; stale/reconnect badge with manual retry button on background-refresh failure.
+- **Step count:** 2 required (arrive → feed+stream) + ~3 optional (filter, paginate, copy).
+
+---
+
+### Trending — `/trending`
+- **Source:** `pages/trending.html` (inline module; imports `/src/shared/agent-wallet-chip.js`)
+- **Entry point:** nav "Trending"; footer; share links.
+- **Prerequisites / gates:** None — public dashboard.
+- **Steps (N):**
+ 1. Arrive → inline module binds tab buttons (Agents / Coins) + window buttons (24h / 7d / All time), loads default (Agents, 24h).
+ 2. System: `GET /api/trending?window=24h&limit=10` renders ranked list (agents by real chat activity, with wallet chip; coins by Oracle conviction score).
+ 3. (optional) Switch tab Agents↔Coins → renders the other ranked list.
+ 4. (optional) Switch window 24h/7d/All time → re-fetch with new `window`.
+ 5. (optional) Click a row → deep link to the agent profile or coin/oracle page.
+- **Decision points / branches:** Agents vs Coins tab; 3 time windows; per-tab retry button on fetch failure.
+- **External calls / dependencies:** `GET /api/trending?window=&limit=10`.
+- **Success state:** what's hot right now — top agents and top conviction coins across windows.
+- **Empty / error states:** per-tab empty + Retry button (`#agentRetry` / `#coinRetry`).
+- **Step count:** 2 required (arrive → list) + ~3 optional (tab, window, drill-in).
+
+---
+
+### Live Trade Feed — `/trades`
+- **Source:** `pages/trades.html`, `src/trades.js` (imports `src/trader-format.js`)
+- **Entry point:** nav; footer newsletter page link.
+- **Prerequisites / gates:** None — explicitly "public, no-auth feed" of notable closed positions from all three.ws agents.
+- **Steps (N):**
+ 1. Arrive → `readUrl()` + `applyStateToControls()` restores window/minPnl/network from URL+localStorage (`tf_network`).
+ 2. System: `GET /api/trades/feed?window=24h&minPnl=25&network=mainnet` renders closed-position rows; auto-refresh every 30s (paused when deep in pagination).
+ 3. (optional) Pick time window via `#tfWinSeg` (ARIA tablist, keyboard arrows/Home/End) → reload.
+ 4. (optional) Change Min PnL (`#tfMinPnl`) → reload from cursor null.
+ 5. (optional) Change network (`#tfNetwork`, persisted to localStorage) → reload.
+ 6. (optional) Manual Refresh (`#tfRefresh`).
+ 7. (optional) Watch button per row (`.tf-watch-btn`) → toggles mint in `ld_watchlist`.
+ 8. (optional) Load more (`#tfLoadMore`) → cursor pagination.
+ 9. (optional) Click a trade row → trader/coin deep link.
+- **Decision points / branches:** window/minPnl/network filters; auto-refresh suspended while paginating; watch toggle state.
+- **External calls / dependencies:** `GET /api/trades/feed` (cursor-paginated).
+- **Success state:** filterable, shareable (URL-reflected) live feed of real closed trades with PnL.
+- **Empty / error states:** empty-feed state; standard boundary error handling on fetch.
+- **Step count:** 2 required (arrive → feed) + ~7 optional (filters, watch, paginate).
+
+---
+
+### Trader Leaderboard — `/leaderboard`
+- **Source:** `pages/leaderboard.html`, `src/leaderboard.js` (imports `src/trader-format.js`, `src/shared/agent-wallet-chip.js`)
+- **Entry point:** nav "Leaderboard"; footer.
+- **Prerequisites / gates:** None — public ranked board.
+- **Steps (N):**
+ 1. Arrive → `readUrl()` hydrates state (network/window/sort/verified), live-refreshing every 20s.
+ 2. System: `GET /api/sniper/leaderboard?network=&window=&sort=&verified=` renders ranked rows (agent name + verified badge, wallet chip, unique coins, copiers count); top 3 styled.
+ 3. (optional) Window: 24h/7d/30d/all (`#lb-window`) → URL + reload.
+ 4. (optional) Network: mainnet/devnet (`#lb-network`).
+ 5. (optional) Sort: score/pnl/winrate/roi (`#lb-sort` select).
+ 6. (optional) "Verified only" checkbox (`#lb-verified`).
+ 7. (optional) Click a row → trader profile (`src/trader.js`, `/trader?wallet=...`) — full track record, equity curve, proof tab with on-chain tx, copy-trading panel, shareable PnL card.
+- **Decision points / branches:** 4 windows × sort × network × verified; stale/reconnecting badge when a background refresh fails with a board already on screen.
+- **External calls / dependencies:** `GET /api/sniper/leaderboard`; row payoff `GET /api/sniper/trader` (on trader page).
+- **Success state:** shareable ranked board; every number deep-links to its on-chain transaction via the trader profile.
+- **Empty / error states:** "No agent has closed a sniper position in this window…" with guidance (widen window / disable verified); `#lb-retry` button on load failure; stale badge.
+- **Step count:** 2 required (arrive → board) + ~5 optional (filters, sort, drill to trader).
+
+---
+
+### Coin Radar — `/radar`
+- **Source:** `pages/radar.html`, `src/radar.js` (imports `src/shared/log.js`, mounted via `mountRadar`)
+- **Entry point:** nav; share links.
+- **Prerequisites / gates:** None — public dashboard.
+- **Steps (N):**
+ 1. Arrive → `mountRadar()` reads URL (`category`, `minQuality`), builds toolbar, polls every 12s.
+ 2. System: `GET /api/pump/coin-intel?...` renders coins observed in first ~90s of trading — classified, risk-scored ("organic, or a bundle/rug?"). Unmeasured signals render "not measured", never 0.
+ 3. (optional) Filter by category chips (meme/ai/tech/…) → URL + reload.
+ 4. (optional) Min-quality slider → reload on change.
+ 5. (optional) Watch toggle per coin → `ld_watchlist`.
+ 6. (optional) Click a coin card → detail drawer → `GET /api/pump/coin-intel?mint=<mint>&wallets=1` (single-coin wallet breakdown).
+- **Decision points / branches:** category × quality filters; risk-flag pills (bundle_launch, dev_dumped, single_whale, low_diversity, fresh_wallet_swarm, sell_pressure, sniped) with danger/warn tones; drawer open/closed.
+- **External calls / dependencies:** `GET /api/pump/coin-intel` (list) and `?mint=&wallets=1` (detail); `/api/img` for logos.
+- **Success state:** live launch-intelligence feed; every number traces to an observed on-chain trade.
+- **Empty / error states:** "not measured" for null signals; empty/loosen-filters guidance; image fallback to seeded identicon.
+- **Step count:** 1 required (arrive → live feed) + ~5 optional (filters, watch, inspect).
+
+---
+
+### Watchlist — `/watchlist`
+- **Source:** `pages/watchlist.html`, `src/watchlist.js` (imports `src/pump/coin-status-card.js`)
+- **Entry point:** nav; closes the loop from any "Watch" button across the platform (writes `ld_watchlist`).
+- **Prerequisites / gates:** None — device-local, private, no account. Synced across tabs via `storage` event.
+- **Steps (N):**
+ 1. (prerequisite) On any coin surface (oracle/radar/trades/launches/etc.) click ☆ Watch → mint stored in `ld_watchlist`.
+ 2. Arrive on `/watchlist` → `readList()` reads + validates mints (base58 32–44).
+ 3. System: for each mint mounts a live coin-status card (`mountCoinStatus` → one `/api/pump/coin` fetch/coin), with deterministic mint identicon placeholder behind real pump.fun logo; refreshes every 90s.
+ 4. System: detects tier upgrades vs `wl_last_tiers` and surfaces changes.
+ 5. (optional) Toggle alerts (`#wl-alerts`, `wl_alerts_on`).
+ 6. (optional) Clear list (`#wl-clear`).
+ 7. (optional) Click a card → full coin profile (`/launches/<mint>`).
+- **Decision points / branches:** empty list vs populated; tier-upgrade highlighting; alerts on/off; cross-tab storage sync.
+- **External calls / dependencies:** `GET /api/pump/coin` (one per watched coin, via coin-status-card).
+- **Success state:** private tracked-coin board with live status cards, tier-change detection, deep links back to profiles.
+- **Empty / error states:** empty state when no mints saved (tells user to Watch coins elsewhere); invalid mints filtered out; per-card load handled by coin-status widget.
+- **Step count:** 1 required to view (arrive) — payoff depends on the prerequisite Watch action elsewhere; + ~3 optional (alerts, clear, drill-in).
+
+---
+
+### Pump Dashboard (Token Cockpit) — `/pump-dashboard`
+- **Source:** `pages/pump-dashboard.html` (large inline module, ~5000 lines); imports `src/solana/vanity/grinder.js`, `src/solana/vanity/validation.js`, `src/shared/state-kit.js`; uses `src/wallet.js`
+- **Entry point:** nav; "Open Token Cockpit →" from `/dashboard/tokens`; `/autopilot`; sitemap; deep link `?agent=<id>` auto-opens the Default Agent panel; `#hash` deep-links any tab.
+- **Prerequisites / gates:** Public — no auth/$THREE gate for the core dashboard. Wallet connect is **optional** (unlocks Wallet snapshot). Server-backed tabs (Agents, Alert rules, API keys) return 401 → sign-in prompts. Watches/Claims tabs require a custom PumpKit backend.
+- **Steps (N):**
+ 1. Arrive → `DOMContentLoaded` bootstrap restores config from localStorage (api/ws/rpc/key), resolves `?agent=`/`#hash`, binds nav + controls.
+ 2. System: `connectApi()` polls `GET /api/healthz` (15s) → status dot; `connectWebSocket()` opens `wss://pumpportal.fun/api/data`, subscribes `subscribeNewToken` + `subscribeMigration` (exponential backoff, 8-attempt cap → manual Reconnect banner).
+ 3. System: preloads `GET /api/pump/channel-feed?limit=40`, `GET /api/pump/helius-stats` (30s), `GET /api/agents/featured`, `GET /api/pump/trending?limit=25` ($THREE pinned first), config probes, uptime ticker.
+ 4. (optional) Connect wallet → `wallet:changed` → `POST /api/wallet/balances` renders SOL + top-10 holdings.
+ 5. (optional) Default tab: inspect monitor stat cards, featured agent, network health, market chart (`chart:tokenChange` → fetch candles), high-conviction Oracle panel, live-feed preview.
+ 6. (optional) **Live Feed** tab: pause + filter (Launches/Trades/Whales/Graduations/Claims) the rAF-batched WS feed.
+ 7. (optional) **Token Scanner**: enter mint → scan for risk/honeypot.
+ 8. (optional) **Quote Engine**: buy/sell quote forms.
+ 9. (optional) **Alerts**: build a rule (type/scope/threshold/agent + in-app/webhook/Telegram delivery + cooldown) → `POST /api/alerts/rules`; list/toggle/edit/delete; live firing against feed; history from `GET /api/notifications`.
+ 10. (optional) **Vanity Generator payoff:** enter prefix/suffix → `validatePattern()` (base58, ≤6 chars) → `grindVanity()` spawns up to 8 Web Workers (WASM) → progress (tries/rate/eta) → match → reveal/copy/download keypair JSON (secret never leaves browser).
+ 11. (optional) **Default Agent**: embed `/agent-embed.html` iframe, speak/gesture via postMessage; manage custom agents (`GET /api/agents`, delete with CSRF).
+ 12. (optional) **Revenue**, **Configuration** (save + reconnect + probes), **API Reference** (create/revoke keys).
+- **Decision points / branches:** 12 hash-routed tabs; wallet connected vs empty; WS backoff (<8 retry vs ≥8 terminal banner); auth 401 on agents/alerts/keys; PumpKit backend present for Watches/Claims; vanity validation failures; simulate vs server-side alert delivery.
+- **External calls / dependencies:** `/api/healthz`, `/api/pump/helius-stats`, `/api/pump/channel-feed`, `/api/pump/trending`, `/api/agents/featured`, `/api/agents` (+CSRF), `/api/wallet/balances`, `/api/pump/scan`, `/api/pump/quote/{buy,sell}`, `/api/alerts/rules` (CRUD), `/api/notifications`, `/api/api-keys` (CRUD), revenue endpoints; `wss://pumpportal.fun/api/data`; Solana RPC via `/api/solana-rpc`; Phantom/MWA wallet; Web Workers for vanity; model-viewer CDN.
+- **Success state:** green API/WS/SOL chips, populated panels, live feed streaming, optional wallet snapshot, working alerts, vanity address found with copy/download.
+- **Empty / error states:** featured-agent retry; WS "Realtime feed stopped" + Reconnect after 8 fails; channel-feed retry (downgrades to WS); RPC error chip auto-clears 8s; sign-in prompts on 401; vanity validation toasts; designed empty states for wallet/agents/alerts/feed (state-kit).
+- **Step count:** 3 required (arrive → API/WS connect → panels populate) + ~9 optional tab/interaction flows (vanity grind and alert-rule build are the headline interactive payoffs).
+
+---
+
+### Strategy Lab — `/strategy-lab`
+- **Source:** `public/strategy-lab.html` (pre-built static; ~720 lines, text-only UI, no 3D); `vercel.json` rewrite `/strategy-lab → /strategy-lab.html`
+- **Entry point:** nav / direct URL; `data/pages.json` + changelog entry.
+- **Prerequisites / gates:** Validate + Backtest + Simulate run are **public** (read-only MCP, real on-chain data, no signing). **Live run** requires sign-in, an agent with a provisioned Solana wallet, balance ≥ 0.02 SOL, and an explicit confirmation dialog. Network toggle mainnet/devnet.
+- **Steps (N):**
+ 1. Arrive → spec editor + results/portfolio panels render; `GET /api/agents` populates agent dropdown if signed in; pick network.
+ 2. (optional) Select agent → `onAgentChange()` → `GET /api/agents/{id}/solana?network=` shows wallet address + balance; provision via `POST` if none; low-balance warning < 0.02 SOL.
+ 3. Load a preset (Momentum / Snipe / Mean-revert) **or** hand-edit the JSON spec (`scan`, `filters`, `entry`, `exit`, `caps`).
+ 4. **Validate** → `POST /api/pump/strategy-validate` → "Valid — N filters, M exit rules" or red issues list.
+ 5. (optional) **Backtest** → `POST /api/pump/strategy-backtest` (real on-chain data, no auth) → metrics grid (PnL, ROI, win rate, trades, max drawdown, SOL deployed) + per-trade table.
+ 6. **Run** → `POST /api/pump/strategy-run` `{durationSec, mode:'simulate'|'live', network, agentId?}` → SSE stream of start/log/enter/exit/skip/done events into the live activity log.
+ 7. (optional) **Stop** (`activeRun.abort()` → "■ stopped").
+ 8. (optional) **Portfolio** panel auto-loads on agent select → `GET /api/pump/portfolio?agentId=&network=` (holdings, cost basis, unrealized PnL); **Close All** → `POST /api/pump/strategy-close-all` market-sells everything.
+- **Decision points / branches:** preset vs custom spec; Validate→Backtest→Run pipeline; simulate (public) vs live (gated, signs real tx); mainnet vs devnet; portfolio empty vs holdings; balance/auth gates on live.
+- **External calls / dependencies:** `/api/agents`, `/api/agents/{id}/solana` (GET+POST), `/api/pump/strategy-validate`, `/api/pump/strategy-backtest`, `/api/pump/strategy-run` (SSE), `/api/pump/portfolio`, `/api/pump/strategy-close-all`; backend MCP → Solana RPC + pump.fun indexer; agent hot wallet signs in live mode.
+- **Success state:** spec validates clean; backtest returns trade history + ROI; run executes entries/exits with live-streaming log; portfolio reflects on-chain holdings; positions closable any time.
+- **Empty / error states:** "select agent" / "No Solana wallet"; "Invalid — N errors" issues panel; backtest error; low-balance warning; "no token holdings"; "■ stopped"; errors surfaced with `error_description`.
+- **Step count:** 4 required (arrive → spec → Validate → Run, simulate path) + ~4 optional (backtest, portfolio, close-all, live mode). Most interactive route in the cluster.
+
+---
+
+### Smart Money Radar — `/smart-money`
+- **Source:** `pages/smart-money.html` (self-contained inline module); backend `api/pump/smart-money.js`
+- **Entry point:** nav; share links.
+- **Prerequisites / gates:** None — public, IP rate-limited only; CORS `*`.
+- **Steps (N):**
+ 1. Arrive → inline module reads `ld_watchlist`, renders 6 skeletons, calls `refresh()`; auto-refresh every 20s (pauses when tab hidden).
+ 2. System: `GET /api/pump/smart-money?limit=60` (feed: coins ranked by smart_money_score, proven-wallet count, smart buy volume) + parallel `?leaderboard=1&limit=60` (top wallets by reputation).
+ 3. (optional) Switch tab Feed ↔ Top wallets.
+ 4. (optional) Watch toggle per coin → `ld_watchlist`.
+ 5. (optional) Click coin → drawer `GET /api/pump/smart-money?mint=<mint>` (notable wallets, labels) + async `GET /api/oracle/coin?mint=` to enrich with conviction pillars.
+ 6. (optional) Click wallet → drawer `GET /api/pump/smart-money?wallet=<addr>` (win rate, record, recent coins).
+- **Decision points / branches:** Feed vs wallets tab; coin scored vs "not scored"; wallet has record vs none; Oracle enrichment present vs absent.
+- **External calls / dependencies:** `GET /api/pump/smart-money` (feed / `?leaderboard=1` / `?mint=` / `?wallet=`), async `GET /api/oracle/coin`. Data sourced from `coin_smart_money` + `wallet_reputation` tables fed by the off-browser sniper engine — no direct browser RPC/WS.
+- **Success state:** 60 fresh coins ranked by buyer pedigree; wallet reputation board (smart_money/sniper/dumper/rugger labels); coin + wallet drawers.
+- **Empty / error states:** "No proven money on a fresh coin yet"; "No wallets ranked yet"; drawer "Not scored yet" / "No track record yet"; "Couldn't reach the radar" + Retry; stale badge with last-update + "Retry now".
+- **Step count:** 1 required (arrive → feed) + ~5 optional (tab, watch, inspect coin/wallet).
+
+---
+
+### Coin Intelligence — `/coin-intel`
+- **Source:** `pages/coin-intel.html` (self-contained inline module); backend `api/pump/intel.js`
+- **Entry point:** nav; share links. (Distinct from `/api/pump/coin-intel` used by `/radar`.)
+- **Prerequisites / gates:** None — public, IP rate-limited; CORS `*`.
+- **Steps (N):**
+ 1. Arrive → inline module reads `ld_watchlist`, renders category chips + 6 skeletons; `loadStats()` (`?view=learning`) + `loadRadar()`; auto-refresh 15s.
+ 2. System: `GET /api/pump/intel?view=feed&limit=60` renders cards (quality score ring 0–100, verdict pill strong/watch/caution/avoid, organic-vs-bundle bar, risk flags, narrative).
+ 3. (optional) Toolbar filters: search (220ms debounce), category chips, verdict dropdown, quality dropdown → `loadRadar()`.
+ 4. (optional) Watch toggle per coin → `ld_watchlist`.
+ 5. (optional) Switch tab: Radar / Leaderboard (`?view=leaderboard`) / Smart-Money Traders (`?view=traders`) / What it learned (`?view=learning`, signal weights + outcome distribution + coverage).
+ 6. (optional) Click coin → drawer `GET /api/pump/intel?mint=<mint>` (full signals + outcome + top wallets classified + funder clusters/bubble-map) + async `GET /api/oracle/coin?mint=` conviction enrichment.
+- **Decision points / branches:** 4 tabs; filter combinations; coin observed vs "not observed"; labeled winners vs none; ≥50 labeled coins for trained weights vs baseline; Oracle enrichment present vs absent.
+- **External calls / dependencies:** `GET /api/pump/intel` (`view=feed|leaderboard|traders|learning`, `?mint=`), async `GET /api/oracle/coin`. Data from `pump_coin_intel`, `pump_coin_outcomes`, `pump_coin_wallets`, `pump_intel_weights` (off-browser engine). No direct browser RPC/WS.
+- **Success state:** live classified-coin radar with verdicts + risk flags; leaderboard of best coins + confirmed winners (ATH multiple); cross-coin trader board; "what it learned" signal-weight transparency; per-coin bubble-map drawer.
+- **Empty / error states:** "The engine is warming up"; "No coins match these filters" + Reset; drawer "Not observed yet"; "No labeled winners yet"; "No traders recorded yet"; "Not enough data to train yet"; degraded badge; retry on network failure.
+- **Step count:** 2 required (arrive → radar feed) + ~6 optional (search/filters, watch, tabs, inspect coin).
+
+---
+
+### GMGN Smart Money — `/gmgn`
+- **Source:** `public/gmgn.html` (pre-built static; ~900 lines); backend `api/agents/gmgn.js`; `vercel.json` rewrite `/gmgn → /gmgn.html`, `/api/agents/gmgn-feed → /api/agents/gmgn?_handler=feed`
+- **Entry point:** nav / direct URL.
+- **Prerequisites / gates:** None — public live feed. Narration needs browser Web Speech API; "My agents" avatar tab needs auth.
+- **Steps (N):**
+ 1. Arrive → 3D agent (CZ default) loads into `<model-viewer>` (auto-rotate); params parsed (chain=sol, interval=1h, minSmartBuys=2, narrate, avatar, mood).
+ 2. System: SSE `EventSource('/api/agents/gmgn-feed?chain=sol&interval=1h&minSmartBuys=2')` → `hello` event (status pill "Live · SOL · 1h"), last 10 events replayed (dimmed), then `smart_entry` events stream live.
+ 3. System per event: render card (symbol, market cap, smart-buy delta, price change), trigger agent animation by delta/new flag, optional TTS narration, increment stats, "↑ N new" jump button if scrolled.
+ 4. (optional) Change chain (sol/eth/base/bsc), interval (1m–24h), minSmartBuys; mood (chill/normal/hype); narration toggle.
+ 5. (optional) Avatar picker modal → `GET /api/avatars/public` + `GET /api/avatars` → "Use this avatar" swaps model.
+ 6. (optional) **Apply** (`#ctl-reconnect`) → `connect()` closes old EventSource, opens new with updated params.
+ 7. (optional) $THREE spotlight tile updates when smart-money activity hits CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.
+- **Decision points / branches:** chain/interval/minSmartBuys filters; narration on/off; mood; default vs community vs my-agents avatar tabs; manual vs auto reconnect.
+- **External calls / dependencies:** SSE `/api/agents/gmgn-feed` (upstream GMGN.ai feed via `connectGmgnFeed`); `/api/avatars/public`, `/api/avatars`; model-viewer CDN.
+- **Success state:** green live dot; smart-money entries stream with animated, optionally-speaking agent; stats tick; instant reconnect on filter change.
+- **Empty / error states:** "Connecting…" (yellow); "Waiting for events…"; "Error — retrying…" with 4–5s backoff auto-reconnect; "Session ended — reconnecting…"; avatar load error recoverable via re-pick.
+- **Step count:** 2 required (arrive → SSE feed) + ~5 optional (filters, mood, avatar, reconnect). Mostly a live monitor with reactive avatar.
+
+---
+
+### Pump.fun Live Agent — `/pumpfun`
+- **Source:** `public/pumpfun.html` (pre-built static; ~2000 lines); backend `api/agents/pumpfun.js`; `vercel.json` rewrites `/pumpfun → /pumpfun.html`, `/api/agents/pumpfun-feed → /api/agents/pumpfun?_handler=feed`, `…pumpfun-metadata → ?_handler=metadata`
+- **Entry point:** nav / direct URL; `?asset=<pubkey>` binds a specific agent.
+- **Prerequisites / gates:** Public for the live feed. Binding an agent / viewing its wallet needs auth (`GET /api/agents`). Provisioning a wallet is a `POST`.
+- **Steps (N):**
+ 1. Arrive → 3D agent (CZ default) renders; params parsed (asset, mint, kind=all/mint/graduation/claims, tier, mcMin/mcMax, minBuy, whale, narrate, mood, avatar).
+ 2. (optional) `GET /api/agents` → pick agent → `onAgentChange()` → `GET /api/agents/{id}/solana?network=mainnet` shows wallet/balance; provision via `POST` if none.
+ 3. System: SSE `/api/agents/pumpfun-feed?...` (withCredentials) → `hello`, replay buffer (~30 events dimmed), then `evt` events (mint/trade/graduation/claim) stream live; agent animates + optionally narrates per configured emotion/TTS map.
+ 4. System: first-time fee-claims sidebar refreshes from `GET /api/pump/first-claims?limit=50&sinceMinutes=1440`.
+ 5. (optional) Filters: asset, mint search, event kind, min tier (notable+/influencer+/mega), MC range, min buy SOL, whale threshold.
+ 6. (optional) Config modal: map emotions→animations and actions→TTS templates (stored in localStorage); narration/announce-mints/mood toggles.
+ 7. (optional) Share/copy filter-encoded link.
+- **Decision points / branches:** public feed vs agent-bound (enriches via `?_handler=metadata`); event-kind/tier/MC/whale filters; narration + emotion config; provisioned wallet vs none.
+- **External calls / dependencies:** SSE `/api/agents/pumpfun-feed` (upstream Helius webhooks), `/api/agents`, `/api/agents/{id}/solana` (GET+POST), `/api/pump/first-claims`, `/api/agents/{id}/pumpfun/metadata`, avatars endpoints; model-viewer CDN.
+- **Success state:** live launch/trade/graduation/claim feed with reacting, narrating 3D agent; first-claims sidebar; accurate wallet info.
+- **Empty / error states:** "Waiting for events…"; quiet/no-events feed dot; "No Solana wallet on this agent" + provision; upstream error soft-degrades to empty `{items:[]}`; reconnect cycle.
+- **Step count:** 1 required (arrive → live feed) + ~6 optional (agent bind, filters, emotion config, share). Live monitor + reactive agent (+ optional agent-management).
+
+---
+
+### Pump Visualizer (3D) — `/pump-visualizer`
+- **Source:** `pages/pump-visualizer.html` (inline Three.js module: OrbitControls + EffectComposer/UnrealBloom); `vercel.json` rewrite `/pump-visualizer → /pump-visualizer.html`
+- **Entry point:** nav / direct URL.
+- **Prerequisites / gates:** None — public. WebGL required; degrades to DOM list fallback if unavailable.
+- **Steps (N):**
+ 1. Arrive → theme/nav boot; WebGL capability check → build Three.js scene (camera fly-in, starfield, bloom, auto-rotating OrbitControls).
+ 2. System: `GET /api/pump/trending?limit=50&rich=1` (+ `GET /api/pump/helius-stats` for SOL→USD) renders top-50 tokens as spheres on a Fibonacci sphere, sized by log market cap, colored by tier, with lazy artwork via `/api/img`; staggered pop-in.
+ 3. System: reveals mode tabs (Feed/Migrations/Trending), search, sort buttons, top-20 legend, color key, hint.
+ 4. (optional) Drag to orbit / scroll to zoom (OrbitControls).
+ 5. (optional) Search (`/` hotkey) → filter legend + dim non-matching spheres; sort by Mcap/Streams/Replies/New; refresh (`R`).
+ 6. (optional) Feed/Migrations mode → SSE `/api/agents/pumpfun-feed?kind=mint|graduation` adds spheres live (capped 60).
+ 7. (optional) Hover sphere (tooltip), click → detail panel (`selectToken`), legend click → camera tween + panel.
+ 8. (optional) In detail panel: Watch (`ld_watchlist`), Oracle badge (`GET /api/oracle/coin?mint=`), Buy (lazy `src/game/coin-buy.js` on-chain trade modal); double-click sphere → `/coin3d?mint=`.
+- **Decision points / branches:** WebGL present vs list fallback; Feed/Migrations/Trending mode; search/sort; Oracle enrichment optional; Buy is the real interactive (on-chain) action.
+- **External calls / dependencies:** `GET /api/pump/trending`, `/api/pump/recent-graduations`, `/api/pump/helius-stats`, `/api/img`, `GET /api/oracle/coin`; optional SSE `/api/agents/pumpfun-feed`; `wss://pumpportal.fun/api/data` referenced for live mode.
+- **Success state:** 50 glowing spheres in an auto-rotating galaxy, sized/colored by market cap, with detail panel, search/sort, and on-chain Buy.
+- **Empty / error states:** WebGL warning banner + DOM list fallback; "Could not load trending tokens" + Retry; image canvas fallback; Oracle badge silently empty if down.
+- **Step count:** 2 required (arrive → spheres render) + ~6 optional (orbit, search/sort, mode, inspect, Buy/Watch). Live-monitor + interaction hybrid.
+
+---
+
+### Pump Live Feed (3D Agent) — `/pump-live`
+- **Source:** `pages/pump-live.html` (inline module + imports `src/viewer.js`, Three.js); `vercel.json` rewrite `/pump-live → /pump-live.html`
+- **Entry point:** nav; footer.
+- **Prerequisites / gates:** None — public live monitor. 3D agent is optional (feed works without WebGL/GLB).
+- **Steps (N):**
+ 1. Arrive → feed module starts immediately (does NOT wait on Three.js); skeleton cards; viewer.js + GLB load in parallel.
+ 2. System: `GET /api/pump/helius-stats` for SOL price (caps shown in SOL until USD lands, then rehydrated).
+ 3. System: connect `wss://pumpportal.fun/api/data`, send `subscribeNewToken` → "● Live"; each `create` event → render token card (image via `/api/img?meta=`, MC, links, empty Oracle slot), prepend (cap 100), update stats, dispatch `pumplive:token`.
+ 4. System: every 30s batch `POST /api/oracle/batch?mints=...` (chunks ≤20, retry 2×) → conviction badges on cards; "🔮 Prime scored" counter.
+ 5. (optional) 3D agent loads `robotexpressive.glb`, plays Idle, waves on each `pumplive:token`.
+ 6. (optional) Pause button (queues events); conviction filter All/Strong+/Prime (hides cards); Watch toggle (`ld_watchlist`); click card → `/coin3d?mint=` or external links.
+- **Decision points / branches:** WebGL/GLB present vs feed-only; paused vs streaming; conviction filter level; Oracle up vs down (badges empty).
+- **External calls / dependencies:** `wss://pumpportal.fun/api/data`; `GET /api/pump/helius-stats`; `POST /api/oracle/batch`; `GET /api/img`; `robotexpressive.glb`.
+- **Success state:** live launches stream as cards, stats tick, agent waves per launch, Oracle conviction badges enrich after ~30s, filterable.
+- **Empty / error states:** "Waiting for new launches…"; WS backoff 2s→60s, terminal error panel + Reconnect after 8 fails; SOL-price hint until USD lands; image seeded placeholder; agent load failure suppressed (feed unaffected).
+- **Step count:** 1 required (arrive → live feed) + ~4 optional (pause, filter, watch, drill-in). Pure live monitor + reactive avatar.
+
+---
+
+### Constellation — `/constellation`
+- **Source:** `pages/constellation.html`, `src/constellation/main.js` (~500 lines), `src/constellation/embedding.js` (PCA/MDS + neighbor lookup)
+- **Entry point:** nav / direct URL.
+- **Prerequisites / gates:** None — public. WebGL required (fatal overlay if absent, no fallback). IBM Granite (watsonx) optional — without it, tokens place by rank instead of semantic space.
+- **Steps (N):**
+ 1. Arrive → boot WebGLRenderer + Three.js scene (camera, starfield, auto-rotate OrbitControls); fatal overlay if WebGL missing.
+ 2. System: `GET /api/pump/trending?limit=64` → ≥3 valid tokens placed on a Fibonacci sphere (rank layout), colored by hue; loading overlay dismisses.
+ 3. System (optional/semantic): `POST /api/watsonx/embed` → 1024-d vectors → PCA to 3 axes → nodes lerp from rank positions into semantic clusters; status "Embedded by IBM Granite · model · 1024d".
+ 4. (optional) Drag to orbit / scroll to zoom.
+ 5. (optional) Hover star → glow + tooltip (symbol/name).
+ 6. (optional) Click star → right detail panel (symbol, name, logo, price, rank, nearest semantic neighbors, Pump.fun/Solscan links).
+ 7. (optional) **Analysis payoff:** click "Analysis by IBM Granite" → `POST /api/brain/chat {provider:'ibm-granite', system: analyst, messages, maxTokens:400}` (SSE) → streams a live token analysis into the panel; Esc/close to dismiss.
+- **Decision points / branches:** WebGL present vs fatal; Granite configured (semantic layout + analysis) vs unconfigured (rank layout, analysis notice); rate-limited; <3 tokens → fatal.
+- **External calls / dependencies:** `GET /api/pump/trending?limit=64`; `POST /api/watsonx/embed`; `POST /api/brain/chat` (SSE).
+- **Success state:** 64-star galaxy clustered by semantic similarity, hover tooltips, detail panel, and streaming Granite analysis per token.
+- **Empty / error states:** WebGL fatal overlay; "No trending tokens right now"; "Semantic layout off — IBM Granite isn't configured… placing by rank"; analysis notices (unconfigured / rate-limited / stream error); trending-fetch failure message.
+- **Step count:** 2 required (arrive → galaxy renders) + ~5 optional (orbit/zoom, hover, select, Granite analysis). Live-data exploration + AI analysis.
+
+---
+
+## Notes on sourcing
+- All 16 routes located and traced to real source. No missing sources.
+- `/gmgn`, `/pumpfun`, `/strategy-lab` are **pre-built static** pages in `public/` (not `pages/`), wired by `vercel.json` rewrites — easy to miss in a `pages/` listing.
+- `/coin-intel` (page `api/pump/intel`) and `/radar` (`api/pump/coin-intel`) are two distinct engines despite similar names — do not conflate.
+- The leaderboard/activity payoff is the trader profile at `/trader` (`src/trader.js`), reached by drilling into a row — outside this cluster's enumerated routes but noted as the terminal step.
diff --git a/docs/ux-flows/08-coin-launch-wallets.md b/docs/ux-flows/08-coin-launch-wallets.md
new file mode 100644
index 000000000..587ee8e6a
--- /dev/null
+++ b/docs/ux-flows/08-coin-launch-wallets.md
@@ -0,0 +1,266 @@
+# Coin Launch & Wallets
+
+UX Flow Atlas — Cluster 08. Traced end-to-end against real source. Routes resolved
+via `vercel.json` rewrites → page HTML → imported modules. All on-chain paths use
+real Solana/EVM RPC, pump.fun, and x402 — no mocks.
+
+> Coin rule: the launcher is generic coin-agnostic plumbing — the user supplies
+> their own name/symbol/description/mint at runtime. The platform's own promoted
+> coin is `$THREE` (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`), surfaced
+> on `/three` and `/three-live`. The launch flow stamps every minted address with
+> the leading `3ws` brand mark.
+
+---
+
+### Launch a Coin — `/launch`
+- **Source:** `pages/launch.html` (inline module imports `/launch/launch.js`) → `public/launch/launch.js` (`mountLaunchCoin`) → `public/studio/launch-panel.js` (`mountLaunchPanel`, the real flow) → `public/studio/fees-panel.js` (`mountFeesPanel`, post-launch). Vanity stamp: `src/solana/vanity/grinder.js` + `src/solana/vanity/brand.js` (`THREE_WS_VANITY`).
+- **Entry point:** `#launch-root` mounts a two-column shell: agent picker (left, `launch.js`) + launch panel (right, `launch-panel.js`).
+- **Prerequisites / gates:**
+ - Account/session required to actually launch (`GET /api/auth/me`). Signed-out users see the guided empty state; the launch button reads "Sign in to launch."
+ - A non-demo agent/avatar must be selected (panel refuses `__demo__`).
+ - Wallet source: either a connected Solana wallet (Phantom/Backpack/Solflare/backpack) that is SIWS-**linked** to the account, OR a custodial agent wallet.
+ - SOL balance ≥ estimated cost (`PUMP_BASE_COST` 0.022 SOL + initial buy). USDC coin type debits the buy from the wallet's USDC ATA instead of SOL.
+- **Steps (N):**
+ 1. Page boots: `fetchMe()` then `fetchAvatars()` (`GET /api/avatars?limit=100`). Picker shows 3 shimmer skeletons while loading.
+ 2. Picker renders agent cards; `?avatar=<id|slug>` deep link is honored, else the first agent is auto-selected. Panel pre-fills name/symbol/description from the avatar.
+ 3. Panel auto-checks for an existing mint for the selected agent (`GET /api/pump/by-agent?agent_id=|avatar_id=`). If one exists, it shows the "Token already launched" card with stats + Fees & rewards panel (skip to step 16) unless the user clicks "Launch a new token."
+ 4. (optional) User edits the **token image** — click/drag-drop a file (≤4 MB), or "📸 Use 3D view" to snapshot the preview canvas (only when a preview viewer is present, i.e. studio mount).
+ 5. User edits **name** (≤32 chars), **symbol** (≤10 codepoints, any chars incl. emoji; auto-derived from name until edited), **description** (≤500).
+ 6. User picks a **coin type**: Regular / Mayhem / Agent (default, buyback-bound) / USDC / Reward.
+ 7. (optional, Agent/USDC only) User sets the **buyback share** slider (0–50%, `buybackBps` 0–5000).
+ 8. (optional) User sets an **initial buy** (SOL, max 50; or USDC, max 1,000,000). Live cost line in the wallet bar updates as they type.
+ 9. User picks **wallet source** via the tab toggle: "Connected wallet" or "Agent wallet (custodial · server-signed)."
+ 10a. **Connected-wallet path:** if no wallet detected → "Install Phantom" opens phantom.app. If detected but not connected → "Connect" calls `wallet.connect()`. Balance polls every 30s via `/api/solana-rpc`. (optional) "Deposit" opens a modal with a Solana Pay QR + copyable address.
+ 10b. If the connected wallet is not SIWS-linked → "Link wallet" button runs the link ceremony: `POST /api/auth/wallets/nonce-solana` → `provider.signMessage` → `POST /api/auth/wallets/link-solana`. A 409 (`address_in_use`) flips to a "Transfer wallet to this account" confirmation that re-signs with `takeover:true`.
+ 10c. **Agent-wallet path:** `POST /api/pump/agent-wallet` provisions/resolves the custodial wallet, returns address + lamports/sol. (optional) "Fund" opens a deposit modal (QR + address); balance polls every 30s.
+ 11. User clicks **Launch $SYMBOL**. The button's `data-action` routes: sign-in / focus-first-missing-field / connect / link / agent-fund / agent-retry / launch.
+ 12. **Build metadata** (both paths): phase `building` — if image present, `fileToDataUrl`, then `POST /api/pump/build-metadata` → `metadata_url` (cached by name|symbol|desc|hasImage key).
+ 13a. **Connected-wallet launch:** phase `stamping` — client grinds the `3ws` mint keypair via `grindVanity(THREE_WS_VANITY)` with live k/s + ETA progress. Then phase `signing` → `POST /api/pump/launch-prep` (sends `wallet_address`, `mint_address` = ground pubkey, coin_type, buyback_bps, buy-in, network=mainnet) → returns `tx_base64` + `prep_id`. Deserialize `VersionedTransaction`, `wallet.signTransaction`, then co-sign with the ground mint keypair.
+ 13b. Phase `confirming` — `conn.sendRawTransaction(skipPreflight:false)` over `/api/solana-rpc`, then `pollConfirmation` (75s, 2s interval). On confirm → `finalizeConfirm`: `POST /api/pump/launch-confirm` with `prep_id` + `tx_signature` → echoes `pump_agent_mint.mint`.
+ 14a. **Agent-wallet launch:** phase `stamping` (server stamps `3ws`), then phase `confirming` → `POST /api/pump/launch-agent` (server signs + submits with the custodial key, ~10s) → returns `mint`. Agent balance refreshes.
+ 15. Phase `success` — success card shows the stamped mint (with the `3ws` mark visually emphasized), "✓ three.ws coin" badge, links to pump.fun / Solscan / the agent page, "Copy launch announcement," and "Launch another token."
+ 16. (existing-token branch) Fees & rewards panel mounts against the mint for claim/delegation management.
+- **Decision points / branches:**
+ - Existing mint found → existing-token card vs. "force new."
+ - Coin type: Regular / Mayhem (high-volatility, no buyback) / Agent (SOL buyback+burn) / USDC (stablecoin-paired agent) / Reward (delegated creator fees; launches as a plain coin, fees split post-graduation). USDC & Reward both remap server-side (`coin_type: 'agent'` / `'regular'`).
+ - Wallet source: connected (client-grinds mark, client-signs) vs. agent (server-grinds, server-signs).
+ - Connected path may require a one-time SIWS link, and a link may hit a takeover branch.
+ - Confirmation timeout → escape-hatch screen ("Finalize once confirmed" re-checks signature status, "Start over").
+- **External calls / dependencies:** `/api/auth/me`, `/api/avatars`, `/api/pump/by-agent`, `/api/auth/wallets`, `/api/auth/wallets/nonce-solana`, `/api/auth/wallets/link-solana`, `/api/pump/agent-wallet`, `/api/pump/build-metadata`, `/api/pump/launch-prep`, `/api/pump/launch-confirm`, `/api/pump/launch-agent`, `/api/solana-rpc` (Connection RPC). External: `esm.sh/@solana/[email protected]`, `esm.sh/[email protected]`, pump.fun (mint target), Solscan (links).
+- **Success state:** `lp-ok` card — stamped mint, verified badge, pump.fun/Solscan/agent-page links, share-announcement copy, relaunch button. The coin appears in `/launches` within 60s via live refresh.
+- **Empty / error states:** signed-out / no-avatar guided onboarding (4-step explainer + coin-type legend + cost note); "Checking for existing token…"; per-phase `lp-phase` status line; `friendlyError()` maps rejections/insufficient SOL/no-wallet/rate-limit to plain copy; confirmation-timeout escape hatch; agent-wallet error/retry/provision states; insufficient-balance "Fund" CTA.
+- **Step count:** 15 required (+5 optional)
+
+---
+
+### Launch Feed — `/launches` (and `/launches/:mint` detail)
+- **Source:** `pages/launches.html` → `src/launches.js`. Imports `src/pump/coin-status-card.js` (`mountCoinStatus`), `src/shared/agent-wallet-chip.js` (`walletChipEl`).
+- **Entry point:** `#lx-feed` (card grid), hero stats, network/oracle filter buttons, marquee ticker, ambient particle canvas.
+- **Prerequisites / gates:** None — fully public, read-only.
+- **Steps (N):**
+ 1. Boot reads URL params: `network` (mainnet|devnet), `agent_id` (UUID), `oracle_tier` (prime|strong|lean). Starts the particle field; renders 8 skeletons.
+ 2. `loadPage()` → `GET /api/pump/launches?network=&offset=&limit=24[&agent_id=&min_tier=]`. Registry rows render immediately as cards.
+ 3. Per mainnet card, `mountCoinStatus` fetches `GET /api/pump/coin?mint=` and streams price / logo / market cap / graduation over the seeded identicon placeholder. Devnet cards show a static identity line.
+ 4. After each page, `enrichCardsWithOracle` batch-fetches `GET /api/oracle/batch?mints=…&network=mainnet` (≤20/req) and paints a conviction tier badge.
+ 5. (optional) User toggles **network**, picks an **Oracle tier**, or applies an **agent filter** (chip resolved via `GET /api/agents/:id`) — each resets and reloads the feed; URL is kept in sync.
+ 6. (optional) User clicks **Load more** (offset paginates) or stars a coin (localStorage `ld_watchlist`).
+ 7. Live refresh every 60s re-checks page zero and prepends genuinely new launches.
+ 8. (optional) Per card: open coin detail (`/launches/:mint`), pump.fun, 3D view (`/coin3d?mint=`), 3D world (`/communities/:mint`), or the launching agent's profile.
+- **Decision points / branches:** mainnet vs devnet (devnet → Explorer link, no market data); filtered vs. unfiltered empty state; watchlist toggle.
+- **External calls / dependencies:** `/api/pump/launches`, `/api/pump/coin`, `/api/oracle/batch`, `/api/agents/:id`. External: pump.fun, Solscan, Solana explorer (links).
+- **Success state:** populated card grid with live market data, ticker, hero stats (count / latest / network).
+- **Empty / error states:** "No launches yet" (with Create-agent / Forge CTAs) or "No matching launches" (Clear-filters) for filtered views; devnet-specific copy; `renderError` with Retry; per-card identicon fallback when pump.fun art is missing.
+- **Step count:** 4 required (+4 optional)
+
+---
+
+### Claim Wallet (Trader Card) — `/claim-wallet`
+- **Source:** `pages/claim-wallet.html` → `src/claim-wallet.js`.
+- **Entry point:** `#cwInput` address field + `#cwBtn` Preview; results render in `#cwResult`.
+- **Prerequisites / gates:** Preview is public. Claiming requires sign-in AND control of the keypair (SIWS signature). The claimed wallet must equal the connected wallet.
+- **Steps (N):**
+ 1. Boot warms `GET /api/auth/me`. `?wallet=` param pre-fills + auto-previews.
+ 2. User pastes a base-58 Solana wallet; client validates with `WALLET_RE`.
+ 3. Click **Preview** → `GET /api/traders/preview?wallet=` → renders the Trader Card: label, win rate / early-win / smart-money score / net PnL / dumps stats, and up to 15 recent pump.fun coins.
+ 4. CTA branches by state: claimed (View card + Share) / signed-in-unclaimed (Claim button) / signed-out (Sign-in-to-claim link). Claimed status verified via `GET /api/auth/wallets` (filtered to chain_type=solana).
+ 5. (claim) User clicks **Claim this wallet** → detect provider → `provider.connect()`. If connected pubkey ≠ previewed wallet, abort with a switch-wallet message.
+ 6. `POST /api/auth/wallets/nonce-solana` → `provider.signMessage` (gasless, no tx) → base64.
+ 7. `POST /api/auth/wallets/link-solana` with message+signature. A 409 `address_in_use` prompts a `window.confirm` takeover; on confirm, re-POST with `takeover:true`.
+ 8. On success, re-read linked wallets (force) and re-render in the claimed state; message "Claimed — your Trader Card is live."
+- **Decision points / branches:** claimable+known vs. not-indexed (`notFoundHtml`); signed-in vs out; wallet-mismatch; takeover confirm; share via Web Share API vs Twitter intent.
+- **External calls / dependencies:** `/api/auth/me`, `/api/traders/preview`, `/api/auth/wallets`, `/api/auth/wallets/nonce-solana`, `/api/auth/wallets/link-solana`. Wallet providers: Phantom/Solana/Backpack/Solflare.
+- **Success state:** "Your Trader Card is live" card with View (`/trader/:wallet`) + Share buttons; linked row reflected server-side.
+- **Empty / error states:** invalid-address inline error; "Wallet not yet indexed" not-found state; signature-cancelled message; per-step error toasts on the claim button.
+- **Step count:** 8 required (claim path; preview alone is 3)
+
+---
+
+### Solana Vanity Wallet — `/vanity-wallet`
+- **Source:** `public/vanity-wallet.html` (self-contained inline module). Grinder: `src/solana/vanity/grinder.js` (`grindVanity`); validation: `src/solana/vanity/validation.js`.
+- **Entry point:** Prefix / suffix inputs, case-insensitive toggle, CPU-core slider, Generate button.
+- **Prerequisites / gates:** None to grind (runs entirely in-browser; keys never leave the device). Assigning the result to an agent requires sign-in.
+- **Steps (N):**
+ 1. User types a **prefix** ("Starts with", ≤6) and/or **suffix** ("Ends with", ≤6); live base-58 validation, difficulty meter, and per-core ETA update.
+ 2. (optional) Toggle **case-insensitive** (much faster). (optional) Click a suggested pattern chip. (optional) Adjust **CPU cores** (slider + presets; defaults to half of hardware concurrency).
+ 3. Click **Generate wallet** → `grindVanity({ prefix, suffix, ignoreCase, maxWorkers })` spins a Web Worker pool. Live attempts/sec, ETA, and an animated scan line.
+ 4. (optional) **Pause/Resume** or **Stop** (AbortController) mid-grind.
+ 5. On hit → result card: highlighted address, attempts/duration/rate stats, **Download keypair (Solana CLI JSON)**, **Copy public key**, and a "save before leaving" warning.
+ 6. (optional) **Assign to an agent**: `GET /api/agents`. If 401 → sign-in prompt; if none → create-agent prompt; else select an agent + check the custody-ack box.
+ 7. (optional, assign) If the agent already has a wallet, the flow switches to "Replace" — `DELETE /api/agents/:id/solana` first, then `POST /api/agents/:id/solana` with `secret_key` (array) + `vanity_prefix`/`vanity_suffix`. 409 handled. Success confirms "encrypted server-side" custody transfer.
+- **Decision points / branches:** prefix vs suffix vs both; case-sensitive vs insensitive; assign vs keep self-custody; replace-existing-wallet branch.
+- **External calls / dependencies:** None for grinding (client-side WASM ed25519 workers). Assign: `/api/agents`, `/api/agents/:id/solana` (POST + DELETE).
+- **Success state:** vanity address found + downloadable keypair; optionally "Assigned to <agent>" with an open-agent link.
+- **Empty / error states:** invalid-Base58 preview; combined-length-over-max warning; grind-failed error; assign 401/empty/409/network errors each handled inline.
+- **Step count:** 3 required (+4 optional)
+
+---
+
+### EVM CREATE2 Vanity (contract address) — `/eth-vanity`
+- **Source:** `public/eth-vanity.html` (inline module). Grinder: `src/eth/vanity/grinder.js` (`grindCreate2Vanity`); validation: `src/eth/vanity/validation.js`; wordlist: `src/eth/vanity/wordlist.js`. (Card variant also in `src/agent-eth-vanity-card.js` for agent pages.)
+- **Entry point:** Prefix/suffix inputs, deployer-factory address, init-code-hash (or raw init code to auto-hash), Grind button.
+- **Prerequisites / gates:** None to grind (computes a salt, not a private key — fully deterministic, in-browser). Assign-to-agent requires sign-in.
+- **Steps (N):**
+ 1. User enters a hex **prefix/suffix** (EIP-55 case-sensitive if any A–F uppercase), a **deployer/factory** address (preset chips e.g. Arachnid available), and an **init code hash** (or pastes raw init code → auto-keccak to fill the hash).
+ 2. Live preview + EIP-55 case-sensitivity tag + per-core ETA; Grind enabled only when deployer + hash + pattern all validate.
+ 3. Click **Grind** → `grindCreate2Vanity({ deployer, initCodeHash, prefix, suffix })` worker pool grinds salts; live attempts/rate/ETA + animated scan.
+ 4. (optional) **Cancel** (AbortController).
+ 5. On hit → result card: predicted address (checksummed when case-sensitive), **salt**, deployer, initCodeHash. Copy salt / copy address / **Download JSON**.
+ 6. (optional) **Assign to an agent**: `GET /api/agents` → select → `POST /api/agents/:id/eth-vanity` with deployer/salt/init_code_hash/(raw init_code)/predicted_address/pattern. 409 → confirm replace → DELETE then re-POST. No private key stored (the record is a deterministic CREATE2 input set).
+- **Decision points / branches:** raw-initcode-provided (enables one-click deploy later, Arachnid-only) vs hash-only; case-sensitive EIP-55 vs lowercase; assign + replace branches.
+- **External calls / dependencies:** None for grinding. Assign: `/api/agents`, `/api/agents/:id/eth-vanity` (POST + DELETE). Hashing via `@noble/hashes/sha3`.
+- **Success state:** "Salt found" — predicted vanity contract address + salt; optionally assigned to an agent for later deploy from the agent home page.
+- **Empty / error states:** invalid deployer / init-code-hash inline; grind-failed error; assign 401/empty/409/network handled.
+- **Step count:** 4 required (+2 optional)
+
+---
+
+### EVM Vanity Wallet (EOA) — `/evm-wallet`
+- **Source:** `public/evm-wallet.html` (inline module). Grinder: `src/eth/vanity/eoa-grinder.js` (`grindEoaVanity`); validation + wordlist as above.
+- **Entry point:** Prefix/suffix inputs, core slider, Grind button.
+- **Prerequisites / gates:** None — pure self-custody. The private key is generated in-browser and never sent to the server (no agent-assign path; importable into MetaMask/ethers/viem/Rabby).
+- **Steps (N):**
+ 1. User enters a hex **prefix/suffix** (≤MAX_PATTERN_LENGTH; EIP-55 case-sensitive if any A–F). Live preview + ETA. (optional) wordlist chips + core slider/presets.
+ 2. Click **Grind** → `grindEoaVanity({ prefix, suffix, … })` secp256k1 + keccak worker pool; live attempts/rate/ETA + scan animation.
+ 3. (optional) **Cancel** mid-grind.
+ 4. On hit → result card: checksummed address, attempts/rate stats, the **private key** (injected as text, not markup), **Copy private key**, and **Download keystore** (encrypted UTC keystore via `Wallet`).
+ 5. Self-custody warning — three.ws never receives the key, so there is no server handoff.
+- **Decision points / branches:** prefix/suffix/both; case-sensitive vs not; copy raw key vs download encrypted keystore.
+- **External calls / dependencies:** None — fully client-side (secp256k1/keccak workers; ethers `Wallet` for keystore export).
+- **Success state:** vanity EOA with downloadable encrypted keystore + copyable private key.
+- **Empty / error states:** invalid-hex inline; grind-failed error; keystore-export error handled at the download button.
+- **Step count:** 4 required (+1 optional)
+
+---
+
+### Agent Wallet x402 Pay (3D demo) — `/play/agent-wallet`
+- **Source:** `pages/play/agent-wallet.html` → `src/play-agent-wallet.js`. Uses `src/game/avatar-rig.js` + `src/game/play-handoff.js`. Bridge: hosted `api/agent-wallet-bridge` (prod) or local `scripts/agent-wallet-x402-bridge.mjs` on `127.0.0.1:4402` (dev).
+- **Entry point:** `#stage3d` 3D scene (avatar + kiosk + stage board) + side panel with topic chips, endpoint card, and a Pay button.
+- **Prerequisites / gates:** Bridge must be **online** (status poll). On the **hosted** bridge a real spend requires a signed-in session (402→401 surfaces "Sign in to pay"); rate-limited (429) handled. Agent wallet must hold USDC.
+- **Steps (N):**
+ 1. Boot loads the saved `/play` avatar (`CC_AVATAR_KEY` / `?avatar=`), builds the 3D rig, and calls `refreshStatus()` → bridge `?status=1` for wallet address/mode + USD balance. Status repolls every 30s.
+ 2. `loadQuote()` → bridge `?quote=1&endpoint=…&method=POST&body={topic}` → fills endpoint name, price, pay-to, tags.
+ 3. (optional) User selects a topic chip (BTC/ETH/SOL) — re-quotes implicitly on next pay.
+ 4. User clicks **Send avatar to pay — $0.01 USDC**. Avatar walks to the kiosk (stage `walk`); pay ring pulses.
+ 5. `POST` bridge `?pay=1` (SSE, `accept: text/event-stream`) streams stages: `challenge` (402) → `signing` (agent wallet signs the SPL USDC transfer) → `signed`/`submitting` (X-PAYMENT submitted, facilitator settles) → `done` (settled on Solana mainnet). Board, kiosk, and side-panel stepper animate in lockstep.
+ 6. On `done` → receipt: amount, payer (agent wallet) → payTo (endpoint), Solscan tx link, and the purchased crypto-intel payload (signal/headline/rationale). Avatar plays a celebrate emote, then walks home. Status refreshes; session total accrues.
+- **Decision points / branches:** local dev bridge vs hosted prod bridge (different URL shapes + auth model); `?bridge=`/`?endpoint=` overrides; 401 needs-auth vs 429 rate-limit vs generic failure; bridge online/offline/connecting.
+- **External calls / dependencies:** bridge `status`/`quote`/`pay` (`/api/agent-wallet-bridge` or local `:4402`); the paid endpoint `https://three.ws/api/x402/crypto-intel`; Solana mainnet settlement via the x402 facilitator; Solscan (tx link). External payment is **real** ($0.01 USDC leaves the wallet).
+- **Success state:** "✓ $0.01 USDC settled on Solana" board + receipt card with tx link and purchased intel; avatar celebrates.
+- **Empty / error states:** "Bridge offline" banner (dev hint to run the bridge) with Retry; low-balance banner; "Sign in to pay" (needs-auth); rate-limit message; "Payment failed — no funds moved" with the stepper marking the failed stage red.
+- **Step count:** 6 required (+1 optional)
+
+---
+
+### Avatar Wallet Chat — `/avatar-wallet-chat`
+- **Source:** `pages/avatar-wallet-chat.html` (self-contained inline module). Avatar rendered via `/avatar-embed.html` iframe (postMessage bridge).
+- **Entry point:** Avatar iframe + a wallet chip (balance/network/address) + a chat composer.
+- **Prerequisites / gates:** Read-only wallet view is open. Autonomous SOL sends run through `/api/agent/send-sol` (optional `?token=` shared secret → `x-avatar-token` header). A server-side IBM Granite Guardian governance check can block a send.
+- **Steps (N):**
+ 1. Boot configures the avatar iframe (`?id=`/`?handle=`/`?model=`, transparent bg, overlay mode) and posts a `v1.avatar.hello`; queued speech/gestures flush on `v1.avatar.ready` (or a 5s resilience timeout).
+ 2. `refreshWallet()` → `GET /api/agent/wallet` → renders balance (SOL + USD), network badge, short address + explorer link.
+ 3. A "Fund your wallet" hint appears when the live balance can't cover a $1 send + fee buffer; user can copy the deposit address.
+ 4. User chats; `ask()` streams an assistant reply, the avatar speaks/gestures, and the model may emit actions.
+ 5. On a `sendSol` action → a payment card renders ("Signing & broadcasting…"); `POST /api/agent/send-sol` with `{ usd, to? }`.
+ 6. On success → card flips to "Confirmed on-chain" with SOL amount, recipient, and a Solscan signature link; the avatar celebrates and the wallet refreshes.
+ 7. If a send was held server-side, a governance chip explains the IBM Granite Guardian block (the action is already stripped from the stream — client never gates).
+- **Decision points / branches:** avatar-source param (id/handle/model); send governance allowed vs blocked; send success vs fail; optional shared-secret token.
+- **External calls / dependencies:** `/api/agent/wallet`, `/api/agent/send-sol`, the chat/stream endpoint, `/avatar-embed.html`; Solscan (links). Real on-chain SOL transfer on success.
+- **Success state:** "Confirmed on-chain" payment card with signature link; avatar verbal + gesture confirmation.
+- **Empty / error states:** "wallet offline" balance fallback; fund-hint / low-balance states; payment-failed card + toast + avatar "didn't go through"; governance-blocked chip.
+- **Step count:** 6 required (+1 optional)
+
+---
+
+### threews.sol Name Claim (SNS subdomain) — `/threews/claim`
+- **Source:** route `/threews/claim` → `pages/threews-claim.html` (self-contained inline module). Pay-by-name plumbing: `src/sns/pay-by-name.js`. Surfaced from `/three`'s rare-name studio.
+- **Entry point:** `#tw-label` label input + `#tw-mint` Mint button; `#tw-status` availability line; `#tw-result`.
+- **Prerequisites / gates:** Sign-in required to mint (CSRF token from `/api/csrf-token`; "not signed in" if absent). Minting an on-chain SNS subdomain under `*.threews.sol`.
+- **Steps (N):**
+ 1. User types a label; input is lowercased and stripped to `[a-z0-9-]`. Debounced 350ms availability check.
+ 2. `GET /api/threews/subdomain?label=` → shows "<full> is available" (enables Mint) or "claimed by @user / owned by <addr>".
+ 3. User clicks **Mint** → `getCsrf()` (`GET /api/csrf-token`) → `POST /api/threews/subdomain` with `{ label }` + `x-csrf-token`.
+ 4. On success → "<full> minted" with the showcase URL and a Solscan tx link for the on-chain mint signature.
+- **Decision points / branches:** available vs taken; pricing tier (common = free; short/dictionary/reserved are priced in $THREE, surfaced via `/three` name-quote before landing here); signed-in vs not.
+- **External calls / dependencies:** `/api/threews/subdomain` (GET check + POST mint), `/api/csrf-token`; Solscan (tx link). On-chain SNS mint.
+- **Success state:** Minted name card with showcase URL + tx signature link.
+- **Empty / error states:** "Type a label to check"; availability "bad" state for taken names; mint-failed (re-enables button); not-signed-in CSRF failure.
+- **Step count:** 4 required
+
+---
+
+### $THREE Economy — `/three`
+- **Source:** `pages/three.html` → `src/three-economy.js`. Wallet/tier via `src/three-access.js` (`getAccess`) + `src/wallet.js` (`initWalletButton`).
+- **Entry point:** "The Flow" canvas viz, live stats, treasury/rewards wallets, holder-tier ladder, pricing explorer, rare-name studio.
+- **Prerequisites / gates:** All read-only. Connecting a wallet resolves the holder tier from on-chain $THREE; no purchase happens on this page (CTAs link out to `/three-token` to buy and `/threews/claim` to mint names).
+- **Steps (N):**
+ 1. Boot fetches `/api/three/{catalog,stats,tier,access}` + `/api/token/price`; renders the flow viz, animated stats, and on-chain-verifiable treasury/rewards wallet addresses.
+ 2. (optional) User clicks **Connect wallet to see your tier** (hidden `#connect-wallet-btn` wired by `initWalletButton`); a `wallet:changed` event re-reads the tier and applies the discount live in the pricing explorer.
+ 3. (optional) **Rare-name studio:** user types a `*.threews.sol` name → `GET /api/three/name-quote?name=` → "Free to mint" (common) or a $THREE rarity price; links to `/threews/claim` to mint.
+ 4. (optional) Explore the holder-tier ladder (Live vs Planned feature matrix from `/api/three/access`) and the pricing explorer (tier discount applied).
+- **Decision points / branches:** wallet connected (real tier) vs synthesized-from-wallet vs no-wallet; name common (free) vs rare (priced).
+- **External calls / dependencies:** `/api/three/catalog`, `/api/three/stats`, `/api/three/tier`, `/api/three/access`, `/api/three/name-quote`, `/api/token/price`. Wallet connect via the global `initWalletButton`.
+- **Success state:** fully populated economy dashboard reflecting live treasury/rewards/holder data; tier + discount applied for a connected wallet.
+- **Empty / error states:** connect-wallet prompts where no tier is resolved; designed loading/empty states throughout; name-quote validation feedback.
+- **Step count:** 1 required (+3 optional)
+
+---
+
+### $THREE Live (Protocol Pulse) — `/three-live`
+- **Source:** route `/three-live` → `pages/three-live.html` (self-contained Three.js inline module). Empty-state helper: `src/shared/state-kit.js` (`emptyStateHTML`).
+- **Entry point:** Full-screen 3D "living organism" viz of the $THREE protocol + a live trade ticker + hero badge.
+- **Prerequisites / gates:** None — public, read-only, real-time.
+- **Steps (N):**
+ 1. Boot fetches `GET /api/three-token/stats` (no-store) for figures and opens an SSE stream `GET /api/agents/pumpfun-feed?kind=trades&mint=<$THREE>`.
+ 2. Each on-chain trade emits a particle burst; whales send shockwaves through the 3D organism; the ticker prepends the trade.
+ 3. Hero badge tracks connection state (connecting → live/quiet → reconnecting on SSE error, with auto-reconnect); stats refresh on an interval.
+- **Decision points / branches:** live vs quiet (no recent trades) vs error/reconnecting; reduced-motion aware.
+- **External calls / dependencies:** `/api/three-token/stats`, `/api/agents/pumpfun-feed` (SSE). The mint is the fixed $THREE CA.
+- **Success state:** live 3D protocol pulse with streaming trades and live stats badge.
+- **Empty / error states:** "Live trades will appear here" guided empty ticker; "$THREE · stats unavailable" / "reconnecting…" hero badge; SSE auto-reconnect.
+- **Step count:** 1 required (read-only/ambient)
+
+---
+
+### Coin 3D Snapshot — `/coin3d`
+- **Source:** `pages/coin3d.html` → `src/coin3d/main.js`. Deep-linked from `/launches` cards and the MCP tool `pumpfun_token_3d`.
+- **Entry point:** Full-screen Three.js scene seeded by `?mint=<base58>` (& optional `&network=`).
+- **Prerequisites / gates:** A valid `?mint=` param. Read-only.
+- **Steps (N):**
+ 1. Boot reads `mint` + `network`; shows a loading overlay.
+ 2. Parallel MCP calls via `POST /api/pump-fun-mcp`: `getTokenDetails`, `getBondingCurve`, `getTokenHolders` (top 12). Token logo fetched from its metadata URI (IPFS→HTTP, 6s timeout).
+ 3. Renders a spinning coin medallion (logo-textured), a galaxy of top holders (spheres sized by balance, tinted by concentration), and a graduation ring filled to bonding-curve progress. OrbitControls for interaction.
+ 4. (optional) Watchlist toggle persists to localStorage (`ld_watchlist`, shared with `/launches`).
+- **Decision points / branches:** mainnet vs devnet; mint present vs missing; logo available vs fallback.
+- **External calls / dependencies:** `/api/pump-fun-mcp` (pump.fun MCP), IPFS gateway for the logo. All on-chain/live.
+- **Success state:** interactive 3D token scene (medallion + holder galaxy + graduation ring).
+- **Empty / error states:** designed loading / error / empty overlays (`?mint=` missing, MCP failure, no holders) via the status-overlay helper.
+- **Step count:** 3 required (+1 optional)
+
+---
+
+## Source-coverage notes
+- All routes resolved and traced to real source. No missing source.
+- `/launch` HTML loads its module by URL (`/launch/launch.js`) — the real source is `public/launch/launch.js`; the launch engine is `public/studio/launch-panel.js` (shared with `/studio` and the avatar page).
+- `/vanity-wallet`, `/eth-vanity`, `/evm-wallet`, `/threews/claim`, `/three-live`, `/avatar-wallet-chat` are served from prebuilt HTML (`public/*.html` or `pages/*.html`) with self-contained inline modules; their crypto workers live under `src/solana/vanity/` and `src/eth/vanity/`.
+- `/threews/claim` rewrites to `threews-claim.html` (no `pages/threews/` dir).
+- `src/agent-eth-vanity-card.js` and `src/agent-vanity-grinder.js` are the embedded-card variants of the standalone vanity tools, mounted on agent home/dashboard pages rather than the standalone routes above.
diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.md
new file mode 100644
index 000000000..ae2081076
--- /dev/null
+++ b/docs/ux-flows/09-x402-agent-commerce.md
@@ -0,0 +1,334 @@
+# x402 & Agent Commerce
+
+UX Flow Atlas — cluster 09. Traced end-to-end from real source: page HTML, imported
+JS modules, and backend API handlers. Routing is path-based via `vite.config.js`
+(`historyApiFallback` map) in dev and Vercel rewrites in prod. Clean URLs resolve to
+files under `pages/` or `public/`.
+
+The cluster's spine is the **x402 pay-per-call** loop: hit a paid endpoint → get
+`402 Payment Required` with `paymentRequirements` → pay (server-held agent wallet,
+or the user's Phantom/MetaMask wallet via the shared `/x402.js` modal) → re-send the
+request with an `X-PAYMENT` header → facilitator verifies + settles on-chain →
+endpoint runs and returns the result. The "agent economy" demos wrap this loop in a
+choreographed two-agent narrative driven by Server-Sent Events.
+
+---
+
+### Pay-per-call (x402) — `/pay`
+- **Source:** `public/pay/index.html` (route → `public/pay/index.html`; inline module scripts hold all app logic), backend `api/x402-pay.js`, `api/mcp`, `api/x402-checkout`, `api/_lib/x402-bsc-direct.js`; agent wallet via `api/agents/[id]/solana`.
+- **Entry point:** Chat-style page. Left = conversation + quick-tool chips + prompt input ("Pay & Run"); right = "x402 settlement timeline"; footer = live "recent paid calls" ticker. First visit shows a 3-step walkthrough overlay (dismissed → `localStorage x402:seen-walk`).
+- **Prerequisites / gates:** No signup to use the **shared demo wallet** (platform-funded). Three payer modes: (a) **platform/agent server-payer** (default) — optional sign-in loads the user's own agents via `/api/x402-pay?agents=1` (401 → "Sign in" CTA, falls back to demo wallet); selecting an agent with no wallet opens the **generate-wallet overlay** (`POST /api/agents/{id}/solana`, or grind a vanity address at `/vanity-wallet`). (b) **Phantom** (Solana USDC, user signs). (c) **MetaMask/EVM** on the "BNB Chain" tab (user signs `approve` + `pay(bytes32)`). Wallet must hold ≥ $0.001 USDC for the chosen mode.
+- **Steps (4 required + several optional):**
+ 1. (optional) Read/dismiss the "How this works" walkthrough overlay.
+ 2. (optional) Pick a payer: sign in and select an agent, generate/import its wallet, or select Phantom / MetaMask card; otherwise the shared demo wallet is used.
+ 3. Choose a tool: click a quick chip (`/list_tools`, `/validate DamagedHelmet.glb`, `/inspect`, `/optimize`, `/search_avatars`) **or** type a prompt (e.g. `validate https://…/model.glb`) and click **Pay & Run** / Enter. (Deep links `/pay?validate=<glb>`, `?inspect=`, `?optimize=`, `?list=1` auto-fire.)
+ 4. System POSTs `/api/x402-pay` (SSE) — timeline advances `challenge → built → verified → dispatched → settled`, each stage showing real ms timings and the settle tx prefix.
+ 5. On `result`: receipt rendered (amount, payment, durations), MCP output rendered in chat — `tools/list` lists tools, `inspect/validate/optimize` show JSON/cards, model-processing tools render an actual `<model-viewer>` GLB. Ticker bumps; balance + feed refresh.
+- **Decision points / branches:** payer mode (server agent vs Phantom vs EVM — `run()` dispatches to `runPhantomPayment` / `runEvmPayment` / SSE path); agent has wallet vs not (gen overlay); prompt parse (`parsePrompt`) into a tool call; stream error vs `result` vs "stream ended without result".
+- **External calls / dependencies:** `/api/x402-pay` (SSE payer + `?agents=1`, `?balance=1`, `?feed=1`, `/og`), `/api/mcp` (402 probe + dispatch), `/api/x402-checkout?action=prepare|encode`, `/api/agents/{id}/solana`, Solana mainnet RPC (`api.mainnet-beta.solana.com`), x402 facilitator (verify/settle), Solscan for tx links; BSC path uses `ThreeWSPayments` contract `0x…1B72Cc`.
+- **Success state:** receipt card + rendered MCP result (incl. live 3D model), Solscan tx link, balance ticks down, feed prepends the call, page title shows elapsed ms.
+- **Empty / error states:** not-signed-in → demo-wallet note; no agents → "Create your first agent"; agent has no wallet → gen overlay; `402`/network failure → timeline stage flips to error + `x402 call failed` / `Network error` message; stream ends without result → explicit error; wallet underfunded surfaces from server error.
+- **Step count:** 4 required (+ ~4 optional).
+
+### Paid-call permalink — `/pay/calls`
+- **Source:** `public/pay/calls/index.html` (static share/OG view).
+- **Entry point:** Shareable permalink for a single completed paid call (linked from the `/pay` ticker / OG image rendered by `/api/x402-pay/og`).
+- **Prerequisites / gates:** None — read-only.
+- **Steps (1):**
+ 1. Open the link → page renders the recorded call (tool, MCP result card, Solscan tx) and sets the document title/OG metadata for social preview.
+- **Decision points / branches:** result renderer branches by tool (`tools/list`, `validate_model`, `inspect_model`, `optimize_model`, generic).
+- **External calls / dependencies:** record payload (embedded / fetched), Solscan, `/api/x402-pay/og` for the share image.
+- **Success state:** rendered call summary with explorer link.
+- **Empty / error states:** missing record → falls back to generic card / JSON dump.
+- **Step count:** 1 required.
+
+### Hosted x402 checkout — `/pay/c/<slug>`
+- **Source:** `public/pay/c/index.html` + `/x402.js`; backend `api/x402-skus.js`, `api/x402-checkout-record.js`.
+- **Entry point:** Hosted checkout for a merchant-defined SKU (`/pay/c/<slug>`), branded with merchant + action name.
+- **Prerequisites / gates:** A valid `?slug`/path slug resolving to a SKU; a wallet (Phantom/EVM) with USDC to pay.
+- **Steps (3 required):**
+ 1. Page loads SKU via `/api/x402-skus?slug=…` and renders merchant/action; probes the target endpoint for its live `402` price + networks.
+ 2. User clicks pay → `window.X402.pay({ endpoint: sku.target_endpoint, … })` opens the shared modal (wallet connect + sign + settle).
+ 3. On success the page re-calls the endpoint with the payment and records the call via `/api/x402-checkout-record`; result shown.
+- **Decision points / branches:** no slug → error; endpoint not returning 402 → "endpoint may have changed"; modal not loaded → error; Base vs Solana network.
+- **External calls / dependencies:** `/api/x402-skus`, target merchant endpoint, `/x402.js` modal, `/api/x402-checkout-record`, Solana/Base settlement.
+- **Success state:** payment settled + result rendered + call recorded.
+- **Empty / error states:** missing slug, endpoint unreachable, non-402 response, modal load failure, payment cancel.
+- **Step count:** 3 required.
+
+---
+
+### x402 Bazaar — `/bazaar`
+- **Source:** `public/bazaar.html` + `public/bazaar.js` + `/x402.js`; backend `api/bazaar/list`, `api/bazaar/search`, `api/bazaar/context`.
+- **Entry point:** Directory of live x402-paid endpoints (merged across facilitators) as a card grid with filters.
+- **Prerequisites / gates:** None to browse; a wallet only when paying ("Try it").
+- **Steps (5 required + 2 optional):**
+ 1. Page loads → `GET /api/bazaar/list` → renders endpoint cards.
+ 2. (optional) Filter by type (HTTP/MCP), network (EVM/Solana), max price, extension, sort.
+ 3. (optional) Search (`/api/bazaar/search?query=`) or scroll.
+ 4. Click a card action: HTTP → **Try it** (pay flow); MCP tool → **Inspect tool** (details only — JSON-RPC, not auto-callable); **Details** → modal + `/api/bazaar/context?resource=`.
+ 5. On **Try it**: `window.X402.pay({ endpoint, method, merchant, action, … })` opens the modal; pay → settle.
+ 6. Inline `.receipt` on the card shows status + on-chain tx + explorer link.
+- **Decision points / branches:** HTTP vs MCP (MCP = inspect only); pay success/cancel/error → distinct receipt states; explorer chosen from endpoint network (Solscan/Basescan/Arbiscan/etc.).
+- **External calls / dependencies:** `/api/bazaar/list|search|context`, `/x402.js`, merchant endpoint, multi-chain explorers.
+- **Success state:** green receipt with tx hash + explorer link + result JSON; SR announcement "Payment succeeded for <service>".
+- **Empty / error states:** no results → "No matching services…"; catalog unreachable → "Couldn't reach the catalog… Retry"; modal load fail → "Payment module failed to load"; cancel → receipt hidden; error → red receipt.
+- **Step count:** 5 required (+2 optional).
+
+### x402 Arbitrage — `/arbitrage`
+- **Source:** `public/arbitrage.html` + `public/arbitrage.js` + `/x402.js` (loaded on-demand); backend `api/bazaar/arbitrage`.
+- **Entry point:** Cross-provider price-disparity board — one card per capability, ranked providers, spread %.
+- **Prerequisites / gates:** None to browse; wallet only to pay.
+- **Steps (3 required + 3 optional):**
+ 1. Page loads → `GET /api/bazaar/arbitrage?minSpreadPct=0&limit=200` → skeleton then arb cards (spread %, up to 5 providers cheapest-first, metrics).
+ 2. (optional) Filter type All/HTTP/MCP; (optional) search by capability/host.
+ 3. Click **Pay cheapest · $X** → lazy-loads `/x402.js`, then `window.X402.pay({ endpoint: cheapest.resource, method:'GET', merchant: host, action: capability })`.
+ 4. Result shows on the button: "✓ Paid" (auto-revert 4s) / "Failed: …" / revert on cancel.
+ 5. (optional) Click **Avoid · $Y** → navigates to `/bazaar?q=<capability>` to see the full spectrum.
+- **Decision points / branches:** MCP capability → "Pay" redirects to `/bazaar?q=` (can't call MCP directly); on-demand x402 load; button state management.
+- **External calls / dependencies:** `/api/bazaar/arbitrage`, `/x402.js`, the cheapest live endpoint, Solscan/Basescan.
+- **Success state:** "✓ Paid" on the cheapest provider; payment settled on-chain.
+- **Empty / error states:** no opportunities → "No arbitrage opportunities right now…"; timeout (20s) → "Request timed out… Retry"; feed error → "Couldn't reach the arbitrage feed…"; modal fail → "Payment modal failed to load".
+- **Step count:** 3 required (+3 optional).
+
+### x402 Providers — `/providers`
+- **Source:** `public/providers.html` + `public/providers.js`; backend `api/bazaar/providers`.
+- **Entry point:** Two modes from one file — **directory** (`/providers`) and **profile** (`/providers?host=<host>`). No payment surface; navigation hub into `/bazaar`.
+- **Prerequisites / gates:** None.
+- **Steps (2 required + 3 optional):**
+ 1. Directory load → skeleton → `GET /api/bazaar/providers?limit=500` → provider cards (service count, median/min price, tags, networks).
+ 2. (optional) Sort (most services / cheapest / most expensive / most networks); (optional) search by host/tag.
+ 3. Click a card → `/providers?host=…` → profile fetch `GET /api/bazaar/providers?host=` → sidebar (metrics, "Visit site", "Open in catalog") + category/network charts + sorted services table.
+ 4. (optional) Click a listing row → `/bazaar?q=<service>`.
+- **Decision points / branches:** directory vs profile keyed on `?host`; sort order; real-time search.
+- **External calls / dependencies:** `/api/bazaar/providers` (list + single host), facilitator URLs, downstream explorers via `/bazaar`.
+- **Success state:** cards / profile render and are navigable.
+- **Empty / error states:** timeout (20s) + retry; directory unreachable; profile 404 → "Failed to load provider" + back link; no search matches; no tags message.
+- **Step count:** 2 required (+3 optional).
+
+---
+
+### x402 Live Demo (IBM × three.ws) — `/ibm/x402-demo`
+- **Source:** `pages/ibm/x402-demo.html` (self-hosted IBM Plex fonts) + `https://three.ws/x402.js` + `https://three.ws/agent-3d/latest/agent-3d.js`; backend `api/x402/forge.js` (forge-v2/models), `api/x402/symbol-availability.js`.
+- **Entry point:** Marketing/live-demo page with 5 stacked sections — two **paid** (Forge, Symbol Check) and three **free/watch** (Agent, Play, IRL); each lazy-boots via IntersectionObserver.
+- **Prerequisites / gates:** Free demos: none. Paid demos: MetaMask (Base) or Phantom (Solana) with mainnet USDC — Forge $0.05–$0.50 by tier, Symbol Check $0.001.
+- **Steps (Forge: 5 required +1 optional; Symbol Check: 4 required):**
+ 1. (Forge) Enter a prompt (default "a brass steampunk owl, full body").
+ 2. Page fetches the live `402` challenge (`GET /api/x402/forge-v2/models?tier=draft`) and shows live price + networks + pay address.
+ 3. (optional) Pick tier Draft/Standard/High → price updates.
+ 4. Click **Pay $X & forge** → `window.X402.pay({ endpoint:'/api/x402/forge-v2/models?tier=…&prompt=…', method:'GET', … })` → wallet signs gasless USDC auth → settle.
+ 5. Endpoint returns a GLB → `<model-viewer>` renders it (orbit/download); the autonomous `<agent-3d>` below celebrates (`expressEmotion('celebration')` + `playEmote('cheer')`).
+ - (Symbol Check) Enter ticker (default "GRANITE") → fetch `402` from `/api/x402/symbol-availability?ticker=` → **Pay $0.001 & run** → result panel shows availability pill + similar matches.
+ - (Agent/Play/IRL) Scroll into view → 3D avatar auto-reacts / `/play` + `/irl` iframes lazy-load with "Full screen" / "Open on your phone".
+- **Decision points / branches:** Forge vs Symbol Check (different endpoints/prices); paid vs free sections; agent reacts autonomously to settlement events; embeds load lazily.
+- **External calls / dependencies:** `/api/x402/forge-v2/models`, `/api/x402/symbol-availability`, `/x402.js`, `/agent-3d/latest/agent-3d.js`, `/play`, `/irl` iframes, model-viewer bundle, Base/Solana settlement, explorers.
+- **Success state:** Forge → GLB rendered + agent celebrates; Symbol Check → availability result + agent reacts; receipt with tx + explorer link.
+- **Empty / error states:** offline → "live price will load when you reconnect"; insufficient balance → "Top up USDC… then try again"; 402 preview fail → "Payment button still works"; modal fail → reload prompt; cancel → result clears; embed timeout (15s) → "Open it in a new tab".
+- **Step count:** Forge 5 required (+1 optional tier); Symbol Check 4 required; free sections auto-play.
+
+---
+
+### Endpoint Shopper — `/shopper`
+- **Source:** `pages/shopper.html` + `src/shopper-app.js`; backend `api/agents/endpoint-shopper-run.js` (x402, $0.01 base + downstream budget) + the Bazaar registry.
+- **Entry point:** "Endpoint Shopper" — describe a task, set a budget, watch an agent discover + chain + call x402 endpoints to answer.
+- **Prerequisites / gates:** No auth. Non-empty task and budget ≥ $0.01 to enable **Run Task**; a wallet only if the run hits a `402` paywall.
+- **Steps (5 required + 3 optional):**
+ 1. Enter a task in `#task-input` (or click an example chip).
+ 2. (optional) Adjust budget slider ($0.10–$2.00, default $0.50).
+ 3. Click **Run Task** → button "Running…", skeleton cards shown.
+ 4. `POST /api/agents/endpoint-shopper-run` with `{ task, maxCostUsd }` → agent emits a step trace: **discover** 🔍 → **plan** 🗺 → **call** ⚡ (per endpoint, with URL + USDC cost + snippet) → **synthesize** 🧠.
+ 5. Timeline renders all steps; **Total spent** row ("$0.00…" or "Free"); **Final Answer** card with synthesized text. Button re-enabled.
+- **Decision points / branches:** empty task / budget < $0.01 → button disabled + hint; `402` → paywall card "Pay with Wallet" → `/paywall.html?req=…&return=/shopper`; `400`/`5xx`/network → error card + retry.
+- **External calls / dependencies:** `/api/agents/endpoint-shopper-run`, downstream x402 endpoints discovered via the Bazaar, `/paywall.html`.
+- **Success state:** full step timeline + final answer + total cost; ready for a new task.
+- **Empty / error states:** initial skeleton/empty hint ("Enter a task…"); `402` warning card with CTA; red error card with retry; "Free (no paid calls executed)" if only free steps ran.
+- **Step count:** 5 required (+3 optional).
+
+### Fact Checker — `/fact-checker`
+- **Source:** `pages/fact-checker.html` + `src/fact-checker-app.js`; backend `api/x402/fact-check.js` ($0.10, 7-day Redis cache).
+- **Entry point:** Enter a claim, pick strictness, get a verdict + sources + cost breakdown + verifiable attestation.
+- **Prerequisites / gates:** No auth. Non-empty claim ≤ 1000 chars; wallet only on `402`.
+- **Steps (4 required + 3 optional):**
+ 1. Enter a claim in `#claim-input` (or click an example chip); live char counter.
+ 2. (optional) Pick strictness Low/Medium(default)/High.
+ 3. Click **Check This Fact** → validate → skeleton + "Searching sources…".
+ 4. `POST /api/x402/fact-check` with `{ claim, strictness }`.
+ 5. On `402` → payment panel (Base USDC $0.10 / Solana USDC $0.10) + "Connect wallet to pay →" (`/marketplace`). On `200` → verdict banner (SUPPORTED/CONTRADICTED/MIXED/INSUFFICIENT + confidence), sources grid (stance/authority), cost breakdown, expandable SHA-256 attestation.
+- **Decision points / branches:** empty claim → no submit; `402` → payment panel; `429` → "Too many checks…"; `5xx` → internal-error message; retry button re-runs same claim. Cached result returns `200` instantly.
+- **External calls / dependencies:** `/api/x402/fact-check` (3 search queries → multi-source retrieval → LLM stance → weighted verdict → attestation; optional vision for image evidence, fail-open), Base/Solana USDC, Redis cache (7-day TTL).
+- **Success state:** verdict banner + sources + cost breakdown + attestation toggle.
+- **Empty / error states:** initial example chips; skeleton loading; error card (title/msg/code + retry); payment panel with network badges.
+- **Step count:** 4 required (+3 optional).
+
+### Unstoppable Agent — `/unstoppable`
+- **Source:** `pages/unstoppable.html` + `src/unstoppable-dashboard.js` + `/x402.js`; backend `api/agents/unstoppable-status.js` ($0.01 optional payment per live query).
+- **Entry point:** A live dashboard of an autonomous agent that must earn to survive — balance, runway, status (RUNNING/CONSERVING/HALTED), activity feed, latest reflection.
+- **Prerequisites / gates:** None to view (cached data from `localStorage unstoppable_last_reading`). To unlock **live** data, donate $0.01 USDC via x402; wallet needed only for the donation.
+- **Steps (2 required + 1 recurring optional):**
+ 1. Load page → render cached data (or skeletons) → auto-poll `GET /api/agents/unstoppable-status` immediately, then every 60s (exponential backoff to 5 min on transient errors).
+ 2. View data: `200` → hero balance + status + runway, 24h earnings/costs, lifetime net, activity feed (THINK/EARN/REFLECT/IDLE/…), latest reflection. `402` → payment notice + cached data + "Unlock live data — $0.01".
+ 3. (optional, repeatable) Click **Donate $0.01** → `window.X402.pay({ endpoint: status, method:'GET', action:'Fund the … runway' })` → on success toast + fresh live data; each donation funds one live query and directly funds the agent.
+- **Decision points / branches:** cache present vs not; `200` (unlocked) vs `402` (paywalled); `5xx` → backoff + keep cache; donation low-balance → retry with link to `/pay`; donation cancel → no charge.
+- **External calls / dependencies:** `/api/agents/unstoppable-status` (free 402 challenge + optional paid query), `/x402.js`, Base/Solana settlement.
+- **Success state:** live hero + stats + non-empty activity feed + reflection + "Updated X ago".
+- **Empty / error states:** initial skeleton "Fetching live data…"; `402` notice with cached data; no-cache `402` → zeroed state ("Pay $0.01 to see live data").
+- **Step count:** 2 required (+1 recurring optional donation).
+
+### Pay-As-You-Learn Tutor — `/tutor`
+- **Source:** `public/tutor.html` + `public/tutor.js` + `/x402.js`; backend `api/x402/tutor.js` ($0.01/question) + `api/tutor/session.js` (free resume).
+- **Entry point:** Chat tutor that charges per answer; session total accrues; "End & invoice" produces an itemized, attested invoice.
+- **Prerequisites / gates:** No auth. Session id auto-minted to `localStorage three-tutor-session-id`. Wallet connect happens lazily on the first paid question. Question 5–2000 chars.
+- **Steps (4 required + 4 optional):**
+ 1. (optional) Click a suggestion chip, or type a question in `#q` (live char counter).
+ 2. (optional) Pick expertise level Beginner/Intermediate(default)/Expert.
+ 3. Click send (or Cmd+Enter) → spinner; question added to thread.
+ 4. `window.X402.pay({ endpoint:'/api/x402/tutor', body:{ sessionId, question, level }, merchant:'three.ws Tutor', action:'Explain' })`; first time → paywall modal connect + sign + settle.
+ 5. On success → tutor bubble with answer + key points + example + follow-up; meta row (cost · level · model); session tab updates total + answer count.
+ 6. (optional) Click a follow-up suggestion to ask again (cost stacks). (optional) **End & invoice** → modal with per-question line items, running total, SHA-256 session attestation.
+- **Decision points / branches:** < 5 chars → ignored; `X402.pay` not ready (6s) → error + retry; payment cancel → "no charge"; payment fail → retry; reload → session resumed via `localStorage` + free `GET /api/tutor/session`.
+- **External calls / dependencies:** `/api/x402/tutor` (per-question charge, server-side session accrual + attestation), `/api/tutor/session` (resume), `/x402.js`, Base/Solana settlement.
+- **Success state:** stacked Q&A thread, session total + count, invoice with attestation.
+- **Empty / error states:** initial title + 4 suggestion chips; spinner loading; error bubble in thread; invoice modal on demand.
+- **Step count:** 4 required (+4 optional).
+
+### Forever (etch a message into Bitcoin) — `/forever`
+- **Source:** `public/forever.html` + `public/forever.js`; backend `api/forever/inscribe.js` (creates a real OrdinalsBot Taproot text inscription on Bitcoin **mainnet**) + `api/forever/status.js` (polling).
+- **Entry point:** Compose a message → pay Bitcoin → it's inscribed onto a single satoshi, permanently. NOT an x402/USDC flow — payment is native BTC to a generated charge address (Lightning invoice offered too).
+- **Prerequisites / gates:** No auth. Message 1–1500 bytes UTF-8. Optional Taproot (`bc1p…`) receive address (else platform vault `BTC_INSCRIPTION_RECEIVE_ADDRESS`). Fee rate 3/8/20/50 sats/vB. **User must hold BTC in their own wallet** — a confirm dialog shows the estimated cost before the order is created.
+- **Steps (6 required + 6 optional):**
+ 1. Type the message (live char + byte counters; orange warning > 1500 bytes).
+ 2. (optional) Enter a Taproot receive address.
+ 3. (optional) Select fee rate → live fee estimate (`#feeEstimate`) with sats / BTC / ≈USD (CoinGecko best-effort).
+ 4. Click **Inscribe forever** → native `confirm()` showing estimated BTC cost + address ("payment is final once broadcast. Continue?").
+ 5. `POST /api/forever/inscribe` `{ message, receiveAddress, feeRate }` → creates OrdinalsBot order → returns charge address, amount (sats), Lightning invoice, mempool URL; order persisted to `sessionStorage forever:order` → **pay view**.
+ 6. Pay view: QR (BIP-21), amount, pay-to/Lightning/receive/order-id rows, "Open in wallet" / "View on mempool" / "Cancel". User sends BTC from their own wallet.
+ 7. Auto-poll `GET /api/forever/status?id=<orderId>` every 6s → `waiting-payment → payment-received → inscribing → inscribed`.
+ 8. On `inscribed` → **win view**: large message, Inscription link (ordinals.com), reveal-tx link (mempool.space), receive address, "Bitcoin mainnet"; share to X / copy permalink / inscribe another.
+- **Decision points / branches:** empty / > 1500 bytes / invalid Taproot / invalid fee rate → inline errors; confirm-dialog cancel → stays in compose; order-create `502/503` → "Inscription failed. Try again."; status `failed` → OrdinalsBot contact note; reload mid-payment → `resumeIfAny()` restores the pay view + resumes polling.
+- **External calls / dependencies:** `/api/forever/inscribe` + `/api/forever/status` → **OrdinalsBot** (`api.ordinalsbot.com`, Bitcoin mainnet Taproot inscription), CoinGecko (USD, best-effort), QR server, mempool.space + ordinals.com for verification.
+- **Success state:** win view with permanent inscription + reveal-tx links + share buttons.
+- **Empty / error states:** compose validation errors; inscribe failure banner; pay-view polling states; order `failed` message with support info.
+- **Step count:** 6 required (+6 optional).
+
+---
+
+### Agent Exchange — `/agent-exchange`
+- **Source:** `pages/agent-exchange.html` + `src/agent-exchange.js`; backend `api/x402-pay.js` (SSE payer), `api/x402/crypto-intel.js` (the paid endpoint).
+- **Entry point:** Two 3D avatars (Intel Agent seller, Buyer Agent) face off; topic chips (SOL/BTC/ETH/DOGE/BNB) + **Buy intel — $0.01 USDC** + on-chain transaction feed. Real USDC settles per buy.
+- **Prerequisites / gates:** No user auth/wallet. Server-side agent wallet (`X402_AGENT_SOLANA_SECRET_BASE58`) must be funded ≥ $0.01; pre-flight `checkWallet()` (`/api/x402-pay?balance=1`) disables the pay button if unconfigured/underfunded.
+- **Steps (2 required; rest auto):**
+ 1. **[auto]** Avatars load + greet (scripted speech via postMessage).
+ 2. **[user]** Select a topic chip (default SOL) → buyer agent reacts.
+ 3. **[user]** Click **Buy intel — $0.01 USDC** → button "Paying…".
+ 4. **[auto SSE from `/api/x402-pay`]** six narrated stages: `challenge → built → verified → dispatched → settled → done`, each with stage chip + agent animation + narration.
+ 5. **[auto]** Receipt card (Confirmed on-chain · amount, payer/payee, Solana mainnet, Solscan tx, headline + signal badge + 24h change); session total flashes. Bubbles auto-hide ~5.5s. Repeat with a new topic.
+- **Decision points / branches:** topic selection feeds the intel request; wallet pre-flight gate; SSE `error`/timeout (30s) → stage error + red receipt + reset + retry.
+- **External calls / dependencies:** `/api/x402-pay` (POST SSE, tool `crypto_intel`, endpoint `/api/x402/crypto-intel`), `/api/x402-pay?balance=1`, `/api/x402/crypto-intel`, Solana RPC settlement, Solscan.
+- **Success state:** all 6 stages + receipt with on-chain tx + agents celebrate + session total increments.
+- **Empty / error states:** "Demo wallet not configured" (button disabled), "Agent wallet low on USDC" + fund address, timeout/SSE error with "No funds were moved", initial narration describing the flow.
+- **Step count:** 2 required (auto SSE pipeline thereafter).
+
+### Agent Commerce — `/agent-trade`
+- **Source:** `pages/agent-trade.html` + `src/agent-trade.js`; backend `api/agent-trade/demo` (SSE), guarded by `api/_lib/agent-trade-guards.js`.
+- **Entry point:** Three.js scene with two geometric agents (Nexus buyer, Oracle seller) on platforms; topic dropdown + **▶ Run Trade Demo**; central card + step log. Cinematic camera, particle beam, burst on confirm.
+- **Prerequisites / gates:** No user auth. Server agent keypairs `AGENT_BUYER_SECRET` + `AGENT_SELLER_SECRET` (+ `AGENT_TRADE_PRICE_SOL`, `AGENT_TRADE_NETWORK`) must be configured + funded. Pre-flight `checkConfig()` (`/api/agent-trade/demo?check=1`); if unconfigured → modal overlay walkthrough + env instructions, Run disabled.
+- **Steps (2 required; rest auto):**
+ 1. **[user]** Select a topic from the dropdown.
+ 2. **[user]** Click **▶ Run Trade Demo** → "⏳ Running…".
+ 3. **[auto SSE `/api/agent-trade/demo?topic=`]** ordered events with choreography: `init` (addresses/balances, camera fly) → `request` (buyer asks) → `challenged` (402 card, SOL price) → `paying` (particle beam buyer→seller) → `confirmed` (burst, Solscan tx card, balance debited) → `delivering` ("Analyzing with <model>…") → `delivered` (final analysis card + model + tx link).
+ 4. Button re-enabled ("Run again"); idle animation resumes.
+- **Decision points / branches:** topic feeds the request payload; config gate (dismiss only hides overlay); `error` event → red chip + toast + retry; 35s safety timeout closes the stream.
+- **External calls / dependencies:** `/api/agent-trade/demo` (`?check=1` + `?topic=` SSE), real SOL settlement on Solana mainnet/devnet, AI model inference for the delivered analysis, Solscan.
+- **Success state:** all 7 SSE stages + final delivered-skill card with model-generated content + on-chain tx.
+- **Empty / error states:** not-configured modal overlay; stream error toast + retry; timeout auto-finish; idle empty scene.
+- **Step count:** 2 required (auto SSE thereafter).
+
+### Agent Economy (Live) — `/agent-economy`
+- **Source:** `pages/agent-economy.html` + `src/agent-economy.js`; backend `api/agent-economy/status` + `api/agent-economy/transact`.
+- **Entry point:** Three-column layout — buyer Nova (3D iframe) | service catalog + transaction feed | seller Oracle (3D iframe). Catalog: Market Analysis ($0.001), On-Chain Insight ($0.002), Risk Score ($0.003) + optional topic input.
+- **Prerequisites / gates:** No user auth. Server wallet (`AVATAR_WALLET_SECRET`) must be configured + funded; `refreshWalletStatus()` (`/api/agent-economy/status`) on init + after each trade shows fund alert / pause banner.
+- **Steps (2 required + 1 optional; rest auto):**
+ 1. **[auto]** Avatars load + greet.
+ 2. **[user]** Select a service button.
+ 3. **[user, optional]** Enter a topic (≤120 chars).
+ 4. **[auto]** Buyer Nova requests + pays (column flash, feed item 📡), `POST /api/agent-economy/transact { service, topic }`.
+ 5. **[auto ~900ms]** Oracle "receives" — payment particle buyer→seller, feed item 💸 with receipt + Solscan link; balances refresh.
+ 6. **[auto ~400ms]** Oracle delivers (speech via LLM, feed item ✅ with content). Status "Transaction complete". Repeat.
+- **Decision points / branches:** service price tier; optional topic; wallet states — `wallet_unconfigured` ("Live transactions paused"), `insufficient_balance` ("Not enough funds" + Add funds), `no_recipient`, generic error.
+- **External calls / dependencies:** `/api/agent-economy/status`, `/api/agent-economy/transact`, Solana RPC settlement, LLM for buyer/seller speech, `/a-embed` avatar iframes (postMessage), Solscan.
+- **Success state:** 3 feed items (request / payment+receipt / delivery) + updated balances + ready for next service.
+- **Empty / error states:** unconfigured pause; underfunded fund banner + "Add funds"; network error feed item; initial empty feed ("Pick a service above…").
+- **Step count:** 2 required (+1 optional topic; auto orchestration thereafter).
+
+### Agent Economy — NOVA & ORACLE — `/demo`
+- **Source:** `pages/demo-economy.html` + `src/demo-economy.js`; backend `api/demo-economy` (SSE).
+- **Entry point:** Single Three.js scene — NOVA (blue) + ORACLE (gold) on platforms with a TV screen between them; **Run demo** button; sidebar wallet chips + payment details + activity log.
+- **Prerequisites / gates:** No user auth. Server agents configured + funded for live settlement; no pre-flight overlay — the stream emits error/demo_mode events if not configured. Unsigned-in/anonymous users get a **simulated** payment path.
+- **Steps (1 required; rest auto):**
+ 1. **[auto]** Idle scene renders (TV idle, particles, auto-rotate, wallet chips).
+ 2. **[user]** Click **Run demo** → "Running…", log cleared, scene reset.
+ 3. **[auto SSE `/api/demo-economy`]** typed events: `step` (e.g. agents_ready → camera fly) → `bazaar` (TV draws x402 service list) → `wallet` (chips updated) → `payment` (pay card; SOL amount; signature link or "SIMULATED" badge; mobile sheet slides up) → `content` (TV draws ORACLE market briefing with pools) → `done`.
+ 4. Button re-enabled ("Run again").
+- **Decision points / branches:** configured+funded vs underfunded (error w/ fund notice) vs not-configured (error, prompts anon to sign in); `simulated=true` → "Simulated payment — sign in for live" + sim row. 35s hard timeout.
+- **External calls / dependencies:** `/api/demo-economy` (SSE), Solana RPC settlement (if live), market-data source, Solscan.
+- **Success state:** TV shows final briefing with markets + prices + 24h changes; full activity log; "Run again".
+- **Empty / error states:** not-configured error; underfunded fund notice; simulated mode; initial idle scene with "not configured" wallet chips.
+- **Step count:** 1 required (auto SSE thereafter).
+
+### Agent Economy — Live — `/live`
+- **Source:** `pages/live.html` (inline module) + `src/live-economy.js`; backend `api/demo/economy` (`?status=1` + `?trade=1` SSE) + `api/chat` (LLM dialogue).
+- **Entry point:** Full-screen Three.js scene — Oracle + Trader on pedestals + TV; CSS-overlaid name tags, balance chips, speech bubbles, HUD with **▶ Agent Trader pays Oracle for Solana market data** + event log. Agents speak LLM-generated lines.
+- **Prerequisites / gates:** Viewing is open; the **live trade** stream `/api/demo/economy?trade=1` is **auth-gated** — anonymous users get a "Sign in to run a live on-chain trade" notice. Server agents must be configured + funded. `refreshStatus()` polls `?status=1` every 10s.
+- **Steps (1 required; rest auto + LLM):**
+ 1. **[auto]** Scene renders; Oracle greets (~3s, LLM via `/api/chat`), Trader greets (~5.5s).
+ 2. **[user]** Click the trade button → "⏳ Trade in progress…", Trader waves + LLM intro line.
+ 3. **[auto SSE `?trade=1`]** events: `thinking` → (`demo_mode` if unsigned/unconfigured → "No real payment in demo mode") → `paying` (beam Trader→Oracle + LLM line) → `paid` (white flash, Oracle pedestal flash, balances refresh, Solscan log link, LLM lines) → `fetching` → `delivering` (TV draws market grid, reverse beam, LLM lines) → `done`.
+ 4. Button re-enabled ("▶ Run Another Trade"). 45s hard timeout.
+- **Decision points / branches:** signed-in + funded (live SOL) vs not-configured/underfunded (`error` with fund address + Copy/View/Retry) vs anonymous (`error` → "Sign in" notice) vs `demo_mode` (data only, no payment).
+- **External calls / dependencies:** `/api/chat` (LLM), `/api/demo/economy?status=1` (poll) + `?trade=1` (auth-gated SSE), Solana RPC settlement, market-data source, `/avatar-embed.html` iframes (postMessage), Solscan.
+- **Success state:** paid + delivered, TV market grid, log with Solscan link, balances updated, "Run Another Trade".
+- **Empty / error states:** not-signed-in notice; underfunded fund notice; stream interrupted; demo-mode (no real SOL); initial idle TV + greetings.
+- **Step count:** 1 required (auto SSE + LLM thereafter).
+
+---
+
+### Sniper Arena — `/play/arena`
+- **Source:** `pages/play/arena.html` + `src/play/arena.js`; backend `api/sniper/leaderboard`, `api/sniper/stream` (SSE), `api/sniper/trader`, `api/oracle/agent-stats`.
+- **Entry point:** A 3D world where **autonomous** AI agents trade real pump.fun tokens on Solana mainnet, live. Left = live leaderboard; right = live trade tape; bottom = movement hints. **No x402 micropayments here** — agents have pre-funded wallets and trade autonomously.
+- **Prerequisites / gates:** None to watch. Picking an avatar is local (`localStorage arena:avatar:v1`), no payment. Agents trade with their own funded Solana wallets.
+- **Steps (4 required + 3 optional):**
+ 1. **[auto]** Page boots `ArenaWorld` (Three.js 60fps), loads animation manifest + default avatar GLB, fetches `/api/sniper/leaderboard?network=mainnet`, opens SSE `/api/sniper/stream`.
+ 2. **[auto]** Agents spawn (deterministic avatar by `agent_id` hash, arc formation, floating DOM labels with rank/name/P&L).
+ 3. **[auto/live]** SSE `buy`/`sell`/`update` events → agent emotes + particle burst, trade tape prepends (BUY/SELL ▲▼, symbol, Solscan link), big-win banner, board refresh.
+ 4. **[user, optional]** **Choose your avatar** → modal → select → spawn player (saved to localStorage).
+ 5. **[user, optional]** Move with WASD / drag look / scroll zoom / touch joystick.
+ 6. **[user, optional]** Click an agent label → camera focus + right drawer profile (equity sparkline, stats grid, recent closed trades with on-chain proof, Oracle conviction section) → **Full proof & copy ↗** → `/trader/<agent_id>` new tab.
+- **Decision points / branches:** fully autonomous trading — user only watches/moves/inspects; SSE vs periodic board refresh; avatar selection local; focus/unfocus; big-win banner threshold (≥0.4◎ or ≥100%).
+- **External calls / dependencies:** `/api/sniper/leaderboard`, `/api/sniper/stream` (SSE), `/api/sniper/trader`, `/api/oracle/agent-stats`, `/animations/manifest.json`, avatar GLBs, Solscan, `/trader/<id>`. Solana mainnet (real pump.fun trades).
+- **Success state:** agents render + leaderboard + live tape; user can move + inspect; real trades animate in real time.
+- **Empty / error states:** no live agents → "No agents are live yet… arm a trader and enter"; SSE drop → "Reconnecting…" (retry 2.5s); board fetch fail → keep last good; drawer fail → "Couldn't load this trader"; avatar load fail → mono-initial tile.
+- **Step count:** 4 required (auto boot) + 3 optional (avatar, move, inspect).
+
+### Agent Exchange (feature page) — `/features/agent-exchange`
+- **Source:** `pages/features/agent-exchange.html` (static marketing landing; `/nav.js` + `/footer.js`).
+- **Entry point:** Static feature page explaining the Agent Exchange concept. NOT a demo — it links to the live demo at `/agent-exchange`.
+- **Prerequisites / gates:** None.
+- **Steps (1 required):**
+ 1. Read the page (hero, "How it works" 3-step, highlights, FAQ).
+ 2. (optional) Click **Watch live →** (`/agent-exchange`) to run the real demo, or **All features** (`/features`).
+- **Decision points / branches:** none (static).
+- **External calls / dependencies:** none beyond nav/footer includes.
+- **Success state:** user navigates to the live `/agent-exchange` demo.
+- **Empty / error states:** none (static content).
+- **Step count:** 1 required (+1 optional CTA).
+
+---
+
+## Notes
+
+- **Routing:** all clean URLs resolve through the `vite.config.js` `historyApiFallback` map (dev) / Vercel rewrites (prod). `/pay`, `/bazaar`, `/arbitrage`, `/providers`, `/forever`, `/tutor` live under `public/`; the rest under `pages/`.
+- **Shared payment modal:** `/x402.js` (`public/x402.js`, ~1.5k LOC) is the drop-in `window.X402.pay()` modal used by `/pay/c`, `/bazaar`, `/arbitrage`, `/ibm/x402-demo`, `/shopper` (paywall), `/fact-checker`, `/unstoppable`, `/tutor`. It handles wallet connect (Phantom/Solana, MetaMask/Base via EIP-3009), the 402→sign→retry loop, and SIWX re-entry.
+- **Server-payer vs user-payer:** the "agent economy" narratives (`/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo`, `/live`) pay from **server-held agent wallets** and stream the choreography over SSE — the user only triggers/selects, then watches. The "showcase" apps (`/shopper`, `/fact-checker`, `/tutor`, `/bazaar`, `/arbitrage`, `/ibm`) make the **user** pay via the `/x402.js` modal.
+- **Auto-play demos:** `/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo` need one user click to start, then auto-play. `/live` adds an auth gate for real settlement. `/play/arena` is fully autonomous (agents trade themselves; user only watches/moves/inspects) and uses **no x402** — real pre-funded Solana trades.
+- **Forever** is the only **non-x402** payment in the cluster: native Bitcoin (or Lightning) to an OrdinalsBot charge address, inscribing a real Taproot text inscription on Bitcoin mainnet.
+- **Source coverage:** all 17 routes located and traced from real source. `/tutor` resolves to `public/tutor.html` + `public/tutor.js` (served statically; no explicit vite map entry needed). No source was missing.
diff --git a/docs/ux-flows/10-chat-brain-labs.md b/docs/ux-flows/10-chat-brain-labs.md
new file mode 100644
index 000000000..2612ac543
--- /dev/null
+++ b/docs/ux-flows/10-chat-brain-labs.md
@@ -0,0 +1,235 @@
+# Chat, Brain & Labs
+
+UX Flow Atlas cluster covering the conversational, multi-LLM, and experimental-feature
+surfaces of three.ws. Each entry traces real source from route → page HTML → imported
+modules. Routes resolved via `vercel.json` rewrites.
+
+---
+
+### Conversational AI Chat (3D talking agent) — `/chat`
+- **Source:** `/workspaces/three.ws/chat/` (a standalone Svelte app, separate Vite build). Entry `/workspaces/three.ws/chat/index.html` → `/workspaces/three.ws/chat/src/main.js` → `/workspaces/three.ws/chat/src/App.svelte`. Key modules: `chat/src/providers.js` (LLM providers), `chat/src/convo.js` (streaming completion pipeline), `chat/src/TalkingHead.svelte` (3D avatar + TTS lip-sync), `chat/src/AgentPicker.svelte`, `chat/src/ModelSelector.svelte`, `chat/src/stores.js`, `chat/src/walletAuth.js` (SIWE/SIWS), `chat/src/tools.js`, `chat/src/sync.js`, `chat/src/SkillsMarketplaceModal.svelte`, `chat/src/TxApprovalModal.svelte`.
+- **Entry point:** `/chat` → `chat/index.html` (`<div id="app">` mounted by `main.js`).
+- **Prerequisites / gates:** None to start chatting — free built-in models stream through the server proxy with no key. Optional gates: user-supplied API key (Anthropic/OpenAI/Groq/Mistral/Ollama/OpenRouter) stored locally for non-built-in models; wallet sign-in (SIWE/SIWS via `/api/auth/*`) only for cross-device sync + on-chain tool calls; `TxApprovalModal` requires a connected wallet for wallet/pump tool transactions. No $THREE gate. 3D talking head and TTS are opt-in toggles (off by default).
+- **Steps (6):**
+ 1. Open `/chat`; app boots, fetches free model list from `/api/chat/models`, shows empty state with suggestion chips.
+ 2. (optional) Click the model selector and pick an LLM, or open `AgentPicker` to load a persona/agent (from `/api/agents`, `/api/marketplace/agents`, or the agent library JSON).
+ 3. (optional) Enable the 3D Talking Head and/or TTS toggle; a GLB avatar loads (`talkingHeadAvatarUrl`, fallback `/avatars/default.glb`).
+ 4. Type a message in the composer and submit (or attach an image / file for multimodal).
+ 5. `convo.complete()` POSTs to the provider's completion URL (built-in → `/api/chat/proxy`; Anthropic → `/v1/messages`; others → `/v1/chat/completions`) and streams tokens back into the assistant bubble (markdown + KaTeX rendered live).
+ 6. On reply completion: if Talking Head is enabled the avatar runs `talkingHead.speak({text, mood})` (TTS via `/api/tts/google` endpoint → viseme lip-sync); else if TTS toggle on, browser `speechSynthesis` reads it. Payoff: a 3D agent that answers in voice with synced mouth + mood animation.
+- **Decision points / branches:** model/provider choice (free built-in vs keyed provider vs OpenRouter "all models" vs local Ollama); text vs voice output (Talking Head 3D vs browser speechSynthesis vs silent); persona/agent loaded vs raw model; tool-calling on/off (curated tool packs: agent, pump, payments, wallet); regenerate / edit / branch a message; share conversation (compressed link via `share.js`).
+- **External calls / dependencies:** `/api/chat/models` (free model list, OpenRouter-proxied), `/api/chat/proxy` (built-in completions), `/api/chat/config`, `/api/chat/mcp`, `/api/tts/google` (TTS for lip-sync), `/api/agents` + `/api/marketplace/agents` (agent picker), `/api/auth/{me,logout,siwe/nonce,siwe/verify,siws/nonce,siws/verify}` (wallet auth), agent-library `index.en-US.json`. Direct provider APIs (api.anthropic.com, api.openai.com, api.groq.com, api.mistral.ai, openrouter.ai, local Ollama) when a user key is set. Three.js (importmap, r0.169) for the Talking Head.
+- **Success state:** Streamed assistant message rendered; if enabled, 3D avatar speaks with lip-sync + mood; conversation persisted to IndexedDB / optional E2E-encrypted sync.
+- **Empty / error states:** Empty state with brand tagline + suggestion chips when no messages. Provider/network errors surface as inline notices; abortable generation via `controller`. Missing API key → model marked unavailable in selector. Avatar GLB load failure falls back to default avatar; TTS failure degrades silently to text.
+- **Step count:** 6 required (+4 optional)
+
+---
+
+### Agent Profile / Directory — `/agent`
+- **Source:** `/agent` is a **301 redirect to `/agents`** (`vercel.json`). The directory `/agents` → `/workspaces/three.ws/pages/agents/index.html`; a single agent `/agents/:id` → `/workspaces/three.ws/pages/agent-detail.html` → `/workspaces/three.ws/src/agent-detail.js`. Supporting: `src/shared/agent-3d.js` (`seeInWorldHref`, `agentAvatarGlb`), `src/shared/agent-wallet-chip.js`, `src/shared/agent-coin.js`, `src/agent-detail-market.js`. (`src/agent-home.js` is a related presence component used by `/app` + `/app-demo`, not by `/agents/:id`.)
+- **Entry point:** `/agent` (redirect) → `/agents` directory grid → click an agent → `/agents/:id` profile.
+- **Prerequisites / gates:** None to view. Editing (`/agent/:id/edit` → `agent-edit.html`) and owner actions require wallet/owner auth. No $THREE gate to browse.
+- **Steps (4):**
+ 1. Hit `/agent` → 301 to `/agents`; directory of agents renders.
+ 2. Click an agent card → `/agents/:id` loads `agent-detail.js`.
+ 3. Profile renders: `<model-viewer>` 3D avatar preview, identity, voice metadata (cloned provider or browser TTS pill), live $THREE/pump token chip (streamed via `/api/pump/by-agent`), skills, history.
+ 4. Click "See in world" → routes to `/play?avatar=<glb>&coin=<THREE_MINT>` (the 3D world payoff); or "Edit" / wallet chip / coin-launch actions for owners.
+- **Decision points / branches:** view vs edit (owner); "See in world" (→ /play) vs embed (`/agent/:id/embed`) vs wallet (`/agent/:id/wallet`); token chip present (launched coin) vs not.
+- **External calls / dependencies:** `/api/agents/:id`, `/api/marketplace/agents/:id`, `/api/pump/by-agent` (live market-cap stream), `/api/agent-share` (share). model-viewer (Google CDN) for the 3D preview.
+- **Success state:** Agent profile with interactive 3D avatar, live token data, and working navigation to world/embed/edit.
+- **Empty / error states:** Avatar fetch failure → flat-image fallback (model-viewer hidden); enrich failure logged non-fatally; save errors surface inline in the edit flow.
+- **Step count:** 4 required (+2 optional)
+- **Note:** This route is a profile/directory surface, **not** a chat interface. The "talk to a 3D agent" experience lives at `/chat` (Talking Head). `/agents/:id` links *out* to `/play` ("See in world"), not to an inline chat.
+
+---
+
+### Brain — Persona Builder + Multi-LLM Playground — `/brain`
+- **Source:** `/workspaces/three.ws/pages/brain.html` → `/workspaces/three.ws/src/brain.js`.
+- **Entry point:** `/brain` → `brain.html` (H1 "Build Your Persona"), two tabs: Persona + Playground.
+- **Prerequisites / gates:** None to use the playground / compare models. Saving a persona as a deployed agent requires sign-in (auth-hint check + `/api/agents` with credentials); an auth gate is shown if signed out. No $THREE gate.
+- **Steps (6):**
+ 1. Open `/brain`; Persona tab active, archetype presets rendered.
+ 2. (optional) Apply an archetype preset or type freeform persona text → `/api/persona/extract` structures it into a persona object (tone, vocabulary, interests, dont_say, greeting).
+ 3. Switch to the Playground tab; provider availability fetched from `GET /api/brain/chat`, model chips/focus selector populated.
+ 4. Choose **Compare** mode (query several models at once) or **Focus** mode (one model); select active models.
+ 5. Type a prompt and run; `streamProvider()` POSTs to `/api/brain/chat` per model and streams responses side-by-side, each prefixed with the effective persona system prompt.
+ 6. (optional) Save the persona as an agent → POST `/api/agents` (or PATCH `/api/agents/:id`) with the built `system_prompt`.
+- **Decision points / branches:** Compare (multi-model fan-out) vs Focus (single model); persona enabled/disabled (`personaEnabled` toggle injects/omits the system prompt); archetype preset vs freeform extraction; model availability (unavailable models disabled in selector); save-as-agent (gated by auth).
+- **External calls / dependencies:** `GET /api/brain/chat` (provider availability), `POST /api/brain/chat` (per-model streaming completions), `/api/persona/extract` (structure persona), `/api/agents` + `/api/agents/:id` (load/save agent). Models span Anthropic / OpenAI / OpenRouter / Groq / ModelScope tiers.
+- **Success state:** Multiple model responses stream into the compare grid (or one in focus); persona optionally persisted locally and/or saved as a deployable agent.
+- **Empty / error states:** "Select at least one model" notice; provider-availability fetch failure is non-fatal (all models treated available); upstream stream error surfaces per-model; auth gate shown when saving while signed out; sessions/persona persisted to localStorage.
+- **Step count:** 6 required (+2 optional)
+
+---
+
+### GLB Playground / Embed Generator — `/playground`
+- **Source:** `/workspaces/three.ws/pages/playground.html` — **self-contained** (inline `<script>` IIFE, no `/src` module). Uses Google `<model-viewer>` (CDN) for rendering.
+- **Entry point:** `/playground` → `playground.html` (H1 "Playground"), drag-drop GLB viewer + embed-code generator.
+- **Prerequisites / gates:** None. No auth, no wallet, no $THREE. Files stay client-side.
+- **Steps (5):**
+ 1. Open `/playground`; default avatar (`/avatars/default.glb`) loads into the `<model-viewer>`.
+ 2. Drag-and-drop or upload a `.glb`/`.gltf` file into the dropzone (or use the file picker).
+ 3. Model loads with a loading indicator; file info (name, size, animation count) populates.
+ 4. (optional) Pick an animation from the dropdown, play/pause it, adjust exposure slider, orbit/zoom the model.
+ 5. Copy the generated `<model-viewer>` embed code from the embed panel to use the model on any site.
+- **Decision points / branches:** default avatar vs uploaded model; local file (embed note warns the URL must be hosted) vs hosted URL; animated vs static GLB (animation section only shows when clips exist); reset to default.
+- **External calls / dependencies:** Google model-viewer CDN (`ajax.googleapis.com/.../model-viewer.min.js`). No backend API calls — all parsing is in-browser via model-viewer.
+- **Success state:** Model renders interactively (rotate/zoom, optional animation playback) and a copyable embed snippet is produced.
+- **Empty / error states:** Status line shows transient messages (auto-clears after 3s); invalid/failed file → status error and the viewer retains the prior/default model; embed note flags that local files need a hosted URL before the embed works.
+- **Step count:** 5 required (+1 optional)
+- **Note:** `src/api-playground.js` exists but is a different surface (API console), not wired into `/playground`.
+
+---
+
+### Labs — Feature Gallery — `/labs`
+- **Source:** `/workspaces/three.ws/pages/labs.html` → `/workspaces/three.ws/src/labs.js`. Data: `/features.json` (static registry, mirror of `/api/features`).
+- **Entry point:** `/labs` → `labs.html`; grid of "gem" cards.
+- **Prerequisites / gates:** None. Pure discovery surface.
+- **Steps (3):**
+ 1. Open `/labs`; skeleton placeholders render while `/features.json` is fetched.
+ 2. Cards render (category-colored: Voice / AI / 3D Live / Crypto / x402); each runs a `HEAD` liveness check (3s timeout) and shows a Live/Checking status, plus a lazy IntersectionObserver iframe preview of the route.
+ 3. Click a card's "Try it →" CTA → navigates to that feature's route (e.g. `/lipsync`, `/brain`, `/three-live`, `/voice`).
+- **Decision points / branches:** category filtering (Voice/AI/3D/Crypto/x402); live vs unreachable (status badge from HEAD check); preview iframe lazy-loads only when scrolled into view.
+- **External calls / dependencies:** `GET /features.json` (registry), `HEAD <route>` per card (liveness), iframe `src=<route>` (sandboxed previews).
+- **Success state:** Populated gallery of feature cards with live previews and working "Try it" links into each experiment.
+- **Empty / error states:** Skeleton loading state; per-card "Checking → Live/Offline" status; HEAD failure (or ≥500) marks a card not-live; registry fetch failure leaves skeletons / empty grid.
+- **Step count:** 3 required (+1 optional)
+
+---
+
+### Launchpad Studio — `/launchpad`
+- **Source:** `/workspaces/three.ws/pages/launchpad.html` → inline `<script type="module">` → `/workspaces/three.ws/src/editor/launchpad-studio.js` (`mountLaunchpadStudio`).
+- **Entry point:** `/launchpad` (optional `?template=&slug=&wallet=&website=&avatar=` query hydration) → studio mounts into `#root` (3-pane: sidebar / live-preview stage / config rail).
+- **Prerequisites / gates:** Building/previewing is open. **Publishing requires a payout wallet address** (throws "Add your payout wallet address." otherwise) and writes via `/api/launchpad/publish`; editing an existing published page (`?slug=`) hydrates owner state and requires owner sign-in. Templates include a Token Launchpad (one-click Pump.fun mint with creator-fee split — generic runtime mint, $THREE-compliant). No $THREE gate to use the editor.
+- **Steps (6):**
+ 1. Open `/launchpad`; studio mounts with a default template (`token-launchpad`) and recent-projects from localStorage.
+ 2. Pick a template card (e.g. Token Launchpad, Concierge, Showroom).
+ 3. Fill the config form (slug, brand color, payout wallet, website, theme, avatar, monetization/chain) — live preview updates in the center stage.
+ 4. (optional) Attach a 3D avatar (agent-3d element) into the avatar-stage slot.
+ 5. Add the payout wallet address (required for publish).
+ 6. Click Publish → `POST /api/launchpad/publish`; on success the page is hosted at `/p/<slug>` and an owner token is kept in localStorage for re-edits.
+- **Decision points / branches:** template choice (token-launchpad vs concierge vs showroom…); new vs edit (`?slug=` hydration via `/api/launchpad/get`); chain/payout selection; signed-in owner vs anonymous (owner-only sections hidden on 401).
+- **External calls / dependencies:** `POST /api/launchpad/publish`, `GET /api/launchpad/get` (hydrate existing), `/api/agents` (my-agents avatar picker), Pump.fun launch plumbing (runtime mint, creator-fee split). agent-3d / Three.js for the avatar preview.
+- **Success state:** A live hosted page at `/p/<slug>` with the chosen template, brand, avatar, and (for token template) a one-click Pump.fun mint; editable later from the same browser.
+- **Empty / error states:** Publish blocked with actionable message if no payout wallet; publish-status line shows ok/err; owner-only sections silently hidden when signed out (401); recent-projects empty on first visit.
+- **Step count:** 6 required (+1 optional)
+
+---
+
+### Lip-Sync (TTS-driven) — `/lipsync`
+- **Source:** `/workspaces/three.ws/public/demos/lipsync-tts.html` (vercel rewrite target `demos/lipsync-tts.html`; resolves under `public/demos/`). Inline `<script type="module">`; uses Three.js + GLTFLoader (importmap) and the `wawa-lipsync` library for viseme detection.
+- **Entry point:** `/lipsync` → `lipsync-tts.html`; 3D avatar viewer (left) + text/voice controls (right).
+- **Prerequisites / gates:** None client-side (no auth, wallet, mic, or $THREE). Requires WebGL; TTS is served by the backend OpenAI integration.
+- **Steps (6):**
+ 1. Open `/lipsync`; avatar GLB (`/avatars/default.glb`) loads, viseme morphs wired, default text prefilled.
+ 2. (optional) Edit the text, pick a voice and speed.
+ 3. Click "Speak"; POST `/api/tts/speak` `{text, voice, speed, format:'mp3'}`.
+ 4. Server returns an MP3 blob; frontend plays it through an `<audio>` element connected to `wawa-lipsync`.
+ 5. Per animation frame, lipsync analyses the audio (FFT) → viseme code → mapped to avatar morph targets with EMA smoothing.
+ 6. Avatar mouth animates in sync; viseme bar chart updates live; "Speak" re-enables when playback ends.
+- **Decision points / branches:** voice + speed selection; retry on TTS failure; avatar-load failure degrades (UI still works, morphs unavailable).
+- **External calls / dependencies:** `POST /api/tts/speak` (OpenAI TTS), `GET /avatars/default.glb`, `wawa-lipsync` (client-side viseme analysis via Web Audio AnalyserNode), Three.js.
+- **Success state:** Avatar speaks the text with synced lips; status log confirms playback + morphs wired.
+- **Empty / error states:** Actionable errors for TTS unreachable / rejected text (400) / rate limit (429) / server error (5xx); autoplay-blocked → "needs a click to play"; avatar-load failure logged but non-blocking.
+- **Step count:** 6 required (+1 optional)
+
+---
+
+### Lip-Sync (Microphone-driven) — `/lipsync/mic`
+- **Source:** `/workspaces/three.ws/public/demos/lipsync-mic.html` → imports `/workspaces/three.ws/src/lip-sync-analyser.js` (`LipSyncAnalyser`). Three.js + GLTFLoader (importmap).
+- **Entry point:** `/lipsync/mic` → `lipsync-mic.html`; avatar viewer + mic controls, meter bars, viseme readout.
+- **Prerequisites / gates:** **Microphone permission** (getUserMedia) and a secure HTTPS context. No auth, wallet, or $THREE. Audio never leaves the browser.
+- **Steps (6):**
+ 1. Open `/lipsync/mic`; avatar loads, controls idle.
+ 2. Click "Start mic".
+ 3. Browser prompts for microphone permission; user grants.
+ 4. AudioContext + MediaStreamSource + AnalyserNode wired; `LipSyncAnalyser.connect()` called.
+ 5. Per frame, `analyser.sample()` reads frequency bands → maps to 9 viseme weights (aa/O/E/I/nn/SS/FF/CH/PP) with EMA smoothing + silence fade → drives avatar morphs.
+ 6. Speak into the mic → avatar mouth follows live; meter bars + viseme readout update; "Stop" resets morphs to 0.
+- **Decision points / branches:** start vs stop; permission granted vs denied; mic present/busy/secure-context branches.
+- **External calls / dependencies:** Web Audio API (`getUserMedia`, AnalyserNode — all in-browser), `GET /avatars/default.glb`, Three.js. No server/TTS calls.
+- **Success state:** Live mic-driven mouth animation with frequency meters and per-frame viseme weights.
+- **Empty / error states:** Actionable errors for mic denied / not found / busy / insecure (non-HTTPS) context, each with a "Try again"; avatar-morph missing → readout shows n/a; Web Audio unsupported → silent no-op.
+- **Step count:** 6 required (+0 optional)
+
+---
+
+### Club — 3D Pole-Stage Venue (x402) — `/club`
+- **Source:** `/workspaces/three.ws/pages/club.html` → scripts: `/x402.js` (wallet/payment modal), `/workspaces/three.ws/src/club-entrance.js` (walk-in alley scene), `/workspaces/three.ws/src/club-gate.js` (cover-charge bouncer), `/workspaces/three.ws/src/club.js` (main pole stage). Supporting modules in `src/`: `club-venue.js`, `club-audio.js`, `club-camera.js`, `club-crowd.js`, `club-perf.js`, `club-sequence.js`, `animation-manager.js`.
+- **Entry point:** `/club` → `club.html`; entrance scene + door gate + pole stage boot in parallel behind a loading screen.
+- **Prerequisites / gates:** **x402 wallet payment** — a cover charge settled on-chain (USDC, via `/api/x402/club-cover`); wallet (Phantom / EVM) connected through `x402.js`. No $THREE gate (USDC-denominated x402). WebGL required.
+- **Steps (7):**
+ 1. Open `/club`; loading screen with real GLB byte-count progress; avatar picker populates (bundled + gallery avatars via `/api/avatars/` and `/api/explore`).
+ 2. (optional) Select an avatar.
+ 3. Spawn in the entrance scene; move with WASD / touch joystick, look via drag.
+ 4. Walk to the neon door → "Enter the club" prompt; activate it.
+ 5. Door reveals the x402 cover screen; connect wallet and pay the cover → `POST /api/x402/club-cover` settles on-chain and checks the gate.
+ 6. On approval the rope drops; walk through to the pole stage — entrance fades, main `club.js` stage becomes active (dancers at poles, leaderboard, live tip feed).
+ 7. Select a pole + dance style and tip → `POST /api/x402/dance-tip`; on settlement the dancer performs the routine, leaderboard + live feed update, reactions float up.
+- **Decision points / branches:** avatar choice; cover approved vs "not tonight"; wallet not connected / insufficient balance; tip per pole + dance style; back-out to alley while paying; entrance-GLB failure → drop straight to stage.
+- **External calls / dependencies:** `POST /api/x402/club-cover`, `POST /api/x402/dance-tip`, `GET /api/club/tips`, SSE `/api/club/tips/stream`, `GET /api/club/leaderboard`, `/api/avatars/`, `/api/explore`; club venue/prop GLBs under `/club/...`, `/avatars/default.glb`, animation manifest/clips; `x402.js` wallet modal (Solana web3 / EVM). Three.js + post-processing.
+- **Success state:** User is inside the 3D club after paying cover; tipping plays dance routines and updates the live leaderboard/feed in real time.
+- **Empty / error states:** Cover denied → "not tonight" card (with reason); wallet-not-connected / insufficient-balance errors in the x402 modal; tip/clip load failure falls back to a default clip or bind pose; tip-stream disconnect → paused-feed badge with retry; entrance-GLB failure skips the walk-in.
+- **Step count:** 7 required (+1 optional)
+- **Note:** Some entrance/tip detail above is reconstructed from `club*.js` + endpoint references; exact on-stage routine names and per-pole UI copy were not exhaustively read.
+
+---
+
+### Feature Landing — Play — `/features/play`
+- **Source:** `/workspaces/three.ws/pages/features/play.html` (static marketing). Shared loaders: `public/nav.js`, `public/footer.js`; inline FAQ-accordion script.
+- **Entry point:** `/features/play` → `features/play.html`.
+- **Prerequisites / gates:** None — explicitly "No wallet needed to explore".
+- **Steps (2):**
+ 1. Read the marketing content (hero, biome swatches, FAQ accordion).
+ 2. Click the primary CTA "Enter a world →" → **`/play`** (secondary: "All features" → `/features`, "Try Walk instead" → `/features/walk`).
+- **Decision points / branches:** primary CTA (→ /play) vs cross-link to /features or /features/walk; FAQ expand/collapse.
+- **External calls / dependencies:** None (nav/footer loaders only; no API, no 3D viewer).
+- **Success state:** User clicks through to the `/play` 3D world.
+- **Empty / error states:** Static page — no data states; FAQ accordion is the only interaction.
+- **Step count:** 2 required (+0 optional) — primarily content/landing.
+
+---
+
+### Feature Landing — AR — `/features/ar`
+- **Source:** `/workspaces/three.ws/pages/features/ar.html` (static marketing with an embedded `<model-viewer>` AR preview). Shared `nav.js`/`footer.js`; model-viewer via Google CDN; inline FAQ script.
+- **Entry point:** `/features/ar` → `features/ar.html`.
+- **Prerequisites / gates:** None to view. The embedded model-viewer offers WebXR / Scene Viewer / Quick Look AR (uses device camera if the user taps the AR button).
+- **Steps (3):**
+ 1. Read content; an interactive `<model-viewer>` (model `/animations/robotexpressive.glb`) rotates in the hero.
+ 2. (optional) On a supported device, tap the model-viewer AR button to place the model in AR (camera permission requested by the browser/OS).
+ 3. Click the primary CTA "Browse avatars →" → **`/gallery`** (secondary: "Generate a model" → `/forge`; doc links → `/docs/ar`, `/docs/tutorials/view-in-ar`, `/docs/web-component`).
+- **Decision points / branches:** view-in-AR vs browse CTA vs generate CTA vs docs; FAQ accordion.
+- **External calls / dependencies:** Google model-viewer CDN; GLB asset `/animations/robotexpressive.glb`. No backend API.
+- **Success state:** User previews/places a model in AR or clicks through to `/gallery`.
+- **Empty / error states:** Static; AR button only appears on AR-capable devices.
+- **Step count:** 3 required (+1 optional) — primarily content with an interactive AR preview.
+
+---
+
+### Feature Landing — Walk — `/features/walk`
+- **Source:** `/workspaces/three.ws/pages/features/walk.html` (static marketing with `<model-viewer>` auto-rotate preview). Shared `nav.js`/`footer.js`; model-viewer CDN; inline FAQ script.
+- **Entry point:** `/features/walk` → `features/walk.html`.
+- **Prerequisites / gates:** None.
+- **Steps (2):**
+ 1. Read content; a `<model-viewer>` (model `/avatars/cz.glb`) auto-rotates (no AR button here).
+ 2. Click the primary CTA "Start walking →" → **`/walk`** (secondary: "All features" → `/features`, "Try Play instead" → `/features/play`).
+- **Decision points / branches:** primary CTA (→ /walk) vs cross-links; FAQ accordion.
+- **External calls / dependencies:** Google model-viewer CDN; GLB `/avatars/cz.glb`. No backend API.
+- **Success state:** User clicks through to the `/walk` experience.
+- **Empty / error states:** Static page.
+- **Step count:** 2 required (+0 optional) — primarily content.
+
+---
+
+### Feature Landing — Deploy — `/features/deploy`
+- **Source:** `/workspaces/three.ws/pages/features/deploy.html` (static marketing; no 3D viewer). Shared `nav.js`/`footer.js`; inline FAQ + static deploy-chain visualization.
+- **Entry point:** `/features/deploy` → `features/deploy.html`.
+- **Prerequisites / gates:** Landing is public. The actual deploy action (on the destination `/deploy` page) requires a Solana wallet to sign the on-chain transaction — the page describes "the UI previews the transaction and metadata before you sign".
+- **Steps (2):**
+ 1. Read content (deploy-chain explainer, ERC-8004 directory references, FAQ).
+ 2. Click the primary CTA "Deploy now →" → **`/deploy`** (secondary: "Browse deployed agents" → `/discover`; FAQ links → `/discover`, `/features/marketplace`, `/features/studio`).
+- **Decision points / branches:** deploy CTA (→ /deploy, wallet-gated at action) vs browse (→ /discover) vs feature cross-links; FAQ accordion.
+- **External calls / dependencies:** None on the landing page (nav/footer loaders only). Wallet/on-chain interaction happens later on `/deploy`.
+- **Success state:** User clicks through to `/deploy`.
+- **Empty / error states:** Static page; the wallet gate is on the destination, not here.
+- **Step count:** 2 required (+0 optional) — primarily content with a wallet-gated downstream action.
diff --git a/docs/ux-flows/11-account-dashboard.md b/docs/ux-flows/11-account-dashboard.md
new file mode 100644
index 000000000..091b4a6b9
--- /dev/null
+++ b/docs/ux-flows/11-account-dashboard.md
@@ -0,0 +1,212 @@
+# Account & Dashboard
+
+UX Flow Atlas — cluster 11. Traced end-to-end against real source in `/workspaces/three.ws`.
+
+## Routing summary
+
+Resolved from `vercel.json` (`routes`) and `vite.config.js` (`vercel-rewrites` dev middleware):
+
+| Route | Resolves to | Page module(s) |
+| --- | --- | --- |
+| `/login` | `public/login.html` | inline JS + `public/wallet-login.js` + `src/privy-login.js` |
+| `/register` | `public/register.html` | inline JS + `public/wallet-login.js` + `src/privy-login.js` |
+| `/forgot-password` | `public/forgot-password.html` | inline JS |
+| `/reset-password` | `public/reset-password.html` | inline JS (atlas-adjacent; documented as the completion of forgot-password) |
+| `/dashboard` | `pages/dashboard-next/index.html` | `src/dashboard-next/pages/home.js` |
+| `/dashboard/account` | `pages/dashboard-next/account.html` | `src/dashboard-next/pages/account.js` |
+| `/dashboard/analytics` | `pages/dashboard-next/analytics.html` | `src/dashboard-next/pages/analytics.js` |
+| `/dashboard/settings` | `pages/dashboard-next/settings.html` | `src/dashboard-next/pages/settings.js` |
+| `/settings` | `public/settings/index.html` | inline module script |
+
+`/login` and `/register` are **dedicated full pages, not modals**. Both share the same auth backend (`/api/auth/*`), the same Privy module (`src/privy-login.js`), and the same wallet-button loader (`public/wallet-login.js`). The shared client helpers live in `src/auth/email-auth.js` (`signInWithEmail`, `registerWithEmail`, `getCurrentUser`, `signOut`, `requireAuth`).
+
+Shared auth concepts:
+- **Session:** a `__Host-sid` cookie minted server-side by `createSession()`, identical across email/password, SIWE (EVM), SIWS (Solana), Privy, and SAML.
+- **Post-auth redirect:** `?next=` query param → `sessionStorage.login_redirect` → default (`/dashboard` for login, `/create` for register). On `/login`, an already-authenticated visitor is bounced to `next` via a `GET /api/auth/me` probe on load.
+- **Auth hint:** every successful auth writes `localStorage['3dagent:auth-hint']` so other surfaces render a logged-in chrome optimistically.
+
+---
+
+### Sign in — `/login`
+- **Source:** `public/login.html` (inline `<script>` for email/password + already-auth guard), `public/wallet-login.js` (EVM SIWE + Solana SIWS connect buttons in the on-chain drawer), `src/privy-login.js` (Privy email-OTP + Privy SIWE/SIWS), `src/auth/email-auth.js` (shared helpers).
+- **Entry point:** Direct nav to `/login`; from "Sign in" links in nav/footer; via `requireAuth()` / `requireUser()` redirects (`/login?return=…` or `?next=…`) from any gated page.
+- **Prerequisites / gates:** None to view. An existing account is required for the email/password path; wallet paths can sign in an existing wallet-linked user. If `GET /api/auth/me` resolves with a user on load, the page `location.replace(next)` immediately (skipped on back/forward navigation).
+- **Steps (N):**
+ 1. Page loads; theme boot script applies dark/light; nav injected from `/nav.js`; login avatar (`@three-ws/agent-ui`) renders on the side panel.
+ 2. On load, fire `GET /api/auth/me` (credentials included). If `{user}` → `location.replace(next)` (already signed in). If 401 → stay on form. If transport error → show "Couldn't verify your session…" notice but keep form usable.
+ 3. (optional) Email is prefilled from `?email=` or `localStorage['3dagent:last-email']`; if present, focus jumps to password.
+ 4. **Email/password path:** type email-or-username into `#email`, password into `#password`. Avatar covers its eyes while a credential field is focused. (optional) toggle show/hide password; Caps-Lock warning shows live.
+ 5. (optional) tick "Remember me".
+ 6. Click **Sign in** (`#submit`). Client validates both fields are non-empty (inline field errors + avatar facepalm on empty).
+ 7. `POST /api/auth/login` with `{ email, password, remember }`, credentials included. Button shows "Signing in…".
+ 8. On `!res.ok`: 429 → "Too many attempts…", else "Email or password is incorrect." — inline error on password field, avatar facepalm, button re-enabled.
+ 9. On success: persist `3dagent:last-email` + auth-hint; button "Signed in — redirecting…"; avatar plays a dance; after one dance cycle (700–1800ms) `location.replace(next)`.
+ 10. **(optional) Privy email-OTP path:** type email in `#privy-email-input` → click **Send code**. If the Privy app has CAPTCHA, a Cloudflare Turnstile challenge resolves first. `privy.auth.email.sendCode()` sends the code; UI advances to the code step.
+ 11. Enter the 6-digit code → **Verify** → `privy.auth.email.loginWithCode()` returns an `identity_token` → `POST /api/auth/privy/verify` mints the session → `location.href = next`. (optional **← Back** returns to email step.)
+ 12. **(optional) Privy EVM wallet:** click the **EVM** chain button → `eth_requestAccounts` → `privy.auth.siwe.init()` builds the message → `personal_sign` in wallet → `privy.auth.siwe.loginWithSiwe(signature)` → `POST /api/auth/privy/verify` → redirect. Status text walks through "Requesting accounts… / Generating message… / Sign… / Signing in…".
+ 13. **(optional) Privy Solana wallet:** click the **Solana** chain button → `provider.connect()` (Phantom/Backpack/Solflare) → `GET /api/auth/siws/nonce` → build SIWS message → `provider.signMessage` → `POST /api/auth/siws/verify` (with `x-csrf-token`) → redirect.
+ 14. **(optional) On-chain features drawer:** click "Connect wallet" to expand `#onchain-section`; Solana/EVM tabs mount the native connect buttons from `public/wallet-login.js` (full SIWE/SIWS via `/wallet/connect-button*.js`). Drawer state persists in `sessionStorage['login:onchain']`.
+ 15. **(optional) Enterprise SSO:** if `GET /api/config` returns `samlEnabled`, the **SSO** button reveals and navigates to `/api/auth/saml/login?next=…`.
+- **Decision points / branches:** email+password (legacy `/api/auth/login`) **vs** Privy email-OTP (`/api/auth/privy/verify`) **vs** Privy EVM SIWE **vs** Privy Solana SIWS **vs** native on-chain drawer SIWE/SIWS (`wallet-login.js`) **vs** SAML SSO. Solana chain tab auto-disables and falls back to EVM when no Solana provider is detected.
+- **External calls / dependencies:** `GET /api/auth/me`, `POST /api/auth/login`, `POST /api/auth/privy/verify`, `GET /api/auth/siws/nonce`, `POST /api/auth/siws/verify`, `GET /api/config`, `/api/auth/saml/login`; Privy JS SDK (`@privy-io/js-sdk-core`, app id from `/api/config`), Cloudflare Turnstile, browser wallet providers (`window.ethereum`, `window.solana`/Phantom/Backpack/Solflare), `@three-ws/agent-ui` (avatar), model-viewer CDN.
+- **Success state:** Session cookie set; auth-hint persisted; `location.replace`/`href` to `next` (default `/dashboard`).
+- **Empty / error states:** Per-field inline errors with shake + avatar facepalm; transport-failure banner on the session probe; SSO error codes from the URL (`sso_unavailable`, `saml_invalid`, `account_deleted`, `rate_limited`, etc.) and `?signed_out` notice; Privy/wallet errors map "reject/denied/cancel" to "Signature cancelled."; wallet-module load failure shows a connection error; wallet skeleton shimmer while connect buttons mount.
+- **Step count:** 9 required (+6 optional)
+
+---
+
+### Create account — `/register`
+- **Source:** `public/register.html` (inline JS: username/password submit + already-auth guard + password-strength + on-chain drawer), `src/privy-login.js` (same Privy email-OTP/wallet paths as login), `public/wallet-login.js`, `src/auth/email-auth.js` (`registerWithEmail`).
+- **Entry point:** "Create one" link from `/login`; "Create account" / "Sign up" CTAs; gated-flow redirects.
+- **Prerequisites / gates:** None. Already-signed-in visitors are bounced to `next` (default `/create`) via the `GET /api/auth/me` guard (skipped on back/forward).
+- **Steps (N):**
+ 1. Page loads; register avatar (`/avatars/cz.glb` model-viewer) renders with mouse-parallax look-around.
+ 2. On load, `GET /api/auth/me`; if `{user}` → `location.replace(next)`; 401 stays; transport error shows a notice.
+ 3. Type a **Username** (`#username`, 3–30 chars, `[a-zA-Z0-9_-]`); inline hint validates live ("✓ Looks good" / specific error).
+ 4. Type a **Password** (`#password`, min 10 chars); strength meter updates (Too short → Very strong); Caps-Lock warning; (optional) show/hide toggle.
+ 5. Click **Create account** (`#submit`); button shows "Creating account…".
+ 6. `POST /api/auth/register` with `{ username, password }`, credentials included.
+ 7. On `!res.ok`: 429 → "Too many attempts…"; 409 → "That username is taken."; 400 → field guidance; 422 → "…isn't allowed — try another."; 5xx → server-fault copy; network `TypeError` → "Couldn't reach the server…". Error banner shown, button re-enabled.
+ 8. On success: server creates the account **and an immediate session** (signed in on register); persist auth-hint; `location.replace(next)` (default `/create`).
+ 9. **(optional) Privy email-OTP / EVM / Solana wallet** registration — identical flows to `/login` (shared `src/privy-login.js`): Send code → Verify, or EVM SIWE, or Solana SIWS → session → redirect.
+ 10. **(optional) On-chain features drawer** — same Solana/EVM native connect buttons; state persists in `sessionStorage['register:onchain']`.
+- **Decision points / branches:** username+password (`/api/auth/register`) **vs** Privy email-OTP **vs** Privy EVM SIWE **vs** Privy Solana SIWS **vs** native on-chain drawer SIWE/SIWS. (Note: the primary form here collects **username** + password, whereas `/login` accepts email-or-username; the shared `registerWithEmail()` helper supports an email+displayName variant used by other surfaces.)
+- **External calls / dependencies:** `GET /api/auth/me`, `POST /api/auth/register`, `POST /api/auth/privy/verify`, `GET /api/auth/siws/nonce`, `POST /api/auth/siws/verify`, `GET /api/config`; Privy SDK, Turnstile, browser wallets, model-viewer CDN.
+- **Success state:** Account created, session minted, redirect to `next` (default `/create`); user is logged in.
+- **Empty / error states:** Live username/password validation; status-mapped error banner (taken username, rate-limit, server fault, offline); Privy/wallet cancellation handling; ToS/Privacy legal copy below the button.
+- **Step count:** 8 required (+2 optional)
+
+---
+
+### Forgot password — `/forgot-password`
+- **Source:** `public/forgot-password.html` (inline JS). Completion happens at `/reset-password` (`public/reset-password.html`).
+- **Entry point:** "Forgot password?" link in the `/login` remember-row.
+- **Prerequisites / gates:** None. Privacy-preserving: never reveals whether an account exists.
+- **Steps (N):**
+ 1. Page loads; avatar look-around; email field focus lights its label.
+ 2. Type email (`#email`); inline hint validates format live ("✓ Looks valid" / "Enter a valid email address.").
+ 3. Click **Send reset link** (`#submit`); button shows "Sending…".
+ 4. `POST /api/auth/forgot-password` with `{ email }`.
+ 5. Server always answers 200 with a privacy-preserving body. On status `< 500` → show success notice: "If an account exists for that email, a reset link has been sent."; on `>= 500` → error notice "Something went wrong on our end…"; on fetch rejection → "Couldn't reach the server…".
+ 6. Button re-enabled ("Send reset link") regardless, so the user can retry.
+ 7. **(completion, separate route) `/reset-password?token=…`:** user clicks the emailed link → `public/reset-password.html` reads `?token`. If no token → error + disabled submit. Enter new password + confirm (both min 10, must match) → **Reset password** → `POST /api/auth/reset-password` with `{ token, password }` → on success swap to "Password reset. You can now log in." with a link back to `/login`; on error show message and re-enable.
+- **Decision points / branches:** Single path (email). The reset-completion step is a distinct page reached from email, not a branch within `/forgot-password`.
+- **External calls / dependencies:** `POST /api/auth/forgot-password`; (completion) `POST /api/auth/reset-password`; model-viewer CDN.
+- **Success state:** Privacy-preserving "reset link sent" notice (request side); on the completion page, "Password reset" confirmation with a sign-in link.
+- **Empty / error states:** Inline email-format hint; 5xx error notice; offline/transport error notice; reset page guards a missing/invalid token and enforces match + length.
+- **Step count:** 6 required (+1 completion step on a separate route)
+
+---
+
+### Dashboard overview — `/dashboard`
+- **Source:** `pages/dashboard-next/index.html` → `src/dashboard-next/pages/home.js`; shell from `src/dashboard-next/shell.js` (sidebar/topbar/drawer/palette); data helpers from `src/dashboard-next/api.js`.
+- **Entry point:** Nav/footer "Dashboard" links; post-login redirect default; `getting-started.js` guide.
+- **Prerequisites / gates:** **Signed-in required.** `requireUser()` (in `api.js`) calls `getMe()` → `GET /api/auth/me`; on 401 it navigates to `/login?return=<path>` and returns a never-resolving promise so the page halts cleanly. `/dashboard-classic/*` and legacy sub-routes 301 to canonical `/dashboard/*` (vercel.json + dev middleware).
+- **Steps (N):**
+ 1. `home.js` boots → `mountShell()` renders sidebar + topbar + live-event drawer + command palette; the active nav item pulses "you are here".
+ 2. `requireUser()` resolves the session (or redirects to login).
+ 3. Greeting renders ("Welcome back, &lt;name&gt;."); new-account detection (< 30 days) and dismissal flags (`twx_onboarding_dismissed`, `twx_forge_announce_dismissed`) decide which banners show.
+ 4. Skeletons render across hero / KPI / activity slots.
+ 5. Parallel fetch: `GET /api/avatars?limit=50`, `GET /api/widgets`, `GET /api/agents?limit=20` (each `Promise.allSettled`, degrades independently).
+ 6. Hero strip shows live 3D avatar previews; KPI row (revenue, views, transcripts, avatars) with sparklines over a 7-day window; trading + world-health sections; 2×2 quick-actions grid; agent/avatar directory; recent-activity feed (stitched transcripts + revenue events).
+ 7. The onboarding guide (`getting-started.js`) is reconciled against authoritative server state (avatars/agents/widgets) on every visit.
+ 8. KPIs + activity re-poll every 30s; relative timestamps tick every 60s.
+ 9. (optional) Use the sidebar to navigate to sub-pages (account, analytics, settings, agents, avatars, tokens, monetize, etc.); open the command palette; open the live-event drawer (pulses on new events); dismiss onboarding/announce banners.
+ 10. (optional) If the user arrived via a referral link, `claimPendingReferral()` attributes it now that a session exists (no-op otherwise).
+- **Decision points / branches:** New vs returning user (onboarding banner); each data slot renders, empties, or errors independently; referral-claim runs only with a pending code.
+- **External calls / dependencies:** `GET /api/auth/me`, `GET /api/avatars`, `GET /api/widgets`, `GET /api/agents`, plus KPI/activity polling endpoints; shared `tour.js`, `crypto-optional.js`, `log.js`.
+- **Success state:** Authenticated overview rendered with live KPIs, hero avatars, and activity; navigation chrome fully wired.
+- **Empty / error states:** Per-slot skeletons during load; new-user onboarding panel as the "empty" guidance; failed data fetches degrade per slot (empty arrays) rather than failing the page; unauthenticated → redirect to `/login`.
+- **Step count:** 8 required (+2 optional)
+
+---
+
+### Account management — `/dashboard/account`
+- **Source:** `src/dashboard-next/pages/account.js` (+ shell + `api.js`).
+- **Entry point:** Sidebar "Account"; quick-links; `/dashboard/wallets`, `/dashboard/actions`, `/dashboard/sns`, `/dashboard/delegation` all 301 here.
+- **Prerequisites / gates:** Signed-in required (`requireUser()` → `/login?return=…` on 401).
+- **Steps (N):**
+ 1. Boot: `mountShell()` then `requireUser()`.
+ 2. Page renders sections: **Profile** (display name, username, sign out), **AI Provider Keys**, **Linked Wallets**, **SNS / .sol handle domains**, **Vanity Wallets** (Solana + ETH CREATE2), **Delegation** console, **Action Log / audit trail**, and quick links to settings/storage/usage/ERC-8004.
+ 3. **(optional) Update profile:** click edit on the name row → inline input (max 60) → **Save** → `PATCH /api/auth/profile` `{ display_name }` → toast "Saved", profile re-renders. Username edit → `PATCH /api/auth/profile` `{ username }` → toast "Username saved".
+ 4. **(optional) Provider keys:** enter a key → **Save** → `PATCH /api/user/provider-keys` `{ [provider]: value }` → toast "Key saved"; clear → `PATCH …` `{ [provider]: null }` → toast "Key removed".
+ 5. **(optional) Linked wallets:** list from `GET /api/auth/wallets`. "Make primary" → `POST /api/auth/wallets/primary` `{ address }` → toast "Primary wallet updated" + refresh. "Disconnect" → confirm → `DELETE /api/auth/wallets/{address}` → toast "Wallet disconnected" + row removed. "+ Link wallet" routes to the wallet-linking flow.
+ 6. **(optional) SNS / vanity:** "Register domain" → `/vanity-wallet`; "Manage" → external `sns.id`; vanity tools open `/vanity-wallet` and `/eth-vanity`.
+ 7. **(optional) Delegation:** open console → pick target agent + message (max 8000) → **Run delegation** → `POST /api/agent-delegate` `{ toAgentId, message }` → response box with model tag; status-specific errors (429/404/503).
+ 8. **(optional) Audit log:** "Export CSV" → `GET /api/audit-log?format=csv` → toast "CSV downloaded"; "Load older" paginates `GET /api/audit-log`.
+ 9. **(optional) Sign out:** `POST /api/auth/logout` → redirect to `/`.
+- **Decision points / branches:** Each section is independent; wallet/SNS sections show empty states when nothing is linked; delegation requires at least one agent.
+- **External calls / dependencies:** `GET /api/auth/me`, `PATCH /api/auth/profile`, `PATCH /api/user/provider-keys`, `GET /api/auth/wallets`, `POST /api/auth/wallets/primary`, `DELETE /api/auth/wallets/{address}`, `POST /api/agent-delegate`, `GET /api/audit-log`, `POST /api/auth/logout`.
+- **Success state:** Toasts on each mutation (Saved / Username saved / Key saved / Primary wallet updated / Wallet disconnected / CSV downloaded); sections re-render with fresh data.
+- **Empty / error states:** "No wallets linked", "No Solana wallets linked", "No primary .sol domains found", "No agents to delegate", "Audit log is empty"; load-failure toasts ("Couldn't load &lt;section&gt;"); audit 404 ("endpoint not deployed yet"), 401 ("Sign in required").
+- **Step count:** 2 required (boot + render) (+7 optional management flows)
+
+---
+
+### Analytics — `/dashboard/analytics`
+- **Source:** `src/dashboard-next/pages/analytics.js` (+ shell + `api.js` + shared `state-kit`). `/dashboard/usage` 301s here.
+- **Entry point:** Sidebar "Analytics"; "View analytics" links.
+- **Prerequisites / gates:** Signed-in required (`requireUser()`; 401 → `/login?return=…`).
+- **Steps (N):**
+ 1. Boot: `mountShell()` → `requireUser()`; title "Analytics" + subtitle render.
+ 2. Skeletons render (4 KPI bones + 3 panel bones).
+ 3. Parallel fetch for the selected range (default **30 days**): `GET /api/billing/revenue?from&to&granularity`, `GET /api/agents?limit=50`, `GET /api/widgets`, `GET /api/billing/summary` (+ `GET /api/monetization/revenue?period=…`).
+ 4. Secondary fetches: per-widget `GET /api/widgets/{id}/stats` (up to 20) and `GET /api/agents/{id}/payments?direction=received&limit=5` for the top 5 agents.
+ 5. Render: **range bar** (7d / 30d / 90d / 12mo), **KPI cards** (Total Revenue, Total Callers, Avg Price/Call, Top Agent), **Revenue Over Time** canvas line chart (animated, hover tooltip), **Revenue by Skill** horizontal bars (top 8), **Agent Performance** table (Views / Chats / Conv.%), **Recent Activity** table (latest 20 payments with Settled/Failed/Pending badges).
+ 6. **(optional)** Click a range button → refetch with new `from/to/granularity` → re-render with chart re-animation.
+- **Decision points / branches:** Time-range selection drives granularity (day vs week). Critical error only when all four primary surfaces fail; individual fetches degrade silently via a `safe()` wrapper.
+- **External calls / dependencies:** `GET /api/auth/me`, `/api/billing/revenue`, `/api/agents`, `/api/widgets`, `/api/billing/summary`, `/api/monetization/revenue`, `/api/widgets/{id}/stats`, `/api/agents/{id}/payments`.
+- **Success state:** Fully rendered metrics dashboard with live charts and tables for the chosen window.
+- **Empty / error states:** Panel-level empties — "No revenue data for this period. Set up monetization" (→ `/dashboard/monetize`), "No skill revenue yet", "No agents yet. Create one" (→ `/dashboard/agents`), "No revenue events yet…"; global "Couldn't load analytics" with a Reload button when all primary surfaces fail; skeletons during load.
+- **Step count:** 5 required (+1 optional)
+
+---
+
+### Dashboard settings (app preferences) — `/dashboard/settings`
+- **Source:** `src/dashboard-next/pages/settings.js` (+ shell + `api.js`). `/dashboard/sessions`, `/dashboard/voice`, `/dashboard/storage` and several legacy routes 301 here.
+- **Entry point:** Sidebar "Settings"; quick-links from `/dashboard/account`.
+- **Prerequisites / gates:** Signed-in required (`requireUser()`; 401 → `/login?return=…`).
+- **Steps (N):**
+ 1. Boot: `mountShell()` → `requireUser()`; 4 skeletons while data loads.
+ 2. Parallel fetch: `GET /api/auth/sessions`, `GET /api/notifications?limit=20`, `GET /api/billing/summary` (storage), `GET /api/usage/summary` (LLM usage), plus dashboard prefs.
+ 3. Render sections: **Appearance/theme**, **Active sessions**, **Notifications**, **Default payment network**, **Storage usage**, **LLM usage**, **Vanity wallet tools**, **Preferences**, **Data export**, **About**.
+ 4. **(optional) Theme:** click Dark/Light/Auto → `localStorage['twx_theme']` (+ `window.threeTheme.set`) → toast "Theme applied" (no API).
+ 5. **(optional) Sessions:** "Revoke" → `DELETE /api/auth/sessions/{id}` → toast + row removed; "Revoke all other" → `POST /api/auth/sessions/revoke-others` → toast.
+ 6. **(optional) Notifications:** "Mark all read" → `POST /api/notifications/read-all` → toast.
+ 7. **(optional) Default network:** Base/Solana/Polygon → `localStorage['twx_default_network']` + best-effort `PATCH /api/dashboard/prefs` `{ prefs: { default_network } }` → toast.
+ 8. **(optional) Preferences:** toggle email notifications / show tips / compact sidebar → **Save preferences** → `PATCH /api/dashboard/prefs` `{ prefs }` → toast "Preferences saved".
+ 9. **(optional) Data export:** Agents / Avatars / All → fetch `GET /api/agents`, `GET /api/avatars?limit=100`, `GET /api/widgets` → build JSON blob → browser download → toast "Data exported".
+- **Decision points / branches:** Theme, default network, and privacy-style toggles are local-first (localStorage) with best-effort prefs sync; sessions/notifications/export hit live APIs. Read-only meters for storage/LLM usage.
+- **External calls / dependencies:** `GET /api/auth/me`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `POST /api/auth/sessions/revoke-others`, `GET /api/notifications`, `POST /api/notifications/read-all`, `GET /api/billing/summary`, `GET /api/usage/summary`, `PATCH /api/dashboard/prefs`, `GET /api/agents`, `GET /api/avatars`, `GET /api/widgets`.
+- **Success state:** Toasts on each action (Theme applied / Session revoked / All notifications marked read / Default network set / Preferences saved / Data exported); sections reflect new state.
+- **Empty / error states:** "No session data", "No notifications" / "You're all caught up", "No usage data"; per-action error toasts with button re-enable for retry; skeletons during load.
+- **Step count:** 3 required (boot + fetch + render) (+6 optional setting flows)
+
+---
+
+### Account settings (profile / security hub) — `/settings`
+- **Source:** `public/settings/index.html` (standalone page, inline module script). **Distinct page** from `/dashboard/settings` — neither redirects to the other.
+- **Entry point:** Direct nav to `/settings`; header/account menu "Settings"; deep links to tab hashes (`#profile`, `#account`, `#privacy`, `#sessions`, `#connected-accounts`, `#danger`).
+- **Prerequisites / gates:** Signed-in required. `loadUser()` → `GET /api/auth/me`; if no user / 401 → `location` to `/login?next=/settings`.
+- **Steps (N):**
+ 1. Page loads; `GET /api/auth/me` resolves the user (or redirects to login).
+ 2. Tabbed UI renders (default `#profile`); fields populate from the user record + follow-up fetches.
+ 3. **Profile tab:** edit display name (max 80) + username (3–30, pattern-validated, live profile-URL preview) → **Save changes** → `PATCH /api/auth/profile` `{ display_name, username }` → "Saved!" inline message (4s) + URL preview update.
+ 4. **(optional) Account tab:** read-only email with Verified/Unverified badge (`user.email_verified`); password "Reset via email ↗" → `/forgot-password`; connected wallets count from `GET /api/auth/wallets` (→ `/dashboard/account` to manage); plan display (→ `/dashboard#billing`); **Sign out everywhere** → `POST /api/auth/logout-everywhere` → clear localStorage → redirect to `/login`.
+ 5. **(optional) Privacy tab:** default avatar visibility select (private/unlisted/public) → **Save** → `localStorage['3dagent:default-vis']` → "Saved preference."
+ 6. **(optional) Sessions tab:** list from `GET /api/auth/sessions` (device/IP/date); "Revoke" → `DELETE /api/auth/sessions/{id}` (row removed); **Revoke all other sessions** → `DELETE /api/auth/sessions` → "All other sessions revoked." + reload.
+ 7. **(optional) Connected Accounts tab:** GitHub status `GET /api/auth/github/status`; connect → `/api/auth/github/connect?agent_id=…`; seed agent memory → `POST /api/agents/{agentId}/memory-seed`. X status `GET /api/agents/{agentId}/memory/seed/x`; connect → `/api/auth/x/connect?agent_id=…`; seed → `POST /api/agents/{agentId}/memory/seed/x`. Supports `?agent_id=` prefill.
+ 8. **(optional) Danger Zone tab:** click "Delete my account…" → type "delete my account" to enable → **Permanently delete** → `DELETE /api/auth/me` → clear localStorage → redirect to `/?deleted=1`.
+- **Decision points / branches:** Six hash-routed tabs; profile is the primary editable surface; privacy is local-only; account/sessions/connections/danger hit live APIs. Distinct from `/dashboard/settings` (which is app preferences, no identity/security fields).
+- **External calls / dependencies:** `GET /api/auth/me`, `PATCH /api/auth/profile`, `GET /api/auth/wallets`, `POST /api/auth/logout-everywhere`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `DELETE /api/auth/sessions`, `GET /api/auth/github/status`, `/api/auth/github/connect`, `POST /api/agents/{id}/memory-seed`, `GET`/`POST /api/agents/{id}/memory/seed/x`, `/api/auth/x/connect`, `DELETE /api/auth/me`.
+- **Success state:** "Saved!" / "Saved preference." / "All other sessions revoked." inline messages (auto-hide 4s); GitHub/X "Connected" tags; account deletion redirect to `/?deleted=1`.
+- **Empty / error states:** "No sessions found."; "Not connected" + connect buttons for GitHub/X; inline `.ok`/`.err` messages; delete-flow confirmation gate + error alert with button revert; "Checking…"/"Loading…" placeholders during async loads.
+- **Step count:** 3 required (boot + profile load + save profile) (+5 optional tab flows)
+
+---
+
+## Notes on routing edge cases
+
+- **No login/register modal:** auth is full-page (`/login`, `/register`). Other surfaces trigger it by redirect (`requireAuth()` in `src/auth/email-auth.js`, `requireUser()` in `src/dashboard-next/api.js`), preserving the origin via `?return=`/`?next=`. The dashboard chrome itself is gated, not the marketing pages.
+- **Two settings surfaces, intentionally separate:** `/settings` = identity/security/connections/danger (profile hub); `/dashboard/settings` = app/dashboard preferences (theme, sessions, notifications, network, storage/LLM meters, export). They share only the concept of "sessions" (each with its own UI and revoke calls).
+- **Heavy 301 consolidation:** `/dashboard-classic/*` and many legacy `/dashboard/*` slugs (wallets, sessions, actions, memory, strategy, voice, sns, delegation, x402, storage, usage, agent-pumpfun) redirect to the canonical `/dashboard/*` pages — mirrored in both `vercel.json` and the Vite dev middleware so dev matches prod.
diff --git a/mcp-server/src/lib/bip39-english.js b/mcp-server/src/lib/bip39-english.js
new file mode 100644
index 000000000..c111ae78b
--- /dev/null
+++ b/mcp-server/src/lib/bip39-english.js
@@ -0,0 +1,268 @@
+// BIP-0039 English wordlist (2048 words) — vendored verbatim from the BIP-39
+// reference (github.com/bitcoin/bips/blob/master/bip-0039/english.txt). This is
+// a public, immutable constant of the BIP-39 standard, embedded here so the
+// vanity mnemonic grinder is fully self-contained and never depends on an
+// undeclared transitive `bip39` install at runtime.
+//
+// Integrity: sha256(words.join('\n')) === '187db04a869dd9bc7be80d21a86497d692c0db6abd3aa8cb6be5d618ff757fae'.
+// Order is consensus-critical — each word's index IS its 11-bit value. Do not
+// sort, dedupe, or otherwise reorder.
+
+export const ENGLISH_WORDLIST = Object.freeze([
+ "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract",
+ "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid",
+ "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual",
+ "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance",
+ "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent",
+ "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album",
+ "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone",
+ "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among",
+ "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry",
+ "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique",
+ "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april",
+ "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor",
+ "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact",
+ "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume",
+ "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction",
+ "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado",
+ "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis",
+ "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball",
+ "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base",
+ "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become",
+ "beef", "before", "begin", "behave", "behind", "believe", "below", "belt",
+ "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle",
+ "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black",
+ "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood",
+ "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body",
+ "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring",
+ "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain",
+ "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief",
+ "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother",
+ "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb",
+ "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus",
+ "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable",
+ "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can",
+ "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable",
+ "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry",
+ "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog",
+ "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling",
+ "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk",
+ "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap",
+ "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child",
+ "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar",
+ "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify",
+ "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff",
+ "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud",
+ "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut",
+ "code", "coffee", "coil", "coin", "collect", "color", "column", "combine",
+ "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm",
+ "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper",
+ "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch",
+ "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle",
+ "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream",
+ "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop",
+ "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch",
+ "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious",
+ "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad",
+ "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn",
+ "day", "deal", "debate", "debris", "decade", "december", "decide", "decline",
+ "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay",
+ "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend",
+ "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk",
+ "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram",
+ "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital",
+ "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover",
+ "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide",
+ "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain",
+ "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft",
+ "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill",
+ "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb",
+ "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager",
+ "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo",
+ "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight",
+ "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator",
+ "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ",
+ "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy",
+ "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough",
+ "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode",
+ "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt",
+ "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil",
+ "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude",
+ "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit",
+ "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend",
+ "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint",
+ "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy",
+ "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault",
+ "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female",
+ "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field",
+ "figure", "file", "film", "filter", "final", "find", "fine", "finger",
+ "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness",
+ "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight",
+ "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly",
+ "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot",
+ "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil",
+ "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend",
+ "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel",
+ "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy",
+ "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment",
+ "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius",
+ "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle",
+ "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass",
+ "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue",
+ "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip",
+ "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass",
+ "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group",
+ "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun",
+ "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy",
+ "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard",
+ "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet",
+ "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip",
+ "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow",
+ "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital",
+ "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble",
+ "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband",
+ "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill",
+ "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose",
+ "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate",
+ "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial",
+ "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane",
+ "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest",
+ "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory",
+ "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel",
+ "job", "join", "joke", "journey", "joy", "judge", "juice", "jump",
+ "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup",
+ "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit",
+ "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know",
+ "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language",
+ "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law",
+ "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave",
+ "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend",
+ "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty",
+ "library", "license", "life", "lift", "light", "like", "limb", "limit",
+ "link", "lion", "liquid", "list", "little", "live", "lizard", "load",
+ "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop",
+ "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber",
+ "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet",
+ "maid", "mail", "main", "major", "make", "mammal", "man", "manage",
+ "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin",
+ "marine", "market", "marriage", "mask", "mass", "master", "match", "material",
+ "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure",
+ "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory",
+ "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message",
+ "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind",
+ "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake",
+ "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment",
+ "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning",
+ "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie",
+ "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music",
+ "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin",
+ "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative",
+ "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral",
+ "never", "news", "next", "nice", "night", "noble", "noise", "nominee",
+ "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice",
+ "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey",
+ "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean",
+ "october", "odor", "off", "offer", "office", "often", "oil", "okay",
+ "old", "olive", "olympic", "omit", "once", "one", "onion", "online",
+ "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit",
+ "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich",
+ "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over",
+ "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page",
+ "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper",
+ "parade", "parent", "park", "parrot", "party", "pass", "patch", "path",
+ "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut",
+ "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper",
+ "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical",
+ "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot",
+ "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet",
+ "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge",
+ "poem", "poet", "point", "polar", "pole", "police", "pond", "pony",
+ "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery",
+ "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare",
+ "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority",
+ "prison", "private", "prize", "problem", "process", "produce", "profit", "program",
+ "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide",
+ "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil",
+ "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle",
+ "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz",
+ "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail",
+ "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid",
+ "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real",
+ "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle",
+ "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject",
+ "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove",
+ "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report",
+ "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire",
+ "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib",
+ "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid",
+ "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road",
+ "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room",
+ "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude",
+ "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness",
+ "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same",
+ "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say",
+ "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science",
+ "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea",
+ "search", "season", "seat", "second", "secret", "section", "security", "seed",
+ "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence",
+ "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft",
+ "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine",
+ "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder",
+ "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side",
+ "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar",
+ "simple", "since", "sing", "siren", "sister", "situate", "six", "size",
+ "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab",
+ "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan",
+ "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth",
+ "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social",
+ "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve",
+ "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup",
+ "source", "south", "space", "spare", "spatial", "spawn", "speak", "special",
+ "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin",
+ "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray",
+ "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium",
+ "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay",
+ "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting",
+ "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street",
+ "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject",
+ "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest",
+ "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme",
+ "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain",
+ "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim",
+ "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table",
+ "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target",
+ "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten",
+ "tenant", "tennis", "tent", "term", "test", "text", "thank", "that",
+ "theme", "then", "theory", "there", "they", "thing", "this", "thought",
+ "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger",
+ "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title",
+ "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token",
+ "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top",
+ "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist",
+ "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic",
+ "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree",
+ "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy",
+ "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try",
+ "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle",
+ "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical",
+ "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo",
+ "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown",
+ "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon",
+ "upper", "upset", "urban", "urge", "usage", "use", "used", "useful",
+ "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley",
+ "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle",
+ "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very",
+ "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view",
+ "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual",
+ "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote",
+ "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want",
+ "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave",
+ "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding",
+ "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat",
+ "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife",
+ "wild", "will", "win", "window", "wine", "wing", "wink", "winner",
+ "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman",
+ "wonder", "wood", "wool", "word", "work", "world", "worry", "worth",
+ "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year",
+ "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo",
+]);
diff --git a/mcp-server/src/lib/mnemonic-vanity.js b/mcp-server/src/lib/mnemonic-vanity.js
new file mode 100644
index 000000000..644b571d0
--- /dev/null
+++ b/mcp-server/src/lib/mnemonic-vanity.js
@@ -0,0 +1,120 @@
+// Mnemonic (BIP-39 seed phrase) vanity grinder for the `vanity_grinder` MCP
+// tool. The sibling pump-vanity.js grinds raw Ed25519 keypairs that have no
+// recovery phrase; this grinds a fresh BIP-39 mnemonic each attempt, derives the
+// Solana key at m/44'/501'/0'/0' (Phantom's default), and matches the resulting
+// address — so a hit yields an importable seed phrase, not just a private key.
+//
+// Each attempt runs PBKDF2-HMAC-SHA512 (2048 iterations) and is ~100× costlier
+// than a raw keypair, so the combined pattern is capped at 2 base58 chars and
+// the iteration budget is small. On exhaustion the grinder throws (status 504)
+// so the paid MCP tool reports isError and the caller is NOT charged.
+
+import { generateMnemonic, deriveSolanaKeypair, STRENGTH_WORD_COUNTS, DEFAULT_STRENGTH } from './mnemonic.js';
+import { BASE58_ALPHABET, estimateAttempts } from './pump-vanity.js';
+
+const BASE58_CHARS = new Set(BASE58_ALPHABET);
+
+// Combined prefix+suffix ceiling for mnemonic mode. Below the raw-keypair limit
+// of 6 because seed-phrase grinding is ~100× slower.
+export const MAX_MNEMONIC_PATTERN_LENGTH = 2;
+
+// Default / hard-cap iteration budget. At ~220 derivations/sec single-threaded,
+// 10k attempts ≈ 45s and clears a 2-char pattern (~3.4k expected) ~95% of the
+// time. The hard cap keeps a single paid call from pinning the event loop for
+// minutes.
+export const DEFAULT_MNEMONIC_MAX_ITERATIONS = 10_000;
+export const MAX_MNEMONIC_ITERATIONS_CAP = 20_000;
+const YIELD_EVERY = 200;
+
+function vanityError(code, msg, status = 400) {
+ return Object.assign(new Error(msg), { status, code });
+}
+
+function validatePattern(pattern, label) {
+ if (typeof pattern !== 'string' || pattern.length === 0) {
+ throw vanityError('invalid_vanity', `${label} must be a non-empty string`);
+ }
+ if (pattern !== pattern.trim()) {
+ throw vanityError('invalid_vanity', `${label} contains whitespace`);
+ }
+ for (let i = 0; i < pattern.length; i++) {
+ if (!BASE58_CHARS.has(pattern[i])) {
+ throw vanityError('invalid_vanity', `${label}: invalid base58 char '${pattern[i]}' at position ${i + 1}`);
+ }
+ }
+}
+
+/**
+ * Grind a Solana keypair recoverable from a BIP-39 mnemonic, whose base58
+ * address matches a prefix and/or suffix.
+ *
+ * @param {object} opts
+ * @param {string} [opts.prefix]
+ * @param {string} [opts.suffix]
+ * @param {boolean} [opts.ignoreCase=false]
+ * @param {number} [opts.strength=128] BIP-39 entropy bits (128→12 words, 256→24).
+ * @param {number} [opts.maxIterations]
+ * @returns {Promise<{ mnemonic:string, wordCount:number, derivationPath:string, keypair:import('@solana/web3.js').Keypair, iterations:number, durationMs:number }>}
+ */
+export async function grindMnemonicKeypair({
+ prefix,
+ suffix,
+ ignoreCase = false,
+ strength = DEFAULT_STRENGTH,
+ maxIterations = DEFAULT_MNEMONIC_MAX_ITERATIONS,
+} = {}) {
+ if (!prefix && !suffix) throw vanityError('invalid_vanity', 'prefix or suffix is required');
+ if (!STRENGTH_WORD_COUNTS[strength]) throw vanityError('invalid_vanity', `invalid strength ${strength} (use 128 or 256)`);
+ if (prefix) validatePattern(prefix, 'prefix');
+ if (suffix) validatePattern(suffix, 'suffix');
+
+ const combinedLength = (prefix?.length || 0) + (suffix?.length || 0);
+ if (combinedLength > MAX_MNEMONIC_PATTERN_LENGTH) {
+ throw vanityError(
+ 'invalid_vanity',
+ `combined pattern length ${combinedLength} exceeds the mnemonic-mode limit of ${MAX_MNEMONIC_PATTERN_LENGTH} ` +
+ `(seed-phrase grinding is ~100× slower) — use a shorter pattern, or drop the mnemonic option for a raw keypair`,
+ );
+ }
+
+ const cap = Math.min(Math.max(1, Math.floor(maxIterations)), MAX_MNEMONIC_ITERATIONS_CAP);
+ const targetPrefix = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : null;
+ const targetSuffix = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : null;
+ const pLen = targetPrefix?.length || 0;
+ const sLen = targetSuffix?.length || 0;
+
+ const start = Date.now();
+ for (let i = 1; i <= cap; i++) {
+ const mnemonic = generateMnemonic(strength);
+ const { keypair, derivationPath } = deriveSolanaKeypair(mnemonic);
+ const addr = keypair.publicKey.toBase58();
+
+ const head = ignoreCase ? addr.slice(0, pLen).toLowerCase() : addr.slice(0, pLen);
+ if (targetPrefix && head !== targetPrefix) {
+ if (i % YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
+ continue;
+ }
+ const tail = ignoreCase ? addr.slice(addr.length - sLen).toLowerCase() : addr.slice(addr.length - sLen);
+ if (targetSuffix && tail !== targetSuffix) {
+ if (i % YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
+ continue;
+ }
+
+ return {
+ mnemonic,
+ wordCount: STRENGTH_WORD_COUNTS[strength],
+ derivationPath,
+ keypair,
+ iterations: i,
+ durationMs: Date.now() - start,
+ };
+ }
+
+ throw vanityError(
+ 'vanity_timeout',
+ `vanity ${prefix ? `prefix '${prefix}'` : ''}${prefix && suffix ? ' + ' : ''}${suffix ? `suffix '${suffix}'` : ''} ` +
+ `not found in ${cap} mnemonic attempts (estimated ~${Math.round(estimateAttempts({ prefix, suffix, ignoreCase })).toLocaleString()}) ` +
+ `— retry, use a shorter pattern, or enable ignoreCase`,
+ 504,
+ );
+}
diff --git a/mcp-server/src/lib/mnemonic.js b/mcp-server/src/lib/mnemonic.js
new file mode 100644
index 000000000..ead1cd434
--- /dev/null
+++ b/mcp-server/src/lib/mnemonic.js
@@ -0,0 +1,198 @@
+// Vendored from the three.ws monorepo: src/solana/vanity/mnemonic.js. Kept in
+// sync by hand so this package is self-contained when published to npm. Do not
+// edit here — edit the canonical src/solana/vanity/mnemonic.js and re-copy
+// (alongside bip39-english.js).
+
+/**
+ * BIP-39 mnemonic ↔ Solana keypair derivation — zero runtime dependencies
+ * beyond Node's built-in `crypto` and `@solana/web3.js`.
+ *
+ * Why hand-rolled instead of pulling in `bip39` + `ed25519-hd-key`: this module
+ * ships inside Vercel serverless functions and a published MCP package, and we
+ * refuse to take a runtime dependency on an undeclared transitive install. Every
+ * primitive used here is a standard-library call (`pbkdf2Sync`, `createHmac`,
+ * `createHash`, `randomBytes`) plus the vendored BIP-39 wordlist, so the feature
+ * is fully self-contained and reproducible.
+ *
+ * Correctness is pinned by canonical test vectors (the BIP-39 "TREZOR" vectors
+ * and the SLIP-0010 ed25519 vectors) in test/vanity-mnemonic.test.js, and the
+ * derived address is verified byte-for-byte against `near-hd-key` so a mnemonic
+ * we emit imports into Phantom / Solflare / the Solana CLI at the exact same
+ * address. The default path is m/44'/501'/0'/0' — Phantom's first account.
+ */
+
+import { createHash, createHmac, pbkdf2Sync, randomBytes } from 'node:crypto';
+import { Keypair } from '@solana/web3.js';
+
+import { ENGLISH_WORDLIST } from './bip39-english.js';
+
+// Phantom / Solflare / Solana-CLI "derived" account path. The trailing two
+// levels are the account and change indices; index 0 is the first wallet.
+export const SOLANA_PURPOSE = 44;
+export const SOLANA_COIN_TYPE = 501;
+export const DEFAULT_DERIVATION_PATH = "m/44'/501'/0'/0'";
+
+// Supported BIP-39 entropy strengths → mnemonic word counts. 128 bits → 12
+// words (the wallet default), 256 bits → 24 words (maximum security margin).
+export const STRENGTH_WORD_COUNTS = Object.freeze({ 128: 12, 160: 15, 192: 18, 224: 21, 256: 24 });
+const VALID_STRENGTHS = Object.keys(STRENGTH_WORD_COUNTS).map(Number);
+export const DEFAULT_STRENGTH = 128;
+
+const WORD_INDEX = new Map(ENGLISH_WORDLIST.map((w, i) => [w, i]));
+
+function err(message, code = 'mnemonic_error', status = 400) {
+ return Object.assign(new Error(message), { code, status });
+}
+
+/**
+ * Encode raw entropy as a BIP-39 mnemonic. Entropy length must be one of the
+ * supported strengths (16/20/24/28/32 bytes). The checksum is the leading
+ * ENT/32 bits of SHA-256(entropy), appended before slicing into 11-bit words.
+ * @param {Uint8Array|Buffer} entropy
+ * @returns {string} space-joined mnemonic
+ */
+export function entropyToMnemonic(entropy) {
+ const bytes = Buffer.from(entropy);
+ const ENT = bytes.length * 8;
+ if (!VALID_STRENGTHS.includes(ENT)) {
+ throw err(`invalid entropy length ${bytes.length} bytes — expected one of ${VALID_STRENGTHS.map((b) => b / 8).join(', ')}`);
+ }
+ const checksumBits = ENT / 32;
+ const hash = createHash('sha256').update(bytes).digest();
+ let bits = '';
+ for (const b of bytes) bits += b.toString(2).padStart(8, '0');
+ for (const b of hash) bits += b.toString(2).padStart(8, '0');
+ bits = bits.slice(0, ENT + checksumBits);
+
+ const words = [];
+ for (let i = 0; i < bits.length; i += 11) {
+ words.push(ENGLISH_WORDLIST[parseInt(bits.slice(i, i + 11), 2)]);
+ }
+ return words.join(' ');
+}
+
+/**
+ * Generate a fresh random BIP-39 mnemonic at the requested strength (default
+ * 128-bit / 12 words). Uses the CSPRNG via `crypto.randomBytes`.
+ * @param {number} [strength=128] bits of entropy
+ * @returns {string}
+ */
+export function generateMnemonic(strength = DEFAULT_STRENGTH) {
+ if (!VALID_STRENGTHS.includes(strength)) {
+ throw err(`invalid strength ${strength} — expected one of ${VALID_STRENGTHS.join(', ')}`);
+ }
+ return entropyToMnemonic(randomBytes(strength / 8));
+}
+
+/**
+ * Validate a mnemonic: every word in the list, valid word count, and a correct
+ * BIP-39 checksum. Returns true/false (does not throw) for cheap guard use.
+ * @param {string} mnemonic
+ * @returns {boolean}
+ */
+export function validateMnemonic(mnemonic) {
+ if (typeof mnemonic !== 'string') return false;
+ const words = mnemonic.normalize('NFKD').trim().split(/\s+/);
+ if (!Object.values(STRENGTH_WORD_COUNTS).includes(words.length)) return false;
+
+ let bits = '';
+ for (const w of words) {
+ const idx = WORD_INDEX.get(w);
+ if (idx === undefined) return false;
+ bits += idx.toString(2).padStart(11, '0');
+ }
+ const dividerIndex = Math.floor(bits.length / 33) * 32;
+ const entropyBits = bits.slice(0, dividerIndex);
+ const checksumBits = bits.slice(dividerIndex);
+
+ const entropyBytes = Buffer.alloc(entropyBits.length / 8);
+ for (let i = 0; i < entropyBytes.length; i++) {
+ entropyBytes[i] = parseInt(entropyBits.slice(i * 8, i * 8 + 8), 2);
+ }
+ const hash = createHash('sha256').update(entropyBytes).digest();
+ let expected = '';
+ for (const b of hash) expected += b.toString(2).padStart(8, '0');
+ return checksumBits === expected.slice(0, checksumBits.length);
+}
+
+/**
+ * BIP-39 mnemonic → 64-byte seed via PBKDF2-HMAC-SHA512 (2048 iterations), per
+ * the standard. The optional passphrase (BIP-39 "25th word") salts the KDF.
+ * @param {string} mnemonic
+ * @param {string} [passphrase='']
+ * @returns {Buffer} 64-byte seed
+ */
+export function mnemonicToSeed(mnemonic, passphrase = '') {
+ const m = mnemonic.normalize('NFKD');
+ const salt = ('mnemonic' + passphrase).normalize('NFKD');
+ return pbkdf2Sync(Buffer.from(m, 'utf8'), Buffer.from(salt, 'utf8'), 2048, 64, 'sha512');
+}
+
+/**
+ * Parse a BIP-32 path string ("m/44'/501'/0'/0'") into an array of hardened
+ * indices. ed25519 (SLIP-0010) supports hardened derivation only, so every
+ * segment must be hardened (trailing `'` or `h`); a non-hardened segment throws.
+ * @param {string} path
+ * @returns {number[]} indices in [0, 2^31)
+ */
+export function parseDerivationPath(path) {
+ const segments = path.split('/');
+ if (segments[0] !== 'm') throw err(`invalid derivation path '${path}' — must start with 'm'`);
+ return segments.slice(1).map((seg) => {
+ const hardened = seg.endsWith("'") || seg.endsWith('h');
+ if (!hardened) {
+ throw err(`invalid derivation path '${path}' — ed25519 requires every segment hardened (e.g. 0')`);
+ }
+ const n = Number(seg.slice(0, -1));
+ if (!Number.isInteger(n) || n < 0 || n >= 0x80000000) {
+ throw err(`invalid derivation path segment '${seg}'`);
+ }
+ return n;
+ });
+}
+
+/**
+ * SLIP-0010 ed25519 key derivation. Returns the 32-byte private key (IL) at the
+ * given hardened path. Master: HMAC-SHA512("ed25519 seed", seed). Child:
+ * HMAC-SHA512(chainCode, 0x00 || key || ser32(index | 2^31)).
+ * @param {Buffer} seed 64-byte BIP-39 seed
+ * @param {number[]} indices hardened indices (without the hardening bit)
+ * @returns {Buffer} 32-byte ed25519 private key
+ */
+export function deriveEd25519PrivateKey(seed, indices) {
+ let I = createHmac('sha512', Buffer.from('ed25519 seed', 'utf8')).update(seed).digest();
+ let key = I.subarray(0, 32);
+ let chainCode = I.subarray(32);
+ for (const index of indices) {
+ const hardened = (index | 0x80000000) >>> 0;
+ const data = Buffer.concat([
+ Buffer.from([0]),
+ key,
+ Buffer.from([(hardened >>> 24) & 0xff, (hardened >>> 16) & 0xff, (hardened >>> 8) & 0xff, hardened & 0xff]),
+ ]);
+ I = createHmac('sha512', chainCode).update(data).digest();
+ key = I.subarray(0, 32);
+ chainCode = I.subarray(32);
+ }
+ return Buffer.from(key);
+}
+
+/**
+ * Full pipeline: mnemonic → Solana Keypair at the given BIP-44 path. The
+ * returned Keypair's `secretKey` is the standard 64-byte Ed25519 form that
+ * Phantom / Solflare / `solana-keygen` import directly.
+ * @param {string} mnemonic
+ * @param {object} [opts]
+ * @param {number} [opts.account=0] account index (the 3rd path level)
+ * @param {number} [opts.change=0] change index (the 4th path level)
+ * @param {string} [opts.passphrase=''] BIP-39 passphrase
+ * @returns {{ keypair: Keypair, derivationPath: string }}
+ */
+export function deriveSolanaKeypair(mnemonic, opts = {}) {
+ const account = opts.account ?? 0;
+ const change = opts.change ?? 0;
+ const derivationPath = `m/${SOLANA_PURPOSE}'/${SOLANA_COIN_TYPE}'/${account}'/${change}'`;
+ const seed = mnemonicToSeed(mnemonic, opts.passphrase || '');
+ const priv = deriveEd25519PrivateKey(seed, parseDerivationPath(derivationPath));
+ return { keypair: Keypair.fromSeed(priv), derivationPath };
+}
diff --git a/mcp-server/src/tools/vanity-grinder.js b/mcp-server/src/tools/vanity-grinder.js
index cb74256c8..f03ec38d7 100644
--- a/mcp-server/src/tools/vanity-grinder.js
+++ b/mcp-server/src/tools/vanity-grinder.js
@@ -21,6 +21,7 @@ import { z } from 'zod';
import { paid } from '../payments.js';
import { jsonSchemaFromZod } from './_shared.js';
import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../lib/pump-vanity.js';
+import { grindMnemonicKeypair, MAX_MNEMONIC_PATTERN_LENGTH } from '../lib/mnemonic-vanity.js';
import bs58 from 'bs58';
const TOOL_NAME = 'vanity_grinder';
@@ -45,10 +46,13 @@ const DEFAULT_MAX_ITERATIONS = 1_500_000;
const DIFFICULTY_REJECT_MULTIPLE = 4;
const TOOL_DESCRIPTION =
- `Generate a Solana keypair whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). ` +
- `SECURITY: the returned \`privateKey64\` is a REAL, fully-funded-capable private key. It transits the MCP channel in plaintext, ` +
+ `Generate a Solana wallet whose base58 address starts with a chosen prefix (and optionally ends with a chosen suffix). ` +
+ `Set \`mnemonic: true\` to receive a BIP-39 SEED PHRASE (12 or 24 words) whose derived key at m/44'/501'/0'/0' lands on the ` +
+ `vanity address — importable as a recovery phrase into Phantom/Solflare/the Solana CLI (combined pattern capped at ` +
+ `${MAX_MNEMONIC_PATTERN_LENGTH} chars, ~100× slower to grind). Otherwise a raw 64-byte private key is returned. ` +
+ `SECURITY: the returned \`privateKey64\`/\`mnemonic\` is a REAL, fully-funded-capable secret. It transits the MCP channel in plaintext, ` +
`so the MCP host (Claude Desktop, Cursor, any proxy) MAY LOG the entire response. Treat the whole tool result as a secret, ` +
- `import it into a wallet immediately, and never reuse a key that may have been logged. ` +
+ `import it into a wallet immediately, and never reuse a secret that may have been logged. ` +
`Billed via x402 \`exact\` (flat ${PRICE_USD} USDC on Solana).`;
// Single source of truth: Zod shape carries descriptions + bounds; JSON Schema
@@ -69,6 +73,17 @@ const inputZodShape = {
.describe('Optional base58 suffix the address must end with. 1-6 chars.')
.optional(),
ignoreCase: z.boolean().describe('Case-insensitive match (folds upper+lower base58 chars).').optional(),
+ mnemonic: z
+ .boolean()
+ .describe(
+ `Return a BIP-39 seed phrase (importable as a recovery phrase) instead of a raw private key. ` +
+ `~100× slower; combined prefix+suffix capped at ${MAX_MNEMONIC_PATTERN_LENGTH} chars in this mode.`,
+ )
+ .optional(),
+ strength: z
+ .union([z.literal(128), z.literal(256)])
+ .describe('Mnemonic mode only: entropy bits — 128 → 12 words (default), 256 → 24 words.')
+ .optional(),
maxIterations: z
.number()
.int()
@@ -119,7 +134,36 @@ export async function buildVanityGrinderTool() {
priceUsd: PRICE_USD,
},
},
- async ({ prefix, suffix, ignoreCase = false, maxIterations = DEFAULT_MAX_ITERATIONS }) => {
+ async ({ prefix, suffix, ignoreCase = false, mnemonic = false, strength = 128, maxIterations = DEFAULT_MAX_ITERATIONS }) => {
+ // Mnemonic mode: grind a BIP-39 seed phrase whose derived key lands on
+ // the vanity address. The grinder enforces its own (lower) pattern cap
+ // and iteration budget and throws on exhaustion so the caller isn't
+ // charged. Returns the phrase plus the derived 64-byte secret key.
+ if (mnemonic) {
+ const grind = await grindMnemonicKeypair({ prefix, suffix, ignoreCase, strength });
+ const address = grind.keypair.publicKey.toBase58();
+ const privateKey64 = bs58.encode(Buffer.from(grind.keypair.secretKey));
+ return {
+ address,
+ mnemonic: grind.mnemonic,
+ wordCount: grind.wordCount,
+ derivationPath: grind.derivationPath,
+ privateKey64,
+ iterations: grind.iterations,
+ estimatedIterations: Math.round(estimateAttempts({ prefix, suffix, ignoreCase })),
+ durationMs: grind.durationMs,
+ prefix,
+ suffix: suffix || null,
+ ignoreCase,
+ format: 'mnemonic',
+ priceUsd: PRICE_USD,
+ _secretWarning:
+ 'mnemonic and privateKey64 are a REAL Solana seed phrase and key. They just transited the MCP channel ' +
+ 'in plaintext, so the MCP host (Claude Desktop / Cursor / any proxy) MAY have logged this entire response. ' +
+ 'Import the phrase into a wallet now, treat the whole result as a secret, and do not reuse a secret you suspect was logged.',
+ };
+ }
+
// Clamp the caller-supplied cap into the safe range so a single paid
// call can never schedule millions of synchronous keypair generations.
const cap = Math.min(Math.max(1, Math.floor(maxIterations)), MAX_ITERATIONS_CAP);
@@ -153,6 +197,7 @@ export async function buildVanityGrinderTool() {
prefix,
suffix: suffix || null,
ignoreCase,
+ format: 'keypair',
priceUsd: PRICE_USD,
_secretWarning:
'privateKey64 is a REAL Solana private key. It just transited the MCP channel in plaintext, ' +
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 0dc8c3b0c..db4787261 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -448,16 +448,7 @@
<span class="ad-bullet"></span>
<h2>AGENT HOLDINGS</h2>
</div>
- <div class="ad-row">
- <span class="ad-mono" id="ad-holdings-addr"></span>
- <button
- class="ad-copy"
- data-copy-target="ad-holdings-addr"
- aria-label="Copy"
- >
- ⧉
- </button>
- </div>
+ <div class="ad-row" id="ad-holdings-chip"></div>
<div class="ad-balance"><span id="ad-holdings-sol">0</span> SOL</div>
<div class="flex space-x-2 mt-4 justify-start" id="ad-holdings-actions"></div>
</section>
diff --git a/pages/trending.html b/pages/trending.html
index c029f98c8..6521888ef 100644
--- a/pages/trending.html
+++ b/pages/trending.html
@@ -272,7 +272,7 @@
</style>
<script type="module">
- import { walletChipHTML } from '/src/shared/agent-wallet-chip.js';
+ import { walletChipHTML, wireWalletChips } from '/src/shared/agent-wallet-chip.js';
const $ = (s) => document.querySelector(s);
const $$ = (s) => document.querySelectorAll(s);
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
@@ -375,6 +375,11 @@
</${tag}>
</li>`;
}).join('');
+
+ // Wire the wallet chips' copy + Tip actions on the public feed. Viewers
+ // don't own these agents, so walletChipHTML defaults to isOwner:false and
+ // renders the ◎ Tip action — this hooks it up.
+ wireWalletChips(list);
}
// ── Render coins ────────────────────────────────────────────────────
diff --git a/prompts/agent-studio/00-README-orchestration.md b/prompts/agent-studio/00-README-orchestration.md
new file mode 100644
index 000000000..458a590ab
--- /dev/null
+++ b/prompts/agent-studio/00-README-orchestration.md
@@ -0,0 +1,137 @@
+# Agent Studio — Orchestration Index
+
+This directory contains self-contained task prompts. Each `.md` is meant to be pasted
+into its own agent chat. Each agent works in this shared worktree and must follow
+`CLAUDE.md` exactly. **When an agent finishes its task (and its self-improvement pass),
+it deletes its own prompt file.** When this directory is empty, the initiative is done.
+
+---
+
+## The vision (read this first — every agent must internalize it)
+
+We are building **Agent Studio**: one central command center where a user completely
+authors their 3D agent — its **brain** (LLM + memory + reasoning), its **money** (wallet
++ trading behavior), its **body** (avatar, outfits, animations), and its **skills**.
+
+Two non-negotiable product principles drive everything:
+
+1. **Everything is visual.** No hidden text-field config screens. The agent's brain is a
+ thing you *see and wire*. Memory is a thing you *watch form*. A trade rule is a thing
+ you *draw*. If a feature can be expressed as a manipulable visual object, it must be.
+
+2. **The avatar is always present.** The user's 3D agent is rendered live on **every page**
+ of the platform, reacting to what's happening (a pumping coin, a filled snipe, an
+ incoming DM). Editing the agent in Studio updates that live presence **instantly,
+ everywhere** — no save-and-refresh.
+
+Why this is gamechanging for crypto: today, sniping/trading/launching tools are dashboards
+of numbers. We make the trader a *character with a programmable brain and a memory of every
+trade* that lives alongside you. You don't configure a bot in a YAML file — you raise an
+agent, dress it, teach it, fund it, and watch it work. That is a product nobody else has.
+
+**Bar:** Vercel / Linear / Stripe / Figma quality. If you wouldn't screenshot it, raise it.
+
+---
+
+## The product map (what we're building)
+
+```
+/studio ──────────────────────────────────────────────────────────────────┐
+│ PERSISTENT LIVE 3D AVATAR (left/stage) │ EDITING SURFACE (right/tabs) │
+│ - the same agent the user sees site-wide │ ┌─────────────────────────┐ │
+│ - reacts live to every edit │ │ Brain (P1) │ │
+│ - emotes, lip-syncs, poses │ │ Memory (P2) │ │
+│ │ │ Body (P3) │ │
+│ │ │ Money (P4) │ │
+│ │ │ Skills (P1/P4) │ │
+│ │ └─────────────────────────┘ │
+└───────────────────────────────────────────────────────────────────────────┘
+ ▲ the SAME avatar presence renders on every other page (P5)
+```
+
+---
+
+## Run order & dependencies
+
+**P0 must merge first.** It defines the shell, the shared state store, the global presence
+component, and the schema/API contract everything else binds to. P1–P5 can then run in
+**parallel** because each owns a distinct set of files (see collision map).
+
+| Prompt | Task | Depends on | Can parallelize with |
+|---|---|---|---|
+| `01-foundation.md` (P0) | Studio shell, route, `AgentStudioStore`, `<agent-presence>` element, schema migration, API contract | — | run alone first |
+| `02-brain-studio.md` (P1) | Visual programmable **brain graph** + model routing | P0 | P2,P3,P4,P5 |
+| `03-memory-studio.md` (P2) | Tiered **memory** (working/recall/archival), visual timeline + graph, trade-aware | P0 | P1,P3,P4,P5 |
+| `04-wardrobe-studio.md` (P3) | **Body**: outfits, wearables, animations, live preview | P0 | P1,P2,P4,P5 |
+| `05-wallet-trading-brain.md` (P4) | **Money**: wallet + visual **sniping/trading rules** wired to real Solana | P0 | P1,P2,P3,P5 |
+| `06-living-presence.md` (P5) | Avatar on **every page**, reactive to live market/trade events | P0 | P1,P2,P3,P4 |
+
+If you want maximum speed: run P0 to completion, then launch P1–P5 as five concurrent agents.
+
+---
+
+## Shared contract (P0 owns these; everyone else consumes them)
+
+P0 publishes a single client module `src/studio/agent-studio-store.js` exporting a reactive
+store. Treat this as the integration seam — do not reach around it.
+
+```js
+import { studio } from '/src/studio/agent-studio-store.js'
+
+studio.agent // current AgentIdentity (live, reactive)
+studio.subscribe(fn) // fn(agent) on any change; returns unsubscribe
+studio.patch(partial) // optimistic local update + debounced PUT /api/agents/:id
+studio.commit() // force-flush pending writes now
+studio.on(event, fn) // 'brain:change' | 'memory:change' | 'body:change' | 'wallet:change'
+studio.emitMarket(evt) // P4/P5: broadcast a live market/trade event to the presence layer
+studio.preview(partial) // ephemeral, non-persisted preview (hover a hat → see it; don't save)
+```
+
+And one custom element, mountable anywhere on any page:
+
+```html
+<agent-presence data-agent-id="…" data-mode="stage|companion|mini"></agent-presence>
+```
+
+It renders the user's live avatar, subscribes to `studio`, and reacts to market events.
+P5 places it across the site; P1–P4 only need to know their edits flow through `studio`
+and the presence updates for free.
+
+---
+
+## Hard rules for every agent (these override defaults — see CLAUDE.md)
+
+- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** Wire 100% to real APIs
+ (`api/agents.js`, `api/agent-memory.js`, `api/chat.js`, `api/brain/chat.js`, the coin/wallet
+ endpoints, Solana RPC, pump.fun). If a credential is missing, find it in `.env` / `vercel env`.
+- **The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never name,
+ hardcode, or recommend any other coin anywhere. Runtime-supplied mints (user launches,
+ launch directories) are the only mechanical exceptions.
+- **Use the design tokens** in `public/tokens.css` — no hardcoded colors/spacing/fonts.
+- **Every state designed:** loading (skeletons), empty (tells user what to do), error
+ (actionable), populated, overflow. Hover/active/focus on every interactive element.
+- **Concurrency:** other agents edit `main` in this worktree simultaneously. Stage **explicit
+ paths only** (never `git add -A`). Re-run `git status` + `git diff --staged` before committing.
+ Stay inside your file-ownership lane (below). If you must touch a shared file, append; don't rewrite.
+- **Changelog:** append a holder-readable entry to `data/changelog.json` for the user-visible change.
+- **Verify for real:** `npm run dev` (port 3000), exercise in a browser, check the network tab
+ shows real calls with real data, zero console errors. `npm test` still passes.
+- **Then improve, then delete this prompt.** After done: do a self-review pass (the five checks
+ in CLAUDE.md), find the single biggest quality gap, fix it, then `rm` your prompt file and
+ report what you shipped.
+
+---
+
+## File-ownership map (avoid collisions)
+
+- **P0:** `src/studio/agent-studio-store.js`, `src/studio/studio-shell.js`, `pages/studio.html`,
+ `src/studio/agent-presence.js` (the custom element), `api/_lib/migrations/*_agent_studio.sql`,
+ `data/pages.json` (one entry).
+- **P1:** `src/studio/brain/**`, `api/brain/**` (extend), `api/agents.js` (brain config fields only — append).
+- **P2:** `src/studio/memory/**`, `api/agent-memory.js` (extend), new `api/memory/**`.
+- **P3:** `src/studio/body/**`, builds on `src/avatar-wardrobe.js`, `src/animation-*.js` (consume, don't rewrite).
+- **P4:** `src/studio/money/**`, `api/coin/**` (extend), new `api/trading/**`, `api/_lib/agent-wallet.js` (extend).
+- **P5:** mounts `<agent-presence>` across `pages/*.html` + their `src/*.js` entry points; `src/presence/**`.
+
+Shared files touched by multiple prompts (`data/pages.json`, `data/changelog.json`, `api/agents.js`):
+**append only**, never reformat, and re-check `git diff --staged` right before commit.
diff --git a/prompts/agent-studio/01-foundation.md b/prompts/agent-studio/01-foundation.md
new file mode 100644
index 000000000..5007c8e5b
--- /dev/null
+++ b/prompts/agent-studio/01-foundation.md
@@ -0,0 +1,107 @@
+# P0 — Agent Studio Foundation (shell · store · global presence)
+
+You are a senior engineer + product thinker building **three.ws**, a platform meant to
+compete with the best in the world. Read `CLAUDE.md` and `STRUCTURE.md` before writing
+anything. Your work here is the **foundation** that five other agents build on — they
+depend on the contracts you publish, so get the seams right.
+
+## The vision you are enabling
+
+Agent Studio is the **one central place** where a user authors their entire 3D agent — its
+brain, memory, money, body, and skills — and the avatar they edit is rendered **live on
+every page of the platform**, reacting to real events. Editing in Studio updates that
+presence **instantly, everywhere**, with no save/refresh. You are building the skeleton and
+nervous system that makes both of those true. Everything must be **visual** and real.
+
+## Your mission
+
+Ship four things, fully wired, no stubs:
+
+### 1. The Studio route + shell — `/studio`
+- New page `pages/studio.html` + entry `src/studio/studio-shell.js`. Add one entry to
+ `data/pages.json` (auth-required, indexable false). Wire it into nav where agents live.
+- Layout: a **persistent live 3D avatar stage** on one side (reuse the existing `Viewer` from
+ `src/viewer.js` and `src/agent-avatar.js` — do not fork rendering), and a **tabbed editing
+ surface** on the other with tabs: **Brain · Memory · Body · Money · Skills**. You build the
+ shell + empty tab containers with designed empty states; P1–P5 fill the tabs by mounting
+ into the containers you expose. Document the mount points clearly in code.
+- Responsive: at 320px the avatar collapses to a sticky mini-stage; at 1440px it's a full
+ cinematic stage. Keyboard: number keys switch tabs, `Esc` closes panels, focus rings everywhere.
+- Loads the caller's agent via `GET /api/agents/me` (auto-creates a default agent — see
+ `api/agents.js`). Handles: no agent yet (onboarding CTA), load error (retry), loading (skeleton).
+
+### 2. The shared reactive store — `src/studio/agent-studio-store.js`
+This is the integration seam every other agent uses. Build on the existing `src/agent-identity.js`
+(`AgentIdentity` with `load/save/update`) — wrap it, don't replace it. Export a singleton `studio`:
+
+```js
+studio.agent // live AgentIdentity
+studio.subscribe(fn) // fn(agent); returns unsubscribe
+studio.patch(partial) // optimistic local merge + debounced PUT /api/agents/:id (real call)
+studio.commit() // flush pending writes immediately; returns Promise
+studio.on(event, fn) // 'brain:change'|'memory:change'|'body:change'|'wallet:change'|'skills:change'
+studio.emit(event, data)// other studios call this after they mutate their domain
+studio.preview(partial) // ephemeral preview — applies to live avatar WITHOUT persisting
+studio.clearPreview()
+studio.emitMarket(evt) // broadcast { type, mint, ... } market/trade events to presence listeners
+studio.onMarket(fn)
+```
+Requirements: optimistic updates with rollback on failed PUT; debounce (~600ms) but flush on
+tab change / page unload (`visibilitychange` + `beforeunload`); CSRF token handling consistent
+with the existing pattern (see commit `1416805fc` and how `agent-wallet-chip.js` / wallet routes
+do CSRF); conflict-safe (if PUT returns a newer `updated_at`, reconcile, don't clobber).
+
+### 3. The global presence element — `src/studio/agent-presence.js`
+A framework-agnostic **custom element** `<agent-presence>` that any page can drop in:
+
+```html
+<agent-presence data-agent-id="…" data-mode="stage|companion|mini"></agent-presence>
+```
+- Renders the user's live avatar using the shared `Viewer` + `agent-avatar.js` (emotion blend,
+ idle loop from `src/idle-animation.js`, lip-sync already exist — wire them, don't reinvent).
+- Subscribes to `studio` so any edit anywhere reflects immediately.
+- `mode="mini"` = a small floating companion (bottom-corner, draggable, remembers position);
+ `companion` = sidebar size; `stage` = full studio stage.
+- Subscribes to `studio.onMarket(...)` and maps event types to avatar reactions via the existing
+ emotion system (e.g. `snipe:filled` → celebration, `position:down` → concern). Define a clean
+ `reactTo(event)` API; P4/P5 will emit the events. Ship sensible default mappings now.
+- **Performance is critical** since this renders on every page: share a single WebGL context where
+ possible, pause rendering when offscreen/tab hidden (`IntersectionObserver` + `visibilitychange`),
+ cap DPR, lazy-load the heavy Three.js modules. The mini companion must never jank scrolling.
+
+### 4. Schema + API contract
+- Migration `api/_lib/migrations/*_agent_studio.sql`: extend `agent_identities.meta` (jsonb) with a
+ documented `studio` sub-object that namespaces what P1–P5 store: `brain` (model/provider/graph),
+ `body` (outfit/animation refs), `trading` (rules), plus a top-level `studio_version`. Don't break
+ existing columns; additive only. Add indexes only if you add queryable columns.
+- Extend `PUT /api/agents/:id` in `api/agents.js` to accept and persist the `meta.studio` bag with
+ validation (reject unknown top-level keys, size-limit the jsonb). Keep owner-only enforcement.
+- Document the exact accepted shape in a header comment so P1–P5 bind to a stable contract.
+
+## Libraries you may adopt (research-backed)
+- Keep the main app **vanilla JS** (it is today). The custom element approach avoids dragging React
+ into every page. If a sub-studio later wants React, it mounts as an island — your store/presence
+ must stay framework-agnostic so both work.
+- Reuse what exists before adding deps: `src/viewer.js`, `src/agent-avatar.js`, `src/animation-manager.js`,
+ `src/idle-animation.js`, `src/agent-identity.js`, `public/tokens.css`.
+
+## Definition of done
+- `/studio` loads the real agent, shows the live avatar, tabs switch, empty states are designed.
+- Editing a field (even a temporary debug control you then remove) flows through `studio.patch`,
+ hits the real `PUT`, and the avatar/presence updates with no refresh.
+- `<agent-presence>` works standalone on a throwaway test page in all three modes with real data.
+- No console errors/warnings; `npm test` passes; network tab shows real calls.
+- Reviewed `git diff` line-by-line. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs. $THREE is the only coin. Design tokens only. Stage explicit paths
+(never `git add -A`); re-check `git status`/`git diff --staged` before commit — other agents are
+editing `main` concurrently. Append-only on `data/pages.json` / `data/changelog.json`.
+
+## When finished
+Run the self-review (the five checks in CLAUDE.md). Then make a final integration check: write a
+1-paragraph "Integration notes for P1–P5" as a comment block at the top of
+`src/studio/agent-studio-store.js` so downstream agents bind correctly. Find the single biggest
+quality gap in what you shipped and fix it. Then **delete this prompt file**
+(`prompts/agent-studio/01-foundation.md`) and report exactly what you shipped + the final
+store/presence API surface.
diff --git a/prompts/agent-studio/02-brain-studio.md b/prompts/agent-studio/02-brain-studio.md
new file mode 100644
index 000000000..2bf7ddc54
--- /dev/null
+++ b/prompts/agent-studio/02-brain-studio.md
@@ -0,0 +1,84 @@
+# P1 — Brain Studio (the visual, programmable agent brain)
+
+You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
+`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged — the Studio shell,
+`src/studio/agent-studio-store.js`, and `<agent-presence>` exist. Read the "Integration notes for
+P1–P5" comment at the top of the store before you start. Mount into the **Brain** and **Skills**
+tab containers the shell exposes.
+
+## The vision you are enabling
+
+Today an agent's "brain" is a single `persona_prompt` text column. That's invisible config — the
+opposite of our product principle. You will make the brain a **thing the user sees and wires**: a
+visual, programmable graph where persona, model choice, memory access, skills, and **trading
+reasoning** are nodes connected into a living circuit. The user doesn't fill in a textarea — they
+*build a mind*, watch it light up as it thinks, and immediately see their avatar's behavior change.
+
+This is the centerpiece of "everything is visual." Make it gamechanging.
+
+## Your mission
+
+### 1. The Brain Graph — a visual node editor for the agent's mind
+Build a node-graph editor in the Brain tab. Nodes the user can place, connect, and configure:
+- **Persona / Identity** (tone, role, risk appetite — feeds the system prompt)
+- **Model** node(s): choose the LLM that powers a branch. Wire to the **real** multi-provider proxies
+ that already exist (`api/chat.js`, `api/brain/chat.js`, the widget `brainProvider`/`brainModel`
+ config in `api/widgets/[id]/[action].js`). Default to the latest Claude models (see `CLAUDE.md`
+ env notes / the claude-api skill) but support the providers already wired (Anthropic, OpenAI,
+ IBM watsonx Granite, etc.). Show real per-node latency + token stats like `pages/brain.html` does.
+- **Memory** node: a port that reads/writes the agent's memory (P2 owns the memory store; you expose
+ the node + call `api/agent-memory.js`). Coordinate via the `studio` contract, not direct coupling.
+- **Skill** nodes: each enabled skill (from `agent_identities.skills[]`, licensed via
+ `api/skills/` + `api/_lib/skill-license-onchain.js`) becomes a node the brain can invoke.
+- **Trading / Reasoning** nodes: conditionals and tools the brain uses to reason about markets
+ (P4 owns execution; you own the *reasoning wiring* — e.g. "if watchlist coin breaks level → ask
+ brain → propose action"). Define the node interface; P4 fills execution. The only coin promoted
+ is `$THREE`; market nodes operate on runtime-supplied mints only.
+- **Output** node: drives the avatar (text → speech → emotion via the existing `agent-avatar.js`
+ emotion blend + lip-sync). When the brain "thinks," the avatar in the stage reacts live.
+
+Serialize the graph into `meta.studio.brain` (the contract P0 defined). The graph IS the persona —
+compile it down to the real `persona_prompt` + tool config the chat endpoints consume, so existing
+chat surfaces keep working. Round-trip must be lossless.
+
+### 2. Live "thinking" visualization
+When the agent runs (test-chat inside the studio, or a real event), **animate the active path**
+through the graph — tokens streaming, which memory was recalled, which skill fired, which model
+answered. The user literally watches their agent think. This is the screenshot moment.
+
+### 3. Test harness in-panel
+A real chat box that runs the current graph against the **real** LLM proxies with the user's actual
+agent + memory, streaming responses, and driving the live avatar. No fake responses, ever.
+
+## Libraries to adopt (research-backed — pick and justify)
+- Node-graph rendering: **Rete.js v2** (framework-agnostic, vanilla-friendly, dataflow + control-flow
+ engines, plugin system) is the best fit for the vanilla main app. **litegraph.js** is a lighter
+ canvas alternative. **React Flow** is excellent *if* you mount the Brain tab as a React island —
+ only do that if it doesn't compromise P0's framework-agnostic seams or load cost. Pick one, justify
+ it in a code comment, keep the saved graph format your own (don't leak the lib's schema into the DB).
+- Sources: React Flow https://reactflow.dev , Rete.js https://retejs.org , litegraph.js
+ https://github.com/jagenjo/litegraph.js , awesome-node-based-uis https://github.com/xyflow/awesome-node-based-uis
+- Memory framework concepts to mirror in the Memory node (P2 implements storage): **Letta/MemGPT**
+ tiered memory and **mem0** add()/search() ergonomics — see https://github.com/mem0ai/mem0 and
+ https://github.com/letta-ai/letta . Don't add a heavy backend dep without cause; mirror the *UX*.
+
+## Definition of done
+- User can build/edit/save a brain graph; it persists to `meta.studio.brain` and round-trips losslessly.
+- Test chat runs against **real** LLM proxies with **real** memory; avatar reacts live via `studio`.
+- Active-path animation works during a run. Model nodes show real latency/token stats.
+- Existing chat surfaces still work (graph compiles to a valid persona/tool config).
+- All states designed (empty graph onboarding, single node, huge graph, model error, rate limit).
+- No console errors; `npm test` passes; network tab shows real provider calls. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs/fake responses. $THREE is the only coin promoted; market nodes use runtime
+mints only. Design tokens only. Stage explicit paths (never `git add -A`); re-check
+`git diff --staged` before commit — concurrent agents share this worktree. Touch `api/agents.js`
+only to append brain-config handling; coordinate the memory port with P2 via the `studio` contract.
+
+## When finished
+Self-review (CLAUDE.md's five checks). Then push the innovation further: add the one thing that
+makes someone share this — e.g. a "brain template" gallery (Sniper, Scalper, Researcher) users can
+fork, or a diff view showing how a graph edit changes behavior. Build it. Then **delete this prompt
+file** (`prompts/agent-studio/02-brain-studio.md`) and report what you shipped + the graph format
+and the node interface P4 should target.
diff --git a/prompts/agent-studio/03-memory-studio.md b/prompts/agent-studio/03-memory-studio.md
new file mode 100644
index 000000000..2317f728e
--- /dev/null
+++ b/prompts/agent-studio/03-memory-studio.md
@@ -0,0 +1,76 @@
+# P2 — Memory Studio (LLM memory you can watch form, edit, and trust)
+
+You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
+`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged. Read the "Integration
+notes for P1–P5" at the top of `src/studio/agent-studio-store.js`. Mount into the **Memory** tab.
+Coordinate with P1 (the Brain's Memory node reads/writes through your store) via the `studio` contract.
+
+## The vision you are enabling
+
+Memory is the difference between a chatbot and a companion that *knows you*. Today we have
+`api/agent-memory.js`, the `agent_memories` table (`id, agent_id, type, content, tags, salience`),
+and `src/memory-seed.js` (synthesizes identity from GitHub/X/Farcaster connectors). That's a
+foundation — but memory is currently invisible. Per our product principle, memory must be a **visual
+thing the user watches form, curates, and trusts.** And for our domain it must be **trade-aware**:
+the agent remembers every snipe, win, loss, watchlist, and rule, and surfaces them at the right moment.
+
+This is what makes our agent feel alive across sessions. No other crypto tool has a trader with a memory you can see.
+
+## Your mission
+
+### 1. Tiered memory architecture (adopt the proven model)
+Mirror **Letta/MemGPT**'s tiers and **mem0**'s ergonomics — implement real storage, don't bolt on a
+heavy vendor unless justified:
+- **Working memory** — the small, always-in-context core (who the user is, current goals, active
+ positions). Editable, pinned, token-budgeted.
+- **Recall memory** — recent interactions/trades, searchable.
+- **Archival memory** — long-term store with semantic search (embeddings). Use a real embedding
+ provider already available in the worker proxies; store vectors in Postgres (pgvector if present —
+ check `api/_lib/schema.sql`; add the extension/migration if not). No fake similarity.
+- Implement `add()` on events and `search()` before responses (the mem0 pattern) so P1's Brain
+ Memory node can recall relevant memories into context for real. Salience/decay so the core stays small.
+
+### 2. Visual memory surfaces (the product principle)
+- **Memory Timeline** — a live, scrollable stream of memories forming over time (trades, chats,
+ learned preferences), each with type, salience, source, and tags. Animate new memories landing.
+- **Memory Graph** — entities and relationships (coins, wallets, people, strategies) as a graph the
+ user can explore. (Zep/Graphiti-style temporal knowledge graph is the inspiration — see sources.)
+- **Curate:** pin to working memory, edit, merge duplicates, adjust salience, and **forget** (with
+ confirm). Show exactly what's in-context right now and the token budget — transparency builds trust.
+- **Trade-aware views:** "What does my agent remember about <mint>?", "Show my agent's lessons from
+ losing trades," "Rules my agent follows." These pull from real trade history (coordinate with P4).
+
+### 3. Live wiring
+- New/extended endpoints under `api/agent-memory.js` and new `api/memory/**` for search, tiering,
+ embeddings, graph edges. Real auth (owner-only), real CSRF (match the existing pattern).
+- Every memory write/edit flows so the Brain and the live avatar can react (`studio.emit('memory:change')`).
+- Hook `src/memory-seed.js` connectors into the timeline so first-run memory has real substance.
+
+## Libraries / concepts to adopt (research-backed)
+- **mem0** (add/search ergonomics, hybrid vector+graph+kv) — https://github.com/mem0ai/mem0
+- **Letta / MemGPT** (tiered working/recall/archival, self-paging) — https://github.com/letta-ai/letta
+- **Zep / Graphiti** (temporal knowledge graph for facts that change over time — best-in-class on
+ LongMemEval) — https://github.com/getzep/graphiti
+- Embeddings/vectors: prefer Postgres + pgvector over a new external service. Reuse worker proxies
+ for the embedding model. Don't add a vendor SDK unless it earns its weight — mirror the patterns.
+
+## Definition of done
+- Real tiered memory with real embeddings + semantic search (no fake similarity, no sample arrays).
+- Timeline + graph render real memories; pin/edit/merge/forget/salience all persist via real APIs.
+- Brain's Memory node (P1) can `search()` and pull real memories into context.
+- "In-context now" + token budget visible. Trade-aware queries return real data.
+- All states designed (no memories yet → explain + offer connector seeding; thousands → virtualized).
+- No console errors; `npm test` passes; network tab shows real calls. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs/fake similarity/sample arrays. $THREE is the only coin promoted; trade memories
+reference runtime mints only. Design tokens only. Stage explicit paths (never `git add -A`); re-check
+`git diff --staged` before commit. Own `src/studio/memory/**`, `api/memory/**`, and extensions to
+`api/agent-memory.js`; coordinate the memory port with P1 and trade history with P4 via `studio`.
+
+## When finished
+Self-review (CLAUDE.md's five checks). Then push it: add the one delightful thing — e.g. a "memory
+replay" that shows how the agent's understanding of a coin evolved over time, or proactive "your
+agent learned X" nudges. Build it. Then **delete this prompt file**
+(`prompts/agent-studio/03-memory-studio.md`) and report what you shipped + the memory API surface
+P1/P4 should use.
diff --git a/prompts/agent-studio/04-wardrobe-studio.md b/prompts/agent-studio/04-wardrobe-studio.md
new file mode 100644
index 000000000..28afd1785
--- /dev/null
+++ b/prompts/agent-studio/04-wardrobe-studio.md
@@ -0,0 +1,72 @@
+# P3 — Body Studio (avatar, outfits, wearables, animations — live preview)
+
+You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
+`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged. Read the "Integration
+notes for P1–P5" at the top of `src/studio/agent-studio-store.js`. Mount into the **Body** tab.
+Your edits must reflect on the persistent stage avatar **and** the site-wide `<agent-presence>` instantly.
+
+## The vision you are enabling
+
+The agent has a brain (P1) and a memory (P2) — now give it a **body the user loves to dress and
+animate**, all visual, all live. We already have strong primitives: `src/avatar-wardrobe.js`
+(outfits/accessories), `src/agent-accessories.js` (bone-attached items), `pages/compose.html`
+(forge items from text, attach to bones), the animation system (`src/animation-manager.js`,
+`src/animation-presets.js`, `src/runtime/animation-slots.js`, `public/animations/*.glb`), the pose
+studio (`pages/pose.html`), `src/idle-animation.js`, and the `Viewer` (`src/viewer.js`). Plus the
+M3-org **CharacterStudio** fork (`character-studio/`) and the `@three-ws/avatar` SDK (`avatar-sdk/`).
+
+Your job: bring all of this into the **one central place** as the Body tab, with a wardrobe/animation
+experience that feels like Figma-grade direct manipulation — and make every change preview live on
+the agent that's standing right there and everywhere else on the site.
+
+## Your mission
+
+### 1. Wardrobe — outfits & wearables
+- A visual wardrobe: browse owned/available wearables from `public/accessories/` and the real asset
+ catalog, drag onto the avatar, snap to bones (build on `src/agent-accessories.js` /
+ `src/avatar-wardrobe.js` — consume them, don't rewrite). Layering, color/material tweaks via the
+ existing material traversal in `src/viewer/internal.js`.
+- Save outfits as named sets to `meta.studio.body` (P0 contract). Switching outfits updates the live
+ avatar + presence with no refresh, via `studio.patch` / `studio.emit('body:change')`.
+- **Live preview without commit:** hovering a wearable calls `studio.preview(...)` so the user sees it
+ on the real avatar before saving; leaving reverts. No persisted writes on hover.
+
+### 2. Animations & expression
+- An animation library panel (build on `src/animation-library.js` / `src/widgets/animation-gallery.js`):
+ assign clips to slots (idle/greet/celebrate/think/alert — align names with
+ `src/runtime/animation-slots.js`). Preview on the live avatar; crossfade via `animation-manager.js`.
+- Let the user set which animation plays on which **event** (e.g. `snipe:filled` → celebrate). These
+ event→animation mappings feed P5's presence reactions — define the mapping in `meta.studio.body` and
+ emit it through `studio` so the presence layer uses real choices, not hardcoded defaults.
+
+### 3. Standards & interop (research-backed)
+- Evaluate adopting **VRM** as the interoperable body format via **@pixiv/three-vrm**
+ (https://github.com/pixiv/three-vrm) so avatars/wearables are portable — we already validate
+ on-chain avatar manifests (`packages/avatar-schema/`) and fork CharacterStudio (VRM-based). If you
+ adopt VRM, do it cleanly through the existing `Viewer`/loader path and keep GLB working; if you
+ decide against a full VRM migration now, wire the wearable-interop *concepts* and say why in a comment.
+- Sources: CharacterStudio https://github.com/M3-org/CharacterStudio , three-vrm
+ https://github.com/pixiv/three-vrm , VerseEngine/three-avatar https://github.com/VerseEngine/three-avatar ,
+ M3-org/avatar-interop https://github.com/M3-org/avatar-interop .
+
+## Definition of done
+- Wardrobe + animation panels work on the **live** studio avatar with real assets; outfits/anim
+ mappings persist to `meta.studio.body` and round-trip; the site-wide presence updates instantly.
+- Hover-preview is ephemeral (no DB writes); save is explicit and real.
+- Performance holds (lazy-load assets, dispose GLTF properly, no leaks across outfit swaps).
+- All states designed (no wearables owned → CTA to forge via `pages/compose.html`; loading skeletons;
+ asset load failure → retry). Accessibility: keyboard-selectable wearables, ARIA on controls.
+- No console errors; `npm test` passes; network tab shows real asset/API calls. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs/sample asset arrays. $THREE is the only coin. Design tokens only. Stage explicit
+paths (never `git add -A`); re-check `git diff --staged` before commit. Own `src/studio/body/**`;
+consume (don't rewrite) `src/avatar-wardrobe.js`, `src/agent-accessories.js`, animation modules.
+Coordinate event→animation mappings with P5 via the `studio` contract.
+
+## When finished
+Self-review (CLAUDE.md's five checks). Then add the share-worthy touch — e.g. a one-click "outfit from
+a prompt" using the existing compose/forge pipeline, or an emote wheel that fires animations live, or
+seasonal/trophy wearables unlocked by trading milestones (coordinate the unlock signal with P4). Build
+it. Then **delete this prompt file** (`prompts/agent-studio/04-wardrobe-studio.md`) and report what
+you shipped + the `meta.studio.body` shape and the event→animation mapping P5 should read.
diff --git a/prompts/agent-studio/05-wallet-trading-brain.md b/prompts/agent-studio/05-wallet-trading-brain.md
new file mode 100644
index 000000000..2400821e9
--- /dev/null
+++ b/prompts/agent-studio/05-wallet-trading-brain.md
@@ -0,0 +1,87 @@
+# P4 — Money & Trading Brain (wallet + visual sniping/trading rules, real Solana)
+
+You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
+`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged. Read the "Integration
+notes for P1–P5" at the top of `src/studio/agent-studio-store.js`. Mount into the **Money** and
+**Skills** tabs. This is the **gamechanging crypto** prompt — treat it with the most care.
+
+## The vision you are enabling
+
+Other platforms give traders a dashboard of numbers. We give them a **character with a brain (P1), a
+memory of every trade (P2), a body (P3), and now its own money and a visually-programmed trading
+mind.** The user funds their agent, draws its sniping/trading rules as a visual flow, and watches the
+agent execute — celebrating fills, flagging dumps, learning from losses — live, on the avatar that
+follows them across the site. Sniping, trading, launching, buying, selling become something you do
+*with a companion you raised*, not a form you submit. Make this the reason people choose three.ws.
+
+We already have: custodial wallets (`api/_lib/agent-wallet.js` — AES-256-GCM, `generateAgentWallet`,
+`generateSolanaAgentWallet`, `getOrCreateAgentEvmWallet`), the `agent-wallet-chip` component
+(`src/shared/agent-wallet-chip.js`), wallet routes in `api/agents.js`, the coin system (`api/coin/`,
+`api/_lib/coin/distribution.js`, `api/_lib/coin/treasury.js`), pump.fun launch (`pages/launch.html`),
+real Solana RPC, and on-chain skill licenses (`api/_lib/skill-license-onchain.js`).
+
+## Your mission
+
+### 1. Money panel — the agent's wallet, made visual and safe
+- Show the agent's real Solana wallet (balance, holdings, P&L, recent txns from real RPC), the vanity
+ prefix/suffix (commit `2486d790c`), and the wallet chip. Fund / withdraw / view-on-explorer flows,
+ all real. The private key stays server-side (custodial) — never expose it; reuse the existing
+ encryption + CSRF patterns exactly.
+- Designed states: unfunded (clear funding CTA + risk copy), low balance, pending tx, failed tx
+ (actionable recovery), empty holdings.
+
+### 2. Trading Brain — visual sniping/trading rules (the centerpiece)
+- A **visual rule builder** where the user composes trading behavior as connected blocks: triggers
+ (new launch matches filter, price crosses level, liquidity/holder thresholds, watchlist event),
+ conditions (risk caps, max position, cooldowns, rug checks), and actions (snipe/buy/sell/ladder/
+ take-profit/stop). This pairs with P1's Brain graph: the **brain reasons, this executes.** Define and
+ honor the node/execution interface P1 specified; the agent can ask its LLM brain to approve/scale an
+ action before firing.
+- Two modes, both first-class: **assisted** (agent proposes, user one-taps to confirm) and
+ **autonomous** (agent executes within hard, user-set guardrails — caps, allowlists, kill switch).
+ Autonomy must be explicit, revocable, and auditable. Default to assisted.
+- **Real execution only:** route through the real Solana stack already in the repo (RPC, pump.fun,
+ the coin/treasury/distribution libs). Real quotes, real slippage, real signatures, real
+ confirmations. No simulated fills, no fake P&L, no paper-trading dressed up as real.
+- Every action writes a **trade memory** (coordinate with P2: `add()` the trade, outcome, and lesson)
+ and emits a market/trade event through `studio.emitMarket(...)` so the avatar reacts live and P5's
+ site-wide presence shows it.
+
+### 3. Safety, trust, and honesty (non-negotiable for money)
+- Hard guardrails enforced **server-side**, not just UI: max spend per tx/day, allowlist/denylist,
+ mandatory rug/honeypot checks before buys, cooldowns, and a global kill switch that halts the agent
+ instantly. Never let a config error spend funds — fail safe.
+- Full audit log of every decision + execution, exportable. Clear, non-hyperbolic risk disclosures.
+ Never imply guaranteed returns.
+
+## The coin rule (read carefully)
+**$THREE (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin three.ws promotes.** The
+trading engine is generic, coin-agnostic plumbing operating on **runtime-supplied mints** the user
+chooses or that come from launch records — that is the allowed mechanical exception. Do **not**
+hardcode, name, market, seed fixtures with, or recommend any specific non-$THREE mint anywhere in
+source, copy, tests, or commit messages. Synthetic placeholders only in any test
+(e.g. `THREEsynthetic1111…`); never a real mainnet mint.
+
+## Definition of done
+- Money panel shows real on-chain wallet state; fund/withdraw/explorer all real and safe.
+- Visual rule builder composes real triggers/conditions/actions; assisted + autonomous both work with
+ enforced server-side guardrails and a working kill switch.
+- Executions are real (real signatures/confirmations), write trade memories (P2), and drive live
+ avatar reactions via `studio.emitMarket` (P5).
+- Audit log complete and exportable. All states designed. No fake fills/P&L anywhere.
+- No console errors; `npm test` passes; network tab shows real RPC/pump.fun/coin calls. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs/simulated fills/fake P&L/sample arrays. $THREE is the only coin promoted; engine
+uses runtime mints only — never paste a real third-party mint. Custodial key never leaves the server.
+Design tokens only. Stage explicit paths (never `git add -A`); re-check `git diff --staged` before
+commit. Own `src/studio/money/**`, `api/trading/**`, extensions to `api/coin/**` and
+`api/_lib/agent-wallet.js`. Coordinate trade memories with P2, the execution interface with P1, and
+events with P5 via the `studio` contract.
+
+## When finished
+Self-review (CLAUDE.md's five checks). Then push the edge — e.g. a "rule backtest against real
+historical launches" preview (clearly labeled as historical, never presented as a guarantee), a
+shareable trade card the avatar "presents" on a win, or trophy unlock signals for P3. Build it. Then
+**delete this prompt file** (`prompts/agent-studio/05-wallet-trading-brain.md`) and report what you
+shipped + the guardrail config shape and the market-event types P5 should handle.
diff --git a/prompts/agent-studio/06-living-presence.md b/prompts/agent-studio/06-living-presence.md
new file mode 100644
index 000000000..9168d4333
--- /dev/null
+++ b/prompts/agent-studio/06-living-presence.md
@@ -0,0 +1,73 @@
+# P5 — Living Presence (the avatar is alive on every page)
+
+You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md` and
+`STRUCTURE.md` first. **Prerequisite:** P0 (`01-foundation.md`) is merged — `<agent-presence>` and
+the `studio` store (with `emitMarket`/`onMarket`) exist. Read the "Integration notes for P1–P5" at
+the top of `src/studio/agent-studio-store.js`.
+
+## The vision you are enabling
+
+Our core product principle: **the user's 3D agent is present on every page**, reacting to what's
+happening, so the platform feels alive and the user stays engaged. Studio (P0–P4) is where the agent
+is authored; **your job is to make that agent show up and behave everywhere else** — the launch feed,
+the trading views, discovery, the snipe terminal, the dashboard, the changelog — as a companion that
+emotes, comments, and acts in context. This is the difference between "a website with a mascot" and
+"a living agent that lives with you." Make it feel inevitable, not gimmicky.
+
+## Your mission
+
+### 1. Mount the presence site-wide
+- Place `<agent-presence>` across the platform's pages (`pages/*.html` + their `src/*.js` entry
+ points). Pick the right `mode` per surface: `mini` floating companion on dense data pages, larger
+ `companion` where the avatar is contextually central. Respect the existing nav/shell
+ (`src/next-layout.js`, `public/nav.html`) — integrate, don't fight it.
+- The companion is **the same agent** the user edits in Studio (one identity, one source of truth via
+ `studio`). Editing in Studio → presence updates live, no refresh.
+- It must be **opt-out-able and unobtrusive**: draggable, dismissible to a small bubble, position +
+ state remembered per user, never covering critical UI, never blocking interaction. Respect
+ `prefers-reduced-motion`. Pause rendering when offscreen/tab hidden (P0 set this up — honor it).
+
+### 2. Make it react to real events (the magic)
+- Subscribe to real platform signals and translate them into avatar behavior using the existing
+ emotion blend + animations (`src/agent-avatar.js`, the event→animation map P3 stored in
+ `meta.studio.body`) and the events P4 emits via `studio.emitMarket`:
+ - `snipe:filled` / big win → celebrate + a short, real spoken/typed callout.
+ - `position:down` / dump / failed tx → concern + a useful prompt ("cut or hold?").
+ - new launch matching the user's watchlist/brain filters → alert + "want me to snipe?".
+ - incoming agent-to-agent message / DM → notice + summarize.
+- Reactions must be driven by **real data** (real RPC/feed/launch/trade events already in the repo —
+ pump.fun feed, Solana RPC, the trade events from P4). No fake/random "ambient" events dressed up as
+ real signals. Idle behavior (breathing/micro-moves via `src/idle-animation.js`) is fine between
+ real events.
+
+### 3. Context-aware behavior per page
+- The companion adapts to where the user is: on a coin/launch page it watches that mint and offers
+ one-tap actions through the agent's real wallet/trading config (P4); on discovery it can comment on
+ what it "remembers" (P2); on the dashboard it surfaces the agent's status. Always provide a one-tap
+ path back to `/studio` to edit the relevant aspect.
+- Voice/lip-sync is already available — use it sparingly and tastefully (default muted, user enables).
+
+## Definition of done
+- The user's live agent renders on every major page in an appropriate mode, performant (no scroll
+ jank, shared/cached WebGL context, paused when hidden), with real edits reflecting instantly.
+- Reactions fire from **real** market/trade/platform events and map to real emotions/animations.
+- Companion is draggable, dismissible, position-remembered, reduced-motion-aware, never blocks UI,
+ fully keyboard accessible, with ARIA.
+- Context actions (snipe/watch/back-to-studio) are wired to the real P2/P4 surfaces — no dead buttons.
+- All states designed (no agent yet → "create your agent" CTA; reconnecting; muted). No console errors;
+ `npm test` passes; network tab shows real event sources. Changelog entry added.
+
+## Operating rules (override defaults)
+No mocks/stubs/TODOs/fake events/random ambient signals presented as real. $THREE is the only coin
+promoted; coin pages use runtime mints only. Design tokens only. Stage explicit paths (never
+`git add -A`); re-check `git diff --staged` before commit — you touch many shared page files, so be
+surgical and append-only where others may be editing. Own `src/presence/**`; mount points across
+pages. Consume P3's event→animation map and P4's market events via the `studio` contract; do not
+rewrite the `<agent-presence>` element P0 owns — extend it through its documented API.
+
+## When finished
+Self-review (CLAUDE.md's five checks). Then add the unforgettable touch — e.g. the companion
+"narrating" a live snipe as it executes, or a subtle cross-page continuity where the agent finishes a
+thought it started on the previous page, or a daily "your agent's recap" the avatar presents. Build
+it. Then **delete this prompt file** (`prompts/agent-studio/06-living-presence.md`) and report what
+you shipped + which pages now host the presence and the full event→reaction mapping.
diff --git a/prompts/agent-wallets/00-README-orchestration.md b/prompts/agent-wallets/00-README-orchestration.md
new file mode 100644
index 000000000..ad7398fcc
--- /dev/null
+++ b/prompts/agent-wallets/00-README-orchestration.md
@@ -0,0 +1,203 @@
+# Program: Agent Wallets — make every avatar a self-custodial financial identity
+
+> **Read this file in full before starting any task in this folder.** Every prompt
+> here (`01-*` … `06-*`) assumes the context below. Do not re-derive it.
+
+## What we are building and why
+
+three.ws is a platform where every 3D avatar is an autonomous agent. Each agent
+already has a **custodial wallet** (Solana + EVM) provisioned automatically. Today
+that wallet is almost invisible: a tiny violet chip in a few places. That is a
+massive missed opportunity.
+
+**The thesis:** an agent's wallet is its identity. It is how it gets tipped, how it
+snipes a launch, how it trades, how it launches a coin, how it pays other agents,
+how its owner withdraws profit. We are going to make the wallet a **first-class,
+ubiquitous, beautiful, genuinely game-changing surface** — present everywhere an
+avatar appears, and powerful enough that traders, snipers, and launchers choose
+three.ws *because of it*.
+
+We are not adding "a wallet widget." We are inventing the wallet layer that the
+rest of crypto will copy. Hold that bar.
+
+## The ownership model (already implemented — do NOT change the backend invariants)
+
+This is the rule the user cares about most. It is already correct in the backend.
+Your UI must make it **legible and delightful**, never violate it.
+
+- **You own the wallet of the avatar you created.** When a user creates/uploads a
+ 3D avatar, an `agent_identities` row is created with `user_id = creator` and a
+ fresh custodial Solana + EVM wallet is provisioned
+ ([api/_lib/avatar-agent.js](../../api/_lib/avatar-agent.js),
+ [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js)).
+- **Forking/saving someone else's avatar mints a NEW wallet for the forker.**
+ `POST /api/agents/fork` ([api/agents/fork.js](../../api/agents/fork.js)) creates a
+ brand-new agent row owned by the caller, copies the GLB into the caller's
+ namespace, **never copies wallet secrets**, and calls `provisionAgentWallets()` to
+ generate fresh keys. Lineage is stored in `meta.forked_from`
+ (`{ agent_id, owner_id, owner_name, name, forked_at }`).
+- **One agent = one owner.** `agent_identities.user_id` is immutable and never
+ co-owned. Only the owner can withdraw, set spend limits, rebrand the vanity
+ address, or recover keys. Everyone else sees a read-only / "tip" / "fork to get
+ your own" view.
+- **Custody:** private keys are AES-256-GCM encrypted at rest
+ ([api/_lib/secret-box.js](../../api/_lib/secret-box.js)), decrypted only at signing
+ time, every decrypt is audit-logged. Never expose, log, or render a secret key.
+
+So the three viewer states your UI must always distinguish:
+
+1. **Owner view** — full controls (deposit, withdraw, vanity, limits, trade, snipe,
+ custody trail).
+2. **Visitor view (public agent)** — read-only balance/holdings + Tip + a "Fork to
+ get your own wallet" CTA.
+3. **Logged-out** — read-only + sign-in / connect prompt.
+
+## Hard rules (from CLAUDE.md — non-negotiable, repeated here so you don't skip them)
+
+- **No mocks. No fake data. No placeholders. No sample arrays.** Every number on
+ screen comes from a real API hitting real Solana/EVM RPC or a real DB row. If a
+ balance is `0`, show a real `0`, never a fake `$1,234`.
+- **No TODOs, no stubs, no `throw new Error("not implemented")`, no commented-out
+ code, no `setTimeout` fake loading.** If you write it, finish it.
+- **The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never name, hardcode, or recommend any other token anywhere. Runtime-supplied
+ mints (a user sniping an arbitrary launch, the launches feed) are the only
+ exception, and you never hardcode or promote a specific non-$THREE mint.
+- **Every state is designed:** loading (skeletons, not spinners), empty (tell the
+ user what to do), error (actionable), populated, overflow.
+- **Errors handled at boundaries**, with real working fallbacks. "No errors without
+ solutions."
+- **Accessibility:** semantic HTML, ARIA on interactive elements, keyboard nav,
+ focus rings, contrast.
+- **Match the design system.** See below — never hardcode hex/px.
+
+## Design system (use these tokens, never invent values)
+
+Source of truth: [public/tokens.css](../../public/tokens.css), imported globally.
+
+- **Palette:** monochrome glass on near-black. `--bg-0:#0a0a0a`, surfaces
+ `--surface-1/2/3` (white at 3/5/8% alpha), `--stroke`/`--stroke-strong`,
+ `--accent:#fff`, text `--ink`/`--ink-dim`/`--ink-bright`/`--ink-faint`,
+ `--success:#4ade80`, `--danger:#f87171`, `--warn:#fbbf24`.
+- **Type:** `--font-display` (Space Grotesk), `--font-body` (Inter), `--font-mono`
+ (JetBrains Mono — use for all addresses/amounts). Sizes `--text-2xs`…`--text-3xl`.
+- **Spacing:** phi scale `--space-2xs`…`--space-2xl`. **Radii:** only
+ `--radius-sm/md/lg/pill`. **Shadows:** `--shadow-1/2/3`. **Blur:**
+ `--blur-sm/md/lg`. **Motion:** `--duration-instant/fast/base`, `--ease-standard`.
+- The existing wallet chip uses a violet accent (`#c4b5fd` /
+ `rgba(139,92,246,…)`) to mark "wallet". Keep wallet UI in that violet family so
+ the wallet layer reads as one coherent system across the app — but route it
+ through a token (add `--wallet-accent` etc. to tokens.css if helpful) rather than
+ scattering raw hex.
+
+## The surfaces (everywhere an avatar/agent appears — the chip/HUD must reach all)
+
+Audit and cover **all** of these. Add any you discover that are missing:
+
+- Agent detail / profile — [src/agent-detail.js](../../src/agent-detail.js) (`/agent/:id`)
+- Character page — [src/character.js](../../src/character.js) (`/character/:id`)
+- Avatar page (3D viewer) — [src/avatar-page.js](../../src/avatar-page.js) (`/avatars/:id`)
+- Marketplace detail — [src/marketplace-detail.js](../../src/marketplace-detail.js)
+- Trending / leaderboard — feed driven by [api/trending.js](../../api/trending.js)
+- Galaxy (3D star map) — [src/galaxy.js](../../src/galaxy.js)
+- My Agents / dashboard — [src/agent-home.js](../../src/agent-home.js) and variants
+- Launches feed — `/launches` and agent launch history
+- Any agent card component shared across the above
+
+## The real APIs you will use (all exist today — read them, don't reinvent)
+
+Wallet endpoints live under `api/agents/` (mostly `api/agents/solana-wallet.js`,
+`api/agents/eth-vanity.js`, `api/agents/fork.js`):
+
+- `GET /api/agents/:id/solana` — address + balance (public read)
+- `POST /api/agents/:id/solana` — provision/import (owner)
+- `GET /api/agents/:id/solana/holdings` — withdrawable SOL + SPL assets
+- `GET /api/agents/:id/solana/activity` — recent signatures (owner)
+- `POST /api/agents/:id/solana/withdraw` — sweep SOL/SPL (owner, CSRF, spend policy)
+- `POST /api/agents/:id/solana/tip` — record a P2P tip (visitor)
+- `GET/PUT /api/agents/:id/solana/limits` — spend policy (owner)
+- `GET /api/agents/:id/solana/custody` — custody audit trail (owner)
+- `GET/POST /api/agents/:id/solana/vanity` — vanity status / grind+swap (owner)
+- `GET/POST/DELETE /api/agents/:id/eth-vanity` — CREATE2 vanity record (owner)
+- `POST /api/agents/fork` — fork → new owner + new wallets
+- Pricing helpers + `$THREE` data, pump.fun feed, Solana RPC: see
+ [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js),
+ [api/_lib/agent-pumpfun.js](../../api/_lib/agent-pumpfun.js).
+
+CSRF: write endpoints expect a CSRF token (see how the existing wallet chip and
+withdraw flow obtain it — recent commit "integrate CSRF token handling"). Reuse
+that pattern; do not bypass it.
+
+Auth: current user via session cookie (`getSessionUser`) or bearer
+([api/_lib/auth.js](../../api/_lib/auth.js)). Ownership check =
+`agent_identities.user_id === auth.userId`.
+
+If an endpoint you need for an innovative feature genuinely does not exist, **build
+it properly** (real implementation, real chain calls, owner auth, CSRF, audit log,
+spend-limit enforcement) — do not fake it client-side.
+
+## Shared component contract (so the surfaces stay consistent)
+
+The single source of truth for the wallet chip is
+[src/shared/agent-wallet-chip.js](../../src/shared/agent-wallet-chip.js). All shared
+wallet UI you build (chip, HUD/drawer, vanity studio modal) must live under
+`src/shared/` and be imported by every surface — never copy-paste per page. If you
+extend the data contract (e.g. add P&L), update every caller. Coordinate via the
+data attributes/exports already used by the chip.
+
+## Working rules for THIS repo (traps that have bitten agents here)
+
+- **Concurrent agents share this worktree.** Other agents (including your siblings
+ in this program) may be committing on `main` while you work. **Stage explicit
+ paths only** (`git add path/to/file`), never `git add -A`/`.`. Re-run
+ `git status` + `git diff --staged` right before committing.
+- **`npx vercel build` overwrites `api/*.js` with esbuild bundles.** If you build,
+ check `head -1` of changed `api/` files for `__defProp`/`createRequire` and
+ `git restore -- api/ public/` if bundled.
+- **Never `git add -A`.** Never pull/fetch/merge from the `threeD` remote.
+- Run `npm run dev` (port 3000) and exercise your feature in a real browser. No
+ console errors/warnings from your code. Confirm real API calls in the Network tab.
+- Existing tests must still pass (`npm test`).
+- **Changelog:** every user-visible change gets an entry in
+ [data/changelog.json](../../data/changelog.json) (plain-language title + summary,
+ tags from feature/improvement/fix/sdk/infra/docs/security). Run
+ `npm run build:pages` to validate.
+
+## Definition of done (per task)
+
+1. Code written, wired into the UI, reachable by navigation across **all** relevant
+ surfaces.
+2. Exercised in a real browser via `npm run dev`. No console errors/warnings.
+3. Network tab shows real API calls returning real data.
+4. Every interactive element has hover/active/focus states; every state (loading/
+ empty/error/populated/overflow) designed.
+5. Owner / visitor / logged-out states all correct and tested.
+6. `npm test` passes. Changelog entry added. `git diff` self-reviewed.
+7. You would proudly demo this to a room of senior engineers and to a room of
+ degens who snipe for a living.
+
+## Then: improve, then delete this task
+
+After you meet the definition of done, **do not stop**. Run the self-review
+protocol from [CLAUDE.md](../../CLAUDE.md): the lazy check, the user check, the
+integration check, the edge-case check (0 / 1 / 1000 items, very long names,
+network failure mid-op, expired session), the pride check. Find the single biggest
+weakness in what you built and **fix it now** — add the keyboard shortcut, the
+empty-state illustration, the cross-feature link, the micro-animation that makes it
+feel alive. Then look one level up: does what you built unlock something adjacent?
+Wire that connection too.
+
+**Finally, when the task is truly complete and committed, delete your own prompt
+file** (`prompts/agent-wallets/0X-*.md`) so the task board reflects reality. Leave
+this `00-README-orchestration.md` in place until the whole program is done.
+
+## Suggested order / dependencies
+
+- **`01` (Wallet Identity Layer)** is the foundation — the shared chip + data
+ contract everything else hangs off. Ideally land first, or coordinate closely.
+- **`02` (Wallet HUD/Drawer)**, **`03` (Vanity Studio)**, **`04` (Ownership /
+ Fork-to-own)** build on `01`'s shared component and can run in parallel.
+- **`05` (Sniper / Trading Co-pilot)** is the headline innovation; it consumes the
+ HUD and balances from `01`/`02`.
+- **`06` (Integration & QA pass)** runs last — verifies every surface, every state,
+ every viewer role, end to end in the browser.
diff --git a/prompts/agent-wallets/01-wallet-identity-layer.md b/prompts/agent-wallets/01-wallet-identity-layer.md
new file mode 100644
index 000000000..5d7e126db
--- /dev/null
+++ b/prompts/agent-wallets/01-wallet-identity-layer.md
@@ -0,0 +1,124 @@
+# Task 01 — The Wallet Identity Layer (foundation)
+
+> **Read [00-README-orchestration.md](./00-README-orchestration.md) first.** It
+> defines the ownership model, design tokens, surfaces, real APIs, hard rules, the
+> definition of done, and the "improve then delete this file" close-out. This task
+> assumes all of it.
+
+## Mission
+
+Turn the tiny, under-used wallet chip into a **living wallet identity component**
+that appears on *every* surface where an avatar/agent is shown, and reads as one
+coherent system across the whole app. This is the foundation the rest of the
+program builds on — get the data contract and the component right.
+
+Today there is [src/shared/agent-wallet-chip.js](../../src/shared/agent-wallet-chip.js):
+a small violet pill showing a shortened Solana address with the vanity prefix/suffix
+highlighted, a copy button, an explorer link, and an owner-only "vanity" action /
+visitor "tip" action. It is imported by a handful of surfaces but not all, and it
+shows almost nothing about the wallet's actual state.
+
+## What the upgraded component must show
+
+A wallet is an identity. At a glance, anywhere an avatar appears, a user should see:
+
+- **Vanity-aware address** (keep the prefix/suffix highlight — it's a great touch).
+- **Live balance** — total portfolio value in USD, derived from real SOL + USDC +
+ SPL holdings via `GET /api/agents/:id/solana` and
+ `GET /api/agents/:id/solana/holdings`. Real numbers only.
+- **Ownership state** — a clear, tasteful marker for "Yours" vs "owned by
+ @creator". Owner badge vs creator attribution (read `meta.forked_from` /
+ `user_id`). This is the user's core ask: make ownership legible everywhere.
+- **A micro P&L sparkline / 24h change** when data exists (see below for the data
+ source). Degens read P&L before anything else.
+- **Multi-chain awareness** — the agent has both Solana and EVM wallets; the chip
+ should not pretend Solana is the only one. Show the primary, make both reachable.
+
+On hover/focus (desktop) or tap (mobile), the chip should **expand into a rich
+preview popover** — balances broken out (SOL / USDC / $THREE / other SPL), the full
+vanity address with copy, top holdings, and the primary actions appropriate to the
+viewer's role (Deposit/Withdraw/Vanity/Trade for owner; Tip/Fork-to-own for
+visitor). The full Wallet HUD (task `02`) opens from a "Open wallet" affordance in
+this popover — coordinate the handoff with that task.
+
+## Innovation mandate (this is where you earn the bar)
+
+Do not just bolt numbers onto a pill. Think about what would make a trader
+screenshot this. Ideas — implement the strong ones, invent better:
+
+- **A wallet "pulse"** — a subtle live animation when the balance changes (a tip
+ lands, a trade fills), driven by real polling or a real event source. No fake
+ ticks.
+- **Identity = address as art.** The vanity address is the agent's brand. Treat it
+ like one: a tasteful gradient/monospace treatment, a one-click "share my wallet"
+ that produces a real OG card (reuse `/api/agent-share`).
+- **Reputation at a glance** — total tips received, lifetime volume, # of forks
+ (real counts from the DB). The wallet becomes a trust signal.
+- **Cross-surface consistency** — the same agent's wallet looks identical in the
+ galaxy, the marketplace, and its profile. One component, one truth.
+
+## Data contract & component API (the foundational deliverable)
+
+- Keep a single shared module under `src/shared/` as the source of truth. Either
+ extend `agent-wallet-chip.js` or introduce a clean
+ `src/shared/agent-wallet-identity.js` that the chip and the HUD both consume —
+ your call, but there must be exactly one normalizer for "agent → wallet
+ descriptor."
+- Define a documented descriptor (address(es), vanity prefix/suffix, balances,
+ USD value, P&L, ownership state, reputation counts) and a normalizer that maps a
+ raw agent/avatar record into it. Every surface passes its existing agent object;
+ the normalizer handles the field aliasing (`agent.solana_address` /
+ `agent.meta.solana_address` / `avatar.agent_solana_address`, etc.).
+- Export both an HTML-string renderer (for template-built lists like trending) and
+ a DOM-node factory with wired handlers (for interactive pages), mirroring the
+ current `walletChipHTML()` / `walletChipEl()` split.
+- **Balance fetching:** lists must not fire N×3 requests on render. Design a
+ batched/lazy strategy — render the chip immediately from whatever the list
+ payload already carries (address, vanity), then lazily hydrate balance/P&L on
+ viewport-enter (IntersectionObserver) or via a single batch endpoint. If a batch
+ balance endpoint doesn't exist and you need one, **build it for real**
+ (`POST /api/agents/balances` taking an array of ids, reading real chain state with
+ sane caching) — no client-side fan-out storms, no fake numbers.
+
+## P&L data source (build it real or don't show it)
+
+If there is no existing source of historical wallet value, you have two honest
+options — pick one and implement fully:
+
+1. Compute 24h change from real on-chain holdings valued at real current vs.
+ 24h-ago prices (price feeds already used in
+ [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js) / coingecko / pump.fun).
+2. Persist periodic balance snapshots server-side and derive change from them.
+
+Whichever you choose, the sparkline reflects real value. If there is genuinely no
+data yet for a wallet, render the *empty* sparkline state, not a fake curve.
+
+## Coverage (wire it EVERYWHERE — audit, don't assume)
+
+Add/upgrade the wallet identity component on **all** surfaces listed in the
+orchestration README: agent detail, character page, avatar page, marketplace
+detail, trending/leaderboard, galaxy, my-agents/dashboard, launches feed, and any
+shared agent-card component. Grep the codebase for existing imports of the chip to
+find current call sites, then find the surfaces that *should* have it but don't.
+Every place an avatar's face shows, its wallet identity shows.
+
+## Constraints specific to this task
+
+- The chip renders in dense lists (trending rows, galaxy cards) and on roomy pages.
+ It must be responsive and not blow up list layouts. Test at 320 / 768 / 1440.
+- Polling must be cheap and must stop when the element is offscreen or the tab is
+ hidden (`visibilitychange`). No runaway intervals.
+- Never render a secret. Only public addresses and balances.
+- Respect the viewer role on the popover actions (owner vs visitor vs logged-out).
+
+## Definition of done
+
+Per the orchestration README's checklist. Specifically also: the chip is present
+and visually identical for the same agent across at least the profile, trending,
+galaxy, and marketplace surfaces; balances are real and hydrate without jank; the
+ownership marker is correct for owner vs visitor; no N+1 request storm in lists.
+
+When done, run the self-review + improvement pass, add a changelog entry, commit
+(staging explicit paths only, pushing to **both** `threeD` and `threews` if the
+user asks to push), then **delete this file**
+(`prompts/agent-wallets/01-wallet-identity-layer.md`).
diff --git a/prompts/agent-wallets/02-wallet-hud-drawer.md b/prompts/agent-wallets/02-wallet-hud-drawer.md
new file mode 100644
index 000000000..2eeaea6b6
--- /dev/null
+++ b/prompts/agent-wallets/02-wallet-hud-drawer.md
@@ -0,0 +1,100 @@
+# Task 02 — The Wallet HUD (the full wallet, reachable from anywhere)
+
+> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the
+> ownership model, tokens, real APIs, hard rules, definition of done, and the
+> "improve then delete this file" close-out. Coordinate with **task 01** — this HUD
+> opens from the wallet identity chip/popover it builds.
+
+## Mission
+
+Build the **Wallet HUD** — a single, gorgeous, full-featured wallet surface that
+slides over any agent from anywhere in the app. The chip (task 01) is the glance;
+this is the cockpit. It must feel like the best wallet experience in crypto:
+faster than Phantom, clearer than a CEX, designed like Linear.
+
+One shared component (`src/shared/agent-wallet-hud.js` or similar under
+`src/shared/`), opened from any wallet chip/popover with an agent id. It adapts to
+the viewer's role (owner / visitor / logged-out) per the ownership model.
+
+## What the HUD contains
+
+A drawer/overlay (slide-in panel on desktop, full-sheet on mobile) with these
+sections, all backed by real APIs:
+
+1. **Header** — avatar thumbnail, agent name, vanity address (mono, copyable),
+ ownership marker ("Yours" / "by @creator"), total portfolio value in USD,
+ 24h change. Real data via `GET /api/agents/:id/solana` +
+ `/api/agents/:id/solana/holdings`.
+2. **Balances by chain & asset** — Solana (SOL, USDC, $THREE, other SPL) and EVM
+ (native + tokens). Each row: token, amount (mono), USD value, % of portfolio.
+ Real on-chain reads. $THREE is the only coin you ever *name/feature*; other
+ holdings render generically from runtime data.
+3. **Deposit** (all viewers) — show the wallet address + a real QR code (use a real
+ QR lib already in the tree or add one properly), chain selector, copy. This is
+ how a wallet gets funded; make it frictionless.
+4. **Withdraw / Sweep** (owner only) — `POST /api/agents/:id/solana/withdraw`.
+ Destination input with address validation, asset + amount (with MAX), live
+ USD preview, CSRF token, spend-policy awareness. Confirm step. Real tx, real
+ signature link to explorer on success.
+5. **Activity** — recent transactions from `GET /api/agents/:id/solana/activity`
+ (owner) and/or public signatures: inflows (tips, deposits), outflows
+ (withdrawals, trades, skill payments). Link each to the explorer. Real data.
+6. **Spend limits / policy** (owner only) — `GET/PUT /api/agents/:id/solana/limits`:
+ daily USD cap, per-tx ceiling, allowlist, freeze toggle. This is the safety rail
+ that makes autonomous agent trading trustworthy — present it as a feature, not a
+ settings dump.
+7. **Custody trail** (owner only) — `GET /api/agents/:id/solana/custody`: every key
+ recovery / withdraw / limit change with reason + timestamp. Frame it as
+ "your wallet's security log." Real audit rows.
+8. **Tip** (visitor) — `POST /api/agents/:id/solana/tip`. A delightful one-tap tip
+ flow for non-owners. Real record; if it involves an on-chain transfer from the
+ visitor's connected wallet, wire that for real.
+9. **Vanity entry point** — link/launch into the Vanity Studio (task 03) for owners.
+10. **Trade / Snipe entry point** — link/launch into the trading co-pilot (task 05)
+ for owners. Coordinate the handoff.
+
+## Innovation mandate
+
+- **The HUD is the same everywhere** — open it from the galaxy, from a trending row,
+ from the agent's profile: identical, instant, context-aware. That ubiquity is the
+ product.
+- **Real-time feel** — when a tip lands or a trade fills, the balance and activity
+ update live (poll cheaply, or a real event source). No fake animation without a
+ real event behind it.
+- **Portfolio intelligence** — allocation donut, biggest mover, "since you opened
+ this" delta. All from real holdings + real prices.
+- **Keyboard-first** — `Esc` closes, focus trap, arrow-nav the asset list, a command
+ to copy the address. Designed for power users.
+- Invent beyond this list where it raises the bar — but every pixel is backed by
+ real data.
+
+## Real APIs (see orchestration README for the full list)
+
+`api/agents/solana-wallet.js` exposes balance / holdings / activity / withdraw /
+tip / limits / custody. CSRF tokens are required on writes — reuse the existing
+CSRF pattern (recent commit "integrate CSRF token handling"); do not bypass it.
+Ownership = `agent_identities.user_id === auth.userId`. If you need a new endpoint
+for an innovative panel, build it for real (auth, CSRF, audit, spend-limit
+enforcement, real chain calls) — never fake it.
+
+## States & edge cases (all designed)
+
+- Loading: skeleton rows, not spinners. Empty wallet: a warm empty state that tells
+ the owner how to fund it (deposit) and tells a visitor they can tip / fork.
+- Withdraw errors (insufficient balance, bad address, over spend limit, network
+ fail): actionable inline messages, never a raw stack.
+- 0 / 1 / many assets; very long token names; dust balances; an agent with no EVM
+ wallet yet (offer to provision); expired session mid-action (re-auth gracefully).
+- Visitor must never see withdraw/limits/custody controls — enforce in UI **and**
+ rely on server-side owner checks (defense in depth).
+
+## Definition of done
+
+Per the orchestration README. Plus: the HUD opens from at least the chip on the
+profile, trending, and galaxy surfaces; a real withdraw on devnet (or a real tip)
+completes end-to-end with an explorer link; owner-only panels are invisible to
+visitors; no console errors; responsive at 320/768/1440; `Esc`/focus-trap work.
+
+When done: self-review + improvement pass, changelog entry, commit (explicit paths
+only), then **delete this file**
+(`prompts/agent-wallets/02-wallet-hud-drawer.md`).
diff --git a/prompts/agent-wallets/03-vanity-studio.md b/prompts/agent-wallets/03-vanity-studio.md
new file mode 100644
index 000000000..aa910076a
--- /dev/null
+++ b/prompts/agent-wallets/03-vanity-studio.md
@@ -0,0 +1,89 @@
+# Task 03 — The Vanity Studio (make every agent's address a brand)
+
+> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the
+> ownership model, tokens, real APIs, hard rules, definition of done, and the
+> "improve then delete this file" close-out. Builds on the shared wallet component
+> from **task 01** and is launched from the HUD (**task 02**).
+
+## Mission
+
+A custom (vanity) wallet address is an agent's signature — `THREExyz…` reads as
+brand, not noise. The backend already grinds vanity addresses (Solana base58
+prefix/suffix; EVM CREATE2 hex) and safely sweeps funds into the new address. Today
+the UI is a bare link. Build the **Vanity Studio**: a delightful, owner-only
+surface that makes minting a custom address feel like a premium feature people
+brag about.
+
+## What exists (read it before building)
+
+- Solana grinder: [api/_lib/pump-vanity.js](../../api/_lib/pump-vanity.js)
+ (`grindMintKeypair`, `estimateAttempts`), base58, max ~6 chars, yields every 10k
+ attempts.
+- Solana vanity endpoint: `GET/POST /api/agents/:id/solana/vanity` in
+ [api/agents/solana-wallet.js](../../api/agents/solana-wallet.js) — grinds a new
+ keypair server-side, **sweeps existing funds to the new address**, swaps keys
+ (money-safe). Stores `meta.solana_vanity_prefix/suffix`. Serverless bounds:
+ `VANITY_MAX_CHARS`, `VANITY_MAX_ITERATIONS`.
+- EVM CREATE2 vanity: [api/agents/eth-vanity.js](../../api/agents/eth-vanity.js) —
+ hex prefix/suffix, verifies CREATE2 derivation and on-chain deployment.
+
+## What the Studio must do
+
+1. **Pattern designer** — input for prefix and/or suffix with **live validation**:
+ base58 alphabet for Solana (reject `0OIl`), hex for EVM, max-length enforcement.
+ Show a live **preview** of what the resulting address will look like
+ (`THREE…xyz`) with the matched part highlighted in the same violet the chip uses.
+2. **Difficulty / time estimate** — call/replicate `estimateAttempts` to show, in
+ real time, "≈ N attempts, ~T to grind" as the user types. Make the cost of a
+ longer pattern visceral and honest. No fake progress.
+3. **Grind with real progress** — kick off the real server grind. Because grinding
+ is bounded server-side, surface real status: queued → grinding → sweeping funds
+ → swapped, with the **real** attempt count / outcome from the endpoint. If the
+ pattern exceeds serverless bounds, tell the user the real limit and the longest
+ pattern that will succeed — don't pretend.
+4. **Money-safe swap, clearly explained** — the user must understand their funds
+ move to the new address and the old key is retired. Show before/after addresses,
+ the sweep tx (explorer link), and a clear success state. This touches real
+ custodial funds — the copy must be precise and reassuring, the confirm explicit.
+5. **Both chains** — Solana (base58) and EVM (CREATE2 hex) in one coherent surface,
+ each with its own validation and flow. Make the difference legible (an EVM
+ vanity is a predicted CREATE2 address that deploys; a Solana vanity is a real
+ keypair swap).
+6. **Owner-only** — enforce in UI and rely on server owner checks. Visitors never
+ see grind controls.
+
+## Innovation mandate
+
+- **Vanity as identity, surfaced everywhere** — once minted, the vanity prefix/
+ suffix highlight propagates to the chip on every surface (it already does via the
+ shared component from task 01 — verify it does for newly minted patterns too).
+- **Smart suggestions** — offer on-brand patterns derived from the agent's name
+ (e.g. name → valid base58 stub) so users get a great address without thinking.
+- **A "rarity"/flex angle** — longer matched patterns are rarer; show that
+ tastefully (this is honest scarcity, computed from real attempt estimates, not a
+ fake badge).
+- Make the grind feel alive and premium — real status, satisfying success moment,
+ shareable result. Invent beyond this if it raises the bar.
+
+## States & edge cases
+
+- Live validation errors (illegal chars, too long) as the user types — inline,
+ friendly. Estimate updates without jank (debounce).
+- Grind that hits the serverless iteration cap: honest "couldn't find in N
+ attempts, try a shorter pattern" with the funds untouched and the old address
+ intact. Never lose funds, never leave the wallet in a half-swapped state — verify
+ the endpoint's guarantees and reflect them.
+- Network failure mid-grind / mid-sweep: clear recoverable state, re-check actual
+ on-chain/db state before claiming success or failure.
+- Agent with no wallet yet: provision first, then offer vanity.
+
+## Definition of done
+
+Per the orchestration README. Plus: a real Solana vanity grind + sweep completes
+end-to-end (devnet acceptable) with the new address showing on the chip across
+surfaces and a real sweep-tx explorer link; live estimate reflects real attempt
+math; EVM CREATE2 flow validates and persists a real record; owner-only enforced;
+no console errors; responsive.
+
+When done: self-review + improvement pass, changelog entry, commit (explicit paths
+only), then **delete this file** (`prompts/agent-wallets/03-vanity-studio.md`).
diff --git a/prompts/agent-wallets/04-ownership-fork-to-own.md b/prompts/agent-wallets/04-ownership-fork-to-own.md
new file mode 100644
index 000000000..546a631f3
--- /dev/null
+++ b/prompts/agent-wallets/04-ownership-fork-to-own.md
@@ -0,0 +1,103 @@
+# Task 04 — Ownership clarity & "Fork to own your wallet"
+
+> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the
+> ownership model, tokens, real APIs, hard rules, definition of done, and the
+> "improve then delete this file" close-out. Builds on the shared wallet component
+> (**task 01**) and the HUD (**task 02**).
+
+## Mission
+
+This is the user's core mental model made visible: **you own the wallet of the
+avatar you created; if you take someone else's avatar, you get your own brand-new
+wallet.** The backend already enforces this (`agent_identities.user_id`, fork mints
+fresh wallets, `meta.forked_from` lineage). Your job is to make it **obvious,
+trustworthy, and delightful** in the UI everywhere — and to make "fork to get your
+own wallet" a first-class, conversion-driving flow.
+
+## What "ownership clarity" means on screen
+
+Everywhere an agent/avatar + wallet appears, the viewer instantly understands their
+relationship to it:
+
+- **Owner:** a clean "Yours" marker on the wallet, full controls (deposit, withdraw,
+ vanity, limits, trade, snipe). No ambiguity that these funds are theirs.
+- **Visitor (public agent they don't own):** read-only wallet, a clear "owned by
+ @creator" attribution that links to the creator, a **Tip** action, and a
+ prominent, well-designed **"Fork to get your own"** CTA explaining: forking gives
+ you your own copy *with its own wallet you control* — the original owner keeps
+ theirs.
+- **Forked agent:** show lineage — "Forked from @creator's <name>" (from
+ `meta.forked_from`) with a link to the original. Attribution is a feature
+ (provenance), not fine print.
+- **Logged-out:** read-only + a sign-in / connect prompt before any owner action.
+
+Derive role from `agent_identities.user_id === auth.userId`
+([api/_lib/auth.js](../../api/_lib/auth.js)). Never trust the client — owner
+controls must also be enforced server-side (they already are; keep it that way).
+
+## The Fork-to-own flow (the headline of this task)
+
+When a visitor wants an avatar, the path to *owning it with their own wallet* must
+be one tap and crystal clear:
+
+1. From the wallet chip/HUD or the avatar's profile, a **"Fork & get my wallet"**
+ action calls `POST /api/agents/fork` ([api/agents/fork.js](../../api/agents/fork.js)).
+2. Show what happens, honestly and beautifully: a new agent owned by you, the GLB
+ copied into your namespace, **a fresh Solana + EVM wallet generated and
+ controlled by you**, lineage credited to the original creator. No wallet secrets
+ are ever copied — say so; it builds trust.
+3. On success, drop the user into **their** new agent with **their** new wallet HUD
+ open, ready to fund/vanity/trade. The moment of ownership should feel great.
+4. Surface fork lineage both ways: the original shows its fork count / network
+ (`GET /api/agents/fork?of=:id`); the fork shows its parent.
+
+## Auto-provision on avatar creation (verify + surface)
+
+When a user creates/uploads a 3D avatar, the agent + wallet are auto-provisioned
+([api/_lib/avatar-agent.js](../../api/_lib/avatar-agent.js)). Make sure the **first
+time a creator sees their new avatar, they also see "your wallet is ready"** — a
+real moment that introduces the wallet, its address, and how to fund it. If the
+provision is async/best-effort, the UI must handle the brief "provisioning…" state
+honestly and then show the real address (poll for the real value; never show a fake
+placeholder address).
+
+## Innovation mandate
+
+- **Ownership as status** — an owner's wallet across the app subtly signals "this is
+ mine" (a consistent marker/treatment) so a creator feels their portfolio of agents
+ is *theirs*. A "My agents & wallets" portfolio roll-up (total value across all
+ agents the user owns) is a natural, high-value addition — build it real from the
+ owner's agent rows + real balances.
+- **Provenance graph** — the fork network is real social/financial lineage. A small,
+ tasteful "forked from / forks of" visualization turns attribution into a feature
+ people explore. Real data from `meta.forked_from` + the fork-lineage endpoint.
+- **Trust copy** — the single most important sentence in this whole program is some
+ version of "fork it and you control your own wallet; the creator keeps theirs."
+ Make that promise legible at exactly the moment it matters.
+- Invent beyond this where it strengthens the ownership story — but never fake a
+ wallet, balance, or lineage edge.
+
+## States & edge cases
+
+- Forking your own agent, a private agent (should be blocked/owner-only per the
+ endpoint), an agent with no avatar, a deeply-nested fork chain, an agent that's
+ been deleted mid-flow.
+- Fork while logged-out → prompt sign-in, then resume the fork.
+- Provision latency on a brand-new fork → honest "setting up your wallet…" then the
+ real address; never block the success screen on a fake value.
+- Visitor must never see owner controls; owner must never see a "fork to own" CTA on
+ an agent they already own (offer "duplicate" semantics if relevant, but don't
+ confuse the two).
+
+## Definition of done
+
+Per the orchestration README. Plus: owner / visitor / forked / logged-out states are
+each correct and visible across profile + at least one feed surface; a real fork
+end-to-end produces a new agent with a **new, real, distinct** wallet address owned
+by the caller (verify the addresses differ from the source and the source is
+untouched); lineage attribution renders on both sides; auto-provision moment shows a
+real address. No console errors. Responsive.
+
+When done: self-review + improvement pass, changelog entry, commit (explicit paths
+only), then **delete this file**
+(`prompts/agent-wallets/04-ownership-fork-to-own.md`).
diff --git a/prompts/agent-wallets/05-sniper-copilot.md b/prompts/agent-wallets/05-sniper-copilot.md
new file mode 100644
index 000000000..a937a2f94
--- /dev/null
+++ b/prompts/agent-wallets/05-sniper-copilot.md
@@ -0,0 +1,106 @@
+# Task 05 — The Agent Wallet Trading Co-pilot & Sniper (headline innovation)
+
+> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** for the
+> ownership model, tokens, real APIs, hard rules, definition of done, and the
+> "improve then delete this file" close-out. Builds on the wallet identity layer
+> (**task 01**) and HUD (**task 02**), and is gated by spend limits (**task 02**).
+
+## Mission
+
+This is where the agent wallet stops being a wallet and becomes a **weapon**. Every
+agent has a funded, custodial wallet and a spend policy. Turn that into the best
+on-platform experience for **sniping new launches, trading, and launching** — fast,
+safe, and reachable from any avatar. This is the feature that makes a serious trader
+choose three.ws.
+
+**Authorization note:** this is legitimate trading tooling operating on the user's
+own custodial agent wallet, with explicit owner consent and server-side spend
+limits. Build it properly and safely. It is owner-only, limit-gated, and fully
+audited.
+
+## What to build
+
+A **trading co-pilot** surface launched from any agent's wallet (chip/HUD → "Trade /
+Snipe"). Owner-only. Spend-policy-enforced. Sections:
+
+1. **Live launch radar** — a real feed of new pump.fun launches (use the existing
+ pump.fun integration: [api/_lib/agent-pumpfun.js](../../api/_lib/agent-pumpfun.js)
+ and the launches feed). Real-time, filterable (age, liquidity, momentum). Each
+ row is a real, runtime-supplied mint — **never hardcode or promote any specific
+ non-$THREE mint**; these render purely from live data. $THREE is the only coin
+ the platform itself features.
+2. **One-tap snipe** — from a radar row, the owner can buy with their agent wallet:
+ amount input (presets + custom), live quote, slippage control, **and the spend
+ policy enforced** (`GET /api/agents/:id/solana/limits` — per-tx ceiling, daily
+ cap, freeze). Real swap, real signature, real fill shown with explorer link.
+3. **Armed auto-snipe (the innovation)** — let the owner *arm* the agent to snipe
+ launches matching real criteria (e.g. min liquidity, creator filters, max buy)
+ up to a strict, owner-set budget that **cannot exceed the spend policy**. This is
+ an autonomous agent acting on its owner's behalf within hard, audited limits.
+ Every armed buy is recorded in the custody trail with its trigger reason. The
+ owner can disarm instantly. Build the execution path for real (server-side
+ watcher + signer using the existing custodial signing + spend-guard code in
+ [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js) and
+ `api/_lib/agent-trade-guards.js`). No simulated fills.
+4. **Positions & P&L** — the agent's open positions valued at real prices, realized/
+ unrealized P&L, one-tap sell. Feeds the chip/HUD sparkline from task 01.
+5. **Sell / take-profit / stop** — real sell orders; optional owner-set TP/SL that
+ execute for real within spend limits.
+6. **Launch from the wallet** — wire the existing pump.fun launcher so an owner can
+ **launch a coin** funded by the agent wallet, end-to-end, from the same surface
+ (generic, coin-agnostic plumbing where the mint is supplied at runtime — this is
+ the sanctioned exception in CLAUDE.md; do not hardcode or market any specific
+ non-$THREE mint).
+
+## Safety rails (non-negotiable — these make it trustworthy, not toy)
+
+- **Spend limits are law.** Every buy/snipe/armed-buy checks the agent's policy
+ server-side (`agent-trade-guards.js`). The UI shows remaining daily budget and
+ per-tx ceiling live, and blocks/clamps over-limit actions with a clear message.
+ Never bypass the policy, even for armed auto-snipe — especially not there.
+- **Owner consent is explicit.** Arming auto-snipe requires a deliberate confirm
+ with the exact budget and criteria spelled out. A visible "ARMED" state and a
+ one-tap "DISARM" are always present.
+- **Everything is audited.** Every trade and armed action writes to the custody
+ trail (`/api/agents/:id/solana/custody`) with reason + amount + tx. The owner can
+ see exactly what their agent did and why.
+- **Owner-only.** Visitors and logged-out users never see trade controls — UI and
+ server both enforce.
+- **Real funds, real care.** Confirmations for amounts, slippage warnings on thin
+ liquidity, honest error states on failed/partial fills. Never lose or
+ double-spend funds; re-check on-chain state before claiming a fill.
+
+## Innovation mandate (go big — this is the differentiator)
+
+- **Snipe from anywhere** — the radar/snipe is reachable from the galaxy, a trending
+ row, an avatar's profile. Your agent's wallet is always one tap from acting.
+- **The agent as trader, with a face** — because every wallet belongs to a 3D
+ avatar, visualize the agent *doing* the trade (its avatar reacts to a fill). This
+ is something no other platform can do — lean into it. Drive any animation off
+ **real** trade events.
+- **Co-pilot intelligence** — surface real signals (liquidity, age, holder count,
+ momentum) so the snipe decision is informed. Pull from real chain/feed data only.
+- **Shared/forked strategies** — a snipe config is data; let owners save and (if they
+ choose) share strategy presets. Real configs, owner-scoped, no fake leaderboards.
+- Invent past this list. The brief is "game-changing for sniping/trading/launching."
+ Every feature backed by real chain calls, real feeds, real money — within real
+ limits.
+
+## States & edge cases
+
+- Empty radar (no launches right now), thin/failed liquidity, slippage exceeded,
+ insufficient balance, over spend limit, frozen wallet, RPC failure mid-swap,
+ partial fill, session expiry mid-trade, armed budget exhausted. Each designed and
+ honest. Re-derive truth from chain/DB before showing outcomes.
+
+## Definition of done
+
+Per the orchestration README. Plus: a real buy executes on the agent wallet
+(devnet/mainnet per available funds) with a real signature + fill; spend limits
+demonstrably block an over-limit attempt; armed auto-snipe arms/disarms and, when
+armed, executes a real limit-gated buy on a matching real launch, audited in the
+custody trail; positions show real P&L; launch-a-coin path works end-to-end.
+Owner-only enforced. No console errors. Responsive.
+
+When done: self-review + improvement pass, changelog entry, commit (explicit paths
+only), then **delete this file** (`prompts/agent-wallets/05-sniper-copilot.md`).
diff --git a/public/changelog.json b/public/changelog.json
index 52e64f4c4..7e4b01e91 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T10:19:18.628Z",
+ "generated_at": "2026-06-19T10:48:07.066Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -119,6 +119,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Freeze your agent wallet in one tap — plus hardened custody security",
+ "summary": "Your agent's wallet now has a freeze switch. Open the wallet's Limits & Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too.",
+ "link": null,
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
@@ -242,6 +253,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Pay-per-call vanity wallets now do seed phrases and encrypted delivery",
+ "summary": "The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away.",
+ "link": "/vanity-wallet",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index aec758810..bb6fc0f2c 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -94,6 +94,14 @@
<category>fix</category>
<description>Several navigation links pointed at pages that no longer exist — &quot;View plans&quot; on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working &quot;claim&quot; button with a plain explanation that revenue share is distributed to holders automatically.</description>
</item>
+ <item>
+ <title>Freeze your agent wallet in one tap — plus hardened custody security</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Freeze your agent wallet in one tap — plus hardened custody security</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your agent's wallet now has a freeze switch. Open the wallet's Limits &amp; Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too.</description>
+ </item>
<item>
<title>Fund any agent wallet by scanning a QR or copying the address — with live confirmation</title>
<link>https://three.ws/changelog</link>
@@ -190,6 +198,14 @@
<category>fix</category>
<description>The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated &quot;neutral&quot; reading — and still take the payment — when their live price feed was rate-limited. They now return a clean &quot;temporarily unavailable, retry shortly&quot; instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal.</description>
</item>
+ <item>
+ <title>Pay-per-call vanity wallets now do seed phrases and encrypted delivery</title>
+ <link>https://three.ws/vanity-wallet</link>
+ <guid isPermaLink="false">2026-06-19:Pay-per-call vanity wallets now do seed phrases and encrypted delivery</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away.</description>
+ </item>
<item>
<title>Pinning your agent holds up when GPS gets flaky</title>
<link>https://three.ws/irl</link>
diff --git a/public/features.json b/public/features.json
index b0efe63a3..a372ba5d0 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T10:19:18.585Z",
+ "generated_at": "2026-06-19T10:48:07.052Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/coin-cli.mjs b/scripts/coin-cli.mjs
index b07fd019a..94b0786ab 100644
--- a/scripts/coin-cli.mjs
+++ b/scripts/coin-cli.mjs
@@ -33,6 +33,8 @@ import readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import { fileURLToPath } from 'node:url';
+import { encryptSecret } from '../api/_lib/secret-box.js';
+
import {
Connection,
Keypair,
@@ -442,7 +444,17 @@ async function cmdRegister(positional, opts) {
treasury_is_creator: !!opts['treasury-is-creator'],
};
if (opts['creator-secret-b64']) {
- metadata.creator_secret_b64 = opts['creator-secret-b64'];
+ // Encrypt the creator key at rest (AES-256-GCM under WALLET_ENCRYPTION_KEY)
+ // so a DB dump never yields a usable signing key. The treasury loader
+ // transparently decrypts the `v2:`-prefixed blob. Requires WALLET_ENCRYPTION_KEY
+ // (or JWT_SECRET) in the operator env — the same secret the runtime decrypts with.
+ if (!process.env.WALLET_ENCRYPTION_KEY && !process.env.JWT_SECRET) {
+ throw new Error(
+ 'Cannot encrypt --creator-secret-b64: set WALLET_ENCRYPTION_KEY (preferred) or JWT_SECRET ' +
+ 'to the SAME value the runtime uses, so the coin cron can decrypt the stored creator key.',
+ );
+ }
+ metadata.creator_secret_b64 = await encryptSecret(opts['creator-secret-b64']);
}
const sql = await neonSql();
diff --git a/src/a-me.js b/src/a-me.js
index bd864300f..d962e059a 100644
--- a/src/a-me.js
+++ b/src/a-me.js
@@ -14,6 +14,7 @@
// GET /api/billing/summary
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
@@ -219,6 +220,14 @@ function renderAgentCards(host, agents, avatars) {
const name = esc(a.name || a.display_name || 'Unnamed');
const tagline = esc((a.persona?.tagline || a.tagline || '').slice(0, 120));
const wallet = a.wallet_address || a.solana_address || '';
+ // Shared wallet chip. /a/me lists only agents the viewer owns, so every
+ // chip here is owner-tier (vanity entry point, never a Tip button). Reads
+ // the address from solana_address/meta/wallet; legacy rows expose only
+ // wallet_address, so normalise it onto solana_address for the chip.
+ const walletChip = walletChipHTML(
+ { ...a, solana_address: a.solana_address || a.meta?.solana_address || a.wallet_address || null },
+ { isOwner: true, showPending: false },
+ );
const onchainBadge = onchainBadgeHTML(a);
const pumpMint = a.meta?.pumpfun?.mint || a.meta?.token?.mint;
const created = a.created_at ? relTime(a.created_at) : '';
@@ -241,8 +250,8 @@ function renderAgentCards(host, agents, avatars) {
${pumpMint ? `<span class="ame-tag pump">pump.fun</span>` : ''}
${created ? `<span class="ame-meta-text">${esc(created)}</span>` : ''}
</div>
- ${wallet
- ? `<div class="ame-wallet">${esc(truncAddr(wallet, 8, 6))}</div>`
+ ${walletChip
+ ? `<div class="ame-wallet">${walletChip}</div>`
: `<button class="ame-btn small" data-action="create-wallet" data-agent-id="${esc(a.id)}">Create wallet</button>`}
</div>
</div>
@@ -269,6 +278,8 @@ function renderAgentCards(host, agents, avatars) {
`;
}).join('');
+ wireWalletChips(host);
+
host.addEventListener('click', e => {
const btn = e.target.closest('[data-action]');
if (!btn) return;
@@ -511,12 +522,16 @@ async function handleCreateWallet(btn) {
});
const d = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(d.message || d.error || `provision failed (${r.status})`);
- btn.replaceWith(
- Object.assign(document.createElement('div'), {
- className: 'ame-wallet',
- textContent: truncAddr(d.wallet_address, 8, 6),
- }),
- );
+ // Swap the CTA for the same owner-tier wallet chip the cards render, so a
+ // freshly-provisioned wallet looks identical to a pre-existing one.
+ const walletDiv = document.createElement('div');
+ walletDiv.className = 'ame-wallet';
+ walletDiv.innerHTML = walletChipHTML(
+ { id: agentId, solana_address: d.wallet_address },
+ { isOwner: true, showPending: false },
+ ) || esc(truncAddr(d.wallet_address, 8, 6));
+ btn.replaceWith(walletDiv);
+ wireWalletChips(walletDiv);
toast('Agent wallet created');
} catch (e) {
btn.disabled = false;
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 00e4f613f..fa9c1d42b 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -25,6 +25,7 @@ const solanaWeb3 = {
clusterApiUrl,
};
import { onchainBadgeEl } from './shared/onchain-badge.js';
+import { walletChipEl } from './shared/agent-wallet-chip.js';
import { mountValidationBadge } from './shared/validation-badge.js';
import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
@@ -582,8 +583,32 @@ function render(agent) {
$('ad-svc-count').textContent = `${agent.services?.length || 0} configured`;
$('ad-svc-count2').textContent = String(agent.services?.length || 0);
- $('ad-holdings-addr').textContent = shortAddr(agent.wallet);
- $('ad-holdings-addr').dataset.full = agent.wallet;
+ // Universal wallet chip — the same vanity-aware component every other surface
+ // renders, so the agent's custodial Solana address (and its vanity styling)
+ // looks and behaves identically here: copy + explorer for everyone, plus the
+ // owner-only "✦ Vanity" entry point into the wallet hub via isOwner. The
+ // Solana address lives on meta.solana_address (agent.wallet is the EVM address,
+ // which the Solana chip rejects), so feed the chip the real Solana key.
+ {
+ const host = $('ad-holdings-chip');
+ const wMeta = agent.rawMetadata?.meta || {};
+ if (host) {
+ host.replaceChildren();
+ const chip = walletChipEl(
+ {
+ id: agent.id,
+ name: agent.name,
+ solana_address: wMeta.solana_address || null,
+ avatar_thumbnail_url: agent.avatar || '',
+ solana_vanity_prefix: wMeta.solana_vanity_prefix || null,
+ solana_vanity_suffix: wMeta.solana_vanity_suffix || null,
+ meta: wMeta,
+ },
+ { isOwner: !!agent.isOwner, showPending: true, link: true },
+ );
+ if (chip) host.appendChild(chip);
+ }
+ }
$('ad-holdings-sol').textContent = String(agent.solBalance ?? 0);
// A re-render (avatar refresh) clears the token body below; tear down any
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 30f1c8907..f3bb29b3a 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -2,6 +2,7 @@ import { AvatarCreator } from './avatar-creator.js';
import { saveRemoteGlbToAccount } from './account.js';
import { apiFetch } from './api.js';
import { openAvatarPicker } from './avatar-gallery-picker.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
import { log } from './shared/log.js';
import { isValidGlbMagic } from './shared/glb-magic.js';
@@ -139,6 +140,7 @@ function render() {
$('panel-persona').classList.add('active');
$('agent-title').textContent = `Edit Agent: ${agentData.name || 'Untitled'}`;
$('back-link').href = `/agents/${agentData.id}`;
+ renderHeaderWalletChip();
// Persona
$('f-name').value = agentData.name || '';
@@ -157,6 +159,31 @@ function render() {
$('f-strategy').value = formatStrategy(agentData.meta?.strategy);
}
+// Render the shared custodial-wallet chip in the edit header. This page is the
+// owner's own agent (the GET above 401s anyone who isn't signed in, and the
+// record carries an authoritative `is_owner` flag), so the chip shows the owner
+// affordances — the "✦ Vanity" entry point routes to the wallet hub where the
+// money-safe grind/swap lives. We never inline withdraw/launch UI here.
+function renderHeaderWalletChip() {
+ const header = document.querySelector('.edit-header');
+ if (!header) return;
+ let host = $('agent-wallet-chip');
+ if (!host) {
+ host = document.createElement('div');
+ host.id = 'agent-wallet-chip';
+ host.className = 'edit-header-wallet';
+ header.appendChild(host);
+ }
+ // showPending so the header always communicates that every agent has a wallet,
+ // even in the brief window before provisioning completes.
+ host.innerHTML = walletChipHTML(agentData, {
+ isOwner: !!agentData.is_owner,
+ showPending: true,
+ link: true,
+ });
+ wireWalletChips(host);
+}
+
function formatStrategy(strategy) {
if (strategy == null) return '';
if (typeof strategy === 'string') return strategy;
diff --git a/src/agent-home.js b/src/agent-home.js
index 445602e1f..1979780ba 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -16,6 +16,7 @@ import { mountAgentVanityGrinderCard } from './agent-vanity-grinder.js';
import { mountAgentEthVanityCard } from './agent-eth-vanity-card.js';
import { mountAgentOnchainCard } from './agent-onchain-card.js';
import { mountClaimsPanel } from './agent-home-claims.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const ACTION_ICONS = {
[ACTION_TYPES.SPEAK]: '💬',
@@ -83,6 +84,25 @@ export class AgentHome {
_buildPanel() {
const id = this.identity;
const skills = id.skills || [];
+
+ // Shared agent-wallet chip for the identity card. Default-deny ownership:
+ // owner-tier (vanity entry point) only when ownership is known true, else a
+ // non-owner Tip action — never show owner controls to a visitor. Reads the
+ // Solana address from the identity (solana_address / meta.solana_address);
+ // renders nothing when the agent has no custodial Solana wallet yet.
+ const walletOwner = this.isOwner !== null ? this.isOwner : id.isOwner;
+ const walletChip = walletChipHTML(
+ {
+ id: id.id,
+ name: id.name,
+ solana_address: id.solana_address || id.meta?.solana_address || '',
+ solana_vanity_prefix: id.solana_vanity_prefix || id.meta?.solana_vanity_prefix || null,
+ solana_vanity_suffix: id.solana_vanity_suffix || id.meta?.solana_vanity_suffix || null,
+ avatar_thumbnail_url: id.avatarUrl || id.image || '',
+ meta: id.meta || {},
+ },
+ { isOwner: walletOwner === true, showPending: false },
+ );
const panel = document.createElement('div');
panel.className = 'agent-home-panel';
panel.innerHTML = `
@@ -123,6 +143,7 @@ export class AgentHome {
: `<button class="agent-home-address agent-home-address--cta" id="agent-home-address" type="button" title="Connect wallet to register on-chain" aria-label="Connect wallet to register on-chain">no wallet</button>`
}
</div>
+ ${walletChip ? `<div class="agent-home-wallet-chip" id="agent-home-wallet-chip">${walletChip}</div>` : ''}
<p
class="agent-home-description agent-home-editable"
id="agent-home-description"
@@ -179,6 +200,8 @@ export class AgentHome {
this.container.appendChild(panel);
this._panel = panel;
+ wireWalletChips(panel.querySelector('#agent-home-wallet-chip'));
+
let _pumpMounted = false;
const mountPumpIfReady = () => {
if (_pumpMounted) return;
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index c58f5763e..c8103f569 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -71,6 +71,19 @@ const STYLE = `
.awh-btn:disabled { opacity: var(--disabled-opacity, .4); cursor: var(--disabled-cursor, not-allowed); }
.awh-btn--primary { background: var(--accent, #fff); color: #0a0a0a; border-color: var(--accent, #fff); font-weight: 600; }
.awh-btn--primary:hover:not(:disabled) { background: color-mix(in srgb, var(--accent,#fff) 88%, #000); }
+.awh-btn--danger { background: color-mix(in srgb, var(--danger,#ef4444) 14%, transparent); color: var(--danger,#ef4444); border-color: color-mix(in srgb, var(--danger,#ef4444) 40%, transparent); font-weight: 600; }
+.awh-btn--danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#ef4444) 22%, transparent); border-color: color-mix(in srgb, var(--danger,#ef4444) 60%, transparent); }
+.awh-freeze-card { margin-bottom: var(--space-3,12px); }
+.awh-freeze-card.is-frozen { border-color: color-mix(in srgb, var(--danger,#ef4444) 45%, transparent); background: color-mix(in srgb, var(--danger,#ef4444) 8%, transparent); }
+.awh-freeze-row { display: flex; align-items: center; gap: var(--space-3,12px); justify-content: space-between; flex-wrap: wrap; }
+.awh-freeze-copy { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.awh-freeze-copy strong { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); }
+.awh-freeze-copy span { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); line-height: 1.45; }
+.awh-freeze-row .awh-btn { flex: 0 0 auto; }
+.awh-warn-irrev { margin-top: var(--space-3,12px); padding: 9px 12px; border-radius: var(--radius-md,10px); font-size: var(--text-sm,.764rem); line-height: 1.45; color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 9%, transparent); border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent); }
+.awh-dest-tag { display: inline-block; margin-left: 8px; font-size: var(--text-2xs,.6875rem); font-weight: 600; padding: 2px 8px; border-radius: var(--radius-pill,999px); white-space: nowrap; }
+.awh-dest-tag.ok { color: var(--ok,#34d399); background: color-mix(in srgb, var(--ok,#34d399) 14%, transparent); border: 1px solid color-mix(in srgb, var(--ok,#34d399) 34%, transparent); }
+.awh-dest-tag.warn { color: var(--danger,#ef4444); background: color-mix(in srgb, var(--danger,#ef4444) 12%, transparent); border: 1px solid color-mix(in srgb, var(--danger,#ef4444) 34%, transparent); }
.awh-mono { font-family: var(--font-mono, ui-monospace, monospace); }
.awh-empty { color: var(--ink-dim, #888); font-size: var(--text-sm, .764rem); padding: var(--space-3,12px) 0; }
.awh-placeholder { display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-3,12px); }
diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.js
index 70e4290fa..c9790aadb 100644
--- a/src/agent-wallet-hub/tabs/deposit.js
+++ b/src/agent-wallet-hub/tabs/deposit.js
@@ -309,7 +309,8 @@ registerWalletTab({
<div class="awh-dep-addr" title="${escapeHtml(state.address)}">${escapeHtml(state.address)}</div>
</div>
<div class="awh-dep-actions">
- <button class="awh-btn" type="button" data-act="copy" aria-label="Copy wallet address">Copy address</button>
+ <button class="awh-btn awh-btn--primary" type="button" data-act="tip" aria-label="Tip from your connected wallet">◎ Tip from your wallet</button>
+ <button class="awh-btn" type="button" data-act="copy" aria-label="Copy wallet address">Copy address</button>
<a class="awh-btn" href="${escapeHtml(explorerAddressUrl(state.address, net))}" target="_blank" rel="noopener">Explorer ↗</a>
</div>
@@ -344,6 +345,23 @@ registerWalletTab({
toast(ok ? 'Address copied' : 'Copy failed — select it manually');
});
+ panel.querySelector('[data-act="tip"]')?.addEventListener('click', async () => {
+ try {
+ const { openTipModal } = await import('../../shared/agent-tip-modal.js');
+ openTipModal(
+ {
+ solana_address: state.address,
+ name: ctx.agent?.name,
+ avatar_thumbnail_url: ctx.agent?.avatar_thumbnail_url,
+ meta: ctx.agent?.meta,
+ },
+ { network: ctx.getNetwork(), onSent: () => { state.baselineSol = null; poll(); } },
+ );
+ } catch {
+ toast('Could not open the tip dialog — copy the address and send from any wallet');
+ }
+ });
+
const amountInput = panel.querySelector('[data-input="amount"]');
amountInput?.addEventListener('input', onAmountInput);
}
diff --git a/src/agent-wallet-hub/tabs/withdraw.js b/src/agent-wallet-hub/tabs/withdraw.js
index 007d3fce5..96a0b1808 100644
--- a/src/agent-wallet-hub/tabs/withdraw.js
+++ b/src/agent-wallet-hub/tabs/withdraw.js
@@ -291,15 +291,28 @@ registerWalletTab({
function renderConfirm() {
const it = state.intent;
+ // Allowlist awareness: if the owner has set an allowlist, show whether this
+ // destination is on it. The server enforces the allowlist regardless — this
+ // is the in-form signal the audit flagged as missing.
+ const allow = Array.isArray(state.limits?.limits?.withdraw_allowlist)
+ ? state.limits.limits.withdraw_allowlist
+ : null;
+ let destBadge = '';
+ if (allow && allow.length) {
+ destBadge = allow.includes(it.destination)
+ ? '<span class="awh-dest-tag ok">✓ allowlisted</span>'
+ : '<span class="awh-dest-tag warn">⚠ not on allowlist — this will be rejected</span>';
+ }
return `
<div class="awh-card">
<div class="awh-sum">
<div class="r"><span>Asset</span><span class="v">${esc(it.assetName)}</span></div>
<div class="r"><span>Amount</span><span class="v">${it.isMax ? 'Max — ' : ''}${esc(fmtAmount(it.amount, it.decimals))} ${esc(it.assetName)}</span></div>
- <div class="r"><span>To</span><span class="v">${esc(it.destination)}</span></div>
+ <div class="r"><span>To</span><span class="v awh-mono" style="word-break:break-all;">${esc(it.destination)}${destBadge}</span></div>
<div class="r"><span>Network</span><span class="v">${esc(ctx.getNetwork())}</span></div>
</div>
${it.kind === 'SOL' && it.isMax ? '<div class="awh-note">A little SOL is kept back to cover rent + network fees.</div>' : ''}
+ <div class="awh-warn-irrev" role="note">⚠ Crypto transfers are final. Once submitted, this cannot be undone or reversed — double-check the destination address.</div>
<div class="awh-err" id="awh-cf-err" hidden></div>
<div class="awh-actions">
<button class="awh-btn" id="awh-back" type="button" style="flex:1;" ${state.phase === 'sending' ? 'disabled' : ''}>Back</button>
@@ -412,6 +425,10 @@ registerWalletTab({
};
state.phase = 'confirm';
render();
+ // Best-effort: pull the spend limits so the confirm step can show the
+ // allowlist-match badge. Non-blocking — the irreversibility warning and
+ // server-side enforcement do not depend on it.
+ if (state.limits === null) loadLimits();
});
}
@@ -468,7 +485,20 @@ registerWalletTab({
const spent = state.limits.spent_today_usd ?? 0;
const allow = Array.isArray(lim.withdraw_allowlist) ? lim.withdraw_allowlist : [];
const overDaily = lim.daily_usd != null && spent >= lim.daily_usd;
+ const frozen = lim.frozen === true;
return `
+ <div class="awh-card awh-freeze-card${frozen ? ' is-frozen' : ''}">
+ <div class="awh-freeze-row">
+ <div class="awh-freeze-copy">
+ <strong>${frozen ? '🔒 Wallet frozen' : 'Wallet active'}</strong>
+ <span>${frozen
+ ? 'Autonomous spending (trades, snipes, payments) is paused. You can still withdraw funds out.'
+ : 'Freeze to instantly pause all autonomous spending. Withdrawals stay available.'}</span>
+ </div>
+ <button class="awh-btn ${frozen ? 'awh-btn--primary' : 'awh-btn--danger'}" id="awh-freeze-btn" type="button"
+ aria-pressed="${frozen}">${frozen ? 'Unfreeze' : 'Freeze wallet'}</button>
+ </div>
+ </div>
<div class="awh-card">
<div class="awh-chips">
<span class="awh-chip${overDaily ? ' alert' : ''}">Spent today: ${esc(formatUsd(spent) || '$0.00')}</span>
@@ -508,6 +538,27 @@ registerWalletTab({
const allowState = (Array.isArray(lim.withdraw_allowlist) ? lim.withdraw_allowlist : []).slice();
const errEl = panel.querySelector('#awh-lim-err');
+ // Freeze toggle — one tap, applied immediately (no Save). Freezing is the
+ // safe direction; unfreezing resumes autonomous spending so we confirm it.
+ const freezeBtn = panel.querySelector('#awh-freeze-btn');
+ freezeBtn?.addEventListener('click', async () => {
+ const currentlyFrozen = lim.frozen === true;
+ if (currentlyFrozen && !confirm('Resume autonomous spending? The agent will be able to trade, snipe and pay from this wallet again.')) return;
+ freezeBtn.disabled = true;
+ freezeBtn.innerHTML = '<span class="awh-spin"></span>' + (currentlyFrozen ? 'Unfreezing…' : 'Freezing…');
+ const res = await call(`${base('limits')}?network=${ctx.getNetwork()}`, { method: 'PUT', body: { frozen: !currentlyFrozen } });
+ if (destroyed) return;
+ if (!res.ok) {
+ freezeBtn.disabled = false;
+ freezeBtn.textContent = currentlyFrozen ? 'Unfreeze' : 'Freeze wallet';
+ errEl.hidden = false; errEl.textContent = res.message;
+ return;
+ }
+ state.limits = res.data;
+ toast(currentlyFrozen ? 'Wallet unfrozen' : 'Wallet frozen — spending paused');
+ render();
+ });
+
function repaint() {
const ul = panel.querySelector('#awh-allow');
if (!ul) return;
@@ -559,7 +610,9 @@ registerWalletTab({
const res = await call(`${base('limits')}?network=${ctx.getNetwork()}`);
if (destroyed) return;
state.limits = res.ok ? res.data : { error: res.message };
- if (state.view === 'limits') render();
+ // Re-render on the limits view (full panel) or the withdraw confirm step,
+ // where the freshly-loaded allowlist drives the destination badge.
+ if (state.view === 'limits' || state.phase === 'confirm') render();
}
// ── Activity view (custody audit trail) ─────────────────────────────────
diff --git a/src/agent-wallet/ownership.js b/src/agent-wallet/ownership.js
new file mode 100644
index 000000000..592819b4c
--- /dev/null
+++ b/src/agent-wallet/ownership.js
@@ -0,0 +1,104 @@
+/**
+ * Ownership resolution for the agent-wallet affordance.
+ *
+ * One agent, one owner. A surface that lists agents/avatars (a marketplace grid,
+ * a leaderboard, a world inspect panel) needs to know, per record, whether the
+ * signed-in viewer owns it — that's the only thing that decides whether the
+ * affordance renders the owner hub (vanity/withdraw) or the visitor view
+ * (tip/pay/fork).
+ *
+ * Server-rendered detail endpoints already carry an authoritative `is_owner`
+ * (api/agents/:id and the marketplace detail). But the cacheable public list
+ * (GET /api/marketplace/agents) is shared across viewers, so it cannot embed a
+ * per-viewer flag — it ships `author_id` instead. This module fetches the
+ * current user id ONCE per page and lets a surface stamp `is_owner` onto those
+ * records client-side.
+ *
+ * Security note: this flag only chooses which buttons render. Every owner-only
+ * action (withdraw, vanity grind/assign, limit changes) is re-authorized
+ * server-side against the session, so a tampered flag grants nothing.
+ */
+
+let mePromise = null;
+
+/**
+ * The signed-in viewer's user id, or null when anonymous. Cached for the page
+ * lifetime — the first card that needs it pays the request, the rest are free.
+ * A transient failure resolves to null (treated as anonymous) and is retried on
+ * the next call.
+ */
+export async function currentUserId() {
+ if (mePromise) return mePromise;
+ mePromise = (async () => {
+ try {
+ const r = await fetch('/api/auth/me', { credentials: 'include' });
+ if (!r.ok) return null;
+ const body = await r.json().catch(() => null);
+ return body?.user?.id || null;
+ } catch {
+ mePromise = null; // allow a later retry after a transient failure
+ return null;
+ }
+ })();
+ return mePromise;
+}
+
+/** Forget the cached viewer (call after sign-in / sign-out). */
+export function resetOwnershipCache() {
+ mePromise = null;
+}
+
+/** The owner id carried by any supported record shape, or null. */
+function ownerIdOf(record) {
+ if (!record || typeof record !== 'object') return null;
+ return (
+ record.author_id ??
+ record.owner_id ??
+ record.user_id ??
+ record.meta?.user_id ??
+ null
+ );
+}
+
+/**
+ * Resolve ownership for one record. Trusts an explicit server `is_owner` /
+ * `isOwner` when present; otherwise compares the record's owner id to the
+ * signed-in viewer. Returns the boolean (and does not mutate).
+ */
+export async function isOwnedByViewer(record) {
+ if (record == null) return false;
+ if (typeof record.is_owner === 'boolean') return record.is_owner;
+ if (typeof record.isOwner === 'boolean') return record.isOwner;
+ const owner = ownerIdOf(record);
+ if (!owner) return false;
+ const me = await currentUserId();
+ return !!me && owner === me;
+}
+
+/**
+ * Stamp `is_owner` onto every record in a list in place (one /auth/me fetch for
+ * the whole list) and return the same array. The one-liner a card grid calls
+ * before mounting the affordance:
+ *
+ * await markOwnership(agents);
+ * for (const a of agents) mountAgentWallet({ mount: cardWalletEl(a), agent: a, tier: 'compact' });
+ */
+export async function markOwnership(records) {
+ if (!Array.isArray(records) || records.length === 0) return records || [];
+ // Records that already carry a server flag don't need the viewer at all.
+ const needsViewer = records.some(
+ (r) => r && typeof r.is_owner !== 'boolean' && typeof r.isOwner !== 'boolean' && ownerIdOf(r),
+ );
+ const me = needsViewer ? await currentUserId() : null;
+ for (const r of records) {
+ if (!r || typeof r !== 'object') continue;
+ if (typeof r.is_owner === 'boolean') continue;
+ if (typeof r.isOwner === 'boolean') {
+ r.is_owner = r.isOwner;
+ continue;
+ }
+ const owner = ownerIdOf(r);
+ r.is_owner = !!me && !!owner && owner === me;
+ }
+ return records;
+}
diff --git a/src/avatar-gallery-picker.js b/src/avatar-gallery-picker.js
index 807cf6fec..fcb82fe26 100644
--- a/src/avatar-gallery-picker.js
+++ b/src/avatar-gallery-picker.js
@@ -18,6 +18,7 @@
import './avatar-gallery-picker.css';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { walletChipHTML } from './shared/agent-wallet-chip.js';
const PAGE_SIZE = 24;
@@ -428,6 +429,10 @@ export class AvatarGalleryPicker {
// The card is a <button>, so render a non-link badge (no nested anchor /
// click conflict). The explorer link lives on the agent's own pages.
const onchain = onchainBadgeHTML(a, { link: false, size: 'sm', showChain: false });
+ // The card is a <button>; render the wallet chip as a non-interactive,
+ // vanity-aware badge (link:false → no nested copy/explorer controls). It
+ // no-ops until the avatar record carries a custodial solana_address.
+ const wallet = walletChipHTML(a, { isOwner: false, showPending: false, link: false });
card.innerHTML = `
<div class="agp-card-thumb">${thumb}</div>
@@ -435,6 +440,7 @@ export class AvatarGalleryPicker {
<div class="agp-card-name">${esc(a.name || 'Untitled')}</div>
<div class="agp-card-meta">
${onchain}
+ ${wallet}
${tags}
${views ? `<span class="agp-card-chip">${compact.format(views)} views</span>` : ''}
</div>
diff --git a/src/avatar-page.js b/src/avatar-page.js
index abec873b7..13a1f565c 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -14,6 +14,7 @@ import { log } from './shared/log.js';
import { emptyStateHTML, errorStateHTML } from './shared/state-kit.js';
import { mountViewSwitcher } from './view-switcher.js';
import { PoseStage, loadPoseManifest } from './avatar-pose.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -196,6 +197,17 @@ async function fetchSkills() {
// ── Render ────────────────────────────────────────────────────────────
+// The avatar's bound agent custodial wallet, rendered with the shared chip.
+// owner_id is only present on the GET response when the viewer owns the avatar
+// (the API strips it for everyone else), so it's a reliable owner signal — the
+// owner gets the vanity entry point, everyone else gets the Tip action. Renders
+// nothing when the bound agent has no wallet yet (showPending:false), which is
+// fine: the avatar itself is an asset and the page already has a fork CTA.
+function walletRowHTML() {
+ const chip = walletChipHTML(avatar, { isOwner: !!avatar.owner_id, showPending: false });
+ return chip ? `<div class="av-wallet-row" id="av-wallet-row">${chip}</div>` : '';
+}
+
function renderShell(glbUrl) {
const tagsHtml = (avatar.tags || [])
.map((t) => `<a class="av-tag" href="/marketplace?tag=${encodeURIComponent(t)}">${esc(t)}</a>`)
@@ -272,6 +284,7 @@ function renderShell(glbUrl) {
<div class="av-source-tag">${avatar.demo ? 'Curated · Public Domain' : 'Community avatar'}</div>
${byLine}
${tagsHtml ? `<div class="av-tags">${tagsHtml}</div>` : ''}
+ ${walletRowHTML()}
</div>
<div class="av-cta-talk-row">
<button class="av-cta-talk" id="av-talk" type="button" aria-label="Talk to ${esc(avatar.name)}">
@@ -416,6 +429,8 @@ function renderShell(glbUrl) {
</div>
`;
+ wireWalletChips($('av-wallet-row'));
+
const viewer = $('av-viewer');
viewer?.addEventListener('load', () => {
$('av-stage-loading')?.remove();
@@ -1738,15 +1753,21 @@ async function loadUsedBy() {
const badge = a.onchain
? `<span class="av-used-by-badge" title="Registered on-chain">on-chain</span>`
: '';
+ // Each agent here is an agent surface — render the shared wallet chip
+ // (tip for visitors, vanity entry for the owner). Hidden when the
+ // used-by row carries no address, so we never show a misleading state.
+ const chip = walletChipHTML(a, { isOwner: false, showPending: false });
return `<a class="av-used-by-card" href="${esc(a.url)}" title="${esc(a.name)}">
${thumb}
<div class="av-used-by-meta">
<span class="av-used-by-name">${esc(a.name)}</span>
${badge}
</div>
+ ${chip ? `<div class="av-used-by-wallet">${chip}</div>` : ''}
</a>`;
})
.join('');
+ wireWalletChips(grid);
}
// ── Forks (GitHub-style network) ──────────────────────────────────────
diff --git a/src/characters.js b/src/characters.js
index ebaf94015..118dc17a6 100644
--- a/src/characters.js
+++ b/src/characters.js
@@ -5,7 +5,7 @@
* Each card links to /character/:id. Supports search, sort, and load-more.
*/
-import { walletChipHTML } from './shared/agent-wallet-chip.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
let state = { cursor: null, loading: false, sort: 'new', q: '' };
@@ -146,6 +146,11 @@ async function fetchCharacters(reset = false) {
grid.insertAdjacentHTML('beforeend', chars.map(cardHtml).join(''));
}
+ // Wire the wallet chips' copy + Tip actions on the freshly-injected cards.
+ // This is a public gallery, so cards default to isOwner:false → the ◎ Tip
+ // action; wiring is idempotent per chip, so re-running it on append is safe.
+ wireWalletChips(grid);
+
state.cursor = data.next_cursor || null;
if (loadMore) loadMore.style.display = state.cursor ? 'flex' : 'none';
if (loadBtn) loadBtn.disabled = false;
diff --git a/src/collection.js b/src/collection.js
index b9945b9d2..b9f4c3561 100644
--- a/src/collection.js
+++ b/src/collection.js
@@ -2,6 +2,8 @@
* My Collection page — shows all purchased skills and active subscriptions.
*/
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
+
const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
@@ -40,6 +42,23 @@ function skillCard(p) {
const priceLine = p.amount ? `<span class="badge badge-muted">${fmtAmount(p.amount, p.currency_mint)}</span>` : '';
+ // Wallet chip for the publishing agent, only when the purchase record carries
+ // its custodial Solana address. The buyer doesn't own the publisher agent, so
+ // the chip renders isOwner:false (◎ Tip), letting the holder tip the creator
+ // straight from their collection. getWalletStatus returns null without an
+ // address, so showPending:false means the chip simply doesn't render.
+ const agentRecord = {
+ id: p.agent_id,
+ name: p.agent_name,
+ solana_address: p.solana_address || p.agent_solana_address || null,
+ solana_vanity_prefix: p.solana_vanity_prefix || null,
+ solana_vanity_suffix: p.solana_vanity_suffix || null,
+ avatar_thumbnail_url: p.agent_thumbnail || null,
+ };
+ const walletLine = agentRecord.solana_address
+ ? `<div class="col-card-wallet" style="margin-top:8px">${walletChipHTML(agentRecord, { isOwner: false, showPending: false })}</div>`
+ : '';
+
return `
<article class="col-card">
<div class="col-card-header">
@@ -49,6 +68,7 @@ function skillCard(p) {
<div class="col-card-agent">${p.agent_name || 'Unknown agent'}</div>
</div>
</div>
+ ${walletLine}
<div class="col-card-badges">${kindBadge}${priceLine}</div>
${nftLine}
<div class="col-card-footer">
@@ -212,6 +232,10 @@ async function load() {
? purchases.map(skillCard).join('')
: emptyState('skills');
+ // Wire the publishing agents' wallet chips (copy + ◎ Tip) on the freshly
+ // rendered skill cards. No-op for purchases without a wallet address.
+ wireWalletChips(skillsGrid);
+
subsGrid.innerHTML = subs.length
? subs.map(subCard).join('')
: emptyState('subscriptions');
diff --git a/src/erc8004/user-profile.js b/src/erc8004/user-profile.js
index 53c38023e..4e7cc1721 100644
--- a/src/erc8004/user-profile.js
+++ b/src/erc8004/user-profile.js
@@ -11,6 +11,29 @@ import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';
import { listAgentsByOwner, fetchAgentMetadata, findAvatar3D } from './queries.js';
import { CHAIN_META, supportedChainIds } from './chain-meta.js';
import { resolveURI } from '../ipfs.js';
+import { walletChipHTML, wireWalletChips } from '../shared/agent-wallet-chip.js';
+
+const SOLANA_BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// Pull a Solana custodial/mint address out of ERC-8004 agent metadata. Agents
+// registered on Solana carry it under registrations[].onchain (family 'solana')
+// as `contract_or_mint`, or sometimes a top-level solana_address. Returns a
+// base58 address or '' so the wallet chip stays silent for EVM-only agents.
+function solanaAddressFromMetadata(data) {
+ if (!data || typeof data !== 'object') return '';
+ const direct = data.solana_address || data.solanaAddress;
+ if (typeof direct === 'string' && SOLANA_BASE58_RE.test(direct)) return direct;
+ const regs = Array.isArray(data.registrations) ? data.registrations : [];
+ for (const reg of regs) {
+ const oc = reg?.onchain || reg || {};
+ const fam = String(oc.family || reg?.family || '').toLowerCase();
+ const candidate = oc.contract_or_mint || oc.address || oc.mint;
+ if (fam === 'solana' && typeof candidate === 'string' && SOLANA_BASE58_RE.test(candidate)) {
+ return candidate;
+ }
+ }
+ return '';
+}
const esc = (s) =>
String(s ?? '').replace(
@@ -111,6 +134,7 @@ export async function mountUserProfile(rootEl, address) {
allCards.sort((a, b) => Number(b.agentId) - Number(a.agentId));
grid.innerHTML = allCards.map(renderCard).join('');
+ wireWalletChips(grid);
// Lazy-load thumbnails via model-viewer after card DOM is present
grid.querySelectorAll('.up-card[data-glb]').forEach((card) => {
@@ -141,6 +165,7 @@ async function resolveAgentCard({ chainId, agentId, address }) {
description: '',
image: '',
glb: '',
+ solanaAddress: '',
};
try {
@@ -167,15 +192,24 @@ async function resolveAgentCard({ chainId, agentId, address }) {
description: data.description || '',
image: data.image || '',
glb,
+ solanaAddress: solanaAddressFromMetadata(data),
};
} catch {
return base;
}
}
-function renderCard({ chainId, agentId, name, description, image, glb }) {
+function renderCard({ chainId, agentId, name, description, image, glb, solanaAddress }) {
const meta = CHAIN_META[chainId];
const agentUrl = `/a/${chainId}/${agentId}`;
+ // Shared wallet chip when the on-chain agent also has a Solana custodial
+ // address. This is a public profile with no reliable viewer-ownership signal,
+ // so isOwner:false — visitors get the Tip action, never owner controls.
+ // Renders nothing for EVM-only agents (showPending:false).
+ const walletChip = walletChipHTML(
+ { id: `${chainId}/${agentId}`, name, solana_address: solanaAddress || '', avatar_thumbnail_url: image || '' },
+ { isOwner: false, showPending: false },
+ );
const hasThumb = !!glb || !!image;
const thumbContent = glb
? '' // filled lazily
@@ -197,6 +231,7 @@ function renderCard({ chainId, agentId, name, description, image, glb }) {
<div class="up-card-chain">${esc(meta?.shortName || chainId)}</div>
<a href="${esc(agentUrl)}" class="up-card-name">${esc(name)}</a>
${description ? `<p class="up-card-desc">${esc(description)}</p>` : ''}
+ ${walletChip ? `<div class="up-card-wallet">${walletChip}</div>` : ''}
<div class="up-card-footer">
<span class="up-card-id">#${agentId}</span>
<a href="${esc(editUrl)}" class="up-card-edit">Edit →</a>
diff --git a/src/irl.js b/src/irl.js
index 4b2d139ad..0897d9ed8 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -75,6 +75,7 @@ import { openMapPlacePicker } from './irl/map-place.js';
import { openPrivacyCenter, maybeShowFirstRunDisclosure, getDiscoveryPrecision } from './irl/privacy-center.js';
import { loadLeaflet } from './shared/leaflet-loader.js';
import { initDiscovery } from './irl/discovery.js';
+import { walletChipEl, hasWallet } from './shared/agent-wallet-chip.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -4529,6 +4530,21 @@ function _applyCard(card, pin) {
parts.push(_repStripHTML(card.reputation));
parts.push(_servicesHTML(card.services));
body.innerHTML = parts.join('');
+
+ // The agent's custodial Solana wallet — the same chip every other surface
+ // shows, so a tapped agent's identity reads identically in the world. The
+ // body is rebuilt on each tap (innerHTML above), so appending here can't
+ // duplicate. isOwner reflects whether this device placed the pin (gold
+ // "your agent" ownership); a stranger sees a Tip action, never owner
+ // controls. No-op unless the card carries a wallet (showPending:false).
+ if (hasWallet(agent)) {
+ const chip = walletChipEl(agent, { isOwner: isOwnRoomPin(pin), showPending: false });
+ if (chip) {
+ chip.classList.add('irl-card-wallet');
+ chip.style.marginTop = '10px';
+ body.appendChild(chip);
+ }
+ }
}
// Prefer the card's resolved x402 endpoint for the footer Pay button.
diff --git a/src/launch-detail.js b/src/launch-detail.js
index e60db2c97..5b05cb7c7 100644
--- a/src/launch-detail.js
+++ b/src/launch-detail.js
@@ -35,6 +35,7 @@ import {
relTime,
verifiedBadge,
} from './trader-format.js';
+import { walletChipEl } from './shared/agent-wallet-chip.js';
const GRADUATION_CAP_USD = 69_000; // pump.fun bonding-curve graduation threshold
const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -1090,6 +1091,20 @@ function renderAgent() {
const body = el('div', { class: 'ld-agent-body' }, [head]);
+ // The launching agent's custodial Solana wallet — vanity-aware, copyable,
+ // read-only for visitors. agent_authority (the on-chain signer) backstops the
+ // agent record's own solana_address. Owner-only actions live in the wallet hub.
+ const walletChip = walletChipEl(
+ {
+ ...agent,
+ id: agent.id,
+ solana_address:
+ agent.solana_address || agent.meta?.solana_address || state.detail.agent_authority || null,
+ },
+ { isOwner: false, showPending: false, link: true },
+ );
+ if (walletChip) body.appendChild(walletChip);
+
if (agent.description) {
body.appendChild(el('p', { class: 'ld-agent-desc', text: agent.description }));
}
diff --git a/src/launches.js b/src/launches.js
index 3ee585b92..ba55d27a4 100644
--- a/src/launches.js
+++ b/src/launches.js
@@ -19,6 +19,7 @@
*/
import { mountCoinStatus } from './pump/coin-status-card.js';
+import { walletChipEl } from './shared/agent-wallet-chip.js';
import { createLogger } from './shared/log.js';
const log = createLogger('launches');
@@ -523,6 +524,20 @@ function launchCard(launch, index, { featured = false } = {}) {
'aria-label': `Open ${launch.symbol ? `$${launch.symbol}` : launch.name || 'coin'} profile`,
});
+ // The launching agent's custodial wallet, shown read-only as a vanity-aware
+ // badge. agent_authority is the on-chain signer = the agent's Solana wallet,
+ // so it backstops the agent record's own solana_address. link:false keeps it a
+ // non-interactive badge so it never fights the stretched whole-card link above.
+ const walletChip = walletChipEl(
+ {
+ ...(launch.agent || {}),
+ id: launch.agent?.id,
+ solana_address:
+ launch.agent?.solana_address || launch.agent?.meta?.solana_address || launch.agent_authority || null,
+ },
+ { isOwner: false, showPending: false, link: false },
+ );
+
const card = el('article', { class: `lx-card${featured ? ' lx-card-featured' : ''}`, 'data-mint': launch.mint }, [
cardLink,
featured ? el('span', { class: 'lx-feat-tag', text: 'Latest' }) : null,
@@ -532,6 +547,7 @@ function launchCard(launch, index, { featured = false } = {}) {
market,
badges,
agentChip(launch.agent),
+ walletChip,
el('div', { class: 'lx-card-actions' }, actions),
el('span', { class: 'lx-mint', text: launch.mint, title: launch.mint }),
el('div', { class: 'lx-oracle-badge', 'aria-hidden': 'true' }),
diff --git a/src/leaderboard.js b/src/leaderboard.js
index 37b540e18..ed1d93838 100644
--- a/src/leaderboard.js
+++ b/src/leaderboard.js
@@ -11,6 +11,7 @@ import {
escapeHtml, fmtSol, fmtUsd, fmtPct, pnlClass, shortAddr, holdTime, relTime,
identicon, verifiedBadge,
} from './trader-format.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const API = '/api/sniper/leaderboard';
const REFRESH_MS = 20_000;
@@ -104,7 +105,7 @@ function rowMarkup(r) {
<img class="lb-avatar" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.src='${identicon(r.agent_id || r.wallet || '?')}'" />
<span class="lb-trader-meta">
<span class="lb-trader-name">${escapeHtml(r.agent_name || 'Unnamed agent')}${verifiedBadge(r.verified)}</span>
- <span class="lb-trader-sub">${escapeHtml(shortAddr(r.wallet))} · ${r.unique_coins} coins${r.copiers ? ` · <span class="lb-copiers">${r.copiers} copying</span>` : ''}</span>
+ <span class="lb-trader-sub">${r.wallet ? walletChipHTML(r, { isOwner: false, showPending: false, link: false }) : escapeHtml(shortAddr(r.wallet))} · ${r.unique_coins} coins${r.copiers ? ` · <span class="lb-copiers">${r.copiers} copying</span>` : ''}</span>
</span>
</span>
<span class="lb-num">
@@ -160,6 +161,9 @@ function renderBoard(data) {
}
stateEl.innerHTML = '';
rows.innerHTML = list.map(rowMarkup).join('');
+ // Wire the wallet chips' copy + Tip actions. The board is public — viewers
+ // don't own these traders' agents — so chips render isOwner:false (◎ Tip).
+ wireWalletChips(rows);
// Stagger the entrance subtly.
rows.querySelectorAll('.lb-row').forEach((el, i) => { el.style.animationDelay = `${Math.min(i, 12) * 22}ms`; });
}
diff --git a/src/marketplace-detail.js b/src/marketplace-detail.js
index fb2d5b405..9c9f5014d 100644
--- a/src/marketplace-detail.js
+++ b/src/marketplace-detail.js
@@ -12,6 +12,7 @@
import { onchainBadgeHTML } from './shared/onchain-badge.js';
import { coinChipHTML } from './shared/agent-coin.js';
+import { walletChipHTML } from './shared/agent-wallet-chip.js';
import { agentAvatarGlb, hasCustomAvatar, seeInWorldHref } from './shared/agent-3d.js';
import { log } from './shared/log.js';
@@ -497,10 +498,13 @@ function renderCreatorModal(payload, deps) {
// on the agent detail page this card opens.
const onchain = onchainBadgeHTML(a, { link: false, size: 'sm' });
const coin = coinChipHTML(a, { link: false, size: 'sm' });
+ // Non-interactive (link:false) vanity-aware wallet badge — the card itself
+ // navigates, and the explorer/copy controls live on the agent's own page.
+ const wallet = walletChipHTML(a, { isOwner: false, showPending: false, link: false });
return `<div class="creator-mini-card" data-agent-id="${escapeHtml(a.id)}">
${thumb}
<div class="name">${escapeHtml(a.name)}</div>
- ${onchain || coin ? `<div class="meta">${onchain}${coin}</div>` : ''}
+ ${onchain || coin || wallet ? `<div class="meta">${onchain}${coin}${wallet}</div>` : ''}
<div class="meta">⊙ ${fmtNumber(a.views_count)} · ⑂ ${fmtNumber(a.forks_count)}</div>
</div>`;
}).join('');
@@ -521,9 +525,11 @@ function renderCreatorModal(payload, deps) {
const thumb = avt.thumbnail_url
? `<div class="thumb" style="background-image:url('${escapeHtml(avt.thumbnail_url)}')"></div>`
: `<div class="thumb">◉</div>`;
+ const wallet = walletChipHTML(avt, { isOwner: false, showPending: false, link: false });
return `<div class="creator-mini-card" data-avatar-id="${escapeHtml(avt.id)}">
${thumb}
<div class="name">${escapeHtml(avt.name || 'Untitled')}</div>
+ ${wallet ? `<div class="meta">${wallet}</div>` : ''}
<div class="meta">${escapeHtml(formatDate(avt.created_at))}</div>
</div>`;
}).join('');
diff --git a/src/marketplace.js b/src/marketplace.js
index df89f2994..0851dcd3a 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -18,6 +18,7 @@ import {
bindDetailExtras,
} from './marketplace-detail.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { walletChipHTML, walletChipEl, wireWalletChips } from './shared/agent-wallet-chip.js';
import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';
import { coinChipHTML } from './shared/agent-coin.js';
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
@@ -1251,6 +1252,10 @@ function renderGrid() {
// Poster cache + shimmer-off for model-viewers.
attachModelViewerBehavior();
+ // Wire wallet-chip copy buttons + explorer links so they act on the chip and
+ // don't bubble a click up to the card's detail-navigation handler.
+ wireWalletChips(els.grid);
+
// Kick off infinite scroll observation.
if (hasMore) _setupInfiniteScroll();
@@ -4506,6 +4511,7 @@ function renderCard(a) {
${buyers > 0 ? `<span class="stat-pill" title="${buyers} confirmed purchase${buyers === 1 ? '' : 's'}${buyers24h ? `, ${buyers24h} in last 24h` : ''}">$ ${fmtNumber(buyers)}${buyers24h > 0 ? ` <em>(+${buyers24h}/24h)</em>` : ''}</span>` : ''}
${skillPriceBadge}
${!skillPriceBadge && paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}
+ ${walletChipHTML(a, { isOwner: false, showPending: false, link: true })}
</div>
<div class="footer">
<span>${date}</span>
@@ -5051,6 +5057,18 @@ function renderDetail(a, bookmarked) {
$('d-views').textContent = `⊙ ${fmtNumber(views)}`;
$('d-overview').textContent = a.description || '';
+ // Agent custodial wallet chip, rendered in the identity stats row beside the
+ // category/views. isOwner is true only when the signed-in viewer provably owns
+ // this row (author match) — that unlocks the "✦ Vanity" entry point to the
+ // wallet hub. The chip no-ops until the row carries a solana_address.
+ const statsRow = $('d-views')?.parentElement;
+ if (statsRow) {
+ statsRow.querySelector('.twc')?.remove();
+ const isOwner = !!(currentUserId && a.author_id && currentUserId === a.author_id);
+ const chip = walletChipEl(a, { isOwner, showPending: false, link: true });
+ if (chip) statsRow.appendChild(chip);
+ }
+
// Render pricing summary if agent has skill prices
renderDetailPricingSummary(a);
diff --git a/src/shared/agent-tip-modal.js b/src/shared/agent-tip-modal.js
new file mode 100644
index 000000000..8aea0b5e0
--- /dev/null
+++ b/src/shared/agent-tip-modal.js
@@ -0,0 +1,277 @@
+/**
+ * Tip-an-agent modal — the shared, surface-agnostic UI for sending a
+ * non-custodial tip to any agent's public Solana wallet.
+ *
+ * Opened from the wallet chip (every avatar/agent surface) and the wallet hub's
+ * Tip tab. It owns nothing the caller can't pass in: an agent record with a
+ * public address. It never shows owner-only controls — tipping is a public,
+ * viewer-signed action (see ./agent-tip.js). For an agent that advertises a
+ * preferred payment asset (meta.payments.accepted_tokens) the modal defaults to
+ * that token, which is how a visitor "pays" the agent rather than just tipping.
+ *
+ * Every state is designed: idle, the live send lifecycle (connect → build →
+ * sign → send → confirm), success (with a real Solscan receipt), and an
+ * actionable error. No fake progress — each stage label reflects a real step of
+ * ./agent-tip.js.
+ */
+
+import { tipAgent, TipError, TIP_TOKENS } from './agent-tip.js';
+import { getWalletStatus } from './agent-wallet-chip.js';
+
+const STYLE_ID = 'tws-tip-modal-styles';
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.ttm-backdrop{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;
+ padding:16px;background:rgba(8,8,12,.66);backdrop-filter:blur(4px);
+ animation:ttm-fade .18s ease;}
+.ttm{width:100%;max-width:380px;background:var(--bg-1,#16161c);color:var(--ink,#e8e8ea);
+ border:1px solid var(--stroke-strong,rgba(255,255,255,.12));border-radius:16px;
+ box-shadow:0 24px 64px rgba(0,0,0,.5);overflow:hidden;
+ font:14px/1.45 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;
+ animation:ttm-rise .2s cubic-bezier(.2,.8,.2,1);}
+.ttm-hd{display:flex;align-items:center;gap:11px;padding:16px 18px;border-bottom:1px solid var(--stroke,rgba(255,255,255,.07));}
+.ttm-av{width:38px;height:38px;border-radius:10px;object-fit:cover;flex:none;
+ background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);}
+.ttm-hd-txt{min-width:0;flex:1;}
+.ttm-hd-k{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--ink-dim,#888);}
+.ttm-hd-n{font-size:15px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
+.ttm-x{appearance:none;background:none;border:none;color:var(--ink-dim,#888);font-size:22px;line-height:1;
+ cursor:pointer;padding:2px 4px;border-radius:6px;flex:none;transition:color .15s,background .15s;}
+.ttm-x:hover{color:#fff;background:rgba(255,255,255,.06);}
+.ttm-bd{padding:16px 18px 18px;}
+.ttm-toggle{display:flex;gap:6px;background:rgba(255,255,255,.04);border:1px solid var(--stroke,rgba(255,255,255,.08));
+ border-radius:10px;padding:4px;margin-bottom:14px;}
+.ttm-tok{flex:1;appearance:none;font:inherit;font-weight:600;font-size:13px;color:var(--ink-dim,#9a9aa2);
+ background:none;border:none;border-radius:7px;padding:7px 0;cursor:pointer;transition:background .15s,color .15s;}
+.ttm-tok[aria-pressed="true"]{background:rgba(139,92,246,.22);color:#c4b5fd;}
+.ttm-presets{display:grid;grid-template-columns:repeat(4,1fr);gap:7px;margin-bottom:11px;}
+.ttm-pre{appearance:none;font:inherit;font-size:13px;color:var(--ink,#e8e8ea);background:rgba(255,255,255,.04);
+ border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:8px;padding:8px 0;cursor:pointer;
+ transition:border-color .15s,background .15s,transform .1s;}
+.ttm-pre:hover{background:rgba(255,255,255,.07);}
+.ttm-pre[aria-pressed="true"]{border-color:rgba(139,92,246,.6);background:rgba(139,92,246,.16);color:#c4b5fd;}
+.ttm-pre:active{transform:translateY(1px);}
+.ttm-field{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.04);
+ border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:10px;padding:2px 12px;margin-bottom:13px;
+ transition:border-color .15s;}
+.ttm-field:focus-within{border-color:rgba(139,92,246,.55);}
+.ttm-field input{flex:1;min-width:0;appearance:none;-moz-appearance:textfield;font:inherit;font-size:18px;font-weight:600;
+ color:#fff;background:none;border:none;padding:10px 0;}
+.ttm-field input::-webkit-outer-spin-button,.ttm-field input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0;}
+.ttm-field input:focus{outline:none;}
+.ttm-field .ttm-unit{font-size:13px;font-weight:600;color:var(--ink-dim,#888);flex:none;font-family:ui-monospace,monospace;}
+.ttm-to{font-size:11px;color:var(--ink-dim,#7d7d86);margin-bottom:13px;word-break:break-all;font-family:ui-monospace,monospace;}
+.ttm-to b{color:#a78bfa;font-weight:700;}
+.ttm-go{width:100%;appearance:none;font:inherit;font-weight:700;font-size:14px;color:#0a0a0a;
+ background:linear-gradient(180deg,#c4b5fd,#a78bfa);border:none;border-radius:11px;padding:13px 0;cursor:pointer;
+ display:inline-flex;align-items:center;justify-content:center;gap:8px;transition:filter .15s,transform .1s,opacity .15s;}
+.ttm-go:hover:not(:disabled){filter:brightness(1.08);}
+.ttm-go:active:not(:disabled){transform:translateY(1px);}
+.ttm-go:disabled{opacity:.55;cursor:not-allowed;}
+.ttm-spin{width:14px;height:14px;border-radius:50%;border:2px solid rgba(10,10,10,.35);border-top-color:#0a0a0a;
+ animation:ttm-spin .7s linear infinite;flex:none;}
+.ttm-msg{font-size:12.5px;margin-top:11px;line-height:1.45;}
+.ttm-msg.err{color:#fca5a5;}
+.ttm-ok{text-align:center;padding:8px 4px 2px;}
+.ttm-ok-ic{width:48px;height:48px;border-radius:50%;margin:0 auto 12px;display:flex;align-items:center;justify-content:center;
+ background:rgba(74,222,128,.14);color:#4ade80;font-size:26px;}
+.ttm-ok-t{font-size:16px;font-weight:700;color:#fff;margin-bottom:5px;}
+.ttm-ok-s{font-size:13px;color:var(--ink-dim,#9a9aa2);margin-bottom:16px;}
+.ttm-ok-row{display:flex;gap:8px;}
+.ttm-ok-row a,.ttm-ok-row button{flex:1;appearance:none;font:inherit;font-size:13px;font-weight:600;text-align:center;
+ text-decoration:none;padding:10px 0;border-radius:9px;cursor:pointer;transition:background .15s,border-color .15s;}
+.ttm-ok-row a{color:#0a0a0a;background:#c4b5fd;border:1px solid #c4b5fd;}
+.ttm-ok-row a:hover{filter:brightness(1.07);}
+.ttm-ok-row button{color:var(--ink,#e8e8ea);background:rgba(255,255,255,.05);border:1px solid var(--stroke,rgba(255,255,255,.1));}
+.ttm-ok-row button:hover{background:rgba(255,255,255,.09);}
+.ttm-note{font-size:11px;color:var(--ink-dim,#6f6f78);margin-top:12px;text-align:center;line-height:1.4;}
+@keyframes ttm-fade{from{opacity:0;}to{opacity:1;}}
+@keyframes ttm-rise{from{opacity:0;transform:translateY(12px) scale(.98);}to{opacity:1;transform:none;}}
+@keyframes ttm-spin{to{transform:rotate(360deg);}}
+@media (prefers-reduced-motion:reduce){.ttm-backdrop,.ttm,.ttm-spin{animation:none;}}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+const STAGE_LABEL = {
+ connecting: 'Connecting wallet…',
+ building: 'Preparing transfer…',
+ signing: 'Approve in your wallet…',
+ sending: 'Broadcasting…',
+ confirming: 'Confirming on-chain…',
+};
+
+/**
+ * Open the tip modal for an agent.
+ *
+ * @param {object} agent Any agent record shape (must resolve a public solana_address).
+ * @param {object} [opts]
+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']
+ * @param {() => void} [opts.onSent] Fired after a confirmed tip (e.g. to refresh a balance).
+ * @returns {{ close: () => void } | null} null when the agent has no tippable wallet.
+ */
+export function openTipModal(agent, opts = {}) {
+ if (typeof document === 'undefined') return null;
+ const status = getWalletStatus(agent);
+ if (!status) return null;
+
+ ensureStyles();
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const name = agent?.name || 'this agent';
+ const avatar = agent?.avatar_thumbnail_url || agent?.avatar_url || agent?.profile_image_url || '';
+ // Agents that advertise a preferred payment asset default the modal to it.
+ const accepted = (agent?.meta?.payments?.accepted_tokens || agent?.payments?.accepted_tokens || [])
+ .map((t) => String(t).toUpperCase());
+ const initialToken = accepted.includes('USDC') && !accepted.includes('SOL') ? 'USDC' : 'SOL';
+
+ const state = { token: initialToken, amount: '', sending: false, done: null, error: null };
+
+ const backdrop = document.createElement('div');
+ backdrop.className = 'ttm-backdrop';
+ backdrop.setAttribute('role', 'dialog');
+ backdrop.setAttribute('aria-modal', 'true');
+ backdrop.setAttribute('aria-label', `Tip ${name}`);
+
+ const prevActive = document.activeElement;
+ function close() {
+ document.removeEventListener('keydown', onKey, true);
+ backdrop.remove();
+ try { prevActive?.focus?.(); } catch { /* noop */ }
+ }
+ function onKey(e) {
+ if (e.key === 'Escape' && !state.sending) { e.preventDefault(); close(); }
+ }
+
+ function tokenMeta() {
+ return TIP_TOKENS.find((t) => t.id === state.token) || TIP_TOKENS[0];
+ }
+
+ function render() {
+ if (state.done) { renderSuccess(); return; }
+ const tk = tokenMeta();
+ backdrop.innerHTML = `
+ <div class="ttm">
+ <div class="ttm-hd">
+ ${avatar ? `<img class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ <div class="ttm-hd-txt">
+ <div class="ttm-hd-k">${esc(accepted.length ? 'Pay' : 'Tip')}</div>
+ <div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
+ </div>
+ <button class="ttm-x" type="button" data-x aria-label="Close" ${state.sending ? 'disabled' : ''}>×</button>
+ </div>
+ <div class="ttm-bd">
+ <div class="ttm-toggle" role="group" aria-label="Tip asset">
+ ${TIP_TOKENS.map((t) => `<button class="ttm-tok" type="button" data-tok="${t.id}" aria-pressed="${state.token === t.id}">${esc(t.label)}</button>`).join('')}
+ </div>
+ <div class="ttm-presets">
+ ${tk.presets.map((p) => `<button class="ttm-pre" type="button" data-pre="${p}" aria-pressed="${String(p) === String(state.amount)}">${tk.symbol === '◎' ? '◎' : '$'}${p}</button>`).join('')}
+ </div>
+ <div class="ttm-field">
+ <input type="number" inputmode="decimal" min="0" step="any" placeholder="0.00"
+ value="${esc(state.amount)}" data-amt aria-label="Tip amount" ${state.sending ? 'disabled' : ''}/>
+ <span class="ttm-unit">${esc(tk.label)}</span>
+ </div>
+ <div class="ttm-to">to <b>${esc(status.address.slice(0, 4))}</b>${esc(status.address.slice(4, -4))}<b>${esc(status.address.slice(-4))}</b></div>
+ <button class="ttm-go" type="button" data-go ${state.sending || !(Number(state.amount) > 0) ? 'disabled' : ''}>
+ ${state.sending ? `<span class="ttm-spin" aria-hidden="true"></span>${esc(STAGE_LABEL[state.sending] || 'Sending…')}` : `Send ${state.amount ? `${esc(state.amount)} ${esc(tk.label)}` : tk.label} →`}
+ </button>
+ ${state.error ? `<div class="ttm-msg err" role="alert">${esc(state.error)}</div>` : ''}
+ <div class="ttm-note">Sent straight from your wallet to the agent — three.ws never holds the funds.${network === 'devnet' ? ' · Devnet' : ''}</div>
+ </div>
+ </div>`;
+ wire();
+ }
+
+ function renderSuccess() {
+ const tk = tokenMeta();
+ backdrop.innerHTML = `
+ <div class="ttm">
+ <div class="ttm-hd">
+ ${avatar ? `<img class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ <div class="ttm-hd-txt">
+ <div class="ttm-hd-k">Sent</div>
+ <div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
+ </div>
+ <button class="ttm-x" type="button" data-x aria-label="Close">×</button>
+ </div>
+ <div class="ttm-bd">
+ <div class="ttm-ok">
+ <div class="ttm-ok-ic" aria-hidden="true">✓</div>
+ <div class="ttm-ok-t">${esc(state.done.amount)} ${esc(tk.label)} sent</div>
+ <div class="ttm-ok-s">Your tip to ${esc(name)} is confirmed on-chain.</div>
+ <div class="ttm-ok-row">
+ <a href="${esc(state.done.explorerUrl)}" target="_blank" rel="noopener">View receipt ↗</a>
+ <button type="button" data-again>Tip again</button>
+ </div>
+ </div>
+ </div>
+ </div>`;
+ backdrop.querySelector('[data-x]')?.addEventListener('click', close);
+ backdrop.querySelector('[data-again]')?.addEventListener('click', () => {
+ state.done = null; state.error = null; state.amount = ''; render();
+ });
+ }
+
+ function wire() {
+ backdrop.querySelector('[data-x]')?.addEventListener('click', () => { if (!state.sending) close(); });
+ for (const b of backdrop.querySelectorAll('[data-tok]')) {
+ b.addEventListener('click', () => { if (state.sending) return; state.token = b.dataset.tok; state.amount = ''; state.error = null; render(); });
+ }
+ for (const b of backdrop.querySelectorAll('[data-pre]')) {
+ b.addEventListener('click', () => { if (state.sending) return; state.amount = b.dataset.pre; state.error = null; render(); });
+ }
+ const amt = backdrop.querySelector('[data-amt]');
+ amt?.addEventListener('input', () => {
+ state.amount = amt.value.trim();
+ const go = backdrop.querySelector('[data-go]');
+ if (go) go.disabled = state.sending || !(Number(state.amount) > 0);
+ for (const b of backdrop.querySelectorAll('[data-pre]')) b.setAttribute('aria-pressed', String(b.dataset.pre) === String(state.amount));
+ const label = go?.querySelector(':scope');
+ if (go && !state.sending) go.innerHTML = `Send ${state.amount ? `${esc(state.amount)} ${esc(tokenMeta().label)}` : tokenMeta().label} →`;
+ });
+ backdrop.querySelector('[data-go]')?.addEventListener('click', send);
+ }
+
+ async function send() {
+ if (state.sending || !(Number(state.amount) > 0)) return;
+ state.error = null;
+ state.sending = 'connecting';
+ render();
+ try {
+ const res = await tipAgent({
+ toAddress: status.address,
+ token: state.token,
+ amount: Number(state.amount),
+ network,
+ onStage: (s) => { state.sending = s; render(); },
+ });
+ state.done = { amount: state.amount, explorerUrl: res.explorerUrl, signature: res.signature };
+ state.sending = false;
+ render();
+ try { opts.onSent?.(res); } catch { /* listener best-effort */ }
+ } catch (e) {
+ state.sending = false;
+ state.error = e instanceof TipError ? e.message : (e?.message || 'The tip could not be completed.');
+ render();
+ }
+ }
+
+ backdrop.addEventListener('click', (e) => { if (e.target === backdrop && !state.sending) close(); });
+ document.addEventListener('keydown', onKey, true);
+ render();
+ document.body.appendChild(backdrop);
+ backdrop.querySelector('[data-amt]')?.focus();
+
+ return { close };
+}
diff --git a/src/shared/agent-tip.js b/src/shared/agent-tip.js
new file mode 100644
index 000000000..c20fc8f58
--- /dev/null
+++ b/src/shared/agent-tip.js
@@ -0,0 +1,194 @@
+/**
+ * Tip an agent — non-custodial, viewer-signed Solana transfer.
+ *
+ * Any visitor (owner or not) can fund/tip an agent's public custodial wallet
+ * directly from their own browser wallet (Phantom / Backpack / Solflare). The
+ * transfer is built and signed client-side and submitted through our
+ * Helius-backed same-origin RPC proxy — three.ws never custodies, signs, or
+ * touches the funds. The destination is the agent's PUBLIC `solana_address`
+ * (the same value GET /api/agents/:id/solana serves anonymously), so no secret
+ * material is involved on either side.
+ *
+ * Two assets are supported, matching what the platform can price 1:1:
+ * • SOL — native transfer (SystemProgram.transfer).
+ * • USDC — SPL transferChecked; the recipient's associated token account is
+ * created in the same tx when it doesn't exist yet (sender pays rent).
+ *
+ * The tip lands on-chain and surfaces automatically in the agent's existing
+ * activity feed (GET /api/agents/:id/solana/activity) — there is no separate
+ * server write, so there is nothing to fake and no unauthenticated endpoint to
+ * abuse. The returned signature + explorer link IS the receipt.
+ */
+
+import {
+ Connection,
+ PublicKey,
+ SystemProgram,
+ Transaction,
+ LAMPORTS_PER_SOL,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddress,
+ getAccount,
+ createAssociatedTokenAccountInstruction,
+ createTransferCheckedInstruction,
+ TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// USDC mints per cluster — mirrors api/agents/solana-wallet.js. USDC has 6 decimals.
+export const USDC_MINT = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+const USDC_DECIMALS = 6;
+
+/** Supported tip assets with the display metadata the modal needs. */
+export const TIP_TOKENS = Object.freeze([
+ { id: 'SOL', label: 'SOL', symbol: '◎', decimals: 9, presets: [0.05, 0.1, 0.25, 1] },
+ { id: 'USDC', label: 'USDC', symbol: '$', decimals: USDC_DECIMALS, presets: [1, 5, 10, 25] },
+]);
+
+/** A tip error that carries a machine code so the UI can tailor recovery copy. */
+export class TipError extends Error {
+ constructor(message, code = 'tip_failed') {
+ super(message);
+ this.name = 'TipError';
+ this.code = code;
+ }
+}
+
+// Poll signature status over HTTP (the proxy refuses WebSocket subscriptions,
+// so Connection.confirmTransaction would hang). Mirrors solana-deploy.js.
+async function waitForConfirmation(conn, signature, timeoutMs = 60_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const status = value?.[0];
+ if (status) {
+ if (status.err) throw new TipError(`Transfer failed on-chain: ${JSON.stringify(status.err)}`, 'onchain_error');
+ if (status.confirmationStatus === 'confirmed' || status.confirmationStatus === 'finalized') return;
+ }
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ throw new TipError('Timed out waiting for confirmation. The tip may still land — check the explorer.', 'timeout');
+}
+
+/**
+ * Send a tip to an agent's public Solana address.
+ *
+ * @param {object} opts
+ * @param {string} opts.toAddress Recipient base58 address (agent's solana_address).
+ * @param {'SOL'|'USDC'} [opts.token='SOL']
+ * @param {number} opts.amount Human amount (e.g. 0.1 SOL or 5 USDC).
+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']
+ * @param {(stage: string) => void} [opts.onStage] Lifecycle: 'connecting'|'building'|'signing'|'sending'|'confirming'.
+ * @returns {Promise<{ signature: string, explorerUrl: string, from: string }>}
+ */
+export async function tipAgent({ toAddress, token = 'SOL', amount, network = 'mainnet', onStage } = {}) {
+ const stage = (s) => { try { onStage?.(s); } catch { /* listener best-effort */ } };
+
+ if (!toAddress || !BASE58_RE.test(String(toAddress))) {
+ throw new TipError('This agent has no valid wallet address to tip.', 'no_address');
+ }
+ const amt = Number(amount);
+ if (!Number.isFinite(amt) || amt <= 0) {
+ throw new TipError('Enter a tip amount greater than zero.', 'bad_amount');
+ }
+
+ const wallet = detectSolanaWallet();
+ if (!wallet) throw new TipError('No Solana wallet found. Install Phantom, Backpack, or Solflare to tip.', 'no_wallet');
+
+ stage('connecting');
+ let fromPubkey;
+ try {
+ const conn = await wallet.connect();
+ fromPubkey = conn?.publicKey || wallet.publicKey;
+ } catch (e) {
+ if (e?.code === 4001 || /reject|cancel/i.test(e?.message || '')) {
+ throw new TipError('Wallet connection cancelled.', 'cancelled');
+ }
+ throw new TipError(e?.message || 'Could not connect your wallet.', 'connect_failed');
+ }
+ if (!fromPubkey) throw new TipError('Could not read your wallet address.', 'connect_failed');
+
+ const from = new PublicKey(fromPubkey.toString());
+ const to = new PublicKey(String(toAddress));
+ if (from.equals(to)) throw new TipError('That wallet is the agent — pick a different wallet to tip from.', 'self_tip');
+
+ const endpoint = SOLANA_RPC[network] || SOLANA_RPC.mainnet;
+ const connection = new Connection(endpoint, 'confirmed');
+
+ stage('building');
+ const tx = new Transaction();
+ try {
+ if (token === 'USDC') {
+ const mint = new PublicKey(USDC_MINT[network] || USDC_MINT.mainnet);
+ const fromAta = await getAssociatedTokenAddress(mint, from);
+ const toAta = await getAssociatedTokenAddress(mint, to);
+ // Sender must actually hold USDC — surface a clear, actionable error if not.
+ try {
+ await getAccount(connection, fromAta);
+ } catch {
+ throw new TipError('Your wallet has no USDC. Switch to SOL or fund your wallet with USDC first.', 'no_usdc');
+ }
+ // Create the recipient's USDC account in-band if it doesn't exist yet.
+ let recipientHasAta = true;
+ try {
+ await getAccount(connection, toAta);
+ } catch {
+ recipientHasAta = false;
+ }
+ if (!recipientHasAta) {
+ tx.add(createAssociatedTokenAccountInstruction(from, toAta, to, mint));
+ }
+ const raw = BigInt(Math.round(amt * 10 ** USDC_DECIMALS));
+ tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, USDC_DECIMALS, [], TOKEN_PROGRAM_ID));
+ } else {
+ const lamports = Math.round(amt * LAMPORTS_PER_SOL);
+ tx.add(SystemProgram.transfer({ fromPubkey: from, toPubkey: to, lamports }));
+ }
+ } catch (e) {
+ if (e instanceof TipError) throw e;
+ throw new TipError(e?.message || 'Could not build the transfer.', 'build_failed');
+ }
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.lastValidBlockHeight = lastValidBlockHeight;
+ tx.feePayer = from;
+
+ stage('signing');
+ let signed;
+ try {
+ signed = await wallet.signTransaction(tx);
+ } catch (e) {
+ if (e?.code === 4001 || /reject|cancel/i.test(e?.message || '')) {
+ throw new TipError('You cancelled the tip.', 'cancelled');
+ }
+ throw new TipError(e?.message || 'Signing failed.', 'sign_failed');
+ }
+
+ stage('sending');
+ let signature;
+ try {
+ signature = await connection.sendRawTransaction(signed.serialize(), {
+ skipPreflight: false,
+ preflightCommitment: 'confirmed',
+ maxRetries: 5,
+ });
+ } catch (e) {
+ const msg = e?.message || 'Transaction was rejected by the network.';
+ if (/insufficient|0x1\b/i.test(msg)) {
+ throw new TipError('Insufficient balance for this tip plus network fees.', 'insufficient');
+ }
+ throw new TipError(msg, 'send_failed');
+ }
+
+ stage('confirming');
+ await waitForConfirmation(connection, signature);
+
+ return { signature, explorerUrl: solanaTxExplorerUrl(network, signature), from: from.toBase58() };
+}
diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.js
index ebb43120c..621eb7bb2 100644
--- a/src/shared/agent-wallet-chip.js
+++ b/src/shared/agent-wallet-chip.js
@@ -14,10 +14,13 @@
* owner it also surfaces a "Make it vanity" entry point that routes to the wallet
* hub where the grind + money-safe swap happens (POST /api/agents/:id/solana/vanity).
*
- * Reads the address from any agent record shape:
+ * Reads the address from any agent OR avatar record shape:
* agent.solana_address | agent.meta.solana_address | agent.wallet (base58)
+ * avatar.agent_solana_address (the agent joined onto an avatar row)
* and the vanity pattern from:
* agent.solana_vanity_prefix/suffix | agent.meta.solana_vanity_prefix/suffix
+ * avatar.agent_solana_vanity_prefix/suffix
+ * so a surface can pass whichever record it already holds without reshaping it.
*/
const STYLE_ID = 'tws-agent-wallet-chip-styles';
@@ -39,14 +42,19 @@ export function getWalletStatus(agent) {
if (!agent || typeof agent !== 'object') return null;
const meta = agent.meta || {};
const address =
- agent.solana_address || meta.solana_address ||
+ agent.solana_address || meta.solana_address || agent.agent_solana_address ||
(typeof agent.wallet === 'string' && BASE58_RE.test(agent.wallet) ? agent.wallet : null) ||
null;
if (!address || !BASE58_RE.test(String(address))) return null;
- const prefix = agent.solana_vanity_prefix || meta.solana_vanity_prefix || null;
- const suffix = agent.solana_vanity_suffix || meta.solana_vanity_suffix || null;
- const agentId = agent.id || agent.agentId || agent.agent_id || null;
+ const prefix =
+ agent.solana_vanity_prefix || meta.solana_vanity_prefix || agent.agent_solana_vanity_prefix || null;
+ const suffix =
+ agent.solana_vanity_suffix || meta.solana_vanity_suffix || agent.agent_solana_vanity_suffix || null;
+ // Prefer the linked-agent id on avatar rows (agent_id) so the hub deep-link
+ // targets the agent that owns the wallet, not the avatar row id. Agent records
+ // have no agent_id field, so this falls through to their own id.
+ const agentId = agent.agent_id || agent.agentId || agent.id || null;
return {
address: String(address),
@@ -106,6 +114,10 @@ a.twc-link{color:inherit;text-decoration:none;display:inline-flex;align-items:ce
.twc-make{font-weight:600;font-size:10px;color:#a78bfa;text-decoration:none;border-left:1px solid rgba(139,92,246,.3);
padding-left:7px;margin-left:1px;white-space:nowrap;transition:color .15s ease;}
.twc-make:hover{color:#fff;}
+button.twc-make{appearance:none;background:none;border:none;border-left:1px solid rgba(139,92,246,.3);cursor:pointer;
+ font-family:inherit;line-height:1;padding:0 0 0 7px;}
+button.twc-make:active{transform:scale(.95);}
+button.twc-make:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2px;border-radius:4px;}
.twc-vanity-tag{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;opacity:.8;}
.twc-pending{color:#888;background:rgba(255,255,255,.04);border-color:rgba(255,255,255,.1);}
.twc-copied{color:#4ade80!important;}
@@ -118,6 +130,19 @@ const COPY_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" str
const LINK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';
const WALLET_SVG = '<svg class="twc-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4Z"/></svg>';
+/** Compact descriptor the tip modal needs, encoded onto the Tip button. */
+function tipAttrs(agent, status) {
+ const name = agent?.name || agent?.display_name || '';
+ const avatar = agent?.avatar_thumbnail_url || agent?.avatar_url || agent?.profile_image_url || '';
+ const accepted = (agent?.meta?.payments?.accepted_tokens || agent?.payments?.accepted_tokens || []).join(',');
+ return (
+ `data-twc-tip="${esc(status.address)}"` +
+ (name ? ` data-twc-name="${esc(name)}"` : '') +
+ (avatar ? ` data-twc-av="${esc(avatar)}"` : '') +
+ (accepted ? ` data-twc-pay="${esc(accepted)}"` : '')
+ );
+}
+
/**
* Render the wallet chip as an HTML string for template-string render sites
* (card grids). Returns a "wallet pending" chip when no address is present yet so
@@ -125,13 +150,18 @@ const WALLET_SVG = '<svg class="twc-ico" viewBox="0 0 24 24" fill="none" stroke=
*
* @param {object} agent Any supported agent record shape.
* @param {object} [opts]
- * @param {boolean} [opts.isOwner=false] Show the "Make it vanity" entry point.
+ * @param {boolean} [opts.isOwner=false] Owner sees the vanity entry point; a
+ * non-owner sees a Tip action instead. Ownership is the ONLY thing that gates
+ * which action shows — never withdraw/manage to a non-owner, never a vanity
+ * grind they can't assign (they must fork first; the fork CTA lives on the
+ * surface, and forking mints them their own wallet).
* @param {boolean} [opts.showPending=true] Render a pending chip when no wallet.
* @param {boolean} [opts.link=true] Make the address a copy/explorer affordance.
+ * @param {boolean} [opts.tip=true] Show the Tip action to non-owners.
*/
export function walletChipHTML(agent, opts = {}) {
ensureWalletChipStyles();
- const { isOwner = false, showPending = true, link = true } = opts;
+ const { isOwner = false, showPending = true, link = true, tip = true } = opts;
const status = getWalletStatus(agent);
if (!status) {
@@ -146,10 +176,17 @@ export function walletChipHTML(agent, opts = {}) {
const explorerLink = link
? `<a class="twc-act twc-link" href="${esc(status.explorerUrl)}" target="_blank" rel="noopener noreferrer" title="View on Solscan" aria-label="View wallet on Solscan" data-twc-stop>${LINK_SVG}</a>`
: '';
- const makeVanity =
+ // Owner → grind a vanity address (routes to the hub's money-safe swap).
+ // Non-owner → tip the agent directly from their own wallet. A non-owner can
+ // never grind/assign a vanity to an agent they don't own.
+ const ownerAction =
isOwner && !status.isVanity && status.hubUrl
? `<a class="twc-make" href="${esc(status.hubUrl)}#vanity" title="Grind a custom vanity address" data-twc-stop>✦ Vanity</a>`
: '';
+ const tipBtn =
+ !isOwner && tip
+ ? `<button type="button" class="twc-make twc-tip" ${tipAttrs(agent, status)} title="Tip ${esc(agent?.name || 'this agent')}" data-twc-stop>◎ Tip</button>`
+ : '';
const title = `Agent wallet ${status.address}${status.isVanity ? ' (vanity)' : ''}`;
return (
@@ -159,7 +196,8 @@ export function walletChipHTML(agent, opts = {}) {
vanityTag +
copyBtn +
explorerLink +
- makeVanity +
+ ownerAction +
+ tipBtn +
`</span>`
);
}
@@ -197,6 +235,25 @@ function wireWalletChip(node) {
for (const stop of node.querySelectorAll?.('[data-twc-stop]') || []) {
stop.addEventListener('click', (e) => e.stopPropagation());
}
+ const tipBtn = node.querySelector?.('[data-twc-tip]');
+ if (tipBtn) {
+ tipBtn.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const agent = {
+ solana_address: tipBtn.getAttribute('data-twc-tip'),
+ name: tipBtn.getAttribute('data-twc-name') || 'this agent',
+ avatar_thumbnail_url: tipBtn.getAttribute('data-twc-av') || '',
+ meta: { payments: { accepted_tokens: (tipBtn.getAttribute('data-twc-pay') || '').split(',').filter(Boolean) } },
+ };
+ try {
+ const { openTipModal } = await import('./agent-tip-modal.js');
+ openTipModal(agent);
+ } catch {
+ /* modal failed to load — the address is still copyable from the chip */
+ }
+ });
+ }
const btn = node.matches?.('[data-twc-copy]') ? node : node.querySelector?.('[data-twc-copy]');
if (btn) {
btn.addEventListener('click', async (e) => {
diff --git a/src/solana/vanity/bip39-english.js b/src/solana/vanity/bip39-english.js
new file mode 100644
index 000000000..c111ae78b
--- /dev/null
+++ b/src/solana/vanity/bip39-english.js
@@ -0,0 +1,268 @@
+// BIP-0039 English wordlist (2048 words) — vendored verbatim from the BIP-39
+// reference (github.com/bitcoin/bips/blob/master/bip-0039/english.txt). This is
+// a public, immutable constant of the BIP-39 standard, embedded here so the
+// vanity mnemonic grinder is fully self-contained and never depends on an
+// undeclared transitive `bip39` install at runtime.
+//
+// Integrity: sha256(words.join('\n')) === '187db04a869dd9bc7be80d21a86497d692c0db6abd3aa8cb6be5d618ff757fae'.
+// Order is consensus-critical — each word's index IS its 11-bit value. Do not
+// sort, dedupe, or otherwise reorder.
+
+export const ENGLISH_WORDLIST = Object.freeze([
+ "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract",
+ "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid",
+ "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual",
+ "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance",
+ "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent",
+ "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album",
+ "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone",
+ "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among",
+ "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry",
+ "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique",
+ "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april",
+ "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor",
+ "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact",
+ "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume",
+ "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction",
+ "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado",
+ "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis",
+ "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball",
+ "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base",
+ "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become",
+ "beef", "before", "begin", "behave", "behind", "believe", "below", "belt",
+ "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle",
+ "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black",
+ "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood",
+ "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body",
+ "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring",
+ "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain",
+ "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief",
+ "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother",
+ "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb",
+ "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus",
+ "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable",
+ "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can",
+ "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable",
+ "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry",
+ "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog",
+ "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling",
+ "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk",
+ "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap",
+ "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child",
+ "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar",
+ "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify",
+ "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff",
+ "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud",
+ "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut",
+ "code", "coffee", "coil", "coin", "collect", "color", "column", "combine",
+ "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm",
+ "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper",
+ "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch",
+ "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle",
+ "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream",
+ "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop",
+ "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch",
+ "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious",
+ "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad",
+ "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn",
+ "day", "deal", "debate", "debris", "decade", "december", "decide", "decline",
+ "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay",
+ "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend",
+ "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk",
+ "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram",
+ "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital",
+ "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover",
+ "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide",
+ "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain",
+ "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft",
+ "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill",
+ "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb",
+ "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager",
+ "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo",
+ "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight",
+ "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator",
+ "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ",
+ "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy",
+ "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough",
+ "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode",
+ "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt",
+ "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil",
+ "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude",
+ "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit",
+ "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend",
+ "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint",
+ "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy",
+ "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault",
+ "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female",
+ "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field",
+ "figure", "file", "film", "filter", "final", "find", "fine", "finger",
+ "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness",
+ "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight",
+ "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly",
+ "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot",
+ "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil",
+ "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend",
+ "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel",
+ "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy",
+ "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment",
+ "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius",
+ "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle",
+ "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass",
+ "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue",
+ "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip",
+ "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass",
+ "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group",
+ "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun",
+ "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy",
+ "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard",
+ "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet",
+ "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip",
+ "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow",
+ "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital",
+ "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble",
+ "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband",
+ "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill",
+ "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose",
+ "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate",
+ "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial",
+ "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane",
+ "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest",
+ "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory",
+ "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel",
+ "job", "join", "joke", "journey", "joy", "judge", "juice", "jump",
+ "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup",
+ "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit",
+ "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know",
+ "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language",
+ "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law",
+ "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave",
+ "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend",
+ "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty",
+ "library", "license", "life", "lift", "light", "like", "limb", "limit",
+ "link", "lion", "liquid", "list", "little", "live", "lizard", "load",
+ "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop",
+ "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber",
+ "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet",
+ "maid", "mail", "main", "major", "make", "mammal", "man", "manage",
+ "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin",
+ "marine", "market", "marriage", "mask", "mass", "master", "match", "material",
+ "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure",
+ "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory",
+ "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message",
+ "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind",
+ "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake",
+ "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment",
+ "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning",
+ "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie",
+ "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music",
+ "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin",
+ "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative",
+ "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral",
+ "never", "news", "next", "nice", "night", "noble", "noise", "nominee",
+ "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice",
+ "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey",
+ "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean",
+ "october", "odor", "off", "offer", "office", "often", "oil", "okay",
+ "old", "olive", "olympic", "omit", "once", "one", "onion", "online",
+ "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit",
+ "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich",
+ "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over",
+ "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page",
+ "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper",
+ "parade", "parent", "park", "parrot", "party", "pass", "patch", "path",
+ "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut",
+ "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper",
+ "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical",
+ "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot",
+ "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet",
+ "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge",
+ "poem", "poet", "point", "polar", "pole", "police", "pond", "pony",
+ "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery",
+ "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare",
+ "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority",
+ "prison", "private", "prize", "problem", "process", "produce", "profit", "program",
+ "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide",
+ "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil",
+ "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle",
+ "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz",
+ "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail",
+ "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid",
+ "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real",
+ "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle",
+ "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject",
+ "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove",
+ "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report",
+ "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire",
+ "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib",
+ "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid",
+ "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road",
+ "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room",
+ "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude",
+ "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness",
+ "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same",
+ "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say",
+ "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science",
+ "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea",
+ "search", "season", "seat", "second", "secret", "section", "security", "seed",
+ "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence",
+ "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft",
+ "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine",
+ "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder",
+ "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side",
+ "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar",
+ "simple", "since", "sing", "siren", "sister", "situate", "six", "size",
+ "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab",
+ "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan",
+ "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth",
+ "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social",
+ "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve",
+ "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup",
+ "source", "south", "space", "spare", "spatial", "spawn", "speak", "special",
+ "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin",
+ "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray",
+ "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium",
+ "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay",
+ "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting",
+ "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street",
+ "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject",
+ "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest",
+ "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme",
+ "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain",
+ "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim",
+ "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table",
+ "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target",
+ "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten",
+ "tenant", "tennis", "tent", "term", "test", "text", "thank", "that",
+ "theme", "then", "theory", "there", "they", "thing", "this", "thought",
+ "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger",
+ "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title",
+ "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token",
+ "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top",
+ "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist",
+ "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic",
+ "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree",
+ "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy",
+ "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try",
+ "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle",
+ "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical",
+ "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo",
+ "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown",
+ "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon",
+ "upper", "upset", "urban", "urge", "usage", "use", "used", "useful",
+ "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley",
+ "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle",
+ "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very",
+ "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view",
+ "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual",
+ "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote",
+ "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want",
+ "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave",
+ "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding",
+ "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat",
+ "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife",
+ "wild", "will", "win", "window", "wine", "wing", "wink", "winner",
+ "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman",
+ "wonder", "wood", "wool", "word", "work", "world", "worry", "worth",
+ "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year",
+ "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo",
+]);
diff --git a/src/solana/vanity/mnemonic-grinder.js b/src/solana/vanity/mnemonic-grinder.js
new file mode 100644
index 000000000..78341fd70
--- /dev/null
+++ b/src/solana/vanity/mnemonic-grinder.js
@@ -0,0 +1,145 @@
+/**
+ * Vanity grinder that returns a BIP-39 SEED PHRASE (not just a raw keypair).
+ *
+ * The WASM grinder in grinder-node.js produces raw Ed25519 keypairs that have
+ * no mnemonic — you can only import them as a private key. This grinder instead
+ * rolls a fresh BIP-39 mnemonic each attempt, derives the Solana keypair at
+ * m/44'/501'/0'/0' (Phantom's default), and checks the resulting address against
+ * the requested prefix/suffix. A hit therefore yields a real seed phrase the
+ * buyer can type into any wallet — at the same address.
+ *
+ * Cost model: each attempt runs PBKDF2-HMAC-SHA512 (2048 iterations) + an
+ * HMAC-SHA512 chain, so throughput is ~200–250 keypairs/sec single-threaded —
+ * roughly 100× slower than the WASM keypair grinder. The honest server ceiling
+ * is therefore a 2-character combined pattern (~3.4k expected attempts, found
+ * inside the default 45s budget the large majority of the time). On budget
+ * exhaustion we throw GrindExhaustedError so the x402 endpoint declines to
+ * charge the buyer. Longer mnemonic patterns belong on the user's own machine.
+ */
+
+import { validatePattern, expectedAttempts } from './validation.js';
+import { generateMnemonic, deriveSolanaKeypair, DEFAULT_STRENGTH, STRENGTH_WORD_COUNTS } from './mnemonic.js';
+import { GrindExhaustedError } from './grinder-node.js';
+
+// Largest combined (prefix + suffix) length the server will grind in mnemonic
+// mode. Held below the keypair grinder's limit of 3 because each attempt is
+// ~100× more expensive — a 3-char mnemonic grind (~195k attempts) would need
+// ~15 minutes single-threaded, far past any serverless budget.
+export const MAX_MNEMONIC_PATTERN_LENGTH = 2;
+
+const DEFAULT_TIME_BUDGET_MS = 45_000;
+
+// How often to re-check the wall-clock budget. The per-attempt cost is high
+// (~4–5ms), so a small batch keeps the budget check responsive without adding
+// measurable overhead.
+const BATCH_SIZE = 64;
+
+/**
+ * @typedef {object} MnemonicGrindResult
+ * @property {string} mnemonic - BIP-39 seed phrase (the secret).
+ * @property {number} wordCount - 12 / 15 / 18 / 21 / 24.
+ * @property {string} derivationPath - e.g. m/44'/501'/0'/0'.
+ * @property {string} publicKey - Base58 address.
+ * @property {Uint8Array} secretKey - 64-byte Ed25519 secret key (derived).
+ * @property {number} attempts - Mnemonics tried.
+ * @property {number} durationMs - Wall-clock duration.
+ */
+
+/**
+ * Grind a vanity Solana address whose key is recoverable from a BIP-39 mnemonic.
+ *
+ * @param {object} opts
+ * @param {string} [opts.prefix] Base58 prefix to match.
+ * @param {string} [opts.suffix] Base58 suffix to match.
+ * @param {boolean} [opts.ignoreCase=false] Case-insensitive match.
+ * @param {number} [opts.strength=128] BIP-39 entropy bits (12–24 words).
+ * @param {number} [opts.timeBudgetMs] Wall-clock budget before giving up.
+ * @returns {MnemonicGrindResult}
+ * @throws {Error} invalid pattern (400) or exhausted budget (504).
+ */
+export function grindVanityMnemonic(opts = {}) {
+ const prefix = opts.prefix || '';
+ const suffix = opts.suffix || '';
+ const ignoreCase = !!opts.ignoreCase;
+ const strength = opts.strength || DEFAULT_STRENGTH;
+ const timeBudgetMs = opts.timeBudgetMs || DEFAULT_TIME_BUDGET_MS;
+
+ if (!prefix && !suffix) {
+ throw Object.assign(new Error('prefix or suffix is required'), { status: 400, code: 'validation_error' });
+ }
+ if (!STRENGTH_WORD_COUNTS[strength]) {
+ throw Object.assign(new Error(`invalid strength ${strength}`), { status: 400, code: 'validation_error' });
+ }
+ for (const [label, pattern] of [['prefix', prefix], ['suffix', suffix]]) {
+ if (!pattern) continue;
+ const v = validatePattern(pattern);
+ if (!v.valid) {
+ throw Object.assign(new Error(`invalid ${label}: ${v.errors.join('; ')}`), {
+ status: 400,
+ code: 'validation_error',
+ });
+ }
+ }
+ const combinedLength = prefix.length + suffix.length;
+ if (combinedLength > MAX_MNEMONIC_PATTERN_LENGTH) {
+ throw Object.assign(
+ new Error(
+ `combined pattern length ${combinedLength} exceeds the mnemonic-mode server limit of ` +
+ `${MAX_MNEMONIC_PATTERN_LENGTH} characters — seed-phrase grinding is ~100× slower than ` +
+ `raw keypair grinding. Grind longer mnemonic patterns on your own machine, or drop the ` +
+ `mnemonic option to get a raw keypair (up to 3 chars server-side).`,
+ ),
+ { status: 400, code: 'pattern_too_long' },
+ );
+ }
+
+ const wantPrefix = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : null;
+ const wantSuffix = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : null;
+ const pLen = wantPrefix?.length || 0;
+ const sLen = wantSuffix?.length || 0;
+
+ const startedAt = performance.now();
+ let attempts = 0;
+
+ while (performance.now() - startedAt < timeBudgetMs) {
+ for (let i = 0; i < BATCH_SIZE; i++) {
+ const mnemonic = generateMnemonic(strength);
+ const { keypair, derivationPath } = deriveSolanaKeypair(mnemonic);
+ const addr = keypair.publicKey.toBase58();
+ attempts++;
+
+ if (wantPrefix) {
+ const head = ignoreCase ? addr.slice(0, pLen).toLowerCase() : addr.slice(0, pLen);
+ if (head !== wantPrefix) continue;
+ }
+ if (wantSuffix) {
+ const tail = ignoreCase ? addr.slice(addr.length - sLen).toLowerCase() : addr.slice(addr.length - sLen);
+ if (tail !== wantSuffix) continue;
+ }
+
+ return {
+ mnemonic,
+ wordCount: STRENGTH_WORD_COUNTS[strength],
+ derivationPath,
+ publicKey: addr,
+ secretKey: Uint8Array.from(keypair.secretKey),
+ attempts,
+ durationMs: performance.now() - startedAt,
+ };
+ }
+ }
+
+ throw new GrindExhaustedError(attempts, performance.now() - startedAt);
+}
+
+/**
+ * Expected attempts for a mnemonic-mode pattern. Identical probability model to
+ * the keypair grinder (base58, case-folding aware) — only throughput differs.
+ * @param {string} prefix
+ * @param {string} suffix
+ * @param {boolean} [ignoreCase=false]
+ * @returns {number}
+ */
+export function expectedMnemonicAttempts(prefix, suffix, ignoreCase = false) {
+ return expectedAttempts(prefix || '', suffix || '', ignoreCase);
+}
diff --git a/src/solana/vanity/mnemonic.js b/src/solana/vanity/mnemonic.js
new file mode 100644
index 000000000..d32ca64e1
--- /dev/null
+++ b/src/solana/vanity/mnemonic.js
@@ -0,0 +1,193 @@
+/**
+ * BIP-39 mnemonic ↔ Solana keypair derivation — zero runtime dependencies
+ * beyond Node's built-in `crypto` and `@solana/web3.js`.
+ *
+ * Why hand-rolled instead of pulling in `bip39` + `ed25519-hd-key`: this module
+ * ships inside Vercel serverless functions and a published MCP package, and we
+ * refuse to take a runtime dependency on an undeclared transitive install. Every
+ * primitive used here is a standard-library call (`pbkdf2Sync`, `createHmac`,
+ * `createHash`, `randomBytes`) plus the vendored BIP-39 wordlist, so the feature
+ * is fully self-contained and reproducible.
+ *
+ * Correctness is pinned by canonical test vectors (the BIP-39 "TREZOR" vectors
+ * and the SLIP-0010 ed25519 vectors) in test/vanity-mnemonic.test.js, and the
+ * derived address is verified byte-for-byte against `near-hd-key` so a mnemonic
+ * we emit imports into Phantom / Solflare / the Solana CLI at the exact same
+ * address. The default path is m/44'/501'/0'/0' — Phantom's first account.
+ */
+
+import { createHash, createHmac, pbkdf2Sync, randomBytes } from 'node:crypto';
+import { Keypair } from '@solana/web3.js';
+
+import { ENGLISH_WORDLIST } from './bip39-english.js';
+
+// Phantom / Solflare / Solana-CLI "derived" account path. The trailing two
+// levels are the account and change indices; index 0 is the first wallet.
+export const SOLANA_PURPOSE = 44;
+export const SOLANA_COIN_TYPE = 501;
+export const DEFAULT_DERIVATION_PATH = "m/44'/501'/0'/0'";
+
+// Supported BIP-39 entropy strengths → mnemonic word counts. 128 bits → 12
+// words (the wallet default), 256 bits → 24 words (maximum security margin).
+export const STRENGTH_WORD_COUNTS = Object.freeze({ 128: 12, 160: 15, 192: 18, 224: 21, 256: 24 });
+const VALID_STRENGTHS = Object.keys(STRENGTH_WORD_COUNTS).map(Number);
+export const DEFAULT_STRENGTH = 128;
+
+const WORD_INDEX = new Map(ENGLISH_WORDLIST.map((w, i) => [w, i]));
+
+function err(message, code = 'mnemonic_error', status = 400) {
+ return Object.assign(new Error(message), { code, status });
+}
+
+/**
+ * Encode raw entropy as a BIP-39 mnemonic. Entropy length must be one of the
+ * supported strengths (16/20/24/28/32 bytes). The checksum is the leading
+ * ENT/32 bits of SHA-256(entropy), appended before slicing into 11-bit words.
+ * @param {Uint8Array|Buffer} entropy
+ * @returns {string} space-joined mnemonic
+ */
+export function entropyToMnemonic(entropy) {
+ const bytes = Buffer.from(entropy);
+ const ENT = bytes.length * 8;
+ if (!VALID_STRENGTHS.includes(ENT)) {
+ throw err(`invalid entropy length ${bytes.length} bytes — expected one of ${VALID_STRENGTHS.map((b) => b / 8).join(', ')}`);
+ }
+ const checksumBits = ENT / 32;
+ const hash = createHash('sha256').update(bytes).digest();
+ let bits = '';
+ for (const b of bytes) bits += b.toString(2).padStart(8, '0');
+ for (const b of hash) bits += b.toString(2).padStart(8, '0');
+ bits = bits.slice(0, ENT + checksumBits);
+
+ const words = [];
+ for (let i = 0; i < bits.length; i += 11) {
+ words.push(ENGLISH_WORDLIST[parseInt(bits.slice(i, i + 11), 2)]);
+ }
+ return words.join(' ');
+}
+
+/**
+ * Generate a fresh random BIP-39 mnemonic at the requested strength (default
+ * 128-bit / 12 words). Uses the CSPRNG via `crypto.randomBytes`.
+ * @param {number} [strength=128] bits of entropy
+ * @returns {string}
+ */
+export function generateMnemonic(strength = DEFAULT_STRENGTH) {
+ if (!VALID_STRENGTHS.includes(strength)) {
+ throw err(`invalid strength ${strength} — expected one of ${VALID_STRENGTHS.join(', ')}`);
+ }
+ return entropyToMnemonic(randomBytes(strength / 8));
+}
+
+/**
+ * Validate a mnemonic: every word in the list, valid word count, and a correct
+ * BIP-39 checksum. Returns true/false (does not throw) for cheap guard use.
+ * @param {string} mnemonic
+ * @returns {boolean}
+ */
+export function validateMnemonic(mnemonic) {
+ if (typeof mnemonic !== 'string') return false;
+ const words = mnemonic.normalize('NFKD').trim().split(/\s+/);
+ if (!Object.values(STRENGTH_WORD_COUNTS).includes(words.length)) return false;
+
+ let bits = '';
+ for (const w of words) {
+ const idx = WORD_INDEX.get(w);
+ if (idx === undefined) return false;
+ bits += idx.toString(2).padStart(11, '0');
+ }
+ const dividerIndex = Math.floor(bits.length / 33) * 32;
+ const entropyBits = bits.slice(0, dividerIndex);
+ const checksumBits = bits.slice(dividerIndex);
+
+ const entropyBytes = Buffer.alloc(entropyBits.length / 8);
+ for (let i = 0; i < entropyBytes.length; i++) {
+ entropyBytes[i] = parseInt(entropyBits.slice(i * 8, i * 8 + 8), 2);
+ }
+ const hash = createHash('sha256').update(entropyBytes).digest();
+ let expected = '';
+ for (const b of hash) expected += b.toString(2).padStart(8, '0');
+ return checksumBits === expected.slice(0, checksumBits.length);
+}
+
+/**
+ * BIP-39 mnemonic → 64-byte seed via PBKDF2-HMAC-SHA512 (2048 iterations), per
+ * the standard. The optional passphrase (BIP-39 "25th word") salts the KDF.
+ * @param {string} mnemonic
+ * @param {string} [passphrase='']
+ * @returns {Buffer} 64-byte seed
+ */
+export function mnemonicToSeed(mnemonic, passphrase = '') {
+ const m = mnemonic.normalize('NFKD');
+ const salt = ('mnemonic' + passphrase).normalize('NFKD');
+ return pbkdf2Sync(Buffer.from(m, 'utf8'), Buffer.from(salt, 'utf8'), 2048, 64, 'sha512');
+}
+
+/**
+ * Parse a BIP-32 path string ("m/44'/501'/0'/0'") into an array of hardened
+ * indices. ed25519 (SLIP-0010) supports hardened derivation only, so every
+ * segment must be hardened (trailing `'` or `h`); a non-hardened segment throws.
+ * @param {string} path
+ * @returns {number[]} indices in [0, 2^31)
+ */
+export function parseDerivationPath(path) {
+ const segments = path.split('/');
+ if (segments[0] !== 'm') throw err(`invalid derivation path '${path}' — must start with 'm'`);
+ return segments.slice(1).map((seg) => {
+ const hardened = seg.endsWith("'") || seg.endsWith('h');
+ if (!hardened) {
+ throw err(`invalid derivation path '${path}' — ed25519 requires every segment hardened (e.g. 0')`);
+ }
+ const n = Number(seg.slice(0, -1));
+ if (!Number.isInteger(n) || n < 0 || n >= 0x80000000) {
+ throw err(`invalid derivation path segment '${seg}'`);
+ }
+ return n;
+ });
+}
+
+/**
+ * SLIP-0010 ed25519 key derivation. Returns the 32-byte private key (IL) at the
+ * given hardened path. Master: HMAC-SHA512("ed25519 seed", seed). Child:
+ * HMAC-SHA512(chainCode, 0x00 || key || ser32(index | 2^31)).
+ * @param {Buffer} seed 64-byte BIP-39 seed
+ * @param {number[]} indices hardened indices (without the hardening bit)
+ * @returns {Buffer} 32-byte ed25519 private key
+ */
+export function deriveEd25519PrivateKey(seed, indices) {
+ let I = createHmac('sha512', Buffer.from('ed25519 seed', 'utf8')).update(seed).digest();
+ let key = I.subarray(0, 32);
+ let chainCode = I.subarray(32);
+ for (const index of indices) {
+ const hardened = (index | 0x80000000) >>> 0;
+ const data = Buffer.concat([
+ Buffer.from([0]),
+ key,
+ Buffer.from([(hardened >>> 24) & 0xff, (hardened >>> 16) & 0xff, (hardened >>> 8) & 0xff, hardened & 0xff]),
+ ]);
+ I = createHmac('sha512', chainCode).update(data).digest();
+ key = I.subarray(0, 32);
+ chainCode = I.subarray(32);
+ }
+ return Buffer.from(key);
+}
+
+/**
+ * Full pipeline: mnemonic → Solana Keypair at the given BIP-44 path. The
+ * returned Keypair's `secretKey` is the standard 64-byte Ed25519 form that
+ * Phantom / Solflare / `solana-keygen` import directly.
+ * @param {string} mnemonic
+ * @param {object} [opts]
+ * @param {number} [opts.account=0] account index (the 3rd path level)
+ * @param {number} [opts.change=0] change index (the 4th path level)
+ * @param {string} [opts.passphrase=''] BIP-39 passphrase
+ * @returns {{ keypair: Keypair, derivationPath: string }}
+ */
+export function deriveSolanaKeypair(mnemonic, opts = {}) {
+ const account = opts.account ?? 0;
+ const change = opts.change ?? 0;
+ const derivationPath = `m/${SOLANA_PURPOSE}'/${SOLANA_COIN_TYPE}'/${account}'/${change}'`;
+ const seed = mnemonicToSeed(mnemonic, opts.passphrase || '');
+ const priv = deriveEd25519PrivateKey(seed, parseDerivationPath(derivationPath));
+ return { keypair: Keypair.fromSeed(priv), derivationPath };
+}
diff --git a/src/solana/vanity/sealed-envelope.js b/src/solana/vanity/sealed-envelope.js
new file mode 100644
index 000000000..4bfe19bb7
--- /dev/null
+++ b/src/solana/vanity/sealed-envelope.js
@@ -0,0 +1,208 @@
+/**
+ * Sealed envelope — hybrid public-key encryption for one-time secret delivery.
+ *
+ * The vanity grinder hands a freshly-ground Solana secret key back to the
+ * buyer. By default that secret travels in the response body in the clear
+ * (TLS only). A caller who would rather the platform never see their secret in
+ * plaintext — not in transit, not in a proxy log, not in an idempotency cache —
+ * supplies an X25519 public key up front; the server seals the secret to it so
+ * only the holder of the matching private key can open it.
+ *
+ * Scheme `x25519-hkdf-sha256-aes256gcm/v1` (ECIES over Curve25519):
+ * 1. Generate an ephemeral X25519 keypair `e`.
+ * 2. shared = X25519(e.secret, recipientPublicKey).
+ * 3. key = HKDF-SHA256(ikm=shared, salt=e.public‖recipientPublicKey,
+ * info="three.ws sealed-envelope v1", 32 bytes).
+ * 4. AES-256-GCM encrypt the plaintext under `key` with a random 12-byte
+ * nonce; the ephemeral public key is bound in as additional authenticated
+ * data so a swapped epk fails the tag check.
+ * 5. Emit { scheme, epk, nonce, ciphertext, recipient } — all Base64url
+ * except `epk`/`recipient`, which are Base58 to match Solana tooling.
+ *
+ * The ephemeral secret is discarded immediately, so the sealed envelope is
+ * forward-secret with respect to the server: nothing retained on our side can
+ * reconstruct the key. `openSealed` is the inverse and ships so clients, the
+ * SDK, and tests share one verified implementation rather than reinventing the
+ * decrypt against a prose spec.
+ *
+ * Isomorphic by construction: ECDH/HKDF come from @noble (pure JS), AES-GCM
+ * from WebCrypto (`globalThis.crypto.subtle`), so it runs unchanged in Node
+ * serverless functions and in the browser.
+ */
+
+import bs58 from 'bs58';
+import { x25519 } from '@noble/curves/ed25519.js';
+import { hkdf } from '@noble/hashes/hkdf.js';
+import { sha256 } from '@noble/hashes/sha2.js';
+
+export const SEALED_ENVELOPE_SCHEME = 'x25519-hkdf-sha256-aes256gcm/v1';
+const HKDF_INFO = new TextEncoder().encode('three.ws sealed-envelope v1');
+const X25519_KEY_BYTES = 32;
+const NONCE_BYTES = 12;
+
+const cryptoObj = globalThis.crypto;
+
+// WebCrypto is checked at call time (not import time) so merely importing this
+// module never throws in an exotic bundle — only sealing/opening requires subtle.
+function subtle() {
+ if (!cryptoObj?.subtle) {
+ throw new Error('sealed-envelope requires WebCrypto (globalThis.crypto.subtle)');
+ }
+ return cryptoObj.subtle;
+}
+
+function randomBytes(n) {
+ const b = new Uint8Array(n);
+ cryptoObj.getRandomValues(b);
+ return b;
+}
+
+function toBase64url(bytes) {
+ let bin = '';
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function fromBase64url(str) {
+ const pad = str.length % 4 === 0 ? '' : '='.repeat(4 - (str.length % 4));
+ const bin = atob(str.replace(/-/g, '+').replace(/_/g, '/') + pad);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
+
+/**
+ * Parse a 32-byte X25519 key supplied as a Uint8Array, Base58, Base64url, or
+ * hex string. Throws a 400-tagged error on anything that isn't a 32-byte key.
+ * @param {Uint8Array|string} key
+ * @param {string} [label='key']
+ * @returns {Uint8Array}
+ */
+export function parseX25519Key(key, label = 'key') {
+ let bytes;
+ if (key instanceof Uint8Array) {
+ bytes = key;
+ } else if (typeof key === 'string') {
+ const s = key.trim();
+ try {
+ if (/^[0-9a-fA-F]{64}$/.test(s)) {
+ bytes = Uint8Array.from(s.match(/.{2}/g).map((h) => parseInt(h, 16)));
+ } else if (/^[1-9A-HJ-NP-Za-km-z]+$/.test(s) && !s.includes('-') && !s.includes('_')) {
+ bytes = bs58.decode(s);
+ } else {
+ bytes = fromBase64url(s);
+ }
+ } catch {
+ throw Object.assign(new Error(`${label} is not valid Base58/Base64/hex`), {
+ status: 400,
+ code: 'invalid_recipient_key',
+ });
+ }
+ } else {
+ throw Object.assign(new Error(`${label} must be a string or Uint8Array`), {
+ status: 400,
+ code: 'invalid_recipient_key',
+ });
+ }
+ if (bytes.length !== X25519_KEY_BYTES) {
+ throw Object.assign(
+ new Error(`${label} must be a 32-byte X25519 key (got ${bytes.length} bytes)`),
+ { status: 400, code: 'invalid_recipient_key' },
+ );
+ }
+ return bytes;
+}
+
+function toBytes(plaintext) {
+ return typeof plaintext === 'string' ? new TextEncoder().encode(plaintext) : plaintext;
+}
+
+/**
+ * Seal a plaintext to a recipient's X25519 public key.
+ * @param {Uint8Array|string} plaintext
+ * @param {Uint8Array|string} recipientPublicKey - 32-byte X25519 public key.
+ * @returns {Promise<{scheme:string, epk:string, nonce:string, ciphertext:string, recipient:string}>}
+ */
+export async function sealToRecipient(plaintext, recipientPublicKey) {
+ const recipientPub = parseX25519Key(recipientPublicKey, 'recipient public key');
+ const ephemeralSecret = x25519.utils.randomSecretKey();
+ const ephemeralPublic = x25519.getPublicKey(ephemeralSecret);
+ const shared = x25519.getSharedSecret(ephemeralSecret, recipientPub);
+
+ const salt = new Uint8Array(ephemeralPublic.length + recipientPub.length);
+ salt.set(ephemeralPublic, 0);
+ salt.set(recipientPub, ephemeralPublic.length);
+ const keyBytes = hkdf(sha256, shared, salt, HKDF_INFO, 32);
+
+ const key = await subtle().importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);
+ const nonce = randomBytes(NONCE_BYTES);
+ const ct = await subtle().encrypt(
+ { name: 'AES-GCM', iv: nonce, additionalData: ephemeralPublic },
+ key,
+ toBytes(plaintext),
+ );
+
+ // Wipe the ephemeral secret + derived key from the local copy. (Best-effort:
+ // GC'd byte arrays may linger, but we don't keep a live reference.)
+ ephemeralSecret.fill(0);
+ keyBytes.fill(0);
+
+ return {
+ scheme: SEALED_ENVELOPE_SCHEME,
+ epk: bs58.encode(ephemeralPublic),
+ nonce: toBase64url(nonce),
+ ciphertext: toBase64url(new Uint8Array(ct)),
+ recipient: bs58.encode(recipientPub),
+ };
+}
+
+/**
+ * Open a sealed envelope with the recipient's X25519 secret key.
+ * @param {{scheme:string, epk:string, nonce:string, ciphertext:string}} envelope
+ * @param {Uint8Array|string} recipientSecretKey - 32-byte X25519 secret key.
+ * @returns {Promise<Uint8Array>} the decrypted plaintext bytes.
+ */
+export async function openSealed(envelope, recipientSecretKey) {
+ if (!envelope || envelope.scheme !== SEALED_ENVELOPE_SCHEME) {
+ throw Object.assign(new Error(`unsupported sealed-envelope scheme: ${envelope?.scheme}`), {
+ code: 'unsupported_scheme',
+ });
+ }
+ const secret = parseX25519Key(recipientSecretKey, 'recipient secret key');
+ const ephemeralPublic = parseX25519Key(envelope.epk, 'ephemeral public key');
+ const shared = x25519.getSharedSecret(secret, ephemeralPublic);
+ const recipientPub = x25519.getPublicKey(secret);
+
+ const salt = new Uint8Array(ephemeralPublic.length + recipientPub.length);
+ salt.set(ephemeralPublic, 0);
+ salt.set(recipientPub, ephemeralPublic.length);
+ const keyBytes = hkdf(sha256, shared, salt, HKDF_INFO, 32);
+
+ const key = await subtle().importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);
+ const pt = await subtle().decrypt(
+ { name: 'AES-GCM', iv: fromBase64url(envelope.nonce), additionalData: ephemeralPublic },
+ key,
+ fromBase64url(envelope.ciphertext),
+ );
+ keyBytes.fill(0);
+ return new Uint8Array(pt);
+}
+
+/** Open a sealed envelope and decode the plaintext as UTF-8 text. */
+export async function openSealedText(envelope, recipientSecretKey) {
+ return new TextDecoder().decode(await openSealed(envelope, recipientSecretKey));
+}
+
+/**
+ * Generate a throwaway X25519 recipient keypair (Base58-encoded). Clients that
+ * don't already manage an X25519 key call this, pass `publicKey` as `sealTo`,
+ * and keep `secretKey` to open the envelope.
+ * @returns {{publicKey:string, secretKey:string}}
+ */
+export function generateRecipientKeypair() {
+ const secret = x25519.utils.randomSecretKey();
+ return {
+ publicKey: bs58.encode(x25519.getPublicKey(secret)),
+ secretKey: bs58.encode(secret),
+ };
+}
diff --git a/src/trader.js b/src/trader.js
index 398e2a80e..57c352727 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -13,6 +13,7 @@ import {
identicon, verifiedBadge,
} from './trader-format.js';
import { mountCopyPanel } from './copy-panel.js';
+import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
const WINDOWS = ['24h', '7d', '30d', 'all'];
const WINDOW_LABEL = { '24h': '24h', '7d': '7d', '30d': '30d', all: 'All-time' };
@@ -204,6 +205,13 @@ function render(data) {
const walletLink = a.wallet
? `<a href="${solscanAddr(a.wallet)}" target="_blank" rel="noopener" title="Agent wallet on Solscan">${escapeHtml(shortAddr(a.wallet, 4, 4))} ↗</a>`
: '';
+ // Shared agent-wallet chip in the profile header. This is a public track-record
+ // page with no ownership signal, so isOwner:false — viewers get the Tip action,
+ // never owner controls. Renders nothing when the trader has no custodial wallet.
+ const walletChip = walletChipHTML(
+ { ...a, solana_address: a.wallet, avatar_thumbnail_url: a.image || '' },
+ { isOwner: false, showPending: false },
+ );
document.title = `${a.name || 'Trader'} · track record · three.ws`;
const winSeg = WINDOWS.map((w) => `<button class="lb-seg-btn ${w === ctx.window ? 'is-active' : ''}" data-window="${w}">${WINDOW_LABEL[w]}</button>`).join('');
@@ -222,6 +230,7 @@ function render(data) {
${m.last_active_at ? `<span>active ${relTime(m.last_active_at)}</span>` : ''}
${a.copiers ? `<span class="tp-copiers">${a.copiers} copying</span>` : ''}
</div>
+ ${walletChip ? `<div class="tp-wallet-chip" style="margin-top:var(--space-2xs)">${walletChip}</div>` : ''}
${a.description ? `<p class="tp-desc">${escapeHtml(a.description)}</p>` : ''}
</div>
<div class="tp-gauge">
@@ -288,6 +297,7 @@ function render(data) {
wireTabs();
wireWindow();
wireShare();
+ wireWalletChips(content);
const panel = document.getElementById('tp-copy-panel');
if (panel) mountCopyPanel(panel, { leaderAgentId: a.id, leaderName: a.name, network: ctx.network });
root.setAttribute('aria-busy', 'false');
diff --git a/src/worlds-lobby.js b/src/worlds-lobby.js
index 6f7338a50..fbcbc1835 100644
--- a/src/worlds-lobby.js
+++ b/src/worlds-lobby.js
@@ -14,6 +14,7 @@
import { AvatarGalleryPicker } from './avatar-gallery-picker.js';
import { AgentPicker } from './agent-picker.js';
+import { walletChipEl, hasWallet } from './shared/agent-wallet-chip.js';
// ── tiny DOM helpers ─────────────────────────────────────────────────────────
const $ = (sel, root = document) => root.querySelector(sel);
@@ -43,6 +44,7 @@ const LS = {
avatarName: 'tws:worldAvatarName',
avatarUrl: 'tws:worldAvatarUrl',
avatarThumb: 'tws:worldAvatarThumb',
+ avatarWallet: 'tws:worldAvatarWallet',
};
const lsGet = (k) => { try { return localStorage.getItem(k) || ''; } catch { return ''; } };
const lsSet = (k, v) => { try { localStorage.setItem(k, v ?? ''); } catch {} };
@@ -74,6 +76,7 @@ function currentAvatar() {
name: lsGet(LS.avatarName) || 'Avatar',
model_url: lsGet(LS.avatarUrl) || '',
thumbnail_url: lsGet(LS.avatarThumb) || '',
+ solana_address: lsGet(LS.avatarWallet) || '',
};
}
return null;
@@ -85,6 +88,7 @@ function setAvatar(a) {
lsSet(LS.avatarName, a?.name || '');
lsSet(LS.avatarUrl, a?.model_url || '');
lsSet(LS.avatarThumb, a?.thumbnail_url || '');
+ lsSet(LS.avatarWallet, a?.solana_address || '');
renderAvatarPanel();
}
@@ -97,6 +101,9 @@ async function resolveAvatar(id) {
name: avatar.name || 'Avatar',
model_url: avatar.model_url || avatar.url || '',
thumbnail_url: avatar.thumbnail_url || '',
+ // Carry the linked agent's custodial wallet so the selection card can
+ // surface it. Avatar rows expose agent_solana_address (api/_lib/avatars.js).
+ solana_address: avatar.agent_solana_address || avatar.solana_address || '',
};
}
@@ -135,6 +142,19 @@ function renderAvatarPanel() {
]);
host.appendChild(meta);
+ // Surface the chosen agent/avatar's custodial wallet so the same identity reads
+ // the same everywhere. Viewer ownership is unknown on this no-sign-in front
+ // door → isOwner:false (a Tip action, never owner controls). No-op when the
+ // selected record carries no wallet (showPending:false).
+ if (a && hasWallet(a)) {
+ const chip = walletChipEl(a, { isOwner: false, showPending: false });
+ if (chip) {
+ chip.classList.add('wl-avatar-wallet');
+ chip.style.marginTop = '8px';
+ meta.appendChild(chip);
+ }
+ }
+
if (nameInput && !nameInput.value) {
nameInput.value = lsGet(LS.name) || `guest-${Math.random().toString(36).slice(2, 6)}`;
}
@@ -182,6 +202,7 @@ function wireAvatarActions() {
name: avatar.name || 'Avatar',
model_url: avatar.model_url || '',
thumbnail_url: avatar.thumbnail_url || '',
+ solana_address: avatar.agent_solana_address || avatar.solana_address || '',
});
},
});
@@ -206,6 +227,7 @@ function wireAvatarActions() {
name: agent.name || 'Agent',
model_url: modelUrl,
thumbnail_url: thumb,
+ solana_address: agent.solana_address || agent.meta?.solana_address || agent.wallet || '',
});
toast(`Dropping in as ${agent.name || 'agent'}.`, 'ok');
},
diff --git a/tasks/trading-frontier/01-conversational-trading-copilot.md b/tasks/trading-frontier/01-conversational-trading-copilot.md
new file mode 100644
index 000000000..48cf8f2b2
--- /dev/null
+++ b/tasks/trading-frontier/01-conversational-trading-copilot.md
@@ -0,0 +1,90 @@
+# Task 01 — Conversational Trading Copilot (voice + chat, in-world execution)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best in the
+> world. Genuinely innovative, not a clone. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Wire 100% end-to-end with REAL APIs and real on-chain
+> data. The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints
+> in generic trade plumbing are the only exception and are never promoted.
+
+## ⛓ Chain protocol — do this as STEP 0, before building
+
+This task is a node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before you
+build the feature below:
+1. Read all of `tasks/` (every epic) + `tasks/trading-frontier/BACKLOG.md`. Know what exists/planned.
+2. Invent **10 genuinely new, non-duplicate feature ideas**, each innovative, grounded in the real
+ three.ws codebase (cite real files/APIs/tables), advancing sniping/trading/launching/buying/selling.
+3. Write each as a full prompt in `tasks/trading-frontier/next/<slug>.md`, matching this file's
+ structure exactly — including this Chain protocol section, so the chain continues.
+4. Append one line per new prompt to `BACKLOG.md` after confirming it isn't a duplicate.
+5. Only then build YOUR feature to the **production-ready bar** in the epic README, and `git rm`
+ this file in the completion commit.
+
+## The invention
+
+three.ws agents are 3D characters with voices and personas. Make the agent a **conversational
+trading copilot**: the user talks (text or voice) — "what's the safest new launch right now?",
+"buy me 0.5 SOL of the one smart money is in, take profit at 2x", "how's my position?" — and the
+agent answers with real data and *executes real trades* through the guarded paths, narrating what
+it did and why. A trading terminal you can simply talk to, in-world. Nobody has that.
+
+## Context (real, verified)
+
+- Agent persona + voice: `agent_identities` (`persona_prompt`, `voice_provider`, `voice_id`,
+ `voice_settings`); LLM access via the platform's existing worker proxy (CLAUDE.md: OpenAI/
+ Anthropic via worker proxies — use it; no browser-side keys).
+- Trade execution (guarded, server-signed): `api/agents/agent-trade.js`, `api/agents/solana-trade.js`;
+ spend guards `api/_lib/agent-trade-guards.js`; firewall `tasks/next-gen-trading/01`.
+- Live market context the copilot can cite: intel (`pump_coin_intel`), oracle
+ (`oracle_conviction`), positions (`api/sniper/stream.js`), balances (`api/agents/solana-wallet.js`).
+- Chat UI surfaces + SDK: `sdk/src/index.js` (AgentKit panel), agent-detail chat, wallet hub.
+
+## Goal
+
+A tool-calling trading copilot: an LLM with a real **trade/quote/portfolio/intel toolset**, a
+confirm-before-execute safety model, optional voice in/out, surfaced as a conversation that can
+actually trade from the agent wallet.
+
+## What to build
+
+1. **Copilot tool layer** — define a real function/tool schema the LLM calls: `getQuote`,
+ `assessSafety` (firewall), `getSmartMoney`, `getPositions`, `getBalance`, `placeBuy`,
+ `placeSell`, `setStrategy`. Each maps to the existing guarded endpoints — the LLM never signs;
+ it calls server endpoints that enforce spend limits + firewall + custody audit.
+2. **Confirm-before-execute** — any state-changing action (buy/sell/arm) returns a structured
+ proposal the user must confirm (UI affirmation or explicit voice "confirm"); express mode after
+ first confirm, per-session, never bypassing spend caps. Read-only queries run freely.
+3. **Voice** — optional speech-to-text in + the agent's configured voice out (use the existing
+ voice provider config); text-only fully functional without voice.
+4. **Grounded answers** — the copilot cites real numbers (price, impact, safety verdict, smart-
+ money count, PnL) pulled live; it never invents figures. If data is unavailable, it says so.
+5. **UI** — a copilot panel (in agent-detail + wallet hub): conversation with streamed responses,
+ inline trade-proposal cards (showing quote + firewall verdict + confirm/cancel), voice toggle,
+ and a transcript of executed actions linking to Solscan. All states designed; accessible
+ (ARIA live regions, keyboard); responsive.
+
+## Constraints
+
+- The LLM proposes; the guarded server endpoints decide. Spend limits, kill switch, and firewall
+ are never bypassable by conversation. Every execution is audited in `agent_custody_events`.
+- Real LLM + real market data only — no canned responses, no fake quotes. Honest degradation on
+ failures with retry.
+- $THREE-only rule in all copilot copy/examples; runtime mints are trade data only.
+
+## Success criteria
+
+- A user can converse (text + optional voice) and the copilot answers with live data and executes
+ a real, confirmed, firewall+spend-guarded trade from the agent wallet, audited.
+- Confirm-before-execute enforced; read-only queries free; data is real and cited.
+- Copilot UI renders all states, accessible + responsive. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/01-conversational-trading-copilot.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/02-programmable-orders-engine.md b/tasks/trading-frontier/02-programmable-orders-engine.md
new file mode 100644
index 000000000..6b8ee3df9
--- /dev/null
+++ b/tasks/trading-frontier/02-programmable-orders-engine.md
@@ -0,0 +1,85 @@
+# Task 02 — Programmable Orders Engine (limit / stop / DCA / TWAP / conditional triggers)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+Pump.fun has no native order types — you watch a chart and click frantically. We give every agent
+wallet a real **programmable order layer**: limit buys/sells, stop-loss + trailing stops that
+survive across sessions, **DCA** (recurring buys), **TWAP** (slice a large order over time to cut
+impact), and **conditional triggers** ("buy when smart-money score > X", "sell if dev dumps",
+"buy on graduation"). A worker watches the market and fires from the agent wallet automatically.
+Set-and-forget institutional order tooling for memecoins.
+
+## Context (real, verified)
+
+- Execution + quotes: `api/agents/agent-trade.js`, `api/_lib/pump.js` (curve + AMM quotes),
+ `api/_lib/pump-swap-ix.js`; spend guards `api/_lib/agent-trade-guards.js`; firewall
+ `tasks/next-gen-trading/01`; MEV engine `tasks/next-gen-trading/02`.
+- Worker loop + position lifecycle precedent: `workers/agent-sniper/index.js`,
+ `workers/agent-sniper/positions.js` (`runPositionSweep`, `decideExit`), per-agent lock pattern.
+- Trigger inputs: live price re-quote (curve/AMM), intel (`pump_coin_intel`), smart-money
+ (`tasks/next-gen-trading/03`), graduation events (`api/_lib/pumpfun-ws-feed.js`).
+- Custody audit: `agent_custody_events`.
+
+## Goal
+
+An `orders` model + a worker that evaluates triggers against live market data and executes
+firewall+spend-guarded fills from the agent wallet, with a full order-management UI.
+
+## What to build
+
+1. **Order model** — `orders` table (id, agent_id, user_id, network, mint, type
+ [limit|stop|trailing|dca|twap|conditional], side, size, limit_price/stop_price/trail_pct,
+ schedule (for dca/twap: interval, slices, total), condition jsonb (for conditional triggers),
+ status [active|partial|filled|cancelled|expired], filled_amount, expires_at, created_at) +
+ `order_fills` audit. Dated migration.
+2. **Evaluation worker** — extend `workers/agent-sniper/` (or sibling) to sweep active orders on a
+ cadence: re-quote each order's mint, evaluate its trigger/schedule, and on fire, execute through
+ the firewall + MEV engine + spend guards, recording fills. DCA/TWAP advance their schedule and
+ partial-fill; trailing stops track the high-water mark like `decideExit`. Idempotent; per-agent
+ serialized; honest on RPC failure (retry, don't double-fire).
+3. **Condition language** — a safe, validated condition spec (no arbitrary code) for triggers over
+ real signals: price thresholds, smart-money score, dev-dump flag, graduation, market-cap bands.
+4. **API + UI** — `/api/orders` (CRUD, cancel), `/api/orders/:id` (state + fills), SSE for live
+ order status. Build an **Orders** surface in the wallet hub: create order (per-type forms with
+ sane presets + a live preview of the fill condition + firewall verdict), an open-orders table
+ with cancel, and a fills history. All states designed; accessible; responsive.
+
+## Constraints
+
+- Every fill is real, firewall-gated, spend-guarded, audited; kill switch halts all orders; cancel
+ is instant. Orders can never exceed daily budget or per-trade caps.
+- Triggers evaluate against **real live data** only — never simulated prices. Honest on data gaps.
+- No arbitrary-code conditions; validated spec only. $THREE-only rule; runtime mints are data.
+
+## Success criteria
+
+- Each order type (limit/stop/trailing/DCA/TWAP/conditional) fires correctly from real market data
+ through the firewall + MEV engine, audited, with partials handled.
+- Orders UI renders all states; cancel + kill instant. Production-ready bar met; chain extended.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/02-programmable-orders-engine.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/03-portfolio-intelligence-command.md b/tasks/trading-frontier/03-portfolio-intelligence-command.md
new file mode 100644
index 000000000..cde2ffab9
--- /dev/null
+++ b/tasks/trading-frontier/03-portfolio-intelligence-command.md
@@ -0,0 +1,85 @@
+# Task 03 — Portfolio Intelligence & Risk Command (unified cross-wallet)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+A trader on three.ws has SOL, SPL holdings, open sniper positions, discretionary positions, and
+(soon) orders/swarms — scattered. Build a **Portfolio Command**: one real-time, unified view of
+everything the agent wallet holds and has done, with honest **PnL attribution** (which strategy /
+signal / source made or lost money), live **risk metrics** (exposure, concentration, drawdown,
+correlation to the broad pump.fun tape), and a cost-basis / realized-vs-unrealized breakdown.
+Bloomberg-grade portfolio analytics for an AI agent's wallet — nothing like it exists for memecoins.
+
+## Context (real, verified)
+
+- Balances: `api/agents/solana-wallet.js` (SOL + SPL holdings, USDC). Live SOL price: feed util in
+ `api/_lib/pumpfun-ws-feed.js#getSolPrice` / `agent-trade-guards.js#lamportsToUsd`.
+- Trade truth: `agent_sniper_positions`, `agent_custody_events` (spend/withdraw/trade/snipe/x402),
+ discretionary trades via `api/agents/solana-trade.js` history.
+- Metrics engine to reuse/extend: `api/_lib/trader-stats.js` (`computeTraderMetrics`: PnL, ROI,
+ drawdown, Sharpe, profit factor, churn). Live position updates: `api/sniper/stream.js`.
+- Token valuation: curve/AMM quotes `api/_lib/pump.js` (`getAmmPoolState`).
+
+## Goal
+
+A portfolio service (`api/_lib/portfolio.js` + `/api/agents/:id/portfolio`) that values all
+holdings live, attributes PnL by source, computes risk, and a Portfolio Command UI — all from real
+on-chain + ledger data.
+
+## What to build
+
+1. **Valuation + holdings** — enumerate the agent wallet's SOL + every SPL holding, value each via
+ live curve/AMM quotes (graceful for illiquid/dead tokens — mark unpriceable, don't crash), sum
+ to a real total in SOL + USD. Cache briefly; never fabricate a price.
+2. **PnL attribution** — reconcile `agent_custody_events` + positions into realized vs unrealized
+ PnL, attributed by source: discretionary, each sniper strategy, signal feed (task 06 of
+ next-gen), swarm, MM. Cost-basis per holding (FIFO lots) for accurate realized PnL.
+3. **Risk metrics** — live exposure (% of net worth at risk), concentration (largest position
+ share + a Herfindahl-style score), max drawdown, realized volatility, and correlation of the
+ portfolio's moves to the broad pump.fun tape (from intel/feed aggregates). Surface plain-language
+ risk flags ("78% concentrated in one illiquid position").
+4. **API + UI** — `/api/agents/:id/portfolio` (holdings, valuation, attribution, risk) + SSE for
+ live updates. Build a **Portfolio Command** surface in the wallet hub: net-worth header with
+ live sparkline, holdings table (value, cost basis, unrealized PnL, liquidity warning), an
+ attribution breakdown (what's making/losing money), a risk panel, and one-click jump to
+ trade/exit any holding. All states designed (incl. a helpful empty state for a fresh wallet);
+ accessible; responsive.
+
+## Constraints
+
+- Every value is real and live; unpriceable/illiquid holdings are honestly flagged, never guessed.
+- Read-only analytics + jump-to-action; all actual trades go through existing guarded paths.
+- Performance: value holdings concurrently, cache, virtualize long tables. $THREE-only rule.
+
+## Success criteria
+
+- Portfolio values all real holdings live in SOL + USD with cost basis and realized/unrealized PnL,
+ attributed by source, with live risk metrics and honest illiquidity flags.
+- Portfolio Command UI renders all states, updates live, is responsive + accessible.
+- Production-ready bar met; chain extended. Build/typecheck/test clean. Changelog (tags: feature,
+ improvement). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/03-portfolio-intelligence-command.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/04-graduation-predictor.md b/tasks/trading-frontier/04-graduation-predictor.md
new file mode 100644
index 000000000..d2a7e44bd
--- /dev/null
+++ b/tasks/trading-frontier/04-graduation-predictor.md
@@ -0,0 +1,88 @@
+# Task 04 — Graduation Predictor (calibrated ML model on intel + outcomes)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+We have captured, for thousands of launches, the structural signals at birth (`pump_coin_intel`)
+AND the eventual ground-truth outcome (`pump_coin_outcomes`: graduated / pumped / flat / rugged,
+`ath_multiple`). That is a labeled dataset nobody else has. Train a **calibrated probability model**
+that, for any live launch, outputs "P(graduates) = 73%, P(2x+) = 41%, P(rug) = 12%" with a real
+confidence band — and feed it into every trading decision and the UI. The existing `intel/learn.js`
+does per-signal win-rates; this is the full multivariate, calibrated successor.
+
+## Context (real, verified)
+
+- Training data: `pump_coin_intel` (features) ⋈ `pump_coin_outcomes` (labels). Existing learning
+ loop to supersede/extend: `workers/agent-sniper/intel/learn.js` → `pump_intel_weights`.
+- Consumers: `workers/agent-sniper/scorer.js#scoreIntel`, `oracle-gate.js`, the NL backtester
+ (`tasks/next-gen-trading/05`), Mission Control (`tasks/next-gen-trading/09`).
+- Inference must run server-side (Vercel functions / worker) — no heavy native deps that break the
+ serverless build; prefer a lightweight, dependency-light model (e.g. gradient-boosted trees or
+ logistic regression implemented/served in-process) trained offline and shipped as weights.
+
+## Goal
+
+A trainable, **calibrated** graduation/outcome model with versioned weights, a recompute/retrain
+job, a fast `predictOutcome(features)` used across the platform, and a UI that shows honest
+probabilities with calibration evidence.
+
+## What to build
+
+1. **Feature pipeline** — assemble a clean training matrix from `pump_coin_intel` ⋈
+ `pump_coin_outcomes` (bundle/organic/concentration/snipe_ratio/fresh_wallet_ratio/entropy/
+ quality_score/creator pedigree/category). Handle class imbalance and time-based splits to avoid
+ leakage. Persist as a reproducible job under `scripts/` or `workers/`.
+2. **Model + calibration** — train a dependency-light classifier for multiple heads (graduates,
+ 2x+, rug), **calibrate** probabilities (Platt/isotonic) and store reliability data so the
+ probabilities mean what they say. Version the weights in a `model_versions` table (version,
+ trained_at, metrics: AUC, log-loss, Brier, calibration error, sample_size, feature_importance).
+3. **Inference service** — `api/_lib/graduation-model.js#predict(features)` returning calibrated
+ probabilities + a confidence band + top contributing features (explainability). Fast, cached per
+ mint. Wire into `scoreIntel`/`oracle-gate` (as an optional gate `min_graduation_prob`) and expose
+ `GET /api/intel/predict?mint=…`.
+4. **Honesty + drift** — show live model metrics + a reliability diagram; track prediction-vs-
+ realized drift over time and flag when retraining is due. Never present an uncalibrated or
+ stale number as fact.
+5. **UI** — a **Prediction** panel (on coin/trade/terminal surfaces): probability bars with
+ confidence band, top drivers ("high organic distribution, graduated creator"), and a link to the
+ model's live accuracy. All states designed; accessible; responsive.
+
+## Constraints
+
+- Trained only on **real captured data**; never synthesize launches/outcomes. If data is too thin
+ for a calibrated estimate, return "insufficient signal" — never a confident fake.
+- Probabilities must be calibrated and explainable; surface metrics + drift honestly.
+- Serverless-safe inference (no build-breaking native deps). $THREE-only rule.
+
+## Success criteria
+
+- A versioned, calibrated model trains from real intel⋈outcomes with stored metrics + reliability.
+- `predict()` returns calibrated probabilities + confidence + drivers, wired into scoring and a
+ public endpoint; an optional `min_graduation_prob` gate works.
+- Prediction UI renders all states with honest accuracy + drift. Production-ready bar met; chain
+ extended. Build/typecheck/test clean. Changelog (tags: feature, improvement). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/04-graduation-predictor.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/05-multichain-agent-treasury.md b/tasks/trading-frontier/05-multichain-agent-treasury.md
new file mode 100644
index 000000000..9e80b58d0
--- /dev/null
+++ b/tasks/trading-frontier/05-multichain-agent-treasury.md
@@ -0,0 +1,86 @@
+# Task 05 — Multi-Chain Agent Treasury & Bridge
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+Agents already have BOTH an EVM wallet and a Solana wallet (`api/_lib/agent-wallet.js`), and
+ERC-8004 identity spans 15+ chains (`api/_lib/onchain.js`). But the trading life is Solana-locked
+and capital is stranded per chain. Build a **unified multi-chain treasury**: one view of the
+agent's balances across every chain, and real **bridging** so a user can move USDC/SOL/ETH into the
+Solana trading wallet (or back out) in a couple of clicks, with the agent picking a safe route. An
+AI agent with a single cross-chain treasury that funds its own trading — a genuinely new primitive.
+
+## Context (real, verified)
+
+- Dual custodial wallets: `api/_lib/agent-wallet.js` (`getOrCreateAgentEvmWallet`,
+ `getOrCreateAgentSolanaWallet`, `provisionAgentWallets`, encryption v2 HKDF+AES-GCM).
+- Multi-chain identity + RPCs: `api/_lib/onchain.js` (`SERVER_CHAIN_META`, 15 mainnets + 6
+ testnets). EVM signing patterns + balances live in the on-chain + agent-payments paths.
+- Solana side: `api/agents/solana-wallet.js` (balances, withdraw), USDC mints per cluster.
+- Withdraw/custody discipline + audit: `api/_lib/agent-trade-guards.js`, `agent_custody_events`.
+- A real bridge API (e.g. a reputable cross-chain bridge/aggregator with a public API) — integrate
+ one real provider; never simulate a bridge. Add its config to env, document required keys.
+
+## Goal
+
+A multi-chain balance service + a real bridge integration so funds can move into/out of the Solana
+trading wallet across chains, with quotes, route selection, status tracking, and full custody audit.
+
+## What to build
+
+1. **Unified balance service** — `api/_lib/treasury.js` enumerating the agent's native + USDC (and
+ key token) balances across its EVM chains + Solana, valued in USD via real price feeds. Cached;
+ honest on per-chain RPC failure (show that chain as degraded, not zero).
+2. **Bridge integration** — integrate one real bridge/aggregator API: quote a transfer (source
+ chain/asset → Solana wallet), show fees + ETA + route, execute by signing from the agent's
+ custodial wallet on the source chain, and track status to completion. Both directions (top-up
+ the trading wallet; sweep profits out). Idempotent; audited in `agent_custody_events` (category
+ `bridge`); spend-guarded where applicable.
+3. **Safety** — validate destination, enforce the withdraw allowlist for outbound bridges, respect
+ kill switch + limits, and never proceed on an ambiguous/failed quote. Clear handling of the
+ inherently async, occasionally-stuck nature of bridges (status polling, recovery guidance).
+4. **API + UI** — `/api/agents/:id/treasury` (cross-chain balances), `/api/agents/:id/bridge`
+ (quote, execute, status). Build a **Treasury** surface in the wallet hub: a cross-chain balance
+ board (per chain, valued), a bridge flow (pick source → quote → confirm → live status with
+ explorer links), and an outbound sweep. All states designed (including a "bridge pending /
+ delayed" state); accessible; responsive.
+
+## Constraints
+
+- Real bridge + real on-chain txs only — never fake a bridge transfer or a balance. If the bridge
+ API is unavailable, the UI says so and offers no fake path.
+- Custodial keys never leave the server; outbound bridges honor the allowlist + spend guards.
+- $THREE remains the only coin referenced in copy; bridged assets (USDC/SOL/ETH) are functional
+ plumbing, not promotions, and no non-$THREE token is ever recommended.
+
+## Success criteria
+
+- Cross-chain balances render live and valued; a real bridge top-up into the Solana wallet
+ completes and is audited; an outbound sweep respects the allowlist.
+- Bridge flow handles async/stuck states honestly with explorer links. Production-ready bar met;
+ chain extended. Build/typecheck/test clean. Changelog (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/05-multichain-agent-treasury.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/06-creator-reputation-registry.md b/tasks/trading-frontier/06-creator-reputation-registry.md
new file mode 100644
index 000000000..ff36469a0
--- /dev/null
+++ b/tasks/trading-frontier/06-creator-reputation-registry.md
@@ -0,0 +1,91 @@
+# Task 06 — Creator Reputation & Anti-Scam Registry
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+The biggest tell on whether a launch is worth touching is *who launched it* — but that history is
+scattered and easy to hide behind fresh wallets. We already enrich creator history per mint
+(`creator_launches`, `creator_graduated`) and capture every launch's structure + outcome. Build a
+persistent **Creator Reputation & Anti-Scam Registry**: a durable per-creator profile (and cluster,
+via funding graph) scoring lifetime graduation rate, rug rate, average ATH, serial-rug patterns,
+and fresh-wallet evasion — surfaced as a "creator score" everywhere a coin appears, and as a
+searchable directory. A credit bureau for memecoin creators, built from real outcomes.
+
+## Context (real, verified)
+
+- Creator enrichment at launch: `api/_lib/pumpfun-ws-feed.js#enrichMint` (creator history via
+ `frontend-api-v3.pump.fun/coins/user-created-coins/{creator}`).
+- Outcomes + per-wallet funding edges: `pump_coin_outcomes`, `pump_coin_wallets.funder` — the basis
+ for both reputation and cluster/evasion detection (pair with `tasks/next-gen-trading/03` smart-
+ money clustering if present).
+- Consumers: `workers/agent-sniper/scorer.js` (creator gates already exist:
+ `max_creator_launches`, `min_creator_graduated`), `oracle-gate.js`, the firewall
+ (`tasks/next-gen-trading/01`), Mission Control.
+- Risk flags already captured per coin: `pump_coin_intel.risk_flags`.
+
+## Goal
+
+A maintained `creator_reputation` table + cluster linkage, a recompute job, a
+`getCreatorReputation(address)` API used by scoring + firewall + UI, and a public creator directory
+— all derived from real launch outcomes.
+
+## What to build
+
+1. **Reputation model** — `creator_reputation` (creator, network, launches, graduated, rugged,
+ grad_rate, rug_rate, avg_ath_multiple, median_lifespan, score 0–100, labels[] e.g.
+ `serial_rugger`/`reliable_grad`/`fresh_wallet`, cluster_id, first_seen, last_seen, scored_at).
+ Link creators that share funding sources into clusters so a rugger can't escape by spinning up a
+ new wallet (the new wallet inherits cluster reputation with a confidence).
+2. **Recompute job** — a worker/`scripts/` job joining launches ⋈ `pump_coin_outcomes` per creator
+ + cluster, with confidence regression for thin histories (mirror `trader-stats.js`). Idempotent;
+ batched for Neon HTTP; fire-and-forget writes that never block the feed.
+3. **Wire into trading** — feed the real creator score into `scoreMint`/`scoreIntel`, the oracle,
+ and the firewall (WARN/BLOCK on `serial_rugger` clusters). Add strategy gates
+ `min_creator_score` / `block_creator_clusters`.
+4. **API + UI** — `GET /api/intel/creator/:address` (public, rate-limited, cached) and a searchable
+ **Creators** directory (`/api/intel/creators` ranked). Build a creator profile card (score,
+ grad/rug rates, launch history with outcomes, cluster + evasion flags, Solscan links) shown
+ wherever a coin's creator is displayed (coin detail, terminal, trade). All states designed;
+ accessible; responsive; an honest "new creator, no history" state.
+
+## Constraints
+
+- Scores derive only from **real launch outcomes** — no hand-maintained blocklists, no naming/
+ shaming without on-chain evidence. Cluster inheritance carries an explicit confidence, never a
+ certainty. Provide a path to surface false-positive concerns.
+- Public address analytics only; never expose private keys. $THREE-only rule; the registry rates
+ *creators*, never promotes a token.
+
+## Success criteria
+
+- `creator_reputation` + clusters populate from real outcomes; fresh-wallet evasion is linked with
+ confidence; recompute is idempotent.
+- Creator score is wired into scoring + firewall; `min_creator_score`/cluster-block gates work.
+- Creators directory + profile cards render everywhere a creator appears, all states designed.
+- Production-ready bar met; chain extended. Build/typecheck/test clean. Changelog (tags: feature,
+ security). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/06-creator-reputation-registry.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/07-universal-wallet-mirror.md b/tasks/trading-frontier/07-universal-wallet-mirror.md
new file mode 100644
index 000000000..4e1389042
--- /dev/null
+++ b/tasks/trading-frontier/07-universal-wallet-mirror.md
@@ -0,0 +1,92 @@
+# Task 07 — Universal Wallet Mirror (copy any external on-chain wallet)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+Copy-trading on three.ws (signal marketplace, `tasks/next-gen-trading/06`) is agent-to-agent. But
+the best traders on Solana aren't on our platform — yet their wallets are public. Build a
+**Universal Wallet Mirror**: paste any external Solana address, and your agent watches it in real
+time and mirrors its pump.fun/AMM trades from your own wallet — with your own risk scaling, your
+firewall, your spend limits, and a live "how this wallet is doing" panel powered by task-03 smart-
+money + task-06 creator data. Copy the on-chain elite, not just platform users. No competitor lets
+you mirror an arbitrary wallet into an autonomous AI agent's risk-managed wallet.
+
+## Context (real, verified)
+
+- Real-time wallet activity: Helius (`HELIUS_API_KEY`) address webhooks / `getSignaturesForAddress`;
+ RPC failover `api/_lib/solana/connection.js`. Tx parse patterns: `api/_lib/pump-claims.js`,
+ feed `api/_lib/pumpfun-ws-feed.js`.
+- Trade detection: identify pump.fun buy/sell (program id + instruction shapes already parsed in
+ `pump-claims.js` / `pump-swap-ix.js`) from a watched wallet's confirmed txs.
+- Mirror execution: `api/agents/agent-trade.js` + firewall (`tasks/next-gen-trading/01`) + MEV
+ engine (`tasks/next-gen-trading/02`) + spend guards `api/_lib/agent-trade-guards.js`.
+- Existing copy scaffolding to generalize: `copy_subscriptions` + `trader-stats.js` copier counts.
+- Wallet scoring context: `wallet_reputation` (`tasks/next-gen-trading/03`).
+
+## Goal
+
+A mirror service: watch any external Solana wallet, detect its trades on-chain in real time, and
+mirror them risk-scaled through the firewall + spend guards from the agent wallet — with a target
+wallet analytics panel and a clean management UI.
+
+## What to build
+
+1. **Mirror model** — `wallet_mirrors` (agent_id, user_id, target_address, network, mode
+ simulate|live, size_mode [fixed|proportional], max_per_trade, slippage, copy_buys, copy_sells,
+ only_pumpfun, min_target_score, firewall_level, status, created_at) + `mirror_fills` audit.
+2. **Watcher** — a worker that monitors each active target (Helius webhook if configured, else
+ polled signatures with backoff + dedupe), detects pump.fun/AMM buys/sells from confirmed txs in
+ near-real-time, and emits a mirror intent. Honest on RPC/webhook failure (pause + report, never
+ miss-then-fake).
+3. **Risk-scaled mirror execution** — translate the target's trade into the subscriber's sized
+ trade (fixed amount or proportional to the target, clamped to caps), run the firewall, execute
+ via the MEV engine from the agent wallet, record a `mirror_fill` tagged with the target + source
+ tx. Simulate mode mirrors without spending. All spend guards + kill switch apply; instant stop.
+4. **Target analytics** — show the target wallet's live track record (recent trades, win-rate,
+ smart-money score from task 03) so users mirror with eyes open; warn on sybil/low-score targets.
+5. **API + UI** — `/api/mirrors` (CRUD, pause, kill), `/api/mirrors/:id` (state + fills + target
+ analytics), SSE for live mirror events. Build a **Mirror** surface in the wallet hub: add a
+ target (paste address → analytics preview → configure scaling/limits → start), an active-mirrors
+ list with live fills, and a kill control. All states designed; accessible; responsive.
+
+## Constraints
+
+- Detection from **real confirmed on-chain txs** only — never fabricate a target trade. Mirror only
+ after the target's tx confirms (no front-running a third party's pending tx; we copy executed,
+ public trades).
+- Every mirror fill is firewall-gated, spend-guarded, audited; kill is instant; never exceed caps.
+- Latency-aware but safety-first: skip a mirror if the price has moved beyond the user's slippage.
+- $THREE-only rule; target addresses + mints are runtime data, never promotions.
+
+## Success criteria
+
+- A user can mirror an arbitrary external Solana wallet; real confirmed target trades are mirrored
+ risk-scaled through the firewall + MEV engine from the agent wallet, audited; simulate mode works.
+- Target analytics + sybil warnings render; kill instant. Mirror UI all states; responsive +
+ accessible. Production-ready bar met; chain extended. Build/typecheck/test clean. Changelog
+ (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/07-universal-wallet-mirror.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/08-realtime-alert-automation.md b/tasks/trading-frontier/08-realtime-alert-automation.md
new file mode 100644
index 000000000..4d184172c
--- /dev/null
+++ b/tasks/trading-frontier/08-realtime-alert-automation.md
@@ -0,0 +1,89 @@
+# Task 08 — Real-Time Alert & Automation Engine (push / Telegram / in-app)
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+Alpha is worthless if you see it too late. Build a **real-time alert & automation engine**: users
+define alerts over live signals — "ping me when a launch scores >85 with smart money in", "alert if
+my position drops 30%", "tell me when a creator I follow deploys", "notify on a rug flag in
+anything I hold" — delivered via in-app toast, push, and Telegram, **with an optional one-tap auto-
+action** ("...and auto-buy 0.2 SOL", "...and auto-sell"). Alerts that can *act*, wired to the
+firewall + spend guards. Programmable, multi-channel, action-capable — beyond any pump.fun alert bot.
+
+## Context (real, verified)
+
+- Telegram already integrated (changelog push): `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHANGELOG_CHAT_ID`,
+ `scripts/changelog:push`. Reuse the bot plumbing for user-scoped chat IDs.
+- Live signal sources: feed `api/_lib/pumpfun-ws-feed.js`, intel `pump_coin_intel`, oracle
+ `oracle_conviction`, positions `api/sniper/stream.js`, smart-money (`tasks/next-gen-trading/03`),
+ creator reputation (this epic 06), graduation predictor (this epic 04).
+- Auto-actions reuse `api/agents/agent-trade.js` + firewall (`tasks/next-gen-trading/01`) + spend
+ guards `api/_lib/agent-trade-guards.js` + custody audit `agent_custody_events`.
+- Sniper already has a `telegram_chat_id` field on strategies — generalize notifications platform-wide.
+
+## Goal
+
+An alert-rule model + an evaluation worker that watches live signals, delivers multi-channel
+notifications, and optionally fires guarded auto-actions — with a clean rule-builder UI.
+
+## What to build
+
+1. **Alert model** — `alerts` (id, user_id, agent_id, network, scope [market|position|creator|
+ wallet], condition jsonb (validated spec over real signals), channels [in_app|push|telegram],
+ throttle/cooldown, auto_action jsonb nullable (buy/sell with size + limits), status, created_at)
+ + `alert_events` (fired alerts: matched payload, delivered_to, action_taken, at).
+2. **Evaluation worker** — extend `workers/agent-sniper/` (or sibling) to evaluate active alerts
+ against the live feed + intel + positions on a tight cadence, with dedupe + cooldown so users
+ aren't spammed. Honest on data gaps; never fire on stale/fake data.
+3. **Delivery** — in-app (SSE + a notification center), Telegram (per-user chat linking flow:
+ `/start`-style bind), and web push (service worker + VAPID). Each channel reliable, with
+ delivery status recorded. Respect per-user channel prefs + quiet hours.
+4. **Action-capable alerts** — when `auto_action` is set, the fired alert executes a guarded trade
+ from the agent wallet (firewall + spend caps + kill switch + audit). Require an explicit opt-in +
+ per-action confirmation default, with an express mode the user can enable knowingly.
+5. **API + UI** — `/api/alerts` (CRUD, mute), `/api/alerts/events` (history), `/api/notifications/
+ stream` (SSE), push subscription endpoints, Telegram bind. Build an **Alerts** surface: a rule
+ builder with plain-language presets + live preview of what would match now, a channel/prefs
+ panel, and an alert history with the action taken. A platform notification center (bell) for
+ in-app. All states designed; accessible; responsive.
+
+## Constraints
+
+- Alerts evaluate **real live signals** only; auto-actions are firewall + spend-guarded + audited
+ and never bypass limits or the kill switch. Conditions use a validated spec, not arbitrary code.
+- Real delivery only — real Telegram messages, real push; no fake "sent" states. Failures surfaced.
+- $THREE-only rule in all copy/templates; mints in alerts are runtime data.
+
+## Success criteria
+
+- A user defines alerts across market/position/creator/wallet scopes; they fire on real live
+ signals and deliver via in-app + push + Telegram with cooldown/dedupe.
+- An action-capable alert fires a guarded, audited auto-trade with opt-in confirmation.
+- Alerts UI (builder, prefs, history) + notification center render all states; responsive +
+ accessible. Production-ready bar met; chain extended. Build/typecheck/test clean. Changelog
+ (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/08-realtime-alert-automation.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/09-amm-migration-sniper.md b/tasks/trading-frontier/09-amm-migration-sniper.md
new file mode 100644
index 000000000..e797047ca
--- /dev/null
+++ b/tasks/trading-frontier/09-amm-migration-sniper.md
@@ -0,0 +1,89 @@
+# Task 09 — AMM Migration & New-Pool Sniper
+
+> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.
+> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`
+> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception, never promoted.
+
+## ⛓ Chain protocol — STEP 0, before building
+
+Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:
+read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded
+feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching
+this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a
+dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`
+this file in the completion commit.
+
+## The invention
+
+The bonding-curve → AMM **graduation** is one of the most reliably tradeable moments in a coin's
+life: liquidity migrates, a fresh pool opens, and price often moves hard — but most snipers only
+watch *new mints*, not *migrations*. Build a **migration sniper**: detect the exact graduation /
+new-pool-open event in real time and snipe the AMM side on signal (only for coins our intel +
+graduation predictor + smart-money flag as strong), plus detect fresh AMM pools / LP-adds for
+graduated coins. A second, higher-quality snipe surface that the curve-only crowd misses.
+
+## Context (real, verified)
+
+- Graduation events already arrive on the feed: `api/_lib/pumpfun-ws-feed.js` (`enrichGrad`,
+ graduation callback). AMM plumbing: `api/_lib/pump.js` (`getAmmPoolState`, `getPumpSwapSdk`),
+ `workers/agent-sniper/amm-exit.js` (`isGraduated`, `quoteAmmSell`, `buildAmmSellInstructions`) —
+ extend to two-sided AMM trading, not just exit.
+- Snipe loop + scoring to extend: `workers/agent-sniper/index.js`, `scorer.js`, executor +
+ positions; the existing `intel_confirmed` trigger pattern is the closest precedent.
+- Quality gates: intel (`pump_coin_intel`, `pump_coin_outcomes`), graduation predictor (epic 04),
+ smart-money (`tasks/next-gen-trading/03`), firewall (`tasks/next-gen-trading/01`), MEV (`02`).
+
+## Goal
+
+A `trigger='amm_migration'` strategy + detection that snipes the graduation/new-pool moment on the
+AMM with full gating, plus a live migration feed surface.
+
+## What to build
+
+1. **Migration detection** — subscribe to graduation events from the feed and confirm the new
+ canonical AMM pool via `getAmmPoolState`; also detect fresh AMM pools / significant LP-adds for
+ already-graduated coins (poll/scan). Emit a `migration_event { mint, pool, liquidity, ts }`,
+ deduped like the existing watchers.
+2. **AMM buy path** — extend the trade client / AMM module with a real **AMM buy** (PumpSwap SDK)
+ to complement the existing AMM sell, with quote + slippage + price-impact. This unlocks both
+ migration sniping and discretionary AMM buys platform-wide.
+3. **Gated snipe** — for each `amm_migration` strategy, score the migration (intel + graduation
+ probability from epic 04 + smart-money + creator reputation from epic 06), run the firewall, and
+ buy via the MEV engine within budget — racing the migration. All spend guards + custody audit
+ apply; positions tracked + managed by the existing lifecycle (stop/trailing/take/timeout) on the
+ AMM side.
+4. **Schema** — add `trigger='amm_migration'` + AMM-specific gates (`min_pool_liquidity_sol`,
+ `min_graduation_prob`, `require_smart_money`) to `agent_sniper_strategies`; a `migration_events`
+ table. Dated migration.
+5. **API + UI** — `GET /api/sniper/migrations?network=…` + SSE live migration feed. Add a
+ **Migrations** view (and a strategy preset in the snipe tab) showing live graduations/new pools
+ with their quality scores and whether the user's agent fired. All states designed; accessible;
+ responsive.
+
+## Constraints
+
+- Detection from **real graduation/pool events** + real pool reads only — never fabricate a
+ migration. The firewall still gates every AMM buy (no buying an AMM honeypot to be first).
+- AMM buys are real PumpSwap txs, spend-guarded + audited; kill switch halts; respect price-impact.
+- $THREE-only rule; mints/pools are runtime data, never promotions.
+
+## Success criteria
+
+- Real graduation + new-pool events are detected; a real AMM buy path exists and works.
+- An `amm_migration` strategy snipes the migration through the firewall + MEV engine, gated by
+ intel/graduation-prob/smart-money, audited, with positions managed on the AMM side.
+- Migrations UI + SSE render all states. Production-ready bar met; chain extended. Build/typecheck/
+ test clean. Changelog (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)
+
+```bash
+git rm "tasks/trading-frontier/09-amm-migration-sniper.md"
+```
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/trading-frontier/BACKLOG.md b/tasks/trading-frontier/BACKLOG.md
new file mode 100644
index 000000000..bab2f7c69
--- /dev/null
+++ b/tasks/trading-frontier/BACKLOG.md
@@ -0,0 +1,23 @@
+# Trading Frontier — Chain Backlog Index
+
+Single source of truth for the self-extending chain. **Read this before inventing ideas; append to
+it after authoring new prompts.** One line per prompt. Dedup is mandatory — if a line already
+covers your idea, it is not new. Remove a line only when its prompt has shipped and been deleted.
+
+Format: `- <slug> — <one-line hook> — proposed by <task>`
+
+## Generation 0 (seeds — live in `tasks/trading-frontier/`)
+
+- 01-conversational-trading-copilot — talk/voice to your agent to trade, explain, manage risk — seed
+- 02-programmable-orders-engine — limit/stop/DCA/TWAP/conditional triggers executed by a worker — seed
+- 03-portfolio-intelligence-command — unified cross-wallet PnL attribution + risk dashboard — seed
+- 04-graduation-predictor — calibrated ML probability a launch graduates, surfaced everywhere — seed
+- 05-multichain-agent-treasury — cross-chain agent wallet + bridging across ERC-8004 chains — seed
+- 06-creator-reputation-registry — track creators across launches, verified-creator + rug history — seed
+- 07-universal-wallet-mirror — mirror any external on-chain wallet's trades from the agent wallet — seed
+- 08-realtime-alert-automation — programmable alerts → push/Telegram/in-app + auto-actions — seed
+- 09-amm-migration-sniper — snipe the graduation→AMM moment + new-pool/LP-add detection — seed
+
+## Generation 1+ (chained — live in `tasks/trading-frontier/next/`)
+
+<!-- Agents append new prompt lines here. Confirm no duplicate above before adding. -->
diff --git a/tasks/trading-frontier/README.md b/tasks/trading-frontier/README.md
new file mode 100644
index 000000000..61d21b3d0
--- /dev/null
+++ b/tasks/trading-frontier/README.md
@@ -0,0 +1,90 @@
+# Trading Frontier — A Self-Extending Chain of Great Ideas (Epic)
+
+This epic is different from a normal backlog: it is a **compounding chain**. It seeds 10
+innovative features (01–10). Every agent that picks up a task does TWO things — it **extends the
+chain** by authoring 10 brand-new, non-duplicate prompts for the next generation, and it **ships
+its own feature 100% production-ready**. The chain grows breadth while each node delivers depth.
+
+The goal is a continuously expanding frontier of genuinely game-changing capabilities for crypto
+sniping, trading, launching, buying, and selling on three.ws — each one real, wired, and
+shippable. No idea is allowed to be a clone. No feature is allowed to ship half-built.
+
+## Two companion epics already exist — read them so you never duplicate
+
+- `tasks/next-gen-trading/` — firewall, MEV execution, smart-money graph, pre-launch radar, NL
+ strategy compiler, signal marketplace, swarms, launch copilot, mission control, arena.
+- `tasks/agent-wallet-trading/` — agent-wallet foundation (some tasks shipped + deleted).
+
+Before inventing anything, read both, this epic, and `BACKLOG.md`. If an idea overlaps something
+already built or planned, it is NOT new — invent something else.
+
+## The chain protocol (every task file repeats this; honor it exactly)
+
+When an agent begins ANY task in this epic, **step 0** (before building the feature) is:
+
+1. **Read the whole backlog.** All of `tasks/` (every epic dir) + `tasks/trading-frontier/BACKLOG.md`.
+ Build a mental set of what already exists in code and what is already planned.
+2. **Invent 10 genuinely NEW feature ideas** — none may duplicate or trivially restate anything in
+ code or any existing task file. Each must be (a) innovative — something users can't get on
+ competing platforms; (b) grounded in the REAL three.ws codebase (cite real files/APIs/tables);
+ (c) advancing sniping / trading / launching / buying / selling or the agent platform.
+3. **Write each as its own prompt** in `tasks/trading-frontier/next/<short-kebab-slug>.md`, using
+ the EXACT structure of this epic's task files: the operating bar, the chain protocol (so the
+ chain continues), the production-ready bar, real context with file refs, goal, what to build,
+ constraints, success criteria, and the self-delete footer. Quality bar: each prompt must be as
+ thorough and grounded as 01–10 here. A vague or generic prompt is a failed chain link — don't
+ write one.
+4. **Register them** — append one line per new prompt to `BACKLOG.md` (slug — one-line hook —
+ `proposed by <task NN>`), AFTER confirming no existing line covers the same idea. Dedup is
+ mandatory; the chain dies if it loops on the same ideas.
+5. Only after the 10 new prompts are authored and registered do you build YOUR feature to the
+ production-ready bar below, then `git rm` your own task file in the completion commit.
+
+Governance so the chain stays great, not just big:
+- **Novelty gate:** if you cannot honestly say an idea is new and valuable, drop it and find a
+ better one. Ten strong prompts beat ten filler prompts. Never pad.
+- **Grounding gate:** every new prompt must reference real files/tables/APIs that exist today.
+- **No infinite trivia:** chained ideas must be substantial features, not micro-tweaks.
+- `BACKLOG.md` is the single source of truth for what's claimed; check it first, append last.
+
+## The production-ready bar (a task is NOT done until ALL are true)
+
+This is the `CLAUDE.md` "Definition of done", restated as the gate for shipping a chain node:
+
+- [ ] Built, wired into the UI, reachable by the user via real navigation — no hidden routes.
+- [ ] 100% real APIs + real data/on-chain. Zero mocks, zero fake/sample arrays, zero placeholders,
+ zero TODO/stubs, zero `throw new Error("not implemented")`, zero `setTimeout` fake-loading.
+- [ ] All trade paths honor existing spend guards (`api/_lib/agent-trade-guards.js`), custody audit
+ (`agent_custody_events`), and the firewall (`tasks/next-gen-trading/01`) when buying.
+- [ ] Every state designed: loading (skeletons), empty (tells the user what to do), error
+ (actionable + recovery), populated, overflow. Hover/active/focus on every interactive element.
+- [ ] Responsive at 320/768/1440; accessible (semantic HTML, ARIA, keyboard nav, focus rings,
+ contrast, reduced-motion); console-clean (no errors/warnings from your code).
+- [ ] Network tab shows real API calls succeeding with real data; exercised in a real browser.
+- [ ] The only coin referenced anywhere is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Runtime-supplied mints in generic trade plumbing are the only exception, never promoted.
+- [ ] `npm run build`, `npm run typecheck`, `npm test` all clean.
+- [ ] `data/changelog.json` entry for every user-visible change; new pages added to `data/pages.json`.
+- [ ] The **completionist** subagent passes on your changed files.
+- [ ] `git diff` self-reviewed; then a self-improvement pass — find what makes it 10× better, ship
+ that too — before claiming done.
+
+Concurrent agents share one worktree: stage explicit paths only (never `git add -A`/`git add .`),
+re-check `git status` and `git diff --staged` immediately before committing.
+
+## Seed ideas (generation 0)
+
+| # | Feature |
+|----|----------------------------------------------------------------------|
+| 01 | Conversational Trading Copilot (voice + chat, in-world execution) |
+| 02 | Programmable Orders Engine (limit / stop / DCA / TWAP / conditional) |
+| 03 | Portfolio Intelligence & Risk Command (unified cross-wallet) |
+| 04 | Graduation Predictor (calibrated ML model on intel + outcomes) |
+| 05 | Multi-Chain Agent Treasury & Bridge |
+| 06 | Creator Reputation & Anti-Scam Registry |
+| 07 | Universal Wallet Mirror (copy any external on-chain wallet) |
+| 08 | Real-Time Alert & Automation Engine (push / Telegram / in-app) |
+| 09 | AMM Migration & New-Pool Sniper |
+
+When every numbered seed file AND every chained `next/` file has shipped and been deleted, and
+`BACKLOG.md` is empty, delete this README.
diff --git a/tests/agent-custody-guards.test.js b/tests/agent-custody-guards.test.js
index d36fac3dd..60427399a 100644
--- a/tests/agent-custody-guards.test.js
+++ b/tests/agent-custody-guards.test.js
@@ -188,3 +188,40 @@ describe('getDailySpendUsd / lamportsToUsd', () => {
expect(await lamportsToUsd(1_000_000_000n)).toBeCloseTo(200, 6);
});
});
+
+// ── wallet freeze (kill switch) ──────────────────────────────────────────────
+describe('wallet freeze', () => {
+ it('normalizes frozen to a strict boolean (default false)', () => {
+ expect(normalizeSpendLimits({}).frozen).toBe(false);
+ expect(normalizeSpendLimits({ frozen: true }).frozen).toBe(true);
+ expect(normalizeSpendLimits({ frozen: 'yes' }).frozen).toBe(false); // only literal true freezes
+ });
+
+ it('blocks an autonomous trade when frozen', async () => {
+ const limits = normalizeSpendLimits({ frozen: true });
+ await expect(
+ enforceSpendLimit({ agentId: 'a', limits, category: 'trade', usdValue: 1 }),
+ ).rejects.toMatchObject({ code: 'wallet_frozen', status: 403 });
+ });
+
+ it('blocks snipe and x402 when frozen', async () => {
+ const limits = normalizeSpendLimits({ frozen: true });
+ for (const category of ['snipe', 'x402']) {
+ await expect(
+ enforceSpendLimit({ agentId: 'a', limits, category, usdValue: 5 }),
+ ).rejects.toMatchObject({ code: 'wallet_frozen' });
+ }
+ });
+
+ it('NEVER blocks the owner withdraw when frozen (funds must stay evacuable)', async () => {
+ const limits = normalizeSpendLimits({ frozen: true });
+ const r = await enforceSpendLimit({ agentId: 'a', limits, category: 'withdraw', usdValue: 10, destination: Keypair.generate().publicKey.toBase58() });
+ expect(r.ok).toBe(true);
+ });
+
+ it('does not block any path when not frozen', async () => {
+ const limits = normalizeSpendLimits({ frozen: false });
+ const r = await enforceSpendLimit({ agentId: 'a', limits, category: 'trade', usdValue: 1 });
+ expect(r.ok).toBe(true);
+ });
+});
diff --git a/tests/vanity-mnemonic.test.js b/tests/vanity-mnemonic.test.js
new file mode 100644
index 000000000..6bc15d542
--- /dev/null
+++ b/tests/vanity-mnemonic.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+
+import {
+ generateMnemonic,
+ validateMnemonic,
+ entropyToMnemonic,
+ mnemonicToSeed,
+ deriveSolanaKeypair,
+ deriveEd25519PrivateKey,
+ parseDerivationPath,
+ STRENGTH_WORD_COUNTS,
+ DEFAULT_DERIVATION_PATH,
+} from '../src/solana/vanity/mnemonic.js';
+import {
+ grindVanityMnemonic,
+ expectedMnemonicAttempts,
+ MAX_MNEMONIC_PATTERN_LENGTH,
+} from '../src/solana/vanity/mnemonic-grinder.js';
+import { ENGLISH_WORDLIST } from '../src/solana/vanity/bip39-english.js';
+
+// Canonical BIP-39 "all-zero entropy" mnemonic and its TREZOR-passphrase seed
+// (the reference vectors at github.com/trezor/python-mnemonic test vectors).
+const ZERO_MNEMONIC =
+ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
+const ZERO_SEED_TREZOR =
+ 'c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04';
+// Phantom / Solflare derive m/44'/501'/0'/0' for the first account; this is the
+// well-known address for the all-zero mnemonic under that path.
+const ZERO_PHANTOM_ADDRESS = 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk';
+
+describe('bip39 wordlist', () => {
+ it('is exactly 2048 unique words', () => {
+ expect(ENGLISH_WORDLIST).toHaveLength(2048);
+ expect(new Set(ENGLISH_WORDLIST).size).toBe(2048);
+ });
+});
+
+describe('mnemonic derivation — canonical vectors', () => {
+ it('encodes all-zero entropy to the reference mnemonic', () => {
+ expect(entropyToMnemonic(Buffer.alloc(16, 0))).toBe(ZERO_MNEMONIC);
+ });
+
+ it('derives the reference seed with the TREZOR passphrase', () => {
+ expect(mnemonicToSeed(ZERO_MNEMONIC, 'TREZOR').toString('hex')).toBe(ZERO_SEED_TREZOR);
+ });
+
+ it('derives the Phantom address at m/44\'/501\'/0\'/0\'', () => {
+ const { keypair, derivationPath } = deriveSolanaKeypair(ZERO_MNEMONIC);
+ expect(derivationPath).toBe(DEFAULT_DERIVATION_PATH);
+ expect(keypair.publicKey.toBase58()).toBe(ZERO_PHANTOM_ADDRESS);
+ });
+});
+
+describe('generateMnemonic / validateMnemonic', () => {
+ it('generates a valid 12-word mnemonic by default', () => {
+ const m = generateMnemonic();
+ expect(m.split(' ')).toHaveLength(12);
+ expect(validateMnemonic(m)).toBe(true);
+ });
+
+ it('supports every standard strength', () => {
+ for (const [bits, words] of Object.entries(STRENGTH_WORD_COUNTS)) {
+ const m = generateMnemonic(Number(bits));
+ expect(m.split(' ')).toHaveLength(words);
+ expect(validateMnemonic(m)).toBe(true);
+ }
+ });
+
+ it('rejects a mnemonic with a tampered word (bad checksum)', () => {
+ const words = generateMnemonic().split(' ');
+ words[words.length - 1] = words[words.length - 1] === 'zoo' ? 'zone' : 'zoo';
+ expect(validateMnemonic(words.join(' '))).toBe(false);
+ });
+
+ it('rejects an out-of-list word and a wrong word count', () => {
+ expect(validateMnemonic('not in the bip39 list at all friend')).toBe(false);
+ expect(validateMnemonic(generateMnemonic().split(' ').slice(0, 11).join(' '))).toBe(false);
+ });
+
+ it('is deterministic: a mnemonic always derives the same address', () => {
+ const m = generateMnemonic();
+ expect(deriveSolanaKeypair(m).keypair.publicKey.toBase58()).toBe(
+ deriveSolanaKeypair(m).keypair.publicKey.toBase58(),
+ );
+ });
+
+ it('varies the account index in the path', () => {
+ const m = generateMnemonic();
+ const a0 = deriveSolanaKeypair(m, { account: 0 });
+ const a1 = deriveSolanaKeypair(m, { account: 1 });
+ expect(a1.derivationPath).toBe("m/44'/501'/1'/0'");
+ expect(a0.keypair.publicKey.toBase58()).not.toBe(a1.keypair.publicKey.toBase58());
+ });
+});
+
+describe('parseDerivationPath / deriveEd25519PrivateKey', () => {
+ it('parses a hardened path', () => {
+ expect(parseDerivationPath("m/44'/501'/0'/0'")).toEqual([44, 501, 0, 0]);
+ });
+
+ it('rejects a non-hardened segment (ed25519 requires hardened)', () => {
+ expect(() => parseDerivationPath('m/44/501/0/0')).toThrow();
+ });
+
+ it('returns a 32-byte private key', () => {
+ const seed = mnemonicToSeed(ZERO_MNEMONIC);
+ expect(deriveEd25519PrivateKey(seed, [44, 501, 0, 0])).toHaveLength(32);
+ });
+});
+
+describe('grindVanityMnemonic', () => {
+ it('grinds a 1-char prefix and returns an importable phrase', () => {
+ const r = grindVanityMnemonic({ prefix: 'z', timeBudgetMs: 20_000 });
+ expect(r.publicKey.startsWith('z')).toBe(true);
+ expect(r.wordCount).toBe(12);
+ expect(r.derivationPath).toBe(DEFAULT_DERIVATION_PATH);
+ expect(r.attempts).toBeGreaterThan(0);
+
+ // The phrase must re-derive to exactly the ground address...
+ expect(validateMnemonic(r.mnemonic)).toBe(true);
+ expect(deriveSolanaKeypair(r.mnemonic).keypair.publicKey.toBase58()).toBe(r.publicKey);
+ // ...and the returned secret key must import to the same address.
+ expect(Keypair.fromSecretKey(r.secretKey).publicKey.toBase58()).toBe(r.publicKey);
+ });
+
+ it('matches a suffix case-insensitively', () => {
+ const r = grindVanityMnemonic({ suffix: 'A', ignoreCase: true, timeBudgetMs: 20_000 });
+ expect(r.publicKey.slice(-1).toLowerCase()).toBe('a');
+ });
+
+ it('supports 24-word strength', () => {
+ const r = grindVanityMnemonic({ prefix: 'a', ignoreCase: true, strength: 256, timeBudgetMs: 20_000 });
+ expect(r.wordCount).toBe(24);
+ expect(r.mnemonic.split(' ')).toHaveLength(24);
+ });
+
+ it('rejects a pattern longer than the mnemonic cap', () => {
+ expect(() => grindVanityMnemonic({ prefix: 'abc' })).toThrow(/exceeds/i);
+ expect(MAX_MNEMONIC_PATTERN_LENGTH).toBe(2);
+ });
+
+ it('throws GrindExhaustedError when the budget runs out', () => {
+ // A 2-char pattern with a near-zero budget cannot be found in time.
+ expect(() => grindVanityMnemonic({ prefix: 'zz', timeBudgetMs: 1 })).toThrow();
+ });
+
+ it('requires at least one of prefix/suffix', () => {
+ expect(() => grindVanityMnemonic({})).toThrow(/required/i);
+ });
+});
+
+describe('expectedMnemonicAttempts', () => {
+ it('scales by ~58 per case-sensitive character', () => {
+ const one = expectedMnemonicAttempts('a', '', false);
+ const two = expectedMnemonicAttempts('ab', '', false);
+ expect(Math.round(two / one)).toBe(58);
+ });
+});
diff --git a/tests/x402-vanity-sealed-envelope.test.js b/tests/x402-vanity-sealed-envelope.test.js
new file mode 100644
index 000000000..dd0eac723
--- /dev/null
+++ b/tests/x402-vanity-sealed-envelope.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest';
+import bs58 from 'bs58';
+
+import {
+ sealToRecipient,
+ openSealed,
+ openSealedText,
+ generateRecipientKeypair,
+ parseX25519Key,
+ SEALED_ENVELOPE_SCHEME,
+} from '../src/solana/vanity/sealed-envelope.js';
+import { grindVanityNode } from '../src/solana/vanity/grinder-node.js';
+import { grindVanityMnemonic } from '../src/solana/vanity/mnemonic-grinder.js';
+import { deriveSolanaKeypair } from '../src/solana/vanity/mnemonic.js';
+
+function toBase64url(bytes) {
+ return Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+// Flip the first byte of a Base64url payload — a guaranteed-significant mutation
+// (flipping a trailing char can be a no-op on the decoded bytes).
+function flipFirstByte(b64u) {
+ const buf = Buffer.from(b64u.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
+ buf[0] ^= 0xff;
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+describe('sealed-envelope', () => {
+ it('round-trips a string through seal → open with the matching key', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const plaintext = JSON.stringify({ secret: 'top', n: 42 });
+ const env = await sealToRecipient(plaintext, publicKey);
+
+ expect(env.scheme).toBe(SEALED_ENVELOPE_SCHEME);
+ expect(env.recipient).toBe(publicKey);
+ expect(typeof env.epk).toBe('string');
+ expect(typeof env.nonce).toBe('string');
+ // The ciphertext must not leak the plaintext.
+ expect(env.ciphertext).not.toContain('top');
+
+ expect(await openSealedText(env, secretKey)).toBe(plaintext);
+ });
+
+ it('round-trips raw bytes', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const bytes = new Uint8Array([0, 1, 2, 255, 128, 64]);
+ const env = await sealToRecipient(bytes, publicKey);
+ expect(Array.from(await openSealed(env, secretKey))).toEqual(Array.from(bytes));
+ });
+
+ it('rejects opening with the wrong private key', async () => {
+ const { publicKey } = generateRecipientKeypair();
+ const env = await sealToRecipient('secret', publicKey);
+ const wrong = generateRecipientKeypair().secretKey;
+ await expect(openSealed(env, wrong)).rejects.toThrow();
+ });
+
+ it('rejects a tampered ciphertext (AES-GCM tag)', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const env = await sealToRecipient('secret', publicKey);
+ const tampered = { ...env, ciphertext: flipFirstByte(env.ciphertext) };
+ await expect(openSealed(tampered, secretKey)).rejects.toThrow();
+ });
+
+ it('rejects a swapped ephemeral public key (epk bound as AAD)', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const env = await sealToRecipient('secret', publicKey);
+ // Replace epk with a different valid X25519 public key.
+ const otherEpk = generateRecipientKeypair().publicKey;
+ await expect(openSealed({ ...env, epk: otherEpk }, secretKey)).rejects.toThrow();
+ });
+
+ it('rejects an unsupported scheme', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const env = await sealToRecipient('secret', publicKey);
+ await expect(openSealed({ ...env, scheme: 'rot13' }, secretKey)).rejects.toThrow(/scheme/);
+ });
+
+ it('accepts the recipient key as Base58, hex, or Base64url', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const raw = parseX25519Key(publicKey);
+ const hex = Buffer.from(raw).toString('hex');
+ const b64 = toBase64url(raw);
+ for (const form of [publicKey, hex, b64]) {
+ const env = await sealToRecipient('ok', form);
+ expect(await openSealedText(env, secretKey)).toBe('ok');
+ }
+ });
+
+ it('throws a 400-tagged error on a wrong-length recipient key', () => {
+ try {
+ parseX25519Key('deadbeef'); // 4 bytes, not 32
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e.code).toBe('invalid_recipient_key');
+ expect(e.status).toBe(400);
+ }
+ });
+});
+
+describe('sealed vanity delivery (endpoint sealSecret path)', () => {
+ // Mirrors api/x402/vanity.js: seal a JSON bundle of the secret, then a client
+ // opens it with their X25519 private key. We exercise both output formats.
+ it('seals a ground keypair so only the recipient can recover the secret', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const g = grindVanityNode({ suffix: 'z', ignoreCase: true, timeBudgetMs: 15_000 });
+ const bundle = {
+ format: 'keypair',
+ secretKeyBase58: bs58.encode(g.secretKey),
+ secretKey: Array.from(g.secretKey),
+ };
+ const sealed = await sealToRecipient(JSON.stringify(bundle), publicKey);
+
+ const opened = JSON.parse(await openSealedText(sealed, secretKey));
+ expect(opened.secretKeyBase58).toBe(bundle.secretKeyBase58);
+ // The recovered secret key must reproduce the ground address.
+ const recovered = bs58.decode(opened.secretKeyBase58);
+ expect(bs58.encode(recovered.slice(32))).toBe(g.publicKey);
+ });
+
+ it('seals a ground mnemonic that re-derives to the vanity address', async () => {
+ const { publicKey, secretKey } = generateRecipientKeypair();
+ const g = grindVanityMnemonic({ suffix: 'z', ignoreCase: true, timeBudgetMs: 20_000 });
+ const bundle = {
+ format: 'mnemonic',
+ mnemonic: g.mnemonic,
+ derivationPath: g.derivationPath,
+ };
+ const sealed = await sealToRecipient(JSON.stringify(bundle), publicKey);
+
+ const opened = JSON.parse(await openSealedText(sealed, secretKey));
+ // Recovering the phrase and deriving at the wallet path lands on the address.
+ const derived = deriveSolanaKeypair(opened.mnemonic).keypair.publicKey.toBase58();
+ expect(derived).toBe(g.publicKey);
+ });
+});