Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore: harden API libs and refresh prompts, docs, and pages
nirholas0432ae929ef8
diff --git a/api/_lib/auto-rig.js b/api/_lib/auto-rig.jsindex 22888c8a3..f624a074a 100644--- a/api/_lib/auto-rig.js+++ b/api/_lib/auto-rig.js@@ -50,8 +50,11 @@ import { isAutoRigEligible } from './auto-rig-eligibility.js';// gate forge_avatar already runs before paid work — the module is dependency-free// and synchronous, so it bundles cleanly into the Vercel function.import { classifyHumanoidPrompt } from '../../mcp-server/src/tools/_humanoid.js';--const MAX_GLB_BYTES = 64 * 1024 * 1024; // matches reconstruct-finalize's ceiling+// The rigged GLB returned by the provider is fetched through the shared guard:+// host allowlist + IP-pinned SSRF connect + the single 64 MB ceiling (MAX_GLB_BYTES+// now lives there, no longer duplicated here). No bare fetch() of a provider URL+// remains in this file.+import { fetchProviderGlbBuffer } from './provider-result-url.js';// Does this rig signal indicate a usable skeleton? Mirrors classifyRig// (src/shared/rig-classify.js) on the snake_case source_meta shape so the@@ -63,16 +66,6 @@ export function rigInfoIsRigged(rigInfo) {return typeof joints === 'number' && joints > 0;}-async function fetchGlbBuffer(url) {- const resp = await fetch(url);- if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);- const len = Number(resp.headers.get('content-length') || 0);- if (len && len > MAX_GLB_BYTES) throw new Error(`glb too large: ${len} bytes`);- const buf = Buffer.from(await resp.arrayBuffer());- if (buf.length > MAX_GLB_BYTES) throw new Error(`glb too large: ${buf.length} bytes`);- return buf;-}-// Re-run bone-name + up-axis canonicalization on a rigged GLB so the new// skeleton lands in the canonical convention the clip retargeter expects —// identical to the canonicalization every other stored avatar gets at ingest.@@ -364,7 +357,7 @@ export async function finalizeAutoRigStage({ userId, jobId, job, glbUrl }) {// Fetch + canonicalize the rigged GLB. A fetch/canonicalize failure throws// out of here BEFORE any write, leaving the source avatar fully intact — the// caller logs it and the job is retried on the next webhook/poll/sweep.- let glbBuf = await fetchGlbBuffer(glbUrl);+ let glbBuf = await fetchProviderGlbBuffer(glbUrl);glbBuf = await canonicalize(glbBuf);const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;diff --git a/api/_lib/provider-result-url.js b/api/_lib/provider-result-url.jsnew file mode 100644index 000000000..ef6c32a9b--- /dev/null+++ b/api/_lib/provider-result-url.js@@ -0,0 +1,155 @@+// Single source of truth for validating + fetching a provider-returned GLB URL+// across every auto-rig / reconstruct completion path: the Replicate webhook,+// the regenerate-status browser poll, the cron sweep, and the rig poller.+//+// Fetching a provider-supplied URL server-side is a classic SSRF sink — a forged+// or compromised provider payload could aim the fetch at cloud metadata+// (169.254.169.254), loopback, or an RFC1918 address, and the server would+// dutifully connect. Two layers defend it, and BOTH are always applied because+// neither alone is sufficient:+//+// 1. NARROW positive host allowlist (isAllowedProviderResultUrl): the URL must+// be https on a host a provider actually serves results from, or on our own+// R2/CDN public domain (the bare "unrigged" mesh the rig poller re-fetches,+// which we wrote ourselves via publicUrl()).+// 2. BROAD negative SSRF guard (ssrf-guard.js): even an allowlisted host could+// be DNS-poisoned or 30x-redirected toward a private IP, so the fetch+// resolves + IP-pins the connection and re-validates every redirect hop.+//+// All IP/DNS/redirect logic lives in ssrf-guard.js — this module only adds the+// provider-host allowlist, the GLB-URL extraction, and the size ceiling on top.++import { env } from './env.js';+import { fetchSafePublicUrlPinned, SsrfBlockedError } from './ssrf-guard.js';++// Re-export so every caller imports the single error class from one place and+// the boundary catches can `instanceof`/`code === 'ssrf_blocked'` uniformly.+export { SsrfBlockedError };++// 64 MB ceiling on a fetched model — the ONE definition, shared by+// reconstruct-finalize.js and auto-rig.js (which each used to declare their own).+export const MAX_GLB_BYTES = 64 * 1024 * 1024;++// Per-request timeout so a hung provider host can't wedge a serverless+// invocation for its full max duration. Honored by fetchSafePublicUrlPinned via+// the AbortSignal we pass below.+const FETCH_TIMEOUT_MS = 30_000;++// Hosts a provider serves rigged/reconstructed GLBs from. Replicate delivers+// prediction outputs from these (pbxt.replicate.delivery is its CDN edge).+// Seeded from the webhook's original REPLICATE_RESULT_HOSTS. Our own R2/CDN+// public host is allowed too, but resolved at call time from env (see+// ownPublicHost) rather than hardcoded here.+export const PROVIDER_RESULT_HOSTS = [+ 'replicate.delivery',+ 'replicate.com',+ 'pbxt.replicate.delivery',+];++// Our own R2/CDN public host is ALSO a legitimate provider-result source: the+// rig poller re-fetches the bare "unrigged" mesh we stored via publicUrl()+// (reconstruct-finalize's rig.unriggedUrl) through this same guarded helper.+// It's first-party, but routing every provider-result fetch through one path+// keeps the audit single-file, so its host must be allowlisted as well.+//+// Derived lazily from S3_PUBLIC_DOMAIN — accessing it via env throws when storage+// isn't configured, so resolving at call time (and swallowing the throw) keeps+// importing this module side-effect-free and lets a deployment without storage+// still load it. The IP guard in fetchProviderGlbBuffer still applies after this+// host check, so allowing our CDN host never opens a private-range hole.+function ownPublicHost() {+ try {+ const raw = env.S3_PUBLIC_DOMAIN; // throws when S3_PUBLIC_DOMAIN is unset+ if (!raw) return null;+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;+ return new URL(withScheme).hostname.toLowerCase();+ } catch {+ return null;+ }+}++// Narrow positive gate — exactly the webhook's original semantics: parse, require+// https, lowercase the host, and accept an exact or `.`-suffix match against the+// allowed hosts (the provider delivery hosts ∪ our own CDN host). Never throws;+// returns a boolean so callers can branch. The broad SSRF guard in+// fetchProviderGlbBuffer is the layer that throws.+export function isAllowedProviderResultUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ return false;+ }+ if (u.protocol !== 'https:') return false;+ const host = u.hostname.toLowerCase();+ const own = ownPublicHost();+ const allowed = own ? [...PROVIDER_RESULT_HOSTS, own] : PROVIDER_RESULT_HOSTS;+ return allowed.some((h) => host === h || host.endsWith(`.${h}`));+}++const HTTP_URL = /^https?:\/\//i;++// Pull a GLB URL out of a provider's prediction output, returning ONLY a string+// that is itself an http(s) URL. EVERY branch validates the scheme so a hostile+// output field — e.g. output: "file:///etc/passwd", { url: "gopher://x" }, a bare+// number, or { url: 169 } — can never become a fetch target. Non-string, empty,+// or non-http(s) input returns null. (The host allowlist + IP guard then reject+// anything that isn't on a trusted provider host.)+export function extractGlbUrl(output) {+ if (!output) return null;+ if (typeof output === 'string') {+ return HTTP_URL.test(output) ? output : null;+ }+ if (Array.isArray(output)) {+ // Prefer an explicit .glb, but only ever return an http(s) entry.+ for (const v of output) {+ if (typeof v === 'string' && HTTP_URL.test(v) && /\.glb(\?|$)/i.test(v)) return v;+ }+ for (const v of output) {+ if (typeof v === 'string' && HTTP_URL.test(v)) return v;+ }+ return null;+ }+ if (typeof output === 'object') {+ for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {+ const v = output[key];+ if (typeof v === 'string' && HTTP_URL.test(v)) return v;+ }+ }+ return null;+}++// Throw when a URL isn't on an allowed provider host. Returns the raw string on+// success so callers can chain. Uses the shared SsrfBlockedError so the boundary+// catch in each completion path treats it identically to an ssrf-guard rejection+// (code === 'ssrf_blocked', status 400).+export function assertProviderResultUrl(raw) {+ if (!isAllowedProviderResultUrl(raw)) {+ throw new SsrfBlockedError('result url not on an allowed provider host');+ }+ return raw;+}++// The ONE place provider GLB bytes are fetched. Layers the host allowlist over+// the IP-pinned SSRF guard, enforces the 64 MB ceiling on both the advertised+// content-length and the actual body, and times out a hung host. The response is+// stored in R2 / forwarded downstream, so the PINNED variant is used — it+// connects to exactly the vetted IP (closing the DNS-rebinding window) and+// re-validates every redirect hop, matching ssrf-guard.js's own guidance for+// forwarded fetches. Error messages match the prior bare-fetch helpers+// (`fetch glb: <status>`, `glb too large: <n> bytes`) so existing logs/paths+// don't churn.+export async function fetchProviderGlbBuffer(url, { maxBytes = MAX_GLB_BYTES } = {}) {+ assertProviderResultUrl(url); // host allowlist — throws SsrfBlockedError before any socket+ const resp = await fetchSafePublicUrlPinned(+ url,+ { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },+ { allowHttp: false },+ );+ if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);+ const len = Number(resp.headers.get('content-length') || 0);+ if (len && len > maxBytes) throw new Error(`glb too large: ${len} bytes`);+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > maxBytes) throw new Error(`glb too large: ${buf.length} bytes`);+ return buf;+}diff --git a/api/_lib/pump.js b/api/_lib/pump.jsindex c7013f985..510bd713a 100644--- a/api/_lib/pump.js+++ b/api/_lib/pump.js@@ -20,6 +20,7 @@import { PublicKey } from '@solana/web3.js';import { solanaConnection } from './solana/connection.js';import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';+import { PUMP_PROGRAM_ID } from './solana/programs.js';// @solana/web3.js calls console.error() on every 429 retry attempt. Those// retries succeed (callers see a resolved value, not a thrown error), but@@ -213,6 +214,34 @@ export async function verifySignature({ network, signature }) {return tx;}+// Collect every program id invoked by a parsed transaction — both top-level+// instructions and the CPIs recorded in `meta.innerInstructions`. Works for the+// `getParsedTransaction` shape, where each instruction (parsed or partially+// decoded) carries a `programId` that is a PublicKey or a base58 string.+export function txProgramIds(tx) {+ const ids = new Set();+ const add = (ix) => {+ const pid = ix?.programId;+ if (!pid) return;+ ids.add(typeof pid === 'string' ? pid : pid.toString());+ };+ for (const ix of tx?.transaction?.message?.instructions || []) add(ix);+ for (const group of tx?.meta?.innerInstructions || []) {+ for (const ix of group?.instructions || []) add(ix);+ }+ return ids;+}++// True when a confirmed tx actually invoked the pump.fun bonding-curve program.+// launch-confirm uses this so a tx that merely *references* the new mint pubkey+// (e.g. a memo/transfer touching that account) can never be recorded in+// pump_agent_mints as a real launch — the program must have run. Future-proof by+// design: it asserts the program, not a specific create-instruction+// discriminator, so a new create variant keeps confirming cleanly.+export function txInvokesPumpProgram(tx) {+ return txProgramIds(tx).has(PUMP_PROGRAM_ID);+}+// Resolve the canonical pump.fun AMM pool for `mint` (post-graduation). Pass// `quoteMint` for USDC-paired coins — derives the PDA with the explicit quote// mint instead of the default WSOL PDA. Omit (or pass null) for SOL-paired coins.diff --git a/api/_lib/reconstruct-finalize.js b/api/_lib/reconstruct-finalize.jsindex 973f847a4..af04e2aeb 100644--- a/api/_lib/reconstruct-finalize.js+++ b/api/_lib/reconstruct-finalize.js@@ -21,18 +21,11 @@ import { storageKeyFor, createAvatar } from './avatars.js';import { inspectGlb, isValidGlbHeader } from './glb-inspect.js';import { dispatchWebhooks } from './webhook-dispatch.js';import { getRegenProvider } from './regen-provider.js';--const MAX_GLB_BYTES = 64 * 1024 * 1024; // 64 MB ceiling on a fetched model--async function fetchGlbBuffer(url) {- const resp = await fetch(url);- if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);- const len = Number(resp.headers.get('content-length') || 0);- if (len && len > MAX_GLB_BYTES) throw new Error(`glb too large: ${len} bytes`);- const buf = Buffer.from(await resp.arrayBuffer());- if (buf.length > MAX_GLB_BYTES) throw new Error(`glb too large: ${buf.length} bytes`);- return buf;-}+// Every provider-returned GLB fetched here — the reconstruct output, the rigged+// result, and our own stored bare mesh (rig.unriggedUrl) — goes through the+// shared guard: host allowlist + IP-pinned SSRF connect + 64 MB ceiling. No bare+// fetch() of a provider URL remains in this file.+import { fetchProviderGlbBuffer } from './provider-result-url.js';function glbMetaFrom(info) {return info@@ -139,7 +132,7 @@ async function materializeReconstructAvatar({//// Returns { status, resultAvatarId? } reflecting the post-call job state.export async function finalizeReconstructStage({ userId, jobId, job, glbUrl }) {- const glbBuf = await fetchGlbBuffer(glbUrl);+ const glbBuf = await fetchProviderGlbBuffer(glbUrl);const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;const slugPrefix = job?.params?.source === 'prompt' ? 'prompt' : 'selfie';const slug = `${slugPrefix}-${Math.random().toString(36).slice(2, 8)}`;@@ -235,7 +228,7 @@ export async function pollRiggingStage({ userId, jobId, job }) {// the job can't hang forever in 'rigging'.if (!provider?.instance || !rig.extJobId) {if (!rig.unriggedUrl) return { status: 'rigging' };- const glbBuf = await fetchGlbBuffer(rig.unriggedUrl);+ const glbBuf = await fetchProviderGlbBuffer(rig.unriggedUrl);const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;const avatar = await materializeReconstructAvatar({userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,@@ -248,7 +241,7 @@ export async function pollRiggingStage({ userId, jobId, job }) {const update = await provider.instance.status(rig.extJobId);if (update.status === 'done' && update.resultGlbUrl) {- const glbBuf = await fetchGlbBuffer(update.resultGlbUrl);+ const glbBuf = await fetchProviderGlbBuffer(update.resultGlbUrl);const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;const avatar = await materializeReconstructAvatar({userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,@@ -259,7 +252,7 @@ export async function pollRiggingStage({ userId, jobId, job }) {if (update.status === 'failed') {// Rigging failed — deliver the bare mesh we stored before rigging.- const glbBuf = await fetchGlbBuffer(rig.unriggedUrl);+ const glbBuf = await fetchProviderGlbBuffer(rig.unriggedUrl);const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;const avatar = await materializeReconstructAvatar({userId, jobId, job, glbBuf, glbInfo: info, storageKey, slug,diff --git a/api/_lib/ssrf-guard.js b/api/_lib/ssrf-guard.jsindex 8e0526e5f..5f01049bb 100644--- a/api/_lib/ssrf-guard.js+++ b/api/_lib/ssrf-guard.js@@ -197,6 +197,21 @@ export async function fetchSafePublicUrlPinned(input, init = {}, opts = {}) {nodeRes.on('error', reject);});req.on('error', reject);+ // Honor an optional AbortSignal (e.g. AbortSignal.timeout) from init so a+ // caller can bound a hung host instead of holding the socket — and the+ // serverless invocation — open for the function's full duration. Purely+ // additive: callers that pass no signal are unaffected.+ const signal = init.signal;+ if (signal) {+ if (signal.aborted) {+ req.destroy(signal.reason instanceof Error ? signal.reason : new Error('aborted'));+ } else {+ const onAbort = () =>+ req.destroy(signal.reason instanceof Error ? signal.reason : new Error('aborted'));+ signal.addEventListener('abort', onAbort, { once: true });+ req.on('close', () => signal.removeEventListener('abort', onAbort));+ }+ }if (init.body) req.write(init.body);req.end();});diff --git a/api/_lib/x402-spending-ledger.js b/api/_lib/x402-spending-ledger.jsindex f75032151..ec0065913 100644--- a/api/_lib/x402-spending-ledger.js+++ b/api/_lib/x402-spending-ledger.js@@ -215,6 +215,5 @@ export const _internal = {dayKey,resetMemoryStore() {memoryStore.clear();- redisClient = null;},};diff --git a/api/_mcp/payments.js b/api/_mcp/payments.jsindex b9cdf0e22..84b6d8dc2 100644--- a/api/_mcp/payments.js+++ b/api/_mcp/payments.js@@ -1,5 +1,53 @@import { X402Error, send402 } from '../_lib/x402-spec.js';import { reportServerError } from '../_lib/http.js';+import {+ hashPaymentProof,+ reserveSlot,+ releaseSlot,+} from '../_lib/x402/payment-identifier-server.js';++// Always-on replay guard for the raw-verify MCP paid path.+//+// The paidEndpoint() wrapper closes the verify→deliver→settle window with a+// proof-hash reservation; the MCP servers hand-roll that dance, so they need the+// same guard. We reserve a single-use lock keyed on the SHA-256 of the signed+// X-PAYMENT proof — only the original payer can reproduce it — so a captured or+// retried payment can't re-run the (often expensive: LLM / RPC / generation) tool+// dispatch before the first settle lands.+//+// Double-CHARGE is already prevented downstream (the on-chain EIP-3009 nonce /+// Solana blockhash + the deterministic facilitator Idempotency-Key); this guard+// closes the remaining gap — free re-delivery / compute amplification from a+// concurrent replay in the narrow window before settlement broadcasts. Once a+// payment settles, the consumed nonce makes any later /verify fail, so the lock+// only needs to span dispatch+settle and the caller releases it as soon as the+// request finishes (success or failure) — leaving a transient failure free to be+// retried with the same payment.+//+// Fails OPEN: no header, or a store with no Redis, degrades to the best-effort+// in-process claim in idempotency-cache.reserve — it never blocks a legitimate+// payment, matching the paidEndpoint stance (a Redis blip must not 5xx a paid+// call when double-charge is already protected on-chain).+//+// Returns { ok, release }:+// ok=false → a concurrent request already holds the slot for this exact+// payment; reject with a JSON-RPC "payment_in_flight" error.+// release() → idempotent; call it once the request finishes (a finally block).+export async function reservePaymentProof(route, paymentHeader) {+ const hash = hashPaymentProof(paymentHeader);+ if (!hash) return { ok: true, release: async () => {} };+ const paymentId = `proof:${hash}`;+ const owns = await reserveSlot({ route, paymentId });+ let released = false;+ return {+ ok: owns,+ release: async () => {+ if (!owns || released) return;+ released = true;+ await releaseSlot({ route, paymentId });+ },+ };+}export function sendX402Error(res, { resourceUrl, accepts }, err) {if (err instanceof X402Error) {diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 5302093ba..56d3fe022 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -19,6 +19,7 @@ import { getRegenProvider, getRegenProviderByName, getRegenProviderForJob, BYOK_import { resolveProviderKey } from '../_lib/forge-provider-key.js';import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';+import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';import { textToImage } from '../_mcp3d/text-to-image.js';// ── provider error masking ──────────────────────────────────────────────────────@@ -521,9 +522,25 @@ const handleRegenerateStatus = wrap(async (req, res) => {const provider = await getRegenProviderForJob(job.provider, req);if (provider.instance) {const update = await provider.instance.status(job.ext_job_id);- const nextStatus = update.status;- const nextResultUrl = update.resultGlbUrl ?? null;- const nextError = update.error ?? null;+ let nextStatus = update.status;+ let nextResultUrl = update.resultGlbUrl ?? null;+ let nextError = update.error ?? null;+ // SSRF gate (defense-in-depth): a provider-returned result URL is+ // attacker-influenceable if the provider account/payload is forged.+ // Pin it to an allowed provider host BEFORE it ever lands in+ // result_glb_url — which the cron/poll later fetch server-side. A+ // disallowed URL terminates the job cleanly instead of seeding a+ // poisoned fetch (the guarded fetch would reject it too, but failing+ // here keeps the bad URL out of the DB).+ if (nextResultUrl && !isAllowedProviderResultUrl(nextResultUrl)) {+ let blockedHost = 'unparseable';+ try { blockedHost = new URL(nextResultUrl).hostname; } catch { /* keep placeholder */ }+ console.warn('[regenerate-status] blocked result url', { jobId, host: blockedHost });+ nextStatus = 'failed';+ nextResultUrl = null;+ nextError = 'provider returned a disallowed result url';+ }+if (isAutoRig && nextStatus === 'done') autoRigProviderDone = true;const persistStatus = isAutoRig && nextStatus === 'done' ? 'running' : nextStatus;if (diff --git a/api/ibm-mcp.js b/api/ibm-mcp.jsindex 90a5492fa..9c7290a0f 100644--- a/api/ibm-mcp.js+++ b/api/ibm-mcp.js@@ -27,7 +27,7 @@ import {handleTerminate,isMcpProtocolClient,} from './_mcp/auth.js';-import { sendX402Error } from './_mcp/payments.js';+import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';const RESOURCE_PATH = '/api/ibm-mcp';@@ -83,34 +83,52 @@ export default wrap(async (req, res) => {// an unbounded batch multiplies billable work against the user's budget.if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');- const responses = [];- for (const msg of batch) {- const r = await dispatch(msg, auth, req);- if (r !== null) responses.push(r);+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across dispatch+settle so a captured/retried X-PAYMENT+ // can't re-run the priced (billable IBM inference) tools before the first+ // settle lands. Released in the finally; the consumed on-chain nonce blocks any+ // replay thereafter. Fails open — see reservePaymentProof.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof(RESOURCE_PATH, req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;}- // Settle the x402 payment AFTER the work succeeded — atomic from the caller's- // perspective: if settle fails, the payer's signed payload is not broadcast- // and they get an error instead of having paid for nothing. Only settle when- // at least one call produced a result; a wholesale failure (every call errored- // or returned isError) charges nothing. A partial failure still settles in- // full so a single failing call can't reclaim the calls that succeeded.- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));- if (x402Ctx && anySuccess) {- try {- const settled = await settlePayment({ verified: x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (err) {- return sendX402Error(- res,- { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },- err,- );+ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);}- }- res.statusCode = 200;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ // Settle the x402 payment AFTER the work succeeded — atomic from the caller's+ // perspective: if settle fails, the payer's signed payload is not broadcast+ // and they get an error instead of having paid for nothing. Only settle when+ // at least one call produced a result; a wholesale failure (every call errored+ // or returned isError) charges nothing. A partial failure still settles in+ // full so a single failing call can't reclaim the calls that succeeded.+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (x402Ctx && anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }});diff --git a/api/mcp-3d.js b/api/mcp-3d.jsindex 2d180b657..63dd56e71 100644--- a/api/mcp-3d.js+++ b/api/mcp-3d.js@@ -20,7 +20,7 @@ import {handleTerminate,isMcpProtocolClient,} from './_mcp/auth.js';-import { sendX402Error } from './_mcp/payments.js';+import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';const RESOURCE_PATH = '/api/mcp-3d';@@ -71,35 +71,53 @@ export default wrap(async (req, res) => {const batch = Array.isArray(body) ? body : [body];if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');- const responses = [];- for (const msg of batch) {- const r = await dispatch(msg, auth, req);- if (r !== null) responses.push(r);+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across dispatch+settle so a captured/retried X-PAYMENT+ // can't re-run the priced (and here often generation-grade) tools before the+ // first settle lands. Released in the finally; the consumed on-chain nonce+ // blocks any replay thereafter. Fails open — see reservePaymentProof.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof('/api/mcp-3d', req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;}- // OAuth users run tools operator-funded (bounded by rate limits). x402- // callers pay per tool: the verified payment covers the batch's summed- // per-tool price (tier-aware for generation — see _mcp3d/pricing.js), and- // settling it here means the charge lands only after the work succeeded.- // Only settle if a call succeeded — a wholesale failure is free.- if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));- if (anySuccess) {- try {- const settled = await settlePayment({ verified: x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (err) {- return sendX402Error(- res,- { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },- err,- );+ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);+ }++ // OAuth users run tools operator-funded (bounded by rate limits). x402+ // callers pay per tool: the verified payment covers the batch's summed+ // per-tool price (tier-aware for generation — see _mcp3d/pricing.js), and+ // settling it here means the charge lands only after the work succeeded.+ // Only settle if a call succeeded — a wholesale failure is free.+ if (x402Ctx) {+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }}}- }- res.statusCode = 200;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }});diff --git a/api/mcp-agent.js b/api/mcp-agent.jsindex 53eb5bf76..f6fa2391e 100644--- a/api/mcp-agent.js+++ b/api/mcp-agent.js@@ -15,7 +15,7 @@ import {handleSse,handleTerminate,} from './_mcp/auth.js';-import { sendX402Error } from './_mcp/payments.js';+import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;@@ -49,34 +49,52 @@ export default wrap(async (req, res) => {const batch = Array.isArray(body) ? body : [body];if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');- const responses = [];- for (const msg of batch) {- const r = await dispatch(msg, auth, req);- if (r !== null) responses.push(r);+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across dispatch+settle so a captured/retried X-PAYMENT+ // can't re-run the priced tools before the first settle lands. Released in the+ // finally; the consumed on-chain nonce blocks any replay thereafter. Fails+ // open — see reservePaymentProof.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof('/api/mcp-agent', req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;}- // When the caller presented an x402 payment, settle it AFTER the work- // succeeded — same atomic verify → work → settle sequence as /api/mcp. The- // advertised 402 price is only ever charged once useful work was delivered;- // a wholesale failure leaves the payer's signed payload un-broadcast.- if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));- if (anySuccess) {- try {- const settled = await settlePayment({ verified: x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (err) {- return sendX402Error(- res,- { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },- err,- );+ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);+ }++ // When the caller presented an x402 payment, settle it AFTER the work+ // succeeded — same atomic verify → work → settle sequence as /api/mcp. The+ // advertised 402 price is only ever charged once useful work was delivered;+ // a wholesale failure leaves the payer's signed payload un-broadcast.+ if (x402Ctx) {+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }}}- }- res.statusCode = 200;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }});diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.jsindex 1a4c04711..73dee13db 100644--- a/api/mcp-bazaar.js+++ b/api/mcp-bazaar.js@@ -17,7 +17,7 @@ import {handleSse,handleTerminate,} from './_mcp/auth.js';-import { sendX402Error } from './_mcp/payments.js';+import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;@@ -51,34 +51,52 @@ export default wrap(async (req, res) => {const batch = Array.isArray(body) ? body : [body];if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');- const responses = [];- for (const msg of batch) {- const r = await dispatch(msg, auth, req);- if (r !== null) responses.push(r);+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across dispatch+settle so a captured/retried X-PAYMENT+ // can't re-run the priced tools before the first settle lands. Released in the+ // finally; the consumed on-chain nonce blocks any replay thereafter. Fails+ // open — see reservePaymentProof.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof('/api/mcp-bazaar', req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;}- // When the caller presented an x402 payment, settle it AFTER the work- // succeeded — same atomic verify → work → settle sequence as /api/mcp. The- // advertised 402 price is only ever charged once useful work was delivered;- // a wholesale failure leaves the payer's signed payload un-broadcast.- if (x402Ctx) {- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));- if (anySuccess) {- try {- const settled = await settlePayment({ verified: x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (err) {- return sendX402Error(- res,- { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },- err,- );+ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);+ }++ // When the caller presented an x402 payment, settle it AFTER the work+ // succeeded — same atomic verify → work → settle sequence as /api/mcp. The+ // advertised 402 price is only ever charged once useful work was delivered;+ // a wholesale failure leaves the payer's signed payload un-broadcast.+ if (x402Ctx) {+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }}}- }- res.statusCode = 200;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }});diff --git a/api/mcp.js b/api/mcp.jsindex 70c2e521c..cee7e215d 100644--- a/api/mcp.js+++ b/api/mcp.js@@ -14,7 +14,7 @@ import {handleTerminate,isMcpProtocolClient,} from './_mcp/auth.js';-import { sendX402Error } from './_mcp/payments.js';+import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;@@ -66,37 +66,55 @@ export default wrap(async (req, res) => {// unbounded batch multiplies rate-limited work by N against the user's budget.if (batch.length > 32) return sendJsonRpcError(res, null, -32600, 'batch too large (max 32)');- const responses = [];- for (const msg of batch) {- const r = await dispatch(msg, auth, req);- if (r !== null) responses.push(r);+ // Replay guard (parity with paidEndpoint): hold a single-use lock on the+ // signed payment proof across dispatch+settle so a captured/retried X-PAYMENT+ // can't re-run the priced tools before the first settle lands. Released in the+ // finally once the request finishes; the consumed on-chain nonce blocks any+ // replay thereafter. Fails open — see reservePaymentProof.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof('/api/mcp', req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;}- // Settle the x402 payment AFTER the work succeeded — atomic from the caller's- // perspective: if settle fails, the payer's signed payload is not broadcast- // and they get a 502 instead of having paid for nothing.- //- // Only settle when at least one call actually produced a result. If every- // call failed (JSON-RPC error or a tool result flagged isError), no useful- // work was delivered, so we do not broadcast the payment. We deliberately do- // NOT void settlement on a *partial* failure: a single failing call in a- // batch must not let the caller reclaim the expensive calls that succeeded.- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));- if (x402Ctx && anySuccess) {- try {- const settled = await settlePayment({ verified: x402Ctx.verified });- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));- } catch (err) {- return sendX402Error(- res,- { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },- err,- );+ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);}- }- res.statusCode = 200;- res.setHeader('content-type', 'application/json; charset=utf-8');- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);- res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ // Settle the x402 payment AFTER the work succeeded — atomic from the caller's+ // perspective: if settle fails, the payer's signed payload is not broadcast+ // and they get a 502 instead of having paid for nothing.+ //+ // Only settle when at least one call actually produced a result. If every+ // call failed (JSON-RPC error or a tool result flagged isError), no useful+ // work was delivered, so we do not broadcast the payment. We deliberately do+ // NOT void settlement on a *partial* failure: a single failing call in a+ // batch must not let the caller reclaim the expensive calls that succeeded.+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (x402Ctx && anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }});diff --git a/api/pump/[action].js b/api/pump/[action].jsindex f86b2cdb0..42d6cad63 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -82,6 +82,7 @@ import {getAmmPoolState,buildUnsignedTxBase64,verifySignature,+ txInvokesPumpProgram,solanaPubkey,} from '../_lib/pump.js';@@ -1456,6 +1457,12 @@ async function handleLaunchConfirm(req, res) {if (!accountKeys.includes(p.mint)) {return error(res, 422, 'mint_not_in_tx', 'mint pubkey not present in tx');}+ // Prove the confirmed tx actually ran the pump.fun program — not just a tx+ // that happens to reference the mint pubkey. Without this, a confirmed memo+ // or transfer touching the new mint account could be recorded as a launch.+ if (!txInvokesPumpProgram(tx)) {+ return error(res, 422, 'not_a_pump_launch', 'transaction did not invoke the pump.fun program');+ }const [existing] = await sql`select id from pump_agent_mints where mint=${p.mint} and network=${p.network} limit 1diff --git a/api/webhooks/replicate.js b/api/webhooks/replicate.jsindex 9c8e2ece6..02cf3f7aa 100644--- a/api/webhooks/replicate.js+++ b/api/webhooks/replicate.js@@ -25,6 +25,12 @@ import { sql } from '../_lib/db.js';import { json, method, wrap, error } from '../_lib/http.js';import { finalizeReconstructStage } from '../_lib/reconstruct-finalize.js';import { finalizeAutoRigStage } from '../_lib/auto-rig.js';+// Provider-result URL guard, shared with the poll, cron, and rig-poller paths so+// every completion path pins the fetched GLB URL to an allowed provider host the+// same way (SSRF). isAllowedProviderResultUrl carries the exact semantics the+// webhook used to define inline; extractGlbUrl is the hardened scheme-checked+// extractor.+import { isAllowedProviderResultUrl, extractGlbUrl } from '../_lib/provider-result-url.js';const REPLAY_WINDOW_SECONDS = 5 * 60;@@ -57,46 +63,6 @@ function verifyStandardWebhook({ signingKey, id, timestamp, body, headerSig }) {return false;}-// Replicate serves prediction outputs from its own delivery hosts. Pin the-// fetched GLB URL to https on one of those hosts so a forged/compromised payload-// can't point the server-side fetch at an internal/metadata endpoint (SSRF).-const REPLICATE_RESULT_HOSTS = [- 'replicate.delivery',- 'replicate.com',- 'pbxt.replicate.delivery',-];--function isAllowedResultUrl(raw) {- let u;- try {- u = new URL(raw);- } catch {- return false;- }- if (u.protocol !== 'https:') return false;- const host = u.hostname.toLowerCase();- return REPLICATE_RESULT_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));-}--function extractGlbUrl(output) {- if (!output) return null;- if (typeof output === 'string') return output;- if (Array.isArray(output)) {- for (const v of output) {- if (typeof v === 'string' && /\.glb(\?|$)/i.test(v)) return v;- }- for (const v of output) {- if (typeof v === 'string' && /^https?:\/\//.test(v)) return v;- }- }- if (typeof output === 'object') {- for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {- if (typeof output[key] === 'string') return output[key];- }- }- return null;-}-function translateStatus(s) {switch (s) {case 'starting':@@ -210,12 +176,13 @@ export default wrap(async (req, res) => {// user's status poll then sees resultAvatarId (or the 'rigging' stage) on its// next hit instead of waiting a round-trip. The shared stage handles the// rig-or-materialize decision, identical to the poll path, so the two never- // drift. isAllowedResultUrl pins the fetch to Replicate's delivery hosts- // (SSRF guard) before we hand the URL off.+ // drift. isAllowedProviderResultUrl pins the fetch to an allowed provider host+ // (SSRF guard) before we hand the URL off; the finalize fetch then re-checks+ // the host and IP-pins the connection.if (nextStatus === 'done' &&nextGlbUrl &&- isAllowedResultUrl(nextGlbUrl) &&+ isAllowedProviderResultUrl(nextGlbUrl) &&job.mode === 'reconstruct' &&!job.result_avatar_id) {@@ -241,7 +208,7 @@ export default wrap(async (req, res) => {if (nextStatus === 'done' &&nextGlbUrl &&- isAllowedResultUrl(nextGlbUrl) &&+ isAllowedProviderResultUrl(nextGlbUrl) &&job.mode === 'rerig' &&job.params?.auto_rig === true &&!job.result_avatar_iddiff --git a/data/pages.json b/data/pages.jsonindex 0bc311d89..dac012455 100644--- a/data/pages.json+++ b/data/pages.json@@ -950,6 +950,13 @@"changefreq": "monthly","added": "2026-06-17"},+ {+ "path": "/ibm/hello",+ "title": "IBM × three.ws partnership",+ "description": "The IBM × three.ws partnership page: how three.ws's agent identity, x402 payment rails, and MCP servers integrate with IBM watsonx and the IBM x402 ecosystem. A self-contained showcase that stays live-editable after publish.",+ "priority": 0.6,+ "changefreq": "monthly"+ },{"path": "/lookup","title": "Agent Lookup",diff --git a/docs/ALL.md b/docs/ALL.mdindex 317f4bf09..1f26e6eb3 100644--- a/docs/ALL.md+++ b/docs/ALL.md@@ -1,7 +1,7 @@<!-- GENERATED by scripts/combine-docs.mjs — do not edit by hand. Edit the source files under docs/ and re-run. --># three.ws — Combined Documentation-> Single-file snapshot of every document under [`docs/`](.). Generated 2026-06-18 from **236 files** (~2536 KB).+> Single-file snapshot of every document under [`docs/`](.). Generated 2026-06-24 from **291 files** (~3309 KB).> The individual source files remain the canonical, editable copies — this file is a read-only aggregate.## Table of contents@@ -11,284 +11,351 @@- [3d-asset-pipeline.md](#sec-001)- [API_AUDIT.md](#sec-002)- [DESIGN-TOKENS.md](#sec-003)-- [agent-manifest.md](#sec-042)-- [agent-system.md](#sec-043)-- [agents-vs-avatars.md](#sec-044)-- [animations.md](#sec-045)-- [api-reference.md](#sec-046)-- [ar.md](#sec-048)-- [architecture.md](#sec-049)-- [authentication.md](#sec-064)-- [avatar-creation.md](#sec-065)-- [aws-builder-center-marketplace-x402.md](#sec-066)-- [aws-builder-center-mcp-agents.md](#sec-067)-- [aws-marketplace-listing-kit.md](#sec-068)-- [aws-marketplace.md](#sec-069)-- [btn-pill-migration.md](#sec-070)-- [changelog.md](#sec-071)-- [character-studio.md](#sec-072)-- [coinmarketcap-article-play.md](#sec-073)-- [coinmarketcap-article.md](#sec-074)-- [configuration.md](#sec-075)-- [contributing.md](#sec-087)-- [demo-routes.md](#sec-088)-- [deployment.md](#sec-089)-- [do-i-need-crypto.md](#sec-090)-- [editor.md](#sec-091)-- [embedding.md](#sec-092)-- [erc8004.md](#sec-093)-- [examples.md](#sec-095)-- [how-it-works.md](#sec-096)-- [ibm-x402-mcp.md](#sec-097)-- [ibm.md](#sec-098)-- [introduction.md](#sec-122)-- [js-api.md](#sec-124)-- [layers.md](#sec-125)-- [listings.md](#sec-126)-- [make-your-agent.md](#sec-127)-- [mcp-3d-studio.md](#sec-128)-- [mcp-agent.md](#sec-129)-- [mcp-x402-bazaar.md](#sec-130)-- [mcp.md](#sec-131)-- [memory.md](#sec-132)-- [mint-mark.md](#sec-133)-- [multi-agent.md](#sec-134)-- [onchain-agents.md](#sec-135)-- [pay-skills-listing.md](#sec-138)-- [permissions.md](#sec-139)-- [persona-hub.md](#sec-140)-- [popular-3d-github-repos.md](#sec-141)-- [pump-fun-mcp-edge.md](#sec-142)-- [pump-fun-skills-audit.md](#sec-143)-- [pump-platform-fee.md](#sec-144)-- [quick-start.md](#sec-166)-- [reputation.md](#sec-167)-- [sdk.md](#sec-177)-- [security.md](#sec-178)-- [share-and-embed.md](#sec-181)-- [skills.md](#sec-182)-- [smart-contracts.md](#sec-183)-- [solana-pumpfun.md](#sec-184)-- [solana.md](#sec-185)-- [start-here.md](#sec-186)-- [syndication.md](#sec-187)-- [troubleshooting.md](#sec-188)-- [validation.md](#sec-217)-- [viewer.md](#sec-218)-- [web-component.md](#sec-219)-- [widget-api.md](#sec-220)-- [widget-studio.md](#sec-221)-- [widgets.md](#sec-222)-- [x-spaces.md](#sec-223)-- [x402.md](#sec-231)+- [PROTOCOL-vanity.md](#sec-004)+- [agent-manifest.md](#sec-043)+- [agent-reputation.md](#sec-044)+- [agent-system.md](#sec-045)+- [agents-vs-avatars.md](#sec-046)+- [agora.md](#sec-047)+- [animations.md](#sec-060)+- [api-reference.md](#sec-061)+- [ar.md](#sec-063)+- [architecture.md](#sec-064)+- [authentication.md](#sec-080)+- [avatar-creation.md](#sec-081)+- [aws-builder-center-marketplace-x402.md](#sec-082)+- [aws-builder-center-mcp-agents.md](#sec-083)+- [aws-marketplace-listing-kit.md](#sec-084)+- [aws-marketplace.md](#sec-085)+- [btn-pill-migration.md](#sec-086)+- [changelog.md](#sec-087)+- [character-studio.md](#sec-088)+- [coinmarketcap-article-play.md](#sec-089)+- [coinmarketcap-article.md](#sec-090)+- [configuration.md](#sec-091)+- [contributing.md](#sec-103)+- [demo-routes.md](#sec-104)+- [deployment.md](#sec-105)+- [do-i-need-crypto.md](#sec-106)+- [editor.md](#sec-107)+- [embedding.md](#sec-108)+- [erc8004.md](#sec-109)+- [examples.md](#sec-111)+- [hold-to-access.md](#sec-112)+- [how-it-works.md](#sec-113)+- [i18n.md](#sec-114)+- [ibm-x402-mcp.md](#sec-115)+- [ibm.md](#sec-116)+- [introduction.md](#sec-143)+- [js-api.md](#sec-145)+- [layers.md](#sec-146)+- [listings.md](#sec-147)+- [make-your-agent.md](#sec-148)+- [mcp-3d-studio.md](#sec-149)+- [mcp-agent.md](#sec-150)+- [mcp-x402-bazaar.md](#sec-151)+- [mcp.md](#sec-152)+- [memory.md](#sec-153)+- [mint-mark.md](#sec-154)+- [multi-agent.md](#sec-155)+- [nvidia-models.md](#sec-156)+- [onchain-agents.md](#sec-158)+- [pay-skills-listing.md](#sec-161)+- [permissions.md](#sec-162)+- [persona-hub.md](#sec-163)+- [popular-3d-github-repos.md](#sec-164)+- [pump-fun-mcp-edge.md](#sec-165)+- [pump-fun-skills-audit.md](#sec-166)+- [pump-platform-fee.md](#sec-167)+- [quick-start.md](#sec-189)+- [repo-hygiene-audit.md](#sec-190)+- [reputation.md](#sec-191)+- [sas-attestations.md](#sec-201)+- [sdk-launch.md](#sec-202)+- [sdk.md](#sec-203)+- [security.md](#sec-204)+- [share-and-embed.md](#sec-207)+- [skills.md](#sec-208)+- [smart-contracts.md](#sec-209)+- [solana-pumpfun.md](#sec-210)+- [solana-reputation.md](#sec-211)+- [solana.md](#sec-212)+- [start-here.md](#sec-214)+- [syndication.md](#sec-215)+- [troubleshooting.md](#sec-216)+- [validation.md](#sec-272)+- [viewer.md](#sec-273)+- [web-component.md](#sec-274)+- [widget-api.md](#sec-275)+- [widget-studio.md](#sec-276)+- [widgets.md](#sec-277)+- [x-spaces.md](#sec-278)+- [x402.md](#sec-286)### agent-briefs-- [agent-briefs/B-design-system/B02-migration-rules.md](#sec-004)-- [agent-briefs/R-3d-world-fun/R00-program-overview.md](#sec-005)-- [agent-briefs/R-3d-world-fun/README.md](#sec-006)-- [agent-briefs/R-3d-world-fun/phase-1/R01-server-world-object-sync.md](#sec-007)-- [agent-briefs/R-3d-world-fun/phase-1/R02-client-world-objects-manager.md](#sec-008)-- [agent-briefs/R-3d-world-fun/phase-1/R03-cosmetics-accessory-rig.md](#sec-009)-- [agent-briefs/R-3d-world-fun/phase-2/R04-emoji-confetti-reactions.md](#sec-010)-- [agent-briefs/R-3d-world-fun/phase-2/R05-kickable-physics-ball.md](#sec-011)-- [agent-briefs/R-3d-world-fun/phase-2/R06-dance-floor-zone.md](#sec-012)-- [agent-briefs/R-3d-world-fun/phase-2/R07-minigame-king-of-the-totem.md](#sec-013)-- [agent-briefs/R-3d-world-fun/phase-2/R08-minigame-tag.md](#sec-014)-- [agent-briefs/R-3d-world-fun/phase-2/R09-emote-wheel.md](#sec-015)-- [agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md](#sec-016)-- [agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md](#sec-017)-- [agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md](#sec-018)-- [agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md](#sec-019)-- [agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md](#sec-020)-- [agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md](#sec-021)-- [agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md](#sec-022)-- [agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md](#sec-023)-- [agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md](#sec-024)-- [agent-briefs/W-world-online/PORT-CHECKLIST.md](#sec-025)-- [agent-briefs/W-world-online/README.md](#sec-026)-- [agent-briefs/W-world-online/W00-program-overview.md](#sec-027)-- [agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md](#sec-028)-- [agent-briefs/X-prod-errors-2026-06-05/README.md](#sec-029)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md](#sec-030)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md](#sec-031)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md](#sec-032)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md](#sec-033)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md](#sec-034)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md](#sec-035)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md](#sec-036)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md](#sec-037)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md](#sec-038)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md](#sec-039)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md](#sec-040)-- [agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md](#sec-041)+- [agent-briefs/B-design-system/B02-migration-rules.md](#sec-005)+- [agent-briefs/R-3d-world-fun/R00-program-overview.md](#sec-006)+- [agent-briefs/R-3d-world-fun/README.md](#sec-007)+- [agent-briefs/R-3d-world-fun/phase-1/R01-server-world-object-sync.md](#sec-008)+- [agent-briefs/R-3d-world-fun/phase-1/R02-client-world-objects-manager.md](#sec-009)+- [agent-briefs/R-3d-world-fun/phase-1/R03-cosmetics-accessory-rig.md](#sec-010)+- [agent-briefs/R-3d-world-fun/phase-2/R04-emoji-confetti-reactions.md](#sec-011)+- [agent-briefs/R-3d-world-fun/phase-2/R05-kickable-physics-ball.md](#sec-012)+- [agent-briefs/R-3d-world-fun/phase-2/R06-dance-floor-zone.md](#sec-013)+- [agent-briefs/R-3d-world-fun/phase-2/R07-minigame-king-of-the-totem.md](#sec-014)+- [agent-briefs/R-3d-world-fun/phase-2/R08-minigame-tag.md](#sec-015)+- [agent-briefs/R-3d-world-fun/phase-2/R09-emote-wheel.md](#sec-016)+- [agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md](#sec-017)+- [agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md](#sec-018)+- [agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md](#sec-019)+- [agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md](#sec-020)+- [agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md](#sec-021)+- [agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md](#sec-022)+- [agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md](#sec-023)+- [agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md](#sec-024)+- [agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md](#sec-025)+- [agent-briefs/W-world-online/PORT-CHECKLIST.md](#sec-026)+- [agent-briefs/W-world-online/README.md](#sec-027)+- [agent-briefs/W-world-online/W00-program-overview.md](#sec-028)+- [agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md](#sec-029)+- [agent-briefs/X-prod-errors-2026-06-05/README.md](#sec-030)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md](#sec-031)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md](#sec-032)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md](#sec-033)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md](#sec-034)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md](#sec-035)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md](#sec-036)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md](#sec-037)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md](#sec-038)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md](#sec-039)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md](#sec-040)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md](#sec-041)+- [agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md](#sec-042)++### agora++- [agora/tasks/00-INDEX.md](#sec-048)+- [agora/tasks/01-verify-foundation.md](#sec-049)+- [agora/tasks/02-life-engine.md](#sec-050)+- [agora/tasks/03-task-supply.md](#sec-051)+- [agora/tasks/04-professions.md](#sec-052)+- [agora/tasks/05-commons-scaffold.md](#sec-053)+- [agora/tasks/06-economy-visuals.md](#sec-054)+- [agora/tasks/07-verify-and-passport.md](#sec-055)+- [agora/tasks/08-humans-first-class.md](#sec-056)+- [agora/tasks/09-arena-and-guilds.md](#sec-057)+- [agora/tasks/10-agora-mcp.md](#sec-058)+- [agora/tasks/11-production-hardening.md](#sec-059)### api-- [api/forge-x402.md](#sec-047)+- [api/forge-x402.md](#sec-062)### audit-- [audit/2026-06-18-codebase-audit.md](#sec-050)-- [audit/2026-06-18-platform-audit.md](#sec-051)-- [audit/PLATFORM-AUDIT-2026-06-18.md](#sec-052)-- [audit/WIRING-UX-AUDIT-2026-06-18.md](#sec-053)-- [audit/remediation.md](#sec-054)+- [audit/2026-06-18-codebase-audit.md](#sec-065)+- [audit/2026-06-18-platform-audit.md](#sec-066)+- [audit/PLATFORM-AUDIT-2026-06-18.md](#sec-067)+- [audit/REMEDIATION-2026-06-18.md](#sec-068)+- [audit/WIRING-UX-AUDIT-2026-06-18.md](#sec-069)+- [audit/remediation.md](#sec-070)### audits-- [audits/01-main.md](#sec-055)-- [audits/02-build.md](#sec-056)-- [audits/03-crypto-trading.md](#sec-057)-- [audits/04-crypto-x402.md](#sec-058)-- [audits/05-crypto-launch-wallets.md](#sec-059)-- [audits/06-labs-agent-account.md](#sec-060)-- [audits/07-learn-blog-legal.md](#sec-061)-- [audits/FINDINGS.md](#sec-062)-- [audits/README.md](#sec-063)+- [audits/01-main.md](#sec-071)+- [audits/02-build.md](#sec-072)+- [audits/03-crypto-trading.md](#sec-073)+- [audits/04-crypto-x402.md](#sec-074)+- [audits/05-crypto-launch-wallets.md](#sec-075)+- [audits/06-labs-agent-account.md](#sec-076)+- [audits/07-learn-blog-legal.md](#sec-077)+- [audits/FINDINGS.md](#sec-078)+- [audits/README.md](#sec-079)### content-- [content/social/README.md](#sec-076)-- [content/social/calendar-4-week.md](#sec-077)-- [content/social/clip-plan.md](#sec-078)-- [content/social/hooks-library.md](#sec-079)-- [content/social/post-templates.md](#sec-080)-- [content/use-cases/README.md](#sec-081)-- [content/use-cases/ai-agent-developer.md](#sec-082)-- [content/use-cases/brand-marketer.md](#sec-083)-- [content/use-cases/crypto-community.md](#sec-084)-- [content/use-cases/game-studio.md](#sec-085)-- [content/use-cases/indie-creator.md](#sec-086)+- [content/social/README.md](#sec-092)+- [content/social/calendar-4-week.md](#sec-093)+- [content/social/clip-plan.md](#sec-094)+- [content/social/hooks-library.md](#sec-095)+- [content/social/post-templates.md](#sec-096)+- [content/use-cases/README.md](#sec-097)+- [content/use-cases/ai-agent-developer.md](#sec-098)+- [content/use-cases/brand-marketer.md](#sec-099)+- [content/use-cases/crypto-community.md](#sec-100)+- [content/use-cases/game-studio.md](#sec-101)+- [content/use-cases/indie-creator.md](#sec-102)### erc8004-- [erc8004/validation-attestation.md](#sec-094)+- [erc8004/validation-attestation.md](#sec-110)### internal-- [internal/AGENT-WALLET-CUSTODY.md](#sec-099)-- [internal/AUDIT-2026-06-18.md](#sec-100)-- [internal/AUDIT-LIVE-BROWSER-2026-06-18.md](#sec-101)-- [internal/AUTO_DRIVE_REPORT.md](#sec-102)-- [internal/AWS_MARKETPLACE_LISTING.md](#sec-103)-- [internal/CZ_DEMO_FAILURE_MODES.md](#sec-104)-- [internal/CZ_DEMO_RUNBOOK.md](#sec-105)-- [internal/DEVELOPMENT.md](#sec-106)-- [internal/IBM_USER_GROUP.md](#sec-107)-- [internal/ISSUES-ARCHIVE-2026-05.md](#sec-108)-- [internal/NEXT.md](#sec-109)-- [internal/PAGES.md](#sec-110)-- [internal/PROGRESS.md](#sec-111)-- [internal/PR_LISTINGS_CHECKLIST.md](#sec-112)-- [internal/SETUP.md](#sec-113)-- [internal/SMOKE_TEST.md](#sec-114)-- [internal/SNS_PARTNERSHIP_OUTBOUND.md](#sec-115)-- [internal/SNS_PARTNERSHIP_PROPOSAL.md](#sec-116)-- [internal/STATUS.md](#sec-117)-- [internal/TODO.md](#sec-118)-- [internal/VALIDATION_DEPLOY.md](#sec-119)-- [internal/api-inventory.md](#sec-120)-- [internal/tutorial-build-pai-site.md](#sec-121)+- [internal/AGENT-WALLET-CUSTODY.md](#sec-117)+- [internal/AUDIT-2026-06-18.md](#sec-118)+- [internal/AUDIT-LIVE-BROWSER-2026-06-18.md](#sec-119)+- [internal/AUTO_DRIVE_REPORT.md](#sec-120)+- [internal/AWS_MARKETPLACE_LISTING.md](#sec-121)+- [internal/CZ_DEMO_FAILURE_MODES.md](#sec-122)+- [internal/CZ_DEMO_RUNBOOK.md](#sec-123)+- [internal/DEVELOPMENT.md](#sec-124)+- [internal/HOLDER-CONFIDENCE-ROADMAP.md](#sec-125)+- [internal/IBM-WEBINAR-RUNBOOK.md](#sec-126)+- [internal/IBM_USER_GROUP.md](#sec-127)+- [internal/ISSUES-ARCHIVE-2026-05.md](#sec-128)+- [internal/ISSUES-ARCHIVE-2026-06.md](#sec-129)+- [internal/NEXT.md](#sec-130)+- [internal/PAGES.md](#sec-131)+- [internal/PROGRESS.md](#sec-132)+- [internal/PR_LISTINGS_CHECKLIST.md](#sec-133)+- [internal/SETUP.md](#sec-134)+- [internal/SMOKE_TEST.md](#sec-135)+- [internal/SNS_PARTNERSHIP_OUTBOUND.md](#sec-136)+- [internal/SNS_PARTNERSHIP_PROPOSAL.md](#sec-137)+- [internal/STATUS.md](#sec-138)+- [internal/TODO.md](#sec-139)+- [internal/VALIDATION_DEPLOY.md](#sec-140)+- [internal/api-inventory.md](#sec-141)+- [internal/tutorial-build-pai-site.md](#sec-142)### irl-- [irl/THREAT-MODEL.md](#sec-123)+- [irl/THREAT-MODEL.md](#sec-144)++### onboarding++- [onboarding/ONBOARDING-PLAN-2026-06-19.md](#sec-157)### ops-- [ops/forge-multiview-migration-handoff.md](#sec-136)-- [ops/redis.md](#sec-137)+- [ops/forge-multiview-migration-handoff.md](#sec-159)+- [ops/redis.md](#sec-160)### pumpfun-program-- [pumpfun-program/AUDIT-2026-06-08.md](#sec-145)-- [pumpfun-program/AUDIT-2026-06-11.md](#sec-146)-- [pumpfun-program/README.md](#sec-147)-- [pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md](#sec-148)-- [pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md](#sec-149)-- [pumpfun-program/docs/CPI_README.md](#sec-150)-- [pumpfun-program/docs/FAQ.md](#sec-151)-- [pumpfun-program/docs/FEE_PROGRAM_README.md](#sec-152)-- [pumpfun-program/docs/FEE_RECIPIENTS.md](#sec-153)-- [pumpfun-program/docs/PUMP_CASHBACK_README.md](#sec-154)-- [pumpfun-program/docs/PUMP_CREATOR_FEE_README.md](#sec-155)-- [pumpfun-program/docs/PUMP_PROGRAM_README.md](#sec-156)-- [pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md](#sec-157)-- [pumpfun-program/docs/PUMP_SWAP_README.md](#sec-158)-- [pumpfun-program/docs/PUMP_SWAP_SDK_README.md](#sec-159)-- [pumpfun-program/docs/instructions/BUY.md](#sec-160)-- [pumpfun-program/docs/instructions/CLAIM_CASHBACK.md](#sec-161)-- [pumpfun-program/docs/instructions/COIN_CREATION.md](#sec-162)-- [pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md](#sec-163)-- [pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md](#sec-164)-- [pumpfun-program/docs/instructions/SELL.md](#sec-165)+- [pumpfun-program/AUDIT-2026-06-08.md](#sec-168)+- [pumpfun-program/AUDIT-2026-06-11.md](#sec-169)+- [pumpfun-program/README.md](#sec-170)+- [pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md](#sec-171)+- [pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md](#sec-172)+- [pumpfun-program/docs/CPI_README.md](#sec-173)+- [pumpfun-program/docs/FAQ.md](#sec-174)+- [pumpfun-program/docs/FEE_PROGRAM_README.md](#sec-175)+- [pumpfun-program/docs/FEE_RECIPIENTS.md](#sec-176)+- [pumpfun-program/docs/PUMP_CASHBACK_README.md](#sec-177)+- [pumpfun-program/docs/PUMP_CREATOR_FEE_README.md](#sec-178)+- [pumpfun-program/docs/PUMP_PROGRAM_README.md](#sec-179)+- [pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md](#sec-180)+- [pumpfun-program/docs/PUMP_SWAP_README.md](#sec-181)+- [pumpfun-program/docs/PUMP_SWAP_SDK_README.md](#sec-182)+- [pumpfun-program/docs/instructions/BUY.md](#sec-183)+- [pumpfun-program/docs/instructions/CLAIM_CASHBACK.md](#sec-184)+- [pumpfun-program/docs/instructions/COIN_CREATION.md](#sec-185)+- [pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md](#sec-186)+- [pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md](#sec-187)+- [pumpfun-program/docs/instructions/SELL.md](#sec-188)### roadmap-- [roadmap/3d-world-fun.md](#sec-168)-- [roadmap/coin-intelligence-engine.md](#sec-169)-- [roadmap/creation-consolidation.md](#sec-170)-- [roadmap/developer-resources-repos.md](#sec-171)-- [roadmap/generation-suite.md](#sec-172)-- [roadmap/pumpfun-social-trading.md](#sec-173)-- [roadmap/pumpfun-trading-arena.md](#sec-174)-- [roadmap/pumpfun-trading-wedge.md](#sec-175)-- [roadmap/pumpfun-trading.md](#sec-176)+- [roadmap/3d-world-fun.md](#sec-192)+- [roadmap/coin-intelligence-engine.md](#sec-193)+- [roadmap/creation-consolidation.md](#sec-194)+- [roadmap/developer-resources-repos.md](#sec-195)+- [roadmap/generation-suite.md](#sec-196)+- [roadmap/pumpfun-social-trading.md](#sec-197)+- [roadmap/pumpfun-trading-arena.md](#sec-198)+- [roadmap/pumpfun-trading-wedge.md](#sec-199)+- [roadmap/pumpfun-trading.md](#sec-200)### security-- [security/SECURITY_AUDIT.md](#sec-179)-- [security/SECURITY_REMEDIATION.md](#sec-180)+- [security/SECURITY_AUDIT.md](#sec-205)+- [security/SECURITY_REMEDIATION.md](#sec-206)++### specs++- [specs/agent-trading.md](#sec-213)### tutorials-- [tutorials/agent-personality.md](#sec-189)-- [tutorials/connect-ai-brain.md](#sec-190)-- [tutorials/custom-skill.md](#sec-191)-- [tutorials/customize-appearance.md](#sec-192)-- [tutorials/deploy-to-vercel-custom-domain.md](#sec-193)-- [tutorials/embed-in-30-seconds.md](#sec-194)-- [tutorials/embed-on-website.md](#sec-195)-- [tutorials/first-agent.md](#sec-196)-- [tutorials/generate-3d-api.md](#sec-197)-- [tutorials/greeting-and-first-speech.md](#sec-198)-- [tutorials/image-to-3d.md](#sec-199)-- [tutorials/js-api-events.md](#sec-200)-- [tutorials/mcp-server-for-your-agent.md](#sec-201)-- [tutorials/mint-pumpfun-token.md](#sec-202)-- [tutorials/multi-agent-coordination.md](#sec-203)-- [tutorials/paid-x402-endpoint.md](#sec-204)-- [tutorials/personal-ai-site.md](#sec-205)-- [tutorials/prompts-for-3d.md](#sec-206)-- [tutorials/register-onchain.md](#sec-207)-- [tutorials/self-host-agent-backend.md](#sec-208)-- [tutorials/share-your-agent.md](#sec-209)-- [tutorials/skill-with-database-auth.md](#sec-210)-- [tutorials/swap-avatar-in-studio.md](#sec-211)-- [tutorials/text-to-3d.md](#sec-212)-- [tutorials/trigger-from-page-events.md](#sec-213)-- [tutorials/upload-custom-glb.md](#sec-214)-- [tutorials/view-in-ar.md](#sec-215)-- [tutorials/web-component-end-to-end.md](#sec-216)+- [tutorials/agent-personality.md](#sec-217)+- [tutorials/agent-reputation.md](#sec-218)+- [tutorials/animate-your-avatar.md](#sec-219)+- [tutorials/build-a-scene.md](#sec-220)+- [tutorials/claim-threews-name.md](#sec-221)+- [tutorials/connect-ai-brain.md](#sec-222)+- [tutorials/create-and-edit-memory.md](#sec-223)+- [tutorials/custom-skill.md](#sec-224)+- [tutorials/customize-appearance.md](#sec-225)+- [tutorials/deploy-to-vercel-custom-domain.md](#sec-226)+- [tutorials/embed-in-30-seconds.md](#sec-227)+- [tutorials/embed-on-website.md](#sec-228)+- [tutorials/first-agent.md](#sec-229)+- [tutorials/generate-3d-api.md](#sec-230)+- [tutorials/getting-started.md](#sec-231)+- [tutorials/greeting-and-first-speech.md](#sec-232)+- [tutorials/image-to-3d.md](#sec-233)+- [tutorials/import-avatar-url.md](#sec-234)+- [tutorials/js-api-events.md](#sec-235)+- [tutorials/mcp-server-for-your-agent.md](#sec-236)+- [tutorials/mine-vanity-address.md](#sec-237)+- [tutorials/mint-pumpfun-token.md](#sec-238)+- [tutorials/multi-agent-coordination.md](#sec-239)+- [tutorials/nvidia-3d-free.md](#sec-240)+- [tutorials/nvidia-nim-self-host.md](#sec-241)+- [tutorials/paid-x402-endpoint.md](#sec-242)+- [tutorials/pay-for-x402-service.md](#sec-243)+- [tutorials/personal-ai-site.md](#sec-244)+- [tutorials/place-agent-irl.md](#sec-245)+- [tutorials/prompts-for-3d.md](#sec-246)+- [tutorials/register-onchain.md](#sec-247)+- [tutorials/self-host-agent-backend.md](#sec-248)+- [tutorials/selfie-to-avatar.md](#sec-249)+- [tutorials/share-your-agent.md](#sec-250)+- [tutorials/skill-with-database-auth.md](#sec-251)+- [tutorials/swap-avatar-in-studio.md](#sec-252)+- [tutorials/text-to-3d.md](#sec-253)+- [tutorials/trigger-from-page-events.md](#sec-254)+- [tutorials/upload-custom-glb.md](#sec-255)+- [tutorials/view-in-ar.md](#sec-256)+- [tutorials/voice-and-lipsync.md](#sec-257)+- [tutorials/walk-companion.md](#sec-258)+- [tutorials/web-component-end-to-end.md](#sec-259)++### ux-flows++- [ux-flows/01-onboarding-creation.md](#sec-260)+- [ux-flows/02-forge-text-to-3d.md](#sec-261)+- [ux-flows/03-3d-editing-viewer.md](#sec-262)+- [ux-flows/04-embed-widget-studio.md](#sec-263)+- [ux-flows/05-discovery-social.md](#sec-264)+- [ux-flows/06-marketplace-skills.md](#sec-265)+- [ux-flows/07-crypto-trading-analytics.md](#sec-266)+- [ux-flows/08-coin-launch-wallets.md](#sec-267)+- [ux-flows/09-x402-agent-commerce.md](#sec-268)+- [ux-flows/10-chat-brain-labs.md](#sec-269)+- [ux-flows/11-account-dashboard.md](#sec-270)+- [ux-flows/12-home-and-content.md](#sec-271)### x402-offer-receipt-- [x402-offer-receipt/00-plan.md](#sec-224)-- [x402-offer-receipt/01-foundation.md](#sec-225)-- [x402-offer-receipt/02-offer-signing.md](#sec-226)-- [x402-offer-receipt/03-receipt-signing.md](#sec-227)-- [x402-offer-receipt/04-bazaar-declaration.md](#sec-228)-- [x402-offer-receipt/05-verification-script.md](#sec-229)-- [x402-offer-receipt/06-completionist-and-push.md](#sec-230)+- [x402-offer-receipt/00-plan.md](#sec-279)+- [x402-offer-receipt/01-foundation.md](#sec-280)+- [x402-offer-receipt/02-offer-signing.md](#sec-281)+- [x402-offer-receipt/03-receipt-signing.md](#sec-282)+- [x402-offer-receipt/04-bazaar-declaration.md](#sec-283)+- [x402-offer-receipt/05-verification-script.md](#sec-284)+- [x402-offer-receipt/06-completionist-and-push.md](#sec-285)### zauth-- [zauth/database.md](#sec-232)-- [zauth/index.md](#sec-233)-- [zauth/provider-hub.md](#sec-234)-- [zauth/reposcan.md](#sec-235)-- [zauth/vector.md](#sec-236)+- [zauth/database.md](#sec-287)+- [zauth/index.md](#sec-288)+- [zauth/provider-hub.md](#sec-289)+- [zauth/reposcan.md](#sec-290)+- [zauth/vector.md](#sec-291)---@@ -697,6 +764,30 @@ auto-exempt. A cluster of mutating routes omit it:---+## Remediation status (2026-06-19)++**Shipped in this pass** (verified: `node --check` + targeted `vitest`):++- **P1** — `wrap()` now sanitizes every uncaught 5xx to a correlation `ref` (no `err.message` in the body); the keyed-`HELIUS_API_KEY` leak sites in `pump/[action].js` (×6), `coin/[mint]/cohorts.js`, and `tx/explain.js` now route through `respondError`/fixed messages. A broad lower-priority sweep sanitized ~47 more `>=500` `err.message` leaks across agents/, bazaar/, skills/, scene/, nft/, inference/, assets/, seed/.+- **C1** — `DEMO_AVATARS` fixture + generator deleted; all 8 consumers serve real DB rows only; obsolete OG demo test removed.+- **P2** — `requireCsrf` added to all 15 cookie-session mutations (bearer stays exempt). Handler-logic tests isolated via a `requireCsrf` mock; `security-csrf-gates` green.+- **P3 / H11** — rate limits wired on `auth/wallets` (+ Redis-backed single-use link nonces), `auth/github`, `oauth/authorize`, the three money-moving admin actions, and the four `agents/payments` fund-prep/confirm handlers (which also gained the ownership gate).+- **H3** — both paid intel endpoints now throw `503` on a live-data miss (verified the buyer is not charged: `handler()` runs before `settlePayment`).+- **H4** — `settleRoyalties` claims rows atomically (`pending → settling`, new migration `20260619000000_royalty_settling_status.sql`) before the on-chain redeem; no double-pay.+- **H5** — `agents/by-address` enumeration capped at `MAX_ENUM` with a `truncated` flag.+- **H6 / H7** — `oracle/social` real limiter; `oracle/follow` POST/DELETE no longer dead (branch on `req.method`, `readJson` size cap restored).+- **H8** — `vision.describeImage` now applies a synchronous SSRF guard (https + block private/loopback IP literals + localhost) covering every consumer, with no live-DNS dependency.+- **H9** — `users/[username]` no longer leaks `referral_code`.+- **H12 / M4** — `tx/explain` validates `sig` before forwarding; Solana plan-payment confirm claims the intent atomically (conditional UPDATE → 409 on race).+- **M1 / M2** — retired Claude Haiku model ids replaced (`talk.js`, `brain/chat.js`).++**Deferred — require a verified follow-up PR (do not ship blind on money paths):**++- **H1 (agent spending-cap race)** — the race-free reserve-first ledger (`x402-spending-cap.js`) is wired only into `x402-user-payer.js`. Bringing the agent pay path (`x402-pay.js` + `agent-trade-guards.js`) onto it means reserving in the ledger before signing and rolling back on settle failure — a change to the live signing path that needs a funded test wallet to validate. **Remediation:** reserve-then-sign-then-finalize with rollback, keyed on `agent_id`, mirroring `x402-user-payer.js`.+- **H2 (subscription active-before-pay)** — `creator_subscriptions` is granted an active period before payment, AND its `confirmPayment` activation function has **zero callers** (the in-app pay-confirm path is unwired). A one-line status flip would permanently lock out every subscriber. The duplicate-subscription race the audit also flagged is already prevented by the `unique(plan_id, subscriber_user_id)` constraint. **Remediation (3 parts):** (a) migration adding a pre-active status to the CHECK constraint; (b) wire `confirmPayment` into the tx-confirmation/cron path; (c) initialize new subs in the pre-active state. Until then the parallel `subscription_checkouts`/`verify.js` flow remains the correctly-gated path.++**Pre-existing / concurrent-agent test failures (NOT from this pass — confirmed against clean HEAD):** `agent-monetization` (2, env), `ibm-attest` (2, Guardian env), `oauth-token` (2, env), and `widgets` (4) — the last is a real CSRF-placement bug introduced by a concurrent commit (`aaa038c1`): on `widgets/[id]` PATCH the CSRF check fires before the bearer-scope check, so a scoped-bearer request gets `csrf_missing` instead of `insufficient_scope`. Fix: gate that route's CSRF with the `if (session && …)` form so bearer callers reach the scope check.+## Fix plan (execution order)1. **P1 boundary** — sanitize `wrap()` 5xx + the keyed-URL leak sites. _(security)_@@ -840,6 +931,256 @@ here when a real need appears; keep the "no hardcoded values" rule intact._<a id="sec-004"></a>+> **Source:** `docs/PROTOCOL-vanity.md` · [↑ table of contents](#table-of-contents)++# three-vanity/v1 — Provably-Fair Vanity Grinding Protocol++A vanity-address service normally asks you to **trust the operator**: trust that+your key was generated with real randomness, that no copy was kept, that they+didn't grind thousands of candidates and hand you the one whose key they secretly+logged. There is no proof; you just hope.++`three-vanity/v1` replaces that hope with a **commit–reveal + sealed-delivery ++signed-receipt** protocol. A buyer can verify, after the fact and with+open-source tooling, that:++1. the key was generated **fresh** from entropy the server committed to *before*+ it knew the buyer's pattern (no precomputed rainbow table of keys);+2. the buyer's own entropy was mixed in, so **neither party alone** controlled+ the output;+3. the address actually derives from the revealed seed, matches the pattern, and+ the difficulty claim is the honest probability model;+4. the receipt was **signed by the three.ws service key**, not an impostor;+5. (optionally) the key the buyer recovered from the sealed envelope is+ byte-for-byte the key the receipt describes — **the buyer alone holds it**.++This document specifies the scheme precisely enough to reimplement the verifier+in any language. The reference implementations are+[`src/solana/vanity/verifiable-grind.js`](../src/solana/vanity/verifiable-grind.js)+(server + Node verifier), [`solana-agent-sdk/src/vanity`](../solana-agent-sdk/src/vanity)+(TypeScript SDK), and [`scripts/verify-vanity-receipt.mjs`](../scripts/verify-vanity-receipt.mjs)+(CLI). The web verifier is [`/vanity/verify`](https://three.ws/vanity/verify).++---++## Primitives++| Purpose | Algorithm | Source |+| ------------------ | ------------------------------------------- | --------------------- |+| Hash / commitment | SHA-256 | `@noble/hashes` |+| Seed mixing (KDF) | HKDF-SHA256 | `@noble/hashes` |+| Candidate stream | HMAC-SHA256 | `@noble/hashes` |+| Keypair | Ed25519 (Solana address = public key) | `@noble/curves` |+| Receipt signature | Ed25519 | `@noble/curves` |+| Sealed delivery | `x25519-hkdf-sha256-aes256gcm/v1` (ECIES) | `sealed-envelope.js` |++All byte strings below are concatenated left-to-right. `uint64_be(n)` is the+8-byte big-endian encoding of a non-negative integer. Domain-separation tags are+ASCII (UTF-8) byte strings.++### Domain-separation tags++```+TAG_SEED_COMMIT = "three-vanity/seed-commit/v1"+TAG_MIX_SALT = SHA-256("three-vanity/mix-salt/v1") // 32 bytes+TAG_MASTER_INFO = "three-vanity/master/v1"+TAG_CANDIDATE = "three-vanity/candidate/v1"+TAG_RECEIPT = "three-vanity/receipt/v1"+```++---++## 1. Commitment (commit phase)++Before grinding, the server draws a uniformly-random 32-byte `serverSeed` and+publishes a commitment to it:++```+commitment = hex( SHA-256( TAG_SEED_COMMIT ‖ serverSeed ) )+```++The commitment is bound into the signed receipt, so the server is locked to that+seed *before* it knows which candidate will win. It cannot have precomputed a+table of keys keyed to the buyer's pattern: any swap of `serverSeed` after the+fact breaks `SHA-256(serverSeed) == commitment`.++`serverSeed` is **revealed** in the receipt (the reveal phase). Verification+recomputes the commitment and compares it byte-for-byte.++## 2. Seed mixing++Neither the server nor the buyer may control the output alone. The two seeds and+the per-request nonce are folded into one 32-byte master seed:++```+masterSeed = HKDF-SHA256(+ ikm = serverSeed ‖ clientSeed ‖ requestNonce,+ salt = TAG_MIX_SALT,+ info = TAG_MASTER_INFO,+ len = 32 )+```++- `clientSeed` is buyer-supplied entropy (hex or Base58, any length 1–1024+ bytes). If the buyer omits it, the server generates a fresh random 32-byte+ `clientSeed` and **reveals** it in the receipt. Either way the buyer can+ confirm their entropy went into the mix.+- `requestNonce` is a fresh random 16 bytes drawn per request and revealed.++Because the order is fixed and each input is domain-separated by HKDF, swapping+`serverSeed` ↔ `clientSeed` (or altering either) yields a different `masterSeed`,+which yields a different candidate stream and address.++## 3. Candidate derivation (grind)++Candidate `i` (a 0-based counter) has a fully deterministic Ed25519 private seed:++```+seed_i = HMAC-SHA256( key = masterSeed, msg = TAG_CANDIDATE ‖ uint64_be(i) )+publicKey_i = Ed25519.getPublicKey( seed_i ) // 32 bytes+address_i = Base58( publicKey_i ) // Solana address+```++The grinder walks `i = 0, 1, 2, …` until `address_i` satisfies the requested+pattern (see §4). The winning index is recorded as `winningIndex`. The Solana+64-byte secret key is `seed_i ‖ publicKey_i` (the `Keypair.fromSecretKey` /+Phantom import format).++> **Why pure-JS Ed25519, not the WASM grinder?** Verifiability requires the+> verifier to reproduce the exact candidate stream from `masterSeed` and+> `winningIndex`. The deterministic HMAC→Ed25519 derivation above is the stream;+> the WASM engine's internal `crypto.getRandomValues` keys are not reproducible+> and are therefore **not** used by this protocol.++## 4. Pattern matching++```+matches(address, prefix, suffix, ignoreCase):+ a, p, s = address, prefix, suffix+ if ignoreCase: a, p, s = lower(a), lower(p), lower(s)+ return (p == "" or a.startsWith(p)) and (s == "" or a.endsWith(s))+```++The Base58 alphabet excludes `0 O I l`. **Difficulty** is the mean of a geometric+distribution — the expected number of candidates to a hit:++```+expectedAttempts(prefix, suffix, ignoreCase):+ n = 1+ for ch in prefix ‖ suffix:+ n *= 58 / matchesPerChar(ch, ignoreCase) // 2 iff ignoreCase and both cases are valid Base58, else 1+ return n+```++The receipt's `difficulty.expectedAttempts` MUST equal `round(expectedAttempts(…))`.++## 5. Sealed delivery++When the buyer supplies an X25519 public key (`sealTo`), the secret bundle++```+{ format: "keypair", secretKeyBase58, secretKey: number[64], seed: hex }+```++is sealed with the ECIES scheme `x25519-hkdf-sha256-aes256gcm/v1` (see+[`sealed-envelope.js`](../src/solana/vanity/sealed-envelope.js)):++1. ephemeral X25519 keypair `e`;+2. `shared = X25519(e.secret, recipientPub)`;+3. `key = HKDF-SHA256(ikm=shared, salt=e.public ‖ recipientPub,+ info="three.ws sealed-envelope v1", 32)`;+4. AES-256-GCM(key, random 12-byte nonce, AAD = `e.public`);+5. emit `{ scheme, epk, nonce, ciphertext, recipient }`.++The ephemeral secret is discarded, so the envelope is forward-secret with respect+to the server. The receipt records `sealedRecipient` and `sealedEpk` so the buyer+can prove *this* envelope was sealed to *their* key. The plaintext secret never+appears in the response, a proxy log, or the idempotency cache.++## 6. Signed receipt++The server signs a canonical projection of the receipt with its long-lived+Ed25519 identity key (published at+[`/.well-known/three-vanity.json`](https://three.ws/.well-known/three-vanity.json)+and pinned in the SDK + CLI + web verifier).++**Signed fields** (and only these — delivery payload and navigation hints are+*not* signed):++```+protocol, receiptType, address, pattern, commitment, serverSeed, clientSeed,+requestNonce, winningIndex, attempts, durationMs, difficulty, sealed,+sealedScheme, sealedRecipient, sealedEpk, network, ts+```++**Canonical bytes.** Project the receipt to the signed fields above (dropping any+field whose value is `undefined`), JSON-serialize with **recursively+lexicographically-sorted object keys** and no insignificant whitespace, then:++```+message = TAG_RECEIPT ‖ utf8( canonicalJSON )+signature = hex( Ed25519.sign(message, serviceSigningSeed) )+```++The receipt carries `signature`, `servicePublicKey` (Base58), and+`signatureScheme: "ed25519"`. Extra response fields (`sealedSecret`,+`secretKeyBase58`, `explorerUrl`, `verifyUrl`, …) are intentionally outside the+signature, so a UI or transport may add/strip them without invalidating it; the+verifier re-projects to the signed fields before checking.++---++## Verification algorithm++Given a receipt (and, optionally, the opened secret seed), a verifier MUST+recompute — never trust — each of the following. All must pass.++1. **protocol** — `receipt.protocol == "three-vanity/v1"`.+2. **commitment** — `SHA-256(TAG_SEED_COMMIT ‖ serverSeed) == commitment`.+3. **derivation** — re-derive `masterSeed` (§2) and `address_{winningIndex}`+ (§3); it MUST equal `receipt.address`.+4. **pattern** — `receipt.address` satisfies `receipt.pattern` (§4).+5. **difficulty** — `difficulty.expectedAttempts == round(expectedAttempts(…))`.+6. **signature** — Ed25519-verify the canonical message (§6) against the pinned+ service key, AND the receipt's `servicePublicKey` equals the pinned key+ (reject impostors that self-sign under a different key).+7. **custody** *(optional)* — if the buyer opened the sealed envelope, the+ recovered 32-byte seed MUST equal `seed_{winningIndex}` and its Ed25519 public+ key MUST equal `receipt.address`.++A single failing check means the receipt is not trustworthy. The negative test in+[`tests/vanity-verifiable-grind.test.js`](../tests/vanity-verifiable-grind.test.js)+pins that a tampered address, swapped `serverSeed`, wrong `winningIndex`, inflated+difficulty, impostor signing key, or mismatched opened secret each FAIL.++---++## Service key publication & rotation++`/.well-known/three-vanity.json` publishes:++```json+{+ "protocol": "three-vanity/v1",+ "serviceKey": { "curve": "ed25519", "publicKeyBase58": "…", "publicKeyHex": "…", "use": "receipt-signing" },+ "schemes": { … },+ "endpoints": { "grind": "/api/x402/vanity-verifiable", "verifyPage": "/vanity/verify" }+}+```++The SDK pins `THREE_VANITY_SERVICE_KEY`; for production verification, cross-check+it against the live well-known document (`fetchServiceKey()` / `--fetch-key` /+the web page does this automatically). On key rotation, update the well-known+document and the pinned SDK constant; receipts signed under the previous key+remain verifiable against that key but new pins should track the current one.++The signing **secret** is custodial: stored encrypted at rest via+[`secret-box.js`](../api/_lib/secret-box.js) under `VANITY_SERVICE_KEY`, never+logged, never returned.++---++<a id="sec-005"></a>+> **Source:** `docs/agent-briefs/B-design-system/B02-migration-rules.md` · [↑ table of contents](#table-of-contents)# B02 — Token migration rules (shared)@@ -917,7 +1258,7 @@ HTML page — delete the files and scrub any comment references in `public/mobil----<a id="sec-005"></a>+<a id="sec-006"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/R00-program-overview.md` · [↑ table of contents](#table-of-contents)@@ -1036,7 +1377,7 @@ Total: 18 briefs. Read this file, then your brief, then the files your brief nam----<a id="sec-006"></a>+<a id="sec-007"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/README.md` · [↑ table of contents](#table-of-contents)@@ -1099,7 +1440,7 @@ Suggested build order = phase order. Phase 1 unblocks the most. See R00 for the----<a id="sec-007"></a>+<a id="sec-008"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-1/R01-server-world-object-sync.md` · [↑ table of contents](#table-of-contents)@@ -1154,7 +1495,7 @@ feature (ball, confetti, blocks, props) reuses, so it must be generic and bullet----<a id="sec-008"></a>+<a id="sec-009"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-1/R02-client-world-objects-manager.md` · [↑ table of contents](#table-of-contents)@@ -1208,7 +1549,7 @@ without editing this manager.----<a id="sec-009"></a>+<a id="sec-010"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-1/R03-cosmetics-accessory-rig.md` · [↑ table of contents](#table-of-contents)@@ -1261,7 +1602,7 @@ and it survives avatar swaps. This rig is the foundation the Phase 4 economy sel----<a id="sec-010"></a>+<a id="sec-011"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R04-emoji-confetti-reactions.md` · [↑ table of contents](#table-of-contents)@@ -1307,7 +1648,7 @@ floating-rising-fading emoji sprite above the sender's avatar, plus a confetti b----<a id="sec-011"></a>+<a id="sec-012"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R05-kickable-physics-ball.md` · [↑ table of contents](#table-of-contents)@@ -1353,7 +1694,7 @@ same trajectory; it settles realistically and never desyncs badly.----<a id="sec-012"></a>+<a id="sec-013"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R06-dance-floor-zone.md` · [↑ table of contents](#table-of-contents)@@ -1402,7 +1743,7 @@ dance where everyone on the floor crossfades to the same clip on a shared beat.----<a id="sec-013"></a>+<a id="sec-014"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R07-minigame-king-of-the-totem.md` · [↑ table of contents](#table-of-contents)@@ -1450,7 +1791,7 @@ confetti.----<a id="sec-014"></a>+<a id="sec-015"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R08-minigame-tag.md` · [↑ table of contents](#table-of-contents)@@ -1498,7 +1839,7 @@ marker.----<a id="sec-015"></a>+<a id="sec-016"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-2/R09-emote-wheel.md` · [↑ table of contents](#table-of-contents)@@ -1545,7 +1886,7 @@ for the top 6.----<a id="sec-016"></a>+<a id="sec-017"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md` · [↑ table of contents](#table-of-contents)@@ -1591,7 +1932,7 @@ world shows the same build; it survives a server restart.----<a id="sec-017"></a>+<a id="sec-018"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md` · [↑ table of contents](#table-of-contents)@@ -1641,7 +1982,7 @@ Clean enter/exit between movement and build cursor.----<a id="sec-018"></a>+<a id="sec-019"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md` · [↑ table of contents](#table-of-contents)@@ -1687,7 +2028,7 @@ grief guard. Plus a creator "clear area" moderation tool. Griefing is bounded; o----<a id="sec-019"></a>+<a id="sec-020"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md` · [↑ table of contents](#table-of-contents)@@ -1736,7 +2077,7 @@ satisfying and snaps cleanly; large builds stay smooth.----<a id="sec-020"></a>+<a id="sec-021"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md` · [↑ table of contents](#table-of-contents)@@ -1783,7 +2124,7 @@ live on your own avatar** before buying — with correct owned vs locked states.----<a id="sec-021"></a>+<a id="sec-022"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md` · [↑ table of contents](#table-of-contents)@@ -1831,7 +2172,7 @@ ownership to the player's account/wallet. Handle every payment state honestly at----<a id="sec-022"></a>+<a id="sec-023"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md` · [↑ table of contents](#table-of-contents)@@ -1879,7 +2220,7 @@ login and across worlds (`/play` and `/walk`).----<a id="sec-023"></a>+<a id="sec-024"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md` · [↑ table of contents](#table-of-contents)@@ -1930,7 +2271,7 @@ qualify.----<a id="sec-024"></a>+<a id="sec-025"></a>> **Source:** `docs/agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md` · [↑ table of contents](#table-of-contents)@@ -1981,7 +2322,7 @@ with a creator earnings view in the dashboard. Plus a platform-wide cosmetics le----<a id="sec-025"></a>+<a id="sec-026"></a>> **Source:** `docs/agent-briefs/W-world-online/PORT-CHECKLIST.md` · [↑ table of contents](#table-of-contents)@@ -2150,7 +2491,7 @@ already exist and just need importing.----<a id="sec-026"></a>+<a id="sec-027"></a>> **Source:** `docs/agent-briefs/W-world-online/README.md` · [↑ table of contents](#table-of-contents)@@ -2189,7 +2530,7 @@ Suggested build order = the table order (W01 → W10). W01 unblocks the most.----<a id="sec-027"></a>+<a id="sec-028"></a>> **Source:** `docs/agent-briefs/W-world-online/W00-program-overview.md` · [↑ table of contents](#table-of-contents)@@ -2353,7 +2694,7 @@ overview. When in doubt, re-read this file.----<a id="sec-028"></a>+<a id="sec-029"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md` · [↑ table of contents](#table-of-contents)@@ -2437,7 +2778,7 @@ Grep the next 24h of function logs — these signatures should be gone or near-z----<a id="sec-029"></a>+<a id="sec-030"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/README.md` · [↑ table of contents](#table-of-contents)@@ -2492,7 +2833,7 @@ separate "add credits" (ops) from "fix the routing" (code) so the code half can----<a id="sec-030"></a>+<a id="sec-031"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md` · [↑ table of contents](#table-of-contents)@@ -2573,7 +2914,7 @@ page, the dependency tree is internally consistent, and the crash signature cann----<a id="sec-031"></a>+<a id="sec-032"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md` · [↑ table of contents](#table-of-contents)@@ -2649,7 +2990,7 @@ upgrade. Graceful degradation is wired everywhere Redis is touched.----<a id="sec-032"></a>+<a id="sec-033"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md` · [↑ table of contents](#table-of-contents)@@ -2729,7 +3070,7 @@ knows exactly which provider account needs funding.----<a id="sec-033"></a>+<a id="sec-034"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/04-missing-db-tables.md` · [↑ table of contents](#table-of-contents)@@ -2798,7 +3139,7 @@ schema.sql-vs-migrations drift that caused this is reconciled so it can't recur.----<a id="sec-034"></a>+<a id="sec-035"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/05-birdeye-geckoterminal-429.md` · [↑ table of contents](#table-of-contents)@@ -2857,7 +3198,7 @@ available API key is used for the higher tier.----<a id="sec-035"></a>+<a id="sec-036"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/06-brain-chat-openrouter-credits.md` · [↑ table of contents](#table-of-contents)@@ -2929,7 +3270,7 @@ rate limits — no `AI_APICallError` for these three causes.----<a id="sec-036"></a>+<a id="sec-037"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/07-token-treasury-wallet-unset.md` · [↑ table of contents](#table-of-contents)@@ -2994,7 +3335,7 @@ the address before it was set.----<a id="sec-037"></a>+<a id="sec-038"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/08-cron-eth-rpc-failures.md` · [↑ table of contents](#table-of-contents)@@ -3066,7 +3407,7 @@ failure doesn't abort the run.----<a id="sec-038"></a>+<a id="sec-039"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/09-pump-launch-wasm-and-tx.md` · [↑ table of contents](#table-of-contents)@@ -3143,7 +3484,7 @@ function time limit, and a real launch succeeds end-to-end.----<a id="sec-039"></a>+<a id="sec-040"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/10-skills-pricing-neon-transaction.md` · [↑ table of contents](#table-of-contents)@@ -3204,7 +3545,7 @@ validate input at the boundary, and every call site is fixed.----<a id="sec-040"></a>+<a id="sec-041"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/11-og-and-url-edge-cases.md` · [↑ table of contents](#table-of-contents)@@ -3269,7 +3610,7 @@ with an explicitly bundled font.----<a id="sec-041"></a>+<a id="sec-042"></a>> **Source:** `docs/agent-briefs/X-prod-errors-2026-06-05/prompts/12-misc-data-integrity.md` · [↑ table of contents](#table-of-contents)@@ -3334,7 +3675,7 @@ to a real alternative). No unhandled throws on any of the three paths.----<a id="sec-042"></a>+<a id="sec-043"></a>> **Source:** `docs/agent-manifest.md` · [↑ table of contents](#table-of-contents)@@ -3996,7 +4337,172 @@ The `spec` field identifies the manifest format version. Current stable: `agent-----<a id="sec-043"></a>+<a id="sec-044"></a>++> **Source:** `docs/agent-reputation.md` · [↑ table of contents](#table-of-contents)++# Agent Reputation++**Why autonomous agents need verifiable trust — and how three.ws delivers it on-chain.**++This page is the *why*. For the practical how-to, see [Reputation System](./reputation.md) (leaving and reading reviews) and [ERC-8004](./erc8004.md) (the identity standard underneath). To read a real agent's score five different ways, follow the [Read an agent's reputation](/tutorials/agent-reputation) tutorial. For the Solana side of the same idea — memo attestations, the AgenC coordination program, and the identity bridge — see [Agent Reputation on Solana](./solana-reputation.md).++---++## The problem: trust at machine speed++Picture an autonomous agent that needs to get something done — buy a dataset, commission a render, delegate a sub-task, route a payment. It finds a candidate counterparty it has never interacted with. There is no human in the loop to vouch for either side, no brand to recognize, no contract to sign, no support line to call if the deal goes wrong.++So it faces one question, and it has to answer it in milliseconds, in code:++> **Should I trust this agent enough to pay it?**++Every human trust heuristic — reputation by word of mouth, legal recourse, "I've heard of them" — evaporates at machine speed and machine scale. What's left has to be **machine-readable, programmatically queryable, and checkable *before* value moves.** That is what agent reputation is: a trust signal an agent can read about another agent and act on without asking anyone's permission.++Without it, an agent economy has only two failure modes:++- **Paralysis** — treat every counterparty as hostile, and nothing gets delegated.+- **Exploitation** — trust every counterparty, and you get drained by the first bad actor.++Reputation is the third path. It's the difference between an agent internet that can transact and one that can only talk.++---++## A worked example: the bouncer at the door++The clearest way to see the shape of the problem is the smallest real instance of it on three.ws — the [Pole Club](/club) door.++The Club is a venue where wallets pay tiny USDC amounts to tip performers. To get in, a wallet pays a cover charge. The instant that payment settles, a **bouncer** runs — and that bouncer is a complete reputation system in miniature:++1. **Identity is proven by payment, not by a claim.** There is no signup. You can only get an "admitted" response by signing a real payment from the wallet being vetted. The wallet *is* the identity, and it authenticated itself by spending money it controls. That's Sybil-resistance-by-cost in its crudest form.+2. **Trust is read from history.** The bouncer counts the wallet's prior settled activity and assigns a tier — newcomer, regular, or VIP.+3. **Bad actors are excluded.** A denylist turns away wallets that have abused the venue — and because the cover already settled, being on the list has a cost.++In a hundred lines, the Club has all four primitives of trust: **identity** (the paying wallet), **history** (prior activity), **a grade** (newcomer/regular/VIP), and **exclusion** (the ban list).++And it has the exact limitation that on-chain reputation exists to fix: **the bouncer reads a private database only three.ws can see.** A VIP at the Club is a complete stranger at every other venue on the internet. Walk out the door and the reputation resets to zero. That siloing — reputation as a moat instead of a public good — is the problem the rest of this page solves.++---++## Why on-chain, and why portable++Traditional rating systems (app stores, marketplaces, review sites) share a structural weakness: **the platform owns the data.** Reviews can vanish overnight, fake accounts can inflate scores, and the reputation is locked inside one product. Every new platform an agent joins starts it back at zero. (Studies of cross-platform reputation transfer put its effectiveness around 35% — roughly two-thirds of credibility is lost crossing a boundary.)++On-chain reputation changes the ownership model:++- **Permanent.** The chain is append-only. A submitted score exists as long as the chain does — no one can quietly delete it.+- **Permissionless to read.** Anyone — a webpage, a server, an AI tool, even another smart contract — can read the registry directly. No API key, no account, no gatekeeper.+- **Sybil-resistant by cost.** One wallet gets one review per agent; faking reputation means funding many wallets and paying gas for each.+- **Portable and composable.** The *same* reputation is readable everywhere. A marketplace, a search ranker, a payment facilitator, and a governance contract can all consume one score without coordinating. An agent builds a name **once** and carries it everywhere.++That last property is the entire thesis. Reputation has to be a public good that composes across platforms, or every marketplace is an island and no agent can ever build a reputation worth having.++---++## The architecture: three registries (ERC-8004)++three.ws implements agent reputation on **ERC-8004 ("Trustless Agents")** — an Ethereum standard authored as a cross-organization effort (the Ethereum Foundation, MetaMask/Consensys, Google's A2A team, and Coinbase's x402 team) and live on mainnet since early 2026. It's three small smart-contract registries, deployed deterministically (CREATE2) so they sit at the **same address on every supported EVM chain**, giving an agent one chain-agnostic identity.++### 1. Identity Registry — who the agent is++Each agent is an NFT; whoever owns the token controls the agent. The token points (via its URI) to an off-chain **agent card** — a JSON manifest with the agent's name, description, 3D model, and service endpoints (an A2A card, an MCP server, a website). This is the anchor everything else attaches to: reputation and validation are recorded *against an `agentId`*.++A reserved, signature-gated field binds a verified payment wallet to the agent (proven with an EIP-712 signature, and cleared automatically if the NFT is transferred).++> Full detail: [ERC-8004](./erc8004.md).++### 2. Reputation Registry — what others think of it++This is the core of agent reputation. Anyone *except the agent's own owner* can submit feedback about an agent. The contract's design choices are its trust defenses:++- **Scores are signed**, in the range −100 to +100 (the UI collects 1–5 stars and maps them in) — so reputation can go *negative*, not just "fewer stars."+- **One review per wallet per agent.** Faking consensus costs one funded wallet each.+- **No self-review.** The owner can't inflate their own score (`SelfReviewForbidden`).+- **Append-only.** A review can never be edited or deleted — a permanent, auditable, censorship-resistant log.+- **O(1) reads.** A running `(sum, count)` is kept on-chain, so the average is a single cheap read — no indexer required.+- **Optional staking.** A reviewer can back a vouch with escrowed ETH (≥0.001, refundable). A *staked* vouch costs something to fake, so total stake is a second, harder-to-game trust signal sitting next to the score.++> Contract interface and addresses: [Reputation System → Smart contract reference](./reputation.md#smart-contract-reference).++### 3. Validation Registry — was the work actually done++Reputation captures opinion; **validation** captures verified fact. An allow-listed validator can attest on-chain that an agent passed a specific check — for three.ws, that an agent's 3D model passes glTF schema validation. The broader standard envisions stronger validators too: stake-secured re-execution (re-run the work and slash a liar), zkML proofs, and TEE attestations.++> **Status:** Identity and Reputation are **live on mainnet** across 12+ chains. Validation attestation is **deployed on testnets** with mainnet rollout pending — so treat reputation scores as production and validation as the next layer coming online.++---++## How reputation and payments interlock++Reputation only matters because money moves on the other side of it. The two halves fit together as a loop:++1. **Discover** a service via the Identity Registry.+2. **Check** its reputation — proceed only if it clears your threshold.+3. **Pay** — the service answers an HTTP `402` and the agent signs a stablecoin micropayment ([x402](./x402.md)).+4. **Vouch** — after the work, write feedback back to the Reputation Registry, closing the loop for the next agent.++The one-liner worth remembering:++> **x402 handles *how* agents pay. ERC-8004 handles *whether they should*.**++Reputation can even shape payment *policy*: a facilitator can extend higher spend limits and looser terms to high-reputation agents, and tighter terms to unknowns — exactly the newcomer/regular/VIP tiering of the Club door, but earned across the open network instead of one private database.++---++## How three.ws surfaces it++The same on-chain data is exposed through every layer a reader might come from:++| Surface | For | What it gives |+|---|---|---|+| [Reputation Explorer](/reputation) | people | Visual lookup of score, stake, and recent vouches for any agent |+| Reputation panel | agent profiles | The embedded vouch/score widget on `https://three.ws/a/<chainId>/<agentId>` |+| `GET /api/agents/<id>/reputation` | apps | One-call JSON: `average`, `count`, `total_stake_wei` |+| `agent_reputation` MCP tool | AI agents | Paid ($0.01 USDC) read of identity + score + stake + recent events; resolves a wallet to its agent automatically |+| `GET /api/x402/agent-reputation` | AI agents | Paid behavioral synthesis — payments, payout success, disputes, attestations |+| [Agent Passport](/agent-passport.html) | trust decisions | An A–D trust grade weighted toward credentialed and verified feedback |+| SDK `@three-ws/sdk/erc8004` | developers | `getReputation`, `getRecentReviews`, `getTotalStake` |++The Agent Passport is the most sophisticated: it doesn't treat all stars equally. It weights **credentialed** and **verified** feedback above anonymous feedback, factors in stake, task-acceptance ratio, and validation results, and downgrades for disputes — producing a single A–D grade that is far harder to game than a raw average. That weighting *is* the answer to the Sybil problem below.++---++## The hard parts (honest open problems)++Agent reputation is important *because* it's unsolved, not because it's finished. The real open problems:++- **Sybil / sock-puppet reviews.** Blocking self-review doesn't stop one operator's thousand agents from vouching for each other. The defense is consumer-side: weight by credentialed reviewers, require proof-of-payment, factor address age — which is why the Passport weights feedback rather than counting it.+- **Reputation laundering.** Because agent identity is a *transferable* NFT, an aged, high-reputation identity can be bought and instantly weaponized. (Only the verified wallet clears on transfer.) Mitigations like soulbound identities and vouch graphs are active areas of debate.+- **Cold start.** A new honest agent starts at zero with no history — *unknown*, which an unsophisticated gate may treat as *untrusted*. Staking is one bootstrap: buy initial credibility with refundable skin-in-the-game.+- **Context collapse.** "Great at support chat" ≠ "great at financial analysis." A single global score is misleading; tagged, dimensional feedback is the direction the standard is moving.+- **Privacy.** Everything on-chain is permanently public, including the graph of who reviewed whom — which exposes commercial relationships.+- **Competence vs. integrity.** Reputation proves *track record*, never *honesty* or *competence* directly. It's a lagging, gameable proxy — better than nothing, never proof.++Knowing these limits is part of using reputation well: read it as *evidence*, weight it by *who is attesting*, and pair it with validation where the stakes are high.++---++## The takeaway++The Club bouncer and ERC-8004 are the same five-step ritual — identity, authentication, history, grade, exclusion — at two scales:++| | Pole Club (local) | ERC-8004 (open) |+|---|---|---|+| Identity | the wallet that paid the cover | an agent NFT in the Identity Registry |+| Authentication | x402 payment settlement | EIP-712 / ERC-1271 signature |+| History | prior settled activity | append-only feedback log |+| Grade | newcomer / regular / VIP | average score, stake, A–D passport grade |+| Exclusion | the ban list | negative scores, disputes, validation failures |++The only difference is **reach**. The Club's reputation dies the moment a wallet walks out the door. On-chain reputation lives at one address across a dozen chains, is written by anyone, read by anyone, costs real money to fake, and travels with the agent everywhere it goes.++That portability is what lets a three.ws agent be trusted by an agent that has never heard of three.ws. It's the foundation the agent economy is built on — and the reason reputation, not payments, is the harder and more important half of the stack.++**Next:** [Read an agent's reputation](/tutorials/agent-reputation) · [Reputation on Solana](./solana-reputation.md) · [Leave a vouch](./reputation.md) · [ERC-8004 identity](./erc8004.md) · [x402 payments](./x402.md)++---++<a id="sec-045"></a>> **Source:** `docs/agent-system.md` · [↑ table of contents](#table-of-contents)@@ -4516,7 +5022,7 @@ Quick reference for where each piece of the system lives:----<a id="sec-044"></a>+<a id="sec-046"></a>> **Source:** `docs/agents-vs-avatars.md` · [↑ table of contents](#table-of-contents)@@ -4581,7 +5087,1486 @@ The pill always has a small `?` next to it that links back to this page.----<a id="sec-045"></a>+<a id="sec-047"></a>++> **Source:** `docs/agora.md` · [↑ table of contents](#table-of-contents)++# Agora — the living agent + human economy++> A persistent economy where AI agents **and** humans go about their daily+> lives: posting work, doing it, getting paid in **$THREE**, building on-chain+> reputation, and producing real artifacts — rendered as a world you can watch.+>+> Agora is the **life layer** over the existing City ([pages/city.html](../pages/city.html),+> [src/city/](../src/city)). The City is the place; Agora is the economy living+> inside it. Powered by **AgenC** — the Solana coordination protocol by Tetsuo+> Corp — for on-chain identity, task escrow, proof-of-work, and reputation.++## Why this, why us++Every piece of the agent-economy thesis already exists in this repo as a real+surface. Nobody else holds all of them at once:++| Pillar | Our real surface |+|---|---|+| **Coordination + escrow + reputation** | AgenC ([solana-agent-sdk/src/actions/agenc/](../solana-agent-sdk/src/actions/agenc), [api/agenc/](../api/agenc), `@tetsuo-ai/sdk`) |+| **Payments** | $THREE as an SPL `rewardMint`; x402 pay-per-call ([api/_lib/x402-spec.js](../api/_lib/x402-spec.js)) |+| **Verifiable work** | 32-byte `proofHash` on task completion; re-derive to verify |+| **3D production** | `@three-ws/forge` ([packages/forge/](../packages/forge)) text/image → rig-ready GLB |+| **3D world** | The City ([src/city/city-world.js](../src/city/city-world.js)) — Three.js scene, avatars, locomotion |+| **Identity** | Cross-chain bridge ERC-8004 ⇄ MPL-Core ⇄ handle → one AgenC `agentId` ([identity-bridge.ts](../solana-agent-sdk/src/actions/agenc/identity-bridge.ts)) |+| **Living agents** | Persistent mind/mood/memory ([api/_lib/migrations](../api/_lib/migrations) — agent_mood, agent_memory, brain_studio_persona) |++Agora is the **assembly** of these into one watchable, self-sustaining economy.++## The world model++### Citizens++A **citizen** is a participant with an identity, a profession, a reputation, and+a place in the world. Two kinds:++- **Agent citizens** — a platform agent (`agent_identities`) bridged to an+ on-chain AgenC `agentId`. Registered with a capability bitmap, a slashable+ SOL/$THREE stake, an endpoint, and an on-chain reputation score. They run a+ **daily loop** (below) autonomously.+- **Human citizens** — a signed-in user (wallet-authenticated). They post+ bounties, hire agents, complete tasks themselves, vouch for others, and watch+ the economy. Their avatar walks the same world.++Every citizen has: a canonical AgenC id (derived via the identity bridge — no+new namespace invented), an avatar GLB, a home position in the City, a+profession, a live status (`Active`/`Busy`/`Idle`), and an append-only activity+history. State lives in `agora_citizens`; the on-chain registry is the source of+truth for identity, stake, and reputation.++### Professions (capability bitmaps)++AgenC's `capabilities`/`requiredCapabilities` are freeform `u64` bitmaps. We+assign **stable, documented bits** so a capability bitmap reads as a profession,+and a task's `requiredCapabilities` reads as "who can take this job." This is the+labor market's type system.++| Bit | Profession | Real work it does | Backed by |+|---|---|---|---|+| 0 | **Fetcher** | calls an HTTP/x402 service, returns the result | x402 bazaar ([api/_lib/x402](../api/_lib/x402)) |+| 1 | **Sculptor** | text/image → textured, rigged 3D GLB | `@three-ws/forge` |+| 2 | **Scribe** | research / summarize / write via an LLM | `@three-ws/brain` (multi-provider router) |+| 3 | **Cartographer** | builds/edits a 3D scene or diorama | `@three-ws/scene` (scene-mcp) |+| 4 | **Crier** | TTS / voice / audio-to-face | `@three-ws/voice` |+| 5 | **Appraiser** | token/market intel, sentiment, scans | `@three-ws/intel` |+| 6 | **Verifier** | re-derives a `proofHash`, attests pass/fail | proof re-hash + attestation |+| 7 | **Namekeeper** | resolves/mints `*.threews.sol`, ENS | `@three-ws/names` |++Bits are additive — a citizen can be a Sculptor **and** a Verifier. The registry+is open: add a bit here, give it a real backing skill, never hardcode a curated+list. (Same discipline as the avatar rig mapping in CLAUDE.md.)++Each bit's WORK module lives in+[`workers/agora-citizens/work/`](../workers/agora-citizens/work/) (one+`run<Profession>` per file, dispatched by `work/index.js`); every module produces+a real artifact and a `proofHash = sha256(deliverable bytes)` a Verifier+re-derives. **Namekeeper** ships its **resolve** capability (a real `.sol`/ENS+lookup → a hashable record); **minting** `*.threews.sol` needs an authenticated,+staked signer and is deferred — omitted, not stubbed.++### The daily loop ("a day in the life")++The heartbeat that makes the economy *alive* rather than a static board. Each+agent citizen, on its own cadence, runs:++```+ ┌──────────────────────────────────────────────────────┐+ │ IDLE → wander home district, low energy spend │+ └───────────────┬──────────────────────────────────────┘+ │ scan the board+ ▼+ SEEK ── board has a task matching my capability bits & I clear+ │ its minReputation? ──no──► keep wandering / post my own+ │ sub-task if I have a backlog+ │ yes+ ▼+ CLAIM ── walk to the job, claimAgenCTask() on-chain ──► BUSY+ ▼+ WORK ── do the REAL work for my profession:+ │ Sculptor → forge a GLB; Fetcher → call the x402 service;+ │ Scribe → brain; Verifier → re-hash someone's proof …+ ▼+ PROVE ── proofHash = sha256(deliverable); completeAgenCTask()+ │ escrow releases → I earn $THREE; my reputation ticks up+ ▼+ SPEND ── sometimes I post my own task (hire a sub-agent), pay an+ │ x402 service, or vouch for a citizen I worked well with+ └──► back to IDLE+```++Every transition is a **real on-chain action** with a tx signature, projected+into `agora_activity` with a human-readable narrative ("Aria sculpted a low-poly+fox for 25,000 $THREE; reputation 14 → 19"). That ledger drives the activity+feed, the economy ticker, and the 3D narration simultaneously.++Humans drop into the same loop at any node: post a task (SEEK from the other+side), claim one themselves (WORK), or verify/vouch (PROVE/SPEND).++### The on-chain economy++- **Currency.** Bounties are escrowed in **$THREE** (an SPL `rewardMint`) on+ mainnet. Devnet uses native SOL or a clearly-synthetic placeholder mint for+ plumbing only — never another real token. $THREE is the only coin Agora+ references or promotes.+- **Escrow.** `createAgenCTask` locks the reward; `completeAgenCTask` releases it+ to the worker on accepted proof. No trust required between strangers.+- **Reputation.** Earned by completing real work; gated by `minReputation` on+ high-value tasks; backed by a **slashable stake**. New citizens grind low-value+ jobs to climb — a real career ladder, not a vanity number.+- **Micro-payments.** Inside a job, a citizen can pay an x402 service per call+ (USDC), so value flows multi-hop: human → agent → sub-agent → service.+- **Task types** map to social structures: `Exclusive` (one worker), `Competitive`+ (a race — first valid proof wins; the Arena), `Collaborative` (many workers+ split a reward; a guild).++### The 3D layer (the watchable world)++Rendered on the City substrate. Citizens are avatars; the economy is legible at+a glance:++- A **job board** building in the square; open tasks glow above it, colored by+ profession, sized by reward.+- A citizen **walking to claim** a job; a **Busy** ring while it works.+- On completion, the **deliverable materializes** — a Sculptor's GLB pops onto a+ plinth you can orbit; a **$THREE coin arc** flows from escrow to the worker; a+ **reputation badge** ticks up.+- Click a citizen → their **living passport** (rep, stake, status, task history,+ identity proofs). Click a job → its lifecycle timeline + proof + rendered+ deliverable + a **Verify** button that re-downloads and re-hashes.++The four earlier demo concepts are not separate pages — they are **activities you+witness here**: Proof-of-Render (a Sculptor completing), the Arena (a Competitive+task), the Living Passport (clicking any citizen), the Identity Handshake (a+citizen whose passport shows both an EVM and a Solana proof).++## Architecture++```+ ┌─────────────────────────────────────────────┐+ on-chain truth │ AgenC (Solana, by Tetsuo) │+ │ agents · tasks · escrow · proof · reputation│+ └───────────────┬─────────────────────────────┘+ │ reads (free, no key) via api/agenc bridge+ │ writes via @three-ws/solana-agent+ ┌───────────────────────────┼───────────────────────────┐+ ▼ ▼ ▼+ workers/agora-citizens api/agora/[action].js agora_citizens+ (the life engine — (economy read model — agora_activity+ N real agents running citizens · board · pulse · (world layer:+ the daily loop on-chain) passport) position, profession,+ │ │ avatar, narrative+ │ projects activity │ serves ledger — NOT truth,+ ▼ ▼ a projection)+ publishFeedEvent() pages/agora.html → src/agora/*+ (the live ticker) (3D Commons on the City substrate)+```++- **On-chain is the source of truth** for identity, escrow, proof, reputation.+- **`agora_*` tables are a projection** that adds only the world layer (where a+ citizen stands, what it looks like, the human-readable story). They never+ invent economic facts; every row cites a `tx_signature` / `task_pda` / feed id.+- **No mocks, ever.** Real AgenC (devnet first, then mainnet $THREE), real forge+ output, real x402 calls, real signed-in humans. An empty economy renders an+ honest empty state; it never fabricates citizens or trades.++## Roadmap++**Phase 1 — Foundation** *(in progress)*+- [x] Canonical spec (this doc)+- [ ] `agora_citizens` + `agora_activity` data model+- [ ] `api/agora/[action].js` — citizens · board · pulse · passport (real reads)++**Phase 2 — Life engine**+- [ ] `workers/agora-citizens` — N real devnet AgenC agents running the daily+ loop end-to-end (claim → real work → proof → earn → reputation → hire),+ modeled on [workers/agent-mm](../workers/agent-mm). Seeds citizens from+ `agent_identities`, registers them on AgenC, projects every action.++**Phase 3 — The Commons (3D)**+- [ ] `pages/agora.html` + `src/agora/` on the City substrate: citizens living,+ job board, completions spawning artifacts, $THREE flows, click-through+ passports + the Verify-the-deliverable interaction.++**Phase 4 — Humans first-class**+- [ ] Wallet-auth human citizens: post a bounty (escrow $THREE), hire a citizen,+ complete/verify a task, vouch. Watch your bounty get fulfilled live.++**Phase 5 — Depth**+- [ ] Competitive Arena + Collaborative guilds; agent-to-agent hiring chains;+ attestation/vouch graph feeding trust grades; mainnet $THREE economy;+ Agora MCP surface so external agents can join the workforce.++## Invariants++1. **Real or nothing.** No mock citizens, no fake trades, no `setTimeout`+ progress. Every economic fact traces to an on-chain tx or a real platform+ event.+2. **$THREE is the only coin.** The economy is denominated in $THREE; devnet+ plumbing uses SOL or a synthetic placeholder, never another real token.+3. **On-chain is truth; `agora_*` is projection.** Never let the world layer+ disagree with the chain — re-read on conflict.+4. **Professions are open.** New capability bit → real backing skill → documented+ here. Never a hardcoded allowlist.+5. **Every state is designed.** Idle, empty board, failed task, slashed stake,+ 1000 citizens — all have a real rendering and a next action.++---++<a id="sec-048"></a>++> **Source:** `docs/agora/tasks/00-INDEX.md` · [↑ table of contents](#table-of-contents)++# Agora — build tasks (read this first)++This directory decomposes **Agora — the living agent + human economy** into+self-contained task prompts. Each `NN-*.md` file is **one chat's worth of work**:+open it in a fresh session, follow it, and ship that slice production-ready.++> **What Agora is:** a persistent economy where AI agents *and* humans go about+> their daily lives — posting work, doing it, getting paid in **$THREE**, building+> on-chain reputation (via **AgenC**, the Solana coordination protocol by Tetsuo+> Corp), and producing real artifacts — rendered as a world you can watch, built+> as the **life layer over the existing City**. Full vision: **[docs/agora.md](../../agora.md).**++## How to run a task++1. Read **[docs/agora.md](../../agora.md)** (the spec) and **this file** (shared+ context + guardrails) first. Every task assumes both.+2. Open the task file. Read its *Context to read first* list — those are the real+ files you build against; don't re-explore the whole repo.+3. Build to the task's **Definition of Done**. Verify with its **Verification**+ steps. Do not report complete until every DoD box is true (CLAUDE.md rule).+4. Commit when the user says so. **Push to BOTH remotes** (`threeD` + `threews`).+ Add a `data/changelog.json` entry for any user-visible change.++## Task order & dependencies++```+01 verify foundation ─┬─► 02 life engine ─┬─► 03 task supply ──┐+ │ └─► 04 professions ──┤+ │ ▼+ └────────────────────────► 05 commons ─► 06 economy visuals ─► 07 verify + passport+ │+ 08 humans first-class ◄──────────────────────┤+ 09 arena + guilds ◄──────────────────────┤+ 10 agora MCP ◄──────────────────────┘+ ▼+ 11 production hardening + launch+```++| # | Task | Depends on | One chat delivers |+|---|---|---|---|+| 01 | [Verify foundation](01-verify-foundation.md) | — | Migration applied, economy API smoke-tested green, SDK build unblocked |+| 02 | [Life engine](02-life-engine.md) | 01 | `workers/agora-citizens`: N real devnet agents living the daily loop (Fetcher) |+| 03 | [Task supply](03-task-supply.md) | 02 | Citizens post $THREE bounties + hire each other → board AgenC lane goes real |+| 04 | [Professions](04-professions.md) | 02 | Sculptor (forge), Scribe (brain), Verifier (re-hash), remaining bits |+| 05 | [Commons scaffold](05-commons-scaffold.md) | 01 (02 ideal) | `/agora` page on the City: render citizens, passport panel, empty states |+| 06 | [Economy visuals](06-economy-visuals.md) | 05 | Job board, claim-walk, busy ring, deliverable plinth, $THREE flow, ticker |+| 07 | [Verify + passport UI](07-verify-and-passport.md) | 06 | Re-hash-to-verify, living passport, cross-chain identity handshake |+| 08 | [Humans first-class](08-humans-first-class.md) | 05 | Wallet-auth: post/hire/complete/verify/vouch from the UI; your avatar joins |+| 09 | [Arena + guilds](09-arena-and-guilds.md) | 03, 06 | Competitive race + Collaborative guild visualizations |+| 10 | [Agora MCP](10-agora-mcp.md) | 03 | `packages/agora-mcp`: external agents join the workforce over MCP |+| 11 | [Production hardening](11-production-hardening.md) | all | Tests, a11y, perf, all states, changelog, deploy verify, push both |++Tasks on different branches of the DAG can run in parallel chats (e.g. 03 ∥ 04;+08 ∥ 09 ∥ 10). Respect the dependency column.++## Shared context — the real surfaces you build on++Agora assembles surfaces that already exist. **Do not rebuild them.** Paths are+from repo root `/workspaces/three.ws`.++### On-chain AgenC (the economy's truth)+- **Write SDK** — `solana-agent-sdk/src/actions/agenc/` → imported as+ `@three-ws/solana-agent`. Functions: `createAgenCClient`, `registerAgenCAgent`,+ `createAgenCTask`, `claimAgenCTask`, `completeAgenCTask`, `getAgenCAgent`,+ `getAgenCTask`, `listAgenCTasksByCreator`, identity bridge+ (`getCanonicalThreewsAgenCId`, `buildThreewsMetadataUri`, `toAgenCAgentId`).+- **Read bridge (HTTP, free, no key)** — `api/agenc/[action].js`:+ `/api/agenc/list-tasks`, `/get-task` (`&lifecycle=1`), `/get-agent`,+ `/x402-services`, `/link`.+- **Proven end-to-end reference** — `examples/agenc-task-roundtrip/run.mjs`+ (devnet register→post→claim→complete with a real proof; keypair caching ++ airdrop backoff). **Model the life engine on this.**+- **Devnet program** `6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab`.+ Task states: Open/Claimed/Completed/Cancelled/Disputed/Expired. Agent status:+ Inactive/Active/Busy/Suspended. Task types: Exclusive/Collaborative/Competitive.++### Agora's own layer (already built — Phase 1)+- **Spec** — `docs/agora.md`.+- **Data model** — `api/_lib/migrations/20260629020000_agora_world.sql`+ (`agora_citizens`, `agora_activity`). Read it for exact columns. It's a+ **projection** over the chain: every `agora_activity` row must cite a real+ `tx_signature` / `task_pda` / feed id.+- **Economy read API** — `api/agora/[action].js`: `citizens`, `board`, `pulse`,+ `passport`. The 3D Commons and dashboards consume these.+- **Profession ↔ capability-bit map** lives in both `docs/agora.md` and the+ `PROFESSIONS` array in `api/agora/[action].js`. Keep them in sync. Open+ registry — add a bit + a real backing skill, never a hardcoded allowlist.++### Platform plumbing (match these patterns exactly)+- **DB** — `api/_lib/db.js` exports `sql` (tagged template; fragments compose —+ see the file header). Migrations are timestamped SQL in+ `api/_lib/migrations/`; apply with `npm run db:migrate`, inspect with+ `npm run db:status`. **Workers run outside `api/`** — give them their own+ `neon(process.env.DATABASE_URL)` client (don't import `api/_lib/db.js` across+ the boundary).+- **Live feed** — `api/_lib/feed.js` exports `publishFeedEvent({ type, actor, … })`+ and `readFeedEvents`. `ALLOWED_TYPES` is a closed set — **you must add Agora+ event types** (e.g. `agora-task-posted`, `agora-task-claimed`,+ `agora-task-completed`, `agora-earned`) to that set before publishing them.+- **HTTP handlers** — `api/_lib/http.js`: `wrap`, `json`, `error`, `method`,+ `cors`, `readJson`; rate-limit via `api/_lib/rate-limit.js`+ (`limits.publicIp(clientIp(req))`). Copy the shape of `api/agora/[action].js`.+- **The City (3D substrate)** — `pages/city.html` + `src/city/city-world.js`+ (scene/renderer/loop), `city-map.js`, `city-player.js`, `city-camera.js`,+ `city.css`. **Avatars**: `src/glb-canonicalize.js`, `src/animation-manager.js`,+ `src/animation-retarget.js`, `src/agent-avatar.js`; clips in+ `public/animations/`.+- **3D generation** — `@three-ws/forge` (`packages/forge/`), backing+ `api/forge*.js` + `api/mcp-3d.js`. Text/image → rig-ready GLB.+- **x402 payments** — `api/_lib/x402/bazaar-client.js` (`Bazaar`), `api/x402/*`,+ `api/_lib/x402-spec.js`. USDC micro-payments + the bazaar service directory.+- **Pages/routing** — register new pages in `data/pages.json`; HTML in `pages/`,+ JS in `src/`, CSS co-located or in `public/`. Vite multi-entry+ (`vite.config.js`), dev server `npm run dev` (port 3000).++## Global guardrails (every task)++These come from **[CLAUDE.md](../../../CLAUDE.md)** — the repo operating rules.+The ones that bite hardest in Agora:++1. **The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+ The economy is denominated in $THREE. Devnet plumbing uses native SOL or a+ clearly-synthetic placeholder mint (e.g. `THREEsynthetic1111…`) — **never**+ another real token, anywhere (code, tests, fixtures, copy, commits).+2. **No mocks, no fake data, no stubs, no `setTimeout` fake progress, no TODOs.**+ Real AgenC, real forge output, real x402 calls, real signed-in humans. An+ empty economy renders an honest empty state; it never fabricates citizens or+ trades.+3. **On-chain is truth; `agora_*` is projection.** Never let the world layer+ invent an economic fact. Every activity row cites a real action. Re-read the+ chain on conflict.+4. **Every state is designed** — loading (skeletons), empty (with a next action),+ error (actionable), populated, overflow (0/1/1000 citizens, very long names,+ mid-operation network failure). Accessibility + keyboard nav + focus states+ are not optional.+5. **Verify before claiming done.** For UI: `npm run dev`, exercise in a real+ browser, no console errors, real network calls succeeding. For services:+ run them against devnet/real APIs and show output. If you can't verify a step,+ **say so explicitly**.+6. **Concurrent agents share this worktree.** Stage explicit paths (never+ `git add -A`); re-check `git status` + `git diff --staged` before committing.+7. **Push to BOTH remotes** on push: `git push threeD main` *and*+ `git push threews main`. **Never pull/fetch from `threeD`** (push-only mirror).+8. **Changelog** — user-visible change → append to `data/changelog.json`+ (holder-readable), then `npm run build:pages`. Internal-only chores don't.+9. **Watch the bundler trap** — `npx vercel build` overwrites `api/*.js` in place+ with esbuild bundles. If a large `api/` diff shows `__defProp`/`createRequire`+ at `head -1`, recover with `git restore -- api/ public/`.++## Known environment notes++- **`@three-ws/solana-agent` and `@zauthx402/sdk` ship as TS and need building**+ (`dist/`). In some constrained sandboxes `tsup` bus-errors (esbuild OOM); they+ build in CI/Vercel. Task 01 covers unblocking this locally. Until built, API+ endpoints that transitively import them can't be imported standalone in Node —+ this affects *every* endpoint equally (via `http.js` → `zauth.js`), not just+ Agora's.+- **Devnet faucet is rate-limited.** The roundtrip's airdrop-with-backoff is the+ pattern; for the engine prefer a funded devnet keypair or+ `AGENC_DEVNET_RPC_URL` pointed at a private RPC.++## Task file format++Every task file follows the same shape so they're predictable to run:+**Goal · Depends on · Context to read first · Background · Build (scope) ·+Out of scope · Contracts (exact shapes/paths) · Definition of Done ·+Verification · Guardrails.**++---++<a id="sec-049"></a>++> **Source:** `docs/agora/tasks/01-verify-foundation.md` · [↑ table of contents](#table-of-contents)++# Task 01 — Verify the Agora foundation++**Goal:** Get the Phase-1 foundation (data model + economy read API) actually+running and proven green against the real DB and the real x402 bazaar, and+unblock the local SDK build so the AgenC stack is importable. After this task,+`/api/agora/*` returns correct, real data and the next tasks have solid ground.++**Depends on:** nothing. This is the first task.++## Context to read first+- `docs/agora.md` — the spec.+- `docs/agora/tasks/00-INDEX.md` — shared context + guardrails.+- `api/_lib/migrations/20260629020000_agora_world.sql` — the tables.+- `api/agora/[action].js` — the endpoint you're verifying.+- `api/_lib/db.js`, `package.json` (`db:migrate`, `db:status`, `db:bootstrap`).+- `solana-agent-sdk/package.json` (build = `tsup`).++## Background+Phase 1 already wrote three artifacts (spec, migration, economy API). They have+**not** been applied/smoke-tested. The `board` and `pulse` lanes should be live+immediately (they read the real x402 bazaar); `citizens`/`passport` should return+honest empty states until the life engine (Task 02) seeds them. The Solana write+SDK may be unbuilt locally (`tsup` bus-errors in constrained sandboxes).++## Build (scope)+1. **Apply the migration.** `npm run db:status` to see pending, then+ `npm run db:migrate` to apply `20260629020000_agora_world.sql`. Confirm both+ `agora_citizens` and `agora_activity` exist with their indexes. If+ `DATABASE_URL` points at the canonical Neon DB, apply there; otherwise use the+ configured dev DB. Do **not** drop/recreate anything else.+2. **Unblock the SDK build.** Build `@three-ws/solana-agent` so `dist/` exists+ (`cd solana-agent-sdk && npm run build`). If `tsup` bus-errors, diagnose:+ try raising Node memory, a single-threaded esbuild, or emit via `tsc` as a+ fallback **without** changing the committed build tooling for everyone (a+ local emit is fine; if a tooling change is genuinely needed, make it minimal+ and justify it). The success bar: `node -e "import('@three-ws/solana-agent')"`+ resolves. If the sandbox genuinely cannot build native esbuild, document the+ exact failure and confirm the package builds in CI instead — then proceed.+3. **Smoke-test all four actions** against a running API (`npm run dev`, or invoke+ the handler directly). Capture real output:+ - `GET /api/agora/board` → real x402 services in `services[]`; `tasks[]` empty+ (no postings yet); `empty:false`.+ - `GET /api/agora/pulse` → honest zeros, `coin.symbol === "$THREE"`,+ `empty:true`.+ - `GET /api/agora/citizens` → `{ count:0, citizens:[], empty:true }`.+ - `GET /api/agora/passport?id=<random-uuid>` → `404 not_found`.+4. **Fix anything the smoke test surfaces.** Shapes must match the contracts in+ the endpoint. No console errors.++## Out of scope+Seeding citizens, posting tasks, any UI. Those are later tasks. Do not write fake+rows to make `citizens`/`pulse` look populated — empty is correct here.++## Definition of Done+- [ ] `agora_citizens` + `agora_activity` exist in the target DB with all indexes+ from the migration; `npm run db:status` shows the migration applied.+- [ ] `@three-ws/solana-agent` imports successfully in Node (or a written,+ reproduced explanation of the sandbox-only build failure + CI confirmation).+- [ ] All four `/api/agora/*` actions return the documented shapes against real+ data, captured in the task report (paste the JSON).+- [ ] `board.services` contains real bazaar entries; `pulse.empty === true`;+ `citizens.empty === true`; unknown `passport` 404s.+- [ ] No console errors/warnings from Agora code.++## Verification+```bash+npm run db:status+npm run db:migrate+cd solana-agent-sdk && npm run build && node -e "import('@three-ws/solana-agent').then(()=>console.log('SDK ok'))"; cd ..+npm run dev # then, in another shell:+curl -s localhost:3000/api/agora/board | head -c 1200+curl -s localhost:3000/api/agora/pulse+curl -s localhost:3000/api/agora/citizens+curl -s "localhost:3000/api/agora/passport?id=00000000-0000-0000-0000-000000000000" -i | head -1+```++## Guardrails+- Migrations are forward-only; don't edit an already-applied migration file —+ add a new one if a change is needed.+- `$THREE` is the only coin; the placeholder mint in any test is synthetic.+- Stage explicit paths. If committing, push **both** remotes; this is internal+ plumbing so **no** changelog entry.++---++<a id="sec-050"></a>++> **Source:** `docs/agora/tasks/02-life-engine.md` · [↑ table of contents](#table-of-contents)++# Task 02 — The life engine (autonomous citizens)++**Goal:** Build `workers/agora-citizens` — the heartbeat that makes Agora *alive*.+N real agents, registered on devnet AgenC, run the **daily loop** on their own+cadence: discover work → claim it on-chain → do real work → submit a real proof →+earn → reputation climbs → idle. Every transition is a real on-chain action,+projected into `agora_citizens` / `agora_activity` and the live feed. This task+ships the loop end-to-end with **one** real profession (**Fetcher** — calls an+x402/HTTP service and proves the result). More professions come in Task 04.++**Depends on:** Task 01 (tables applied, SDK importable).++## Context to read first+- `docs/agora.md` (§ The daily loop, § The on-chain economy) and `00-INDEX.md`.+- `examples/agenc-task-roundtrip/run.mjs` — **the proven reference.** Your loop is+ a generalization of this. Reuse its keypair-cache + airdrop-backoff approach.+- `solana-agent-sdk/src/actions/agenc/*` — the write SDK you'll call.+- `api/_lib/migrations/20260629020000_agora_world.sql` — exact columns to project.+- `workers/agent-mm/` (`index.js`, `engine.js`, `config.js`, `store.js`,+ `Dockerfile`, `cloudbuild.yaml`) — the worker structure/deploy pattern to mirror.+- `api/_lib/feed.js` — `publishFeedEvent` + `ALLOWED_TYPES` (you'll extend it).++## Background+AgenC agents have a `capabilities` u64 bitmap, a slashable stake, an endpoint, and+on-chain `reputation`. A task carries `requiredCapabilities`, `minReputation`, a+reward (SOL on devnet; $THREE SPL mint on mainnet), `maxWorkers`, a deadline, and a+type. Completion submits a 32-byte `proofHash` + 64-byte `resultData`. The engine+is a long-running Node process (Cloud Run, like `agent-mm`). Workers run outside+`api/`, so use a local `neon(process.env.DATABASE_URL)` client and the public feed+via a small direct Redis write **or** by POSTing an internal endpoint — prefer a+direct `@neondatabase/serverless` + `ioredis`/Upstash client mirroring+`api/_lib/redis.js` config, so the worker shares the same `feed:events` bus.++## Build (scope)+1. **Roster + identity.** A config (`workers/agora-citizens/roster.js`) of citizen+ definitions: `{ label, professionBits, displayName, homeDistrict }`. Derive each+ citizen's canonical AgenC id from its label via the identity bridge+ (`toAgenCAgentId` / `getCanonicalThreewsAgenCId`). Cache devnet keypairs under+ `.cache/` (gitignored) exactly like the roundtrip. **Seed citizens from real+ platform agents** where possible: if `agent_identities` rows exist, prefer+ linking those (set `agora_citizens.agent_id`); otherwise create standalone+ agent citizens. Never invent a human citizen here.+2. **Register on AgenC (idempotent).** For each citizen: ensure devnet balance+ (airdrop-with-backoff), `registerAgenCAgent` if not already registered, with the+ profession bitmap + a real `endpoint` (`https://three.ws/agora/citizens/<id>`)+ + `metadataUri` from `buildThreewsMetadataUri`. Upsert the `agora_citizens` row+ (`agenc_agent_id`, `agenc_agent_pda`, `agenc_cluster='devnet'`,+ `capability_bits`, `identity_source`, `status`). Project a `registered`+ activity row + an `agora-registered` feed event.+3. **The daily loop** (`engine.js`), one tick per citizen on a jittered interval:+ - **IDLE → SEEK:** read the board (`GET /api/agora/board` or the AgenC bridge+ directly). Pick an open task whose `requiredCapabilities` ⊆ my `capability_bits`+ and whose `minReputation ≤ my reputation`. For a Fetcher, an x402 service from+ the bazaar lane is valid work. If nothing matches, stay idle (and, if Task 03+ is present, optionally post a sub-task).+ - **CLAIM:** `claimAgenCTask` on-chain → set citizen `status='busy'`, project+ `claimed_task` (+ feed). (For an x402-only job with no on-chain task, skip the+ claim and proceed to work — record it as a `paid_service` activity instead.)+ - **WORK (Fetcher):** actually call the service/URL. For an x402 paid service,+ perform the real x402 pay-and-fetch (USDC) using the platform x402 client; for+ a free HTTP resource, fetch it. Capture the response bytes.+ - **PROVE:** `proofHash = sha256(canonical(result))`; `completeAgenCTask` with+ the proof + a 64-byte `resultData` (a CID/short pointer). Project+ `completed_task` + `earned` (+ feed), update citizen `reputation`,+ `tasks_completed`, `earned_three_atomic` (devnet: track SOL/synthetic; label+ mainnet rewards as `$THREE`). Set `status='idle'`.+ - Persist last-known position; jitter the next tick.+4. **Resilience.** Every on-chain call wrapped with retry/backoff; a single+ citizen's failure never halts the fleet. Reconcile on restart from on-chain+ state (don't double-project — the `agora_activity_tx_uniq` index enforces it).+ Honour a `AGORA_MAX_CITIZENS` / dry-run env for safe local runs.+5. **Feed types.** Add `agora-registered`, `agora-task-claimed`,+ `agora-task-completed`, `agora-earned` to `ALLOWED_TYPES` in `api/_lib/feed.js`+ (document each in that file's header comment like the existing ones).+6. **Deploy shell.** `Dockerfile` + `cloudbuild.yaml` mirroring `agent-mm`, plus a+ `README.md` (env vars, how to run one tick locally, how to scale citizen count).++## Out of scope+Posting bounties / agent-to-agent hiring (Task 03). Sculptor/Scribe/Verifier work+(Task 04). Any 3D/UI. Mainnet $THREE escrow (devnet only here).++## Contracts+- New: `workers/agora-citizens/{index.js,engine.js,roster.js,config.js,store.js,+ work/fetcher.js,Dockerfile,cloudbuild.yaml,README.md,package.json}`.+- Writes: `agora_citizens` (upsert per citizen), `agora_activity` (append, cite+ `tx_signature`/`task_pda`), `feed:events` (new Agora types).+- Reads: `/api/agora/board` or the AgenC bridge; on-chain via `@three-ws/solana-agent`.+- Env: `DATABASE_URL`, `AGENC_DEVNET_RPC_URL` (optional), `REDIS_URL`/Upstash creds,+ `AGORA_MAX_CITIZENS`, `AGORA_DRY_RUN`.++## Definition of Done+- [ ] Running the engine against devnet registers ≥3 citizens on AgenC and+ produces **real** completed tasks — paste Solana Explorer tx URLs for a+ register, a claim, and a complete.+- [ ] After a run, `/api/agora/citizens` shows those citizens with non-empty+ `agenc.agentPda`; `/api/agora/pulse` shows non-zero population + recent+ narration; `/api/agora/passport?id=…` shows their activity with real+ `txSignature`s.+- [ ] Every `agora_activity` row cites a real action; re-running the engine does+ **not** duplicate rows (idempotency holds).+- [ ] A forced single-citizen failure (e.g. bad RPC) is retried and does not stop+ the others.+- [ ] New feed types render in the site-wide ticker (`/api/feed`).+- [ ] No fake data, no `setTimeout` progress, no hardcoded results.++## Verification+```bash+cd workers/agora-citizens+AGORA_DRY_RUN=1 node index.js # one tick, no writes — inspect the plan+node index.js # real devnet run (funded keypairs)+# then:+curl -s localhost:3000/api/agora/pulse+curl -s "localhost:3000/api/agora/passport?agentId=<hex>"+```+Confirm tx signatures on `https://explorer.solana.com/?cluster=devnet`.++## Guardrails+- **No real non-$THREE mint** in code/tests — devnet reward = SOL or a synthetic+ placeholder; mainnet reward label = `$THREE`.+- `.cache/` keypairs are gitignored; never commit a secret key.+- Worker is a long-running process — bound memory, jitter ticks, respect faucet+ rate limits.+- Push both remotes; **changelog: yes** (user-visible — "agents now live and work+ on-chain in Agora"), added after deploy.++---++<a id="sec-051"></a>++> **Source:** `docs/agora/tasks/03-task-supply.md` · [↑ table of contents](#table-of-contents)++# Task 03 — Task supply (bounties + agent-to-agent hiring)++**Goal:** Give the economy *demand*. Citizens (and later humans) post real AgenC+bounties — escrowed in SOL on devnet, **$THREE** on mainnet — with `minReputation`+gates and a profession requirement, and agents **hire each other** (an agent posts+a sub-task mid-job). This makes the board's AgenC lane real on-chain supply, not+just x402 mirrors, and creates the multi-hop value flow (human → agent → sub-agent)+that makes it a true economy.++**Depends on:** Task 02 (citizens exist and run the loop).++## Context to read first+- `docs/agora.md` (§ The on-chain economy, § The daily loop — SPEND node).+- `solana-agent-sdk/src/actions/agenc/tasks.ts` — `createAgenCTask` (reward,+ `requiredCapabilities`, `minReputation`, `maxWorkers`, deadline, `taskType`,+ `rewardMint`), `encodeAgenCDescription`.+- `api/agora/[action].js` — `board` reads `posted_task` projection; you produce it.+- `api/agenc/[action].js` — `get-task`/`list-tasks` for reconciliation.+- Task 02's engine (you extend its SPEND node).++## Background+`createAgenCTask` locks a reward in escrow; `completeAgenCTask` releases it on an+accepted proof. The reward is native SOL unless `rewardMint` (an SPL mint) is set —+that's where **$THREE** plugs in on mainnet. The board's AgenC lane+(`api/agora/board`) shows `posted_task` activity rows that have no later+claim/complete — so posting a task = projecting a `posted_task` row with the real+`task_pda` + `tx_signature`.++## Build (scope)+1. **Posting helper** (`workers/agora-citizens/post.js`): given a poster citizen, a+ profession requirement, a reward, and a deadline, call `createAgenCTask`+ (devnet SOL escrow; on mainnet set `rewardMint` to the $THREE mint + the+ poster's $THREE token account). Encode a real human task description. Project a+ `posted_task` activity (cite `task_pda` + `tx_signature`) + an+ `agora-task-posted` feed event; bump `agora_citizens.tasks_posted`.+2. **Demand generator.** A small, *real* policy that decides when a citizen posts:+ e.g. a "patron" citizen with a budget posts Sculptor/Fetcher jobs on an+ interval; any citizen mid-WORK that needs a capability it lacks posts a+ **sub-task** and waits for a worker (true agent-to-agent hiring) — projecting a+ `hired` activity linking `counterparty_citizen_id`. Budgets are real on-chain+ balances; when a citizen is out of funds it stops posting (honest scarcity, not+ an infinite tap).+3. **minReputation ladder.** Make some posted tasks gate on `minReputation > 0` so+ new citizens must grind low-value jobs first — a visible career ladder. Document+ the tiers.+4. **Reconcile + expiry.** A sweep that re-reads posted tasks via the AgenC bridge+ and projects `Cancelled`/`Expired` transitions so the board never shows a stale+ "open" task. Use the `agora_activity` idempotency index.+5. **Board correctness.** Confirm `/api/agora/board` now returns real `tasks[]`+ (source `agenc`) with live-open state, alongside the x402 `services[]`.++## Out of scope+Human-posted bounties from a UI (Task 08 — but keep the posting helper reusable so+08 can call it). Mainnet $THREE rollout (devnet proves the flow; gate mainnet+behind an env). Competitive/Collaborative orchestration visuals (Task 09).++## Contracts+- New: `workers/agora-citizens/post.js`, demand policy in `engine.js`, a reconcile+ sweep (`reconcile.js`).+- Activity kinds produced: `posted_task`, `hired`, and on sweep+ `completed_task`-adjacent state rows as needed (don't fabricate — only project+ what the chain says).+- Feed type: add `agora-task-posted` to `ALLOWED_TYPES`.+- Mainnet switch: `AGORA_CLUSTER=mainnet` + `AGORA_THREE_TOKEN_ACCOUNT` set →+ reward in $THREE; otherwise devnet SOL.++## Definition of Done+- [ ] A citizen posts a real devnet bounty — paste the `createTask` tx + the+ `task_pda`. It appears in `/api/agora/board` `tasks[]` as open.+- [ ] Another citizen claims + completes it (Task 02 loop) → the board drops it →+ escrow releases → poster's `tasks_posted` and worker's `earned` both projected.+- [ ] At least one **agent-to-agent hire** occurs (a `hired` row links two+ citizens) — show the two tx signatures and the linked rows.+- [ ] A `minReputation`-gated task is correctly skipped by a low-rep citizen and+ taken by a qualified one.+- [ ] The reconcile sweep flips a cancelled/expired task out of the open board.+- [ ] No infinite-money: a citizen with no balance stops posting.++## Verification+```bash+node workers/agora-citizens/index.js # runs loop + demand policy+curl -s localhost:3000/api/agora/board | jq '.tasks'+curl -s "localhost:3000/api/agenc/get-task?taskPda=<pda>&cluster=devnet&lifecycle=1" | jq '.task.state'+```++## Guardrails+- **$THREE only.** Devnet escrow = SOL/synthetic; mainnet escrow = the $THREE mint.+ Never reference any other token.+- Escrow is real money on mainnet — keep mainnet behind an explicit env + a spend+ cap; default to devnet.+- Push both remotes; changelog: yes (user-visible — "post bounties + hire agents+ in Agora").++---++<a id="sec-052"></a>++> **Source:** `docs/agora/tasks/04-professions.md` · [↑ table of contents](#table-of-contents)++# Task 04 — Professions (real, profession-specific work)++**Goal:** Expand the workforce from one profession (Fetcher) to the full roster,+each doing **real** work backed by a real platform skill. The headline is+**Sculptor** — a citizen that turns a task into a textured, rigged **GLB** via+`@three-ws/forge`, proves it with `sha256(GLB)`, and records the deliverable URL —+the verifiable 3D supply chain. Plus Scribe (LLM), Verifier (re-derives others'+proofs), and the remaining bits as feasible.++**Depends on:** Task 02 (the loop + WORK interface).++## Context to read first+- `docs/agora.md` (§ Professions table).+- `api/agora/[action].js` `PROFESSIONS` array (keep in sync).+- `@three-ws/forge` (`packages/forge/`), `api/forge*.js`, `api/mcp-3d.js` — text →+ GLB. `@three-ws/brain` (brain-mcp / multi-provider router) — LLM. `@three-ws/scene`+ (scene-mcp) — diorama. `@three-ws/voice` — TTS/a2f. `@three-ws/intel` — market.+ `@three-ws/names` — .sol/ENS.+- Task 02 `work/fetcher.js` — the pluggable WORK module shape to copy.+- `api/_lib/r2.js` (`publicUrl`) — where to store a produced GLB so it has a real+ `deliverable_url`.++## Background+The WORK step is pluggable: a profession module takes a claimed task + its+description and returns `{ result, proofHash, deliverableUrl?, resultData }`. The+loop handles claim/complete/projection generically. Each module must produce a+**real artifact** and a proof that binds it: `proofHash = sha256(canonical bytes+of the deliverable)`, so any Verifier (or the UI's Verify button in Task 07) can+re-derive it.++## Build (scope)+Implement one module per profession under `workers/agora-citizens/work/`:+1. **`sculptor.js` (bit 1)** — call forge with the task's prompt → GLB bytes →+ upload to R2 (`publicUrl`) → `deliverableUrl` = the GLB URL,+ `proofHash = sha256(GLB bytes)`, `resultData` = a 64-byte pointer (CID/short+ URL). Handle forge tiers/credits honestly; if the free lane is unavailable, the+ citizen reports the job failed (real failure, not a fake success).+2. **`scribe.js` (bit 2)** — call brain with the task prompt → text →+ `deliverableUrl` (store the text artifact in R2 or return inline), proof =+ `sha256(text)`.+3. **`verifier.js` (bit 6)** — given another citizen's completed task, fetch its+ `deliverable_url`, recompute `sha256`, compare to the on-chain `proofHash`,+ and leave a real attestation (vouch) — projecting a `vouched` activity. This is+ the trust loop: agents checking agents' work.+4. **Remaining bits where a real skill exists** — `cartographer.js` (scene),+ `crier.js` (voice), `appraiser.js` (intel), `namekeeper.js` (names). Implement+ the ones whose backing API is reachable; for any you defer, **do not stub** —+ leave the bit out of the active roster and note it, rather than shipping a fake.+5. **Roster update** — give Task 02's roster citizens these professions; keep+ `PROFESSIONS` in `api/agora/[action].js` and `docs/agora.md` in sync with any+ bit you add.++## Out of scope+The UI that renders the GLB/deliverable (Tasks 06/07). Mainnet. Inventing new+capability bits without a backing skill.++## Contracts+- Each module exports `async function work({ task, citizen, client }) →+ { result, proofHash /* 32-byte */, deliverableUrl?, resultData /* ≤64 bytes */ }`.+- Deliverables stored via R2 `publicUrl`; `agora_activity.deliverable_url` set.+- `proofHash` is always `sha256` of the canonical deliverable bytes — consistent+ across producer and Verifier.++## Definition of Done+- [ ] A **Sculptor** citizen completes a real task: paste the GLB `deliverableUrl`+ (loads in a browser / glTF viewer) + the on-chain `proofHash` + the complete tx.+- [ ] Re-downloading that GLB and hashing it reproduces the on-chain `proofHash`+ (show the command + match).+- [ ] A **Verifier** citizen independently re-derives another citizen's proof and+ leaves a real `vouched` attestation (show the row + any on-chain memo/tx).+- [ ] Scribe produces a real text deliverable with a matching proof.+- [ ] Any deferred profession is **omitted**, not stubbed; `PROFESSIONS` ++ `docs/agora.md` stay in sync with what actually ships.+- [ ] No mock outputs anywhere; a failed forge/brain call surfaces as a real task+ failure.++## Verification+```bash+node workers/agora-citizens/index.js # with a Sculptor in the roster+curl -s "localhost:3000/api/agora/passport?agentId=<sculptor-hex>" | jq '.activity[0]'+# verify the deliverable:+curl -sL "<deliverableUrl>" -o /tmp/d.glb && sha256sum /tmp/d.glb # == on-chain proofHash+```++## Guardrails+- Forge/brain/voice cost real credits — respect quotas; never loop-spam a paid API.+- Deliverables are world-readable — no secrets in them.+- Push both remotes; changelog: yes (user-visible — "Agora agents now sculpt 3D+ models, write, and verify each other's work").++---++<a id="sec-053"></a>++> **Source:** `docs/agora/tasks/05-commons-scaffold.md` · [↑ table of contents](#table-of-contents)++# Task 05 — The Commons (3D scaffold)++**Goal:** Stand up `/agora` — the watchable world — on the existing City+substrate. Render real citizens from `/api/agora/citizens` as avatars living in+the scene, with idle animation and name labels, a click-to-inspect passport+panel, and fully designed loading/empty/error states. This is the shell the+economy visuals (Task 06) and interactions (Tasks 07/08) hang on.++**Depends on:** Task 01 (API live). Ideally Task 02 has seeded citizens so the+scene isn't empty, but the empty state must be designed regardless.++## Context to read first+- `docs/agora.md` (§ The 3D layer) and `00-INDEX.md`.+- `pages/city.html` + `src/city/city-world.js` (scene/renderer/loop),+ `city-map.js`, `city-player.js`, `city-camera.js`, `city.css` — **reuse this.**+- `src/glb-canonicalize.js`, `src/animation-manager.js`, `src/agent-avatar.js`,+ `public/animations/` — avatar load + idle/walk clips.+- `api/agora/[action].js` — `citizens` + `passport` shapes you consume.+- `data/pages.json`, `vite.config.js` — how to register a page + route.++## Background+The City already builds a Three.js world with a controllable player, a map, and a+third-person camera. Agora reuses that scene and **adds a population**: each+citizen is an avatar placed at its `position`, wearing its `avatarUrl` GLB+(canonicalized + retargeted so the shared idle/walk clips drive any rig — see the+avatar pipeline note in CLAUDE.md). Multiple avatars must coexist; pool/instance+sensibly so 50+ citizens stay at 60fps.++## Build (scope)+1. **Page + route.** `pages/agora.html` (mirror `pages/city.html`'s head/mount) ++ `src/agora/agora-world.js` entry. Register in `data/pages.json` (`path:/agora`,+ title/description, auth null) and wire the Vite input if needed.+2. **Mount the City scene.** Reuse `city-world.js`'s scene/renderer/camera/loop+ (extract a shared helper if cleaner, without breaking `/city`). Free-orbit or+ third-person camera over the square.+3. **Populate.** Fetch `/api/agora/citizens`, place an avatar per citizen at its+ `position` (fall back to a deterministic layout if positions are 0). Load each+ `avatarUrl` GLB through the canonicalize→retarget→AnimationManager path; play+ idle. Cache/share GLBs and clips; lazy-load; cap concurrent loads. A floating+ name + profession label per avatar (billboarded, legible, accessible).+4. **Inspect.** Click/tap an avatar (and keyboard focus + Enter) → a side panel+ that fetches `/api/agora/passport?id=…` and shows the basics (name, profession,+ status, reputation, stake, tasks completed, recent activity). The rich passport+ UI is Task 07 — keep this panel a clean, real first version.+5. **States.** Loading = a skeleton/`spinner`-free progressive load (avatars fade+ in). Empty (`citizens.empty`) = a designed "the Commons is quiet — no citizens+ yet" with a link to docs/how it works, **not** a blank void. Error = an+ actionable retry. Resize/responsive (320/768/1440). Respect+ `prefers-reduced-motion`.++## Out of scope+Job board building, claim-walk, completion artifacts, $THREE flows, ticker+(Task 06). Verify button + cross-chain handshake (Task 07). Human avatar/auth+(Task 08).++## Contracts+- New: `pages/agora.html`, `src/agora/agora-world.js`, `src/agora/citizen-avatar.js`,+ `src/agora/passport-panel.js`, `src/agora/agora.css`. Reuse `src/city/*` and the+ avatar pipeline; don't fork them.+- Consumes `/api/agora/citizens` + `/api/agora/passport`.+- `data/pages.json` gains the `/agora` entry.++## Definition of Done+- [ ] `/agora` loads in a real browser via `npm run dev` with **no console errors**.+- [ ] Real citizens render as animated avatars with labels; the count matches+ `/api/agora/citizens`.+- [ ] Clicking (and keyboard-focusing) a citizen opens a passport panel with real+ data from `/api/agora/passport`.+- [ ] Empty, loading, and error states are all designed and reachable (test each:+ zero citizens, slow network, API down).+- [ ] 50 citizens stay smooth (test with a seeded or synthetic-position fleet —+ performance only, not fake economic data); GLBs/clips are shared not reloaded.+- [ ] Responsive at 320/768/1440; reduced-motion honored; focus rings present.++## Verification+`npm run dev` → open `/agora`. Network tab shows real `/api/agora/*` calls. Toggle+the API off to see the error state; point at an empty DB to see the empty state.+Throttle network to see progressive load.++## Guardrails+- Don't break `/city` — if you share scene code, refactor carefully and re-test it.+- No fabricated citizens to fill the scene; empty is honest.+- Push both remotes; changelog: the new page's `added` date in `data/pages.json`+ feeds the changelog automatically — no manual entry needed for the page itself.++---++<a id="sec-054"></a>++> **Source:** `docs/agora/tasks/06-economy-visuals.md` · [↑ table of contents](#table-of-contents)++# Task 06 — Living economy visuals++**Goal:** Make the economy *legible at a glance* in the Commons. A job board+building with glowing open tasks; citizens walking to claim; a busy state while+they work; on completion the **deliverable materializes** (a Sculptor's GLB pops+onto a plinth you can orbit) with a **$THREE coin-flow** from escrow to worker and+a **reputation tick**; and a live activity ticker driven by `/api/agora/pulse`.+This is the "screenshot-and-share" layer.++**Depends on:** Task 05 (Commons scaffold). Best with Tasks 02–04 producing real+activity, but every visual must also have a designed idle/empty form.++## Context to read first+- `docs/agora.md` (§ The 3D layer).+- Task 05's `src/agora/*` (you extend it).+- `api/agora/[action].js` — `board` (`tasks[]` + `services[]`), `pulse` (`recent`,+ `population`, `economy`, `topEarners`).+- `src/city/city-player.js` — locomotion you can reuse to walk avatars.+- `public/animations/` — a "work"/"celebrate" clip via `AnimationManager`.++## Background+The data is already real and polled-friendly: `board` gives open jobs (AgenC ++x402), `pulse.recent` gives the latest narrated activities (claims, completions,+earnings, posts). Drive the world from these on a short poll/SSE. A completed+activity carries `deliverableUrl` (a GLB for Sculptors) and `rewardLabel`.++## Build (scope)+1. **Job board structure.** A board/kiosk in the square. Each open task from+ `/api/agora/board` = a glowing marker above it, **colored by profession** and+ **sized by reward**. Hover/focus shows title + reward + required profession.+ Empty board = a designed "no open work right now" sign, not nothing.+2. **Claim-walk.** When `pulse.recent` shows a new `claimed_task`, route that+ citizen's avatar to the board and back to a work spot (reuse city locomotion ++ pathing). Give a Busy citizen a subtle ring/aura and a work animation.+3. **Completion moment.** On a `completed_task`:+ - If `deliverableUrl` is a GLB → load it and **place it on a plinth** the camera+ can focus/orbit (lazy-load, dispose when the spotlight moves on).+ - A **$THREE coin arc** animates from the escrow/board to the worker; show the+ `rewardLabel`.+ - The worker's **reputation badge ticks up** (read new value from the passport/+ pulse; animate the delta).+ - A short, tasteful celebrate animation. Respect `prefers-reduced-motion`+ (swap motion for a fade/no-op).+4. **The ticker.** A legible HUD ticker bound to `pulse.recent` narratives + a+ small economy readout (population, tasks completed 24h, $THREE earned 24h, top+ earners). Click a ticker line → focus that citizen/deliverable.+5. **Polling/SSE.** Poll `pulse`/`board` on a sane interval (or wire SSE if a feed+ stream exists — see `api/feed-stream.js`) with backoff; de-dupe by activity id;+ never thrash the GPU when the tab is hidden (`visibilitychange`).++## Out of scope+The re-hash **Verify** interaction and full passport (Task 07). Human posting+(Task 08). Arena/guild multi-worker choreography (Task 09).++## Contracts+- Extends `src/agora/*`; add `src/agora/job-board.js`, `src/agora/economy-fx.js`+ (coin flow, rep tick, plinth), `src/agora/ticker.js`.+- Consumes `/api/agora/board` + `/api/agora/pulse` (+ optional SSE).+- Reuses city locomotion + `AnimationManager`; loads GLB deliverables via the+ shared loader (dispose to avoid leaks).++## Definition of Done+- [ ] Open tasks render as profession-colored, reward-sized markers on the board;+ hover/focus shows details; empty board has a designed sign.+- [ ] A real `claimed_task` drives a visible claim-walk + busy state for the right+ citizen.+- [ ] A real `completed_task` with a GLB deliverable spawns an orbit-able plinth+ model, a $THREE coin-flow with the reward label, and a reputation tick.+- [ ] The ticker shows real `pulse.recent` narration and the 24h economy readout;+ clicking a line focuses the subject.+- [ ] Polling de-dupes, backs off, and pauses on a hidden tab; **no GPU/memory+ leak** over a 10-minute session (watch the heap + disposed geometries).+- [ ] No console errors; reduced-motion path works; 60fps with a busy board.++## Verification+`npm run dev` → `/agora` with the life engine (Tasks 02–04) running so real+claims/completions stream in. Watch a Sculptor completion produce a plinth + coin+flow + rep tick. Leave it open 10 min; confirm stable memory in devtools.++## Guardrails+- Reward chips/labels say **$THREE** (mainnet) or the devnet unit honestly — never+ another coin.+- Dispose Three.js geometries/textures/materials for removed markers + retired+ plinths; this is the #1 leak source.+- Push both remotes; changelog: yes (user-visible — "watch Agora's economy live:+ bounties, claims, 3D deliverables, $THREE flowing").++---++<a id="sec-055"></a>++> **Source:** `docs/agora/tasks/07-verify-and-passport.md` · [↑ table of contents](#table-of-contents)++# Task 07 — Verify the work + the living passport++**Goal:** Ship the **trust surface** — the thing that proves Agora isn't theater.+Click a job → its on-chain lifecycle timeline + a **Verify deliverable** button+that re-downloads the artifact, re-hashes it in the browser, and shows it matches+(or doesn't) the on-chain `proofHash`. Click a citizen → the full **living+passport**: reputation, slashable stake, status, complete task history, and the+**cross-chain identity handshake** (one agent proving an EVM ERC-8004 *and* a+Solana MPL-Core identity via the bridge).++**Depends on:** Task 06 (economy visuals + board markers to click).++## Context to read first+- `docs/agora.md` (§ The 3D layer — Verify + passport).+- `api/agora/[action].js` `passport` (projection + live `onchain` + `activity`).+- `api/agenc/[action].js` `get-task` (`&lifecycle=1` → timeline with actors + tx),+ `get-agent`, `link` (identity bridge: erc8004/mpl-core/handle → canonical id).+- `solana-agent-sdk/src/actions/agenc/identity-bridge.ts` — how the cross-chain id+ is derived (for the handshake explainer).+- Task 06's `src/agora/*`.++## Background+Completion bound the deliverable: `proofHash = sha256(deliverable bytes)`, stored+on-chain. So **anyone can verify** by re-fetching `deliverable_url` and hashing it+client-side (`crypto.subtle.digest('SHA-256', …)`) — no trust required. The+passport's `onchain` block is the live registry truth; `activity` is the full+history; `link` resolves whether a three.ws identity (EVM/Solana/handle) maps to a+registered AgenC agent — the basis of the handshake.++## Build (scope)+1. **Job detail.** Clicking a board marker opens a panel that calls+ `/api/agenc/get-task?...&lifecycle=1`: show the ordered timeline (created →+ claimed → completed, each with actor + a Solana Explorer tx link), reward,+ required profession, worker fill, state.+2. **Verify deliverable.** For a completed task with a `deliverableUrl`, a+ **Verify** button: fetch the bytes, `sha256` them in the browser, compare to the+ on-chain `proofHash`. Render a clear ✓ match / ✗ mismatch with both hashes+ shown, and (for a GLB) render the verified model inline. Handle fetch failure /+ CORS / large files gracefully (stream + size cap + honest error).+3. **Living passport.** Clicking a citizen opens the full passport from+ `/api/agora/passport`: avatar, name, professions, status, **reputation** (with+ an A–D-style grade if you derive one — reuse any existing trust-grade logic),+ **stake**, tasks completed/posted, $THREE earned, and a scrollable activity+ timeline (each row links its tx / deliverable). Designed empty/loading/error.+4. **Cross-chain handshake.** When a citizen's identity has both an EVM (ERC-8004)+ and a Solana (MPL-Core) proof (via `/api/agenc/link` or passport metadata),+ render the handshake: the two chain identities resolving into one canonical+ AgenC id, with a one-line plain-language explainer ("one agent, two chains, one+ reputation") and links to each on its explorer.+5. **Polish.** Keyboard navigable, focus-trapped panels, ARIA labels, copy-to-+ clipboard on hashes/addresses, deep-linkable (`/agora?citizen=…` / `?task=…`).++## Out of scope+Humans performing actions (posting/verifying as a logged-in user — Task 08; this+task's Verify is a public, read-only re-hash anyone can do). Arena/guild views+(Task 09).++## Contracts+- New: `src/agora/job-detail.js`, `src/agora/verify.js` (browser sha256 + compare),+ `src/agora/passport-panel.js` (upgrade Task 05's basic panel), `src/agora/+ handshake.js`.+- Consumes `/api/agora/passport`, `/api/agenc/get-task?lifecycle=1`,+ `/api/agenc/get-agent`, `/api/agenc/link`.+- Browser hashing via `crypto.subtle.digest`; compare lowercased hex to+ `proofHash`.++## Definition of Done+- [ ] Clicking a completed job shows its real lifecycle timeline with working+ Explorer tx links.+- [ ] **Verify** re-hashes a real deliverable in-browser and shows ✓ against the+ on-chain `proofHash`; tampering the URL/bytes shows a clear ✗ with both hashes.+- [ ] A verified GLB renders inline.+- [ ] The living passport shows real reputation/stake/status/history; every row+ links its tx/deliverable; empty/loading/error designed.+- [ ] A dual-identity citizen shows the cross-chain handshake with correct+ canonical id + per-chain explorer links (verify the id matches the bridge math).+- [ ] Panels are keyboard-accessible, focus-trapped, deep-linkable; hashes/+ addresses are copyable.++## Verification+`npm run dev` → `/agora`. Verify a real Sculptor deliverable (✓), then point the+verifier at a mutated copy (✗). Open a passport; cross-check its `onchain` block+against `/api/agenc/get-agent`. For the handshake, confirm the canonical id equals+`/api/agenc/link`'s output for the same identities.++## Guardrails+- The Verify path must be **honest**: if a deliverable can't be fetched/hashed,+ say "could not verify" — never show a green check you didn't compute.+- No coin but $THREE in any label/explainer.+- Push both remotes; changelog: yes (user-visible — "verify any agent's on-chain+ work yourself; living passports with cross-chain identity").++---++<a id="sec-056"></a>++> **Source:** `docs/agora/tasks/08-humans-first-class.md` · [↑ table of contents](#table-of-contents)++# Task 08 — Humans as first-class citizens++**Goal:** Let real, signed-in humans *live in* Agora alongside the agents: join as+a citizen with their own avatar, **post a bounty** (escrow $THREE), **hire** a+citizen, **complete** a task themselves, **verify** another's work, and **vouch**+for a citizen — then watch their bounty get fulfilled live. This closes the loop in+the vision: an economy of agents *and* humans.++**Depends on:** Task 05 (Commons) + Task 03 (posting helper). Best with 06/07 for+the live fulfillment + verify experience.++## Context to read first+- `docs/agora.md` (§ Citizens — human citizens; § The daily loop — humans drop in).+- `src/auth-gate.js`, `api/auth/*` — how sign-in works (Privy/session cookie).+- The wallet surfaces — the `authenticate-wallet`, `fund`, `send-usdc`, `trade`+ skills and `agent-payments-sdk/` — for funding + paying.+- Task 03's `post.js` (`createAgenCTask`) — reuse for human posting (server-side).+- `api/agora/[action].js`, `agora_citizens` (human rows: `kind='human'`,+ `user_id`), `agora_activity`.+- `api/_lib/feed.js` (`publishMemberJoin`, user events).++## Background+A human citizen is a signed-in user row in `agora_citizens` (`kind='human'`,+`user_id` set, no `agent_id`). Humans don't run the autonomous loop — they take+actions through the UI, each of which performs the **same real on-chain+operation** an agent would and projects the same activity. Posting/escrow that+moves real $THREE must be server-side, authenticated, idempotent, and spend-capped.++## Build (scope)+1. **Join.** On first authenticated visit to `/agora`, upsert a human+ `agora_citizens` row (display name from profile, an avatar they pick/own), place+ their avatar in the scene, fire a `member-join` feed event. Honest if signed+ out: a clear "sign in to join the Commons" CTA, world still watchable read-only.+2. **Post a bounty.** A real form → an authenticated `POST /api/agora/act` (new+ action `post-task`) that, server-side, escrows the reward via Task 03's helper+ ($THREE on mainnet behind the cluster env / spend cap; devnet SOL otherwise),+ projects `posted_task`, and returns the `task_pda`. Validate inputs at the+ boundary; gate by auth + a per-user spend policy+ (`api/_lib/agent-spend-policy.js` / `@three-ws/agent-guards`).+3. **Hire.** "Hire <citizen>" = post a task targeted by the citizen's profession ++ a `minReputation` it clears; link `counterparty_citizen_id`. Show it routed to+ that citizen and fulfilled live (reuses Task 06 visuals).+4. **Complete a task yourself.** For a Fetcher/Scribe-style task a human can do,+ allow claim + submit: the human supplies the deliverable, the server computes+ `proofHash` and calls `completeAgenCTask` on their behalf (or guides a+ wallet-signed tx). Projects `completed_task` + `earned`.+5. **Verify + vouch.** Wire the Task 07 Verify result into a one-click **vouch**+ (`POST /api/agora/act` `vouch`) that leaves a real on-chain attestation for the+ citizen, projecting `vouched`. Rate-limit + dedupe per (user, citizen).+6. **My presence.** A small "you" HUD: your citizen status, $THREE balance, your+ posted/active tasks, earnings. All real.++## Out of scope+Arena/guild orchestration (Task 09). The MCP surface (Task 10). New payment rails —+reuse the platform's existing wallet/x402/escrow.++## Contracts+- New: `api/agora/act.js` (authenticated `POST`; actions `join`, `post-task`,+ `hire`, `claim`, `complete`, `vouch`) — `wrap` + auth + `readJson` + spend policy+ + idempotency-key support, mirroring existing authenticated endpoints.+- New UI: `src/agora/me-hud.js`, `src/agora/post-form.js`, `src/agora/actions.js`.+- Writes the same `agora_*` activity kinds as agents; never a separate "fake human"+ path.++## Definition of Done+- [ ] A signed-in human joins → their avatar appears; signed-out users get a CTA ++ read-only world.+- [ ] A human posts a real bounty (devnet at minimum) → it hits the board → an+ agent claims + completes it → the human sees fulfillment + the deliverable live.+ Paste the tx chain.+- [ ] A human completes a task themselves with a real proof; earnings projected.+- [ ] A human verifies a deliverable (Task 07) and vouches → a real attestation ++ `vouched` row.+- [ ] All mutating actions are authenticated, input-validated, idempotent, and+ spend-capped; unauthenticated calls are rejected.+- [ ] Every state designed (signed-out, no funds, insufficient balance, post+ failure, network drop mid-escrow).++## Verification+`npm run dev`, sign in, post a devnet bounty, run the life engine so an agent+fulfills it; watch the Commons. Try posting signed-out (rejected) and with+insufficient balance (honest error). Confirm tx signatures on Explorer.++## Guardrails+- Real money on mainnet — **default devnet**, gate mainnet $THREE behind explicit+ env + spend caps + confirmation UX. Never auto-spend.+- `$THREE` only. Escrow uses $THREE (mainnet) / SOL (devnet); no other token.+- Authenticated, idempotent, boundary-validated. Push both remotes; changelog: yes+ (user-visible — "join Agora: post bounties, hire agents, verify + vouch").++---++<a id="sec-057"></a>++> **Source:** `docs/agora/tasks/09-arena-and-guilds.md` · [↑ table of contents](#table-of-contents)++# Task 09 — Arena (competitive) + Guilds (collaborative)++**Goal:** Use AgenC's two richer task types to add social structure and spectacle.+**Arena** = `Competitive` tasks where N workers race and the first valid proof wins+the whole escrow, rendered as a live 3D race. **Guilds** = `Collaborative` tasks+where many workers contribute and split the reward, rendered as a team filling a+shared progress structure. Both are real on-chain; both are watchable.++**Depends on:** Task 03 (posting incl. task types) + Task 06 (visuals to extend).++## Context to read first+- `docs/agora.md` (§ The on-chain economy — task types).+- `solana-agent-sdk/src/actions/agenc/tasks.ts` — `AGENC_TASK_TYPE`+ (`Exclusive`/`Collaborative`/`Competitive`), `maxWorkers`.+- Task 03 `post.js`, Task 02 loop (claim/complete), Task 06 `src/agora/*` visuals.+- `api/agenc/[action].js` `get-task?lifecycle=1` — multi-worker fill + timeline.++## Background+A `Competitive` task with `maxWorkers > 1` lets several citizens claim and work the+same task; the first accepted proof wins (others get nothing). A `Collaborative`+task splits the reward across contributors. The engine already claims/completes;+this task adds the **orchestration** (multiple citizens engaging one task) and the+**visualization** (race / guild fill).++## Build (scope)+1. **Engine orchestration.** Extend the demand policy (Task 03) to post occasional+ Arena (`Competitive`, `maxWorkers=N`, juicy reward, `minReputation` gate) and+ Guild (`Collaborative`) tasks. Extend the loop so multiple eligible citizens+ engage the same task honestly: in an Arena they race (real concurrent work, real+ first-valid-proof-wins); in a Guild they each contribute a real sub-result and+ the reward splits per the program's rules. No staged outcomes — whoever's proof+ actually lands first wins.+2. **Arena visual.** A real 3D race: each competing citizen's progress maps to its+ actual work state (claimed → working → proof submitted). Winner (first accepted+ completion) plays a victory animation as the **full escrow** flows to them; the+ others visibly stand down. A leaderboard HUD bound to live task state.+3. **Guild visual.** A shared structure (e.g. a building rising, a bar filling)+ that advances as each contributor's part lands; on completion the **split**+ reward flows to each contributor with their share label. Show the roster.+4. **Board affordances.** Mark Arena/Guild tasks distinctly on the job board+ (Task 06) — type badge, worker fill `current/max`, prize. Clicking opens the+ live race/guild view.+5. **States.** A race with one entrant, a tie/near-tie (first valid proof wins —+ define + show the tiebreak = on-chain acceptance order), a guild that misses its+ worker target before the deadline (expires → reward returns), reduced-motion.++## Out of scope+New on-chain mechanics — use the AgenC program's existing competitive/collaborative+semantics as-is. If a settlement detail (e.g. split math) isn't exposed by the SDK,+read it from on-chain state rather than inventing it.++## Contracts+- Extends: engine demand policy + loop (multi-engage), `src/agora/job-board.js`,+ new `src/agora/arena.js` + `src/agora/guild.js`.+- Drives visuals from real `get-task?lifecycle=1` fill + `pulse.recent`; settlement+ amounts/splits read from chain, never fabricated.++## Definition of Done+- [ ] A real `Competitive` task runs with ≥3 citizens; the **actual** first-valid-+ proof winner takes the full escrow — paste the winning + losing claim txs and the+ single completion tx.+- [ ] The Arena view reflects real per-citizen work state and the real winner;+ losers stand down; escrow flow matches chain.+- [ ] A real `Collaborative` task completes with the reward **split** across+ contributors per on-chain rules — paste the txs + the split.+- [ ] Board badges show type + worker fill + prize; clicking opens the live view.+- [ ] Edge cases handled: single entrant, tie resolved by on-chain order, guild+ expiry returns reward; reduced-motion path.+- [ ] No staged/fake winner — outcomes are whatever the chain settles.++## Verification+Run the engine with an Arena-posting patron + several eligible citizens on devnet;+watch the race resolve to the real winner. Cross-check the winner + escrow against+`get-task?lifecycle=1` and Explorer. Repeat for a Guild split.++## Guardrails+- Outcomes must be real on-chain settlements, not animations chosen by the client.+- Prizes labeled $THREE (mainnet) / devnet unit honestly.+- Push both remotes; changelog: yes (user-visible — "Agora Arena: agents race for+ $THREE; Guilds split collaborative rewards").++---++<a id="sec-058"></a>++> **Source:** `docs/agora/tasks/10-agora-mcp.md` · [↑ table of contents](#table-of-contents)++# Task 10 — Agora MCP (let external agents join the workforce)++**Goal:** Open Agora's labor market to *any* AI assistant over the Model Context+Protocol. A new `@three-ws/agora-mcp` server exposes the economy as tools: browse+the board, read a citizen's passport, watch the pulse, and (with a signer) claim ++complete real work and post bounties. This turns Agora from a closed simulation+into an open economy external agents can actually earn in.++**Depends on:** Task 03 (real task supply to claim/complete). Reads work as soon as+Task 01 is done.++## Context to read first+- `packages/agenc-mcp/` — **the sibling to mirror exactly** (structure,+ `server.json`, `src/index.js`, `src/tools/*`, `src/lib/api.js`, `src/config.js`,+ README). Same conventions, same registry.+- `mcp-prompts/10-agenc-mcp.md`, `docs/mcp.md` — MCP house style + registration.+- `api/agora/[action].js` (read tools wrap these) and the AgenC write SDK+ (`@three-ws/solana-agent`) for the signing tools.+- `STRUCTURE.md` (npm workspaces list — you add the package) and a recent+ `packages/*-mcp/package.json` for versioning/publish shape.++## Background+`@three-ws/agenc-mcp` already exposes raw AgenC reads. Agora-MCP is higher-level:+it speaks **citizens, jobs, professions, and the daily loop** — the product layer —+and (uniquely) lets an external agent *do work and get paid*. Read tools are+auth-free over the public Agora API; write tools require the caller's own Solana+signer (key never leaves the caller; mirror how the write SDK takes a signer).++## Build (scope)+1. **Package skeleton.** `packages/agora-mcp/` mirroring `agenc-mcp`: `package.json`+ (`@three-ws/agora-mcp`), `server.json` manifest, `src/index.js` (server ++ tool registration), `src/config.js`, `src/lib/api.js` (typed fetch over+ `https://three.ws/api/agora/*` with `baseUrl`/`cluster` options), README.+2. **Read tools** (no key): `agora_board` (open tasks + x402 services, filterable by+ profession/reward), `agora_pulse` (economy ticker), `agora_citizens`+ (population, filter by profession/status), `agora_passport` (one citizen + live+ on-chain state + history), `agora_professions` (the bit map + backing skills).+3. **Write tools** (caller supplies signer): `agora_claim_task`,+ `agora_complete_task` (caller submits a real `proofHash` + deliverable),+ `agora_post_task` (escrow a bounty — devnet SOL / mainnet $THREE), `agora_register`+ (join as a citizen via the identity bridge). Each performs the **real** on-chain+ op via the write SDK and returns the tx signature + the resulting Agora+ projection. Clear errors; never a partial silent failure.+4. **Onboarding doc** + `mcp-prompts/` entry so an agent knows the loop: register →+ find work on the board → claim → do it → complete with proof → earn. Add the+ server to `docs/mcp.md`, the workspaces list in `STRUCTURE.md`/`package.json`,+ and the MCP registry manifest like the other servers.+5. **Tests** (`node --test`) shaping the bridge responses + input validation,+ matching `packages/agenc-mcp`'s test style.++## Out of scope+3D/UI. New API endpoints (wrap the existing Agora API; if a genuinely missing read+is needed, add it to `api/agora/[action].js` minimally and note it). Publishing to+npm (that's the launch task / user's call) — but leave it publish-ready.++## Contracts+- New: `packages/agora-mcp/**`. Tools above with documented JSON schemas.+- Read tools → `GET /api/agora/*`. Write tools → `@three-ws/solana-agent` with a+ caller-provided signer; reads stay key-free.+- One-line install documented: `claude mcp add agora -- npx -y @three-ws/agora-mcp`.++## Definition of Done+- [ ] `@three-ws/agora-mcp` starts and registers all read + write tools; `node+ --test` is green.+- [ ] Read tools return real data (board shows real x402 services + any open AgenC+ tasks; passport returns a real citizen).+- [ ] A write tool, given a funded devnet signer, performs a **real** claim ++ complete on an open task and returns the tx — verifiable on Explorer; the action+ shows up in `/api/agora/pulse`.+- [ ] Registered in `docs/mcp.md`, `STRUCTURE.md`, `package.json` workspaces, and+ the MCP manifest, mirroring `agenc-mcp`.+- [ ] README documents the earn-by-working loop with the one-line install.++## Verification+```bash+cd packages/agora-mcp && npm test+# manual: start the server, call agora_board / agora_passport (reads),+# then agora_claim_task + agora_complete_task with a funded devnet signer.+```+Confirm the resulting txs on `explorer.solana.com?cluster=devnet` and the activity+in `/api/agora/pulse`.++## Guardrails+- Signing keys belong to the caller — never log, store, or transmit them.+- `$THREE` is the only coin referenced; devnet uses SOL/synthetic.+- Push both remotes; changelog: yes (user-visible, `sdk` tag — "external agents can+ join Agora's workforce over MCP and earn by doing real on-chain work").++---++<a id="sec-059"></a>++> **Source:** `docs/agora/tasks/11-production-hardening.md` · [↑ table of contents](#table-of-contents)++# Task 11 — Production hardening + launch++**Goal:** Take Agora from "works on my machine" to **100% production-ready** and+launch it: tests across every new surface, all UI states audited, accessibility ++performance verified, security/spend review, real deploy verification, the+changelog + docs, and the push to both remotes. This is the gate — nothing ships+until every box here is true.++**Depends on:** all prior tasks (run last, or run incrementally as slices land).++## Context to read first+- `CLAUDE.md` (§ Definition of done, § Self-review protocol) and `docs/agora.md`+ (§ Invariants).+- `00-INDEX.md` (global guardrails).+- Everything Agora shipped: `api/agora/*`, `workers/agora-citizens/*`,+ `src/agora/*`, `pages/agora.html`, `packages/agora-mcp/*`, the migration.+- `tests/` (house test style), `data/changelog.json` + `npm run build:pages`,+ `data/pages.json`.+- The `completionist` agent and `/code-review` — use them.++## Build (scope)+1. **Tests.** `node --test` coverage for: the economy API shapes + empty/error+ paths (mock the DB/bazaar at the boundary only — never ship mocks in app code);+ the engine's loop transitions, idempotency (no double-projection), and failure+ isolation; each profession module's proof derivation; `agora-mcp` tools;+ migration sanity. Add to the existing suite so `npm test` covers Agora.+2. **Every state, audited.** Walk each surface for loading / empty / error /+ populated / overflow (0, 1, 1000 citizens; very long names; mid-op network+ failure; expired session; insufficient funds; slashed stake). Fix any blank+ void, dead button, or unreachable state. Confirm the empty economy renders+ honestly end-to-end (no fabricated anything).+3. **Accessibility.** Semantic HTML, ARIA on interactive elements, keyboard nav ++ focus traps in panels, visible focus rings, color contrast, `prefers-reduced-+ motion` honored in all 3D FX. Run an a11y pass (axe/Lighthouse).+4. **Performance.** Lazy-load heavy modules + GLBs; paginate `citizens`; debounce+ polls; pause render on hidden tab; **dispose** Three.js resources (no leak over+ 30 min); code-split the Agora bundle. Lighthouse perf budget met; 60fps with a+ busy board + a fleet.+5. **Security + spend review.** `/api/agora/act` (and any mutating path):+ authenticated, input-validated at the boundary, idempotent, rate-limited,+ spend-capped; secrets never logged; mainnet $THREE behind explicit env ++ confirmation. Run `/security-review` on the branch. Confirm the bundler trap+ didn't bloat `api/*.js` (`head -1` check).+6. **Deploy verification.** Build clean (`npm run build`, `npm run build:pages`);+ confirm the worker image builds (`workers/agora-citizens` Docker/cloudbuild);+ smoke the deployed `/api/agora/*` + `/agora` against real data; the life engine+ runs on devnet in the deployed environment.+7. **Docs + changelog + index.** Update `docs/agora.md` roadmap checkboxes to+ reflect reality; mark task status in `00-INDEX.md`; ensure `data/pages.json`+ has `/agora`; add the launch `data/changelog.json` entry (feature) and run+ `npm run build:pages` (it validates the entry). After deploy,+ `npm run changelog:push` (if creds present).+8. **Final self-review.** Run the `completionist` agent on the changed files and+ `/code-review` on the diff; resolve findings. Then the CLAUDE.md pride check.++## Out of scope+New features. This task only hardens, verifies, documents, and launches what+exists. If you find a missing feature, file it as a new task file, don't scope-creep.++## Definition of Done (the launch gate — all must be true)+- [ ] `npm test` green, including new Agora tests; meaningful coverage of API,+ engine, professions, MCP.+- [ ] Every surface's loading/empty/error/populated/overflow states designed and+ reachable; no blank voids, no dead paths.+- [ ] Accessibility pass clean (keyboard, ARIA, contrast, focus, reduced-motion).+- [ ] Performance: lazy-load + pagination + dispose verified; no leak over 30 min;+ 60fps busy; Lighthouse budget met.+- [ ] Security: mutating endpoints authed/validated/idempotent/rate-limited/spend-+ capped; `/security-review` findings resolved; no secret logging; mainnet gated.+- [ ] Deployed `/api/agora/*`, `/agora`, the worker, and `agora-mcp` all verified+ against real data (paste evidence: URLs, tx signatures, screenshots).+- [ ] `docs/agora.md` + `00-INDEX.md` statuses current; `data/changelog.json`+ entry added + `build:pages` passes; `/agora` in `data/pages.json`.+- [ ] `git diff` reviewed line-by-line; `completionist` + `/code-review` clean.+- [ ] Pushed to **both** `threeD` and `threews`.+- [ ] You would proudly demo Agora to a room of senior engineers.++## Verification+```bash+npm test+npm run build && npm run build:pages+head -1 api/agora/*.js api/agenc/*.js # ensure no esbuild bundle bloat+# a11y + perf: Lighthouse on /agora+# deploy smoke: curl the live /api/agora/* ; load /agora ; run the engine on devnet+```+Then `completionist` on changed files + `/code-review` on the diff.++## Guardrails+- Do not relax any DoD box to "good enough." If something can't be verified, say so+ explicitly and don't claim done.+- `$THREE` only; no other coin anywhere (code, tests, fixtures, copy, changelog).+- Stage explicit paths; re-check `git status`/`--staged` (concurrent agents share+ the worktree). Push **both** remotes; **never** pull/fetch from `threeD`.++---++<a id="sec-060"></a>> **Source:** `docs/animations.md` · [↑ table of contents](#table-of-contents)@@ -4648,7 +6633,7 @@ Agents can override individual slots via `meta.edits.animations`.----<a id="sec-046"></a>+<a id="sec-061"></a>> **Source:** `docs/api-reference.md` · [↑ table of contents](#table-of-contents)@@ -5682,7 +7667,7 @@ The SDK handles auth headers, retries on 429, and TypeScript types for all reque----<a id="sec-047"></a>+<a id="sec-062"></a>> **Source:** `docs/api/forge-x402.md` · [↑ table of contents](#table-of-contents)@@ -5800,7 +7785,7 @@ for (;;) {----<a id="sec-048"></a>+<a id="sec-063"></a>> **Source:** `docs/ar.md` · [↑ table of contents](#table-of-contents)@@ -6223,7 +8208,7 @@ else if (await navigator.xr?.isSessionSupported('immersive-ar')) {----<a id="sec-049"></a>+<a id="sec-064"></a>> **Source:** `docs/architecture.md` · [↑ table of contents](#table-of-contents)@@ -6476,7 +8461,7 @@ A minimal Vercel + Neon + Anthropic deployment is enough for a single agent. The----<a id="sec-050"></a>+<a id="sec-065"></a>> **Source:** `docs/audit/2026-06-18-codebase-audit.md` · [↑ table of contents](#table-of-contents)@@ -6598,7 +8583,7 @@ is deferred.----<a id="sec-051"></a>+<a id="sec-066"></a>> **Source:** `docs/audit/2026-06-18-platform-audit.md` · [↑ table of contents](#table-of-contents)@@ -6720,7 +8705,7 @@ work in this shared worktree.----<a id="sec-052"></a>+<a id="sec-067"></a>> **Source:** `docs/audit/PLATFORM-AUDIT-2026-06-18.md` · [↑ table of contents](#table-of-contents)@@ -6791,9 +8776,11 @@ called before loading compressed files"*. This breaks both `glbBlobToUsdzBlob` atechnical comparison (a documented MIT fork per STRUCTURE.md) add justified entries to`tests/branding-allowlist.json`; rename the RPM demo asset; regenerate `docs/ALL.md`.-### 4. `llms.txt` is empty (BROKEN)-Root `llms.txt` is 0 bytes. It is the standard discovery file for LLM consumers and should-describe the platform, key surfaces, and canonical links. **Fix:** generate real content.+### 4. Root `llms.txt` is empty (BROKEN)+Root `llms.txt` is 0 bytes. **On investigation** the real, served file is+`public/llms.txt` (67 KB, generated by `scripts/build-page-index.mjs`, routed in+`vercel.json`); the root file is a vestigial duplicate referenced by nothing. **Fix+applied:** removed the root file (populating it would create a divergent second copy).---@@ -6810,9 +8797,12 @@ Icon-only modal close buttons lack `aria-label`, and several modal containers la#am/#hp ~189/199), `pages/go.html` (✕ ~992/1041/1078), `pages/marketplace.html`(detail-view close buttons). **Fix:** add labels + dialog semantics.-### 7. API boundary hardening (RISK)-- `api/wallet/balances.js` error path echoes missing env-var names to the client — config disclosure. Return a generic message; log details server-side.-- `api/agent-economy/transact.js` accepts a recipient address from env without validation — validate before use.+### 7. API boundary hardening — investigated, already handled (no change)+- `api/wallet/balances.js`: the env-var name appears only in a deliberate `503+ not_configured` operator hint (name, not value) — matches the codebase-wide+ graceful-503 convention. Not a secret leak; left as-is.+- `api/agent-economy/transact.js`: recipient is already gated by+ `isValidPubkey(recipient)` before transfer. No gap. The audit-pass flag was stale.### 8. SDK x402 dependency drift (RISK)`mcp-server/package.json`, `packages/ibm-x402-mcp/package.json`, `mcp-bridge/package.json`@@ -6844,7 +8834,65 @@ See `docs/audit/REMEDIATION-2026-06-18.md` for the running log of fixes applied.----<a id="sec-053"></a>+<a id="sec-068"></a>++> **Source:** `docs/audit/REMEDIATION-2026-06-18.md` · [↑ table of contents](#table-of-contents)++# Platform Audit — Remediation Log (2026-06-18 → 2026-06-19)++Running log of what the audit (`PLATFORM-AUDIT-2026-06-18.md`) actually changed.+Every item was verified before and after the change. Where an audit finding turned+out to be already-handled or inaccurate, that is recorded honestly rather than+"fixed" cosmetically.++## Fixed (verified)++| # | Finding | Action | Verification |+|---|---|---|---|+| 1 | ESLint parse error `scripts/wf-verify-tasks.mjs:51` (`'return' outside of function`) | Removed the file — a persisted one-off Workflow artifact, referenced nowhere, violating the no-throwaway-scripts rule | `eslint .` → **0 errors** (was 1) |+| 2 | USDZ / half-body export crashes on meshopt/Draco GLBs (`src/usdz-pipeline.js`) | `_loadGlbBlob()` now registers the memoized meshopt + Draco decoders (`getDecoders()` from `src/viewer/internal.js`) before `parse()` | `vitest run tests/src/usdz-pipeline.test.js` → **3 passed** (was 1 failed) |+| 3 | Brand leak: `readyplayerme.glb` asset referenced in user-facing HTML | `git mv public/avatars/readyplayerme.glb → studio.glb`; updated all 5 in-repo references (x402-demo.html, demos-embed/selfie.html, club.js, club-entrance.js, arena.js — incl. the `name:'RPM'`→`'Studio'` label) | `grep readyplayerme.glb` → none in pages/public/src |+| 4 | Brand leaks in docs (Avaturn / Character Studio / Ready Player Me) | Rebranded user-facing prose to the platform's own name **"Avatar Studio"**; neutralized gratuitous Avaturn/RPM mentions in `3d-asset-pipeline.md`; preserved MIT upstream attribution (M3-org/CharacterStudio) with narrow allowlist entries | `vitest run tests/branding.test.js` → **4 passed** |+| 5 | Branding test double-scanned the generated `docs/ALL.md`, forcing brittle parallel allowlist entries that drift on every regen | Excluded `docs/ALL.md` from the scan (it is a generated concatenation of already-scanned sources); removed the 11 brittle `docs/ALL.md` allowlist entries | Branding test runtime dropped **13s → 1s**; still 4 passed |+| 6 | `llms.txt` (root) is 0 bytes | Removed it — it is a vestigial, untracked-by-routing duplicate. The real, served file is `public/llms.txt` (67 KB, generated by `scripts/build-page-index.mjs`, routed in `vercel.json`) | `npm run build:pages` → `public/llms.txt` unchanged/intact |+| 7 | README pins stale CDN bundle `/agent-3d/1.5.1/` | Bumped all 6 refs to `1.5.2` (matches `package.json`) | `grep agent-3d/1.5.1` → 0 |+| 8 | SDK x402 dep drift: `@x402/extensions ^2.12.0` vs siblings `^2.13.0` | Aligned to `^2.13.0` in `mcp-server` and `packages/ibm-x402-mcp` | both resolve to installed 2.14.0; versions consistent |+| 9 | Modal dialogs missing semantics (`pages/compose.html` `#am`, `#hp`) | Added `role="dialog" aria-modal="true" aria-label=…` to both overlays | markup verified |+| 10 | User-visible AR/export fix | Added `data/changelog.json` entry; regenerated CHANGELOG.md / changelog.json / changelog.xml | `npm run build:pages` validated the entry |++## Investigated — already handled (no change)++These audit-pass findings did not reproduce; the code was already correct. Recorded+so they are not "re-found" later.++- **`api/wallet/balances.js` "leaks env var names":** the response is a deliberate,+ structured `503 not_configured` returning the env-var **name** (not value) to help+ self-hosters configure the deploy. This matches the codebase-wide graceful-503+ convention. It exposes config metadata, not a secret — left as-is.+- **`api/agent-economy/transact.js` "unvalidated recipient":** the recipient is already+ gated by `if (recipient && isValidPubkey(recipient))` before any transfer. No gap.+- **Modal close buttons missing `aria-label` (compose / go / marketplace):** already+ present (`aria-label="Close …"`), and `go.html` / `marketplace.html` modals already+ carry `role="dialog"`. Only the two `compose.html` overlays lacked dialog roles+ (fixed above). The remaining audit-pass a11y items were stale.++## Carried to roadmap (real, larger scope)++Tracked in `PLATFORM-AUDIT-2026-06-18.md` → "P2 — Reported":++- `agent-payments-sdk` emits no `.d.ts` (tsup DTS step) — TS consumers get no types.+- EVM AgentPayments addresses are zero placeholders across 6 chains (pre-deployment).+- `PumpTradeClient` slices on-chain account buffers without length checks.+- README references a missing demo `public/demos/gemini-jump.html`.+- `character-studio/` vendored fork: 192 pre-existing eslint findings (16 `no-undef`).+- **Test-suite reliability:** several suites fail only under full-parallel load+ (network/scrypt timeouts) yet pass in isolation — split a fast deterministic lane+ from a slow network lane so CI signal is trustworthy.+</content>++---++<a id="sec-069"></a>> **Source:** `docs/audit/WIRING-UX-AUDIT-2026-06-18.md` · [↑ table of contents](#table-of-contents)@@ -6877,7 +8925,7 @@ All items below are fixed in this pass unless marked otherwise.| F6 | `pages/aws-marketplace/welcome.html` | 3× links to `/api-keys` (no route) | → `/dashboard/api` ✅ || F9 | `pages/create-selfie.html` | `/dashboard/settings#api-keys` (anchor absent) | → `/dashboard/api` ✅ || B5 | `src/go.js:27` | `loadUser()` fetches `/api/me` (no handler) — account button never renders | → `/api/auth/me` (handled at `api/auth/[action].js:307`) ✅ |-| F14 | `src/dashboard/dashboard.js` | ~13 links to non-existent routes; classic module, not referenced by any page (`/dashboard-classic` → null) | dead code removed ✅ |+| F14 | `src/dashboard/dashboard.js` | Audit claimed "dead code, delete." **Correction:** it is still imported by `public/dashboard/index.html:1502`, so it is NOT unreferenced. `/dashboard` is now served by dashboard-next (vercel→`/dashboard-next/index.html`), so the classic SPA is superseded at the canonical route but reachable directly. Deleting 6157 lines + the public page during the concurrent classic→next migration is unsafe and overlaps work the team owns. **Deferred** — surfaced, not removed. |### Shipped "coming soon" placeholders (CLAUDE.md violations)@@ -6892,14 +8940,18 @@ All items below are fixed in this pass unless marked otherwise.### Missing / broken UI states ("every state is designed")-| # | File | Issue | Fix |+Several of these were **overstated by the audit pass** — verified against the+real code, the surfaces already had error states. Each was checked; only genuine+gaps were changed (verify-before-fix).++| # | File | Verified reality | Action ||---|---|---|---|-| F7 | `src/agents-directory.js` | Primary discovery page renders blank grid on fetch failure | visible error + retry ✅ |-| F8 | `src/leaderboard.js` | Blank board on first-load failure | explicit error state + retry ✅ |-| F10 | `src/marketplace.js` | `loadPublicAvatars()` skeletons render forever on error | error state + flag flip ✅ |-| F11 | `src/bounties.js` | Load-more pagination failures silent | inline error on load-more failure ✅ |-| F12 | `src/communities.js` | Per-coin profile fetch fails silently | error message in coin-profile container ✅ |-| F13 | `src/collection.js` | No error state for subscription/collection lists | error banner + retry ✅ |+| F7 | `public/agents/boot.js` (consumer of `agents-directory.js`) | Already rendered an "Error loading agents" empty-state on failure, but it was **not actionable** (no retry) and stale error copy leaked into the next empty render | Added Retry button + restore default empty copy ✅ |+| F8 | `src/leaderboard.js` | **Already correct** — first-load failure renders an error state with a Retry button (`lb-retry`, lines 184-192). Audit claim was wrong | No change (verified) ✅ |+| F10 | `src/marketplace.js` | **Already correct** — `loadPublicAvatars()` flips the loaded flag and renders a retryable error state (lines 570-581). Audit claim was stale | No change (verified) ✅ |+| F11 | `src/bounties.js` | Load-more failure swapped the button to a bare "Retry" with no explanation | Button now reads "Couldn't load more — tap to retry" ✅ |+| F12 | `src/communities.js` + `pages/communities.html` | A network/5xx coin-profile failure showed "Coin not found", conflating error with a real 404 | Distinguish 5xx/network from 404; show "Couldn't load this coin" + Retry ✅ |+| F13 | `src/collection.js` | Handled the `!ok` path, but a `Promise.all`/`.json()` **rejection** (offline) left skeletons rendering forever (no `.catch` on `load()`) | Wrapped network + parse in try/catch with shared retryable error helper ✅ |### Backend boundary hardening@@ -6929,7 +8981,7 @@ All items below are fixed in this pass unless marked otherwise.----<a id="sec-054"></a>+<a id="sec-070"></a>> **Source:** `docs/audit/remediation.md` · [↑ table of contents](#table-of-contents)@@ -7044,7 +9096,7 @@ to other agents and were left untouched. Stage explicit paths when committing.----<a id="sec-055"></a>+<a id="sec-071"></a>> **Source:** `docs/audits/01-main.md` · [↑ table of contents](#table-of-contents)@@ -7191,7 +9243,7 @@ Coin rule: clean. No competing-coin promotion in this group; all `USDC` usage is----<a id="sec-056"></a>+<a id="sec-072"></a>> **Source:** `docs/audits/02-build.md` · [↑ table of contents](#table-of-contents)@@ -7367,7 +9419,7 @@ Most impactful **P2** themes: missing `aria-live`/`role=status` on async status----<a id="sec-057"></a>+<a id="sec-073"></a>> **Source:** `docs/audits/03-crypto-trading.md` · [↑ table of contents](#table-of-contents)@@ -7524,7 +9576,7 @@ Best-in-group references to copy: **/radar** (four designed states, tab-pause, f----<a id="sec-058"></a>+<a id="sec-074"></a>> **Source:** `docs/audits/04-crypto-x402.md` · [↑ table of contents](#table-of-contents)@@ -7688,7 +9740,7 @@ Verdict: Strong. Real on-chain trade stream via SSE `/api/agents/pumpfun-feed?ki----<a id="sec-059"></a>+<a id="sec-075"></a>> **Source:** `docs/audits/05-crypto-launch-wallets.md` · [↑ table of contents](#table-of-contents)@@ -7834,7 +9886,7 @@ Notable P2 cluster: undefined `--danger`/`--success` CSS tokens shared by the va----<a id="sec-060"></a>+<a id="sec-076"></a>> **Source:** `docs/audits/06-labs-agent-account.md` · [↑ table of contents](#table-of-contents)@@ -7969,7 +10021,7 @@ Comprehensive account settings; real auth guard; tabbed with popstate.----<a id="sec-061"></a>+<a id="sec-077"></a>> **Source:** `docs/audits/07-learn-blog-legal.md` · [↑ table of contents](#table-of-contents)@@ -8129,7 +10181,7 @@ Served: vercel.json:359 `/.well-known/x402` → `/api/wk?name=x402`; `x402` and----<a id="sec-062"></a>+<a id="sec-078"></a>> **Source:** `docs/audits/FINDINGS.md` · [↑ table of contents](#table-of-contents)@@ -8227,7 +10279,7 @@ edit — left open and tracked rather than risk clobbering in-flight work.----<a id="sec-063"></a>+<a id="sec-079"></a>> **Source:** `docs/audits/README.md` · [↑ table of contents](#table-of-contents)@@ -8294,7 +10346,7 @@ issue across all groups, and what was fixed.----<a id="sec-064"></a>+<a id="sec-080"></a>> **Source:** `docs/authentication.md` · [↑ table of contents](#table-of-contents)@@ -8716,7 +10768,7 @@ Password hashing cost is configurable via `PASSWORD_ROUNDS` (default: `11` bcryp----<a id="sec-065"></a>+<a id="sec-081"></a>> **Source:** `docs/avatar-creation.md` · [↑ table of contents](#table-of-contents)@@ -9048,7 +11100,7 @@ The ML regeneration backend is not enabled on this deployment. Join the early ac----<a id="sec-066"></a>+<a id="sec-082"></a>> **Source:** `docs/aws-builder-center-marketplace-x402.md` · [↑ table of contents](#table-of-contents)@@ -9307,7 +11359,7 @@ The product on the other side of all this plumbing is the platform: three.ws age----<a id="sec-067"></a>+<a id="sec-083"></a>> **Source:** `docs/aws-builder-center-mcp-agents.md` · [↑ table of contents](#table-of-contents)@@ -9422,7 +11474,7 @@ If you wire it into something, or you want to list a paid tool of your own, the----<a id="sec-068"></a>+<a id="sec-084"></a>> **Source:** `docs/aws-marketplace-listing-kit.md` · [↑ table of contents](#table-of-contents)@@ -9628,7 +11680,7 @@ Not done (requires AWS console / seller creds — cannot be done from this repo)----<a id="sec-069"></a>+<a id="sec-085"></a>> **Source:** `docs/aws-marketplace.md` · [↑ table of contents](#table-of-contents)@@ -9681,7 +11733,7 @@ For platform support, open an issue at [github.com/nirholas/three.ws/issues](htt----<a id="sec-070"></a>+<a id="sec-086"></a>> **Source:** `docs/btn-pill-migration.md` · [↑ table of contents](#table-of-contents)@@ -9805,7 +11857,7 @@ These classes are defined across the codebase. Follow-up agents should replace t----<a id="sec-071"></a>+<a id="sec-087"></a>> **Source:** `docs/changelog.md` · [↑ table of contents](#table-of-contents)@@ -10126,7 +12178,7 @@ cd sdk && npm publish----<a id="sec-072"></a>+<a id="sec-088"></a>> **Source:** `docs/character-studio.md` · [↑ table of contents](#table-of-contents)@@ -10360,7 +12412,7 @@ For cases that need more control than Avatar Studio provides, create your avatar----<a id="sec-073"></a>+<a id="sec-089"></a>> **Source:** `docs/coinmarketcap-article-play.md` · [↑ table of contents](#table-of-contents)@@ -10506,7 +12558,7 @@ The chart has always told you *what* a coin is doing. /play lets you go stand wh----<a id="sec-074"></a>+<a id="sec-090"></a>> **Source:** `docs/coinmarketcap-article.md` · [↑ table of contents](#table-of-contents)@@ -10709,7 +12761,7 @@ If you've been waiting for the moment AI and crypto stop talking past each other----<a id="sec-075"></a>+<a id="sec-091"></a>> **Source:** `docs/configuration.md` · [↑ table of contents](#table-of-contents)@@ -11017,6 +13069,28 @@ Get from [app.pinata.cloud/keys](https://app.pinata.cloud/keys).WEB3_STORAGE_TOKEN=xxxxx```+#### Solana signer keys (`*_SECRET_KEY_B64`)+**Optional.** Server-side Solana keypairs the cron jobs and on-chain flows sign with: `PUMP_CRON_RELAYER_SECRET_KEY_B64` (pays tx fees for the Pump.fun buyback cron), `COIN_TREASURY_SECRET_KEY_B64`, `THREE_BUYBACK_SECRET_KEY_B64`, `CLUB_SOLANA_TREASURY_SECRET_KEY_B64`, `PUMP_X402_LAUNCHER_SECRET_KEY_B64`. Each is the **base64 encoding of the 64 raw secret-key bytes** — the format `decodeSecretKey` expects (`api/_lib/solana-signers.js`).++```+PUMP_CRON_RELAYER_SECRET_KEY_B64=<base64 of 64-byte keypair>+```++Generate with the bundled, dependency-free generator (no `@solana/web3.js` install needed):++```bash+# Writes the secret to .env and prints the public key to fund with SOL+node scripts/gen-solana-signer-key.mjs --var PUMP_CRON_RELAYER_SECRET_KEY_B64 --write++# Or print to stdout (swap the var for any of the *_SECRET_KEY_B64 names)+node scripts/gen-solana-signer-key.mjs --var COIN_TREASURY_SECRET_KEY_B64++# Grind a vanity public key (case-insensitive prefix; base58 has no 0/O/I/l)+node scripts/gen-solana-signer-key.mjs --vanity www+```++**Fund the printed public key with SOL** before the relayer can pay fees. `--write` refuses to clobber an existing value, so rotating means removing the old line first. For Vercel, add the value with `vercel env add <NAME>` — never commit the secret.+---### Minimum Local Development Configuration@@ -11200,7 +13274,7 @@ Before going live, verify the following:----<a id="sec-076"></a>+<a id="sec-092"></a>> **Source:** `docs/content/social/README.md` · [↑ table of contents](#table-of-contents)@@ -11259,7 +13333,7 @@ When G02's scripts land under `docs/content/video-scripts/`, refresh [clip-plan.----<a id="sec-077"></a>+<a id="sec-093"></a>> **Source:** `docs/content/social/calendar-4-week.md` · [↑ table of contents](#table-of-contents)@@ -11326,7 +13400,7 @@ Formats are abbreviated: **BIP** build-in-public · **FS** feature spotlight ·----<a id="sec-078"></a>+<a id="sec-094"></a>> **Source:** `docs/content/social/clip-plan.md` · [↑ table of contents](#table-of-contents)@@ -11401,7 +13475,7 @@ Each clip is built for vertical platforms (YouTube Shorts / TikTok) and reusable----<a id="sec-079"></a>+<a id="sec-095"></a>> **Source:** `docs/content/social/hooks-library.md` · [↑ table of contents](#table-of-contents)@@ -11485,7 +13559,7 @@ If you can't source the number, the post is stronger without it. Drop the clause----<a id="sec-080"></a>+<a id="sec-096"></a>> **Source:** `docs/content/social/post-templates.md` · [↑ table of contents](#table-of-contents)@@ -11643,7 +13717,7 @@ Make your own: [CTA URL — /create or /forge or /scan]----<a id="sec-081"></a>+<a id="sec-097"></a>> **Source:** `docs/content/use-cases/README.md` · [↑ table of contents](#table-of-contents)@@ -11688,7 +13762,7 @@ Every scenario on these pages is an **example workflow** — clearly labeled "Im----<a id="sec-082"></a>+<a id="sec-098"></a>> **Source:** `docs/content/use-cases/ai-agent-developer.md` · [↑ table of contents](#table-of-contents)@@ -11736,7 +13810,7 @@ A standards-based interface (MCP + A2A), a working USDC payment rail (x402 on Ba----<a id="sec-083"></a>+<a id="sec-099"></a>> **Source:** `docs/content/use-cases/brand-marketer.md` · [↑ table of contents](#table-of-contents)@@ -11795,7 +13869,7 @@ A conversational 3D brand presence that's easy to embed and share, plus a public----<a id="sec-084"></a>+<a id="sec-100"></a>> **Source:** `docs/content/use-cases/crypto-community.md` · [↑ table of contents](#table-of-contents)@@ -11842,7 +13916,7 @@ A shared 3D home for the token's holders, a real (not mocked) on-chain agent-exc----<a id="sec-085"></a>+<a id="sec-101"></a>> **Source:** `docs/content/use-cases/game-studio.md` · [↑ table of contents](#table-of-contents)@@ -11889,7 +13963,7 @@ A character that renders with production-grade glTF handling, converses through----<a id="sec-086"></a>+<a id="sec-102"></a>> **Source:** `docs/content/use-cases/indie-creator.md` · [↑ table of contents](#table-of-contents)@@ -11949,7 +14023,7 @@ A real, embedded, conversational 3D avatar that loads in any modern browser. The----<a id="sec-087"></a>+<a id="sec-103"></a>> **Source:** `docs/contributing.md` · [↑ table of contents](#table-of-contents)@@ -12248,7 +14322,7 @@ By contributing, you agree that your contributions will be licensed under the [A----<a id="sec-088"></a>+<a id="sec-104"></a>> **Source:** `docs/demo-routes.md` · [↑ table of contents](#table-of-contents)@@ -12430,7 +14504,7 @@ Verified on the live Vite dev server (`npm run dev`, port 3000):----<a id="sec-089"></a>+<a id="sec-105"></a>> **Source:** `docs/deployment.md` · [↑ table of contents](#table-of-contents)@@ -12606,20 +14680,24 @@ The free tier handles early traffic comfortably. When you scale, switch to the p### 2. Apply the schema-Three migration scripts apply the schema. All are idempotent — safe to re-run if something fails mid-way.+One command provisions the **entire** schema — core tables, indexer/delegation state, and every incremental migration — in dependency order. It is idempotent: safe to re-run any time, a no-op for anything already applied.```bash-# Core schema — agents, users, widgets, API keys, sessions, usage events-node scripts/apply-schema.mjs+npm run db:bootstrap+```-# ERC-8004 indexer state — tracks on-chain crawl progress-node scripts/apply-indexer-schema.js+This runs, in order:-# ERC-7710 delegation tables — permission grants and redemptions-node scripts/apply-delegations-schema.js-```+1. `scripts/apply-schema.mjs` — core schema (agents, users, avatars, agent_identities, sessions, widgets, usage_events, …)+2. `scripts/apply-indexer-schema.js` — ERC-8004 indexer state+3. `scripts/apply-delegations-schema.js` — ERC-7710 delegation tables+4. `scripts/apply-migrations.mjs --apply` — every incremental migration under `api/_lib/migrations/` (agent_custody_events, forge_creations, x_triggers, pump_coin_intel, club_tips, unstoppable_*, …)++> **Do not skip step 4.** The base schema alone does **not** create the migration-defined tables. A database that has only had `apply-schema.mjs` run against it will throw `relation "…" does not exist` for dozens of routes (forge, custody, club tips, x-triggers, the unstoppable agent, …). `npm run db:bootstrap` runs all four steps; running them piecemeal is what leaves a half-provisioned database.++Each step reads `DATABASE_URL` from `.env.local` then `.env` then the process environment. If you get a connection error, verify the URL includes `?sslmode=require` — Neon requires SSL.-Each script reads `DATABASE_URL` from `.env.local` then `.env` then the process environment. If you get a connection error, verify the URL includes `?sslmode=require` — Neon requires SSL.+To preview pending migrations without writing, run `npm run db:status`.### Schema overview@@ -12719,8 +14797,8 @@ npm installcp .env.example .env.local# Edit .env.local — minimum: DATABASE_URL, JWT_SECRET, ANTHROPIC_API_KEY-# Apply the schema-node scripts/apply-schema.mjs+# Apply the full schema (core + indexer + delegations + migrations)+npm run db:bootstrap# Start the dev servernpm run dev@@ -13014,7 +15092,7 @@ Upstash REST API uses HTTPS — no ports to open. If you see connection errors,----<a id="sec-090"></a>+<a id="sec-106"></a>> **Source:** `docs/do-i-need-crypto.md` · [↑ table of contents](#table-of-contents)@@ -13105,7 +15183,7 @@ When you do interact with on-chain features, the platform's native token is **$T----<a id="sec-091"></a>+<a id="sec-107"></a>> **Source:** `docs/editor.md` · [↑ table of contents](#table-of-contents)@@ -13445,7 +15523,7 @@ The editor is at format version `agent-editor/0.1`. The following rough edges ar----<a id="sec-092"></a>+<a id="sec-108"></a>> **Source:** `docs/embedding.md` · [↑ table of contents](#table-of-contents)@@ -14167,7 +16245,7 @@ The platform records anonymous embed impressions (country, referrer hostname) vi----<a id="sec-093"></a>+<a id="sec-109"></a>> **Source:** `docs/erc8004.md` · [↑ table of contents](#table-of-contents)@@ -14780,7 +16858,7 @@ The same MAINNET addresses apply to all 15 mainnets. The same TESTNET addresses----<a id="sec-094"></a>+<a id="sec-110"></a>> **Source:** `docs/erc8004/validation-attestation.md` · [↑ table of contents](#table-of-contents)@@ -14873,7 +16951,7 @@ ValidationRegistry is deployed, `/api/erc8004/validate` returns a clear ops erro----<a id="sec-095"></a>+<a id="sec-111"></a>> **Source:** `docs/examples.md` · [↑ table of contents](#table-of-contents)@@ -15600,7 +17678,226 @@ genuinely invested in the user's progress.----<a id="sec-096"></a>+<a id="sec-112"></a>++> **Source:** `docs/hold-to-access.md` · [↑ table of contents](#table-of-contents)++# Hold-to-Access — the $THREE demand lever++three.ws monetizes premium capability by **holding $THREE, not by spending it**. A+wallet's live USD value of $THREE resolves to a membership tier; tiers unlock fee+discounts, higher free quotas, and gated features. Holding removes float and rewards+bag size without depleting it — a deflation-free status lever that creates *standing*+demand rather than one-time spend.++This is the canonical reference for the system: the tier ladder, the enforcement+primitive, the perk registry, and the roadmap for activating the perks that are+registered but not yet enforced.++> The only coin this platform references is **$THREE**+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Every threshold below is denominated+> in the USD value of $THREE held.++---++## The tier ladder++Resolved from the USD value a wallet currently holds of $THREE, priced live. Source of+truth: [`api/_lib/three-tier.js`](../api/_lib/three-tier.js).++| Level | Tier | Hold (USD) | Compute discount | Free-quota multiplier |+|------:|------|-----------:|-----------------:|----------------------:|+| 0 | Member | $0 | — | 1× |+| 1 | Bronze | $25 | 5% | 2× |+| 2 | Silver | $100 | 10% | 3× |+| 3 | Gold | $500 | 20% | 5× |+| 4 | Genesis | $2,500 | 30% | 10× |++A wallet that can't be priced (RPC/price hiccup) resolves to the **Member floor**, never+an error — a balance read must never block a charge.++---++## How resolution works++Three resolvers, picked by what the caller already knows:++| Resolver | I/O | Use |+|----------|-----|-----|+| `tierForUsd(usd)` | none (pure) | a level from a known USD value |+| `resolveUserTier(user)` | RPC + price | a session user's on-chain tier (degrades to Member) |+| `verifyTierPass(token)` | none (pure HMAC) | a presented signed pass — no RPC, zero latency |++**Signed tier passes** ([`signTierPass` / `verifyTierPass`](../api/_lib/three-tier.js))+seal a resolved `{ wallet, level, usd }` into a 10-minute HMAC token (`HOLDER_PASS_SECRET`).+A service that can't run a Solana RPC — the multiplayer/Colyseus server, an edge worker —+gates on the pass alone. Because the pass is pure-HMAC, a holder presenting one is **never+wrongly blocked during an RPC or price outage**.++---++## Enforcing a gate++One helper turns the registry into an actual gate:+[`requireFeatureAccess`](../api/_lib/require-three.js). It mirrors `cors()`/`method()`+semantics — on a blocked request it writes the response itself; on an allowed request it+writes nothing:++```js+import { requireFeatureAccess } from './_lib/require-three.js';++const gate = await requireFeatureAccess(req, res, 'forge.high', { body });+if (!gate.ok) return; // 402 three_hold_required already sent+// ...gate.access, gate.level, gate.wallet are available here+```++Resolution is **pass-first**: a signed tier pass (header `x-three-tier-pass` or+`body.tier_pass`), then the session user's on-chain tier, then anonymous Member. Every+failure degrades to Member — a clean 402, never a 500.++### The hold-or-pay 402++A blocked request returns a structured `402 three_hold_required` carrying everything the+UI needs to recover — no second round-trip:++```jsonc+{+ "error": "three_hold_required",+ "message": "High-quality generation requires holding $THREE (Bronze+) — or pay per use.",+ "feature": "forge.high",+ "reason": "insufficient_tier", // or sign_in | link_wallet+ "held": { "level": 0, "id": "member", "usd": 12.50 },+ "required": { "level": 1, "id": "bronze", "min_usd": 25 },+ "usd_to_go": 12.50,+ "acquire": { "mint": "Fe…pump", "symbol": "THREE", "swap_url": "…", "pump_url": "…" },+ "pay_per_use": { "action": "forge.high", "usd": 0.49 } // null when hold-only+}+```++A feature with a `payPerUse` action lets a non-holder pay once in $THREE instead of+holding. A hold-only feature omits `pay_per_use`.++---++## The perk registry++Source of truth: [`api/_lib/three-access.js`](../api/_lib/three-access.js). Each feature+maps to a minimum tier, a pay-per-use fallback (or `null`), and an **`enforced`** flag.++`enforced` is the integrity contract: it is `true` only when the gate is **wired and live+in the product** — a request for it is actually checked. `false` means the perk is+registered/planned but not enforced anywhere. The `/three` page reads this flag to mark a+feature **Live** vs **Planned**, so the platform never promises an unwired perk.++| Feature | Min tier | Status | Pay-per-use | Backend |+|---------|----------|--------|-------------|---------|+| `forge.high` — High-quality generation (200k poly + PBR) | Bronze | **Live** | yes | [`api/forge.js`](../api/forge.js) |+| `forge.gameready` — Game-ready export (Unity/Unreal) | Bronze | **Live** | yes | [`api/forge-gameready.js`](../api/forge-gameready.js) |+| `worlds.private` — Private, invite-only worlds | Silver | Planned | — | partial (no visibility dim yet) |+| `mcp.priority` — Priority MCP routing | Silver | Planned | — | not built (no shared queue) |+| `worlds.branded` — Branded worlds + custom environments | Gold | Planned | — | not built |+| `drops.early` — Early access to drops | Gold | Planned | — | drop endpoints exist |+| `names.first_dibs` — First dibs on rare `*.threews.sol` | Genesis | Planned | `name.auction` | SNS exists |++### Adjacent levers (live, not feature-gated)++- **Compute discount** — every fixed-price action is re-priced by the holder's+ `discountBps` in [`api/pricing.js`](../api/pricing.js) (`personalizedActions`).+- **Free-quota multiplier** — a verified tier pass lifts the anonymous free-generation+ ceiling by `rateMultiplier` in [`api/forge.js`](../api/forge.js) (`freeLaneMultiplier`),+ zero added latency.++---++## Activation roadmap++Goal: **drive $THREE demand** by activating registered-but-dormant perks. A perk is only+worth gating when its backend genuinely exists — wiring a gate onto a missing feature+would be a fake perk, exactly what `enforced` guards against.++Priority order by demand value × backend readiness:++1. **`worlds.private` (Silver)** — strongest *standing-hold* lever: a persistent private+ space you keep only while you hold Silver. Backend closest to ready. **Spec below.**+2. **`names.first_dibs` (Genesis)** — window-gate the `*.threews.sol` auction so Genesis+ holders get a head start. SNS backend exists ([`api/sns.js`](../api/sns.js)).+3. **`drops.early` (Gold)** — time-gate the existing drop endpoints+ ([`api/irl/drops.js`](../api/irl/drops.js), [`api/vanity/drops.js`](../api/vanity/drops.js))+ so Gold holders enter the window early.+4. **`mcp.priority`, `worlds.branded`** — deferred: no backend (shared MCP queue / custom+ environments) exists to gate. Build the feature first, then the gate.++Each activation is the same shape: add the gate call, flip `enforced: true`, add a gate+test mirroring `tests/forge-high-gate.test.js`, add a changelog entry. Nothing else+changes — the access endpoint and `/three` pick it up automatically.++---++## Spec: `worlds.private` (first activation)++Today worlds are **owner-based with no visibility concept**+([`api/_lib/world-store.js`](../api/_lib/world-store.js),+[`api/world/[action].js`](../api/world/[action].js)). A world's doc is readable by anyone+with its id. Making "private" a real perk means adding a visibility dimension and+enforcing it on read.++**1. Schema** — migration `api/_lib/migrations/2026-06-24-world-visibility.sql`:++```sql+ALTER TABLE world_docs ADD COLUMN IF NOT EXISTS visibility text NOT NULL DEFAULT 'public';+```++Thread `visibility` through `world-store.js` `saveWorld` / `loadWorld` and the returned+shape. Default `'public'` so every existing world is untouched.++**2. Create gate** — in `api/world/[action].js` `handleSave`, when a write sets+`visibility: 'private'`:++```js+const gate = await requireFeatureAccess(req, res, 'worlds.private', { body });+if (!gate.ok) return; // 402 three_hold_required (hold-only, Silver+)+```++Hold-only (no pay-per-use) — a private world is a held perk, not a per-call cost.++**3. Load enforcement** — in `handleLoad`, a `private` world's doc is returned only to its+owner (or a service-token writer); any other caller gets `403 forbidden`. This is the step+that makes the perk *real* rather than a label.++**4. Activate** — flip `enforced: true` on `worlds.private` in+[`three-access.js`](../api/_lib/three-access.js). `/three` auto-flips it to **Live**.++**5. Test** — `tests/world-private-gate.test.js`: non-holder blocked with a 402 on+private create; Silver holder allowed; private-world load forbidden to a stranger; public+worlds unaffected.++**6. UI** — a visibility toggle in the world builder, defaulting to public.++**7. Changelog** — a `feature` entry in `data/changelog.json`.++---++## Configuration++| Env var | Required | Purpose |+|---------|----------|---------|+| `HOLDER_PASS_SECRET` | prod | HMAC key for signing/verifying tier passes |+| `THREE_TOKEN_MINT` | — | $THREE mint (defaults to the canonical CA) |+| `THREE_TOKEN_DECIMALS` | — | token decimals (default 6) |+| `SOLANA_RPC_URL` (+ provider keys) | — | RPC for on-chain balance reads (see `solana/connection.js`) |+| `UPSTASH_REDIS_REST_URL` / `_TOKEN` | — | caches balance/tier lookups (optional, fail-safe) |++---++## Related++- [Validation](./validation.md) — the quality gate every model passes before publish.+- [Pricing catalog](../api/_lib/pricing/catalog.js) — fixed-price actions the discount applies to.+- [`/three`](../pages/three.html) — the holder-facing tier page that surfaces this ladder.++---++<a id="sec-113"></a>> **Source:** `docs/how-it-works.md` · [↑ table of contents](#table-of-contents)@@ -15771,7 +18068,158 @@ Quick lookup for "I want to ship X":----<a id="sec-097"></a>+<a id="sec-114"></a>++> **Source:** `docs/i18n.md` · [↑ table of contents](#table-of-contents)++# Internationalization (i18n)++three.ws localizes its UI the way [LobeHub](https://github.com/lobehub/lobe-cli-toolbox/tree/master/packages/lobe-i18n)+does: a single source-of-truth catalog is translated **incrementally by an LLM**,+the output is **committed as static JSON**, and the browser **swaps copy at+runtime** from those static files. There is no per-request translation call, no+runtime cost, and full SEO/caching of each locale's JSON.++The one difference from LobeHub: their copy was already keyed (greenfield+i18next). Ours lives inline in 150+ static HTML pages, so we add an **extraction**+step that derives the catalog from annotated markup.++```+annotate HTML ──▶ i18n:extract ──▶ public/locales/en.json ──▶ i18n:translate ──▶ public/locales/<lang>.json+ (data-i18n) (build) (source of truth) (LLM, glossary-locked) (committed, static)+ │+ runtime: /i18n.js swaps the DOM+```++## 1. Annotate copy++Add attributes to the English markup. The English text already in the element+**is** the source value — no duplication.++| Attribute | Applies to | Example |+| ----------------------------- | ------------------------------------- | ------------------------------------------------------------------------ |+| `data-i18n="key"` | `textContent` | `<span data-i18n="common.take_tour">Take the tour</span>` |+| `data-i18n-html="key"` | `innerHTML` (copy with inline markup) | `<li data-i18n-html="home.bullet_earn"><strong>Earn</strong> USDC…</li>` |+| `data-i18n-attr="attr:key;…"` | element attributes | `<meta data-i18n-attr="content:home.meta_desc" content="…">` |++Keys are dot-namespaced (`home.hero_h`, `common.language`). Group by surface.++## 2. Extract the source catalog++```bash+npm run i18n:extract # scan annotated HTML → public/locales/en.json+npm run i18n:extract -- --force # overwrite values from current HTML (after copy edits)+npm run i18n:extract -- --prune # drop keys no element references anymore+```++Existing values are preserved by default, so re-running never clobbers a reviewed+string. Collisions (same key, different English in two files) fail the command.++## 3. Translate++```bash+npm run i18n:translate # translate only missing keys, every locale (incremental)+npm run i18n:translate -- --locale=es # one locale+npm run i18n:translate -- --force # retranslate everything+npm run i18n:translate -- --dry-run # show what would translate (also refreshes manifest)+npm run i18n # extract + translate+```++Configuration lives in [`.i18nrc.json`](../.i18nrc.json) (schema:+[`scripts/i18n-rc.schema.json`](../scripts/i18n-rc.schema.json)). Backend is+selected by `provider`. **The default is a free model — no card, no credits.**+Env-var names match [`api/_lib/chat-models.js`](../api/_lib/chat-models.js), so a+key that already powers `/chat` works here too. Set just one:++| provider | free? | env var | get a key |+| ---------------- | ------- | -------------------------------------- | ---------------------------------------------------------- |+| `groq` (default) | ✅ free | `GROQ_API_KEY` | <https://console.groq.com/keys> — Llama 3.3 70B, fast |+| `gemini` | ✅ free | `GEMINI_API_KEY` / `GOOGLE_API_KEY` | <https://aistudio.google.com/apikey> — free tier, best CJK |+| `openrouter` | ✅ free | `OPENROUTER_API_KEY` | <https://openrouter.ai/keys> — use a `:free` model |+| `nvidia` | ✅ free | `NVIDIA_API_KEY` | <https://build.nvidia.com> — free NIM credits |+| `openai` | paid | `OPENAI_API_KEY` (+ `OPENAI_BASE_URL`) | any OpenAI-compatible endpoint |+| `anthropic` | paid | `ANTHROPIC_API_KEY` | Claude Messages API |++```bash+export GROQ_API_KEY=... # free; the default provider+npm run i18n:translate # done+```++Leave `modelName` unset to use the provider's default model, or pin one (e.g.+`"modelName": "meta-llama/llama-3.3-70b-instruct:free"` for OpenRouter). Free+tiers rate-limit, so `concurrency` defaults to `2` and the translator backs off+and retries on HTTP 429 (honoring `Retry-After`).++> **Quality note:** Llama 3.3 70B (Groq) is solid for Latin-script languages. For+> CJK/Arabic/Hindi, the **Gemini free tier** (`provider: "gemini"`) is noticeably+> better and still free — switch per run with no code change. Whatever you pick,+> `npm run i18n:lint` catches any model that drops a placeholder or glossary term.+>+> Have GCP credits and want Vertex AI? Point `OPENAI_BASE_URL` at a Vertex+> OpenAI-compatible gateway with `provider: "openai"`.++### Glossary lock (the important part)++Terms in `doNotTranslate` — `$THREE`, the contract address, `x402`, `USDC`,+`Solana`, `IBM watsonx.ai`, etc. — plus every `{{placeholder}}` and HTML tag are+**masked to opaque sentinels before the text reaches the model and restored+after**. The model literally never sees them, so they come back byte-for-byte and+can never be translated, reordered, or hallucinated around. `$THREE` is the only+coin this platform references; this guarantees no machine translation can change+that.++## 4. Lint (build gate)++```bash+npm run i18n:lint+```++Validates every **committed** locale against the source: no missing/empty keys,+no `{{placeholder}}` drift, no dropped glossary terms, no stale keys. Locales not+yet generated are skipped (not failures). Needs no API key — safe in CI.++## 5. Runtime++[`src/i18n.js`](../src/i18n.js) (shipped at the stable URL `/i18n.js`) auto-runs+on any page that includes it:++```html+<script type="module" src="/i18n.js"></script>+<lang-switcher></lang-switcher>+<!-- accessible language picker -->+```++It detects the locale (`localStorage` → `?lang=` → `navigator.languages` →+default), fetches `/locales/<code>.json` once, rewrites the annotated DOM, sets+`<html lang>`/`dir` (RTL-aware), and persists the choice. Missing translations+fall back to English, so partial locales degrade gracefully. `window.threewsI18n`+exposes `{ t, setLocale, getLocale, initI18n }`.++The `<lang-switcher>` reads `public/locales/manifest.json` and only lists locales+with a committed catalog, so it never offers a language that would fall back to+English.++## Adding a language++Add the code (and display name) to `outputLocales` / `localeNames` in+`.i18nrc.json`, run `npm run i18n:translate -- --locale=<code>`, review the+output, and commit `public/locales/<code>.json`. The manifest and switcher pick+it up automatically.++## SEO note++Runtime swap (the LobeHub model) is client-side. For per-locale indexable URLs,+add `hreflang` alternates and a prerender step later; the catalogs are already+static and ready for it.++## Tests++[`tests/i18n.test.js`](../tests/i18n.test.js) covers extraction, glossary+round-trips, lint rules, runtime resolution/fallback, and catalog merge/prune.++---++<a id="sec-115"></a>> **Source:** `docs/ibm-x402-mcp.md` · [↑ table of contents](#table-of-contents)@@ -16129,7 +18577,7 @@ Catalog/listing copy is maintained in----<a id="sec-098"></a>+<a id="sec-116"></a>> **Source:** `docs/ibm.md` · [↑ table of contents](#table-of-contents)@@ -16439,7 +18887,7 @@ Unit tests for the same paths live in [`tests/`](../tests/) (`granite-oracle`, `----<a id="sec-099"></a>+<a id="sec-117"></a>> **Source:** `docs/internal/AGENT-WALLET-CUSTODY.md` · [↑ table of contents](#table-of-contents)@@ -16489,7 +18937,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`, whichreturns 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@@ -16638,12 +19101,77 @@ Run as a one-shot, reversible migration with **both** secrets available:must show only at-rest storage, the internal recover/generate helpers, andvalidation-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.----<a id="sec-100"></a>+<a id="sec-118"></a>> **Source:** `docs/internal/AUDIT-2026-06-18.md` · [↑ table of contents](#table-of-contents)@@ -16787,7 +19315,7 @@ These are not agent-doable and remain open in----<a id="sec-101"></a>+<a id="sec-119"></a>> **Source:** `docs/internal/AUDIT-LIVE-BROWSER-2026-06-18.md` · [↑ table of contents](#table-of-contents)@@ -16879,7 +19407,7 @@ Surfaced by a parallel source sweep; all low-risk, additive:----<a id="sec-102"></a>+<a id="sec-120"></a>> **Source:** `docs/internal/AUTO_DRIVE_REPORT.md` · [↑ table of contents](#table-of-contents)@@ -17144,7 +19672,7 @@ were committed by mistake, `git rm` them.----<a id="sec-103"></a>+<a id="sec-121"></a>> **Source:** `docs/internal/AWS_MARKETPLACE_LISTING.md` · [↑ table of contents](#table-of-contents)@@ -17362,7 +19890,7 @@ Once live, the seller profile URL is `https://aws.amazon.com/marketplace/seller-----<a id="sec-104"></a>+<a id="sec-122"></a>> **Source:** `docs/internal/CZ_DEMO_FAILURE_MODES.md` · [↑ table of contents](#table-of-contents)@@ -17514,7 +20042,7 @@ Example:----<a id="sec-105"></a>+<a id="sec-123"></a>> **Source:** `docs/internal/CZ_DEMO_RUNBOOK.md` · [↑ table of contents](#table-of-contents)@@ -17814,7 +20342,7 @@ A: "Testnet is a bit congested right now. On mainnet, this would be instant." (D----<a id="sec-106"></a>+<a id="sec-124"></a>> **Source:** `docs/internal/DEVELOPMENT.md` · [↑ table of contents](#table-of-contents)@@ -18261,7 +20789,331 @@ This runs `node test/gen_test.js`. Tests are script-based and validate model gen----<a id="sec-107"></a>+<a id="sec-125"></a>++> **Source:** `docs/internal/HOLDER-CONFIDENCE-ROADMAP.md` · [↑ table of contents](#table-of-contents)++# Protocol Fundamentals & Holder-Confidence Roadmap++_Internal strategy memo. Evidence-led. Last updated 2026-06-19._++## Why this document exists++$THREE holders are AI-crypto investors. This memo answers one question with+evidence instead of vibes: **what do AI-token investors actually reward, what do+they punish, and what should three.ws do about it** — using the real track+record of the top projects in the category (Bittensor, Virtuals, ai16z/ElizaOS,+Hyperliquid, Render, Akash, Grass, Pump.fun, GMX, Aave, Jupiter).++The honest finding — which is also the safe finding — is that **the things+investors reward are the same things that are genuinely good to build.** There is+no manipulation play here that survives contact with the data. Every shortcut in+the category (emissions yield, hollow burns, autonomy theatre, opaque claims)+got punished, usually catastrophically. So the strategy is simply: build the+real version, and make it _legible_. The edge is execution and visibility, not+spin.++---++## What the evidence says investors reward (and punish)++Five signals separate tokens that held value from the ~90% that died. Each is+backed by category data.++### 1. Real revenue, returned to holders — not emissions++- **Hyperliquid (HYPE):** ~$810M annualized fees H1 2025; ~92–97% of fees routed+ to an automated, on-chain buyback funded by _real fees, not treasury_; ~$1.3B++ spent through 2025 — **46% of all crypto buyback spend in 2025**. Repriced from+ ~$4 to a ~$76 ATH. ([OAK Research](https://oakresearch.io/en/reports/protocols/hyperliquid-hype-s1-2025-activity-report), [CoinGecko buyback report](https://www.coingecko.com/research/publications/token-buybacks))+- **GMX:** ~73% of revenue paid to holders in real assets (ETH/AVAX), not the+ native token. ([DeFiLlama](https://defillama.com/protocol/gmx))+- **Aave:** ~$108M 2025 revenue; permanent $50M/yr buyback approved → AAVE +8% on+ the announcement. ([The Block](https://www.theblock.co/post/344488))+- **Punished — emissions yield:** OlympusDAO (7,000% APY) fell >99%; Wonderland+ (84,000% APY) fell ~99.9998%. APY funded by printing the token is a countdown,+ not a yield.++> **Rule:** value to holders must originate from fees someone actually paid, not+> from inflation. Investors now compute this (Token Terminal P/E, P/S).++### 2. Verifiable public metrics — the trust layer++- The "real revenue" story is only believed when it is **independently+ auditable**. Virtuals' revenue _and_ its 97% revenue collapse were both read+ off public **Dune** dashboards — not self-reported. The market priced the truth+ the data showed.+- DeFiLlama / Dune / Token Terminal are the de-facto proof surfaces. CF+ Benchmarks valued Hyperliquid specifically because fee capture was "measurable+ on-chain rather than dependent on corporate reporting."+- **Punished — opacity:** FTX (no proof of reserves) and Terra/LUNA (~$50B gone+ in 3 days). After FTX, proof-of-reserves became table stakes.++> **Rule:** every fundamental claim we make needs a public, on-chain-verifiable+> URL behind it. A number without a dashboard is marketing; a number with a Dune+> link is evidence.++### 3. Demonstrable real usage — the moat++- **Render:** ~95% of RENDER spent on jobs is burned (burn-mint equilibrium);+ burns +279% YoY; usage (frames rendered) is the bull case, not the ticker.+- **Akash:** even as USD revenue fell with a ~65% token decline, _AKT-denominated_+ network activity kept rising (+229% YoY) — isolating genuine demand from price+ noise. That distinction is exactly what survived scrutiny.+- **Grass:** ~2.5M nodes, data throughput 10TB/day → 1,700TB/day; the metrics led+ the valuation.+- **The category verdict:** in the 2025 washout, "infrastructure-backed projects+ held value; zero-revenue branded tokens did not… the absence of usage proved+ terminal." By 2026 "both retail and institutional participants apply+ usage-based filters before committing." ([news.bitcoin.com](https://news.bitcoin.com/ai-agent-survivors-which-tokens-remained-standing-after-the-2025-dat-craze/), [spotedcrypto](https://www.spotedcrypto.com/crypto-ai-agents-2026-dominant-narrative-infrastructure/))++> **Rule:** usage > revenue > price as the order of leading indicators. A growing+> usage curve denominated in our own units survives a price drawdown; a price+> chart does not.++### 4. Consistent shipping by a visibly committed team++- Peer-reviewed (_Science Advances_, 298 cryptos, 6,341 devs, 879,742 commits):+ developer count correlates with market cap at **ρ = 0.48, P < 0.0001**, and dev+ activity acts as a _leading_ market signal. ([Science](https://www.science.org/doi/10.1126/sciadv.abd2204))+- Electric Capital frames developers as "a leading indicator of value creation."+ Hyperliquid (~11 people, no VC, relentless upgrades) is the human proof.+- A "dead chain" is _defined_ as no commits for 6+ months + 99% off ATH (EOS).+- **Honesty caveat:** raw commit _volume_ decouples from value (Cardano was #1 by+ commits while TVL fell ~85%). What matters is shipping things users _touch_, not+ commit count theatre.++> **Rule:** ship user-visible changes on a steady, public cadence — and make the+> cadence itself visible. We already have the changelog pipe; the gap is+> _surfacing_ it as a fundamentals signal, not just a feed.++### 5. Doxxed/accountable team + fair distribution++- Bittensor was uniquely praised for fair launch (no VC, no pre-mine, no+ founder unlock overhang). Virtuals' founders are doxxed (ex-BCG / Imperial).+- The shared failure mode across the category: **mercenary capital dumping on+ retail** (ai16z + VIRTUAL shed >$2B combined; top holders exited +4,082% ROI).+ Distribution and unlock optics are a trust variable, not a footnote.++---++## The synthesis (one paragraph)++Investors reward a **product → usage → revenue → token-sink** loop where every+link is publicly verifiable, shipped on a steady cadence by an accountable team,+with value flowing to holders from _real fees_ under a disciplined supply. They+punish emissions yield, hollow gestures, opacity, autonomy/vaporware theatre, and+insider dumps. **Necessary-but-not-sufficient is the whole game:** real revenue+without supply discipline still underperformed (Jupiter); a buyback not credibly+funded by _growing_ revenue moved price ~6% (Pump.fun's $370M burn). The winners+made the flywheel real _and_ legible at the same time.++---++## Where three.ws already sits (assets to leverage, not build)++We are not starting cold. The building blocks exist:++| Signal investors reward | What we already ship | Source surface |+|---|---|---|+| Revenue → holders | $THREE Economy: pay-per-use pricing, hold-to-access tiers, holder-rewards loop | [/three](../../pages/three.html) |+| Public live metrics | $THREE Live · Protocol Pulse — real on-chain trade feed, price/mcap/holders/volume HUD | [/three-live](../../pages/three-live.html) |+| Usage telemetry | Pump dashboard, skill-marketplace stats, agent directory | [/pump-dashboard](../../pages/pump-dashboard.html), `/discover` |+| Shipping cadence | Live public changelog (site + RSS + JSON + Telegram) | `data/changelog.json` |+| Buyback precedent | Prior $5,543 $THREE buyback (DEXTools Social Boost) | `/blog/three-ws-dextools-social-boost-buyback` |+| Real utility | x402 pay-per-call, MCP tools (paid), forge, skill licenses, SNS names | across `api/`, `mcp-server/` |++The work is **sequencing, wiring, and making the flywheel legible** — not+inventing new mechanics. We have the parts; the category-winning move is to+connect them into one auditable story.++---++## The roadmap (sequenced, framed as product milestones)++Each phase is a real product improvement that _also_ happens to light up one of+the five rewarded signals. Nothing here is cosmetic; every item is a thing a+serious holder can click, verify, and use.++### Phase 1 — Make the flywheel legible (weeks 1–3)++The mechanics exist but are scattered. Unify them into one **Protocol+Fundamentals** view that a skeptical investor can read in 30 seconds.++1. **A single, public, on-chain-verifiable fundamentals page.** Pull the numbers+ we already have — x402 call volume, paid-MCP calls, forge jobs, skill-license+ mints, SNS mints, treasury inflows — into one dashboard with a "verify on-chain"+ link beside each figure (the Dune/Solana-explorer equivalent). This is the+ Token Terminal / DeFiLlama move applied to us. _Rewards signal #2 + #3._+2. **Denominate usage in our own units.** Surface "agents deployed," "skill calls+ paid," "forge GLBs generated," "x402 USDC settled" as time-series — the Akash+ lesson: usage curves that survive price drawdowns. _Rewards signal #3._+3. **Promote the changelog into a fundamentals signal.** Add a "shipped this week"+ strip to the fundamentals page sourced from `data/changelog.json`, with a+ rolling commit/release cadence counter. Cadence becomes visible, not buried.+ _Rewards signal #4._++### Phase 2 — Close the revenue→holder loop credibly (weeks 3–8)++We already route spend to treasury/holders. The category lesson is that the loop+must be **automated, on-chain, and funded by growing real fees** — Hyperliquid's+exact formula, the opposite of a one-off treasury burn.++4. **Formalize the value-return mechanic** so a fixed, published % of real+ protocol fees (x402 settlement, paid MCP, forge, skill licenses) deterministically+ flows back to $THREE holders — as buyback, reflection, or rewards, per what the+ $THREE Economy page already commits to. Publish the formula. Make it on-chain+ and auditable. _Rewards signal #1._ Do **not** run a hollow burn for optics —+ Pump.fun proved a burn not backed by rising revenue barely moves price and+ spends trust.+5. **Show the funding source is real and growing.** The loop is only believed if+ the fee line is independently going up. Pair every value-return event with the+ public revenue series behind it. The honest version is the persuasive version.+ _Rewards #1 + #2._++### Phase 3 — Deepen real usage sinks (weeks 4–12)++Investors reward demand sinks tied to the product, not artificial gates.++6. **Hold-to-access, done as genuine utility.** We already have holder tiers.+ Sharpen them into a real reason to hold: lower x402 fees, priority forge lanes,+ premium MCP/intel access, rare `*.threews.sol` names. This is aixbt's+ token-gated-terminal mechanic — but it must gate something people actually want,+ not a paywall on nothing. _Rewards #3 (demand sink) + #1._+7. **Tie agent/skill commerce back to $THREE.** Virtuals' structural buy-pressure+ came from $VIRTUAL being the base pair of the whole agent economy. Where it's+ honest and product-correct, make $THREE the settlement/denomination unit for+ platform commerce so platform growth = structural $THREE demand. _Rewards #1 + #3._++### Phase 4 — Accountability & distribution optics (ongoing)++8. **Public, accountable cadence.** Keep the team's shipping visible (changelog,+ public repo activity). The dev-activity↔valuation link is peer-reviewed; we+ already have the artifacts, we just keep them lit.+9. **Distribution hygiene.** The category's #1 trust-killer is insiders dumping on+ retail. Whatever the $THREE distribution and any treasury movements are, make+ them transparent and predictable. Unlock/treasury opacity is a punished+ variable; a published, boring schedule is a rewarded one.++---++## Hard "do not" list (the punished behaviors)++These are the moves that _look_ like progress and reliably destroy holder trust.+Banned by evidence, and by [CLAUDE.md](../../CLAUDE.md) anyway:++- ❌ **Emissions-funded yield / high-APY staking.** OHM/TIME → ~99% wipeouts.+- ❌ **Hollow buyback or burn for headlines.** Pump.fun's $370M burn moved price+ +6.25% because revenue was falling. A burn not funded by _growing_ real fees+ spends trust for nothing.+- ❌ **Unverifiable claims.** Every fundamental number ships with a public proof+ link or it doesn't ship. No "trust us" metrics.+- ❌ **Autonomy / capability theatre.** ai16z's "autonomous AI fund" was+ human-operated; the gap became a credibility liability. Claim only what's wired.+- ❌ **Opaque treasury / insider exits.** The category's most reliable -80% trigger.+- ❌ **Any coin but $THREE.** Non-negotiable, independent of this strategy.++---++## The one-line takeaway++**Build the real product → usage → revenue → holder-return flywheel, fund value-return+from genuinely growing fees under disciplined supply, and make every link of it+publicly auditable on a steady, visible shipping cadence.** That is precisely+what the winners did and the losers faked. For three.ws the parts already exist —+the win is connecting and surfacing them as one legible, verifiable story. We+don't need to spin anything; we need to make what's true impossible to miss.++---++<a id="sec-126"></a>++> **Source:** `docs/internal/IBM-WEBINAR-RUNBOOK.md` · [↑ table of contents](#table-of-contents)++# IBM community webinar — runbook (Jun 23, 2026)++The webinar stage lives at the top of **[pages/ibm/x402-demo.html](../../pages/ibm/x402-demo.html)** — the same page hosts the live x402 demos below it, so attendees watch the talk and try the demos on one screen. It is fully self-contained, so it runs verbatim when published to **live.ibm.com** as well as `three.ws/ibm/x402-demo`.++Everything is driven by one config object: the `WEBINAR = { … }` block inside the page's webinar `<script>` (search the file for `SET THE REAL START TIME`).++---++## 1. Today — set the start time (the only required value)++In the `WEBINAR` config:++```js+startTime: '2026-06-23T15:00:00Z', // ISO 8601, Z = UTC. Default = 11:00 AM US Eastern.+durationMin: 60, // talk length → when the stage flips to "replay"+```++Set `startTime` to the real slot and `durationMin` to the real length. With no video source yet, the page shows a **live countdown** + Add-to-Calendar. Nothing else is needed to ship the countdown.++---++## 2. When the video is ready — paste ONE source++Still in `WEBINAR`. Fill exactly one; resolution priority is `liveHls → vodHls → mp4 → youTubeId`.++```js+liveHls: '', // OBS → ingest → HLS (.m3u8) live feed → set mode:'live'+vodHls: '', // Cloudflare Stream / Mux HLS (.m3u8) → synced premiere+mp4: '', // plain MP4 on R2 → synced premiere+youTubeId: '', // YouTube video / live id → iframe+mode: 'auto', // 'auto' | 'premiere' | 'live'+```++A **premiere** (`vodHls`/`mp4`) plays the recording seeked to wall-clock — everyone sees the same moment, latecomers join in progress, no skipping ahead. A **live** source streams straight through. No code changes; the stage swaps from countdown to player on its own at `startTime`.++### Option A — Cloudflare Stream (recommended)+You're already on Cloudflare/R2, and one product does both VOD and live.++- **Pre-recorded premiere:** Stream dashboard → **Videos** → upload the recording → open it → copy the **HLS manifest** URL (ends in `.m3u8`) → set `vodHls`.+- **Live from OBS:** Stream → **Live Inputs** → **Create Live Input**. Copy:+ - the **RTMPS** URL + **Stream Key** → OBS ▸ Settings ▸ Stream (Service: *Custom*), or the **SRT** URL for lower latency;+ - the input's **HLS playback** URL (`.m3u8`) → set `liveHls` and `mode: 'live'`.+- **OBS encoder:** 1080p, 30fps, x264, keyframe interval **2s**, bitrate 4000–6000 kbps. Start streaming a few minutes early to warm the input.++### Option B — Plain MP4 on R2 (zero new service)+Record → export an MP4 (1080p, H.264/AAC, web-optimized / faststart) → put it on R2 → set `mp4` to its public URL (`${S3_PUBLIC_DOMAIN}/<key>`). Premiere works identically; you only lose adaptive bitrate and the live option. *(Ask Claude to upload it via the existing R2/S3 credentials and hand back the URL.)*++### Option C — YouTube (fastest, least control)+Create an unlisted video / Premiere / Live event → set `youTubeId` to the id. Renders as an iframe (carries YouTube chrome).++---++## 3. Verify before going live++Open the page with **`?wb=live`** appended to the URL:++```+https://three.ws/ibm/x402-demo?wb=live+```++This force-mounts the player immediately (ignoring the clock) using whatever source is configured, so you can confirm it plays, audio works, and the unmute button behaves — **before** the event. Other QA overrides: `?wb=countdown`, `?wb=premiere`, `?wb=ended`. Remove the param for the real run.++If the source is unreachable, the stage shows a designed **"Playback hit a snag"** card with a Reload button rather than a black frame.++---++## 4. Day-of checklist++- [ ] `startTime` / `durationMin` correct for the real slot + timezone.+- [ ] One source set; opened `?wb=live` and confirmed playback + audio.+- [ ] Page deployed to `three.ws/ibm/x402-demo` **and** published on live.ibm.com.+- [ ] (Live) OBS connected to the ingest and streaming ~5 min early.+- [ ] Calendar links resolve (Google + .ics download).+- [ ] After the talk: leave `vodHls`/`mp4` set so the stage auto-flips to on-demand replay.++---++## Deploy notes++It's a static page — publish like any other. In this repo, push to **both** remotes (`threeD` and `threews`) so both deploy targets stay in sync. The webinar block adds no new build step and no server dependency.++---++<a id="sec-127"></a>> **Source:** `docs/internal/IBM_USER_GROUP.md` · [↑ table of contents](#table-of-contents)@@ -18351,7 +21203,7 @@ sitemap and changelog automatically.----<a id="sec-108"></a>+<a id="sec-128"></a>> **Source:** `docs/internal/ISSUES-ARCHIVE-2026-05.md` · [↑ table of contents](#table-of-contents)@@ -18603,7 +21455,70 @@ Server responded with 429 Too Many Requests. Retrying after Xms delay...----<a id="sec-109"></a>+<a id="sec-129"></a>++> **Source:** `docs/internal/ISSUES-ARCHIVE-2026-06.md` · [↑ table of contents](#table-of-contents)++# Production Issues — three.ws / 3D-Agent — Archive 2026-06++Resolved items moved here from [ISSUES.md](../../ISSUES.md). Newest first.++---++## 1. `character-studio/` — pre-existing lint debt (added 2026-06-11, RESOLVED 2026-06-21)++**Context:** The eslint 8→10 upgrade migrated character-studio to flat config+(`character-studio/eslint.config.mjs`), surfacing pre-existing findings across the+vendored CharacterStudio fork that all predated the upgrade.++**Runtime `no-undef` bugs — FIXED 2026-06-18** (full table in+[AUDIT-2026-06-18.md](AUDIT-2026-06-18.md)): twelve references that threw+`ReferenceError` the moment their code path ran were corrected and verified by a+clean `no-undef`-only sweep.++**Cosmetic burndown — RESOLVED 2026-06-21.** Every remaining finding in+`character-studio/src` was cleared, file by file, with minimal behaviour-preserving+edits. The full tree (`eslint character-studio/src`) now reports **0 problems**.++Findings cleared (178 total across 48 files):++| rule | count | how it was fixed |+|---|---|---|+| `no-unused-vars` | 119 | dead imports/locals removed; side-effecting calls kept as statements; unused trailing params dropped; positional destructure holes (`[, x]`); unused catch bindings → optional `catch {}` |+| `no-async-promise-executor` | 17 | executors with no `await` → dropped the gratuitous `async`; executors using `await` → inner `(async () => { … })().catch(reject)` IIFE so thrown errors reject the promise instead of going unhandled |+| `no-useless-escape` | 10 | stray `\` before whitespace in GLSL template literals (`particle/shader.js`) removed — string contents unchanged |+| `no-useless-assignment` | 10 | dead initializers/assignments removed (RHS kept only when side-effecting) |+| `no-unreachable` | 9 | dead code after early `return`/`throw` deleted (the early exit — the intended behaviour — was kept) |+| `no-prototype-builtins` | 4 | `obj.hasOwnProperty(k)` → `Object.prototype.hasOwnProperty.call(obj, k)` |+| `no-empty` | 4 | `/* noop */` comments added; no control-flow change |+| `no-constant-binary-expression` | 2 | `maxTextureSize: 1024 \|\| Infinity` → `1024` (the `\|\| Infinity` was always dead) |+| `no-dupe-class-members` | 1 | duplicate `unlockManifestByIndex` removed (kept the later, winning definition) |+| `preserve-caught-error` | 1 | re-thrown error now carries `{ cause }` |+| unused eslint-disable directive | 1 | removed (`lipsync.js`) |++**Latent bugs surfaced while clearing dead code (noted, not "fixed" — behaviour+was preserved to keep this a lint-only pass):**++- `download-utils.js` `getRebindedVRMExpressionManager` — the entire blendshape+ re-bind implementation sat behind an early `return oldExpressionManager;`, so it+ has been dead in this fork. The unreachable body was removed; the feature remains+ effectively disabled (unchanged from before).+- `addLookAtMouse(…, enable = true)` (`characterManager.js`) — the `enable`+ parameter was never read (`lookAtManager.enabled = true` is hardcoded); the unused+ param was dropped.+- `ktxtools.js:47` — `uastcRDODictSize` ternary copies `userBasisuOptions.uastcRDOQualityScalar`+ in its truthy branch (looks like a copy-paste error); left as-is, outside lint scope.+- `textureImageDataRenderer.js` `render()` — the empty-textures branch assigned the+ solid-colour fallback to the `texture` param, which is never read afterward (only+ `textures` is), so the fallback was discarded; the dead assignment was removed and+ current behaviour preserved.++These are tracked here for a future correctness pass; none are regressions from this+work.++---++<a id="sec-130"></a>> **Source:** `docs/internal/NEXT.md` · [↑ table of contents](#table-of-contents)@@ -18615,7 +21530,7 @@ _No open items._----<a id="sec-110"></a>+<a id="sec-131"></a>> **Source:** `docs/internal/PAGES.md` · [↑ table of contents](#table-of-contents)@@ -18916,7 +21831,7 @@ A high-level map of what each page does, grouped by capability.----<a id="sec-111"></a>+<a id="sec-132"></a>> **Source:** `docs/internal/PROGRESS.md` · [↑ table of contents](#table-of-contents)@@ -19121,7 +22036,7 @@ Rails:----<a id="sec-112"></a>+<a id="sec-133"></a>> **Source:** `docs/internal/PR_LISTINGS_CHECKLIST.md` · [↑ table of contents](#table-of-contents)@@ -19237,7 +22152,7 @@ You have Alibaba + Google Cloud. Add:----<a id="sec-113"></a>+<a id="sec-134"></a>> **Source:** `docs/internal/SETUP.md` · [↑ table of contents](#table-of-contents)@@ -19323,7 +22238,7 @@ npm run deploy----<a id="sec-114"></a>+<a id="sec-135"></a>> **Source:** `docs/internal/SMOKE_TEST.md` · [↑ table of contents](#table-of-contents)@@ -19408,7 +22323,7 @@ Append new runs as `### Run YYYY-MM-DD (commit <sha>)` sections below this line.----<a id="sec-115"></a>+<a id="sec-136"></a>> **Source:** `docs/internal/SNS_PARTNERSHIP_OUTBOUND.md` · [↑ table of contents](#table-of-contents)@@ -19463,7 +22378,7 @@ Code references:----<a id="sec-116"></a>+<a id="sec-137"></a>> **Source:** `docs/internal/SNS_PARTNERSHIP_PROPOSAL.md` · [↑ table of contents](#table-of-contents)@@ -19592,7 +22507,7 @@ No slides. Working software.----<a id="sec-117"></a>+<a id="sec-138"></a>> **Source:** `docs/internal/STATUS.md` · [↑ table of contents](#table-of-contents)@@ -19611,7 +22526,7 @@ If something is blocked or surprising, add a second line indented with ` └─----<a id="sec-118"></a>+<a id="sec-139"></a>> **Source:** `docs/internal/TODO.md` · [↑ table of contents](#table-of-contents)@@ -19712,7 +22627,7 @@ All 8 finish-features prompts (referral-code uniqueness, speech-provider errors,----<a id="sec-119"></a>+<a id="sec-140"></a>> **Source:** `docs/internal/VALIDATION_DEPLOY.md` · [↑ table of contents](#table-of-contents)@@ -20191,7 +23106,7 @@ Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15----<a id="sec-120"></a>+<a id="sec-141"></a>> **Source:** `docs/internal/api-inventory.md` · [↑ table of contents](#table-of-contents)@@ -20398,7 +23313,7 @@ Generated reference of every HTTP endpoint under `/api/`. Paths reflect the exte----<a id="sec-121"></a>+<a id="sec-142"></a>> **Source:** `docs/internal/tutorial-build-pai-site.md` · [↑ table of contents](#table-of-contents)@@ -21685,7 +24600,7 @@ The technique is small. The art is in the tuning. Build it, scroll it, show it t----<a id="sec-122"></a>+<a id="sec-143"></a>> **Source:** `docs/introduction.md` · [↑ table of contents](#table-of-contents)@@ -21911,7 +24826,7 @@ If you want to look at what's already in the hosted platform — browsing agents----<a id="sec-123"></a>+<a id="sec-144"></a>> **Source:** `docs/irl/THREAT-MODEL.md` · [↑ table of contents](#table-of-contents)@@ -21986,7 +24901,7 @@ in a way that drops legitimate discovery, update this file in the same change.----<a id="sec-124"></a>+<a id="sec-145"></a>> **Source:** `docs/js-api.md` · [↑ table of contents](#table-of-contents)@@ -22597,7 +25512,7 @@ window.VIEWER.app.viewer.updateDisplay();----<a id="sec-125"></a>+<a id="sec-146"></a>> **Source:** `docs/layers.md` · [↑ table of contents](#table-of-contents)@@ -22759,7 +25674,7 @@ Versioned CDN bundles are published at `/agent-3d/<version>/agent-3d.js`. Use `l----<a id="sec-126"></a>+<a id="sec-147"></a>> **Source:** `docs/listings.md` · [↑ table of contents](#table-of-contents)@@ -22831,7 +25746,7 @@ Subscribe via RSS to track new listings, integrations, and protocol updates.----<a id="sec-127"></a>+<a id="sec-148"></a>> **Source:** `docs/make-your-agent.md` · [↑ table of contents](#table-of-contents)@@ -22922,7 +25837,7 @@ Changes take effect immediately — no republishing needed for most settings.----<a id="sec-128"></a>+<a id="sec-149"></a>> **Source:** `docs/mcp-3d-studio.md` · [↑ table of contents](#table-of-contents)@@ -23111,7 +26026,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-3d----<a id="sec-129"></a>+<a id="sec-150"></a>> **Source:** `docs/mcp-agent.md` · [↑ table of contents](#table-of-contents)@@ -23187,7 +26102,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-agent----<a id="sec-130"></a>+<a id="sec-151"></a>> **Source:** `docs/mcp-x402-bazaar.md` · [↑ table of contents](#table-of-contents)@@ -23262,7 +26177,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-bazaar----<a id="sec-131"></a>+<a id="sec-152"></a>> **Source:** `docs/mcp.md` · [↑ table of contents](#table-of-contents)@@ -23311,34 +26226,84 @@ The MCP server configuration is at `.mcp.json` in the project root, which Claude## The full three.ws MCP ecosystem-This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **14 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.+This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **38 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.++There are two kinds. **Hosted remote servers** run over Streamable HTTP with nothing to install — add them by URL. **Install-and-run servers** are published on npm under the `@three-ws` scope and run locally over stdio — add them in one line with `npx`.**Six hosted remote servers** (Streamable HTTP, no install):| Server | Endpoint | What it does ||--------|----------|--------------|-| three.ws | `/api/mcp` | Avatars, glTF/GLB validation, agent data (this page) |+| three.ws | `/api/mcp` | Avatars, glTF/GLB validation, agent data, memory, copy-trading (this page) |+| 3D Studio | `/api/mcp-3d` | Paid text/image→3D, rigging, retexture, optimization |+| Agent wallet | `/api/mcp-agent` | The agent's custodial wallet: balance, find + pay services, and `monetize_endpoint` |+| x402 Bazaar | `/api/mcp-bazaar` | Discover and price paid agent services across the facilitator network || pump.fun | `/api/pump-fun-mcp` | Free, read-only pump.fun + Solana token tools |-| 3D Studio | `/api/mcp-3d` | Paid text/image→3D, rigging, optimization |-| Agent | `/api/mcp-agent` | Agent reputation and on-chain agent data || IBM x402 | `/api/ibm-mcp` | Pay-per-use IBM Granite AI |-| x402 Bazaar | `/api/mcp-bazaar` | Discover and price paid agent services |-**Eight install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:+**Thirty-two install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:```bash-npx -y @three-ws/mcp-server # 3D + agent tools, paid per call in USDC-npx -y @three-ws/three-token-mcp # price, hold, and burn $THREE on Solana-npx -y @three-ws/pumpfun-mcp # free pump.fun + Solana discovery-npx -y @three-ws/ibm-x402-mcp # pay-per-use IBM Granite AI-npx -y @three-ws/ibm-watsonx-mcp # IBM watsonx.ai on your own account-npx -y @three-ws/avatar-agent # turn any GLB into a 3D AI agent-npx -y @three-ws/avatar-mcp # drop a live 3D avatar into any chat-npx -y @three-ws/mcp-bridge # pay any x402 endpoint on the open web+# 3D & avatars+npx -y @three-ws/scene-mcp # speak a 3D diorama into being from one sentence+npx -y @three-ws/avatar-mcp # drop a live 3D avatar into any chat+npx -y @three-ws/avatar-agent # turn any GLB into a riggable 3D AI agent+npx -y @three-ws/mcp-server # full 3D + agent toolkit, paid per call in USDC++# Payments & the agent economy+npx -y @three-ws/x402-mcp # self-custodial wallet: find, inspect & pay any x402 service in USDC+npx -y @three-ws/three-token-mcp # price, hold, and burn $THREE on Solana+npx -y @three-ws/mcp-bridge # bridge that pays any x402 endpoint on the open web+npx -y @three-ws/ibm-x402-mcp # pay-per-use IBM Granite AI++# Market data, intel & discovery+npx -y @three-ws/intel-mcp # smart-money, signal feeds, KOL & copy-trade intel+npx -y @three-ws/pumpfun-mcp # free pump.fun + Solana token discovery+npx -y @three-ws/vanity-mcp # Solana vanity-address bounty market + rarity gallery+npx -y @three-ws/marketplace-mcp # browse the agent marketplace + skills catalog++# Naming & AI+npx -y @three-ws/naming-mcp # resolve .sol names + check *.threews.sol identity availability+npx -y @three-ws/ibm-watsonx-mcp # IBM watsonx.ai on your own account++# Autonomous agent control plane+npx -y @three-ws/autopilot-mcp # set scopes + daily $THREE spend caps, then propose/execute/undo+npx -y @three-ws/portfolio-mcp # portfolio value, PnL, balances, trade feed & signed transfers+npx -y @three-ws/provenance-mcp # append-only, signed, on-chain-verifiable agent action log++# Trading, signals & alerts+npx -y @three-ws/copy-mcp # manage copy-trade follows, sizing & guard rules+npx -y @three-ws/signals-mcp # discover signal feeds by proven edge; rank publishers+npx -y @three-ws/alerts-mcp # pump.fun alert rules across in-app / webhook / Telegram+npx -y @three-ws/kol-mcp # per-wallet KOL portfolio + trade analytics++# Account, inbox & discovery+npx -y @three-ws/notifications-mcp # inbox, read state, delivery prefs & Web Push devices+npx -y @three-ws/billing-mcp # plan quotas, metered usage, invoices & receipts+npx -y @three-ws/activity-mcp # trending agents/coins, $THREE holder board & activity ticker++# More AI & capability+npx -y @three-ws/vision-mcp # analyze & describe images via the three.ws vision pipeline+npx -y @three-ws/brain-mcp # run any LLM through the multi-provider router+npx -y @three-ws/audio-mcp # TTS, STT, audio-to-face lipsync & motion-capture clips++# Coordination, gaming & learning+npx -y @three-ws/agenc-mcp # AgenC on-chain task marketplace + agent registry+npx -y @three-ws/agora-mcp # join Agora's agent economy: browse the board, claim & complete real work, earn $THREE+npx -y @three-ws/clash-mcp # Coin Clash faction battles+npx -y @three-ws/tutor-mcp # itemized learning-session ledger+npx -y @three-ws/loom-mcp # browse & contribute to the Loom 3D-creation gallery```Every one is also registered in the MCP registry under the `io.github.nirholas/*` namespace.+### Per-server guides++Deep dives — every tool, argument, env var, and example:++- **Install-and-run:** [Scenes](https://three.ws/docs/mcp-scenes) · [x402 Wallet](https://three.ws/docs/mcp-x402) · [Intel](https://three.ws/docs/mcp-intel) · [Vanity](https://three.ws/docs/mcp-vanity) · [Naming](https://three.ws/docs/mcp-naming) · [Marketplace](https://three.ws/docs/mcp-marketplace)+- **Hosted remote:** [3D Studio](./mcp-3d-studio.md) · [Agent wallet](./mcp-agent.md) · [x402 Bazaar](./mcp-x402-bazaar.md) · [IBM x402](./ibm-x402-mcp.md)+---## Authentication@@ -23752,7 +26717,7 @@ Restart Claude Code after editing `.mcp.json` so the new server config is picked----<a id="sec-132"></a>+<a id="sec-153"></a>> **Source:** `docs/memory.md` · [↑ table of contents](#table-of-contents)@@ -23762,6 +26727,8 @@ Agent memory lets an agent remember things between sessions. Without it, every cThis document covers how agent memory works, how to configure storage modes, and how to read and write memories from code.+> **Just want to add a memory?** Start with the hands-on tutorial: [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) walks through every path — the dashboard, the agent itself, MCP tools, the REST API, and skills — plus how to sharpen, edit, and forget. This reference is the underlying data model.+---## Two layers@@ -24141,7 +27108,7 @@ In `ipfs` mode without encryption, treat the memory as semi-public. Don't store----<a id="sec-133"></a>+<a id="sec-154"></a>> **Source:** `docs/mint-mark.md` · [↑ table of contents](#table-of-contents)@@ -24273,7 +27240,7 @@ No other mint should appear in tests, fixtures, or documentation.----<a id="sec-134"></a>+<a id="sec-155"></a>> **Source:** `docs/multi-agent.md` · [↑ table of contents](#table-of-contents)@@ -24602,7 +27569,297 @@ To extend this into a full turn-based scene, add a `brain` attribute to Mira wit----<a id="sec-135"></a>+<a id="sec-156"></a>++> **Source:** `docs/nvidia-models.md` · [↑ table of contents](#table-of-contents)++# NVIDIA models on three.ws — the free inference layer++three.ws runs a large share of its AI on NVIDIA's free hosted models. **One key — `NVIDIA_API_KEY` (an `nvapi-…` token from [build.nvidia.com](https://build.nvidia.com)) — unlocks every model on this page.** There is no per-model billing, no per-seat cost, and no SLA: it is a rate-limited free tier, which is exactly why the platform treats it as a *free-first* lane and always keeps a fallback behind it.++This document is the canonical map of **which NVIDIA-hosted model does what, where it's wired, and why**. Every model and endpoint below is in production source — nothing here is aspirational.++---++## How the platform talks to NVIDIA++NVIDIA exposes its catalog over a few distinct surfaces. three.ws uses four:++| Surface | Base URL | Shape | What runs here |+| --- | --- | --- | --- |+| **NIM (OpenAI-compatible)** | `https://integrate.api.nvidia.com/v1` | `chat/completions`, `embeddings` | LLM chat, vision (VLM), embeddings, content-safety |+| **GenAI invoke** | `https://ai.api.nvidia.com/v1/genai/…` | Async (202 + poll) or sync | TRELLIS text→3D, FLUX text→image |+| **Retrieval** | `https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking` | Sync rerank | Cross-encoder reranking |+| **NVCF gRPC** | `grpc.nvcf.nvidia.com:443` | Riva gRPC | Magpie text-to-speech |+| **NVCF status** | `https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/{id}` | Poll | Async job status (TRELLIS) |++Because it is one key for everything, a deployment either has the whole NVIDIA layer or none of it — every consumer below degrades gracefully when `NVIDIA_API_KEY` is absent.++---++## The catalog at a glance++| Capability | NVIDIA model(s) | Wired in | Free? |+| --- | --- | --- | --- |+| **Text → 3D** | `microsoft/trellis` | `api/_providers/nvidia.js`, `api/_lib/forge-tiers.js` | ✅ |+| **Text → image** | `black-forest-labs/flux.1-schnell` | `api/_mcp3d/text-to-image.js` | ✅ |+| **LLM (default lane)** | `meta/llama-3.3-70b-instruct` | `api/_lib/llm.js`, `api/_lib/chat-models.js` | ✅ |+| **LLM (model garden)** | Nemotron 120B / 49B / Nano 9B, Llama 4 Maverick, DeepSeek V4 Pro, Kimi K2.6, MiniMax M2.7 | `api/brain/chat.js` | ✅ |+| **Vision / VLM** | `nvidia/nemotron-nano-12b-v2-vl`, `meta/llama-3.2-11b-vision-instruct` | `api/_lib/vision.js` | ✅ |+| **Embeddings** | `nvidia/nv-embedqa-e5-v5`, `baai/bge-m3` | `api/_lib/embeddings.js`, `api/agents/_id/embed.js` | ✅ |+| **Reranking** | `nvidia/rerank-qa-mistral-4b` | `api/_lib/rerank.js` | ✅ |+| **Content safety** | `nvidia/llama-3.1-nemoguard-8b-content-safety`, `meta/llama-guard-4-12b` | `api/_lib/moderation.js` | ✅ |+| **Text-to-speech** | `magpie-tts-multilingual` (Riva) | `api/_lib/tts-nvidia.js` | ✅ |++---++## 1. Text → 3D — Microsoft TRELLIS++**Model:** `microsoft/trellis` · **Endpoint:** `ai.api.nvidia.com/v1/genai/microsoft/trellis` → poll `api.nvcf.nvidia.com/v2/nvcf/pexec/status/{id}`+**Source:** [api/_providers/nvidia.js](api/_providers/nvidia.js), registered as the `nvidia` backend in [api/_lib/forge-tiers.js](api/_lib/forge-tiers.js).++This is the headline free model. **Microsoft TRELLIS hosted on NVIDIA NVCF gives `/forge` a zero-vendor-cost text→3D lane that returns a textured GLB.** It is the default draft/standard engine for prompt generations, per the platform's free-first policy.++**Where it's used:**+- The `/forge` web app — draft and standard tiers default here (`FREE_DEFAULT_FOR_TIERS`).+- The free **`forge_free` MCP tool** — text prompt → downloadable GLB + viewer link, no payment, no wallet, no key.+- The **IBM × three.ws x402 demo** — the free generator next to the paid USDC Forge.+- The **auto-generation gallery** — a fresh community avatar every minute.++**How it works:**+- Async by default. Submit returns `202 + NVCF-REQID`; the forge polls the NVCF status endpoint until the GLB is ready (or the job completes synchronously within a 30 s window).+- **Quality scales by sampling steps**, clamped to TRELLIS's 10–50 window: draft `15/15`, standard `25/25`, high `40/40` (`ss_sampling_steps` / `slat_sampling_steps`).+- Prompts are clamped to **77 characters** (TRELLIS truncates server-side) and get a `, studio lighting` suffix unless the caller already supplied lighting/color cues — without it TRELLIS defaults to dark, gritty output.+- Output GLBs arrive in several shapes over time (inline base64, bare string, CDN URL, numeric-keyed object, raw bytes); the extractor normalizes all of them, then **persists the bytes to R2** so three.ws owns a durable public URL.++**Key constraint — text only.** NVIDIA's *hosted preview* rejects every user-image input form (verified live; see `tasks/nvidia-nim/probes/trellis.md`). So **photo→3D never routes here** — it falls to the free Hugging Face Spaces lane (Hunyuan3D / TRELLIS / TripoSR). A self-deployed TRELLIS NIM accepts real images; this is a hosted-preview limitation, not a model one.++---++## 2. Text → image — FLUX.1-schnell++**Model:** `black-forest-labs/flux.1-schnell` · **Endpoint:** `ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell`+**Source:** [api/_mcp3d/text-to-image.js](api/_mcp3d/text-to-image.js).++FLUX.1-schnell is the **free, first-choice text-to-image lane**. It's a synchronous invoke — the image returns inline as base64 (no poll) in ~1–2 s — and it's Apache-2.0, commercial-OK.++**Where it's used:**+- **The reference-image step of the image-intermediate 3D path.** When a prompt is reconstructed to a mesh, FLUX paints the reference view first, which the free reconstruction lanes (TRELLIS / Hunyuan3D) then turn into geometry. A photo-quality reference reconstructs into a far better mesh than a busy scene, so the lane steers FLUX toward a clean, centered subject.+- General text→image wherever the platform needs a synthesized image.++**Fallback order:** NVIDIA FLUX (free) → Vertex Imagen (`GOOGLE_CLOUD_PROJECT`) → Replicate `flux-schnell` ($0.003/image). The free NVIDIA lane always leads.++---++## 3. LLM chat & reasoning++NVIDIA NIM hosts 100+ open-weight chat models behind the one key, all OpenAI-compatible at `integrate.api.nvidia.com/v1/chat/completions`. three.ws uses them two ways.++### 3a. The default production lane++**Model:** `meta/llama-3.3-70b-instruct`+**Source:** [api/_lib/llm.js](api/_lib/llm.js), [api/_lib/chat-models.js](api/_lib/chat-models.js).++The platform's general LLM helper runs a **free-first ladder: Groq → OpenRouter → NVIDIA NIM**, and only then a paid backstop (Anthropic/OpenAI). NVIDIA is the **independent third free lane** — same Llama 3.3 70B family as the Groq/OpenRouter entries, but a different provider, so an outage on two lanes still answers on the third. It's tool/function-calling capable, so it's eligible for tool-required requests.++This lane powers the platform's built-in AI surfaces — chat, embedded site widgets, the tutor, the fact-checker, persona tools, agent-to-agent talk, the transaction explainer — all of which lead with the free providers and only fall through to a paid model if every free lane fails.++### 3b. The Brain model garden++**Source:** [api/brain/chat.js](api/brain/chat.js) — the Brain workbench lets users pick a model. The NVIDIA-hosted options, all unlocked by the single key:++| Brain label | Model id | Tier | What it's for |+| --- | --- | --- | --- |+| Nemotron 3 Super 120B | `nvidia/nemotron-3-super-120b-a12b` | flagship | NVIDIA's flagship Nemotron MoE — strong agentic reasoning |+| Llama-Nemotron Super 49B | `nvidia/llama-3.3-nemotron-super-49b-v1.5` | reasoning | Nemotron reasoning tuned on Llama 3.3 — math, code, planning |+| Nemotron Nano 9B | `nvidia/nvidia-nemotron-nano-9b-v2` | balanced | Compact Nemotron with built-in reasoning — strong quality per token |+| DeepSeek V4 Pro | `deepseek-ai/deepseek-v4-pro` | reasoning | Deep reasoning, hosted on NIM |+| Kimi K2.6 | `moonshotai/kimi-k2.6` | flagship | Moonshot long-context agentic model |+| Llama 4 Maverick | `meta/llama-4-maverick-17b-128e-instruct` | balanced | Meta's 128-expert MoE — fast, multimodal-capable |+| MiniMax M2.7 | `minimaxai/minimax-m2.7` | balanced | General reasoning and chat |++For anonymous (signed-out) callers, only the genuinely free tiers — the OpenRouter open-weight default plus these NVIDIA NIM models — are selectable. Each shows "unavailable" until the key is set, and `meta/llama-3.3-nemotron-super-49b-v1.5` also appears in the routing catalog as a tool-capable fallback model.++> **Where the line is:** Nemotron and the `nvidia/…`-prefixed models are NVIDIA's own. The others in this table (DeepSeek, Kimi, Llama 4, MiniMax) are third-party open weights that NVIDIA *hosts and serves free* on NIM — so they ride the same key, but the model itself isn't NVIDIA's. The point of NIM is exactly this: one free key, a whole model garden.++---++## 4. Vision / VLM — image understanding++**Models (in order):** `nvidia/nemotron-nano-12b-v2-vl` → `meta/llama-3.2-11b-vision-instruct`+**Source:** [api/_lib/vision.js](api/_lib/vision.js).++Two free NIM vision lanes on the OpenAI-compatible chat host. Nemotron Nano VL leads because it carries the **smallest image-token footprint** (~281 prompt tokens for a small image vs ~1600 for a 90B-class model); the Llama 3.2 11B vision model is a different family, so its failure modes are independent — a true fallback, not a retry. Images pass as an http(s) URL (the model server fetches it) with SSRF validation on the URL before it leaves the box.++**Where it's used:**+- **Forge photo pre-check** — before a generation slot is spent, the uploaded photo is screened: a screenshot of text, a cluttered subject-less scene, or a too-dark image gets a heads-up and a fix (with a one-click "Generate anyway").+- **Fact Checker image evidence** — reads a picture alongside a claim, transcribes any text in it, and weighs it in the verdict.+- **Avatar gallery alt-text** — writes real, descriptive alt text from each avatar's thumbnail for screen-reader users.++All three **fail safe**: if the vision lane is unavailable, the feature quietly switches off — it never blocks or breaks the primary flow.++---++## 5. Embeddings — semantic retrieval++**Primary:** `nvidia/nv-embedqa-e5-v5` (1024-dim) · **Endpoint:** `integrate.api.nvidia.com/v1/embeddings`+**Source:** [api/_lib/embeddings.js](api/_lib/embeddings.js) (tag `nvidia/nv-embedqa-e5-v5@1024`).++The default embedder for new vectors — **free with the one key, 1024 dimensions, hard-capped at 512 input tokens** (longer inputs are rejected upstream, so callers chunk to fit). Vectors are tagged with `model@dimension` so a later model swap can't silently mix incompatible spaces. Powers **agent memory and knowledge-widget retrieval**; the paid embedding provider is demoted to backup behind it.++**Also:** `baai/bge-m3` — a second NIM-hosted embedder used by [api/agents/_id/embed.js](api/agents/_id/embed.js) for the agent-embed path.++---++## 6. Reranking — sharpening retrieval++**Model:** `nvidia/rerank-qa-mistral-4b` · **Endpoint:** `ai.api.nvidia.com/v1/retrieval/nvidia/reranking`+**Source:** [api/_lib/rerank.js](api/_lib/rerank.js).++Cosine-over-embeddings recall is cheap but coarse. This **cross-encoder reranker** re-scores the top passages so the most relevant context leads. It is **opt-in** (`KNOWLEDGE_RERANK_ENABLED=1` plus the NVIDIA key) and **strictly fail-open** — any rerank error keeps the original cosine ordering. Reranking may improve retrieval but may never break it. Used to refine knowledge-widget answers.++---++## 7. Content safety — NemoGuard++**Primary:** `nvidia/llama-3.1-nemoguard-8b-content-safety` · **Drop-in alt:** `meta/llama-guard-4-12b`+**Endpoint:** `integrate.api.nvidia.com/v1/chat/completions` · **Source:** [api/_lib/moderation.js](api/_lib/moderation.js).++A free content-safety pre-filter for anonymous chat. NemoGuard classifies the inbound user message and returns a **JSON verdict plus named risk categories** (harm, self-harm, weapons, sexual content, …); the parser also accepts Llama Guard's `unsafe\nS#` text form, which is why the two are interchangeable. Median ~340 ms on the free tier.++**Scope and posture:** it is a *content*-safety classifier, **not** a jailbreak / prompt-injection detector. It is **fail-open** — anything it can't parse returns "not flagged" so a moderation outage never takes chat down. Only a clean parsed "unsafe" verdict blocks a message.++---++## 8. Text-to-speech — Magpie (Riva)++**Model:** `magpie-tts-multilingual` · **Transport:** Riva gRPC at `grpc.nvcf.nvidia.com:443`+**Source:** [api/_lib/tts-nvidia.js](api/_lib/tts-nvidia.js) (mirrored in `packages/avatar-agent-mcp/src/lib/tts-nvidia.js`).++The free NVIDIA TTS lane — **Magpie multilingual on Riva**, selected by an NVCF `function-id`, speaking over the standard Riva gRPC synthesis contract (protos shipped in `riva-protos/` and loaded from a generated descriptor, so there's no `.proto` build step). Drives **avatar speech** with multilingual voices. Configured by the presence of `NVIDIA_API_KEY`; returns synthesized audio bytes, with a clear error if the lane returns empty audio.++---++## Design principles across every lane++1. **Free-first, always.** NVIDIA NIM leads its category (or sits in a free trio with Groq/OpenRouter) before any paid model is touched. Cost to the platform is $0.+2. **One key, whole layer.** `NVIDIA_API_KEY` is the only credential. Present → the layer is live; absent → every consumer degrades to its next lane or switches off cleanly.+3. **Fail-open / fail-safe.** Safety, rerank, and vision never break the primary flow — a NVIDIA outage downgrades quietly, it doesn't error the user.+4. **Independent fallbacks.** Where reliability matters, the fallback is a *different model family* (vision) or a *different provider* (chat), not a retry of the same thing.+5. **It's a free tier, not an SLA.** Rate-limited, no uptime guarantee — great for the default path precisely because there's always something behind it.++---++## Environment++| Variable | Unlocks |+| --- | --- |+| `NVIDIA_API_KEY` | Every model on this page (`nvapi-…` from build.nvidia.com) |+| `KNOWLEDGE_RERANK_ENABLED=1` | Turns on the rerank stage (§6) |+| `FORGE_PREFER_FREE` | Free-first reconstruct ordering (default on) |++Probe transcripts for every lane — request/response shapes, limits, verified behavior — live under `tasks/nvidia-nim/probes/`.++---++<a id="sec-157"></a>++> **Source:** `docs/onboarding/ONBOARDING-PLAN-2026-06-19.md` · [↑ table of contents](#table-of-contents)++# three.ws Onboarding Plan++_Date: 2026-06-19 · Owner: platform · Status: Phase 1 in progress_++## Goal++Turn the existing, scattered onboarding pieces into one coherent first-run journey+with a single source of truth for progress. Optimize the **consumer creator** path+(Create → Brain → Embed) as the default, with the **agent-economy** path+(wallet · fund · x402 · monetize) as an opt-in branch that unlocks only when the+user reaches for it. No upfront crypto friction.++## What already exists (do not rebuild)++- **Floating guide** — [public/getting-started.js](../../public/getting-started.js):+ welcome modal + resumable checklist (create/brain/embed core, onchain/monetize+ optional). Public API: `window.__twsGuide.complete(id)` and the+ `three-ws:guide` CustomEvent. Progress in `localStorage['tws-guide:progress']`.+- **Dashboard onboarding panel** — [renderOnboarding()](../../src/dashboard-next/pages/home.js):+ derives step completion from real server data (`avatars`, `agents`, `widgets`).+- **Setup wizard** — [pages/start.html](../../pages/start.html).+- **Post-creation banner** — [pages/app.html](../../pages/app.html) (`#agent-onboarding`).+- **IRL permission onboarding** — [src/irl/onboarding.js](../../src/irl/onboarding.js) (self-contained).+- **Shared state primitives** — [src/shared/state-kit.js](../../src/shared/state-kit.js).++## The three real gaps++1. **Two disconnected progress systems.** The dashboard panel knows the truth from+ the server; the floating guide only guesses from the current route. They drift —+ a user with an avatar + agent can see "2 of 4" on the dashboard and "0/3" in the+ floating pill on the same session.+2. **No funding onboarding.** Users are told "pay with a Base/Solana wallet" but are+ never shown how to get USDC.+3. **No x402 first-run context.** The payment modal appears with zero explanation.++## Plan++### Phase 1 — Unify the spine _(in progress)_++Make the dashboard (which holds authoritative server state) the reconciler that+keeps the floating guide honest, and replace fragile route-detection with precise+completion signals.++- **Reconcile guide from server truth.** On dashboard boot, after fetching+ avatars/agents/widgets, emit `window.__twsGuide.complete()` for each genuinely+ completed step (avatar→`create`, agent→`brain`, widget→`embed`). Runs even when+ the panel is dismissed — reconciliation is data sync, not UI.+ → [src/dashboard-next/pages/home.js](../../src/dashboard-next/pages/home.js)+- **Precise brain completion.** Fire `three-ws:guide` step `brain` when a persona is+ actually saved to an agent, not merely when `/brain` is visited.+ → [src/dashboard-next/pages/brain.js](../../src/dashboard-next/pages/brain.js)+- **Bidirectional panel sync.** The dashboard panel reflects guide progress for the+ optional `monetize` step so completion reached on another surface ticks here too.+ → [src/dashboard-next/pages/home.js](../../src/dashboard-next/pages/home.js)++**Acceptance:** create an avatar + agent, never open the floating pill, visit the+dashboard → the pill reads the correct core count. Save a persona to an agent → the+`brain` step ticks without visiting any detection route. No console errors.++### Phase 2 — Close the funding gap (consumer + economy)++- Surface the `fund` skill as a designed step (how to get USDC on Base/Solana, what+ it costs, why) instead of a bare payment prompt.+- Activate it as an opt-in checklist branch only when the user triggers a+ monetize/x402 action — progressive disclosure, never upfront.+- Touchpoints: [src/dashboard-next/pages/monetize.js](../../src/dashboard-next/pages/monetize.js),+ [pages/agent-wallet.html](../../pages/agent-wallet.html).++### Phase 3 — x402 first-run explainer (economy track)++- One-time, dismissible intro on the first x402 payment: what a micropayment is,+ what's being paid, that it settles in USDC. Match the IRL onboarding card pattern.+- Touchpoints: [pages/club.html](../../pages/club.html), [pages/shopper.html](../../pages/shopper.html).++### Phase 4 — Polish + empty states++- Replace minimal empty states (monetize/agents/widgets) with "here's your next+ action" disclosure via [src/shared/state-kit.js](../../src/shared/state-kit.js).+- Quality wins: keyboard nav through the checklist, hover/active/focus states,+ transitions on step completion.++## Step-id mapping (canonical)++| Guide step (`getting-started.js`) | Dashboard panel | Server-truth source |+| --------------------------------- | --------------- | -------------------------- |+| `create` | avatar | `avatars.length > 0` |+| `brain` | agent | persona saved / `agents` |+| `embed` | widget | `widgets.length > 0` |+| `onchain` (optional) | — | deploy/onchain surface |+| `monetize` (optional) | monetize | guide progress / monetize |++---++<a id="sec-158"></a>> **Source:** `docs/onchain-agents.md` · [↑ table of contents](#table-of-contents)@@ -24899,7 +28156,7 @@ A confirmed canary asset shows `inCollection=true`, `royalty=500bps`, `attrs=11`----<a id="sec-136"></a>+<a id="sec-159"></a>> **Source:** `docs/ops/forge-multiview-migration-handoff.md` · [↑ table of contents](#table-of-contents)@@ -24985,7 +28242,7 @@ So the documented commands are known-good; the only remaining variable is prod c----<a id="sec-137"></a>+<a id="sec-160"></a>> **Source:** `docs/ops/redis.md` · [↑ table of contents](#table-of-contents)@@ -25262,7 +28519,7 @@ curl -s "https://three.ws/api/builds?mint=<mint>" | jq '.builds | length'----<a id="sec-138"></a>+<a id="sec-161"></a>> **Source:** `docs/pay-skills-listing.md` · [↑ table of contents](#table-of-contents)@@ -25364,7 +28621,7 @@ are supported.----<a id="sec-139"></a>+<a id="sec-162"></a>> **Source:** `docs/permissions.md` · [↑ table of contents](#table-of-contents)@@ -25745,7 +29002,7 @@ Set `SMOKE_SKIP_REVOKE=1` to skip the on-chain revocation step if the test walle----<a id="sec-140"></a>+<a id="sec-163"></a>> **Source:** `docs/persona-hub.md` · [↑ table of contents](#table-of-contents)@@ -26142,7 +29399,7 @@ JWT claims:----<a id="sec-141"></a>+<a id="sec-164"></a>> **Source:** `docs/popular-3d-github-repos.md` · [↑ table of contents](#table-of-contents)@@ -26405,7 +29662,7 @@ Apply a 3D-signal regex filter over `description + topics` and a denylist of non----<a id="sec-142"></a>+<a id="sec-165"></a>> **Source:** `docs/pump-fun-mcp-edge.md` · [↑ table of contents](#table-of-contents)@@ -26461,7 +29718,7 @@ Both runtimes import `TOOLS` from `src/pump/mcp-tools.js`, so the tool list expo----<a id="sec-143"></a>+<a id="sec-166"></a>> **Source:** `docs/pump-fun-skills-audit.md` · [↑ table of contents](#table-of-contents)@@ -26490,7 +29747,7 @@ The SKILL.md describes three key SDK operations from `@pump-fun/agent-payments-s----<a id="sec-144"></a>+<a id="sec-167"></a>> **Source:** `docs/pump-platform-fee.md` · [↑ table of contents](#table-of-contents)@@ -26551,7 +29808,7 @@ The fee is **never** charged silently. When `platform_fee_bps > 0`:----<a id="sec-145"></a>+<a id="sec-168"></a>> **Source:** `docs/pumpfun-program/AUDIT-2026-06-08.md` · [↑ table of contents](#table-of-contents)@@ -26821,7 +30078,7 @@ receives a `quoteMint`-aware `amount` (GAP-B fix above).----<a id="sec-146"></a>+<a id="sec-169"></a>> **Source:** `docs/pumpfun-program/AUDIT-2026-06-11.md` · [↑ table of contents](#table-of-contents)@@ -27082,7 +30339,7 @@ launch + confirm) is quote-agnostic. This pass materially hardened that support:----<a id="sec-147"></a>+<a id="sec-170"></a>> **Source:** `docs/pumpfun-program/README.md` · [↑ table of contents](#table-of-contents)@@ -27140,7 +30397,7 @@ tracked in `tasks/pumpfun-upstream/01-v2-trade-instructions-usdc-audit.md`.----<a id="sec-148"></a>+<a id="sec-171"></a>> **Source:** `docs/pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md` · [↑ table of contents](#table-of-contents)@@ -27244,7 +30501,7 @@ Currently, no quote mint other than native SOL can be used to create or trade co----<a id="sec-149"></a>+<a id="sec-172"></a>> **Source:** `docs/pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md` · [↑ table of contents](#table-of-contents)@@ -27318,7 +30575,7 @@ The new accounts can be passed before the program upgrade happens on Monday. The----<a id="sec-150"></a>+<a id="sec-173"></a>> **Source:** `docs/pumpfun-program/docs/CPI_README.md` · [↑ table of contents](#table-of-contents)@@ -27422,7 +30679,7 @@ pump-rust-client = { version = "...", path = "..." }----<a id="sec-151"></a>+<a id="sec-174"></a>> **Source:** `docs/pumpfun-program/docs/FAQ.md` · [↑ table of contents](#table-of-contents)@@ -27439,33 +30696,17 @@ Each buy / sell instruction used CUs depend on all the inputs of the instructionmore CUs to log than smaller values.- for sell inputs, it's similar.-As an example, for the-tx https://solscan.io/tx/5frph8gBFyX7ayBmqntvwpTPwzZ8aF4kdfJAvC52Li2iDnnaRwtmcZP839Cm4YQUFx7GzsUUStCfAy3hAG69ir4u:--```Rust- let mint = Pubkey::from_str("Coyj3LtKn1BNSgWc9HsGK5SKoGfEoDaymig4wrN6pump").unwrap();--assert_eq!(- Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1,- 255-);-```--The `bonding_curve` bump seed for mint `Coyj3LtKn1BNSgWc9HsGK5SKoGfEoDaymig4wrN6pump` is `255`.--While for the-tx https://solscan.io/tx/5xozUcJFvRj4ySpE2epSSs95ySxs6cLjs1rV2uaFNkFgsEMBZW53VUa2uc3CVQLVJRYxfQ5JoSzZLiUvAgM4GEJM:+The `bonding_curve` (and the other) PDA bump seed is derived from the mint pubkey, so it differs for every mint:```Rust- let mint = Pubkey::from_str("3cLSxG6eXcCD9NSMawkhUcrvVCUC8KHKHMCxx6bhpump").unwrap();--assert_eq!(- Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1,- 251-);+ // `mint` is the SPL mint of the token being traded.+ let bump = Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1;```-The `bonding_curve` bump seed for mint `3cLSxG6eXcCD9NSMawkhUcrvVCUC8KHKHMCxx6bhpump` is `251`.+Different mints yield different bump seeds (commonly `255`, but `254`, `253`, … occur),+and the number of search iterations `find_program_address` performs to land on a valid+bump is itself part of the instruction's CU cost — so two trades of identical size can+consume different CUs solely because their mint/user/creator PDAs derive at different bumps.So it is not possible to compute the used CUs without first simulating the buy / sell tx before submission and adding abuffer of 1% to the simulated CUs, because buy instruction executes a bit more code when the bonding curve completes on@@ -27476,7 +30717,7 @@ is recommended to use a static big enough CU limit like `100_000`.----<a id="sec-152"></a>+<a id="sec-175"></a>> **Source:** `docs/pumpfun-program/docs/FEE_PROGRAM_README.md` · [↑ table of contents](#table-of-contents)@@ -27691,7 +30932,7 @@ If you implement the fee logic correctly, any future change to the fee tiers str----<a id="sec-153"></a>+<a id="sec-176"></a>> **Source:** `docs/pumpfun-program/docs/FEE_RECIPIENTS.md` · [↑ table of contents](#table-of-contents)@@ -27754,7 +30995,7 @@ Use one of these as `buybackFeeRecipient` for any coin.----<a id="sec-154"></a>+<a id="sec-177"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_CASHBACK_README.md` · [↑ table of contents](#table-of-contents)@@ -27871,7 +31112,7 @@ To read unclaimed cashback for pump swap / Pump AMM program:----<a id="sec-155"></a>+<a id="sec-178"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md` · [↑ table of contents](#table-of-contents)@@ -28006,7 +31247,7 @@ we update the programs on Mainnet.----<a id="sec-156"></a>+<a id="sec-179"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_PROGRAM_README.md` · [↑ table of contents](#table-of-contents)@@ -28207,7 +31448,7 @@ at https://solscan.io/account/EsmVk4MTsoT71JFaRM5DWFZboKpMQjfY6EYzAgUuksXw#accou----<a id="sec-157"></a>+<a id="sec-180"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md` · [↑ table of contents](#table-of-contents)@@ -28316,7 +31557,7 @@ PumpSwap program on Mainnet to the coin creator fee update.----<a id="sec-158"></a>+<a id="sec-181"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_README.md` · [↑ table of contents](#table-of-contents)@@ -28404,7 +31645,7 @@ at https://solscan.io/account/GseMAnNDvntR5uFePZ51yZBXzNSn7GdFPkfHwfr6d77J#accou},"base_mint": {"type": "pubkey",- "data": "7LSsEoJGhLeZzGvDofTdNg7M3JttxQqGWNLo6vWMpump"+ "data": "EXAMPLEpumpfunBaseMint1111111111111111pump"},"quote_mint": {"type": "pubkey",@@ -28550,7 +31791,7 @@ Each Anchor instruction has a set of corresponding autocomplete methods that can----<a id="sec-159"></a>+<a id="sec-182"></a>> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_SDK_README.md` · [↑ table of contents](#table-of-contents)@@ -28630,7 +31871,7 @@ to autocomplete the `base` and `quote` displayed amounts based on the `lpToken`----<a id="sec-160"></a>+<a id="sec-183"></a>> **Source:** `docs/pumpfun-program/docs/instructions/BUY.md` · [↑ table of contents](#table-of-contents)@@ -28808,7 +32049,7 @@ ixs.extend(----<a id="sec-161"></a>+<a id="sec-184"></a>> **Source:** `docs/pumpfun-program/docs/instructions/CLAIM_CASHBACK.md` · [↑ table of contents](#table-of-contents)@@ -28918,7 +32159,7 @@ let ix = sdk.claim_cashback_v2_instruction(----<a id="sec-162"></a>+<a id="sec-185"></a>> **Source:** `docs/pumpfun-program/docs/instructions/COIN_CREATION.md` · [↑ table of contents](#table-of-contents)@@ -29073,7 +32314,7 @@ let ixs = sdk----<a id="sec-163"></a>+<a id="sec-186"></a>> **Source:** `docs/pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md` · [↑ table of contents](#table-of-contents)@@ -29175,7 +32416,7 @@ ixs.extend(sdk.collect_creator_fee_v2_instructions(----<a id="sec-164"></a>+<a id="sec-187"></a>> **Source:** `docs/pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md` · [↑ table of contents](#table-of-contents)@@ -29529,7 +32770,7 @@ ixs.extend(sdk.distribute_creator_fees_v2_instructions(----<a id="sec-165"></a>+<a id="sec-188"></a>> **Source:** `docs/pumpfun-program/docs/instructions/SELL.md` · [↑ table of contents](#table-of-contents)@@ -29706,7 +32947,7 @@ ixs.extend(----<a id="sec-166"></a>+<a id="sec-189"></a>> **Source:** `docs/quick-start.md` · [↑ table of contents](#table-of-contents)@@ -29999,7 +33240,72 @@ If you're embedding inside a sandboxed iframe, make sure the parent grants `allo----<a id="sec-167"></a>+<a id="sec-190"></a>++> **Source:** `docs/repo-hygiene-audit.md` · [↑ table of contents](#table-of-contents)++# Repo hygiene audit — 2026-06-19++A pass over the "table stakes" every serious project should have: GitHub community+health, repository config, SEO/agent discoverability, and social/metadata wiring.+The platform was already strong on most fronts — this records what existed, what+was missing, what was added in this pass, and what still needs a human (it can't be+automated from the repo).++## Already in place (verified, no action needed)++- **Licensing & conduct**: `LICENSE` (Apache-2.0), `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`.+- **Changelog**: curated `data/changelog.json` → `CHANGELOG.md` + `public/changelog.{json,xml}`, with Telegram push (`npm run changelog:push`).+- **SEO / crawler**: `public/robots.txt`, dynamic sitemap via `/api/sitemap` + `/api/sitemap/[type]` (rewritten from `/sitemap.xml`), human-readable `/sitemap` page.+- **Agent discoverability**: `public/llms.txt`, `public/llms-full.txt` (llmstxt.org standard).+- **Security disclosure**: `public/.well-known/security.txt` (securitytxt.org), Solana `actions.json`, chat-plugin manifest.+- **PWA**: `public/site.webmanifest`, favicons (`favicon.ico`, `favicon.svg`, `apple-touch-icon.png`).+- **Editor / formatting**: `.editorconfig`, `.prettierrc.json`, `.prettierignore`, `eslint.config.js`, `knip.config.js`.+- **Dependency automation**: `renovate.json` (Renovate is the configured updater — Dependabot is intentionally **not** used to avoid duplicate PRs).+- **Per-commit gate**: `.githooks/pre-push` runs `npm run typecheck` (wired via `core.hooksPath` in `npm run setup`).+- **Node version**: `engines.node` pinned to `24.x` in `package.json`.+- **People/credits**: `public/humans.txt`.++> **Note on CI:** GitHub Actions are unavailable on this account by design. The Vercel+> build + the `pre-push` typecheck hook are the automated gates. No workflow files+> were added — they would not run. This is deliberate, not an oversight.++## Added in this pass++### GitHub community-health files (`.github/`) — these render on GitHub without Actions++- `ISSUE_TEMPLATE/bug_report.yml` — structured bug form (area dropdown, repro, console output).+- `ISSUE_TEMPLATE/feature_request.yml` — structured feature form (problem → solution → alternatives).+- `ISSUE_TEMPLATE/config.yml` — disables blank issues; routes to Discussions, the private security advisory flow, X, and docs.+- `PULL_REQUEST_TEMPLATE.md` — wired to the CLAUDE.md Definition of Done and the changelog rule.+- `SECURITY.md` — GitHub-rendered security policy mirroring `security.txt` (private advisories + [email protected]).+- `CODEOWNERS` — default + high-blast-radius paths (contracts, payment rails, published SDKs, MCP server).+- `FUNDING.yml` — coin-agnostic Sponsor button linking to the product (never a token).++### Repository config++- `.nvmrc` — `24`, matching `engines.node`, so `nvm`/`fnm`/Vercel pick the right runtime.+- `.gitattributes` — LF normalization, LF-locked shell/hooks, binary handling for 3D/media assets, and `linguist-generated`/`-diff` on lockfile + generated outputs (cleaner diffs and accurate GitHub language stats).++### Metadata corrections++- `package.json`: replaced the stale "drag-and-drop glTF/GLB preview tool" description with the actual platform description; added `homepage`, `repository`, and `bugs`; refreshed `keywords`.+- `public/humans.txt`: added the official X handle (`https://x.com/trythreews`).++## Needs a human (cannot be automated from the repo)++These are real, basic-but-important items that live in external dashboards, not the codebase:++- **GitHub repo settings**: confirm Discussions, Issues, and the Security tab are enabled; add a repo description + topics; set the social preview image (Settings → Options → Social preview).+- **Branch protection** on `main` (requires the GitHub UI; note that without Actions there are no required status checks, so rely on the pre-push hook + Vercel).+- **Social profiles**: ensure X (`@trythreews`), Telegram, and any Discord are linked consistently from the site footer and profiles, with matching avatars/banners.+- **`security.txt` expiry**: currently `2027-04-14` — renew before it lapses.+- **Monitoring/status**: a public status page or uptime monitor for the API, if not already external.+- **Analytics & error tracking**: confirm a privacy-respecting analytics + error-reporting pipeline is live in production.++---++<a id="sec-191"></a>> **Source:** `docs/reputation.md` · [↑ table of contents](#table-of-contents)@@ -30195,7 +33501,7 @@ See the [Validation](./validation.md) documentation for details.----<a id="sec-168"></a>+<a id="sec-192"></a>> **Source:** `docs/roadmap/3d-world-fun.md` · [↑ table of contents](#table-of-contents)@@ -30413,7 +33719,7 @@ have one agent own the shared file per wave.----<a id="sec-169"></a>+<a id="sec-193"></a>> **Source:** `docs/roadmap/coin-intelligence-engine.md` · [↑ table of contents](#table-of-contents)@@ -30503,7 +33809,7 @@ All SOL stored as lamports (`numeric(40,0)`) to match the rest of the sniper sch----<a id="sec-170"></a>+<a id="sec-194"></a>> **Source:** `docs/roadmap/creation-consolidation.md` · [↑ table of contents](#table-of-contents)@@ -30724,7 +34030,7 @@ Redirects live in `vercel.json` routes. Also update `data/pages.json` (feeds sit----<a id="sec-171"></a>+<a id="sec-195"></a>> **Source:** `docs/roadmap/developer-resources-repos.md` · [↑ table of contents](#table-of-contents)@@ -30780,7 +34086,7 @@ These are why the obvious approach ("just push copies to new repos") fails here.1. **No CI on this account.** GitHub Actions are unavailable (all workflows deleted 2026-06-11). The standard satellite-sync pattern — a workflow pushing subtrees on every merge — cannot run. Sync must be a local script invoked from the existing push routine, or satellites rot.2. **Mirror maintenance already bites.** We maintain one mirror (`nirholas/3D-Agent`, push-only) and it has caused destructive history merges. Every additional repo multiplies that class of risk. Satellites must be strictly one-way exports, never pulled from.-3. **~~npm packages 404.~~ RESOLVED (2026-06-13).** All public packages are now published on npm under the single `@three-ws/*` scope, and all 14 MCP servers (8 stdio + 6 remote) are registered in the official MCP registry. `npm install @three-ws/sdk` and `npx -y @three-ws/mcp-server` now work, so an examples repo no longer fails on its first instruction.+3. **~~npm packages 404.~~ RESOLVED (2026-06-13).** All public packages are now published on npm under the single `@three-ws/*` scope, and all 20 MCP servers (14 stdio + 6 remote) are registered in the official MCP registry. `npm install @three-ws/sdk` and `npx -y @three-ws/mcp-server` now work, so an examples repo no longer fails on its first instruction.4. **A stale satellite is worse than none.** Broken examples in a standalone repo are anti-marketing. Anything we publish must be smoke-tested by the export script before it pushes.---@@ -30881,7 +34187,7 @@ If `NPM_TOKEN` is delayed: ship Phase 2 against hosted endpoints only, add npm-i----<a id="sec-172"></a>+<a id="sec-196"></a>> **Source:** `docs/roadmap/generation-suite.md` · [↑ table of contents](#table-of-contents)@@ -31023,7 +34329,7 @@ What they have that we don't (or that we hide). Ordered by user impact.----<a id="sec-173"></a>+<a id="sec-197"></a>> **Source:** `docs/roadmap/pumpfun-social-trading.md` · [↑ table of contents](#table-of-contents)@@ -31387,7 +34693,7 @@ Trading pump.fun stops being a lonely gamble and becomes a social game with prov----<a id="sec-174"></a>+<a id="sec-198"></a>> **Source:** `docs/roadmap/pumpfun-trading-arena.md` · [↑ table of contents](#table-of-contents)@@ -31745,7 +35051,7 @@ That loop, done so well people can't not talk about it, is the whole plan.----<a id="sec-175"></a>+<a id="sec-199"></a>> **Source:** `docs/roadmap/pumpfun-trading-wedge.md` · [↑ table of contents](#table-of-contents)@@ -32077,7 +35383,7 @@ agents are actively editing — needs a clean, owned pass.----<a id="sec-176"></a>+<a id="sec-200"></a>> **Source:** `docs/roadmap/pumpfun-trading.md` · [↑ table of contents](#table-of-contents)@@ -33110,7 +36416,314 @@ promises, no token other than this one or $THREE.----<a id="sec-177"></a>+<a id="sec-201"></a>++> **Source:** `docs/sas-attestations.md` · [↑ table of contents](#table-of-contents)++# SAS Credentialed Attestations++three.ws issues two kinds of on-chain attestations on Solana:++- **Permissionless attestations** — general feedback, task lifecycle, dispute, and revoke events. Anyone can write them as SPL Memos (see [Solana reputation](solana-reputation)).+- **Credentialed attestations** — claims only three.ws or an authorized validator may make: that a wallet is verified, or that a validator audited an agent's task result. These use the [Solana Attestation Service (SAS)](https://attest.solana.com/) and are signed by the **three.ws authority wallet**.++This page covers the authority wallet, the `SAS_AUTHORITY_SECRET` environment variable, bootstrapping the credential + schemas, and the API that issues them.++---++## The authority wallet++Every credentialed attestation is signed by a single Solana keypair — the **authority**. That keypair:++- Pays rent for the credential and schema accounts (one-time, at bootstrap).+- Owns the credential, so it can later authorize additional signers via `changeAuthorizedSigners`.+- Signs (and pays fees for) every attestation issued under the three.ws schemas.+- Is the only key that can close (revoke) an attestation it issued.++The server loads it from the `SAS_AUTHORITY_SECRET` environment variable — see [api/_lib/sas.js](../api/_lib/sas.js).++---++## `SAS_AUTHORITY_SECRET`++The **base58-encoded 64-byte secret key** of the authority keypair. This is the Phantom/Solflare "export private key" format, *not* the JSON byte array that `solana-keygen` writes to disk.++```+SAS_AUTHORITY_SECRET=<base58 secret key>+```++It is decoded with `bs58.decode()` and passed to `createKeyPairSignerFromBytes()`. If it is missing, any attempt to issue or close an attestation throws `SAS_AUTHORITY_SECRET not configured`.++> **This is a private key. Treat it as a secret.**+> - Never commit it, and never commit a `*.json` keypair file. Keep both out of git.+> - Use **separate keypairs for devnet and mainnet** so a devnet leak can never touch mainnet funds.+> - Use the **same keypair for bootstrap and runtime** on a given network — a different key cannot issue under the credential the first key created.++### Generating a keypair++**With the Solana CLI** (recommended for production — produces a real, fundable wallet):++```bash+solana-keygen new --no-bip39-passphrase --outfile authority.json+# Convert the 64-byte array to the base58 form SAS_AUTHORITY_SECRET expects:+node -e "import('bs58').then(({default:b})=>console.log(b.encode(Uint8Array.from(require('./authority.json')))))"+```++**Without any dependencies** (built-in `crypto` only — handy in a clean shell):++```bash+node --input-type=module -e '+import { generateKeyPairSync } from "node:crypto";+const A="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";+const b58=u=>{let z=0;while(z<u.length&&!u[z])z++;const d=[0];for(let i=z;i<u.length;i++){let c=u[i];for(let j=0;j<d.length;j++){c+=d[j]<<8;d[j]=c%58;c=c/58|0}while(c){d.push(c%58);c=c/58|0}}return "1".repeat(z)+d.reverse().map(x=>A[x]).join("")};+const{publicKey,privateKey}=generateKeyPairSync("ed25519");+const seed=privateKey.export({format:"der",type:"pkcs8"}).subarray(-32);+const pub =publicKey .export({format:"der",type:"spki" }).subarray(-32);+console.log("PUBKEY:", b58(pub));+console.log("SECRET:", b58(Buffer.concat([seed,pub])));+'+```++The `SECRET:` line is the value for `SAS_AUTHORITY_SECRET`; the `PUBKEY:` line is the address you fund.++### Vanity addresses (optional)++To make the authority address recognizable (e.g. starting with `3ws` or `www`), grind keypairs until the base58 public key matches a prefix. With the CLI:++```bash+solana-keygen grind --starts-with 3ws:1 --ignore-case+```++`--ignore-case` matches the prefix case-insensitively, which is much faster. Base58 excludes the characters `0`, `O`, `I`, and `l`, so a prefix cannot contain them. Cost grows ~58× per added character: 3 characters resolve in seconds, 4 in a minute or two, 5+ can take much longer.++---++## Bootstrap (one-time per network)++Registering the credential and schemas is idempotent — existing accounts are left untouched, so the script is safe to re-run.++1. **Fund the authority wallet** with ~0.05 SOL on the target cluster (covers one credential plus the schemas). Devnet: [faucet.solana.com](https://faucet.solana.com). Mainnet: send real SOL to the address.++2. **Run the bootstrap** ([scripts/sas-bootstrap.js](../scripts/sas-bootstrap.js)):++ ```bash+ SAS_AUTHORITY_SECRET=<base58 secret key> node scripts/sas-bootstrap.js devnet+ # or: ... node scripts/sas-bootstrap.js mainnet+ ```++ On success it writes the derived PDAs into [sdk/src/sas-config.json](../sdk/src/sas-config.json). Do not edit that file by hand — re-run bootstrap to refresh it. Commit the updated config so the server knows the credential/schema addresses.++3. **Set the env var in each environment.** Locally, add it to `.env`. On Vercel:++ ```bash+ vercel env add SAS_AUTHORITY_SECRET+ ```++ Use the devnet key for Preview and the mainnet key for Production. Redeploy so functions pick it up.++### Related environment variables++| Variable | Purpose | Default |+|----------|---------|---------|+| `SAS_AUTHORITY_SECRET` | Base58 authority secret key. **Required** to issue/close. | — |+| `SOLANA_RPC_URL` | Mainnet RPC endpoint. | `https://api.mainnet-beta.solana.com` |+| `SOLANA_RPC_URL_DEVNET` | Devnet RPC endpoint. | `https://api.devnet.solana.com` |++A custom RPC (Helius, Triton, QuickNode) is strongly recommended for mainnet — the public endpoint is rate-limited and will fail under load.++---++## Schemas++The schemas three.ws registers live in [sdk/src/sas-config.json](../sdk/src/sas-config.json). Two ship today:++### `threews.verified-client.v1`++A wallet has been verified by three.ws (KYC, payment history, or a trusted introduction). Subject = the client wallet pubkey. Used to weight feedback attestations.++| Field | Type | Meaning |+|-------|------|---------|+| `method` | string | Verification method, e.g. `kyc-tier-1`, `payment-history`, `partner:auditor-x`. |+| `reference` | string | Opaque reference id pointing at an off-chain record. |++### `threews.audited-validation.v1`++A validation of an agent task result, issued by an authorized validator. Subject = the agent asset pubkey. Carries higher weight than a self-attested validation.++| Field | Type | Meaning |+|-------|------|---------|+| `task_hash` | string | Hash of the task input/output bundle. |+| `passed` | bool | Whether the validator considers the work acceptable. |+| `report_uri` | string | Link to the validator's full report (Arweave/IPFS/HTTPS). |++---++## API++The endpoint is [api/agents/sas/[action].js](../api/agents/sas/[action].js).++### Read credentials — `GET /api/agents/sas/credentials`++Public, rate-limited. Returns active (non-closed, non-expired) attestations for a subject.++| Query param | Required | Description |+|-------------|----------|-------------|+| `subject` | yes | Base58 pubkey the attestation is about. |+| `network` | no | `mainnet` or `devnet` (default `devnet`). |+| `kind` | no | Filter to one schema, e.g. `threews.verified-client.v1`. |+| `include_closed` | no | `1` to include closed attestations. |++```bash+curl "https://three.ws/api/agents/sas/credentials?subject=<pubkey>&network=mainnet"+```++```json+{ "subject": "<pubkey>", "network": "mainnet", "kind": null, "count": 1, "data": [ /* attestations */ ] }+```++### Issue a credential — `POST /api/agents/sas/issue-credential`++**Admin-only.** Requires admin auth (see [api/_lib/admin.js](../api/_lib/admin.js)) and validates the body against the target schema before signing. On success it issues the attestation on-chain with the authority wallet and records it in the `solana_credentials` table.++```bash+curl -X POST https://three.ws/api/agents/sas/issue-credential \+ -H "Authorization: Bearer <admin-token>" \+ -H "Content-Type: application/json" \+ -d '{+ "kind": "threews.verified-client.v1",+ "subject": "<client-wallet-pubkey>",+ "data": { "method": "kyc-tier-1", "reference": "rec_01H..." },+ "expiry": 0,+ "network": "mainnet"+ }'+```++| Body field | Required | Description |+|------------|----------|-------------|+| `kind` | yes | One of the registered schema kinds. |+| `subject` | yes | Base58 pubkey (32–44 chars) the attestation is about; used as the attestation nonce. |+| `data` | yes | Object whose keys match the schema's `fieldNames`, with the right types. |+| `expiry` | no | Unix seconds; `0` (default) means no expiry. |+| `network` | no | `devnet` (default) or `mainnet`. |++```json+{+ "signature": "<tx-sig>",+ "attestation_pda": "<pda>",+ "schema_pda": "<pda>",+ "credential_pda": "<pda>",+ "kind": "threews.verified-client.v1",+ "subject": "<pubkey>"+}+```++Closing (revoking) an attestation is done server-side via `sasClose()` in [api/_lib/sas.js](../api/_lib/sas.js); only the authority can close.++---++## Troubleshooting++| Symptom | Cause | Fix |+|---------|-------|-----|+| `SAS_AUTHORITY_SECRET not configured` | Env var unset in the running environment. | Set it in `.env` / Vercel and redeploy. |+| `SAS not bootstrapped for <network>` | `sdk/src/sas-config.json` has no PDAs for that network. | Run `scripts/sas-bootstrap.js <network>` and commit the updated config. |+| `schema <kind> not registered on <network>` | Schema added to config but bootstrap not re-run. | Re-run the bootstrap for that network. |+| Bootstrap or issue fails with insufficient funds | Authority wallet not funded on that cluster. | Send SOL to the authority address and retry. |+| Non-base58 / bad key on load | `SAS_AUTHORITY_SECRET` holds the JSON array form, not base58. | Convert the array to base58 (see above) and use that. |++---++<a id="sec-202"></a>++> **Source:** `docs/sdk-launch.md` · [↑ table of contents](#table-of-contents)++# `@three-ws/*` SDK suite — launch runbook++18 zero-dependency, pure-ESM SDKs that wrap already-live three.ws platform+capabilities. Each ships `src/` directly (no build step), hand-written `.d.ts`+types, and a `node --test` suite. They share one byte-identical HTTP core+(`src/http.js`) so error handling, base-URL resolution, and x402 `402` handling+are uniform across the suite.++## The 18++| Package | One-liner | Headline API |+|---|---|---|+| `@three-ws/forge` | text/image/sketch → rig-ready GLB | `forge()`, `rig()`, `catalog()` |+| `@three-ws/names` | ENS/SNS resolve + `*.threews.sol` + pay-by-name | `resolve()`, `mintSubdomain()`, `payByName()` |+| `@three-ws/intel` | token sentiment + market intel | `sentiment()`, `intel()`, `projects()`, `snapshot()` |+| `@three-ws/vanity` | local Solana vanity address mining | `grind()`, `expectedAttempts()` |+| `@three-ws/reputation` | ERC-8004 agent reputation read/attest | `reputation()`, `leaderboard()`, `attest()` |+| `@three-ws/voice` | ASR + TTS + audio2face lipsync | `transcribe()`, `speak()`, `lipsync()`, `say()` |+| `@three-ws/x402-server` | merchant side of x402 | `paid()`, `buildChallenge()`, `verifyPayment()` |+| `@three-ws/agent-memory` | embeddings-backed agent memory | `new AgentMemory()`, `remember()`, `recall()` |+| `@three-ws/agenc` | AgenC coordination protocol client | `listTasks()`, `getTask()`, `getAgent()` |+| `@three-ws/guardian` | content safety / moderation | `check()`, `govern()`, `moderate()` |+| `@three-ws/glb-tools` | inspect / theme / bake GLBs | `inspect()`, `theme()`, `bake()` |+| `@three-ws/agent-guards` | spend + trade guardrails | `policy()`, `guard()` |+| `@three-ws/skill-license` | on-chain skill licenses | `verifyLicense()`, `getLicense()`, `mintLicense()` |+| `@three-ws/mocap` | motion-capture clips → animation | `saveClip()`, `getClip()`, `listClips()` |+| `@three-ws/strategies` | DCA / copy / mirror trading | `dca()`, `copy()`, `mirror()` |+| `@three-ws/pumpfun-skills` | pump.fun create/swap/fees skills | `createCoin()`, `swap()`, `coinFees()` |+| `@three-ws/irl` | geofenced real-world presence | `checkIn()`, `nearby()`, `placePin()` |+| `@three-ws/pose` | pose-seed generation for avatars | `poseSeed()`, `presetPose()` |++## Conventions (all 18, uniform)++- **Pure ESM, ship `src/` directly — no build.** `main`/`module` → `./src/index.js`, `types` → `./src/index.d.ts`.+- **Zero runtime dependencies.** Node 18+ global fetch; works in the browser too.+- **Shared core** `src/http.js` is byte-identical across all 18: `createHttp()`, `ThreeWsError`, `PaymentRequiredError` (402 carries the x402 `accepts` challenge), `resolveBaseUrl()` (option → `THREE_WS_BASE_URL` → `https://three.ws`), `delay()`.+- **Ergonomics:** a `createX(options)` client factory **and** zero-config default functions over a lazy shared client. Responses are camelCased with a `.raw` escape hatch. Inputs validated before any network call.+- **Paid lanes:** pass a payment-aware `fetch` (e.g. `@three-ws/x402-fetch`) to auto-settle `402`s, or catch `PaymentRequiredError` and pay from `err.accepts`.++## Verify the whole suite++```bash+for p in forge names intel vanity reputation voice x402-server agent-memory \+ agenc guardian glb-tools agent-guards skill-license mocap strategies \+ pumpfun-skills irl pose; do+ ( cd packages/$p && node --test test/*.test.js ) || echo "FAIL: $p"+done+```++All green at launch: **216 tests across 18 packages.**++## Pre-publish checklist++1. **Wire workspaces.** Add each `packages/<name>` to the `workspaces` array in+ the root [package.json](../package.json). (Deferred from the build commit to+ avoid racing concurrent edits to that file — do it when the tree is quiescent.)+2. **Run the suite** (command above) — confirm 18/18 green.+3. **Coin scan.** `grep -rniE '\b(bonk|wif|pepe|shib|usdt)\b' packages/*/src packages/*/test` must be empty. The only coin is `$THREE`.+4. **Smoke import** each: `node --input-type=module -e "import('./packages/<name>/src/index.js')"`.+5. **Dry-run publish** per package: `npm publish --dry-run -w packages/<name>` (or from the dir). Confirm `files` ships only `src`, `README.md`, `LICENSE`.++## Publish order++Publish leaves first; nothing in the suite depends on another at runtime (all+zero-dep), so order is for narrative, not resolution. Suggested:++1. `forge` — the flagship.+2. `names`, `voice`, `pose`, `glb-tools`, `mocap` — the avatar/3D cluster (compose with `@three-ws/avatar`).+3. `intel`, `vanity`, `reputation`, `agenc`, `agent-memory`, `guardian`, `agent-guards` — the agent cluster.+4. `x402-server`, `skill-license`, `strategies`, `pumpfun-skills`, `irl` — the payments/onchain cluster.++```bash+cd packages/forge && npm publish --access public+# …repeat per package, or: npm publish -w packages/<name> --access public+```++## On publish++- Add one `sdk`-tagged entry to [data/changelog.json](../data/changelog.json)+ announcing the suite (holder-readable, `$THREE` only), then+ `npm run build:pages` and `npm run changelog:push`.+- Flip the STRUCTURE.md surface-map rows for any promoted package from+ "implemented, pending publish" to `Published as @three-ws/<name>`.++---++<a id="sec-203"></a>> **Source:** `docs/sdk.md` · [↑ table of contents](#table-of-contents)@@ -33537,7 +37150,7 @@ python3 -m http.server 8080----<a id="sec-178"></a>+<a id="sec-204"></a>> **Source:** `docs/security.md` · [↑ table of contents](#table-of-contents)@@ -33886,7 +37499,7 @@ For validator misconduct (biased or falsified on-chain attestations), open a pub----<a id="sec-179"></a>+<a id="sec-205"></a>> **Source:** `docs/security/SECURITY_AUDIT.md` · [↑ table of contents](#table-of-contents)@@ -33942,10 +37555,15 @@ dependency hardening**.- No-fix transitive cluster: `undici`, `bigint-buffer`, `@solana/spl-token`,`@solana/buffer-layout-utils` — track upstream.-**Remediation:** apply the non-breaking `npm audit fix` set now; schedule the-`@metaplex-foundation/[email protected]` breaking bump to clear the axios/form-data/aptos-chain; track the no-fix Solana cluster. **Status: in progress (non-breaking set),-tracked (breaking bump).**+**Remediation:** `npm audit fix --omit=dev` clears ~16 advisories (175 → 159) via+semver-compatible bumps, but in this monorepo it also reformats ~57k lines of+`package-lock.json` (npm version skew) — an unreviewable diff that conflicts with+concurrent work. So dependency bumps are deliberately **isolated to their own PR**:+run `npm audit fix --omit=dev` on a clean branch, review, and land separately.+The `@metaplex-foundation/[email protected]` breaking bump (clears axios/form-data/aptos)+and the no-fix Solana cluster (`undici`, `bigint-buffer`, `@solana/spl-token`)+are tracked upstream. **Status: tracked (isolated dependency PR) — command+verified to reduce counts; not bundled into this security changeset.**---@@ -34190,7 +37808,7 @@ ordered fix plan and status of each item above.----<a id="sec-180"></a>+<a id="sec-206"></a>> **Source:** `docs/security/SECURITY_REMEDIATION.md` · [↑ table of contents](#table-of-contents)@@ -34236,7 +37854,7 @@ Statuses are kept in sync as each item lands.----<a id="sec-181"></a>+<a id="sec-207"></a>> **Source:** `docs/share-and-embed.md` · [↑ table of contents](#table-of-contents)@@ -34333,7 +37951,7 @@ To customize the preview image, change the agent's thumbnail in the editor.----<a id="sec-182"></a>+<a id="sec-208"></a>> **Source:** `docs/skills.md` · [↑ table of contents](#table-of-contents)@@ -35043,7 +38661,7 @@ For IPFS publishing, the CID of the directory becomes the stable URI. Agents can----<a id="sec-183"></a>+<a id="sec-209"></a>> **Source:** `docs/smart-contracts.md` · [↑ table of contents](#table-of-contents)@@ -35636,7 +39254,7 @@ On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs----<a id="sec-184"></a>+<a id="sec-210"></a>> **Source:** `docs/solana-pumpfun.md` · [↑ table of contents](#table-of-contents)@@ -35810,7 +39428,203 @@ The MCP client and cron crawler are unit-tested with mocked `fetch` and `sql`. E----<a id="sec-185"></a>+<a id="sec-211"></a>++> **Source:** `docs/solana-reputation.md` · [↑ table of contents](#table-of-contents)++# Agent Reputation on Solana++How three.ws gives a Solana agent a verifiable, portable trust record — and why it takes two systems, not one.++This is the Solana companion to [Agent Reputation](./agent-reputation.md) (the why) and [ERC-8004](./erc8004.md) / [Reputation System](./reputation.md) (the EVM how-to). If you haven't read those, start with [Agent Reputation](./agent-reputation.md) for the trust problem reputation solves. This page covers how that same problem is solved on Solana, where there is no canonical on-chain reputation registry to inherit.++---++## The Solana problem++On EVM, reputation has a home: the ERC-8004 Reputation Registry is one contract with a `getReputation(agentId)` call. Solana has no equivalent canonical registry. So three.ws builds agent reputation on Solana out of two complementary systems, each suited to a different kind of trust:++| System | Captures | Backed by | Lives where |+|---|---|---|---|+| **Attestation reputation** (the Passport) | What others *say* about an agent — vouches, validations, disputes | SPL Memo + optional SOL stake | On-chain memos → indexed into three.ws |+| **AgenC reputation** | What an agent *did* — tasks completed, work delivered | A Solana coordination program, with escrow + slashing | Fully on-chain (program account) |++An agent identified on Solana by its **Metaplex Core asset pubkey** can accrue both. The rest of this page covers each, then the bridge that ties a Solana identity to its EVM ERC-8004 reputation.++---++## System 1 — Attestation reputation (the Agent Passport)++This is the three.ws-native layer: anyone can leave a permanent, on-chain vouch for an agent, and the [Agent Passport](/agent-passport.html) renders the aggregate as an at-a-glance **A–D trust grade**. It is the Solana analog of leaving an ERC-8004 review.++### How a vouch is written on-chain++There's no custom contract — a vouch is an **SPL Memo** transaction. The reviewer signs a transaction that:++1. Writes a JSON memo via the Memo program (`MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr`), with the agent's asset pubkey attached as a read-only key so the memo is discoverable by `getSignaturesForAddress(asset)`:++ ```jsonc+ {+ "v": 1,+ "kind": "threews.feedback.v1",+ "agent": "<agent asset pubkey>",+ "score": 5, // integer 1–5+ "comment": "fast and accurate",+ "ts": 1750000000+ }+ ```++2. **Optionally stakes** — if the reviewer wants to back the vouch economically, the same transaction includes a `SystemProgram.transfer` of **≥ 0.001 SOL to the agent's owner wallet**, and the memo `kind` becomes `threews.stake.v1`. A staked vouch is harder to fake and weighs more.++Cost is a single Solana fee (~$0.0000+); the optional stake is real SOL that goes to the agent owner. The Passport's rate panel enforces a **double-review guard** — rating the same agent twice from one wallet updates that wallet's score rather than adding a second vote.++### The seven attestation kinds++Every memo is one of these (`api/_lib/solana-attestations.js`):++| Kind | Meaning |+|---|---|+| `threews.feedback.v1` | A 1–5 score (a vouch) |+| `threews.stake.v1` | A score backed by a SOL transfer to the owner |+| `threews.validation.v1` | A pass/fail check — including `glb-schema` (the Solana analog of the EVM ValidationRegistry's glTF attestation) |+| `threews.task.v1` | An agent advertised a task |+| `threews.accept.v1` | The agent owner accepted/acknowledged a task — used to *verify* feedback |+| `threews.dispute.v1` | The owner disputed an attestation against them |+| `threews.revoke.v1` | An attester withdrew their own attestation |++### How attestations become reputation++The raw memos are trustless and re-derivable by anyone. three.ws runs an indexer so reads are fast:++```+on-chain memo → crawler (cron: every 5 min) → solana_attestations table → reputation API → Passport trust grade+```++The crawler (`crawlAgentAttestations`) calls `getSignaturesForAddress(asset)` from a saved cursor, fetches the transactions, extracts and **validates** each memo against its schema, computes a `verified` flag, and upserts it. Revocations and disputes flip flags on the rows they target. The `verified` rule is where Sybil resistance starts:++- A **stake** attestation is `verified` only if the lamports actually transferred are ≥ 0.001 SOL.+- An **accept**/**dispute** is `verified` only if the signer is the agent owner.+- **feedback**/**validation**/**task** are `verified` when structurally valid; their *trust tier* is decided at read time.++### The trust tiers (the Sybil-resistance ladder)++The reputation API (`GET /api/agents/solana-reputation?asset=<pubkey>&network=<mainnet|devnet>`) doesn't return one number — it returns the same score computed at four trust levels, strongest first:++1. **Credentialed** — feedback from attesters holding a `threews.verified-client.v1` credential (a Solana Attestation Service credential). The hardest to forge.+2. **Verified** — feedback whose `task_id` has a matching `threews.accept.v1` from the agent owner: proof the reviewer actually transacted with the agent.+3. **Event-attested** — feedback whose source is a machine monitor (`pumpkit.*` / `pumpfun.*`): observed market behavior, not a human claim.+4. **Community** — raw, unweighted feedback from any wallet.++Two design choices blunt Sybil attacks:++- **Per-attester averaging.** Each wallet's opinion is averaged to a single value *before* being averaged across wallets — so spamming 100 memos from one wallet counts once, not 100 times.+- **Tiered weighting.** The grade is computed from the *strongest tier that has data*, so a wave of anonymous community vouches can't outvote credentialed ones.++### The A–D trust grade++The Passport's `computeTrust` picks the best populated tier, then adjusts for risk:++```js+// best.score is the 1–5 average from the strongest tier that has attesters+const passRate = (passed + failed) ? passed / (passed + failed) : 1;+const adjust = best.score+ - (disputed > 0 ? 0.5 : 0) // any dispute: −0.5+ - (passRate < 0.5 ? 1 : 0); // failing validation: −1+const grade = adjust >= 4.5 ? 'A'+ : adjust >= 3.8 ? 'B'+ : adjust >= 3.0 ? 'C'+ : 'D';+```++An agent with **no attestations grades `—` (unknown), not `D`** — new is not the same as bad. The Passport live-polls the chain every ~8 seconds, so a fresh vouch appears within seconds.++> **Trust property, stated honestly.** The *attestations* are on-chain, signed, and anyone can re-crawl them to reproduce the numbers. The *aggregation and grade* are computed off-chain by three.ws for convenience — there is no on-chain `getReputation` on Solana the way ERC-8004 has one. Read the grade as a fast, reproducible summary of trustless underlying data, not as an on-chain consensus value.++---++## System 2 — AgenC coordination reputation++The Passport captures *opinion*. **AgenC** captures *delivery*. AgenC (by Tetsuo Corp, `agenc.tech`) is a Solana Anchor program where agents register, post and claim tasks, and earn reputation by completing work — with stake and slashing making it costly to misbehave.++- **Program:** devnet `6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab`; mainnet via `@tetsuo-ai/sdk`. Live on both.+- **Agent account** (PDA `["agent", agentId]`): holds `reputation: u16` (0–10000, **starts at a neutral 5000**), `stake: u64` (minimum **0.001 SOL** to register), `capabilities` (a u64 bitmask), `status`, `tasks_completed`, `total_earned`, and `active_tasks`.+- **Task lifecycle:** a creator posts a task (reward escrowed in a PDA) → a worker **claims** it (gated by capability bits *and* a `min_reputation` threshold) → the worker **completes** it with a proof hash → the creator **accepts**, which releases the escrow and **bumps the worker's reputation**. A disputed task can trigger `apply_dispute_slash`, which **slashes stake and lowers reputation**.++So AgenC reputation is *earned and slashable*: do good work, it rises; lose a dispute, it falls and your stake bleeds. That's a different and complementary signal to "people vouched for me."++### Reading AgenC reputation++Three paid MCP tools ($0.001 USDC each) read the program directly:++- **`agenc_get_agent`** — `{ agentPda | agentId, cluster }` → the agent's `reputation`, `status`, `stakeAmount`, `activeTasks`, `capabilities`, `endpoint`, `metadataUri`.+- **`agenc_list_tasks`** — `{ creator, cluster }` → a creator's tasks with state, reward, deadline, worker counts.+- **`agenc_get_task`** — `{ taskPda | creator+taskId, cluster }` → one task's state plus a lifecycle timeline (claim/complete/accept events with signatures).++The SDK (`solana-agent-sdk`) exposes the write side: `registerAgenCAgent`, `createAgenCTask`, `claimAgenCTask`, `completeAgenCTask`.++---++## One agent, two chains: the identity bridge++A single three.ws agent can hold **both** a Solana identity (a Metaplex Core asset) and an EVM ERC-8004 identity. The bridge (`solana-agent-sdk/.../identity-bridge.ts`) folds external identities into AgenC's 32-byte `agentId` space with namespaced SHA-256:++```+AgenC/three.ws/erc8004/v1 + erc8004AgentId → agentId+AgenC/three.ws/mpl-core/v1 + assetPubkey → agentId+AgenC/three.ws/handle/v1 + handle → agentId+AgenC/three.ws/composite/v1 + {erc8004, mpl} → agentId ← canonical when both exist+```++When an agent has both an EVM and a Solana identity, the **composite** hash binds the two proofs together so neither can be swapped after the fact. The bridge also builds a resolvable `metadataUri` — `https://three.ws/.well-known/agent.json?erc8004=<id>&mpl=<asset>&handle=<slug>` — that a counterparty on either chain can fetch to discover the agent's full identity.++In the agent card, both registrations sit side by side as CAIP-style references (see [3D Agent Card](../specs/3D_AGENT_CARD.md)):++```jsonc+"registrations": [+ { "agentId": 42, "agentRegistry": "eip155:8453:0x8004A169…" }, // EVM (Base)+ { "agentId": "<asset>", "agentRegistry": "solana:5eykt4Us…:<collection>" } // Solana mainnet+]+```++**Reputation from the two chains is read separately, not mathematically merged.** A consumer that wants the full picture reads ERC-8004 (via the [`agent_reputation` MCP tool](./reputation.md)) *and* the Solana reputation API, and weighs them itself. The agent has one identity; its trust record is the union of what each chain attests.++---++## EVM vs. Solana reputation, side by side++| | ERC-8004 (EVM) | Attestation (Solana) | AgenC (Solana) |+|---|---|---|---|+| Identity | agent NFT (`agentId`) | Metaplex Core asset pubkey | AgenC agent PDA |+| Write a vouch | `submitFeedback` on the Reputation Registry | SPL Memo (+ optional SOL stake) | earned by completing tasks |+| Where the score lives | on-chain aggregate (`getReputation`) | on-chain memos, aggregated off-chain | on-chain program account (`u16`) |+| Score scale | 1–5 stars (stored −100…+100) | 1–5 | 0–10000 (starts 5000) |+| Stake | ETH escrow, refundable | SOL transfer to owner | SOL stake, slashable |+| Sybil defense | one review per wallet, no self-review | per-attester averaging + credential/verified tiers | capability + `min_reputation` gates, slashing |+| Read | MCP tool, REST, SDK, contract | Passport, `/api/agents/solana-reputation`, x402 | `agenc_*` MCP tools, SDK |++The shapes differ; the purpose is identical — let an agent decide, before it pays, whether a counterparty is worth trusting. ([Why that matters →](./agent-reputation.md))++---++## Status++- **Attestation reputation / Passport** — **live.** On-chain memo writes, the 5-minute indexer cron, the reputation API, and the A–D Passport are all in production on mainnet and devnet.+- **AgenC** — **live** on mainnet and devnet; the end-to-end task→claim→complete→reputation flow runs against real transactions (see `examples/agenc-task-roundtrip`).+- **Identity bridge** — **live** for deriving and linking IDs; cross-chain reputation is *read* from both sides rather than auto-synced between them.+- **Solana `glb-schema` validation** — rides on `threews.validation.v1`, mirroring the EVM ValidationRegistry attestation.++---++## Next++- **[Read a Solana agent's reputation](/tutorials/solana-agent-reputation)** — open a Passport, read the grade, query the API, and leave an on-chain vouch.+- **[Agent Reputation: why it matters](./agent-reputation.md)** — the trust problem both chains solve.+- **[Solana agents](./solana.md)** — registering an agent as a Metaplex Core asset.+- **[ERC-8004](./erc8004.md)** · **[Reputation System](./reputation.md)** — the EVM side of the same idea.++---++<a id="sec-212"></a>> **Source:** `docs/solana.md` · [↑ table of contents](#table-of-contents)@@ -36034,7 +39848,94 @@ A full ERC-8004-equivalent on Solana would mean writing three Anchor programs (I----<a id="sec-186"></a>+<a id="sec-213"></a>++> **Source:** `docs/specs/agent-trading.md` · [↑ table of contents](#table-of-contents)++# Spec — Agent trading capability (Feature B)++Status: **proposed** · Author: three.ws · Depends on: autopilot v0.2.0 (SOL spend cap + $THREE buy-only guard)++## Why++Today an agent's autopilot can create alerts, author briefings, and send **native SOL**. It cannot trade. The realistic, high-value autonomous behavior users want is **buying and selling pump.fun coins in SOL** — sniping new launches and acting on alpha — while treating **$THREE as buy-only** (accumulate/burn, never sell). This spec adds that capability on top of the v0.2.0 foundation.++## Principles (inherited from v0.2.0)++1. **SOL is the spend currency.** Every buy is denominated in SOL and counts against the daily SOL cap (`daily_spend_sol`). Sells return SOL.+2. **$THREE is a one-way valve.** The agent may *buy* $THREE (SOL → $THREE) and *burn* it, but a **sell of $THREE (or any transfer out of $THREE) is hard-refused server-side** — the same guard `validateWalletTransfer` already enforces, extended to the swap path.+3. **Runtime mints only.** Coins to trade are supplied at runtime (mint address from discovery/intel). Never hardcode, market, or recommend a specific non-$THREE mint in source, copy, or proposals (CLAUDE.md). $THREE remains the only coin the platform promotes.+4. **Server-side enforcement.** Scope, caps, slippage bounds, and the $THREE-sell ban live in `api/_lib/autopilot.js` / a new trade guard — the MCP client cannot bypass them.++## New autopilot action kind: `trade`++Extend `AUTOPILOT_ACTION_KINDS` with `trade` and `ACTION_TYPE.trade = 'autopilot.trade.executed'`.++**Params** (validated by a new `validateTrade`):+```+{+ side: "buy" | "sell",+ mint: "<solana mint>", // the coin to trade; "three"/$THREE allowed for side:"buy" ONLY+ amount_sol?: number, // required for buy — SOL to spend (counts against daily cap)+ amount_tokens?: number | "all", // required for sell — token units (or all) to sell back to SOL+ max_slippage_bps?: number, // default 100 (1%), hard ceiling e.g. 500+ reason: string+}+```++**Guards** (all server-side, deny — never partial-execute):+- `side:"sell"` with `mint === $THREE` (or the CA) → **refused** (`code: 'three_sell_forbidden'`). This is the buy-only valve.+- `side:"buy"`: `amount_sol > 0`, `spent_24h + amount_sol ≤ daily_spend_sol`, scope `trade` granted, `confirm:true` (reuse the irreversible-confirmation policy).+- `side:"sell"`: agent must hold the position; slippage within `max_slippage_bps`.+- Reuse `dailySolSpent` for buys; sells do not add to the spend tally (they return SOL).++## Execution path++Reuse existing building blocks — do **not** add a new swap implementation if one is reusable:+- Quote: `@three-ws/pumpfun-mcp` already exposes `pumpfun_quote_swap` / `quote_swap`; the backend equivalent should quote via the same Jupiter/pump.fun route.+- Buy: pattern already proven in `avatar-agent-mcp` (`pump_buy`) and the agent custodial wallet path (`recoverSolanaAgentKeypair`, `submitProtected`).+- Settle: bundle/submit via the same protected-send path used by `transferNativeSol`.+- Record: write a signed `agent_actions` row (`autopilot.trade.executed`) with provenance, mint, side, amounts, signature, realized SOL — same receipt discipline as `wallet_transfer`.++## MCP surface++Two options — **recommended: a dedicated `@three-ws/trading-mcp`** rather than overloading autopilot, because trading has its own discovery + quote + position surface:+- `quote_trade` (read) — price + expected out + slippage for a prospective buy/sell.+- `list_positions` (read) — open positions with cost basis + unrealized PnL (reuse `portfolio-mcp` data).+- `execute_trade` (write · destructive) — buy/sell in SOL; `confirm:true`; $THREE-sell refused.+- Autopilot integration: `generate_proposals` may emit `trade` proposals (grounded in `intel-mcp` smart-money / signal memories); they flow through the existing dryrun → confirm → execute → signed-receipt loop.++`portfolio-mcp`'s `send_transfer` already lazy-loads `@solana/spl-token`; the trading server should follow the same lazy-import discipline to avoid the ESM load crash.++## Discovery → decision (where alpha comes from)++Trading proposals should cite real signals, never guess:+- `intel-mcp` — smart-money score, KOL trades, signal-feed accuracy.+- `pumpfun-mcp` — new/trending/graduating tokens, bonding-curve + holder analysis.+- Alert fires (`alerts-mcp`) → a candidate `trade` proposal the owner reviews.++## Risk & limits++- **Per-trade cap** + **daily SOL cap** (existing) + **max open positions** + **slippage ceiling**.+- **Confirmation**: buys/sells are irreversible → `require_confirm` applies, like `wallet_transfer`.+- **Trust gating**: only agents at `trusted`/`autonomous` trust may auto-execute reversibly-scoped trades (sells of a held position); buys always confirm.+- **No $THREE sell, ever** — enforced at validate + execute, covered by a test mirroring the v0.2.0 `three_sell_forbidden` case.++## Phased plan++1. **Quotes + positions (read-only):** `quote_trade`, `list_positions` over live routes. No funds move. Ship + verify.+2. **Buy (SOL → coin):** `execute_trade side:"buy"`, confirm-gated, daily-cap-bounded, signed receipt.+3. **Sell (coin → SOL):** `execute_trade side:"sell"` for held positions; $THREE-sell hard-refused.+4. **Autopilot `trade` proposals:** generation from intel/signal memories → dryrun → confirm → execute.+5. **Changelog + docs** at each phase; publish `@three-ws/trading-mcp` (start 0.1.0) and bump `autopilot-mcp` when the `trade` kind lands.++## Definition of done (per phase)++Real routes (no mocks), server-side guards with tests (including the $THREE-sell refusal), confirm-gated irreversible actions, signed `agent_actions` receipts, MCP descriptions accurate, changelog entry, and `npm run test:mcp` green.++---++<a id="sec-214"></a>> **Source:** `docs/start-here.md` · [↑ table of contents](#table-of-contents)@@ -36108,7 +40009,7 @@ If you're here to create and share agents rather than write code, follow this pa----<a id="sec-187"></a>+<a id="sec-215"></a>> **Source:** `docs/syndication.md` · [↑ table of contents](#table-of-contents)@@ -36227,7 +40128,7 @@ to publish, commit + push and let Vercel redeploy.----<a id="sec-188"></a>+<a id="sec-216"></a>> **Source:** `docs/troubleshooting.md` · [↑ table of contents](#table-of-contents)@@ -36702,13 +40603,27 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix1. Verify `DATABASE_URL` is set. The format for Neon is: `postgres://user:password@host/dbname?sslmode=require`.2. If using Neon: check that your server's IP is in the Neon project's IP allowlist (or set it to allow all IPs during development).-3. Run the schema migration to ensure tables exist:+3. Run the full schema bootstrap to ensure every table exists:```bash- node scripts/apply-schema.mjs+ npm run db:bootstrap```---+### `relation "…" does not exist` errors in production logs++**Symptom:** API routes and crons throw `NeonDbError: relation "agent_custody_events" does not exist` (or `forge_creations`, `x_triggers`, `club_tips`, `unstoppable_activity`, …). Often hundreds or thousands of identical errors.++**Cause:** The database was provisioned with only part of the schema — typically `apply-schema.mjs` was run but the incremental migrations under `api/_lib/migrations/` were not. The base schema does **not** create migration-defined tables.++**Fix:** Point `DATABASE_URL` at the affected database and run the complete bootstrap. It is idempotent — it only creates what is missing:+```bash+DATABASE_URL=<prod connection string> npm run db:bootstrap+```+Run `npm run db:status` first to preview which migrations are pending.++---+### API routes return 500**Symptom:** Requests to `/api/*` return HTTP 500 with no useful body.@@ -36859,7 +40774,7 @@ This is a known open issue. The `IdleAnimation` class is implemented in `src/idl----<a id="sec-189"></a>+<a id="sec-217"></a>> **Source:** `docs/tutorials/agent-personality.md` · [↑ table of contents](#table-of-contents)@@ -37311,7 +41226,1005 @@ The system prompt is the cheapest, highest-leverage thing you can change about a----<a id="sec-190"></a>+<a id="sec-218"></a>++> **Source:** `docs/tutorials/agent-reputation.md` · [↑ table of contents](#table-of-contents)++# Read an Agent's On-Chain Reputation++By the end of this tutorial you'll be able to look up any agent's reputation in the [Reputation Explorer](/reputation), understand exactly how those scores and reviews accrue on-chain, and read an agent's reputation programmatically — from the browser, a REST call, an MCP client, or directly off the contract. This is the trust layer on top of on-chain identity: [registration](/docs/tutorials/register-onchain) gives an agent a permanent name; reputation tells you whether to trust it.++**Prerequisites:** an Ethereum address or ENS name to look up (any will do — start with a well-known one). Reading reputation needs no wallet and no account. The programmatic paths assume light JavaScript familiarity; the SDK paths use [ethers v6](https://docs.ethers.org). To *submit* a review you'll need a wallet with a little gas, but this tutorial is about reading.++---++## What you're building++```+You: look up an agent or address in the Reputation Explorer+ ↓ [reads on-chain attestations + ERC-8004 registry — no wallet]+Page: avg rating, review count, score distribution, every signed review+ ↓+Code: getReputation({ agentId, chainId, runner }) → { average, count }+ ↓+Agent: an autonomous agent reads a peer's score before deciding to pay it+```++Reputation on three.ws is not a database row a platform can edit. It is the aggregate of **signed, on-chain feedback** — one review per wallet, permanent, public, and readable by anyone without an API key. This tutorial is the read-side companion to the [register-onchain](/docs/tutorials/register-onchain) tutorial: there you minted an identity; here you learn what accrues around it and how to consume it.++---++## How reputation accrues (two minutes of theory)++ERC-8004 separates identity from reputation into two contracts. The **`ReputationRegistry`** is where trust signals live. Two kinds of signal stack on top of an agent's identity:++| Signal | Where it lives | What it is |+|---|---|---|+| Registry feedback | `ReputationRegistry.submitFeedback` | A signed score `−100..+100` + optional comment/URI, one per wallet per agent |+| EAS attestation | Ethereum Attestation Service | A signed `address agent, uint8 score, string comment` attestation against an address |++The registry keeps a **running aggregate** so reads are O(1): it stores the sum and count, and `getReputation(agentId)` returns `(avgX100, count)` — the average already multiplied by 100 to preserve one decimal without floating-point math. You divide by 100 on the client. No pagination, no indexer required for the headline number.++Three rules are enforced by the contract itself, so the aggregate can't be gamed from the client:++- **One review per wallet per agent.** A second attempt reverts with `AlreadyReviewed`. Sybil attacks cost real gas, one wallet at a time.+- **No self-review.** An agent's own owner can't vouch for it (`SelfReviewForbidden`).+- **Score bounds.** Anything outside `−100..+100` reverts with `ScoreOutOfRange`.++Each individual review is also stored as a `Feedback` struct — `from` (reviewer address), `score` (int8), `timestamp` (uint64), `uri` (optional `ipfs://` pointer to a longer write-up) — and emitted as a `FeedbackSubmitted(agentId, from, score, uri)` event. The aggregate is the cheap read; the events and structs are how you enumerate who said what.++For the full contract reference and chain addresses, see the [Reputation System](/docs/reputation) and [ERC-8004](/docs/erc8004) docs. This tutorial is the hands-on path.++---++## Step 1: Open the Reputation Explorer++Go to [/reputation](/reputation). You'll land on a search box, not a single agent — the Explorer reads reputation for **any** Ethereum address or ENS name, registered agent or not.++Enter one of:++- An ENS name — e.g. `vitalik.eth` (the page resolves it to an address for you)+- A raw `0x…` address+- One of the example chips below the box++Pick a **Network** from the dropdown. The default is **Base (mainnet)** — the recommended chain for three.ws agents. The Explorer also supports Base Sepolia, Ethereum, Optimism, Arbitrum, and Polygon.++Click **Look up**. The URL becomes `/reputation?address=<addr>&chain=<chainId>`, so any reputation view is a shareable link.++---++## Step 2: Read the reputation profile++The profile renders three things, all from on-chain data, with a skeleton loader while it fetches:++**The stats grid:**++- **Avg Rating** — the mean of all scored reviews, shown as `X / 5` stars. Scores stored on a `−100..+100` (or 0–100) scale are mapped to the 1–5 star display.+- **Total Reviews** — how many attestations exist for this address, with a breakdown of how many are scored and how many carry a written comment.+- **Score Distribution** — a 5-to-1 bar chart showing how the scores cluster. A score of all 5s reads very differently from a bimodal split, and the distribution makes that visible at a glance.++**The ERC-8004 badge.** If the looked-up address *owns* a registered agent, the Explorer also reads the `ReputationRegistry` directly and shows a registry line: `ERC-8004 registry: N votes · avg X.X/100`, with a link into the registry-specific view (`/reputation?agent=<chainId>:<agentId>`). This is the on-chain aggregate from Step's theory section — distinct from the EAS attestations above it.++**The review list.** Up to 30 recent reviews, each a card with the reviewer's identicon and short address, their star score, an optional comment, a relative timestamp, and links to the transaction and the attestation on a block explorer. Tabs let you filter to **All**, **Scored**, or **With comments**.++If there are no reviews yet, the page shows a designed empty state ("Be the first to review!") rather than a blank panel — useful confirmation that the lookup worked and the agent simply has no history.++---++## Step 3: Look up a registered agent by its on-chain ID++If you already have a three.ws agent's chain + ID (from the [register-onchain](/docs/tutorials/register-onchain) flow — e.g. `8453:42`), you can jump straight to its registry reputation:++```+/reputation?agent=8453:42+```++The Explorer resolves the agent's owner address via the `IdentityRegistry` and redirects to that address's full profile, so you see both its EAS attestations and its ERC-8004 registry score in one view. Agents also surface their reputation inline on their public page at `https://three.ws/a/<chainId>/<agentId>` — the Explorer is the place to inspect it standalone or to inspect an address that isn't a three.ws agent at all.++---++## Step 4: Read the registry aggregate in JavaScript++The headline number — average and count — comes straight off the contract with one read. Use the helper in [src/erc8004/reputation.js](../../src/erc8004/reputation.js):++```js+import { getReputation } from './src/erc8004/reputation.js';+import { JsonRpcProvider } from 'ethers';++const provider = new JsonRpcProvider('https://mainnet.base.org');++const { average, count } = await getReputation({+ agentId: 42,+ chainId: 8453, // Base mainnet+ runner: provider,+});++console.log(`${count} review(s), average ${average.toFixed(1)}`);+// e.g. "14 review(s), average 87.5"+```++`getReputation` returns `{ average, count }` where `average` is already the on-chain `avgX100` divided by 100 — so `8750` on-chain reads as `87.5`. When `count` is `0`, `average` is `0`. **Never divide `average` by `count` again** — the contract already averaged it. That's the single most common mistake when reading this contract.++The same helper module covers reads on every chain in `REGISTRY_DEPLOYMENTS` (the registry is at the same CREATE2 address on all of them). Point `runner` at that chain's RPC and pass the matching `chainId`.++---++## Step 5: Enumerate the individual reviews++The aggregate tells you *how good*; the events tell you *who said what*. `getRecentReviews` queries the `FeedbackSubmitted` event log:++```js+import { getRecentReviews } from './src/erc8004/reputation.js';++const reviews = await getRecentReviews({+ agentId: 42,+ chainId: 8453,+ runner: provider,+ fromBlock: 0, // for recent-only, pass (latestBlock - 50000)+});++reviews.forEach((r) => {+ console.log(r.from, r.score, r.comment, r.txHash);+});+// each: { agentId, from, score, comment, blockNumber, txHash }+```++`from` is the reviewer's address, `score` the signed int8, `comment` the `uri` field (a short string or an `ipfs://` pointer), plus `blockNumber` and `txHash` for explorer links.++Two practical notes:++- **Log queries can be rejected by free-tier RPCs.** Wide `queryFilter` ranges are the most fragile call here. Scope `fromBlock` to a recent window (the last ~50,000 blocks is roughly a week on most L2s), or fall back to the aggregate alone — `getReputation` always works even when log queries don't.+- **The contract also exposes paginated reads** if you'd rather not rely on logs at all: `getFeedbackCount(agentId)`, `getFeedback(agentId, index)`, and `getFeedbackRange(agentId, offset, limit)` each return the `Feedback` struct(s) directly. These are the deterministic path for a UI that must show every review.++---++## Step 6: Read reputation over the REST API++If you have a three.ws agent's UUID (not its on-chain ID) and just want the number server-side, call the platform endpoint. It does the chain read for you and caches the result:++```js+const res = await fetch('/api/agents/<agent-uuid>/reputation?chain_id=8453');+const { average, count, total_stake_wei, chain_id } = await res.json();++console.log(`${count} reviews, avg ${average}, ${total_stake_wei} wei staked`);+```++The endpoint resolves the agent's on-chain `erc8004_agent_id` and chain from its three.ws record, reads `getReputation` (and `getTotalStake`) against a public RPC, and caches for five minutes (`X-Cache: HIT`/`MISS`). If the agent isn't registered on-chain, it returns `{ average: 0, count: 0, total_stake_wei: "0" }` rather than an error — a clean zero state, not a failure.++This is the right path when you're rendering reputation in your own UI and already speak to the three.ws API by agent UUID.++---++## Step 7: Read reputation from an MCP client or as a paid service++Two more read surfaces exist for agent-to-agent and tooling contexts.++**The MCP `agent_reputation` tool.** From an MCP client (Claude Desktop, Cursor, an agent flow) connected to three.ws, the `agent_reputation` tool takes an `address` — an ERC-8004 `agentId`, a `0x` wallet, or a CAIP-10 `eip155:<chainId>:<wallet>` — and an optional `chain` (defaults to Base). It returns the aggregate score, count, average, total ETH staked, and the latest reputation events, resolving the agentId from a wallet via the `IdentityRegistry` when needed. It's a paid tool ($0.01 USDC per call) cataloged in the x402 bazaar.++**The paid HTTP snapshot.** [`GET /api/x402/agent-reputation?agent_id=<uuid>`](../../api/x402/agent-reputation.js) returns a richer **vetting snapshot** synthesized from on-chain activity three.ws indexes — confirmed payments and distinct payers, distribution and buyback success rates, and signed Solana attestation counts — for $0.01 USDC. Use it when an autonomous agent needs to decide whether a counterparty is trustworthy *before* paying, trading, or composing skills with it. It's a separate, defensible signal from the EVM registry score: behavior over time, not a single subjective rating.++---++## Step 8: Gate an autonomous action on reputation++The point of readable, on-chain reputation is that code can act on it. The agent-to-agent payment layer ships a reputation gate ([api/_lib/a2a/reputation-gate.js](../../api/_lib/a2a/reputation-gate.js)) that refuses to pay a peer whose score is below a threshold:++```js+import { assertReputationOk } from './api/_lib/a2a/reputation-gate.js';++// Before paying a peer agent, require a minimum track record:+await assertReputationOk({+ agentId: peerAgentId,+ chainId: 8453,+ minAverage: 50, // require avg score ≥ 50+ minCount: 3, // and at least 3 reviews+});+// Throws ReputationError if the peer is below the bar; returns the read otherwise.+```++The design choices are worth copying in your own gating logic:++- **No threshold set → no-op.** If neither `minAverage` nor `minCount` is requested, the gate does nothing. You opt into trust enforcement explicitly.+- **Threshold set but reputation unreadable → fail closed.** If a bar is set and the RPC read fails, it throws rather than waving the payment through. You cannot prove a peer is trustworthy, so the safe default is "no."+- **The reader is injectable.** Pass a `read` function to swap in an indexer or to test without a live RPC.++This is the second-order payoff of on-chain reputation: budget caps stop an agent from *overspending*, but only a reputation gate stops it from *paying a scammer*.++---++## Troubleshooting++**Lookup returns "No attestations found" for a real agent**+- The agent may have reviews in the **ERC-8004 registry** but no **EAS attestations** (or vice-versa) — they're separate signals. Check the ERC-8004 badge on the profile, and try the registry view at `/reputation?agent=<chainId>:<agentId>`.+- Confirm you picked the **right network**. Reputation is per-chain; an agent reviewed on Base won't show reviews when you query Ethereum.++**`getReputation` returns a huge `average` like `8750`**+- That's `avgX100`. The `getReputation` helper in `src/erc8004/reputation.js` already divides by 100; if you're calling the contract directly, divide by 100 yourself. Don't also divide by `count` — the contract pre-averaged it.++**`getRecentReviews` throws or hangs**+- Free-tier RPCs often reject wide `queryFilter` log ranges. Narrow `fromBlock` to a recent window, or use the deterministic `getFeedbackRange(agentId, offset, limit)` reads instead. The aggregate from `getReputation` still works regardless.++**ENS name won't resolve in the Explorer**+- ENS resolves on Ethereum mainnet even when you're viewing reputation on another chain. If it fails, paste the raw `0x` address instead.++**`/api/agents/<id>/reputation` returns all zeros**+- That's the designed response for an agent with no on-chain registration (no `erc8004_agent_id`/`chain_id`) or no reviews yet — not an error. Register the agent on-chain first (see [register-onchain](/docs/tutorials/register-onchain)), then reviews can accrue.++**The reputation gate rejects every peer**+- A `reputation_unavailable` error means a threshold was set but the read failed (RPC down or no `A2A_REPUTATION_RPC_URL` configured) — the gate fails closed by design. Configure a working RPC, or drop the threshold to disable gating.++---++## Recap++You learned to read agent reputation at every layer:++- **The Reputation Explorer** ([/reputation](/reputation)) — search any address or ENS name, no wallet, and see avg rating, count, distribution, and every signed review across EAS attestations and the ERC-8004 registry.+- **How it accrues** — signed, on-chain feedback in the `ReputationRegistry`, one review per wallet, aggregated O(1) as `(avgX100, count)`, with self-review, double-review, and out-of-range scores all rejected by the contract.+- **In JavaScript** — `getReputation` for the aggregate (divide-by-100 already done), `getRecentReviews` / `getFeedbackRange` for individual reviews.+- **Over REST** — `GET /api/agents/<uuid>/reputation?chain_id=` for a cached server-side read by agent UUID.+- **For agents and tooling** — the MCP `agent_reputation` tool and the paid `/api/x402/agent-reputation` vetting snapshot.+- **Acting on it** — `assertReputationOk` to gate an autonomous payment on a minimum score and review count, failing closed when trust can't be proven.++The leverage is composability: because reputation is on-chain, the same score you read in the Explorer is the score another agent reads before it decides to trust you. To give an agent the identity these reviews attach to, see [Register Your Agent On-Chain](/docs/tutorials/register-onchain). For the full data model and contract interface, continue to the [Reputation System reference](/docs/reputation) and [ERC-8004](/docs/erc8004).++## See also++- [Register Your Agent On-Chain](/docs/tutorials/register-onchain) — the identity layer reputation attaches to.+- [Reputation System reference](/docs/reputation) — full contract interface, deployed addresses, and the standalone dashboard.+- [ERC-8004 Blockchain Identity](/docs/erc8004) — the three-contract standard behind identity, reputation, and validation.+- [Build a Custom Skill](/docs/tutorials/custom-skill) — give an agent capabilities worth reviewing.++---++<a id="sec-219"></a>++> **Source:** `docs/tutorials/animate-your-avatar.md` · [↑ table of contents](#table-of-contents)++# Animate your avatar++By the end of this tutorial you'll be able to take any rigged avatar, browse the three.ws clip library, apply a motion to it live, control its speed and looping, and export an animated GLB you can use anywhere. You'll also understand *why* a clip authored for one skeleton plays correctly on yours — the runtime retargeting that makes the library universal.++**Prerequisites:** a three.ws account and at least one rigged avatar ([create one](/create), or load any public avatar). No code required — everything here happens in the browser. Light JavaScript familiarity helps only for the optional "how retargeting works" section.++---++## What you're building++```+Pick an avatar ──► Browse the clip library ──► Click a clip+ │+ retarget onto your rig + play live+ │+ tune speed / loop ──► export animated GLB+```++You don't author motion from scratch (you can — that's the keyframe timeline, a separate workflow). Here you *apply* and *remix* the shared library: dozens of pre-baked clips — idle, walk, dances, gestures, reactions — that drive **any** humanoid rig without manual bone mapping.++Two surfaces do this, and they're connected:++| Surface | Route | What it's for |+|---|---|---|+| **Animation Studio** | [/pose](/pose) | Load an avatar, apply or generate motion, tune it, export an animated GLB |+| **Animation Gallery** | [/animations](/animations) | Browse public community clips, preview on a live avatar, send any to the Studio |++The Gallery is where you *discover* a clip; the Studio is where you *apply* it. Every Gallery card's **Open in Studio** button deep-links to `/pose?anim=<id>`, so the two are one workflow.++---++## How clips drive any rig (two minutes of theory)++The thing that makes the library work is that **motion and body are stored separately**.++- An avatar is a **GLB** — geometry, skeleton, skin, textures.+- A motion is a **clip JSON** — keyframe tracks only, no geometry. One clip can play on every avatar.++A clip's tracks are named against a **canonical skeleton** — a 53-bone humanoid set (`Hips → Spine → Spine1 → Spine2 → Neck → Head`, both arms `Shoulder → Arm → ForeArm → Hand` with finger chains, both legs `UpLeg → Leg → Foot → ToeBase`). Every clip in [public/animations/clips](../../public/animations/clips) is baked against the reference rig `public/avatars/cz.glb`.++Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `DEF-spine`, `J_Bip_C_Hips`, `pelvis`, `leftUpperArm`. Two runtime modules bridge that gap:++1. **Bone-name canonicalization** ([src/glb-canonicalize.js](../../src/glb-canonicalize.js)) recognizes the common skeleton conventions — Mixamo (`mixamorig:`), Blender (`Armature_`, `.L`/`.R`), Rigify (`DEF-`/`ORG-`), Unreal (`upperarm_l`), VRM/VRoid (`J_Bip_L_UpperArm`), VRM 1.0 (`leftUpperArm`), Daz/Genesis (`lShldr`), MakeHuman, and simple rigs (`shoulderL`) — and maps each bone to its canonical name.++2. **Retargeting** ([src/animation-retarget.js](../../src/animation-retarget.js)) rewrites each track onto your rig's actual bone names, applies a per-bone bind-pose correction (so an A-pose clip plays right on a T-pose rig, and a hip baked at −90°X doesn't tip the body over), and rescales hip translation by your avatar's height so root motion lands where it should.++**There is no rig allowlist.** Any humanoid avatar drives the library through this canonicalize-then-retarget path. The only gates are sanity thresholds: a rig needs **≥8** recognizable humanoid bones, and a clip must map **≥50%** of its tracks onto the rig to land. Below that the motion would read as a few twitching joints, so the Studio refuses it with an actionable message instead of playing garbage. If you hit a brand-new skeleton convention the canonicalizer doesn't know, the fix is to add its bone-name mapping to `glb-canonicalize.js` — never to hardcode a curated list of supported rigs.++---++## Step 1: Open the Studio and load an avatar++Open **[/pose](/pose)**. You'll land on the built-in **mannequin** — a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.++In the top bar, click **Load avatar** and pick one of your rigged avatars (or a public one). The right-panel **Animation** section unlocks the moment a compatible rig is loaded.++If you'd rather skip the picker, deep-link directly:++```+/pose?avatar=<your-avatar-id>+```++The Studio reads `?avatar=` on boot and loads it for you. Add `&anim=<clip-id>` and it also opens that saved clip — this is exactly what the Gallery's **Open in Studio** button does.++If the right panel shows **"Load a rigged avatar to animate"**, you're still on the mannequin — load an avatar. If it shows **"This rig can't be retargeted,"** the model exposes fewer than 8 recognizable humanoid bones (see Troubleshooting).++---++## Step 2: Browse the clip library++With an avatar loaded, the **Animation** section on the right fills with a searchable, categorized gallery:++- **Category chips** across the top (Featured plus grouped categories) filter the grid.+- **Search** ("Search animations…") matches clip labels and names as you type.+- Each **card** shows an icon, a label, and a **loop** / **once** badge so you know up front whether a clip cycles forever or plays a single shot.++The library covers a wide range — idle breaths, walks, dances, celebrations, reactions, sitting and crouching poses, and more. Browse by category, or search for what you want (e.g. `dance`, `wave`, `idle`).++> Want to browse the *full* community catalog first? Open the **[Animation Gallery](/animations)** in another tab. It lists public clips with hover-to-preview on a live avatar, a loop/one-shot filter, and infinite scroll. When you find one you like, click **Open in Studio** and it lands back here applied to your avatar.++---++## Step 3: Apply a clip++Click any card. The Studio:++1. Fetches that clip's JSON.+2. Retargets it onto your loaded rig (rewrites bone names, corrects the bind pose, scales the hips).+3. Plays it live on the figure in the viewport.++The shared 3D stage **is** the preview — one figure performing the motion, the way Mixamo previews look, rather than a wall of video thumbnails. The active card gets a "now playing" equalizer animation and a highlighted border.++The status line at the bottom of the stage confirms the retarget, e.g.:++```+Playing "Cheering" — 96% retargeted (51/53 bones matched).+```++That percentage is the coverage — how many of the clip's tracks found a home on your rig. A couple of dropped bones (often fingers a simpler rig lacks) is normal and fine. If coverage falls below 50%, the clip won't apply and the status explains why (see Troubleshooting).++Clips marked **once** play a single shot and hold the final frame; **loop** clips cycle until you stop them or pick another.++---++## Step 4: Control playback — speed and loop++Once a clip is playing, a **transport bar** appears under the gallery:++- A pulsing **now-playing** indicator with the clip's name.+- A **Speed** slider, `0.25×` to `2.5×`. Drag it to taste — `1.8×` turns a walk into something close to a jog; `0.5×` slows a gesture down for emphasis. The value updates live.+- **⏹ Stop** ends the preview and hands the figure back to a clean rest pose.+- **Export animated GLB** (covered next).++Looping follows the clip's own `loop` flag (the **loop** / **once** badge). Speed is a live preview control *and* it's baked into the export — the GLB you download carries the tempo you previewed, not a default one.++To swap clips, just click a different card — the new motion retargets and replaces the old one. To compare two dances, apply one, watch it, then click the other; the transport always reflects what's currently playing.++---++## Step 5: Generate a motion that doesn't exist yet++The preset library is finite; your imagination isn't. At the top of the **Animation** section is a text-to-motion box:++```+Generate a motion — "waving confidently" [ ✨ Generate ]+```++Type a short description (e.g. `waving confidently`, `a slow bow`, `excited jumping`) and click **Generate**. The Studio submits a motion job, polls until the clip is ready (typically ~10–30s on a warm GPU; up to ~90s), then **retargets and plays it on your rig through the exact same path as a preset.** A generated motion behaves identically — same transport, speed slider, loop, and export. The status line counts the seconds while it works.++If the deployment hasn't enabled text-to-animation, you'll get a clear "isn't enabled on this deployment yet" message rather than a hang. Either way, the preset library is always available.++---++## Step 6: Export an animated GLB++When a clip looks right, click **Export animated GLB** in the transport bar.++The Studio bakes the retargeted clip — at your chosen speed — onto your avatar's rig and downloads a single self-contained file:++```+<avatar-name>-<clip-name>.glb+```++This closes the loop: you started with a GLB (body) and a separate clip (motion), and you end with **one GLB that has the motion embedded.** It loads in any standard glTF viewer or in any three.ws surface, no retargeting required at play time.++The figure is parked on the clip's first frame before export, so the file's rest pose is the animation's actual start — not wherever the live preview happened to pause.++> The Studio can also export **clip JSON** (motion only, reusable on other rigs) and a **PNG screenshot** from the top bar, and — if you author your own motion on the keyframe timeline — save it to your account and list it. Those are adjacent workflows; this tutorial is the apply-and-remix path.++---++## Step 7: Discover and remix from the Gallery++The **[Animation Gallery](/animations)** is the social, browse-first side of the same system. It lists public, community-authored clips:++- **Search** and a **loop / one-shot** filter narrow the grid.+- **Hover or click a card** to launch a live preview — an embedded viewer plays the clip on the reference CZ avatar, so you see real motion, not a static thumbnail.+- **Open in Studio** deep-links to `/pose?anim=<id>`, dropping the clip into the Studio so you can apply it to *your* avatar, tune its speed, and export.++This is the remix loop: find a motion someone else published, open it in the Studio, retarget it onto your own avatar, adjust it, export. Because every clip is format-light JSON addressed by canonical bone names, the same clip that previewed on the CZ avatar drives your custom rig with no extra work.++---++## Emotion and expression on the live agent++Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two complementary channels:++**Gesture slots** ([src/runtime/animation-slots.js](../../src/runtime/animation-slots.js)) — a fixed emotional vocabulary the agent plays in conversation: `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `dance`. Each slot resolves to a concrete library clip at runtime (e.g. `celebrate` → the `celebrate` clip, `think` → `pray`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations` — point `wave` at a different clip, or map a slot to a motion you authored yourself.++**Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — independent of the skeleton. If your avatar carries ARKit-52 blendshapes (most modern exports do — RPM, Avaturn, VRoid), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.++The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion.** All three ride the same universal-rig foundation — name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.++---++## Troubleshooting++- **The Animation section says "Load a rigged avatar to animate."** You're on the built-in mannequin. The mannequin has no skinned skeleton to retarget or export — click **Load avatar** in the top bar (or open `/pose?avatar=<id>`).++- **"This rig can't be retargeted — only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, RPM, Avaturn, VRM all work), or auto-rig a rig-less mesh first.++- **A clip won't apply: "can't retarget to this rig — only X/Y tracks mapped."** Coverage fell below 50%. The rig is missing too many of the clip's bones (often a stripped-down skeleton with no spine subdivisions or no fingers). Try a clip that uses fewer bones, or use a more complete humanoid rig. The fix for a recurring convention is to add its bone-name mapping in [src/glb-canonicalize.js](../../src/glb-canonicalize.js) — never a hardcoded allowlist.++- **The motion plays but limbs look skewed or the body lies down.** This is the symptom the bind-pose correction exists to prevent, so it should be rare. It usually means the rig rests in an unusual pose the canonicalizer mapped but couldn't fully correct. Verify the avatar imports upright and T- or A-posed; re-export from the source tool if it doesn't.++- **A few bones are "not on this rig" but it still plays.** Expected. The status note (`51/53 bones · 2 not on this rig`) just lists dropped tracks — usually fingers or toes a simpler rig lacks. As long as coverage is ≥50% the performance reads correctly.++- **"Text-to-animation isn't enabled on this deployment yet."** The motion generator isn't configured on this instance. Use the preset library, which is always available.++- **Generation times out.** The job exceeded the poll window. Try a shorter, simpler prompt.++- **Export downloads nothing / fails.** Make sure a clip is actively playing (the transport bar is visible) before clicking **Export animated GLB** — export bakes the *currently previewing* clip onto the rig.++---++## Recap++You learned the apply-and-remix workflow for motion on three.ws:++- **The library is universal.** Motion is stored as canonical-skeleton clip JSON, separate from the avatar GLB. [glb-canonicalize.js](../../src/glb-canonicalize.js) maps any humanoid's bone names to canonical; [animation-retarget.js](../../src/animation-retarget.js) rewrites tracks, corrects the bind pose, and scales the hips so one clip drives every rig. No rig allowlist — only an 8-bone / 50%-coverage sanity gate.+- **[/pose](/pose) is where you apply.** Load a rigged avatar, browse or search the categorized gallery, click to retarget and preview live, tune speed (0.25×–2.5×) and loop in the transport bar, and **export an animated GLB** with the motion baked in.+- **[/animations](/animations) is where you discover.** Browse public community clips with live hover-preview, then **Open in Studio** to apply any of them to your own avatar.+- **Generate what doesn't exist.** Text-to-motion synthesizes a brand-new clip and runs it through the identical retarget-and-apply path as a preset.+- **On a live agent**, the same clips drive emotion through gesture **slots**, while **ARKit-52 blendshapes** drive facial expression independently — clips move the body, blendshapes move the face.++**See also:**++- [docs/animations.md](../animations.md) — the runtime animation registry, manifest, and agent slot reference.+- [docs/3d-asset-pipeline.md](../3d-asset-pipeline.md) — how FBX, GLB, and clip JSON relate, and how clips are built and retargeted.+- [docs/tutorials/swap-avatar-in-studio.md](swap-avatar-in-studio.md) — loading and switching avatars in the Studio.+- [docs/tutorials/upload-custom-glb.md](upload-custom-glb.md) — getting a Mixamo or custom rig into three.ws as a clean, animatable GLB.++Primary call to action: open **[/pose](/pose)**, load an avatar, and apply your first clip.++---++<a id="sec-220"></a>++> **Source:** `docs/tutorials/build-a-scene.md` · [↑ table of contents](#table-of-contents)++# Build a 3D scene in Scene Studio++By the end of this tutorial you'll have composed a complete 3D scene in the browser — imported GLB models, arranged them with transform gizmos, edited their materials, lit the scene, and exported the whole thing as a single GLB you can drop anywhere. No install, no build step; everything runs client-side at [/scene](/scene).++Along the way you'll learn how the editor's panels fit together, why the scene autosaves to your browser, and when to reach for the lighter [Scene Composer](/compose) instead.++**Prerequisites:** a desktop browser (the editor is keyboard- and gizmo-driven). At least one GLB or glTF model to import — generate one for free from text at [/forge](/forge), or use any GLB file you already have. No account required.++---++## What you're building++A scene is a collection of objects — meshes, lights, cameras — arranged in 3D space, with materials and a background, exported as one file:++```+Import GLB(s) → arrange with Move / Rotate / Scale → edit materials+ ↓ ↓+ add lights ───────────────► set background ───────► Export GLB → scene.glb+```++The result is a self-contained `scene.glb` (or `.gltf`) that carries every object, material, and embedded texture. You can re-import it later, hand it to another tool, or view it in AR.++[Scene Studio](/scene) is a full editor — the vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) editor (`r184`, MIT — see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md)) mounted under the three.ws nav. It is dark-locked: the editor chrome only ships a dark theme.++---++## How the editor is laid out (two minutes of orientation)++[/scene](/scene) is a single full-screen workspace. Five regions do all the work:++| Region | Where | What it's for |+|---|---|---|+| **Menubar** | top | File, Edit, Add, View, Help, Render — every command |+| **Toolbar** | top-left, over the viewport | Move / Rotate / Scale gizmo modes |+| **Viewport** | center | the live 3D scene; orbit, select, drag gizmos |+| **Sidebar** | right | three tabs — **Scene**, **Project**, **Settings** |+| **Animation** | bottom (resizable) | keyframe timeline for animated objects |++The **Sidebar → Scene** tab is where you'll spend most of your time. It shows the **outliner** (the scene graph as a tree) at the top, and below it a **properties** area that changes depending on what's selected — Object, Geometry, and Material sub-panels for a mesh; light controls for a light.++One thing to know up front: **the editor autosaves.** Every change (add, move, material edit, delete) is written to your browser's local storage about a second later, and restored when you return to [/scene](/scene). Your scene persists across reloads on the same browser — but it is *local*, not synced to an account. To keep a scene permanently or move it elsewhere, you **export** it (Step 7) or save the project JSON (`File → Save`).++---++## Step 1: Open Scene Studio++Go to [/scene](/scene). You'll see an empty viewport with a default grid and lighting.++If you arrived from another surface — for example clicking **Open in Scene Studio** after a [Forge](/forge) generation, or a hand-off from the [Animation Studio](/pose) — the model is already loaded into the scene and selected for you. In that case skip to Step 3.++Orbit the empty scene to get oriented:++- **Orbit** — left-drag in the viewport+- **Pan** — right-drag+- **Zoom** — scroll wheel++---++## Step 2: Import a GLB++There are two ways to bring a model in, and they behave slightly differently.++**Drag and drop (fastest):** drag a `.glb` or `.gltf` file from your file manager straight onto the viewport. The editor loads it, adds it to the scene, and lists it in the outliner. Dropping a folder works too — it imports every model inside.++**File → Import:** open the **File** menu, click **Import**, and pick one or more files. This is the same path as drag-and-drop and supports the same formats.++Scene Studio imports far more than GLB. The vendored loader (see [src/scene-studio/vendor/js/Loader.js](src/scene-studio/vendor/js/Loader.js)) accepts `glb`, `gltf`, `fbx`, `obj`, `dae` (Collada), `usdz`, `ply`, `stl`, `3mf`, `amf`, `drc`, `vox`, `wrl`, `svg`, and several more — but **GLB is the recommended format**: it bundles mesh, materials, and textures into one binary file, and it's what every other three.ws surface produces.++> **Deep-link import.** You can also load a model by URL: `/scene?model=<glb_url>&name=<label>`. The editor fetches the GLB, adds it through the normal undo-able import path, then strips the query from the address bar so a reload doesn't import a duplicate. This is exactly how the **Open in Scene Studio** hand-off works. The URL must be `https://` or a same-origin path.++After import, the model appears in the outliner. Click its row to select it — a transform gizmo snaps onto it in the viewport.++---++## Step 3: Arrange objects with the transform gizmo++Select an object (click it in the viewport or its outliner row), then choose a transform mode. The three modes live in the Toolbar and on the keyboard:++| Mode | Toolbar | Key |+|---|---|---|+| **Move** (translate) | the move icon | `W` |+| **Rotate** | the rotate icon | `E` |+| **Scale** | the scale icon | `R` |++Drag the colored gizmo handles in the viewport to transform along an axis. Useful companions while you arrange:++- **`F`** — focus the camera on the selected object (frames it in view).+- **Snapping** — hold while dragging, or set a snap distance, to move in fixed increments.+- **World / Local space** — the gizmo can operate in world axes or the object's own axes.++For precision, type exact values instead of dragging: with the object selected, open **Sidebar → Scene** and use the **Object** sub-panel's **Position**, **Rotation**, and **Scale** number fields. Every edit here goes through the editor's command system, so it's fully undoable.++**Multiple copies?** With an object selected, **Edit → Clone** (or the duplicate shortcut) makes an independent copy you can reposition. **Edit → Center** moves the object so its bounding box is centered on its own origin — handy when an imported model arrives off-center.++Everything you do is undoable: **Edit → Undo** (`Ctrl+Z`) and **Edit → Redo** (`Ctrl+Shift+Z`). The full edit history is also browsable under **Sidebar → Settings → History**.++---++## Step 4: Organize the scene graph++As the scene grows, keep the outliner tidy.++- **Rename** — select an object and edit the **Name** field in the **Object** sub-panel. Clear names make a complex scene navigable.+- **Group** — **Add → Group** creates an empty container. Drag objects onto the group's row in the outliner to nest them. Transforming the group moves everything inside it as a unit — ideal for, say, a table and everything on it.+- **Delete** — select and press `Del`, or **Edit → Delete**.++A well-organized outliner pays off at export time: groups and names survive into the exported GLB.++---++## Step 5: Edit materials++Select a mesh, then open **Sidebar → Scene**. Below the Object and Geometry sub-panels is the **Material** sub-panel — this is the live material editor.++The exact controls depend on the material type (imported GLB models typically use a physically-based `MeshStandardMaterial`). Common properties you can edit:++- **Color** — the base color swatch. Click it to open a color picker.+- **Roughness** and **Metalness** — the PBR sliders that define whether a surface looks matte or glossy, dielectric or metallic.+- **Emissive** — a color the material gives off regardless of lighting (good for glowing elements).+- **Maps** — texture slots (color/albedo, normal, roughness, metalness, emissive, and more). Click a map slot to assign an image.+- **Opacity / Transparent** — make a material see-through.+- **Side** — render the front, back, or both faces.++Every change renders in the viewport immediately and is captured in undo history. If a primitive you added looks unlit and flat, it's usually because the scene has no light yet — that's the next step.++> **Add primitives directly.** You don't have to import everything. **Add → Mesh** drops in a Box, Sphere, Plane, Cylinder, Torus, Capsule, Text, and more — each with a fresh editable material. Great for floors, platforms, and blockout geometry.++---++## Step 6: Light the scene++A scene with no lights renders dark (unlit materials show flat color; PBR materials show nearly black). Add lights from the **Add → Light** submenu:++| Light | Use it for |+|---|---|+| **Ambient** | a flat base fill so nothing is pure black |+| **Directional** | a sun — parallel rays, casts a consistent shadow direction |+| **Hemisphere** | sky/ground gradient fill, good for outdoor scenes |+| **Point** | a bulb — radiates in all directions from a position |+| **Spot** | a cone — a focused beam with an angle and falloff |++Each light appears in the outliner like any other object. Select it to:++- **Position** it with the Move gizmo (`W`) — point and spot lights have a position; directional and spot lights also have a target.+- **Edit its properties** in the Sidebar: **Color** and **Intensity** for every light; **Distance**, **Angle**, and **Penumbra** for the lights that have them.++A solid starting rig: one **Directional** light for key/shadow direction plus a low-intensity **Ambient** or **Hemisphere** light to lift the shadows. Adjust intensities until the scene reads the way you want.++**Set the background and environment** while you're here. In **Sidebar → Scene**, the **Background** control switches between a solid **Color**, a **Texture**, or an **Equirectangular** HDR/image (which doubles as image-based lighting). You can also add **Fog** for depth. These settings export with the scene.++---++## Step 7: Export the scene++When the scene looks right, open **File → Export** and choose a format. For a complete, portable scene, pick **GLB**:++- **GLB** — exports the **entire scene** (all objects, materials, embedded textures, and any optimized animations) as one binary `scene.glb`. This is the recommended output.+- **GLTF** — same content as GLB but as human-readable JSON (`scene.gltf`), with assets referenced/embedded per the glTF spec.++The Export submenu also offers single-object/whole-scene formats for specific pipelines: **OBJ** and **DRC** (these export the *selected* object — select a mesh first), and **PLY**, **STL** (ASCII and binary variants), and **USDZ** for the whole scene. Reach for these only when a downstream tool requires them; for everything on three.ws, **GLB** is the right choice.++The file downloads through your browser. That's your finished scene — re-import it anywhere, [view it in AR](/docs/tutorials/view-in-ar), or hand it to another agent.++> **Save the editable project too.** Export bakes the scene into a delivery format. To keep working on it later with full editor state, use **File → Save**, which writes a `project.json` you can reopen with **File → Open**. The autosaved browser copy persists between visits, but `project.json` is your portable, backup-able source of truth.++---++## When to use Scene Composer instead++[Scene Composer](/compose) is a distinct, lighter surface — not the full editor. Where Scene Studio is a general-purpose 3D editor, Composer is purpose-built for **forging items from text and dressing an avatar**:++- **Forge from text, in place.** Describe an item ("a glowing katana with blue neon energy"), pick a type (accessory, item, scene, creature, vehicle), and it's generated and dropped straight into the scene — no separate trip to [/forge](/forge).+- **Attach to avatar bones.** Load an avatar (paste a GLB URL or browse your avatars), then attach items to specific skeleton bones — a hat to the head, a sword to the hand. The item rides the bone.+- **Familiar arranging.** The same `W` / `E` / `R` Move/Rotate/Scale gizmos, `F` to focus, `Del` to remove, undo/redo, and camera presets — with a streamlined inspector.+- **Two outputs.** **Export GLB** downloads the composition, and **Save Outfit** persists the assembled set to your account.++Rule of thumb: reach for **[/compose](/compose)** when you're generating items and equipping an avatar; reach for **[/scene](/scene)** when you need the full editor — many models, fine material control, primitives, multiple lights, and the broad set of import/export formats.++---++## Troubleshooting++- **My scene is black / models look unlit.** The scene has no light. Add a light from **Add → Light** (start with Directional + a low Ambient). PBR materials render near-black without lighting.+- **An imported model is huge, tiny, or far off-screen.** Models export at wildly different scales. Select it, press `F` to focus, then use **Scale** (`R`) or the Object sub-panel's Scale fields. If it's off-center, **Edit → Center**.+- **The deep-link import failed.** `/scene?model=…` only accepts `https://` or same-origin URLs, and the host must allow the fetch (CORS). The editor will tell you to drag the GLB in instead — that path always works.+- **I lost my scene after closing the tab.** The autosave is per-browser and per-origin: a different browser, profile, or private window won't have it. For anything you care about, **File → Save** the `project.json` or **File → Export** a GLB.+- **The editor loaded in light mode / looks wrong.** Scene Studio is dark-locked; the chrome only ships a dark theme. If styling looks broken, hard-reload to clear a stale cache.+- **OBJ / DRC export did nothing.** Those formats export the *selected* object, not the whole scene. Select a mesh first. For the full scene, use **GLB** or **GLTF**.+- **Drag-and-drop won't import.** Drop onto the viewport, not the sidebar, and use a supported extension (`.glb`/`.gltf` recommended). For a stubborn file, try **File → Import**.++---++## Recap++You composed and exported a complete 3D scene in the browser:++- **Imported** GLBs by drag-and-drop, **File → Import**, or the `/scene?model=` deep link — GLB recommended, but many formats accepted.+- **Arranged** objects with the Move / Rotate / Scale gizmos (`W` / `E` / `R`), `F` to focus, plus precise numeric transforms and **Clone** / **Center** — all undoable.+- **Organized** the scene graph with names and **Add → Group**.+- **Edited materials** (color, roughness, metalness, emissive, maps) in the live Material sub-panel, and added primitives via **Add → Mesh**.+- **Lit the scene** with Directional / Ambient / Point / Spot / Hemisphere lights and set a Color / Texture / Equirectangular background.+- **Exported** the whole scene as a self-contained **GLB** (and learned to **File → Save** the editable `project.json`).++The leverage of [Scene Studio](/scene) is that it's a *real* editor producing a *portable* file: a single GLB that flows into AR, other tools, and the rest of three.ws. When your task is forging items and dressing an avatar instead, the lighter [Scene Composer](/compose) is the faster path.++## See also++- [Generate a 3D model from text](/docs/tutorials/text-to-3d) — make GLBs to import here.+- [Image to 3D](/docs/tutorials/image-to-3d) — turn a photo into a model.+- [Upload a custom GLB](/docs/tutorials/upload-custom-glb) — bring your own assets in.+- [View in AR](/docs/tutorials/view-in-ar) — open your exported scene on a phone.+- [Swap an avatar in the studio](/docs/tutorials/swap-avatar-in-studio) — work with avatars across the editors.++---++<a id="sec-221"></a>++> **Source:** `docs/tutorials/claim-threews-name.md` · [↑ table of contents](#table-of-contents)++# Claim a *.threews.sol name and get paid by name++By the end of this tutorial you'll own a real Solana Name Service name — `yourname.threews.sol` — that resolves to your three.ws showcase in Brave, and you'll know exactly how another agent or person sends you USDC using that name instead of a 44-character wallet address.++Along the way you'll understand what the subdomain points at on-chain, why the mint is gasless for you, and how the pay-by-name endpoint turns a human-readable name into a signed USDC transfer.++**Prerequisites:** a signed-in three.ws account with a **username set** (the subdomain label must match it) and at least one agent — creating an agent provisions the Solana wallet that receives the name ([create one](/create)). Light JavaScript familiarity for the pay-by-name section; the claim itself is no-code.++---++## What you're building++```+You (once): claim "nich" at /threews/claim+ ↓ [threews.sol subdomain minted, URL record set, ownership transferred to your wallet]+Anyone, later: pays nich.threews.sol → USDC lands in your wallet+Brave user: types nich.threews.sol → lands on https://three.ws/u/nich+```++A wallet address is unspeakable, unmemorable, and easy to fat-finger. `nich.threews.sol` is a name a person can read aloud, an agent can resolve in one request, and a browser can navigate to. One claim gives you all three: a resolvable name, a showcase page, and a pay-by-name handle.++---++## How it works (two minutes of theory)++three.ws owns the parent domain `threews.sol`. When you claim a label, the platform mints `<label>.threews.sol` as a **subdomain** under that parent and hands it to you. Three on-chain actions happen inside **one** transaction (so the subdomain is never claimable by a third party in between):++1. **createSubdomain** — the parent owner mints the new registry and is, momentarily, its owner.+2. **createRecordV2Instruction(URL → `https://three.ws/u/<label>`)** — a `URL` record is written while the platform still owns the subdomain. This record is what makes the name resolve in Brave and any SNS-aware client.+3. **transferSubdomain** — ownership (and the attached records) is transferred to your wallet.++The platform keypair is the only signer and fee payer, so **you pay no SOL gas and never sign a wallet transaction** to claim. After the transfer, the name is yours — the platform doesn't retain custody, it just set the URL record on the way out.++What the name resolves *to* depends on the flow:++| Flow | Endpoint | URL record points at |+|---|---|---|+| **User claim** (this tutorial) | [POST /api/threews/subdomain](/api/threews/subdomain) | `https://three.ws/u/<label>` — your showcase |+| **Agent attach** | [POST /api/sns-subdomain](/api/sns-subdomain) | `https://three.ws/a/<agent_id>` — the agent page |++For payments, three.ws resolves any of three name forms to a recipient wallet, in this order: a raw base58 address (pass-through), a `.sol` domain or subdomain (resolved on-chain via Bonfida `resolve()`), or a bare `@username` (looked up to the user's default agent wallet). That's what makes `nich.threews.sol`, `@nich`, and the raw address all valid payment targets.++Two hard rules to know before you start:++- **The label must equal your account username.** `<label>.threews.sol` showcases `/u/<label>`, so allowing divergent labels would let anyone mint a name impersonating another handle. Set your username first if you haven't.+- **Some labels are reserved.** Platform paths and impersonation-risk words (`admin`, `api`, `pay`, `threews`, `wallet`, `official`, and similar) are denied. The availability check tells you immediately.++---++## Step 1: Set your username++The mint endpoint rejects any label that doesn't match `users.username` (HTTP `409 username_mismatch`), so this is the gate.++1. Open your account settings and set a username if you don't have one — it must be lowercase `[a-z0-9-]`, 1–63 characters, and not a reserved word.+2. That username **is** your subdomain label. If your username is `nich`, you can only claim `nich.threews.sol`.++If you skip this, the mint fails with `409 no_username` ("set a username on your account before claiming a subdomain").++---++## Step 2: Open the claim page++Go to **[/threews/claim](/threews/claim)**.++You'll see a single input with a fixed `.threews.sol` suffix and a disabled **Mint subdomain** button. The button stays disabled until the availability check confirms the label is free.++Type your username into the label field. As you type, the page:++- Lowercases the input and strips anything outside `[a-z0-9-]` in real time.+- Debounces for 350ms, then calls `GET /api/threews/subdomain?label=<label>` to check availability.++---++## Step 3: Read the availability result++The check returns a small envelope describing the label's status:++```jsonc+{+ "data": {+ "full": "nich.threews.sol",+ "label": "nich",+ "parent": "threews",+ "available": true,+ "owner": null,+ "on_chain_check": "ok",+ "on_chain_error": null,+ "claim": null,+ "showcase_url": null+ }+}+```++Interpreting it:++- **`available: true`** — nobody has claimed it through three.ws and no on-chain owner was found. The Mint button enables and the status reads `nich.threews.sol is available.`+- **`available: false` with `claim`** — already claimed through three.ws; the status shows `claimed by @<username>`.+- **`available: false` with only `owner`** — registered on-chain to a wallet outside our records; the status shows `owned by <wallet>`.+- **`on_chain_check: "unavailable"`** — a Solana RPC hiccup meant the on-chain side couldn't be verified. The endpoint still answers `200` (it won't `500` the UI) and the response is sent `no-store` so you can retry. If you see this, wait a moment and re-type the last character to re-check.++The availability check is **public and rate-limited** — it needs no auth, so you can verify a label before committing.++---++## Step 4: Mint the subdomain++With an available label, click **Mint subdomain**. The page now does the authenticated write:++1. Fetches a CSRF token from `/api/csrf-token` (your session must be signed in).+2. `POST /api/threews/subdomain` with `{ "label": "nich" }`, sending the `x-csrf-token` header and same-origin credentials.++```jsonc+// POST /api/threews/subdomain+// headers: { "content-type": "application/json", "x-csrf-token": "<token>" }+// credentials: same-origin+{ "label": "nich" }+```++The server then, in order:++1. Confirms minting is configured (the platform parent key is present) — otherwise `503 config_missing`.+2. Loads your user, confirms you have a username, and confirms it **matches the label** — otherwise `409`.+3. Confirms nobody has claimed it through three.ws and nobody owns it on-chain — otherwise `409 conflict`.+4. Picks the **recipient wallet**: if you pass `owner_wallet` it must be a Solana wallet **linked to your account** (else `403 forbidden`); otherwise it falls back to your **default agent's Solana wallet** (the oldest agent you own). No agent and no linked wallet → `409 no_wallet`.+5. Runs the atomic mint + URL-record + transfer transaction and records the claim in `user_subdomains`.++On success you get a `201` with the receipt:++```jsonc+{+ "data": {+ "id": "…",+ "label": "nich",+ "parent": "threews",+ "owner_wallet": "<your Solana wallet>",+ "url_record": "https://three.ws/u/nich",+ "signature": "<tx signature>",+ "full": "nich.threews.sol",+ "showcase_url": "https://three.ws/u/nich",+ "explorer": "https://solscan.io/tx/<signature>"+ }+}+```++The page renders a green result card with your name, the showcase link, and a Solscan link to the on-chain transaction. The subdomain is yours and already owned by your wallet — the whole thing typically lands in a few seconds.++### Claiming to a specific wallet++To receive the name in a wallet other than your default agent's, link that Solana wallet to your account first, then include it in the POST body:++```jsonc+{ "label": "nich", "owner_wallet": "<your linked base58 wallet>" }+```++If the wallet isn't linked, the mint refuses with `403` — three.ws will not mint a subdomain into a third-party wallet.++---++## Step 5: Verify the name resolves++Two ways to confirm the claim is live.++**Forward resolution (any client):**++```js+const r = await fetch('/api/sns?name=nich.threews.sol');+const { data } = await r.json();+// { name: "nich.threews.sol", address: "<wallet>", network: "solana", resolved: true }+```++`/api/sns` is the public resolver. A miss returns `resolved: false` with `address: null` (a `200`, not a `404`) — so if you see `resolved: false` right after minting, give the RPC cache its short TTL and retry.++**In Brave:** type `nich.threews.sol` into the URL bar. Because the `URL` record was written at mint time, Brave's SNS resolver redirects you straight to `https://three.ws/u/nich` — your showcase, rendering your public agents, avatars, paid skills, and socials. No extension, no plugin.++---++## Step 6: Resolve the name for a payment++Now the payoff: getting paid by name. Anyone — a human or an agent — can resolve your name to a wallet with a single public GET:++```js+const r = await fetch('/api/x402/pay-by-name?name=nich.threews.sol');+const { data } = await r.json();+// {+// address: "<your wallet base58>",+// source: "sns",+// resolved: "nich.threews.sol",+// claim: { user_id, username: "nich", display_name } // present for *.threews.sol+// }+```++The resolver accepts all three name forms, tried in order:++1. A **raw base58 address** → returned as-is (`source: "address"`).+2. A **`.sol` domain or subdomain** like `nich.threews.sol` → resolved on-chain via Bonfida `resolve()` (`source: "sns"`). For `*.threews.sol` names it also attaches the matching three.ws `claim` so the caller can show your showcase link.+3. A bare **`@username`** (3–30 chars) → mapped to that user's default agent Solana wallet (`source: "username"`).++A name that resolves to nothing returns `404 not_found`. This GET is the safe, side-effect-free way to preview *exactly which wallet* a name points at before sending anything.++---++## Step 7: Have someone pay you by name++There are two payment modes on `POST /api/x402/pay-by-name`. Payments are denominated in **USDC** (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`, 6 decimals), capped at **10,000 USDC per call**.++### Mode `prep` — browser wallet signs (no auth)++The payer passes their own wallet as `payer_wallet`; the server builds an **unsigned** USDC SPL transfer and returns it base64-encoded for the payer's wallet to sign and broadcast. The transfer includes an idempotent "create associated token account" instruction so it works even if your USDC token account doesn't exist yet.++```js+const r = await fetch('/api/x402/pay-by-name', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: 'nich.threews.sol',+ amount_usdc: 5,+ payer_wallet: '<payer base58 wallet>',+ // mode defaults to "prep"+ }),+});+const { data } = await r.json();+// {+// recipient: { address, source: "sns", resolved: "nich.threews.sol", claim },+// amount_usdc: 5,+// tx_base64: "<unsigned VersionedTransaction>",+// blockhash, last_valid_block_height,+// mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"+// }+```++The payer deserializes `tx_base64`, signs with their wallet, and submits it to Solana. No three.ws account needed on the payer's side.++### Mode `send` — an agent pays on the caller's behalf (auth required)++If the payer is a three.ws user paying from one of **their own agents**, `mode: "send"` has the server sign as that agent and broadcast the transfer, returning the signature directly. This requires a signed-in session (or bearer token) and an `agent_id` the caller owns.++```js+const r = await fetch('/api/x402/pay-by-name', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ name: 'nich.threews.sol',+ amount_usdc: 5,+ mode: 'send',+ agent_id: '<your agent uuid>',+ expected_address: '<address you previewed in Step 6>', // recommended+ }),+});+const { data } = await r.json();+// { recipient, payer, amount_usdc: 5, signature: "<tx>", mode: "send" }+```++Two guardrails worth knowing on the send path:++- **`expected_address`** — pass the address you previewed, and the server requires the fresh resolution to still match it before signing. A name can repoint between preview and send (or a lookalike name can resolve to an attacker wallet); this binds the recipient you approved into the signed request. A mismatch returns `409 recipient_changed`.+- **Per-transaction limit** — the agent's configured per-tx USD ceiling applies. A send over the limit returns `403 per_tx_exceeded`. The amount must also be `> 0`, and off-curve targets (PDAs/program addresses) are rejected as invalid recipients.++Either way, the USDC lands in the wallet your `nich.threews.sol` points at — the one the subdomain was transferred to in Step 4.++---++## What you get from one claim++- `nich.threews.sol` **resolves in Brave** to your showcase at `/u/nich` — no extension.+- A **pay-by-name handle** — anyone can `POST /api/x402/pay-by-name` with `nich.threews.sol` to send you USDC, or preview the target wallet with the matching GET.+- **On-chain ownership** in your wallet — three.ws set the URL record and transferred custody; it doesn't hold the name.+- A **verified profile** at [/u/nich](/u/).++---++## Troubleshooting++- **`409 no_username` / `409 username_mismatch`** — the label must equal your account username. Set or correct your username, then claim that exact string.+- **Mint button never enables** — availability returned `available: false` (claimed or on-chain owned) or `on_chain_check: "unavailable"` (RPC hiccup). For the latter, retry in a moment; the response is `no-store` precisely so you can.+- **`409 conflict` on mint** — someone claimed or registered the label between your availability check and your click. Pick another label (which must still match your username — in practice this means the name is genuinely taken).+- **`409 no_wallet`** — you passed no `owner_wallet` and have no agent. Create an agent (it provisions a Solana wallet) or link a Solana wallet and pass it as `owner_wallet`.+- **`403 forbidden` on mint** — the `owner_wallet` you passed isn't linked to your account. Link it first; three.ws won't mint into an unlinked wallet.+- **`503 config_missing`** — subdomain minting isn't configured on this deployment (the platform parent key is absent). This is an environment issue, not a request error.+- **`401 unauthorized`** — minting and `mode=send` need a signed-in session or bearer token. The availability check and `mode=prep` preview do not.+- **`/api/sns` says `resolved: false` right after minting** — resolution is cached briefly; the negative cache TTL is short. Wait a few seconds and re-resolve.+- **Pay-by-name `404 not_found`** — the name doesn't resolve. Confirm the exact spelling (`<label>.threews.sol`), or use the GET resolver to see what it points at.+- **`409 recipient_changed` on `mode=send`** — the name now resolves to a different address than the `expected_address` you sent. Re-run the GET preview and confirm the new target before sending.+- **`403 per_tx_exceeded`** — the send exceeds the paying agent's per-transaction USD limit. Lower the amount or raise the agent's limit.++---++## Recap++You claimed a real Solana name and wired it to payments:++- **Claim** ([/threews/claim](/threews/claim)) — type your username, the page checks `GET /api/threews/subdomain?label=…`, and `POST /api/threews/subdomain` mints `<label>.threews.sol` gaslessly, sets its URL record to `/u/<label>`, and transfers ownership to your wallet — all in one transaction.+- **Resolve** — `GET /api/sns?name=<name>.threews.sol` (forward), and the name lands in Brave on your showcase via the URL record.+- **Get paid by name** — `GET /api/x402/pay-by-name?name=…` previews the recipient wallet; `POST` with `mode=prep` returns an unsigned USDC transfer for a browser wallet, or `mode=send` (auth + `agent_id`) has an agent sign and broadcast it, guarded by `expected_address` and a per-tx limit.++One name, three jobs: a browser destination, a verifiable identity, and a USDC pay-by-name handle. For the full SNS surface — agent-attached subdomains, attaching an existing `.sol` you already own, and reverse lookups — see [POST /api/sns-subdomain](/api/sns-subdomain) and the [resolver at /api/sns](/api/sns).++See also:++- [Build a custom skill](/docs/tutorials/custom-skill) — give your named agent new capabilities.+- [Create & edit agent memory](/docs/tutorials/create-and-edit-memory) — make your agent remember to quote in USDC.++---++<a id="sec-222"></a>> **Source:** `docs/tutorials/connect-ai-brain.md` · [↑ table of contents](#table-of-contents)@@ -37633,7 +42546,328 @@ The brain is the part of the agent you'll iterate on most after the system promp----<a id="sec-191"></a>+<a id="sec-223"></a>++> **Source:** `docs/tutorials/create-and-edit-memory.md` · [↑ table of contents](#table-of-contents)++# Create, enhance & edit agent memory++By the end of this tutorial you'll be able to give any of your agents a **custom memory** — a durable fact it carries into every future conversation — and then sharpen, edit, or remove it. You'll do it five ways: from the dashboard with no code, by letting the agent remember on its own, over the MCP tools, over the REST API, and from inside a skill.++Along the way you'll understand the four memory types, how salience and recency decide what an agent recalls, and why editing a memory quietly re-indexes it.++**Prerequisites:** a three.ws account with at least one agent ([create one](/create)). The code paths assume light JavaScript familiarity; the dashboard path assumes none.++---++## What you're building++A custom memory is one fact, attached to one agent, that survives between sessions:++```+You (once): "Always quote prices in USDC, never in SOL."+ ↓ [stored as a feedback memory on the agent]+Agent (every session after): reads it at boot, quotes in USDC without being asked+```++Without memory, every conversation starts cold — the agent re-learns who you are and re-makes the same mistakes. A custom memory is how you teach it something once and have it stick.++This tutorial covers the full lifecycle: **create → enhance → edit → forget**.++---++## How memory works (two minutes of theory)++Every memory has a **type**. The type decides how strongly the agent prioritizes the fact when it builds context for a new turn:++| Type | What it stores | Pull | Example |+|---|---|---|---|+| `user` | Who the user is — role, goals, preferences | high | "Maria is a Solana dev; prefers terse answers" |+| `feedback` | Corrections and confirmed instructions | **highest** | "Quote prices in USDC, never SOL" |+| `project` | Ongoing work — goals, deadlines, stakeholders | medium | "Shipping the marketplace by July; blocked on x402" |+| `reference` | Pointers to external systems | low (looked up on demand) | "Design tokens live in docs/DESIGN-TOKENS.md" |++`feedback` is weighted highest on purpose: a correction the user had to give once should never need repeating. `reference` gets no boost — it's retrieved when relevant, not kept front-of-mind.++Two more levers govern what surfaces in a given conversation:++- **Salience** — a 0–1 weight. Higher = more likely to be recalled. Defaults to `0.5`.+- **Recency** — a 7-day exponential half-life. Yesterday's note outranks an equally-salient one from two weeks ago.++The agent ranks candidate memories by a blend of relevance-to-the-moment, salience, and recency, then injects the top ones into its system prompt. You don't call anything to make this happen — storing the memory is enough.++For the full data model (storage modes, the file format, IPFS persistence), see the [Memory System reference](/docs/memory). This tutorial is the hands-on path.++---++## Path A — Create a memory from the dashboard (no code)++The fastest way to add a custom memory.++1. Open **[Library → Memory](/library)** in your dashboard.+2. Click **+ Add a note**.+3. **Attach to agent** — pick which agent should remember this.+4. **Type** — choose `user`, `feedback`, `project`, or `reference` (see the table above; default is `project`).+5. **Content** — write the fact in plain language. One fact per memory.+6. Click **Save**.++The note appears immediately in the list, tagged with its type and agent, newest first. The next time that agent loads, the fact is part of its context.++```+Type: feedback+Content: When I ask for a summary, give me three bullets max — no preamble.+```++The Memory tab lists every memory across all your agents in one place, so this is also where you audit what your agents currently know. Long notes collapse to three lines with a **Show more** toggle.++> The dashboard is the place to **create and review** memories. To **edit** an existing memory in place or **delete** one, use the API or MCP paths below, or just tell the agent (Path B). The agent's own corrections and the API write to the same store the dashboard reads from.++---++## Path B — Let the agent remember on its own++Every agent has a built-in `remember` capability. When a conversation contains something worth keeping, the agent stores it without you lifting a finger:++```+You: My name is Maria and I prefer to be addressed formally.+Agent: [remembers → type: user, "User is Maria; prefers formal address"]+ Noted, Maria. I'll keep it formal from here on.+```++You can also instruct it directly:++```+You: Remember that our standup is every Tuesday at 9am.+You: Forget my old shipping address.+```++This is the most natural path for end users. The agent picks the type, writes a tight summary, and confirms. Everything it saves shows up in **Library → Memory** alongside the notes you added yourself — the two paths share one store.++---++## Path C — Create & forget over the MCP tools++If you drive your agent from an MCP client (Claude Desktop, Cursor, an agent-to-agent flow), connect to `/api/mcp` and you get three memory tools. They're scoped to agents you own via three.ws OAuth (`memory:read` / `memory:write`).++**`remember`** — store a memory. Always adds a new entry (additive, never overwrites):++```jsonc+{+ "name": "remember",+ "arguments": {+ "agent_id": "your-agent-uuid",+ "content": "Quote prices in USDC, never in SOL.",+ "type": "feedback", // user | feedback | project | reference (default: reference)+ "tags": ["pricing", "currency"],+ "salience": 0.8, // 0–1, default 0.5+ "expires_at": "2026-12-31T00:00:00Z" // optional ISO-8601; excluded from recall after this+ }+}+```++**`recall`** — retrieve the most relevant memories for a query. Ranks by query relevance blended with salience and recency, skipping expired entries:++```jsonc+{+ "name": "recall",+ "arguments": { "agent_id": "your-agent-uuid", "query": "how should I quote prices?", "limit": 8 }+}+```++**`forget`** — delete a memory by id (get the id from a `recall` result):++```jsonc+{ "name": "forget", "arguments": { "memory_id": "the-memory-uuid" } }+```++> `remember` only ever inserts. To **change** a fact over MCP, `forget` the stale one and `remember` the corrected version — or simply `remember` the correction with higher salience; recall will surface the newer, stronger memory first.++If a call comes from an anonymous, pay-per-call x402 principal (no account), the tools refuse with a clear message — memory is account-scoped, so sign in with three.ws OAuth and pass an `agent_id` you own.++---++## Path D — Create & edit over the REST API++The dashboard and the agent both write through one endpoint: `POST /api/agent-memory`. Calls are owner-scoped — you can only touch agents you own.++**Create** (omit `id`; the server assigns one):++```js+await fetch('/api/agent-memory', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ agentId: 'your-agent-uuid',+ entry: {+ type: 'feedback',+ content: 'Quote prices in USDC, never in SOL.',+ salience: 0.8,+ tags: ['pricing'],+ },+ }),+});+// → 201 { entry: { id, type, content, salience, tier, createdAt, ... } }+```++**Edit** — pass the existing memory's `id`. The endpoint upserts: same id → in-place update.++```js+await fetch('/api/agent-memory', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ agentId: 'your-agent-uuid',+ entry: {+ id: 'existing-memory-uuid',+ type: 'feedback',+ content: 'Quote prices in USDC by default; show SOL only if asked.',+ salience: 0.9,+ },+ }),+});+```++Editing the `content` is more than a text swap: the server resets that row's stored embedding and extracted entities, so the memory **re-indexes itself** on the next read. An edited memory becomes findable by its new wording — you don't have to do anything to refresh the index.++**Read** what an agent knows:++```js+const { entries } = await (await fetch('/api/agent-memory?agentId=your-agent-uuid&limit=200', { credentials: 'include' })).json();+```++Filter with `&type=feedback` or fetch only recent changes with `&since=<unix-ms>`.++**Delete:**++```js+await fetch(`/api/agent-memory/${memoryId}`, { method: 'DELETE', credentials: 'include' });+```++These calls run same-origin from a signed-in session (the dashboard's own `post()` helper handles the CSRF token for you). For server-to-server automation, prefer the MCP tools in Path C, which authenticate with an OAuth bearer.++---++## Path E — Create & edit from inside a skill++When you're building a [custom skill](/docs/tutorials/custom-skill), the handler's `ctx.memory` API writes to the same memory the agent reads at boot. Here the **key** is the identity — writing the same key again **edits in place**:++```js+export async function set_preference({ units }, ctx) {+ // Same key → overwrites/updates the existing memory (this is the edit path)+ ctx.memory.write('preferred_units', {+ name: 'Preferred units',+ description: `user prefers ${units}`,+ type: 'user',+ body: `Always present measurements in ${units}.`,+ });+ return { ok: true, units };+}++export async function get_preference(_args, ctx) {+ const pref = ctx.memory.read('preferred_units'); // { meta, body } or null+ return { ok: true, units: pref?.meta?.description ?? 'unknown' };+}+```++`ctx.memory.note(type, data)` appends to a timeline for ephemeral history, and `ctx.memory.recall(query)` searches across stored memories. See the [skill context API](/docs/tutorials/custom-skill) for the full surface.++---++## The portable file format++Under the hood, the file-based layer stores one Markdown file per memory, with YAML frontmatter — the same shape Claude Code uses, so memory is portable and human-editable:++```markdown+---+name: Pricing currency+description: quote prices in USDC, never SOL+type: feedback+created: 2026-06-21+updated: 2026-06-21+---++Quote all prices in USDC by default. Show SOL only when the user explicitly asks.++**Why:** user corrected this twice in early sessions.+**How to apply:** default every quote to USDC; offer SOL as a follow-up, not the headline.+```++To **edit** a memory at this layer, change the body and bump `updated` — the `MEMORY.md` index is rebuilt automatically on the next write. The `**Why:**` / `**How to apply:**` convention (used for `feedback` and `project` memories) is what turns a fact into something the agent can act on, not just recall.++---++## Enhancing a memory: make it actually get used++Creating a memory is easy. Making it reliably *recalled and acted on* is the craft. Five things move the needle:++1. **Pick the sharpest type.** A correction is `feedback`, not `project` — it gets the highest salience and surfaces first. Miscategorizing buries good guidance.+2. **One fact per memory.** "Maria is a Solana dev who ships on Tuesdays and hates emoji" is three memories. Splitting them means each can be recalled, edited, or forgotten on its own.+3. **Add tags.** Tags both boost salience slightly and widen lexical recall — `["pricing","currency"]` makes the memory findable by either word.+4. **Raise salience for durable, load-bearing facts.** Bump important standing instructions to `0.8`–`0.9` so recency decay never sinks them below the noise.+5. **Write the body for action.** For `feedback`/`project`, add **Why:** (so it isn't second-guessed) and **How to apply:** (so the agent knows the behavior, not just the rule). Set `expires_at` on anything time-bound so it self-cleans.++A weak memory and a strong one carry the same fact but behave differently:++```+Weak: type=project "usdc"+Strong: type=feedback salience=0.85 tags=[pricing,currency]+ "Quote prices in USDC, never SOL.+ **Why:** user corrected twice. **How to apply:** default every quote to USDC."+```++---++## Verify it worked++After creating or editing, confirm the agent can actually retrieve it:++- **Dashboard:** the note shows in [Library → Memory](/library) with its type, agent, and salience.+- **MCP / API:** `recall` (or `GET /api/agent-memory`) returns it, ranked. Run a query in the user's own words — if it doesn't surface in the top results, raise salience or add a matching tag.+- **In conversation:** start a fresh session and prompt the situation the memory covers. The agent should act on it unprompted. If it doesn't, the memory is probably mistyped or too low-salience.++---++## What not to store++Memory is for facts a *future* session needs and can't otherwise find:++- ❌ Anything derivable from the agent's code, skills, or manifest+- ❌ Ephemeral context ("we were just talking about X")+- ❌ Secrets, API keys, wallet seeds — **ever**+- ✅ Stated preferences, corrections, durable project context, external pointers++The test: *would the agent need this next week, and could it not just look it up in its current state?* If yes, it's a memory.++---++## Troubleshooting++- **`401` / "sign in required"** — the write needs an authenticated owner. (Public embeds get an empty list, never an error, by design.)+- **`403` / "not your agent"** — the `agentId` belongs to another account. You can only write memories on agents you own.+- **`409` / "memory id already in use"** — you tried to upsert with an `id` that belongs to a different agent. Drop the `id` to create a fresh memory.+- **Type silently became `project` (or `reference`)** — an invalid `type` was sent; the server falls back to a safe default. Use exactly `user`, `feedback`, `project`, or `reference`.+- **MCP tool refused** — anonymous x402 callers have no account. Sign in with three.ws OAuth and pass an `agent_id` you own.+- **Edited a memory but recall still returns the old wording** — re-index is lazy; it refreshes on the next read after the content changes. Run `recall` once and try again.++---++## Recap++You learned five ways to give an agent a custom memory and manage it:++- **Dashboard** ([Library → Memory](/library)) — create and review, no code.+- **The agent itself** — it remembers and forgets in conversation.+- **MCP tools** (`remember` / `recall` / `forget`) — for MCP clients and agent-to-agent flows.+- **REST API** (`POST` / `GET` / `DELETE /api/agent-memory`) — create, edit-by-id (re-indexes), read, delete.+- **Skill `ctx.memory`** — write-by-key (same key edits in place), read, recall, note.++The leverage is in *enhancement*: the right type, one fact per memory, tags, deliberate salience, and an action-oriented body are what turn a stored string into something the agent reliably uses. For the underlying data model and storage modes, continue to the [Memory System reference](/docs/memory).++---++<a id="sec-224"></a>> **Source:** `docs/tutorials/custom-skill.md` · [↑ table of contents](#table-of-contents)@@ -38146,7 +43380,7 @@ The skill installs via a URI in the agent manifest, runs entirely client-side, a----<a id="sec-192"></a>+<a id="sec-225"></a>> **Source:** `docs/tutorials/customize-appearance.md` · [↑ table of contents](#table-of-contents)@@ -38571,7 +43805,7 @@ Most production embeds use four or five of these together. The combination is wh----<a id="sec-193"></a>+<a id="sec-226"></a>> **Source:** `docs/tutorials/deploy-to-vercel-custom-domain.md` · [↑ table of contents](#table-of-contents)@@ -39086,7 +44320,7 @@ In rough order of likelihood:----<a id="sec-194"></a>+<a id="sec-227"></a>> **Source:** `docs/tutorials/embed-in-30-seconds.md` · [↑ table of contents](#table-of-contents)@@ -39359,7 +44593,7 @@ A working embedded agent is the foundation everything else builds on. From here,----<a id="sec-195"></a>+<a id="sec-228"></a>> **Source:** `docs/tutorials/embed-on-website.md` · [↑ table of contents](#table-of-contents)@@ -39842,7 +45076,7 @@ Squarespace's developer preview and published output can differ. Try adding the----<a id="sec-196"></a>+<a id="sec-229"></a>> **Source:** `docs/tutorials/first-agent.md` · [↑ table of contents](#table-of-contents)@@ -40359,7 +45593,7 @@ Now that you have a working agent, here's what to explore next:----<a id="sec-197"></a>+<a id="sec-230"></a>> **Source:** `docs/tutorials/generate-3d-api.md` · [↑ table of contents](#table-of-contents)@@ -40568,7 +45802,178 @@ If you've never made an x402 call, start with [Build a paid x402 endpoint](/tuto----<a id="sec-198"></a>+<a id="sec-231"></a>++> **Source:** `docs/tutorials/getting-started.md` · [↑ table of contents](#table-of-contents)++# Getting started: your first hosted agent++By the end of this tutorial you'll have a live 3D AI agent — a character with a body, a personality, and a public URL you can paste into a chat, a tweet, or a website. No code, no 3D software, no wallet. Five minutes, start to share.++This is the easiest entry point on the platform. Everything you do here is editable later, so don't overthink any single choice — the goal is to get something live and shareable.++**Prerequisites:** a modern browser (Chrome, Firefox, or Safari) and an email address. No coding experience, no 3D files, and no crypto required. You'll sign in once, partway through, to save your work.++---++## What you're building++A hosted agent is three things stacked together: a **body** (a 3D avatar), a **brain** (an LLM plus a personality you write), and a **public page** anyone can open.++```+You: pick a body → name it → describe its personality+ ↓+Result: three.ws/@aria → a 3D character that talks, on a page you can share+```++A concrete example. Say you run a small coffee roaster and want a friendly guide on your site:++```+Name: Aria+Personality: "You are Aria, the guide for Bean & Brew coffee roasters.+ You're warm and concise. You answer questions about our+ beans, brewing methods, and shipping. If you don't know+ something, you say so and point people to [email protected]."+Shared at: three.ws/@aria (and embeddable on beanbrew.co)+```++That's the whole loop. Pick a body, give it a voice, share the link.++---++## The three pieces (one minute of concepts)++Before you start, it helps to know the difference between the two core objects on the platform:++| | What it is | The analogy |+|---|---|---|+| **Avatar** | A 3D model — the body, with a rig so it can move | The actor's body |+| **Agent** | An avatar **plus** a brain: an LLM and the personality you write | The character the actor plays |++You'll create an avatar first, then turn it into an agent by giving it a personality. The platform handles all the 3D rendering, the rig, and the animations — you never touch a 3D tool.++For a deeper take on the distinction, see [Agents vs. Avatars](/docs/agents-vs-avatars). To go straight through, just follow the steps below.++---++## Step 1: Open the create flow++Go to **[/create](/create)**. This is the launchpad for every way to make a body.++You'll see a few starting points. For the fastest five-minute path, you have two good choices:++- **Customize a base avatar** (the recommended hero card) — click **Open editor** to sculpt a face, pick outfits, and adjust colors in the browser. Free, no sign-in to start, about a minute.+- **Start with a template** — click **Browse templates** to pick a ready-made character and make it yours. The fastest option at roughly 15 seconds.++If you already have a model, the **Upload your own GLB** card takes any glTF 2.0 / `.glb` file via **Choose file**. There's also **Scan yourself to 3D** (point your camera and hold still) if you'd rather star as your own agent — that one asks you to sign in first.++Pick one. For your first agent, **Start with a template** is the quickest way to reach the finish line; you can always swap the body later without losing the personality.++---++## Step 2: Name it and choose "Agent"++Whichever starting point you picked, you land on the **preview page** at [/create-review](/create-review). Your 3D character renders in the viewer — drag to orbit it, scroll to zoom.++On the right, fill in two things:++1. **Name & handle** — type a name in the field (placeholder: *"Give your avatar a name"*). As you type, a live handle preview shows the public URL your agent will get, like `three.ws/@aria`. There's a **Copy** button next to it once a handle is reserved.+2. **Is this an agent or an item?** — choose **Agent** (described as *"Thinks, talks, remembers — can go on-chain"*). The other option, **Item**, is for static 3D props with no brain — not what you want here.++Picking **Agent** is the choice that gives your character a mind. Don't pick Item.++---++## Step 3: Save it (sign in once)++Click the primary button. Its label depends on whether you're signed in:++- If you're already signed in, it reads **Save to my account**.+- If you're not, it reads **Sign in to save** — clicking it sends you to sign-in and brings you right back to this exact preview afterward, so you don't lose your work.++> The preview lives only in your browser until you save. That's why signing in is required at this step: it claims your handle and creates the agent record on the platform. Use the email sign-in option — no wallet needed. (Wondering about the crypto stuff? See [Do I need crypto?](/docs/do-i-need-crypto) — short answer: not for this.)++After it saves, you land on a short **"Your agent is ready"** screen with next steps. The first one — **Chat with your agent** — is where the personality gets set. Click it.++---++## Step 4: Give it a personality++**Chat with your agent** opens your agent in the app at `/app?agent=<your-agent-id>`. Here you can talk to it directly and shape how it behaves.++To write its personality properly, open the agent's editor: from your **[dashboard](/dashboard)**, find the agent and open **Edit** (the editor lives at `/agent/<id>/edit`). It's organized into tabs across the top — **Persona**, **Outfit**, **Voice**, **Knowledge**, **Skills**, **Publish**, **Embed**, and more.++Two fields define who your agent is:++- **Persona tab → Description** — a short, public-facing summary of the character (up to 500 characters). Click **Save** when you're done.+- **Publish tab → Agent Profile (system prompt)** — the real instructions the agent follows, in plain language (the placeholder shows *"You are a professor of computer science…"*). This is the heart of the personality. Write it in the second person, like you're briefing an employee:++```+You are Aria, the guide for Bean & Brew coffee roasters.+You're warm, concise, and never pushy. You answer questions about our+single-origin beans, brewing methods, and shipping. When you don't know+something, say so plainly and point the person to [email protected].+Keep replies to two or three sentences unless asked for detail.+```++The clearer and more specific you are, the better the agent behaves. State its name, its job, its tone, and what to do when it's unsure. You can also set a **Greeting (demo first message)** on the Publish tab so visitors get a warm opening line.++When you're happy, click **Publish to Marketplace** on the Publish tab to make the agent's public page live.++---++## Step 5: Share the URL++Your agent now has a public page at **`three.ws/agents/<id>`**, and a friendly handle URL like **`three.ws/@aria`**. Open it — anyone can talk to your agent there in 3D.++On the public agent page you'll find a **Share** button to copy the link, and an **EMBED THIS AGENT** section with three ready-to-copy snippets:++- **Web component** — a `<script>` tag plus an element you drop into any HTML page.+- **Iframe** — a self-contained frame for sites where you can't add scripts.+- **Direct link** — just the URL, for chats, emails, or social posts.++Each has its own **Copy** button. For sharing in a message, copy the **Direct link**. To put the live agent on your own website, copy the **Web component** snippet and paste it into your page — that's the whole integration.++That's it. You created a body, gave it a brain, and shipped a shareable URL.++---++## Troubleshooting++- **The Save button says "Sign in to save" and I lost my preview.** You didn't — sign-in returns you to the same preview and resumes the save automatically. Finish signing in, and the button becomes **Save to my account**.+- **My 3D model doesn't appear in the preview.** Orbit and zoom first (drag / scroll) in case it loaded off-camera. If it still doesn't show, go back to [/create](/create) and pick a template instead of uploading — templates are guaranteed to render.+- **I uploaded a GLB and it was rejected.** The uploader only accepts valid `.glb` (glTF 2.0 binary) files. Re-export as `.glb`, or skip the upload and use a template for now.+- **I picked "Item" by mistake.** Items have no brain. Start over from [/create](/create) and choose **Agent** on the preview page — or, if you already saved it, open the agent editor and promote it.+- **The agent replies generically / ignores its personality.** The personality lives in **Publish → Agent Profile (system prompt)**, not just the Description. Make it specific (name, role, tone, fallback behavior), click **Publish to Marketplace**, then start a fresh chat to test.+- **"Sign in to save" but I don't want a wallet.** You don't need one. Use the email sign-in option — wallets are only for the optional on-chain step, which this tutorial skips entirely.+- **I hit an avatar limit.** The free plan caps how many avatars you can keep. Delete one you don't need from the [dashboard](/dashboard), then create the new one.++---++## Recap++You shipped a hosted agent in five minutes, no code:++1. **[/create](/create)** — picked a body (template, in-browser editor, upload, or selfie scan).+2. **[/create-review](/create-review)** — named it, chose **Agent**, and clicked **Save to my account** (signing in once).+3. **Chat with your agent** — opened it in the app, then the **Edit** view.+4. **Persona → Description** and **Publish → Agent Profile (system prompt)** — wrote the personality and clicked **Publish to Marketplace**.+5. **`three.ws/@your-handle`** — shared the public URL, or copied an **Embed** snippet to put it on your own site.++Everything is editable forever — swap the body, rewrite the prompt, add capabilities — without breaking the URL you shared.++**See also**++- [Make your first agent](/docs/make-your-agent) — the same path with extra screenshots and context.+- [Agents vs. Avatars](/docs/agents-vs-avatars) — the body-vs-brain distinction in depth.+- [Embed in 30 seconds](/docs/tutorials/embed-in-30-seconds) — put your agent on any web page with one line.+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — teach your agent durable facts it carries between sessions.+- [Build a custom skill](/docs/tutorials/custom-skill) — give your agent a new capability, like calling a live API.+- [Do I need crypto?](/docs/do-i-need-crypto) — honest answers on wallets and the optional on-chain step.++---++<a id="sec-232"></a>> **Source:** `docs/tutorials/greeting-and-first-speech.md` · [↑ table of contents](#table-of-contents)@@ -40936,7 +46341,7 @@ A working greeting moves the embed from "decoration" to "interaction", which is----<a id="sec-199"></a>+<a id="sec-233"></a>> **Source:** `docs/tutorials/image-to-3d.md` · [↑ table of contents](#table-of-contents)@@ -41037,7 +46442,175 @@ Everything you generate is kept in **Your creations** at the bottom of the page,----<a id="sec-200"></a>+<a id="sec-234"></a>++> **Source:** `docs/tutorials/import-avatar-url.md` · [↑ table of contents](#table-of-contents)++# Import an avatar by URL++You already have an avatar living somewhere else — a Ready Player Me model on a CloudFront link, a GLB on Arweave, an export sitting in your own storage. You don't need to download it, convert it, or re-host it. Paste the URL into [three.ws/import/rpm](/import/rpm) and the platform fetches it server-side, normalizes its skeleton, auto-rigs it so it can move, and saves it to your account as an avatar an agent can wear.++This tutorial walks the URL-import path end to end. It's the sibling of [Upload a custom GLB](/docs/tutorials/upload-custom-glb) — that one covers pushing a file from your disk; this one covers pulling one in from a link. Same destination, different on-ramp.++**Prerequisites:** a three.ws account (the importer redirects you to sign in if you're not), and a live, publicly reachable URL to a glTF 2.0 `.glb` file. No command line, no Blender, no local tooling required — the whole flow runs in the browser.++---++## What you're building++```+You: paste https://models.readyplayer.me/64c3….glb into /import/rpm+ ↓ server fetches the file (no CORS to fight)+ ↓ humanoid bones canonicalized → idle/walk clips will play+ ↓ stored on the three.ws CDN as an avatar record+ ↓ a fresh agent is provisioned and the avatar attached+ ↓ static rigs get auto-rigged so they animate, not freeze in T-pose+You: "Avatar imported!" → open it at /avatars/<id> and chat with the agent+```++The end result is identical to creating an avatar from a selfie or building one in Studio: a saved avatar record, owned by you, attached to an agent with its own custodial wallet, ready to embed anywhere.++---++## How URL import works (two minutes of theory)++The import page offers two tabs — **Paste URL** and **Upload GLB**. This tutorial is the URL tab. Here's why it exists as a separate path from a plain file upload.++Most avatar hosts (Ready Player Me's CloudFront CDN, Arweave gateways, arbitrary object storage) serve their GLBs **without CORS headers**. A browser `fetch()` to those URLs is blocked before a single byte arrives. So the importer doesn't rely on your browser reaching the file at all:++1. The browser tries a direct CORS fetch first (works for the rare host that allows it).+2. When that's blocked — the common case — it falls back to a **server-side proxy fetch**. The three.ws API pulls the file on your behalf. No CORS to satisfy, and the server applies SSRF guards (it refuses loopback, private, link-local, and cloud-metadata addresses, follows a bounded number of redirects, and caps the download size) so a pasted URL can't be turned into a request against internal infrastructure.+3. Either way, the bytes land in three.ws storage and an avatar record is created.++Two things happen automatically once the file is in:++- **Bone canonicalization.** Humanoid skeletons come in many naming dialects — Mixamo (`mixamorig:LeftArm`), VRM/VRoid, Unreal, Daz/Genesis, MakeHuman, Blender. The platform renames whatever it finds to one canonical bone set so the pre-baked animation library (idle, walk, gestures) retargets onto it out of the box. A non-humanoid rig passes through untouched. The mapping lives in [src/glb-canonicalize.js](../../src/glb-canonicalize.js).+- **Auto-rig.** If the imported GLB has **no skeleton at all** (a static mesh export), the platform submits an auto-rig job after saving. The rigged GLB is swapped in place once the job lands — no T-pose, no second copy. This is the same guarantee every avatar created on three.ws gets: it can move. A GLB that already ships a skeleton skips this step.++You don't trigger any of this. Pasting the URL is enough.++---++## Step 1: Get the GLB URL of your avatar++The importer needs a direct link to a `.glb` file — the URL must end at the model itself, not a viewer page wrapped around it.++**Ready Player Me.** RPM gives you a model URL of the form `https://models.readyplayer.me/<id>.glb`. If you only have the avatar's web page, append `.glb` to the avatar ID, or open the page, then DevTools → **Network**, filter by `.glb`, and copy the request URL. RPM serves these from a CloudFront CDN with no CORS headers — exactly the case the server-side fetch is built for.++**Any other hosted glTF/GLB.** The importer accepts any GLB URL, not just RPM:++- A CDN link (CloudFront, Cloudflare, Bunny, etc.)+- An Arweave or IPFS gateway URL ending in `.glb`+- A file in your own object storage or static host++**Finding the URL when an app fetches it on load.** If your avatar shows up in some other web app but you don't know the raw URL, open that app, then **DevTools → Network → filter `.glb`**, and copy the request URL straight from the network log. That's the link to paste.++The only hard requirements: the URL is `http://` or `https://`, it's publicly reachable (no auth header, no signed-cookie wall), and it points at a valid glTF 2.0 binary. If the original host is gone or the file is behind a login, download it once and use the **Upload GLB** tab instead — see [Upload a custom GLB](/docs/tutorials/upload-custom-glb).++---++## Step 2: Open the importer++Go to **[/import/rpm](/import/rpm)** (linked from [/create](/create) as the "bring your own avatar" path).++You'll see an import card with two tabs. Leave it on **Paste URL** (the default). The warning banner up top spells out the model: the file is fetched on three.ws servers, so CORS-restricted CDNs all work; the Upload tab is the fallback for files on disk or dead hosts.++If you're not signed in, the import call returns a `401` and the page bounces you to `/login?return=/import/rpm` — sign in and you land right back on the importer.++---++## Step 3: Paste the URL and name the avatar++1. In **Avatar GLB URL or CDN link**, paste the full `.glb` URL from Step 1.+2. The field validates the protocol on submit — anything that isn't `http://` or `https://` is rejected with *"Enter a valid http:// or https:// URL."*+3. Optionally fill in **Avatar name**. If you leave it blank, the importer derives a name from the filename in the URL (e.g. `64c3f8e2.glb` → `64c3f8e2`), falling back to *"Imported Avatar"* when the path has nothing useful.++That's the whole form. Hit **Import from URL**.++---++## Step 4: Watch the import run++The progress bar narrates the real pipeline as it executes — these aren't fake stages on a timer, they map to actual work:++| Stage | What's happening |+|---|---|+| **Fetching model…** | The server (or browser, if CORS allows) pulls the GLB bytes from your URL. |+| **Normalizing bones…** | Humanoid bone names are canonicalized so the animation library can drive the rig. |+| **Uploading to three.ws…** | The file is written to the platform CDN with correct CORS and cache headers. |+| **Saving avatar record…** | The avatar row is created in your account; the agent provisioning and auto-rig jobs kick off. |++When it finishes you get an **"Avatar imported!"** card with a **View avatar** button pointing at `/avatars/<your-avatar-id>`.++Behind that success screen, three fire-and-forget jobs have already started and will complete on their own:++- **An agent is provisioned.** A fresh agent is created (or an unpaired one reused) with your imported avatar attached, and it gets its own custodial Solana wallet.+- **The avatar is auto-rigged if needed.** Static meshes are upgraded to animation-ready in place.+- **A thumbnail and tags are generated.** The GLB is rendered off-screen, a poster image is captured, and the model is auto-tagged.++None of these block the success screen — the avatar is usable immediately, and these enrich it over the next few moments.++---++## Step 5: Open the avatar and confirm it moves++Click **View avatar** (or go to `/avatars/<id>`). The avatar page renders your imported model.++What to check:++- **It's not frozen in a T-pose.** A canonicalized humanoid plays the idle clip right away. If you imported a *static* mesh, give the auto-rig job a moment — the model swaps to its rigged version in place once the job lands, and then it animates too. The platform never leaves an avatar stuck bind-pose; a rig that genuinely can't be skeleton-driven falls back to the default rig.+- **Geometry and materials look right.** PBR (`pbrMetallicRoughness`) materials render correctly. If the source used an unsupported material extension you may see a fallback — see [Upload a custom GLB](/docs/tutorials/upload-custom-glb) for the material fix-list, which applies identically to imported files.++---++## Step 6: Use the avatar on an agent++The import already provisioned an agent with this avatar attached, so the fastest path is to just use it:++1. Go to [three.ws/my-agents](/my-agents).+2. Find the agent created for your imported avatar.+3. Send it a message — it should switch to a talk-style animation while it replies, then return to idle.++To put the same avatar on a *different* agent, or to swap an existing agent's body to this one, open that agent and set its body to the imported avatar from the editor's **Body** tab. Because the avatar is a saved record on your account, it's available to any agent you own, and every embed of that agent — `<agent-3d agent-id="…">`, iframe widgets, script-tag embeds — picks up the body on next page load with no code change.++From here you can give the agent a brain and a voice: see [Give your agent a personality](/docs/tutorials/agent-personality) and [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory).++---++## Troubleshooting++- **"Could not fetch that URL … The file may no longer exist."** The server couldn't retrieve the GLB. The host is down, the link is dead, the path is wrong, or the file sits behind authentication. Open the URL in a new browser tab — if you don't get a file download, the importer can't reach it either. Re-copy the URL, or download the file once and use the **Upload GLB** tab.+- **"Enter a valid http:// or https:// URL."** The pasted value isn't a parseable web URL, or uses a non-web protocol. Paste the full link including `https://`. `file://`, `data:`, and relative paths are rejected.+- **The import gets you redirected to sign in.** The save needs an authenticated owner; you weren't signed in. Log in — you're returned to `/import/rpm` automatically. Then re-paste and import.+- **Avatar imported but stuck in a T-pose.** If it's a *static* mesh, the auto-rig job is still finishing — reload the avatar page in a moment and it swaps to the rigged, animating version in place. If a *humanoid* skeleton still won't animate, its bone naming convention may be one the canonicalizer doesn't yet map; the platform adds new conventions rather than maintaining an allowlist, so report the rig.+- **Materials render chalky/grey.** The source GLB uses a material extension the runtime renders as a fallback. Convert the materials to standard `pbrMetallicRoughness` at the source and re-import — the [Upload a custom GLB](/docs/tutorials/upload-custom-glb) material fix-list covers this exactly.+- **"This is taking forever" on a large file.** The server fetch caps download size and a huge, uncompressed GLB takes longer to pull and store. If your file is well over the cap, optimize it first (the `optimize:glb` / `gltf-transform` steps in [Upload a custom GLB](/docs/tutorials/upload-custom-glb)) and import the slimmer result.+- **I want to import a file on my disk, not a URL.** Switch to the **Upload GLB** tab on the same page — drag-and-drop or file-pick a `.glb` (up to 100 MB). Same canonicalization, auto-rig, and agent provisioning apply.++---++## Recap++You imported an existing avatar by URL, no download or conversion required:++- **Paste a `.glb` URL** at [/import/rpm](/import/rpm) — Ready Player Me, any CDN, Arweave, or your own storage all work.+- **The server fetches it for you**, so CORS-restricted hosts are a non-issue, with SSRF guards on the pasted URL.+- **Humanoid bones are canonicalized** ([src/glb-canonicalize.js](../../src/glb-canonicalize.js)) so the pre-baked animation library plays out of the box.+- **Static meshes are auto-rigged** in place after save — the platform guarantees an avatar that can move, never a frozen T-pose.+- **An agent is provisioned** with the avatar attached and its own wallet; the avatar is a reusable record you can put on any agent you own.++The URL path and the file-upload path converge on the same avatar record and the same agent flow — choose whichever fits where your file already lives.++### See also++- [Upload a custom GLB avatar](/docs/tutorials/upload-custom-glb) — the file-upload counterpart, plus the validator, compression, and material/skinning fix-lists+- [Avatar Creation](/docs/avatar-creation) — every way to make an avatar (photo, builder, upload) and the format spec+- [Give your agent a personality](/docs/tutorials/agent-personality) — match the brain to the imported body+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — give the agent durable facts to carry between sessions++---++<a id="sec-235"></a>> **Source:** `docs/tutorials/js-api-events.md` · [↑ table of contents](#table-of-contents)@@ -41515,7 +47088,7 @@ The `whenReady`, `speakAndWait`, and try/catch patterns are small but they remov----<a id="sec-201"></a>+<a id="sec-236"></a>> **Source:** `docs/tutorials/mcp-server-for-your-agent.md` · [↑ table of contents](#table-of-contents)@@ -42126,7 +47699,276 @@ Things that look right but bite you:----<a id="sec-202"></a>+<a id="sec-237"></a>++> **Source:** `docs/tutorials/mine-vanity-address.md` · [↑ table of contents](#table-of-contents)++# Mine a Solana vanity address++By the end of this tutorial you'll have ground a **custom Solana address** — one that starts with, ends with, or is bookended by characters you choose — entirely in your browser, with the secret key never leaving your device. You'll also understand the **proof-of-grind protocol** around the paid grinder: how to verify a signed receipt, publish to the rarity gallery, and post a bounty when a pattern is too hard for one machine.++Along the way you'll learn why a vanity service is normally a trust problem, and how `three-vanity/v1` replaces "just trust us" with math you can check yourself.++**Prerequisites:** a modern browser (the grind uses Web Workers + WASM). No account is needed to grind in the browser. The paid grinder, gallery publishing, and bounties are optional and covered later — those touch x402 payments and an X25519 key you generate on the page.++---++## What you're building++A vanity address is a normal Solana keypair whose public key happens to match a pattern you picked:++```+Pattern: starts with "AGNT"+ ↓ [your CPU grinds candidates until one matches]+Result: AGNTxK9…vP4q ← a real Ed25519 keypair, address matches the pattern+```++A Solana address is just the Base58 encoding of an Ed25519 public key. There's no shortcut to "AGNT…" — you generate random keypairs and check each address until one starts with your characters. That's *grinding*. Each extra character multiplies the work by ~58, so short patterns are instant and long ones can take a fleet.++This tutorial covers the full lifecycle: **grind in the browser → (optionally) buy a provably-fair grind → verify the receipt → publish to the gallery → post a bounty for hard patterns**.++---++## How grinding works (two minutes of theory)++The address space is the Base58 alphabet (`123…ABC…xyz`, minus the ambiguous `0 O I l` — 58 symbols). To match `n` chosen characters you expect to try about `58ⁿ` random keypairs:++| Pattern length | Expected attempts | Feel |+|---|---|---|+| 1 char | ~58 | instant |+| 3 chars | ~195k | seconds |+| 4 chars | ~11M | a minute on several cores |+| 5 chars | ~633M | minutes to hours |+| 6+ chars | billions | a fleet, or a bounty |++A **case-insensitive** match (matching letters in any case) roughly halves the work per letter, at the cost of not choosing the casing of the result.++Two ways to do the grind exist on three.ws, and they solve different problems:++- **In-browser grind ([/vanity-wallet](/vanity-wallet))** — your machine generates the keypair. Nothing is sent anywhere, so there's nothing to trust. Free, up to 6 pattern characters.+- **Provably-fair paid grind (`/api/x402/vanity-verifiable`)** — three.ws's servers do the work and hand back a **signed receipt**. Because someone else generated your key, the protocol exists to *prove* they did it honestly and never kept a copy. This is the `three-vanity/v1` protocol, specified in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md).++Start with the browser grind. It's the right default for almost everyone.++---++## Step 1: Open the grinder and pick a pattern++Go to **[/vanity-wallet](/vanity-wallet)**.++You'll see two inputs:++- **Starts with** — the prefix your address should begin with (e.g. `AGNT`).+- **Ends with** — the suffix it should end with (e.g. `pump`).++Fill in either, or both. Each field accepts only Base58 characters (max 6 each). As you type, the page shows a live **preview** of where your characters land in a sample address, a difficulty meter, and a rough time estimate:++```+type a prefix or suffix to see estimated time+ ↓ (you type "AGNT")+rough estimate: ~40s on 4 cores [tier: slow — minutes+]+```++The estimate comes from the honest `58ⁿ` model and your selected core count. The page calculates expected attempts as:++```+expectedAttempts = product over each pattern character of (58 / matchesPerChar)+```++where `matchesPerChar` is `2` for a letter when case-insensitive is on (both cases are valid Base58), otherwise `1`. This is the same difficulty math the paid receipt commits to — see [src/solana/vanity/validation.js](../../src/solana/vanity/validation.js).++> **Tip:** the suggested-pattern chips (`AGNT…`, `…pump`, `GM…gm`, …) each show their own estimate. They're a fast way to see how dramatically each extra character costs you.++---++## Step 2: Decide on case sensitivity++Below the inputs is a **Case-insensitive** toggle:++> Case-insensitive — match letters in any case. Much faster to grind, but you don't get to choose the casing of the result.++Leave it **off** if the exact casing matters (you want `AGNT`, not `agnt` or `Agnt`). Turn it **on** when you only care about the letters and want the grind to finish sooner — each letter then matches two Base58 symbols instead of one, cutting the expected work for that character roughly in half.++The time estimate updates immediately when you toggle it, so you can see the trade-off before committing CPU.++---++## Step 3: Set your compute budget and grind++The **Compute — CPU cores to use** slider controls how many Web Workers run the grind in parallel. The page defaults to a sensible fraction of your machine's cores and caps at what your browser reports.++- More cores = faster, but a heavier load on the rest of your machine.+- You can **Pause** at any time to free the cores, then resume.++Press **Generate wallet**. The grind starts and a live panel shows:++```+12,400/s 847,213+tries/sec · 4 cores attempts · eta ~12s+```++- **tries/sec** — combined throughput across your workers.+- **attempts** — cumulative candidates checked.+- **eta** — live estimate to a hit.++Under the hood each worker loads a WASM grinder ([src/solana/vanity/grinder-worker.js](../../src/solana/vanity/grinder-worker.js)) that batches keypair generation, draws fresh entropy with `crypto.getRandomValues`, and checks each candidate against your pattern. The orchestration lives in [src/solana/vanity/grinder.js](../../src/solana/vanity/grinder.js). No network requests are made during the grind — open DevTools → Network and confirm it stays empty.++---++## Step 4: Save the key (this is the critical step)++When a match is found, the page shows your new address and a warning that's there for a reason:++> Save this file somewhere safe before navigating away. Once you close this tab the secret key is gone unless you assign it to an agent. Anyone with the file can spend funds at this address.++The secret key exists **only in this browser tab's memory**. Your options:++- **Download** — saves a JSON file containing the 64-byte secret key as an integer array. This is the Solana CLI / `Keypair.fromSecretKey` format, importable into Phantom, Solflare, or the CLI.+- **Copy** — copies the public address to your clipboard (the address is safe to share; the secret key is not).+- **Assign to an agent** — encrypts the key at rest on three.ws and attaches the wallet to one of your agents, so the agent can transact from a memorable address.++If you only download, store the file somewhere safe (a password manager works). There's no recovery — three.ws never saw the key, so it can't help you restore it. That's the whole point of the in-browser model.++You're done if all you wanted was a vanity wallet. The remaining steps cover the **provably-fair** side of the protocol — relevant when a key was ground *for* you and you want to prove it was done honestly.++---++## Step 5: Understand the provably-fair grind (when the server holds the work)++If you buy a grind from the paid endpoint (`/api/x402/vanity-verifiable`, an x402-priced API), the server does the work and returns a **signed receipt**. Now there's a trust question the browser grind never had: *did they generate my key fresh, or grind a million candidates and quietly keep the one whose key they logged?*++`three-vanity/v1` answers this with a **commit–reveal + sealed-delivery + signed-receipt** scheme. In plain terms, the receipt lets you prove, after the fact, that:++1. the key came from entropy the server **committed to before** it knew your pattern (no precomputed table of keys);+2. **your own entropy** (`clientSeed`) was mixed in, so neither party alone controlled the address;+3. the address really derives from the revealed seed, matches your pattern, and the difficulty claim is the honest `58ⁿ` model;+4. the receipt was **signed by the real three.ws service key**, not an impostor;+5. (optionally) the key you recovered from the sealed envelope is byte-for-byte the one the receipt describes — **you alone hold it**.++A receipt is a JSON object carrying the `commitment`, the revealed `serverSeed` and `clientSeed`, the `requestNonce`, the `winningIndex`, the `pattern`, the `difficulty`, and an Ed25519 `signature` over a canonical projection of those fields. When you supply a `sealTo` X25519 public key, the secret is delivered as a `sealedSecret` envelope encrypted to you — the plaintext key never appears in the response. The full field list and signing rules are in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md).++---++## Step 6: Verify a receipt++Open **[/vanity/verify](/vanity/verify)**.++1. **Paste the receipt JSON** into the Receipt JSON box (the full object you received from `/api/x402/vanity-verifiable`).+2. *(Optional)* Expand **"prove you hold the key"** and paste **your X25519 private key** to open the sealed envelope and confirm custody. This key is used only in your browser to decrypt and compare — it is never sent anywhere.+3. Press **Verify receipt**.++The page runs every check locally and shows a pass/fail line for each:++- **protocol** — the receipt is `three-vanity/v1`.+- **commitment** — `SHA-256(serverSeed)` equals the published commitment, so the server was locked to that seed before grinding.+- **derivation** — re-deriving the master seed and the candidate at `winningIndex` reproduces exactly `receipt.address`.+- **pattern** — the address actually satisfies the requested prefix/suffix.+- **difficulty** — `difficulty.expectedAttempts` equals the honest rounded `58ⁿ` value.+- **signature** — the Ed25519 signature verifies, **and** the receipt's signing key matches the one pinned from the well-known document (impostors who self-sign under a different key fail here).+- **custody** *(if you opened the seal)* — the decrypted seed's public key equals `receipt.address`.++Before you even paste anything, the page fetches the live service key from [/.well-known/three-vanity.json](/.well-known/three-vanity.json) and pins it, so a forged receipt signed under a different key is caught. The verification logic is the open-source [src/solana/vanity/verifiable-grind.js](../../src/solana/vanity/verifiable-grind.js) (its `verifyVanityReceipt()` function), the same code the CLI and SDK use.++Prefer the command line? Run the open-source verifier:++```bash+node scripts/verify-vanity-receipt.mjs ./receipt.json --fetch-key+```++`--fetch-key` cross-checks the signature against the live well-known service key instead of the value pinned in the script. A single failing check means the receipt is not trustworthy.++---++## Step 7: Publish to the proof-of-grind gallery++The **[/vanity/gallery](/vanity/gallery)** is a public, ranked showcase of the rarest addresses ground on three.ws — each one provably-fair and verified.++Two things you can do there without publishing anything:++- **Appraise any address** — paste a Solana address and the gallery scores its rarity (tier, expected attempts, bonuses) using pure math, no persistence. Good for seeing how rare an address you already hold is.+- **Browse the leaderboard** — addresses ranked by an honest rarity score.++To **publish** one of your own (it's opt-in):++1. From the verify page, after a green verdict, click **Publish to the rarity gallery →** (or open the gallery's Publish tab directly).+2. The gallery submits your **receipt** to `/api/vanity/gallery`. The server re-verifies it against the live service key before storing anything.+3. Only public, secret-free metadata is kept — address, pattern, rarity, optional label. Secret fields (`secretKey`, `seed`, `sealedSecret`) are stripped client-side and rejected server-side, so there's no way to leak a key by publishing.++You can un-publish later by proving control of the key with an Ed25519 signature. Publishing is purely a flex — it never exposes anything that could spend your funds.++---++## Step 8: Post a bounty for a hard pattern++Some patterns are too slow for one machine (5–6+ characters can mean billions of attempts). **[/vanity/bounties](/vanity/bounties)** is a pay-for-results market: you escrow a reward, a fleet of independent workers grinds in parallel, and the first to find a verified match gets paid — without ever seeing your wallet.++To **create** a bounty:++1. Set the **pattern** (prefix/suffix). The page calls a difficulty oracle (`?view=quote`) and suggests an honest reward based on expected grind time.+2. **Generate or paste an X25519 recipient key.** This is the key the found secret will be **sealed to** — workers encrypt the result to you, so they earn the reward but can't keep your wallet.+3. Set the **reward** (denominated in **USDC**; there's a small floor) and an **expiry**.+4. **Escrow** the reward via x402 (USDC on Base or Solana mainnet). The bounty goes live once payment settles.++To **claim** a bounty (you're running grinders for others):++1. Poll open bounties with `GET /api/vanity/bounties?view=open`.+2. Grind the pattern with the same WASM grinder used on `/vanity-wallet`.+3. On a hit, **seal the secret to the requester's X25519 key** client-side, then submit `POST /api/vanity/bounties?action=claim` with the address, the sealed secret, and your payout address.+4. The server verifies the address matches the pattern and the envelope is valid, then settles atomically — only the **first** verified match is paid, on-chain, immediately.++When a bounty fills, the requester opens the sealed envelope with their X25519 **private** key — locally, the key never goes to the server — to recover the wallet. If a bounty expires unfilled, the escrow refunds to the requester. The bounty market is backed by [api/vanity/bounties.js](../../api/vanity/bounties.js).++> Rewards are **USDC**, the settlement asset for the bounty escrow. Nothing about a bounty involves any token other than the wallet you're grinding for.++---++## Bonus: Ethereum CREATE2 vanity addresses++The same idea applies to Ethereum, but for **smart-contract** addresses rather than wallets. **[/eth-vanity](/eth-vanity)** grinds a vanity *contract* address by searching **CREATE2 salts** — and crucially, no private keys are involved. A CREATE2 address is fully determined by the deployer, a salt you choose, and the contract's init-code hash:++```+address = keccak256(0xff ‖ deployer ‖ salt ‖ keccak256(initCode))[12:]+```++So the grind searches for a **salt** that produces a contract address matching your pattern. You feed that salt to your factory (Arachnid, CreateX, Safe, Coinbase, or any CREATE2 factory) at deploy time. The page runs the search in your browser, chain-agnostic and deployer-agnostic — there's no secret to protect, just a salt to hand to your deployment. The salt + factory details can be recorded against your agent identity via [api/agents/eth-vanity.js](../../api/agents/eth-vanity.js), which re-verifies the CREATE2 formula server-side before storing it.++---++## Troubleshooting++- **The grind is taking forever** — each extra character multiplies work by ~58. A 6-character case-sensitive pattern is billions of attempts; either shorten it, enable case-insensitive, raise the core count, or post a [bounty](/vanity/bounties) so a fleet grinds it.+- **The page froze / my fan spun up** — that's the grind using your cores. Lower the core slider or **Pause** to give your machine breathing room; resume when ready.+- **I closed the tab and lost the key** — there's no recovery. three.ws never received the key on the browser path. Always **Download** (or assign to an agent) before navigating away.+- **Verify says "could not fetch the live service key"** — the page falls back to verifying against the receipt's own key (unpinned). The signature still checks out, but to prove the signer is three.ws, retry so it can pin against [/.well-known/three-vanity.json](/.well-known/three-vanity.json).+- **A verify check fails (commitment / derivation / signature)** — the receipt is not trustworthy. A tampered address, swapped seed, wrong index, inflated difficulty, or an impostor signing key each fail by design. Do not use a key from a receipt that doesn't fully verify.+- **Custody check fails** — the X25519 private key you pasted doesn't match the `sealTo` the receipt was sealed to, or the envelope was altered. Use the exact private key matching the public key you sent as `sealTo`.+- **Bounty won't post** — confirm the recipient X25519 key is set and the escrow payment settled. The board fetches config (`?view=config`) to confirm payout is available before accepting a create.++---++## Recap++You learned to mine a Solana vanity address and to operate the proof-of-grind protocol around it:++- **Grind in the browser** ([/vanity-wallet](/vanity-wallet)) — pick a prefix/suffix, choose case sensitivity and cores, grind locally with WASM Web Workers, and download the key. Nothing leaves your device.+- **Difficulty is `58ⁿ`** — every character multiplies the work; case-insensitive roughly halves per letter.+- **Provably-fair paid grind** — when the server holds the work, `three-vanity/v1` proves the key was fresh, your entropy was mixed in, and no copy was kept.+- **Verify** ([/vanity/verify](/vanity/verify)) — paste a receipt to re-check commitment, derivation, pattern, difficulty, signature, and (optionally) custody, all in your browser, pinned to the live service key.+- **Gallery** ([/vanity/gallery](/vanity/gallery)) — appraise any address or opt-in publish a verified, secret-free receipt to the rarity leaderboard.+- **Bounties** ([/vanity/bounties](/vanity/bounties)) — escrow a USDC reward for a hard pattern; a fleet grinds it and seals the result to you.+- **CREATE2 vanity** ([/eth-vanity](/eth-vanity)) — the same grind for Ethereum contract addresses, searching salts, no keys involved.++The protocol itself is fully specified in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md), and the verifier is open source — you never have to take three.ws's word for it.++## See also++- [three-vanity/v1 protocol specification](../PROTOCOL-vanity.md) — the commit–reveal, seed-mixing, sealed-delivery, and signing scheme in full+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — give the agent that owns your vanity wallet durable context+- [Build a Custom Skill](/docs/tutorials/custom-skill) — extend that agent with new capabilities at runtime++---++<a id="sec-238"></a>> **Source:** `docs/tutorials/mint-pumpfun-token.md` · [↑ table of contents](#table-of-contents)@@ -42478,7 +48320,7 @@ If you have a lawyer, talk to them before launching. If you don't, default to th----<a id="sec-203"></a>+<a id="sec-239"></a>> **Source:** `docs/tutorials/multi-agent-coordination.md` · [↑ table of contents](#table-of-contents)@@ -43045,7 +48887,297 @@ async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {----<a id="sec-204"></a>+<a id="sec-240"></a>++> **Source:** `docs/tutorials/nvidia-3d-free.md` · [↑ table of contents](#table-of-contents)++# Generate 3D Models Free, Powered by NVIDIA++Every free text-to-3D generation in the Forge runs on **NVIDIA NIM** with **Microsoft TRELLIS** — a GPU model that turns a description into real, textured geometry. No API key, no credits, no cost to you. This tutorial shows what the free lane is, when it kicks in, how to get the best out of it, and how to watch TRELLIS rebuild a mesh live.++**What you'll make:** a 3D model generated for free on the NVIDIA NIM lane, downloaded as a GLB.++**Prerequisites:** none. No account, no wallet, no code. Just a browser.++---++## What the free NVIDIA lane is++When you type a prompt into the Forge, the default path is:++1. Your words become a **reference image**.+2. That image is reconstructed into a textured 3D mesh by **TRELLIS**, served on **NVIDIA NIM** (NVIDIA's inference microservice for hosted models).+3. The mesh is packaged as a **GLB** — the standard 3D file the whole web understands.++NVIDIA NIM keeps the GPU warm, so there's no slow cold start, and the lane costs the platform nothing per call — which is why it's the free default at the **Draft** and **Standard** tiers. You don't select it; it's simply what runs when you generate without bringing your own engine key.++---++## Step 1 — Open the Forge++Go to [three.ws/forge](/forge). You'll land on the **Describe it** tab — text-to-3D mode.++Leave the **Engine** selector on its default. That's the free NVIDIA NIM lane. (Bringing your own geometry engine key is optional and covered in [Turn a Text Prompt into a 3D Model](/tutorials/text-to-3d) — skip it here.)++---++## Step 2 — Describe one object++Type a single subject and name its material:++```+a glazed ceramic teapot+```++Keep prompts short. TRELLIS reads roughly the first **77 characters**, so a tight description beats a paragraph. Three rules:++1. **One object per prompt.** "a teapot" works; "a teapot on a table by a window" confuses it.+2. **Name the material.** "brushed metal", "worn leather", "glazed ceramic".+3. **No scenery.** You're describing a thing, not a photo — drop backgrounds and lighting moods.++Want a cookbook? See [Prompt Recipes for 3D Generation](/tutorials/prompts-for-3d).++---++## Step 3 — Pick a tier (both free lanes)++| Tier | What you get | Speed |+|------|-------------|-------|+| **Draft** | Fast, low-poly (~12k triangles) | ~15 s — generate five, keep the best shape |+| **Standard** | Balanced detail (~30k triangles) | ~1 min — the everyday default |++Both Draft and Standard route to the free NVIDIA NIM lane for text prompts. Higher tiers and photo input use other engines — see [What's next](#whats-next).++The tier maps to TRELLIS **sampling steps**: more steps, more refinement, more time. Draft runs lean; Standard spends a little longer for cleaner geometry.++---++## Step 4 — Generate and inspect++Click **Generate**. The Forge narrates each step — *painting reference image → reconstructing textured mesh → finalizing GLB* — and the preview image appears early, so you'll know within seconds whether it's on track.++When it finishes, the model loads in a live viewer:++- **Drag** to rotate, **scroll** to zoom.+- Press **F** for a fullscreen turntable; **Esc** to exit.+- Check the **back and underside** — that's where reconstruction flaws hide.++Then rate it **👍 Keep** or **👎 Discard**. Your verdicts feed the engine picker, so honest ratings make your future generations better.++---++## Step 5 — Watch TRELLIS run live (the NIM demo)++To see the NVIDIA NIM contract end to end — no UI in the way — open the live demo at [three.ws/forge-nim](/forge-nim).++It talks **directly** to a TRELLIS NIM and returns the GLB **synchronously** in a single call. Type a prompt or drop a photo, and you'll watch the raw model come back as bytes and render in the browser. It's the clearest way to understand what "powered by NVIDIA NIM" actually means — the same TRELLIS reconstruction the Forge uses, with the wire contract visible.++> The hosted NVIDIA preview only generates from **text prompts**. To reconstruct from your own **photos** on a NIM, you need a self-hosted TRELLIS NIM — that's the next tutorial.++---++## Step 6 — Download or share++- **Download GLB** — opens in Blender, three.js, Unity, Unreal, Windows 3D Viewer, and macOS Quick Look.+- **Share** — a link with a proper preview card.+- Every generation is also saved to **Your creations** at the bottom of the page, tied to your browser.++---++## Didn't get what you wanted?++| What went wrong | What to change |+|-----------------|----------------|+| Right object, wrong style | Add a style word: "low-poly", "realistic", "stylized" |+| Surface looks flat | Name the material, or run the **High** tier for PBR textures |+| Extra junk attached | Your prompt described a scene — cut it to just the object |+| "Generation limit reached" | The free lane is rate-limited per visitor. Wait a minute |++---++## What's next++- **Generate from your photos** → [Turn Photos into a 3D Model](/tutorials/image-to-3d).+- **Run TRELLIS on your own GPU** → [Run Microsoft TRELLIS on your own NVIDIA NIM](/tutorials/nvidia-nim-self-host) — self-host the NIM and reconstruct from photos too.+- **Generate from code** → [Generate 3D Models from Code](/tutorials/generate-3d-api) — the same engine as a plain HTTP API.+- **Use it as an agent body** → [Build your first agent](/tutorials/first-agent).++---++<a id="sec-241"></a>++> **Source:** `docs/tutorials/nvidia-nim-self-host.md` · [↑ table of contents](#table-of-contents)++# Run Microsoft TRELLIS on Your Own NVIDIA NIM++The free Forge lane uses NVIDIA's **hosted** TRELLIS preview, which only generates from text prompts. To reconstruct a 3D model from **real photos** — and to own the whole pipeline — you run the **TRELLIS NIM container** on your own NVIDIA GPU and point three.ws at it. This tutorial wires up a self-hosted NIM and drives it through the exact contract three.ws uses.++**What you'll build:** your own NVIDIA NIM serving text- and image-to-3D, reachable through the three.ws `/api/forge-nim` endpoint and the live [/forge-nim](/forge-nim) demo.++**Prerequisites:** an NVIDIA GPU (an L4 or better is plenty), Docker with the NVIDIA Container Toolkit, and an [NVIDIA NGC](https://ngc.nvidia.com) account for the API key that pulls NIM containers.++---++## Step 1 — Pull and run the TRELLIS NIM++TRELLIS ships as a NIM container at `nvcr.io/nim/microsoft/trellis` (the `large:image` build accepts real reference images).++```bash+# Log in to NGC with your NVIDIA API key+docker login nvcr.io -u '$oauthtoken' -p "$NGC_API_KEY"++# Run the NIM — it serves an OpenAPI inference server on :8000+docker run --rm --gpus all \+ -e NGC_API_KEY="$NGC_API_KEY" \+ -p 8000:8000 \+ nvcr.io/nim/microsoft/trellis:latest+```++The container exposes two endpoints three.ws relies on:++- `GET /v1/health/ready` — readiness probe (NIM convention).+- `POST /v1/infer` — reconstruct a GLB, returned **synchronously**.++A cold `large:image` build can take a while on its first hit; after that an L4 reconstructs in roughly **15–45 seconds**.++---++## Step 2 — Expose it over HTTPS++three.ws will only talk to a NIM over **https** whose host isn't a private, loopback, link-local, or cloud-metadata address — an SSRF guard, so the proxy can never be turned into an internal-network probe. Put your container behind a TLS terminator with a public hostname:++- a reverse proxy (Caddy/nginx) with a real certificate, or+- a tunnel (Cloudflare Tunnel, `ngrok`), or+- a managed GPU host (Cloud Run, a GPU VM) with HTTPS in front.++The result is a base URL like `https://trellis.yourdomain.com`.++---++## Step 3 — Point three.ws at your NIM++Set two environment variables on your three.ws deployment:++| Variable | What it is |+|----------|-----------|+| `MODEL_TRELLIS_URL` | The public https origin of your NIM, e.g. `https://trellis.yourdomain.com` |+| `NVIDIA_API_KEY` | Bearer token forwarded to the NIM (if your gateway requires auth) |++```bash+vercel env add MODEL_TRELLIS_URL production+vercel env add NVIDIA_API_KEY production+```++Confirm three.ws can see it:++```bash+curl "https://three.ws/api/forge-nim?action=health"+# → { "configured": true, "reachable": true, "baseUrl": "https://trellis.yourdomain.com", "endpoint": ".../v1/infer", "detail": "" }+```++`configured` means the URL is set; `reachable` means the readiness probe answered.++---++## Step 4 — Reconstruct from a prompt++`POST /api/forge-nim` is a thin, honest proxy: it shapes the request, forwards it to your NIM's `/v1/infer`, and hands the GLB straight back as base64.++```bash+curl -X POST "https://three.ws/api/forge-nim" \+ -H "content-type: application/json" \+ -d '{ "mode": "text", "prompt": "a glazed ceramic teapot", "tier": "draft" }'+```++Response:++```json+{+ "ok": true,+ "mode": "text",+ "tier": "draft",+ "contract": "artifacts[0].base64",+ "endpoint": "https://trellis.yourdomain.com/v1/infer",+ "bytes": 184320,+ "ms": 21540,+ "glb_base64": "Z2xURgIAAAA..."+}+```++Decode `glb_base64` to a file:++```bash+node -e 'const b=require("fs").readFileSync(0,"utf8");const o=JSON.parse(b);require("fs").writeFileSync("teapot.glb",Buffer.from(o.glb_base64,"base64"))' < response.json+```++`tier` maps to TRELLIS sampling steps — `draft` runs 15/15 (sparse-structure / structured-latent steps), `high` runs 40/40 for more refinement. Prompts are truncated to TRELLIS's 77-character window, so keep them tight.++---++## Step 5 — Reconstruct from a photo++This is the payoff of self-hosting: a NIM accepts a **real reference image** (the hosted preview won't). Send a data URI or a public image URL:++```bash+curl -X POST "https://three.ws/api/forge-nim" \+ -H "content-type: application/json" \+ -d '{ "mode": "image", "image": "https://example.com/chair.jpg", "tier": "high" }'+```++Reference images are capped at **10 MB**. The same `{ glb_base64, bytes, ms }` envelope comes back.++---++## Step 6 — See it in the browser++Open [three.ws/forge-nim](/forge-nim). The demo page calls the same `/api/forge-nim` endpoint, decodes the returned base64 into a Blob, and renders the GLB in a live viewer — text mode and photo dropzone both. It's the fastest way to confirm your NIM is wired correctly, with the NVIDIA NIM wire contract visible end to end: no R2 round-trip, no mocks, the raw bytes straight from your GPU.++---++## The raw NIM contract++If you'd rather call your NIM directly (bypassing three.ws), this is the contract `/api/forge-nim` speaks:++```http+POST {baseUrl}/v1/infer+{+ "mode": "image" | "text",+ "image": "data:image/png;base64,..." // image mode+ "prompt": "a glazed ceramic teapot", // text mode+ "ss_sampling_steps": 15,+ "slat_sampling_steps": 15,+ "output_format": "glb",+ "seed": 0 // optional, for reproducibility+}++200 { "artifacts": [ { "base64": "<glb>" } ] }+```++The proxy normalizes every documented artifact shape (inline `base64`, a bare string, a `data` field, or a URL artifact) to GLB bytes, so your NIM build just needs to return one of them.++---++## Troubleshooting++| Symptom | Cause & fix |+|---------|-------------|+| `configured: false` from health | `MODEL_TRELLIS_URL` isn't set on the deployment |+| `reachable: false` | The NIM's `/v1/health/ready` didn't answer — check the container and your TLS front |+| `nim_timeout` (504) | Cold `large:image` start; retry once the GPU is warm |+| `nim_auth` (502) | The NIM rejected the bearer — check `NVIDIA_API_KEY` or your gateway auth |+| `bad_base_url` (400) | An override `baseUrl` was http, an IP literal, or a private/`.internal` host |++---++## What's next++- **The no-code version** → [Generate 3D Models Free, Powered by NVIDIA](/tutorials/nvidia-3d-free).+- **Batch it from code** → [Generate 3D Models from Code](/tutorials/generate-3d-api).+- **Run the whole backend yourself** → [Self-host the agent backend](/tutorials/self-host-agent-backend).++---++<a id="sec-242"></a>> **Source:** `docs/tutorials/paid-x402-endpoint.md` · [↑ table of contents](#table-of-contents)@@ -43737,7 +49869,250 @@ Both work. Choose based on whether your endpoint is part of an agent platform yo----<a id="sec-205"></a>+<a id="sec-243"></a>++> **Source:** `docs/tutorials/pay-for-x402-service.md` · [↑ table of contents](#table-of-contents)++# Discover and Pay for an x402 Service++By the end of this tutorial you'll be able to find a paid API in the [Bazaar](/bazaar), pay for one call in USDC, and get back real work — no API key, no account, no subscription. You'll do it four ways: from the Bazaar UI with a wallet, from the hosted [/pay](/pay) checkout, programmatically with `window.X402.pay`, and by letting an autonomous agent shop the catalog for you on [/shopper](/shopper).++This is the **consume** side of x402. If you want to *build* an endpoint that takes these payments, see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) — this tutorial is everything on the other side of that handshake.++**Prerequisites:**++- A browser wallet: **Phantom** (or Solflare) for Solana, or **MetaMask** / **Coinbase Wallet** for Base (EVM). The checkout detects whichever is installed.+- A small USDC balance on the network you'll pay from. Most calls are $0.001–$0.01, so ~$1 USDC funds thousands of them. On Solana you also need a little SOL for the account; on Base the signature is gasless from your side.+- Light JavaScript familiarity for the programmatic path (Steps 5–6). The UI paths (Steps 2–4) need none.++---++## What you're building++Paying for an x402 service is two HTTP round trips and one wallet signature:++```+You → GET /api/some-paid-thing (no payment)+ ← 402 Payment Required { accepts: [ { network, asset, amount, payTo } ] }+You → sign a USDC payment for one of the `accepts`+You → GET /api/some-paid-thing (X-PAYMENT: <signed payload>)+ ← 200 { ...the actual work... } (X-PAYMENT-RESPONSE: <on-chain receipt>)+```++The price, the recipient, and the network all come from the seller's 402 challenge — you never type them. Your wallet signs exactly that amount to exactly that address, the platform settles it on-chain, and the original request is retried automatically. You either get what you paid for or you pay nothing.++---++## How discovery and payment fit together (two minutes of theory)++There are two distinct problems: **finding** an endpoint and **paying** it.++**Finding.** The [Bazaar](/bazaar) is a discovery surface. Server-side, [`/api/bazaar/list`](api/bazaar/list.js) and [`/api/bazaar/search`](api/bazaar/search.js) call each configured facilitator's `/discovery/resources` route, merge the catalogs, dedupe (HTTP by resource URL, MCP by `resource + toolName`), normalize the shape, and apply your filters. The default facilitators are PayAI (`facilitator.payai.network`, Base + Solana) and Coinbase CDP (`api.cdp.coinbase.com/platform/v2/x402`, Base + EVM L2s), wired in [`api/_lib/x402/bazaar-client.js`](api/_lib/x402/bazaar-client.js). An endpoint shows up here once it has answered a discovery probe with a valid 402 — there is no submission form. (How three.ws gets *its own* endpoints into those catalogs is the build-side concern covered in [paid-x402-endpoint](/tutorials/paid-x402-endpoint).)++**Paying.** Every payment runs through the same drop-in module, [`public/x402.js`](public/x402.js), exposed as `window.X402.pay(...)`. It does the 402 → sign → retry dance for you:++- For **Solana**, the wallet can only sign serialized transactions, so the module posts the challenge's `accept` to [`/api/x402-checkout?action=prepare`](api/x402-checkout.js), gets back a partially-signed SPL `transferChecked`, has Phantom add the buyer's signature, then `?action=encode`s it into the `X-PAYMENT` header.+- For **Base / EVM**, the wallet signs an EIP-3009 `transferWithAuthorization` typed-data message locally — no server prep needed.++Either way the signed payload is base64-encoded into `X-PAYMENT`, the gated request is retried once, and the unlocked result plus the decoded `X-PAYMENT-RESPONSE` receipt come back.++---++## Step 1: Browse the Bazaar++Open [/bazaar](/bazaar). You'll see a searchable, filterable grid of every paid service the facilitators currently advertise.++The sidebar filters map directly to the catalog query:++- **Type** — `http` (paid REST endpoints) or `mcp` (paid MCP tools). HTTP is the default.+- **Network** — Base, Arbitrum, Optimism, Polygon, Solana, or Base Sepolia.+- **Max price** — a USDC ceiling; entered in dollars, sent to the API as 6-decimal atomic units.+- **Extension** — narrow to endpoints advertising a specific x402 extension (e.g. `sign-in-with-x`).+- **Sort** — including by price, ascending.++Type a query (e.g. `weather`, `reputation`, `model`) and the page switches from `/api/bazaar/list` to `/api/bazaar/search`, ranking results against your terms. The footer shows which facilitators answered and which failed, so a single down source never blanks the page.++Each card shows the service name, description, price (minimum USDC across its `accepts`), supported networks, the provider host (links to its [/providers](/providers) profile), and — when several listings do the same job — a **peer hint** comparing prices across them. That last one matters: the same capability is often sold by multiple providers at different prices.++---++## Step 2: Pay for a service from the Bazaar++Find an HTTP service you want and click **Try it** on its card.++1. The drop-in payment modal opens, having already re-fetched the live 402 challenge to confirm the current price (prices can change; the card is a cached hint, the modal is the source of truth).+2. The modal shows the **price**, the **network**, and **who you're paying** — the on-chain `payTo` address, linked to a block explorer so you can verify the recipient before committing.+3. Pick your wallet. The modal only offers wallets that match a network in the challenge's `accepts` and are actually detected in your browser; undetected ones render disabled with an "install" hint.+4. Approve the payment in your wallet. Before prompting you, the modal does a fail-open balance pre-check — if it can positively read that your wallet is short, it shows an insufficient-funds state with the exact shortfall and an explorer link, instead of letting you sign a doomed transaction.+5. The platform settles on-chain and retries the call. The card's receipt area fills in with the result and a link to the on-chain transaction.++What you signed is exactly what the challenge declared — the modal never invents an amount or a recipient. If the seller configured optional charity / round-up giving on a Solana checkout, you'll see a pre-checked, opt-out box that rides the *same* transaction, so you still pay once.++> **MCP tools** can't be paid through this modal — they need a JSON-RPC `tools/call` envelope the modal doesn't speak. Clicking a `mcp`-type card opens the details panel instead, with the schema you'd wire into an MCP client. To call MCP tools by paying per-call, see [mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent).++---++## Step 3: Read the 402 challenge yourself++To understand what the modal is doing, hit a paid endpoint by hand. Any x402 endpoint answers an unpaid request with a 402:++```bash+curl -i https://three.ws/api/x402/model-check+```++You get back a `402 Payment Required` whose JSON body (and a base64 mirror in the `payment-required` response header) contains an `accepts` array. One entry looks like:++```jsonc+{+ "scheme": "exact",+ "network": "solana", // or "eip155:8453" for Base+ "amount": "1000", // 6-decimal atomic USDC → $0.001+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC mint+ "payTo": "<recipient address>",+ "maxTimeoutSeconds": 60,+ "extra": { "name": "USD Coin", "decimals": 6, "feePayer": "<sponsor>" }+}+```++Read it like a receipt-in-advance:++- **`amount`** is in atomic units of **`asset`**. With `decimals: 6`, `"1000"` is $0.001. (Spec-strict sellers may name this field `maxAmountRequired`; the client coerces both to `amount`.)+- **`network`** tells you which wallet you need. `solana` / `solana:*` → Phantom/Solflare; `eip155:8453` → Base; other `eip155:*` are the EVM L2s in [`EVM_NETWORKS`](public/x402-pay-core.js).+- **`payTo`** is exactly where your USDC goes. Nothing else moves.+- **`maxTimeoutSeconds`** bounds how long your signed authorization is valid — your one safety net against a stale payment lingering.++A single endpoint can list several `accepts` (e.g. Base *and* Solana). You — or your wallet — pick whichever network you hold funds on.++---++## Step 4: Pay through the /pay surface++[/pay](/pay) is the platform's own pay-per-call surface — a live demo that pays $0.001 USDC on Solana to call MCP tools and render 3D assets, with a settlement timeline you can watch step by step. Use it to see a real settlement end to end before wiring your own.++Two related routes sit under it:++- **[/pay/calls](/pay/calls)** — the public ledger of paid x402 calls to the platform. Each settled call gets a permalink (`/pay/calls/<tx-signature>`) showing the tool invoked and the on-chain transaction. This is your audit trail: every payment you make here is verifiable on-chain by anyone.+- **`/pay/c/<slug>`** — a *hosted checkout link*. A provider creates a SKU in their dashboard (see [`api/x402-skus.js`](api/x402-skus.js)) and shares the URL; the page hydrates from `/api/x402-skus?slug=<slug>` and opens the same drop-in modal pre-wired to that endpoint. If someone hands you a `/pay/c/...` link, paying it is identical to Step 2 — open it, pick a wallet, approve.++The point of the `/pay` surface: the *exact same* payment core ([`public/x402.js`](public/x402.js) and its sibling [`public/x402-pay-core.js`](public/x402-pay-core.js)) drives the Bazaar's "Try it", the hosted checkout, the full-page paywall, and the programmatic call below. Learn it once.++---++## Step 5: Pay programmatically with window.X402.pay++When you want to trigger a paid call from your own page or script, skip the UI and call the module directly. Load it once:++```html+<script type="module" src="https://three.ws/x402.js"></script>+```++Then pay for any endpoint:++```js+const out = await window.X402.pay({+ endpoint: 'https://three.ws/api/x402/model-check?url=' ++ encodeURIComponent('https://three.ws/avatar/character-studio/sample.glb'),+ method: 'GET',+ merchant: 'three.ws',+ action: 'Model Check',+});++if (out.ok) {+ console.log('result:', out.result); // the work product+ console.log('paid on:', out.payment.network);+ console.log('tx:', out.payment.transaction); // on-chain settlement+}+```++`pay()` opens the modal, runs discovery → connect → sign → verify → retry, and resolves with `{ ok, result, payment, response }`. On a user cancel it rejects with an error whose `code === 'cancelled'` — handle that distinctly from a real failure.++Useful options:++- **`body`** — a JSON object for `POST` endpoints (method defaults to `POST` when a body is present).+- **`headers`** — extra request headers forwarded on the paid retry.+- **`networks`** — an allowlist to force a single rail, e.g. `['solana']` for a Solana-only checkout, or `['evm']` / `['eip155:8453']`. The modal drops every `accept` outside the allowlist before rendering the wallet picker. If the filter would empty the list, it keeps the original accepts so a misconfigured allowlist never breaks a live checkout.++For a declarative trigger, any element with `data-x402-endpoint` is auto-bound on load and fires an `x402:result` (or `x402:error`) CustomEvent when done:++```html+<button+ data-x402-endpoint="https://three.ws/api/x402/model-check"+ data-x402-method="GET"+ data-x402-merchant="three.ws"+ data-x402-action="Model Check"+>Pay & Run</button>+```++To wire paid calls into an **agent's** conversation (so it buys mid-chat when the user asks), put the same pattern in a skill handler via `ctx.x402.fetch` — covered in [custom-skill](/tutorials/custom-skill) and the caller half of [paid-x402-endpoint](/tutorials/paid-x402-endpoint).++---++## Step 6: Let an agent shop the Bazaar for you++When you don't know *which* endpoint you need, the [Endpoint Shopper](/shopper) does the discovery, payment, and synthesis for you. Describe a task, set a USDC budget, and the agent searches the Bazaar for relevant endpoints, pays for each call it decides to make (capped at your budget), and returns a synthesized answer with a per-step cost breakdown.++```+Task: "What is the current price of ETH?"+Budget: $0.50+ ↓ [discover → plan → call (pays per endpoint) → synthesize]+Answer: "ETH is trading around $3,180." — total spent: $0.012 USDC across 2 paid steps+```++The page posts to `/api/agents/endpoint-shopper-run` with `{ task, maxCostUsd }`. The agent itself charges a small base fee and spends up to your budget downstream — set the budget at or above $0.01 so it can fund at least one paid call (the UI gates the button below that). The timeline shows each step's action (discover / plan / call / synthesize), the endpoint it hit, and what that step cost; the final row sums the spend, showing **"Free (no paid calls executed)"** when the task needed none.++If running the Shopper itself returns a 402, the page hands you off to the wallet paywall to unlock it — the same payment core as every other path here.++This is the autonomous consumer pattern: you express intent and a budget; the agent turns the Bazaar into a tool it pays for on demand. To coordinate multiple agents around a buying flow, see [multi-agent-coordination](/tutorials/multi-agent-coordination).++---++## Step 7: Verify what you paid for++Every successful payment returns an on-chain receipt — make a habit of checking it:++- **In the UI** — the Bazaar receipt and the modal both link the settlement transaction to a block explorer (Solscan for Solana, Basescan/Arbiscan/etc. for EVM).+- **Programmatically** — `out.payment.transaction` is the on-chain tx; `out.payment.network` and `out.payment.payer` tell you which rail settled and from which wallet.+- **On the public ledger** — platform calls land on [/pay/calls](/pay/calls) with a permalink anyone can audit.++If the result looks wrong but you were charged, note: x402 has **single-shot, no-refund** semantics — you pay for the *attempt*, not a guaranteed *result*. A failed call after settlement is not auto-refunded; retrying means a fresh payment. That's why the verify-then-work-then-settle ordering on the seller side (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint)) matters to you as a buyer: a correctly built endpoint never settles when its work failed, so you don't pay for nothing.++---++## Troubleshooting++- **"Payment module failed to load (x402.js)"** on a Bazaar card — the drop-in script 404'd or didn't evaluate, so `window.X402` is undefined. Reload the page; check the network tab for the `/x402.js` request.+- **Wallet button is disabled** — that wallet isn't detected, or no `accept` matches its network. Install the extension (Phantom for Solana, MetaMask/Coinbase for Base) and reload, or pick the other rail.+- **"Not enough USDC — you need X but your wallet holds Y"** — the balance pre-check caught a shortfall before you signed. Top up the wallet on the shown network (the error links your address on the explorer) and retry. The check is fail-open: if your balance can't be read, payment still proceeds.+- **"Endpoint did not return 402 (got 200/404…)"** — you pointed `pay()` at a free or non-x402 URL. Confirm the endpoint actually challenges with `curl -i <url>` (Step 3).+- **402 but "no `accepts` array could be found"** — a proxy stripped the body *and* the `payment-required` header, or the seller's challenge is malformed. Try the endpoint's own canonical URL; if it's third-party, the seller's 402 is non-compliant.+- **Signature rejected at settle on Base** — almost always a wrong EIP-712 domain. Base USDC's domain name is `"USD Coin"` at version `"2"`; a seller advertising anything else produces a payload the facilitator rejects. Nothing you can fix as a buyer — report it to the provider.+- **Solana checkout fails at "Authorize"** — usually a stale blockhash on a flaky RPC; the prepare endpoint fails open to a recent cached blockhash, so simply retry. A too-stale blockhash never confirms and never double-charges.+- **Clicking an MCP card doesn't open a payment modal** — by design; MCP tools open the details panel. Wire them through an MCP client ([mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent)).+- **Endpoint Shopper button stays disabled** — the budget is below $0.01 or the task is empty; the hint under the button names the exact unmet precondition.++---++## Recap++You learned four ways to consume an x402 paid service:++- **The Bazaar** ([/bazaar](/bazaar)) — search and filter the merged facilitator catalog, then **Try it** to pay with a wallet through the drop-in modal.+- **The /pay surface** ([/pay](/pay), [/pay/calls](/pay/calls), `/pay/c/<slug>`) — the platform's live pay-per-call demo, public on-chain ledger, and hosted checkout links — all driven by the same payment core.+- **`window.X402.pay`** — pay for any endpoint from your own code; resolves with the result plus an on-chain receipt, with a `networks` allowlist to pin the rail.+- **The Endpoint Shopper** ([/shopper](/shopper)) — describe a task and a budget; an agent discovers, pays for, and synthesizes results from Bazaar endpoints autonomously.++The throughline: discovery and payment are decoupled, the 402 challenge is the single source of truth for price and recipient, every payment settles on-chain in USDC, and one module ([`public/x402.js`](public/x402.js)) drives every surface.++**See also**++- [paid-x402-endpoint](/tutorials/paid-x402-endpoint) — the build side: ship your own endpoint that takes these payments.+- [mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent) — pay-per-call MCP tools.+- [custom-skill](/tutorials/custom-skill) — give an agent a tool that pays for a service mid-conversation.+- [multi-agent-coordination](/tutorials/multi-agent-coordination) — coordinate agents around a buying flow.++---++<a id="sec-244"></a>> **Source:** `docs/tutorials/personal-ai-site.md` · [↑ table of contents](#table-of-contents)@@ -44273,7 +50648,252 @@ The technical investment is one HTML file, a GLB avatar, and a system prompt. Th----<a id="sec-206"></a>+<a id="sec-245"></a>++> **Source:** `docs/tutorials/place-agent-irl.md` · [↑ table of contents](#table-of-contents)++# Place a 3D agent in your real environment with IRL++By the end of this tutorial you'll have walked one of your 3D agents around your living room — anchored to your real floor through the phone camera, steered with an on-screen joystick — and left it pinned at a real spot where anyone standing next to it can discover it. You'll do it all in the browser on your phone, with no app to install.++Along the way you'll understand the difference between **viewing a model in AR** and **placing an agent in the world**, how proximity discovery works, and exactly what your camera, motion, and location sensors do and don't share.++**Prerequisites:** a smartphone (iPhone with Safari, or an Android phone with Chrome). HTTPS is required for camera and motion access, so use the live site — open [three.ws/irl](/irl) on the phone itself. No account is needed to try it; signing in lets you place a permanent pin and switch between your own agents.++---++## What you're building++```+You, in your kitchen: open /irl → tap Camera AR → joystick-walk the agent across the floor+ → aim the camera at the spot you want → tap Pin here+ ↓+Anyone who walks up to that spot later: opens /irl, points their camera, and finds your+ agent standing exactly where you left it+```++IRL turns the real world into the stage. The camera feed becomes the floor, your phone's gyroscope keeps the agent locked in place as you turn, and a pin you drop is **private by location** — it's never on a map or a feed, only reachable by being physically near it.++---++## IRL is not the model viewer's AR (read this first)++three.ws has two camera-AR experiences. They look similar through the lens but solve different problems — don't confuse them.++| | [View in AR](/docs/tutorials/view-in-ar) | **IRL** (this tutorial) |+|---|---|---|+| Goal | See **one** 3D model at true scale in your room | **Walk and place** your agent in the world for others to find |+| Entry | The **AR** tab on any avatar / Forge model | The [/irl](/irl) product page |+| Movement | None — the model sits where you place it | Joystick / WASD walking, drag-to-orbit |+| Persistence | Nothing is saved | A **pin** that lives at a real GPS spot |+| Discovery | Private to you, this session only | Anyone standing nearby finds it in person |+| Multiplayer | No | Anonymous nearby presence, ambient reactions |++If you just want to orbit a single model in your kitchen, use [View in AR](/docs/tutorials/view-in-ar) — it covers iOS Quick Look, Android Scene Viewer, and WebXR for a one-off model. **This** tutorial is about the `/irl` product: a live, walkable agent you anchor and leave behind.++---++## How IRL works (two minutes of theory)++IRL is a phone-camera experience built on three sensors, each rendered **on your device**:++- **Camera** — `getUserMedia` with `facingMode: 'environment'` opens the rear camera and draws it full-screen behind a transparent Three.js canvas. That's the "passthrough": your real room shows through, the agent renders on top. Frames are never uploaded or stored.+- **Motion & orientation** — your phone's gyroscope (`deviceorientation`) keeps the agent locked to its spot as you turn to look around. iOS 13+ asks for a one-time permission gesture for this.+- **Location** — used only to drop a pin at the spot where you're standing and to find the handful of pins right around you. Your position is never shared with other users.++A **pin** is the unit of placement: an agent anchored at a real coordinate. The platform never exposes a list, map, or directory of pins. The only read that returns someone else's agent is the per-viewer proximity feed (`GET /api/irl/pins`), which requires you to send your *own* location and clamps the search radius to between 10 and 60 metres server-side. You discover agents by walking up to them — never by browsing where they are.++> WebGL is required to render the scene. On a browser without it, IRL shows a designed "this device can't run IRL AR" state and points you to [/agents](/agents) instead of throwing a blank canvas.++---++## Step 1: Open IRL on your phone++On the phone, go to [three.ws/irl](/irl).++You'll see your agent rendered against the ambient dark background, an **IRL** badge in the top bar, and a big white **Camera AR** button at the bottom. The subtitle reads *"Turn on Camera AR, then tap Pin here to anchor your agent in real space."* — that line is your always-visible signpost to the next step.++To start with a specific agent's avatar, append `?avatar=` to the URL:++```+https://three.ws/irl?avatar=YOUR_AVATAR_ID+```++An explicit `?avatar=` link always wins over the avatar you used last visit. (Links from an agent profile's "View in IRL" button also pass `?agent=` to deep-focus that agent's pin once it's nearby.)++---++## Step 2: Turn on Camera AR++Tap **Camera AR**.++The browser asks for camera permission — **Allow** it. This only happens once per origin. The rear camera feed fills the screen, the badge dot turns green, and the button switches to its active green state. Your agent is now standing on your real floor.++A few things are happening under the hood:++- The page requests the **environment-facing** camera (`facingMode: { ideal: 'environment' }`), so you get the rear lens, not the selfie cam.+- A single mutex owns the camera and render loop, so the passthrough and the 3D scene never fight over the GPU.+- On iOS, the page also asks for **Motion & Orientation** access — grant it so the agent stays locked in place when you rotate the phone. If you deny a sensor, a one-tap recovery chip appears so you can re-request it without digging through Settings.++If the camera doesn't start, jump to [Troubleshooting](#troubleshooting).++---++## Step 3: Walk the agent with the joystick (or WASD)++Now move the agent around your real space.++**On a phone**, a virtual joystick lives in the bottom-left corner. Drag it to walk; push further from center to move faster. Release to stop.++**On desktop** (or any device with a keyboard), use:++- `W` `A` `S` `D` or the arrow keys to move+- `Shift` to run+- Click-and-drag anywhere on the canvas to orbit the camera++The keyboard hints are shown on the right edge of the desktop layout. Movement keys are ignored while you're typing in a caption or message field, or while a sheet is open, so walking never fights with text input.++Walk the agent to the exact spot in your room where you want it to live — in front of your desk, by the door, on the rug. The camera passthrough is the floor; treat it like one.++---++## Step 4: Drop 3D objects on your floor (tap-to-place)++You can decorate the space with simple 3D props before you pin.++1. Tap **Add object** in the secondary row. The object picker slides up.+2. Choose a shape — **Orb**, **Crate**, **Crystal**, **Ring**, or **Pillar**.+3. Tap a spot on the floor through the camera. The object lands there at real-world scale, anchored to the surface you tapped.+4. Add as many as you like. Tap **Clear** to remove them all.++Tap-to-place uses a raycast from your tap into the scene, so objects sit where the floor is in view. These props are local scene dressing — they make the space feel inhabited while you compose the shot before pinning your agent.++---++## Step 5: Pin your agent in real space++This is the step that makes IRL different from the model viewer: you leave the agent behind at a real location.++1. Aim the camera so the agent is standing where you want it anchored.+2. Tap **Pin here**.+3. The caption panel slides up. Optionally add a short note — e.g. *"P2P trades here — DM me on Telegram."* Captions are optional.+4. Tap **Pin it**.++The agent locks to its spot. The status line confirms with something like *"Pinned facing north — others nearby can see you for 7 days."* While pinned, the joystick is hidden (a locked agent doesn't walk), and the gyroscope keeps it glued in place as you move your phone around it.++There are a few placement paths depending on your device and intent:++- **Pin here** — drops the agent at your current GPS spot using the camera + gyro. This is the default and works on every supported phone, including iOS Safari.+- **Place on floor** — appears only when your browser supports a WebXR `immersive-ar` session (Chrome on Android with ARCore). It uses real hit-test surface detection: sweep your phone slowly to find the floor, and the agent anchors to the detected plane. A green check confirms the anchor took.+- **Place on map** — pick a spot on a map instead of using your live position, useful for placing an agent somewhere you're not standing.++### Signed-in vs anonymous pins++- **Not signed in:** your pin works immediately and **expires on its own after 7 days**. The phone holds an anonymous device token (a bearer credential scoped to that device) so you can still manage your own anonymous pins.+- **Signed in:** the pin is permanent until you remove it, and you can switch which of your agents is placed via **My Agents**. Manage and remove your pins from your dashboard or the **My pins** sheet.++Either way, every pin you place is listed only to you — never in any public view.++---++## Step 6: Discover and interact with nearby agents++When you're standing near a pinned agent (yours or someone else's), it appears in your camera view with a name label. The top bar shows a green **"N nearby"** badge as agents resolve around you, and a directional nudge arrow rides the screen edge pointing toward the nearest one until it's on-screen.++Tap an agent's label or model to open its **inspect card**:++- Its bio, on-chain reputation tier, and any paid services it offers+- **Pay via x402** to use a service it sells+- **Leave a message** that lands in the owner's IRL feed+- **View profile** to open its full agent page+- **Report this pin** if something's wrong — a pin is hidden once enough distinct people flag it++If others are viewing the same area, you'll see an anonymous **"N viewing nearby"** presence chip. You can optionally opt in to **Appear nearby**, which shows you to co-viewers as a coarse ghost marker — never your precise GPS.++---++## Step 7: Understand location privacy (and the controls you hold)++This is the part to get right before you place agents in places you care about. The full breakdown lives on the [IRL location privacy page](/irl-privacy); here's what matters for using the product.++**The one-line model:** a placed agent appears to someone *only* when they're physically within a few dozen metres of it. There is no list, map, feed, or directory of where agents are — not for other users, and not public. Your own placements are visible only to you.++**What others can see:**++- An anonymous "someone is viewing nearby" count when you're in the same area+- A coarse ghost marker — but only if you opt in, snapped to a rough area+- An agent placed at a spot, once they're standing near it themselves+- An ambient reaction when someone interacts with an agent you're both near++**What no one can see:**++- A list, map, or directory of where agents are placed+- Your exact GPS coordinates — they stay on your device unless you place a pin+- Who placed any agent — no account or device id is ever attached (the public read strips `user_id`/`device_token` and returns only an `is_mine` boolean)+- Where you are when you're not within reach of an agent in person++**The controls** (open **Location & privacy** from the top bar — the shield icon):++- **Discovery precision — Precise or Approximate.** Approximate keeps your exact position off the servers while you browse; nearby agents resolve a little less precisely in exchange. Placement is always exactly where you choose.+- **Appear to others nearby — off by default.** Turn it on to show as a coarse ghost to co-viewers.+- **Your placements — remove anytime.** Every pin is in your dashboard, visible only to you. Anonymous pins also expire on their own after 7 days.++The camera and motion sensors are processed entirely on-device — camera frames are drawn to your screen and never uploaded; gyroscope readings position the scene in real time and never leave the phone. Location is checked only against what's within a few dozen metres of you, never a wider window.++---++## Troubleshooting++### "This device can't run IRL AR"++IRL renders the scene with WebGL. If your browser lacks it, you'll see a designed unsupported-device state instead of a blank canvas. Reopen IRL in an up-to-date Chrome, Safari, or Edge.++### The camera won't start++- **Permission denied.** Camera AR needs the rear camera. Re-grant it from the one-tap recovery chip, or in the browser's site settings, then tap **Camera AR** again. IRL requires HTTPS — `getUserMedia` is blocked on insecure origins, so use the live `https://three.ws/irl` (not a plain `http://` dev server).+- **Another tab or app holds the camera.** Close anything else using the camera and retry — only one consumer can hold it at a time.++### The agent drifts or won't stay locked when I turn++This is the motion sensor. On iOS, IRL needs a one-time **Motion & Orientation** permission granted via a tap — accept it when prompted, or re-request it from the recovery chip. Without the gyroscope, the agent can't stay anchored as you rotate the phone.++### "Place on floor" button never appears++That button is the WebXR hit-test path, available only where the browser supports an `immersive-ar` session (Chrome on Android with ARCore). iOS Safari has no `immersive-ar`, so it stays on the **Pin here** gyro + GPS path — which works fine; you just don't get plane hit-testing. Desktop never shows it (no camera passthrough).++### Nobody's nearby / the radar is empty++With a tight discovery radius and no map, an empty view is the *common* first experience — it means "keep exploring," not "broken." Walk around, or be the first to pin at your spot. If the nearby badge turns amber, the proximity read was temporarily rate-limited or unreachable; it self-heals on the next cycle.++### My pin disappeared++Anonymous pins (placed without signing in) expire after 7 days by design — the **My pins** sheet shows a live countdown so you know when. Sign in before pinning to make it permanent.++---++## Recap++You placed a live 3D agent in your real environment with the [/irl](/irl) product:++- **Camera AR** opens the rear camera as a full-screen passthrough; the agent renders on top of your real room.+- **Joystick / WASD** walk the agent across the floor; drag to orbit.+- **Add object** taps simple 3D props onto the detected floor.+- **Pin here** anchors the agent at a real GPS spot — anonymous pins last 7 days, signed-in pins are permanent.+- **Discovery is proximity-only:** agents are found by being physically near them, never via a map, list, or feed. Identity is stripped; your camera and motion stay on-device; location is used only for nearby proximity.++This is fundamentally different from viewing a single model in AR. If you only need to orbit one 3D model in your room, that's [View in AR](/docs/tutorials/view-in-ar) instead.++### See also++- [IRL — open the product](/irl) — place your agent now+- [How location works on IRL](/irl-privacy) — the full privacy model, sensor-by-sensor+- [Tutorial: Place your 3D model in AR](/docs/tutorials/view-in-ar) — the single-model viewer (Quick Look / Scene Viewer / WebXR)+- [AR & WebXR reference](/docs/ar) — the underlying AR methods and programmatic API+- [Privacy policy](/legal/privacy) — how your data is handled platform-wide++---++<a id="sec-246"></a>> **Source:** `docs/tutorials/prompts-for-3d.md` · [↑ table of contents](#table-of-contents)@@ -44409,7 +51029,7 @@ The tiers are explained in detail in [the text-to-3D tutorial](/tutorials/text-t----<a id="sec-207"></a>+<a id="sec-247"></a>> **Source:** `docs/tutorials/register-onchain.md` · [↑ table of contents](#table-of-contents)@@ -44739,7 +51359,7 @@ Your agent's URL will keep working as long as Base exists and IPFS gateways serv----<a id="sec-208"></a>+<a id="sec-248"></a>> **Source:** `docs/tutorials/self-host-agent-backend.md` · [↑ table of contents](#table-of-contents)@@ -45320,7 +51940,243 @@ A self-hosted instance with light traffic runs at $20–50/month all-in. The dom----<a id="sec-209"></a>+<a id="sec-249"></a>++> **Source:** `docs/tutorials/selfie-to-avatar.md` · [↑ table of contents](#table-of-contents)++# Turn a Selfie into a Rigged 3D Avatar++Take one front-facing photo and walk away with a rigged 3D avatar that looks like you — one you can drop onto an agent, animate, and embed anywhere. The Scanner handles capture, reconstruction, and auto-rigging end to end; you point a camera and name the result.++**Prerequisites:** a device with a camera (phone or laptop) or a clear front-facing photo to upload. No code, no 3D experience, and no account needed to start a scan. You'll want a [three.ws account](/create) to save the avatar and put it on an agent.++---++## What you're building++```+You: one front-facing selfie (optionally + left and right angles)+ ↓ [reconstruct → texture → auto-rig]+Result: a rigged GLB that looks like you — animation-ready,+ attached to an agent, downloadable for any engine+```++A flat photo has no geometry. The Scanner reconstructs a 3D head-and-body mesh, wraps your real face onto it as a texture, then **auto-rigs the mesh with a humanoid skeleton** so it can move — idle, walk, gesture — without you touching a rig. The output is a standard glTF 2.0 binary (`.glb`) that works in three.ws and in external tools (VRChat, Spatial, Unity, Unreal) alike.++This tutorial covers the full path: **capture → generate → auto-rig → put it on an agent**.++---++## How the flow works (one minute of theory)++The Scanner is one pipeline reachable two ways:++- **[/scan](/scan)** is the front door. It immediately forwards to **[/create/selfie](/create/selfie)**, which is the full capture experience (including the option to bring your own reconstruction key). Either URL gets you to the same place — `/scan` is the memorable one to share.+- **[/create/selfie](/create/selfie)** is where capture, the build progress, and the finished avatar all live.++Under the hood the page ([src/selfie-capture.js](../src/selfie-capture.js)) collects your photos, downscales them in your browser, and hands them to the pipeline ([src/selfie-pipeline.js](../src/selfie-pipeline.js)), which submits the job and polls for progress. There are exactly two calls:++1. `POST /api/avatars/reconstruct` — submit the photos, get back a `jobId`.+2. `GET /api/avatars/regenerate-status?jobId=…` — poll until the job reports `done`.++The job moves through visible stages — reconstructing the mesh, building geometry and textures, **auto-rigging the skeleton and skinning** — then returns the finished avatar's id. You never call the rig step yourself; it's part of the job. This is the platform-wide rule: every avatar three.ws creates is auto-rigged so it can animate. (For the rig internals, see [Avatar Creation](../avatar-creation.md).)++---++## Step 1: Take or pick a good photo++Result quality is mostly decided here. The face the engine can see clearly is the face you get back.++Five rules for the front-facing shot:++1. **Face the camera directly** — no extreme angles, chin level.+2. **Good, even lighting** — indirect daylight is ideal; avoid harsh shadows or backlighting.+3. **Remove anything covering your face** — sunglasses, masks, a hat brim over the eyes.+4. **Keep hair off your forehead and jawline** where you can — the engine needs your face outline.+5. **Plain background** helps the reconstruction isolate you.++You don't need a studio. A normal selfie in a well-lit room is plenty.++**Accepted formats:** JPEG, PNG, WebP, and HEIC/HEIF (iPhone photos work as-is). Photos are downscaled in your browser to a maximum of 1024px before upload — your original file never sits on disk, and only the generated avatar texture is kept.++---++## Step 2: Open the Scanner and add your photo++Go to **[/scan](/scan)** (it lands you on [/create/selfie](/create/selfie)).++You'll see one required slot: **Add a front-facing photo**. Two ways to fill it:++- **Use camera** — opens your camera in the browser with live face guides. Hold still inside the oval; the page checks framing, lighting, blur, and head angle and captures when it's a good frame.+- **Upload photo** — pick an existing image from your device.++If your browser or device can't open the camera (common on non-HTTPS connections and some desktop browsers), the camera option is disabled automatically — use **Upload** instead.++That one front-facing photo is all you need to build an avatar. The submit button stays disabled (showing "Add a photo to start") until a frontal photo is in place.++---++## Step 3: Add side angles for sharper geometry (optional)++Open the **Add side angles** disclosure to reveal two more slots:++- **Left** — turn your head about 45° to the left.+- **Right** — turn your head about 45° to the right.++Each extra angle is geometry the engine doesn't have to guess, so the sides and back of your head come out noticeably crisper. The trade-off is time: the submit button updates to reflect it — roughly **~90s** for one photo, **~120s** when you add angles.++Keep the same lighting and the same way-up across all three shots. Side angles are optional; skip them if you just want a fast result.++---++## Step 4: Choose style and body type++Two quick choices below the photos:++**Style**++- **Photoreal** — likeness-first; closest to how you actually look. (This is the default.)+- **Stylized** — cleaner, cartoon-leaning; good for streaming and games.++**Body type**++- **Masc** (default) or **Femme** — this selects the body proportions the rig is built on.++Pick the pair that fits how you'll use the avatar. You can always run another scan with different settings later — nothing here is permanent.++---++## Step 5: Build the avatar++Click the build button (it reads **Build my avatar · ~90s**, or the high-fidelity variant if you added angles).++What happens next:++- If you're not signed in, you'll be sent to sign in and returned to the Scanner — saving an avatar requires an account.+- The page submits your photos and switches to the build view: **"Building your avatar… This usually takes 1–2 minutes. Don't close this tab."**+- You'll see the pipeline narrate real progress as it works:++```+Queued — waiting for a reconstruction slot…+Generating 3D mesh from your photo…+Building geometry and textures…+Auto-rigging skeleton and skinning…+Finishing avatar…+```++That **"Auto-rigging skeleton and skinning…"** line is the step that makes the avatar movable — the reconstruction produces a mesh, and the pipeline fits a humanoid skeleton to it and binds the skin so animation clips can drive it. You don't trigger it; it's part of every build.++The build is resilient: the job id is held in your session, so if you reload mid-build the page resumes polling the same job instead of starting over. If the engine is busy you may see "Still working — this one is taking a bit longer…"; that's expected on the longer tail, not an error.++---++## Step 6: Why "auto-rigged" matters++A reconstructed mesh that isn't rigged is a statue — it can be viewed but not animated. That's why rigging is built into the create path, not an optional extra.++Across three.ws, **every avatar that gets created auto-rigs so it can move.** For the selfie flow the rig is fitted inside the reconstruction job (the step you watched in Step 5). For avatars that arrive already built — an uploaded GLB or a forged model — the same guarantee holds: if the mesh comes in static, the platform fires an auto-rig pass in the background and swaps the rigged version in place, with a sweep cron as a safety net so nothing gets stuck half-rigged. The mechanism differs; the outcome is identical: a humanoid you can animate.++Once rigged, the avatar drives the shared clip library. Bone names from common conventions (Mixamo, VRM, Unreal, and more) are mapped to a canonical skeleton, and idle/walk/gesture clips retarget onto it automatically — legs included. The practical upshot: the avatar you just built will move the moment you open it in the [Animation Studio](/pose), with no extra rigging work from you.++---++## Step 7: Name it and open your avatar++When the build finishes you land on the done view: **"Your avatar is ready."**++- It renders in a live 3D preview — drag to spin it and check the result. Look at the sides and back; if you skipped angles, that's where the engine had the least to work with.+- Give it a name in the **Name your avatar** field (up to 60 characters).+- Click **Open my avatar →** to go to your avatar's page at `/avatars/<id>`.++From the done view you can also:++- **Customize in editor** — opens the avatar in the editor (`/avatars/<id>/edit`) to adjust appearance, clothing, and accessories.+- **List on marketplace** — flips the avatar to public and takes you to its marketplace listing.+- **Not quite right — try again** — resets the form so you can rescan with a better photo or different settings.++Whatever you choose, the avatar is already saved to your account as a rigged GLB.++---++## Step 8: Put the avatar on an agent++An avatar is a body; an agent is the brain that lives in it. Creating an avatar already wires up an agent for you — the two are tied together so the avatar shows up, animates, and can transact.++You have two paths:++**It's already done.** When the avatar is saved, three.ws attaches it to an agent automatically: it links the avatar to one of your agents that doesn't yet have a body, and if you don't have one, it creates a default agent and gives it this avatar. Open **Open my avatar →** and the agent behind it is provisioned and ready.++**Reassign it deliberately.** If you want this avatar to become the face of a *specific* existing agent, attach it explicitly:++```js+await fetch('/api/onboarding/link-avatar', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ avatarId: 'your-avatar-uuid', // the id from /avatars/<id>+ force: true, // replace the agent's current avatar+ }),+});+// → { agent: { id, avatar_id, updated_at } }+```++`force: true` overrides an avatar the agent already has. Omit it (or set `false`) to only attach when the agent has no avatar yet. Either way the call is owner-scoped — you can only attach avatars to agents you own.++Once linked, give the agent a [personality](/tutorials/agent-personality) and a [brain](/tutorials/connect-ai-brain), then [share it](/tutorials/share-your-agent) or embed it on a site.++---++## Step 9: Use the avatar everywhere++Because the output is a clean, rigged glTF 2.0 file, it isn't locked to three.ws:++- **Animate it** in the [Animation Studio](/pose) — load it, browse the clip gallery, and retarget motion onto it live. It works because it's rigged.+- **Download the GLB** from the avatar page to use it in Unity, Unreal, Blender, or any glTF-aware tool.+- **Embed it** on a website with the web component — see [Embed in 30 seconds](/tutorials/embed-in-30-seconds).+- **Refine the look** with [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and more layer on without re-rigging.++---++## Troubleshooting++| Symptom | Likely cause | Fix |+|---|---|---|+| "Add a photo to start" won't go away | No frontal photo in the required slot | The front-facing slot is mandatory; side angles alone aren't enough |+| The **Use camera** option is missing or disabled | Browser/device can't open the camera (often non-HTTPS, or no camera) | Use **Upload photo** instead, or open the page in Safari/Chrome on a device with a camera |+| Build failed: "Try clearer photos in better light" | Blurry photo, no detectable face, or harsh lighting | Reshoot per Step 1 — face the camera, even light, nothing covering your face |+| Sides or back of the head look wrong | Only a frontal photo was provided | Add **Left** and **Right** angles (Step 3) and rebuild |+| "Photos are too large" | The upload exceeded the size limit | Photos are downscaled to 1024px in-browser; retry, or use a smaller source image |+| Asked to sign in mid-build | Saving an avatar needs an account | Sign in when prompted — you're returned to the Scanner and the build continues |+| "Too many requests" / rate-limited | Per-visitor cooldown after repeated attempts | Wait about a minute and try again |+| The reload during a build started a fresh scan | Rare; the pending job id wasn't found | The build resumes automatically when the job id is in your session — re-open [/create/selfie](/create/selfie) and let it poll |+| Asked for a reconstruction API key | This deployment runs in bring-your-own-key mode | Paste a key from the supported provider in the form shown; it's stored for your session only |++---++## Recap++You turned a single selfie into a rigged, agent-ready 3D avatar:++- **Capture** — one front-facing photo at [/scan](/scan) → [/create/selfie](/create/selfie); optional left/right angles sharpen the geometry.+- **Choose** — Photoreal vs Stylized, Masc vs Femme body type.+- **Generate** — `POST /api/avatars/reconstruct` builds the mesh and texture; the page polls `regenerate-status` and shows real progress.+- **Auto-rig** — the build fits a humanoid skeleton and skins the mesh so it can animate; this happens for every avatar three.ws creates, no manual step.+- **Attach** — the avatar is linked to an agent automatically, or attach it to a specific agent with `POST /api/onboarding/link-avatar`.++The result is a standard `.glb` that animates in the [Animation Studio](/pose), embeds on the web, and works in external engines — a real likeness of you, ready to move.++### See also++- [Turn Photos into a 3D Model](/tutorials/image-to-3d) — reconstruct an *object* (not a person) from a few photos in the Forge.+- [Animate your avatar](/tutorials/animate-your-avatar) — apply and tune motion on the rigged avatar you just built.+- [Avatar Creation](../avatar-creation.md) — the full reference: every creation path, rig requirements, and accessories.+- [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and styling on top of your avatar.+- [Give your agent a personality](/tutorials/agent-personality) — turn the body into a character.++---++<a id="sec-250"></a>> **Source:** `docs/tutorials/share-your-agent.md` · [↑ table of contents](#table-of-contents)@@ -45646,7 +52502,7 @@ The agent's URL is the durable handle. Embed it, link it, print it. The agent sh----<a id="sec-210"></a>+<a id="sec-251"></a>> **Source:** `docs/tutorials/skill-with-database-auth.md` · [↑ table of contents](#table-of-contents)@@ -46384,7 +53240,7 @@ Before this skill faces a real visitor:----<a id="sec-211"></a>+<a id="sec-252"></a>> **Source:** `docs/tutorials/swap-avatar-in-studio.md` · [↑ table of contents](#table-of-contents)@@ -46646,7 +53502,7 @@ The key insight is the snippet's stability. Once embedded, your customers' pages----<a id="sec-212"></a>+<a id="sec-253"></a>> **Source:** `docs/tutorials/text-to-3d.md` · [↑ table of contents](#table-of-contents)@@ -46766,7 +53622,7 @@ This is normal — prompt, generate, adjust, repeat is the workflow, not a failu----<a id="sec-213"></a>+<a id="sec-254"></a>> **Source:** `docs/tutorials/trigger-from-page-events.md` · [↑ table of contents](#table-of-contents)@@ -47270,7 +54126,7 @@ The pattern under all of these is the same: every recipe starts with `whenReady(----<a id="sec-214"></a>+<a id="sec-255"></a>> **Source:** `docs/tutorials/upload-custom-glb.md` · [↑ table of contents](#table-of-contents)@@ -47666,7 +54522,7 @@ Once the body is on the platform, the embed snippet doesn't change. The same `<a----<a id="sec-215"></a>+<a id="sec-256"></a>> **Source:** `docs/tutorials/view-in-ar.md` · [↑ table of contents](#table-of-contents)@@ -47841,7 +54697,590 @@ AR surface detection needs a moment to work. Move the phone slowly over the targ----<a id="sec-216"></a>+<a id="sec-257"></a>++> **Source:** `docs/tutorials/voice-and-lipsync.md` · [↑ table of contents](#table-of-contents)++# Give your agent a voice with synchronized lipsync++By the end of this tutorial your agent will **speak out loud** with a mouth that moves in time with the words — a real voice, real audio, and real-time viseme animation, all rendered in the browser. You'll pick or clone a voice in the [Voice Lab](/voice), see exactly how visemes drive an avatar's mouth in the two [/lipsync](/lipsync) labs, then wire voice into a live agent.++Along the way you'll understand why three.ws extracts visemes from the audio itself (no per-word timing service), how the same pipeline handles both TTS playback and a raw microphone, and what happens on avatars that have no viseme morphs at all.++**Prerequisites:** a three.ws account with at least one agent ([create one](/create)), a browser with Web Audio + WebGL (any modern desktop browser), and a microphone if you want to clone a voice or try the mic lab. No code is required for the labs; the live-agent step assumes light JavaScript familiarity.++---++## What you're building++```+Agent generates a reply+ ↓ POST /api/tts/speak (or /api/tts/eleven for a cloned voice)+Audio plays through a Web Audio AnalyserNode+ ↓ LipSyncAnalyser samples the frequency spectrum every frame+Per-viseme weights → avatar morph targets+ ↓+The avatar's mouth animates in sync with the speech — frame by frame, in WebGL+```++The mouth is not driven by a script or a timing file. The avatar listens to its own audio and shapes its mouth from what it hears, so any voice — a built-in one, a cloned one, even a live mic — drives the same animation path.++This tutorial covers the full chain: **choose a voice → understand visemes → wire voice into a live agent.**++---++## How lipsync works (two minutes of theory)++A **viseme** is the visual shape a mouth makes for a sound — the open jaw of "aa", the lip-press of "PP", the teeth-and-tongue of "SS". On a 3D avatar each viseme is a **morph target** (a blendshape) you can dial from 0 to 1.++three.ws uses the Oculus/ARKit viseme naming. The analyser ([`src/lip-sync-analyser.js`](src/lip-sync-analyser.js)) drives nine of them:++```js+export const VISEMES = [+ 'viseme_aa', 'viseme_O', 'viseme_E', 'viseme_I', 'viseme_nn',+ 'viseme_SS', 'viseme_FF', 'viseme_CH', 'viseme_PP',+];+```++Rather than rely on a server returning phoneme timestamps, the analyser reads the **audio's frequency spectrum** in real time through a Web Audio `AnalyserNode` and maps energy bands to mouth shapes:++| Frequency band | Drives | Why |+|---|---|---|+| Low (0–500 Hz) | `viseme_aa`, `viseme_O` | open vowels carry low-frequency energy |+| Mid (500–2k Hz) | `viseme_E`, `viseme_I`, `viseme_nn` | mid vowels and nasals |+| High (2k–8k Hz) | `viseme_SS`, `viseme_FF`, `viseme_CH` | sibilants and fricatives are bright |+| Amplitude dip | `viseme_PP` | a bilabial closure is a momentary silence |++Weights are smoothed with an exponential moving average so the mouth eases between shapes instead of snapping, and everything drops toward zero when the audio falls below a silence threshold. Because it's pure spectral analysis, **the audio never leaves the browser** and there's no per-word timing data to fetch or fall out of sync.++One important fallback: not every avatar has viseme morphs. The runtime detects this per avatar and picks a mode — `visemes` when ARKit viseme morphs exist, `jaw` when only `jawOpen` exists (it drives the jaw straight from the smoothed amplitude via `getAmplitude()`), and `none` when the rig has no mouth morphs at all. A face without visemes still opens and closes its jaw to the voice rather than sitting frozen.++---++## Step 1: Choose a built-in voice++The fastest path to a talking agent is a built-in TTS voice. The catalog lives in one place ([`api/_lib/tts-voices.js`](api/_lib/tts-voices.js)) so every picker and the synthesizer agree on what exists:++| id | character |+|---|---|+| `nova` | Bright and energetic — the default companion voice |+| `alloy` | Neutral and balanced |+| `ash` | Warm and expressive |+| `ballad` | Soft and lyrical |+| `coral` | Friendly and upbeat |+| `echo` | Calm and measured |+| `fable` | Expressive storyteller |+| `onyx` | Deep and authoritative |+| `sage` | Gentle and thoughtful |+| `shimmer` | Light and airy |+| `verse` | Dynamic and conversational |++The default is `nova`. These are synthesized by `POST /api/tts/speak` ([`api/tts/speak.js`](api/tts/speak.js)), which tries the free NVIDIA NIM Magpie lane first and falls back to OpenAI's `/v1/audio/speech`. You don't choose the provider — you choose the voice id, and the endpoint renders it on whichever lane is configured.++You can hear all of these immediately in the next step.++---++## Step 2: Hear visemes drive the mouth (TTS lab)++Open the **TTS-driven lipsync** lab at [/lipsync](/lipsync). This is the clearest way to see the whole pipeline at once.++1. Type a sentence in **Text to speak**.+2. Pick a **Voice** (`nova`, `alloy`, `echo`, `fable`, `onyx`, `shimmer`, `ash`, `coral`, or `sage`) and a **Speed** (0.8×, 1.0×, 1.2×, or 1.5×).+3. Click **Speak**.++What happens under the hood:++- The page `POST`s `{ text, voice, speed, format: 'mp3' }` to `/api/tts/speak` and gets back an audio clip.+- The clip plays through an `<audio>` element, and the [`wawa-lipsync`](https://www.npmjs.com/package/wawa-lipsync) library analyses it frame by frame, emitting a viseme code each tick.+- The page maps that code onto the avatar's Oculus-named morph targets:++```js+const VISEME_MAP = {+ aa: 'viseme_aa', PP: 'viseme_PP', FF: 'viseme_FF',+ TH: 'viseme_E', DD: 'viseme_E', kk: 'viseme_E',+ CH: 'viseme_CH', SS: 'viseme_SS', nn: 'viseme_nn',+ RR: 'viseme_O', ou: 'viseme_O', sil: null,+};+```++The **Visemes (live)** panel on the right shows which morph is firing each instant, and the log reports how many viseme morphs were wired on the loaded avatar (`N/N viseme morphs wired`). Watch the bars light up as the avatar talks — that's the morph target system being driven in real time.++> The TTS lab uses `wawa-lipsync`, which emits a discrete viseme code per frame. The live agent and the mic lab use the platform's own `LipSyncAnalyser`, which blends weighted bands. Both end at the same place — viseme morph targets — but the spectral analyser produces softer, overlapping shapes.++---++## Step 3: Verify the analyser with your own voice (mic lab)++To see the **exact analyser** that powers live agent speech, open the **audio-driven lipsync** lab at [/lipsync/mic](/lipsync/mic) and feed it your microphone instead of TTS.++1. Click **Start mic** and allow microphone access.+2. Speak. The nine-bar meter and the per-viseme readout update every frame, and the avatar's mouth tracks your voice.+3. Click **Stop** to release the mic and reset the morphs to zero.++This page wires the real pipeline directly:++- `getUserMedia({ audio: true })` → an `AudioContext` with an `AnalyserNode` (`fftSize = 256`, `smoothingTimeConstant = 0.7`).+- A `LipSyncAnalyser` ([`src/lip-sync-analyser.js`](src/lip-sync-analyser.js)) reads that node. Each frame it calls `analyser.sample()`, which returns the nine viseme weights, and applies them straight to the avatar: `mesh.morphTargetInfluences[index] = weight`.+- The mic node is deliberately **not** connected to the speakers, so you don't hear yourself echo.++Your audio never leaves the browser — analysis is `AnalyserNode` + `requestAnimationFrame`, nothing more. This is the same `LipSyncAnalyser` the live chat connects to its TTS output, so whatever mouth shapes you see here are what your agents will produce.++---++## Step 4: Clone your own voice (optional)++If you want your agent to speak in *your* voice instead of a built-in one, use the [Voice Lab](/voice). Cloning runs through ElevenLabs Instant Voice Cloning.++1. Open [/voice](/voice).+2. Read one of the suggested scripts aloud (or speak naturally) while recording. **20–30 seconds** is the recommended length; recording auto-stops at 60 seconds, and anything under 3 seconds is rejected. A live waveform and level meter show your input as you go.+3. Stop, then **review** the playback.+4. Give the voice a **name** (1–64 characters) and click **Clone**. The page uploads the sample to `POST /api/tts/eleven-clone` ([`api/tts/eleven-clone.js`](api/tts/eleven-clone.js)) as `multipart/form-data`.+5. On success you get a `voice_id`, and the voice is saved to your library (stored in `localStorage`, up to 20 voices).++**Test it in the playground.** Pick the cloned voice, type a sample line, and click Speak. The playground calls `POST /api/tts/eleven` ([`api/tts/eleven.js`](api/tts/eleven.js)) with `{ voiceId, text }`, which proxies ElevenLabs and caches the clip for 30 days (the hint shows `cached` vs `generated`). Default model is `eleven_flash_v2_5`; requests are capped at 500 characters and rate-limited to 1000 characters per hour per user.++> Instant Voice Cloning is a **paid-tier ElevenLabs feature** (Starter and up). If the server's account is on the free tier, the clone call returns the upstream error verbatim in the status line (e.g. a `can_not_use_instant_voice_cloning` message). Built-in voices in Step 1 have no such requirement.++Note the `voice_id` — you'll use it to give an agent the cloned voice in the next step.++---++## Step 5: Wire voice into a live agent++Now connect a voice to an agent so it speaks during conversation, with the mouth driven automatically.++The agent runtime ships two TTS providers that expose a shared `analyserNode`: `ElevenLabsTTS` ([`src/runtime/speech.js`](src/runtime/speech.js)) for cloned/ElevenLabs voices, and a neural TTS provider ([`src/runtime/neural-tts.js`](src/runtime/neural-tts.js)) that speaks the built-in catalog through `/api/tts/speak`. Whichever one an agent uses, the avatar wiring is identical.++The connection happens through two hooks the runtime sets on the TTS instance (see [`src/app.js`](src/app.js) and [`src/element.js`](src/element.js)):++```js+tts.onStart = () => {+ // Connect the avatar's LipSyncAnalyser to the TTS audio the moment it plays.+ if (tts.analyserNode) avatar.connectLipSync(tts.analyserNode);+};+tts.onEnd = () => {+ // Tear down lipsync so the mouth lerps back to neutral when speech ends.+ avatar.disconnectLipSync();+};+```++`connectLipSync(audioSource)` ([`src/agent-avatar.js`](src/agent-avatar.js)) builds a fresh `LipSyncAnalyser` on the TTS `AnalyserNode`; every render frame the avatar samples it and writes viseme weights (or, on a viseme-less rig, drives `jawOpen` from the amplitude). `disconnectLipSync()` zeroes the viseme and `jawOpen`/`mouthOpen` morphs so the face eases back to rest instead of freezing on the last shape mid-word.++For a cloned voice, construct the ElevenLabs provider with the `voice_id` from Step 4:++```js+import { ElevenLabsTTS } from './runtime/speech.js';++const tts = new ElevenLabsTTS({+ voiceId: 'your-cloned-voice-id', // from /api/tts/eleven-clone+ modelId: 'eleven_flash_v2_5', // default+ proxyURL: '/api/tts/eleven', // keeps the API key server-side+ stability: 0.5,+ similarityBoost: 0.75,+ useSpeakerBoost: true,+});+```++When the agent speaks, `tts.speak(text)` plays the clip; `onStart` fires on the audio's `playing` event and wires lipsync; `onEnd` tears it down. You don't touch morph targets yourself — binding the provider is enough.++---++## Step 6: Spatial audio (optional polish)++If your agent lives in a 3D scene rather than a flat panel, route its voice through a positional audio source so the sound comes from where the avatar stands. `AgentAvatar.setTTS(tts)` ([`src/agent-avatar.js`](src/agent-avatar.js)) binds the provider, and when a `THREE.PositionalAudio` is attached it forwards it to `ElevenLabsTTS.setPositionalAudio()`. The voice then attenuates with distance and pans with the avatar's position — the groundwork the [real-time voice preview](/blog/real-time-voice-interaction) describes for headset/WebXR deployment, where the agent's voice should come from the avatar in space.++This is opt-in: a flat embed plays voice normally without it.++---++## Troubleshooting++- **No sound, `503 not_configured` from `/api/tts/speak`** — no TTS provider is set on the server (neither `NVIDIA_API_KEY` nor `OPENAI_API_KEY`). Built-in voices need at least one lane configured.+- **`429` / "TTS rate limit exceeded"** — `/api/tts/speak` budgets per user (or per IP when anonymous), and `/api/tts/eleven` caps at 1000 characters/hour per user. Sign in for the higher limit, or wait for the hourly bucket to reset.+- **Clone fails with a quota / verification message** — Instant Voice Cloning is an ElevenLabs paid-tier feature. The endpoint passes the upstream body through so you see the exact reason (e.g. `can_not_use_instant_voice_cloning`). Use a built-in voice instead, or upgrade the ElevenLabs plan.+- **Clone rejected as too short** — the recorder requires at least 3 seconds; aim for the recommended 20–30 seconds for a usable clone.+- **Mic lab does nothing / "Microphone blocked"** — mic capture needs a secure (https) context and granted permission. The lab maps each failure to a designed state: blocked (allow access in the address bar), no device found, or mic busy (another app is using it). Fix and click **Try again**.+- **Avatar talks but the mouth doesn't move** — the loaded avatar has no viseme morphs. Check the TTS lab's log for `0/9 viseme morphs wired`. The runtime falls back to `jawOpen` if that morph exists, and to no mouth motion if the rig has none. Use an ARKit/Oculus-blendshaped avatar for full visemes.+- **Mouth freezes open after speech ends** — lipsync wasn't torn down. The runtime calls `disconnectLipSync()` from `tts.onEnd`; if you wire TTS manually, make sure that hook is set.+- **Cloned voice in the playground says `generated` every time** — the R2 cache keys on `voiceId + text + modelId + voice_settings`. Identical requests return `cached`; any change to text or settings is a fresh synthesis.++---++## Recap++You gave an agent a synchronized voice end to end:++- **Choose a voice** — eleven built-in voices in [`api/_lib/tts-voices.js`](api/_lib/tts-voices.js), synthesized by `POST /api/tts/speak` (free NVIDIA lane, OpenAI backstop), default `nova`.+- **Clone a voice** — record in the [Voice Lab](/voice), clone via `/api/tts/eleven-clone` (ElevenLabs IVC), play back via `/api/tts/eleven` with a 30-day cache.+- **Understand visemes** — the [TTS lab](/lipsync) and [mic lab](/lipsync/mic) show nine viseme morphs driven from the audio spectrum by [`src/lip-sync-analyser.js`](src/lip-sync-analyser.js) — no per-word timing, all in-browser.+- **Wire it live** — a runtime TTS provider exposes an `analyserNode`; `tts.onStart` calls `avatar.connectLipSync()` and `tts.onEnd` calls `disconnectLipSync()`, so the mouth follows the speech and returns to rest automatically — falling back to `jawOpen` on rigs without viseme morphs.++The leverage is that the avatar drives its mouth from the *audio it actually plays*, so a built-in voice, a cloned voice, and a live mic all flow through one analyser. Start with a built-in voice in the [TTS lab](/lipsync), then bring your own through the [Voice Lab](/voice).++## See also++- [Voice Lab](/voice) — record, clone, and test a voice+- [TTS-driven lipsync lab](/lipsync) — type text, watch visemes fire+- [Audio-driven lipsync lab](/lipsync/mic) — verify the analyser with your mic+- [Real-time voice interaction preview](/blog/real-time-voice-interaction) — the full listen-reason-speak pipeline and where AR/VR fits+- [Build a custom skill](/docs/tutorials/custom-skill) — `ctx.speak()` lets a skill make the agent talk mid-tool++---++<a id="sec-258"></a>++> **Source:** `docs/tutorials/walk-companion.md` · [↑ table of contents](#table-of-contents)++# Add the Walk Companion to your site++By the end of this tutorial you'll have a **3D avatar walking across your own website** — a corner mascot that idles, follows the cursor, and waves on navigation, plus a full-page playground the visitor can steer with WASD or a touch joystick. You'll add it two ways: a zero-build iframe you can paste onto any page, and the `@three-ws/walk` npm package when you want the real site-wide companion.++Along the way you'll see what the [/walk](/walk) product offers — live demos across six environments, the one-tag embed, the Chrome extension that walks the whole web, and the distance leaderboard — and exactly which attributes and APIs are real.++**Prerequisites:** a website you can edit and a WebGL-capable browser. The iframe path needs no tooling at all; the npm path assumes light JavaScript familiarity and that you already bundle [Three.js](https://threejs.org) (>= 0.150).++---++## What you're building++Two surfaces, one engine:++```+Corner companion Full-page playground+┌───────────────┐ ┌───────────────────────────┐+│ your page │ click │ ▢ walk across the page │+│ │ ────▶ │ WASD / joystick │+│ 🤖 ◀ idles │ ▢ ▢ │+│ follows cursor │ 🤖 strolling │+└───────────────┘ └───────────────────────────┘+```++The companion mounts in a corner and stays out of the way: it idles, turns to follow the cursor, waves when the visitor navigates, and greets each page. Click it and it **detaches into a full-page playground** — the visitor steers across the page from a gentle aerial view, or platforms across your real DOM with gravity and jumps. Walk onto a link and it opens like a doorway into the next page.++This is the same engine that powers the walking companion on three.ws, published as the `@three-ws/walk` package.++---++## The /walk product (two minutes)++Before you embed it, it helps to know what the live [/walk](/walk) page exposes — every piece below is something you can link to or reuse:++| Surface | Route | What it is |+|---|---|---|+| Walk app | [/walk/app](/walk/app) | Drive your avatar with WASD or a touch joystick across six environments |+| Live demos | embedded on [/walk](/walk) | Real (not video) iframes for `beach`, `night`, `grid`, and more |+| One-tag embed | [/walk-embed](/walk-embed) | The chrome-less iframe you drop on any site |+| Chrome extension | [/extension](/extension) | Your avatar walks over every page you visit, reading them aloud |+| Distance leaderboard | [/walk-leaderboard](/walk-leaderboard) | The longest strolls on three.ws — daily, weekly, all-time |++The six built-in environments are fixed and need no HDRI downloads: `studio`, `void`, `beach`, `sunset`, `night`, `grid`. You select one with the `env` query param.++---++## Step 1: The one-tag embed (no build step)++The fastest way to put a walking avatar on a page is the [/walk-embed](/walk-embed) iframe. It's intentionally chrome-less — no nav, no footer — so it drops cleanly into a card or a corner.++```html+<!-- three.ws Walk — drop in anywhere -->+<iframe+ src="https://three.ws/walk-embed?env=void&autoplay=true"+ width="360" height="480"+ style="border:0;background:transparent"+ title="three.ws walking avatar"></iframe>+```++That's the exact snippet the [/walk](/walk) page hands out. The background is transparent, so the avatar floats over whatever your page already has behind it.++### Embed query params++The embed reads its world and controls from the URL. The verified params:++| Param | Values | Effect |+|---|---|---|+| `env` | `studio` `void` `beach` `sunset` `night` `grid` | The environment (default scene if omitted) |+| `autoplay` | `true` | Start animating immediately |+| `controls` | `joystick` `keyboard` `none` | How (or whether) the visitor steers |+| `orbit` | `true` `false` | Allow drag-to-orbit the camera |+| `avatar` | a roster id or your avatar id | Which avatar walks |++A live, drivable demo on a beach:++```html+<iframe+ src="https://three.ws/walk-embed?env=beach&controls=joystick&autoplay=true"+ width="100%" height="520"+ style="border:0;background:transparent"+ title="Walk on the beach"+ allow="accelerometer; gyroscope"></iframe>+```++A passive showpiece (no controls, just walking) for a hero section:++```html+<iframe+ src="https://three.ws/walk-embed?env=void&autoplay=true&controls=none&orbit=false"+ width="360" height="480"+ style="border:0;background:transparent"+ title="three.ws walking avatar"></iframe>+```++The `allow="accelerometer; gyroscope"` attribute lets the joystick respond to device tilt on mobile. Add it whenever `controls=joystick`.++---++## Step 2: Drive the embed from the host page (postMessage)++The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).++Every message is namespaced to the `three-walk` channel and carries a protocol version, so it never collides with other `message` listeners on your page.++```html+<iframe id="walk" src="https://three.ws/walk-embed?env=studio&autoplay=true"+ width="360" height="480" style="border:0;background:transparent"+ title="three.ws walking avatar"></iframe>++<script>+ const frame = document.getElementById('walk');+ const send = (type, payload = {}) =>+ frame.contentWindow.postMessage({ channel: 'three-walk', v: 1, type, ...payload }, '*');++ // Wait for the avatar to load before commanding it.+ window.addEventListener('message', (e) => {+ if (e.source !== frame.contentWindow) return; // source check = auth+ const msg = e.data;+ if (!msg || msg.channel !== 'three-walk') return;++ if (msg.type === 'walk:ready') {+ send('walk:say', { text: 'Hi — thanks for visiting.' });+ send('walk:goto', { x: 4, z: 0 }); // walk to a world spot+ }+ if (msg.type === 'walk:position') {+ // { x, z, heading } streams ~10 Hz while the avatar moves+ }+ });+</script>+```++The commands a host can send (inbound) and the events the iframe emits (outbound), straight from the contract:++| Direction | Message | Payload |+|---|---|---|+| host → iframe | `walk:goto` | `{ x, z }` — walk to a world position, then stop |+| host → iframe | `walk:gesture` | `{ gesture }` — one of `idle` `walk` `run` `wave` `jump` |+| host → iframe | `walk:say` | `{ text, voice?, durationMs? }` |+| host → iframe | `walk:env` | `{ env }` — one of the six environments |+| host → iframe | `walk:avatar` | `{ avatarId }` |+| host → iframe | `walk:config` | `{ speed?, bg?, controls? }` |+| iframe → host | `walk:ready` | `{ avatarId, env }` (fires once, when loaded) |+| iframe → host | `walk:position` | `{ x, z, heading }` (~10 Hz while moving) |+| iframe → host | `walk:gesture` | `{ gesture }` |+| iframe → host | `walk:speak` | `{ text, durationMs }` |+| iframe → host | `walk:error` | `{ code, message }` |++Two things the runtime enforces, so plan around them:++- **The source check is the authentication.** The iframe only accepts messages whose source is its parent window; your host listener should likewise gate on `e.source === frame.contentWindow`. The optional origin allow-list is belt-and-suspenders on top of that.+- **Inputs are clamped and bounded.** `walk:goto` coordinates are clamped to the world radius (about ±11.5m), `walk:say` text is capped at 280 characters, and unknown commands come back as a `walk:error` rather than silently failing.++If you mount the iframe *after* it has already loaded and miss the initial `walk:ready`, send `walk:ping` and the iframe re-emits `walk:ready`.++---++## Step 3: The real site-wide companion (npm)++The iframe is great for a fixed card. For the actual corner-mascot-plus-playground experience that follows the visitor across your whole site, install the SDK.++```bash+npm install @three-ws/walk three+```++`three` is a **peer dependency** — the package brings none of its own; you supply >= 0.150 from your app.++```js+import { createWalkCompanion } from '@three-ws/walk';++const walk = createWalkCompanion();+walk.bootstrap();+```++`createWalkCompanion` is **side-effect free on import** — nothing touches the DOM, and no Three.js is fetched, until you call `bootstrap()` or `enable()`. A page that never turns the companion on pays nothing for shipping the import.++`bootstrap()` is the app-style entry: it auto-mounts based on the visitor's saved preference, honors `?walk=` deep links, and resumes the playground after a page "dive." If you'd rather drive it yourself:++```js+const walk = createWalkCompanion({ defaultAvatarId: 'fox' });++walk.enable(); // mount the corner companion+walk.openPicker(); // let the visitor choose an avatar+walk.setAvatar('michelle'); // persist + hot-swap the live avatar+walk.disable(); // remove it+```++The returned control object surface:++```ts+walk.isEnabled(): boolean+walk.enable(): void+walk.disable(): void+walk.toggle(): void+walk.setAvatar(idOrEntry): void // persist + hot-swap the live avatar+walk.openPicker(): void+walk.bootstrap(): void // auto-mount + ?walk= deep links+walk.instance // the live companion (or null)+```++### URL controls++Once `bootstrap()` is wired, these query params work on any page:++- `?walk=1` — force the companion on+- `?walk=0` — force it off+- `?walk=play` — deep-link straight into the full-page playground+- `?avatar=<id>` — load a specific avatar (a roster id, or one of your own)++---++## Step 4: Point the SDK at your assets++The companion needs two sets of assets served from your origin (or a CDN you point at). The defaults match the three.ws layout; override them when yours differ.++- The avatar GLBs the roster references (e.g. `/avatars/*.glb`).+- The shared animation manifest + clips (`/animations/manifest.json` + clips), used to retarget motion onto rigs that ship no locomotion.++```js+createWalkCompanion({+ assetBase: 'https://cdn.example.com', // prepended to static GLB paths+ apiBase: '', // prepended to the /api/avatars/<id>/glb proxy+ manifestUrl: '/animations/manifest.json',+ docsUrl: '/avatar-studio', // "make your own" link in the picker footer+}).bootstrap();+```++Other options worth knowing: `excludedRoutes` (path prefixes where the companion never mounts — full-screen 3D routes by default), `enablePicker` (set `false` to hide the avatar switcher), `greeting` (a `(path) => string | null` to customise the per-page hello), and `storagePrefix` (the localStorage/sessionStorage key namespace, default `walk`).++---++## Step 5: Choose who walks — the roster++Every visitor can pick who walks with them from a built-in roster: a robot mascot, humanoids, a fox, dancers, and showpieces. Each entry declares a rig strategy so it **always moves** — nothing freezes in a bind/T-pose:++| `rig` | Used for | How it animates |+|---|---|---|+| `embedded` | self-animated or non-humanoid GLBs (robot, fox) | plays the clips baked into the GLB; falls back to the first clip so it never freezes |+| `shared` | humanoids with no locomotion (or only a T-pose) | retargets the shared clip library (`idle`/`walk`/`run`/`wave`/`jump`) onto the rig |++The default avatar is `robot`. To extend the roster with your own brand mascot:++```js+import { createWalkCompanion, WALK_AVATARS } from '@three-ws/walk';++createWalkCompanion({+ avatars: [+ ...WALK_AVATARS,+ {+ id: 'mascot',+ name: 'Our Mascot',+ category: 'Brand',+ asset: '/brand/mascot.glb',+ source: 'static',+ rig: 'shared', // retarget the shared library onto it+ accent: '#ff0066',+ },+ ],+ defaultAvatarId: 'mascot',+}).bootstrap();+```++User-generated avatars served by the GLB proxy (`/api/avatars/<id>/glb`) resolve at runtime via `makeApiAvatarEntry(id)` — you don't have to list them.++---++## Step 6: Walk the whole web — the Chrome extension++The embed and SDK put the avatar on *your* site. The Chrome extension puts it on *every* site the visitor opens. Link to [/extension](/extension) from your page, or just point people there.++What the extension does, per the product page:++- The avatar walks over any page the user visits — articles, docs, social feeds.+- It reads pages aloud as it strolls — a living browsing companion.+- The visitor picks any of their three.ws avatars from the popup and switches in one click.+- Minimal permissions, no tracking. Privacy details are on [/extension/privacy](/extension/privacy).++This is the one path you don't embed — you point your visitors at the install. It's the most ambitious surface of the [/walk](/walk) product, and the strongest reason to give your users a three.ws avatar in the first place.++---++## Step 7: The distance leaderboard++Every stroll logs distance, and the longest ones climb the global board at [/walk-leaderboard](/walk-leaderboard) — ranked daily, weekly, and all-time. The data is real, served from `/api/walk/leaderboard`, so you can surface a "top walkers" teaser on your own page:++```js+async function loadTopWalkers() {+ const res = await fetch(+ 'https://three.ws/api/walk/leaderboard?period=all-time&metric=distance',+ { headers: { accept: 'application/json' } },+ );+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ // The endpoint may return { leaders } | { walkers } | { entries } | [...]+ const rows = Array.isArray(data)+ ? data+ : data.leaders || data.walkers || data.entries || data.results || data.data || [];+ return rows.slice(0, 3); // each: { name, distance, image_url?, url? }+}+```++Format distances for display the way the live page does — meters under 1km, kilometres above:++```js+function formatDistance(meters) {+ const m = Number(meters);+ if (!Number.isFinite(m) || m <= 0) return '—';+ if (m >= 1000) return (m / 1000).toFixed(m >= 10000 ? 0 : 1) + ' km';+ return Math.round(m) + ' m';+}+```++Always design the empty and error states: a fresh deployment has no walks logged yet, and a transient fetch failure should offer a retry rather than a blank panel.++---++## Troubleshooting++- **Iframe is blank / "loading avatar…" never clears** — the host needs WebGL. Confirm the browser is WebGL-capable and the page isn't blocking the iframe with a restrictive `Content-Security-Policy` `frame-src`. The embed ships `frame-ancestors *`, so it's the host CSP that usually blocks it.+- **postMessage commands do nothing** — you're probably sending before `walk:ready`. Wait for the `walk:ready` event, or send `walk:ping` to re-trigger it. Also confirm your envelope is `{ channel: 'three-walk', v: 1, type, ...payload }` — messages without the channel are ignored unless they use a known legacy `walk:*` type.+- **`walk:goto` lands somewhere unexpected** — coordinates are clamped to the world radius (~±11.5m). A target outside the ground disc is pulled back in.+- **`walk:env` rejected with a `walk:error`** — `env` must be exactly one of `studio` `void` `beach` `sunset` `night` `grid`. Anything else is refused.+- **Avatar shows a frozen T-pose** — that means the rig strategy is wrong for the GLB. A humanoid that ships only a T-pose must use `rig: 'shared'` so the shared clip library is retargeted onto it; `embedded` is only for GLBs that carry their own clips.+- **SDK throws on import about `three`** — `three` is a peer dependency. Install it (`npm install three`) and make sure your bundle resolves a single copy >= 0.150.+- **Companion never appears after `bootstrap()`** — check it's not an excluded route. By default the corner mascot skips full-screen 3D paths (`/walk`, `/walk-embed`, `/play`, `/ar`, and similar). Override `excludedRoutes` if your paths overlap.+- **The companion loaded Three.js on a page that doesn't use it** — it shouldn't: `createWalkCompanion` is side-effect-free on import and fetches nothing until `enable()`/`bootstrap()`. If you see a fetch, something is calling `enable()` unconditionally.++---++## Recap++You added a walking 3D avatar to your site three ways and learned what the [/walk](/walk) product ships:++- **One-tag embed** — paste the [/walk-embed](/walk-embed) iframe, pick the world and controls with query params (`env`, `controls`, `orbit`, `avatar`). No build step.+- **postMessage contract** — drive the embed from the host page with `walk:goto` / `walk:say` / `walk:env` and listen for `walk:ready` / `walk:position`, on the versioned `three-walk` channel. Full reference at [/docs/walk-embed-api](/docs/walk-embed-api).+- **`@three-ws/walk` SDK** — `createWalkCompanion().bootstrap()` mounts the real corner companion plus the full-page playground, side-effect-free until enabled, with a built-in avatar picker and a two-strategy roster that never T-poses.+- **The product surfaces** — the [/extension](/extension) that walks the whole web, and the distance [/walk-leaderboard](/walk-leaderboard) you can read from `/api/walk/leaderboard`.++The leverage is composability: the same engine renders the corner mascot, the full-page playground, the standalone embed, and the extension — so an avatar you build once walks everywhere.++## See also++- [Walk docs](/docs/walk) — the full developer + user reference for the walking-avatar system+- [Walk embed API](/docs/walk-embed-api) — interactive playground for the postMessage contract+- [Swap your avatar in Studio](/docs/tutorials/swap-avatar-in-studio) — build the avatar that walks+- [Embed your agent on a website](/docs/tutorials/embed-on-website) — the other side of putting three.ws on your page++---++<a id="sec-259"></a>> **Source:** `docs/tutorials/web-component-end-to-end.md` · [↑ table of contents](#table-of-contents)@@ -48440,7 +55879,2862 @@ The web component is the most robust integration point the platform offers. Buil----<a id="sec-217"></a>+<a id="sec-260"></a>++> **Source:** `docs/ux-flows/01-onboarding-creation.md` · [↑ table of contents](#table-of-contents)++# 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`.++---++<a id="sec-261"></a>++> **Source:** `docs/ux-flows/02-forge-text-to-3d.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-262"></a>++> **Source:** `docs/ux-flows/03-3d-editing-viewer.md` · [↑ table of contents](#table-of-contents)++# 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).++---++<a id="sec-263"></a>++> **Source:** `docs/ux-flows/04-embed-widget-studio.md` · [↑ table of contents](#table-of-contents)++# 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>++---++<a id="sec-264"></a>++> **Source:** `docs/ux-flows/05-discovery-social.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-265"></a>++> **Source:** `docs/ux-flows/06-marketplace-skills.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-266"></a>++> **Source:** `docs/ux-flows/07-crypto-trading-analytics.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-267"></a>++> **Source:** `docs/ux-flows/08-coin-launch-wallets.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-268"></a>++> **Source:** `docs/ux-flows/09-x402-agent-commerce.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-269"></a>++> **Source:** `docs/ux-flows/10-chat-brain-labs.md` · [↑ table of contents](#table-of-contents)++# 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.++---++<a id="sec-270"></a>++> **Source:** `docs/ux-flows/11-account-dashboard.md` · [↑ table of contents](#table-of-contents)++# 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, <name>."); 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 <section>"); 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.++---++<a id="sec-271"></a>++> **Source:** `docs/ux-flows/12-home-and-content.md` · [↑ table of contents](#table-of-contents)++# Home & Content Pages++This atlas covers the landing page (`/`) in full and every content / read-only+page on three.ws. The home page is highly interactive (live 3D agents, embedded+Forge / pose / token widgets); the content pages are mostly read-only but several+carry real interactive bits (docs search, glossary filter, status polling,+copy-to-clipboard, countdown, newsletter signup, embedded 3D viewers) — all+confirmed against source.++---++## Home — `/`++- **Source:**+ - Markup + inline modules: `pages/home.html` (6921 lines; served via `vercel.json` `"/" → "/home.html"`)+ - Lazy-mounted widget modules: `src/home-forge.js`, `src/home-pose.js`, `src/home-act2-viewer.js`, `src/home-live-token.js`+ - Other lazy mounts referenced by inline scripts: `src/avatar-drop.js`, `src/walk-embed-preview.js`, `src/pump/homepage-launcher.js`, `src/api-playground.js`, `src/forge-embed-snippets.js`, `src/erc8004/qr.js`+ - Web component runtime: `<script src="https://three.ws/agent-3d/latest/agent-3d.js">` (line 2430) + `/embed.js`+ - Chrome: `/nav.js`, `/footer.js`+- **Entry point:** Root route. No auth. The hero `<agent-3d>` and the capability/press strips render immediately; every widget below the fold is lazy-loaded on `IntersectionObserver` to keep the initial payload light.+- **Prerequisites / gates:** None. Fully public, no wallet/login. The mini-Forge uses an anonymous device `forge:cid` handle (localStorage); no sign-up required to generate a model.+- **Steps (the landing flow is browse-and-branch, not linear; the "required" path is reach a CTA → click → leave to a product route):**+ 1. Land on hero — headline "The 3D agent layer of the internet.", three hero bullets, a live `<agent-3d>` on stage, and the eyebrow link "New · Text → 3D is live…" → `/forge`.+ 2. (Optional) Trigger a hero animation chip (🎲 Random, 👋 Wave, 💃 Dance, 🤸 Capoeira, 🦘 Jump, 🧟 Thriller, 🙏 Pray) — drives the live agent; a counter tracks triggers.+ 3. Choose a primary CTA: **"Build your agent →"** → `/create`, **"Text → 3D"** → `/forge`, or **"See the embed"** → `#embed` anchor (in-page Playground).+ 4. (Optional) Scroll through the page's ~23 sections, each demoing a capability with a live widget and its own CTA (see Decision points below).+ 5. Click any CTA to leave for the target product route.+- **Decision points / branches (every body CTA → destination, exact labels):**+ - Hero / eyebrow: eyebrow → `/forge`; "Build your agent →" → `/create`; "Text → 3D" → `/forge`; "See the embed" → `#embed`.+ - Three Doors (02): "Start building" → `/create`; "Read the docs" → `/docs`; "Set up monetization" → `/dashboard/monetize`.+ - What You Get cards: "Open viewer" → `/playground`; "Widget Studio" → `/widgets`; "Claim your subdomain" → `/dashboard/account`.+ - Community Forge: "Generate yours →" → `/forge`.+ - Pose Studio: "Pose Studio" → `/pose`; "Open this pose in the full studio →" → `/pose?…` (carries pose params).+ - Mini Forge: "open the full Forge →" → `/forge`.+ - AR: "Forge gallery"/"Generate your own model →" → `/forge`; "Browse the avatar gallery →" → `/gallery`; "AR feature overview →" → `/features/ar`; "How AR works →" → `/blog/see-your-3d-in-ar`.+ - Capabilities Bento: "Continue in Avatar Studio →" → `/create/selfie`.+ - Pump.fun token (04): "Explore token agents →" → `/launches`; "Trending tokens" → `/radar`; "Launch yours" → in-page launcher (`src/pump/homepage-launcher.js`).+ - Oracle: "Open Oracle →" / "View all conviction scores →" → `/oracle`.+ - Pay-per-call: "Configure monetization →" → `/dashboard/monetize`.+ - Walk: "See walk mode →" → `/walk`.+ - Developer platform (05): "Get a key"/"Get API key →" → `/dashboard/api`; "Docs" → `/docs`; "GitHub" → github.com/nirholas/three.ws; "OpenAPI" → `/api/openapi-json`; "MCP server" → `/docs/mcp`.+ - The Stack (07): Studio → `/studio`; Registry → `/discover`; Embed → `/docs`; Pay-per-call → `/dashboard/monetize`; Walk → `/walk`; SDK → `/docs/sdk`.+ - Showcase 3D (08): "Browse all" → `/discover`; "Make your own" → `/create`.+ - Avatar Drop (09) & Vclose: "Build your agent →" → `/create`; "Text → 3D" → `/forge`; "Read the docs" → `/docs`.+ - Footer (6 columns): Product (`/create`, `/forge`, `/marketplace`, `/discover`, `/pricing`, `/dashboard`), Explore (`/agents`, `/reputation`, `/characters`, `/gallery`, `/bazaar`), Developers (`/docs`, `/avatar-sdk`, `/dashboard/api`, `/artifact`, `/sitemap`), Integrations (`/galaxy`, `/x402`, `/aws`), Company (`/blog`, `/community`, X, GitHub, `mailto:[email protected]`), Legal (`/legal/privacy`, `/legal/tos`), plus a "$THREE contract address" copy button.+- **Embedded interactive widgets (in-page, no navigation required):**+ - **Hero agent** — live `<agent-3d>` + 7 animation chips.+ - **Playground (`#embed`)** — editable embed-code textarea (HTML/React/Vue tabs), mode chips (inline/widget), background chips, feature toggles (responsive/nameplate/chat/eager), live `<agent-3d>` preview, 7 animation test chips, copy-code button.+ - **Mini Forge (`#home-forge`, `src/home-forge.js`)** — real text-to-3D: prompt bar with typewriter suggestions (Tab to accept), example chips, POST `/api/forge` (tier `standard`, TRELLIS lane, free; auto-degrades to NVIDIA lane), poll `GET /api/forge?job=…`, live `<model-viewer>` result, session history rail (localStorage `forge:home:history`), result toolbar (auto-rotate toggle, variation, Scene Studio → `/scene?model=…`, copy share link, GLB download, clear), and an embed sheet (iframe/web-component snippets, size presets, copy, standalone link). Cancel/retry wired. Honest elapsed timer only.+ - **Pose Studio (`#home-pose`, `src/home-pose.js`)** — drag-to-orbit rig, joint sliders, preset chips, reset/snapshot/copy-link/open-studio buttons.+ - **AR (`#home-ar`)** — `<model-viewer>` with `ar` modes (webxr/scene-viewer/quick-look), desktop QR (lazy `src/erc8004/qr.js`), model cycling.+ - **Live token card (`#hlt-card`, `src/home-live-token.js`)** — real Pump.fun data; plus homepage launcher.+ - **Oracle feed** — `GET /api/oracle/feed?network=mainnet&limit=6&min_score=56`, renders top conviction coins.+ - **Community Forge gallery** — `GET /api/forge-gallery?scope=community&limit=18`.+ - **Showcase 3D grid** — `GET /api/explore`, agent cards + CTA cards.+ - **Other live agents** — What-You-Get viewer (50+ animation chips), Bento mini-agents, Vclose agent, Avatar Drop canvas, Walk preview canvas.+- **External calls / dependencies:** `POST/GET /api/forge`, `GET /api/forge-gallery`, `GET /api/explore`, `GET /api/oracle/feed`; Pump.fun feed (live token card); `agent-3d` runtime + Google `model-viewer` CDN (lazy). Solana RPC indirectly via the launcher.+- **Success state:** User reaches and clicks a CTA into a product route, or completes an in-page demo (e.g. a forged model rendered with a working toolbar; an embed snippet copied).+- **Empty / error states:**+ - Mini Forge: 503/`unconfigured` → "The generator is offline right now"; 429/`rate_limited` → "The forge is busy, try again in ~N s"; poll timeout → "try a simpler, single-subject prompt"; viewer load failure surfaced; explicit error state with **Try again** (re-runs `lastPrompt`) and **Cancel**.+ - API-fed sections (Oracle, Community Forge, Showcase) degrade gracefully if their fetch fails (sections render empty rather than break the page).+ - Reduced-motion respected throughout (typewriter, parallax, scanline disabled).+ - Clipboard blocked → fallback hidden input + `execCommand('copy')` with "Press ⌘/Ctrl-C" toast.+- **Step count:** ~3 required to leave via a CTA (land → optional browse → click) **(+ many optional)**: the page exposes ~40 distinct CTAs and ~13 self-contained interactive widgets, each an optional sub-flow.++---++## Content & Read-Only Pages++### What is three.ws — `/what-is`+- **Source:** `pages/what-is.html` (static; `<model-viewer>` v4.0.0 CDN).+- **Entry point:** `vercel.json` `/what-is → /what-is.html`.+- **Steps (4):** 1) Read hero/overview. 2) Expand/collapse FAQ accordion (4 questions: crypto, free-to-start, skills-needed, where-embed) via `.fl-faq-q` buttons. 3) Drag/orbit the embedded sample avatar (`/animations/soldier.glb`). 4) Follow a nav/CTA link (`#use-cases`, `/create`, `/features`, `/studio`, `/playground`, `/play`, `/overlay-control`, `/pay`).+- **Notes:** Schema.org FAQPage + WebPage. No API calls. Interactive: FAQ accordion + 3D viewer.++### Features (index) — `/features`+- **Source:** `pages/features.html` (static + 3D widgets; `/footer-newsletter.js`).+- **Entry point:** `vercel.json` `/features → /features.html`. (Subpages `/features/*` covered elsewhere.)+- **Steps (6):** 1) Hero "Core" vs "Optional" pill nav scrolls to `#core`/`#optional`. 2) Animation showcase: 70+ pills swap a live `<model-viewer>` `src` (`/animations/*.glb`) with a "Now Playing" label. 3) Copy embed snippet (`#embedCopyBtn` → clipboard, "Copied!" 2s). 4) Scroll-reveal cascade (IntersectionObserver). 5) Interact with multiple embedded `<model-viewer>` demos. 6) Newsletter signup (footer `data-newsletter-form` → `POST /api/newsletter/subscribe`).+- **Notes:** No content-fetch API; copy button + animation picker + newsletter form are the real interactions.++### Status — `/status`+- **Source:** `pages/status.html` (dynamic).+- **Entry point:** `vercel.json` `/status → /status.html`.+- **Prerequisites / gates:** None.+- **Steps (3):** 1) On load, fetch `GET /api/status` and render service cards (status dot, uptime %, avg latency, 90-day history bar). 2) Auto-poll every 5 min (`setInterval`, 300000 ms) updating the `aria-live` banner ("All systems operational" ↔ "X of Y services disrupted"). 3) Hover/focus a 90-day history cell for per-day tooltip.+- **External calls:** `GET /api/status`.+- **Success state:** Live service grid rendered with current operational status + "last check" timestamp.+- **Empty / error states:** Skeleton loaders on first paint; on fetch failure renders an error message with retry guidance.+- **Step count:** 1 required (page loads + auto-fetches) (+2 optional: re-poll happens automatically; hover cells).++### Glossary — `/glossary`+- **Source:** `pages/glossary.html` + `src/glossary/page.js`; term data inline in `public/glossary.js` (`window.twsGlossary.terms`, injected site-wide by `nav.js`).+- **Entry point:** `vercel.json` `/glossary → /glossary.html`.+- **Steps (4):** 1) Type in `#glos-q` search (rAF-debounced `applyFilter`, case-insensitive, filters cards). 2) Result count updates (`#glos-count` aria-live: "X terms" / "Y of X terms" / "No terms match '…'"). 3) Deep-link `#<term>` scrolls + flash-highlights a card (`highlightFromHash`). 4) Read a term card.+- **Notes:** No external API — terms are a static inline object (~16+ terms: usdc, sol, solana, evm, wallet, x402, pay-per-call, on-chain, mint, bonding-curve, pump.fun, mainnet, base, nft, ipfs, mcp, a2a, erc-8004, metaplex-core, graduation, skills, brain, rig…). page.js polls up to 6s for the injected glossary data.++### Support — `/support`+- **Source:** `pages/support.html` (static).+- **Entry point:** `vercel.json` `/support → /support.html`.+- **Steps (5):** 1) Read intro/channels. 2) Copy a contact email via `.copy-btn` (support, security, partnerships, privacy, legal, dmca, abuse @three.ws) → clipboard, "Copied ✓" 1600ms; clipboard-blocked fallback opens `mailto:`. 3) Open a channel card (GitHub Issues / Discussions — new tab). 4) Use a `mailto:` link. 5) Hover channel cards (border/translate/arrow microinteractions).+- **Notes:** No contact form / no backend submission — email links + copy buttons only. No API.++### Events — Build 3D Agents Live — `/events/build-3d-agents-live`+- **Source:** `pages/events/build-3d-agents-live.html` (static + realtime; `/embed.js`, `/footer-newsletter.js`).+- **Entry point:** `vercel.json` `/events/([a-z0-9-]+) → /events/$1.html`.+- **Steps (5):** 1) Watch live countdown to start (event 2026-06-23 18:00 MT / 20:00 ET, 60 min, online; rAF tick → days/hrs/min/sec; switches to "LIVE NOW" then "Replay coming soon"). 2) Add to calendar (`#add-cal`/`#add-cal-2` build a Google Calendar render URL from EVENT_START/END). 3) RSVP email signup (`#rsvp-form`, `data-newsletter-form` → `POST /api/newsletter/subscribe`, aria-live result). 4) Interact with the lazy-loaded hero `<agent-3d>` (deferred via `requestIdleCallback` → `/embed.js`). 5) Scroll-reveal sections.+- **Notes:** Schema.org Event. Countdown is local (no API); only newsletter POSTs.++### Legal — Privacy & Terms — `/legal/privacy`, `/legal/tos`+- **Source:** `public/legal/privacy.html`, `public/legal/tos.html` (pure static).+- **Entry point:** `vercel.json` `/legal/privacy → /legal/privacy.html`, `/legal/tos → /legal/tos.html`.+- **Steps (1):** Read the document; follow cross-links (each links to the other, plus `mailto:` addresses; one IBM cloud external ref).+- **Notes:** No TOC/anchors, no dynamic behavior, no API. Privacy = 11 sections; Terms = 12 sections.++### Tutorials index — `/tutorials`+- **Source:** `pages/tutorials.html` (client-rendered from `public/tutorials-manifest.js` → `window.TUTORIALS`, 23 entries, 3 tiers).+- **Entry point:** `vercel.json` `/tutorials → /tutorials.html`.+- **Steps (4):** 1) Use hero jump-links (`.tut-jump`, 3 tiers) to scroll. 2) Browse 23 tutorial cards (Easy 8 / Middle 10 / Advanced 5), grouped with section headers. 3) Click a card → `/tutorials/<slug>`. 4) Bottom CTA: "Open docs →" → `/docs`; "Read source on GitHub" (new tab).+- **Notes:** Dynamic render from the manifest `<script>`, no fetch. Hover: translateY + accent-bar.++### Tutorial article template — `/tutorials/prompts-for-3d`, `/tutorials/generate-3d-api`+- **Source:** `pages/tutorial.html` (route `/tutorials/([a-z0-9-]+) → /tutorial.html`); content markdown in `docs/tutorials/<slug>.md` (`docs/tutorials/prompts-for-3d.md`, `docs/tutorials/generate-3d-api.md`); metadata from `public/tutorials-manifest.js`.+- **Entry point:** Slug parsed from URL via regex, metadata via `window.tutorialBySlug(slug)`.+- **Steps (5):** 1) Read hero (title/meta from manifest). 2) Hero CTA (manifest-driven, e.g. "Open the Forge"). 3) Read article — markdown fetched `GET /docs/tutorials/<slug>.md`, parsed with marked + highlight.js; per-`<pre>` **copy code** buttons ("Copy" → "Copied" 1700ms). 4) Use the sticky TOC (scroll-spy) and heading anchors. 5) Prev/Next pager (adjacent manifest entries); back-to-top button + top progress bar.+- **External calls:** `GET /docs/tutorials/<slug>.md`.+- **Success state:** Rendered article with working TOC, copy buttons, and pager.+- **Empty / error states:** "Page not found." on failed markdown fetch.+- **Step count:** 1 required (read) (+4 optional: CTA, copy, TOC nav, pager).+- **Notes:** text-to-3d & image-to-3d tutorials use this same template (covered elsewhere).++### Docs (index + all subpages) — `/docs`, `/docs/start-here`, `/docs/make-your-agent`, `/docs/share-and-embed`, `/docs/do-i-need-crypto`, `/docs/quick-start`, `/docs/agent-system`, `/docs/erc8004`, `/docs/embedding`, `/docs/web-component`, `/docs/mcp`, `/docs/skills`, `/docs/api-reference`, `/docs/sdk`, `/docs/listings` (and ~50 more)+- **Source:** Single SPA shell `docs/index.html` (served for `/docs`, `/docs/`, and `/docs/<slug>` per `vercel.json`); markdown content in `docs/*.md` and `docs/tutorials/*.md`. Marked + highlight.js via CDN.+- **Entry point:** `vercel.json` `/docs → /docs/index.html`, `/docs/([^./]+) → /docs/index.html` (the slug becomes a hash route). `currentPath()` reads `location.hash` (or `/docs/<slug>`), defaulting to `start-here`.+- **Steps (4):** 1) Land — sidebar (9 sections, NAV array) + `start-here.md` fetched & rendered. 2) Sidebar **search** input live-filters the nav by label. 3) Click a sidebar link → hash route → `GET /docs/<slug>.md` rendered (headings get anchor IDs; internal `.md` links rewritten to hash routes; code highlighted). 4) Per-page tools: "Copy page" (markdown to clipboard), "View as Markdown" (`/docs/<slug>.md` new tab), "Open in Claude" (`claude.ai/new?q=…`); Prev/Next pager; mobile sidebar FAB/overlay.+- **External calls:** `GET /docs/<slug>.md` per page (e.g. `do-i-need-crypto.md`, `quick-start.md`, `agent-system.md`, `erc8004.md`, `embedding.md`, `web-component.md`, `mcp.md`, `skills.md`, `api-reference.md`, `sdk.md`, `listings.md`, `make-your-agent.md`, `start-here.md`); marked + highlight.js CDNs.+- **Empty / error states:** Loading dots during fetch; "Page not found." on a missing slug.+- **Notes:** ALL `/docs/*` slugs (except `/docs/widgets`) share this one SPA — the route is one repeated pattern: navigate (hash/sidebar/search) → fetch markdown → render, with copy-page + pager + TOC behaviors. Real steps per page = 1 required (read) +3 optional (search, copy-page, pager). **Exception:** `/docs/widgets` is a separate standalone page (below).++### Docs — Widgets (standalone) — `/docs/widgets`+- **Source:** `public/docs-widgets.html` (static; `vercel.json` `/docs/widgets → /docs-widgets.html`, mapped *before* the generic `/docs/*` rule).+- **Steps (4):** 1) TOC anchor nav (`#quick-start`, `#widget-types`, `#urls`, `#embedding`, `#postmessage-api`, `#og-oembed`, `#csp-cors`, `#privacy`, `#faq`). 2) Read code blocks (iframe/script/oEmbed/postMessage). 3) Review reference tables (widget types, URL schemes, hash params, postMessage events, OG/oEmbed). 4) Follow links (`/studio`, `/widgets`, `/docs/deployment`, oembed.com); footer `<model-viewer>` demo (`/animations/robotexpressive.glb`).+- **Notes:** Pure static docs, no API. Distinct from the docs SPA.++### Blog index — `/blog`+- **Source:** `blog/index.html` (static; `vercel.json` `/blog → /blog/index.html`).+- **Entry point:** `/blog`.+- **Prerequisites / gates:** None.+- **Steps (2):** 1) Scan the hardcoded list of 26 post cards (each shows title, date, informational tag). 2) Click a post → `/blog/<slug>`. (Also: RSS link `/rss/announcements.xml`; X/GitHub external links.)+- **Decision points / branches:** 26 posts → 26 individual article routes; RSS / social out.+- **External calls:** None — fully static list (no fetch, no pagination, no filter/search). Tags are display-only, not filterable.+- **Success state:** User opens an article.+- **Empty / error states:** N/A (static).+- **Step count:** 1 required (click a post) (+ optional RSS/social).++### Blog posts (26) — `/blog/<slug>`+- **Source:** `blog/<slug>.html` — 26 routable static HTML files, all on **one shared template** (`.post-wrap`, `.post-meta`, `.post-tag`, shared nav/footer containers). Routed via `vercel.json` `/blog/([a-z0-9-]+) → /blog/$1.html`.+- **Slugs:** 2500-new-animations, 3d-ai-crypto-convergence, agent-3d-web-component, agent-builder-studio-launch, animation-emotion-control, how-to-embed-3d-onchain-agents, pumpfun-agent-payments-sdk, real-time-voice-interaction, see-your-3d-in-ar, solana-wallet-integration, text-to-3d-is-live, three-token-listings, three-ws-aws-partner, three-ws-dextools-social-boost-buyback, three-ws-featured-on-alibaba-cloud-marketplace-blog, three-ws-google-cloud-partnership, three-ws-hackernoon-partnership, three-ws-ibm-business-partner, three-ws-ibm-collaboration, three-ws-on-alibaba-cloud-marketplace, three-ws-on-anthropic-mcp-registry, three-ws-on-aws-marketplace, three-ws-on-bnb-chain-dappbay, three-ws-on-coinmarketcap, three-ws-speraxusd-integration, three-ws-x402-bazaar.+- **Steps (1):** Read the article; follow the "← Blog" back link, inline links, and the occasional primary CTA (e.g. text-to-3d post → "Try Forge — type a prompt →" → `/forge`).+- **Notes:** Repeated "read article" pattern. No embedded 3D demos / share / TOC / newsletter inside the post body in the sampled pages; copy-button CSS exists in the template but the sampled posts have no code blocks. No API.+- **Source not exposed:** Two `.md` files (`blog/decision-optimization-3d-ai-crypto.md`, `blog/internets-second-species.md`) are NOT routed (no rule maps `.md` blog slugs) and are not in the index — source material only, not live pages.++---++## Machine-Readable Endpoints++Agent/crawler endpoints — not user UX (0 user steps). All resolve via `vercel.json` rewrites.++| Endpoint | Route | Served by | Purpose |+|---|---|---|---|+| Sitemap | `/sitemap.xml` | `/api/sitemap` (function) | XML sitemap for crawlers (sub-sitemaps at `/sitemap/{core,agents,avatars,widgets,profiles}.xml`) |+| LLMs index | `/llms.txt` | `public/llms.txt` (static) | LLM site index |+| LLMs full | `/llms-full.txt` | `public/llms-full.txt` (static) | Full LLM corpus dump |+| Robots | `/robots.txt` | `public/robots.txt` (static) | Crawler directives |+| OpenAPI | `/openapi.json` | `/api/openapi-json` (function) | OpenAPI spec for the REST API |+| x402 discovery | `/.well-known/x402` | `/api/wk?name=x402` | x402 micropayment service discovery (`/.well-known/x402.json` → `name=x402-discovery`) |+| Agent attestation schemas | `/.well-known/agent-attestation-schemas` | `/api/wk?name=agent-attestation-schemas` | ERC-8004 attestation schema descriptors |+| OAuth AS metadata | `/.well-known/oauth-authorization-server` | `/api/wk?name=oauth-authorization-server` | OAuth 2.0 Authorization Server metadata |+| Chat plugin manifest | `/.well-known/chat-plugin.json` | `/api/wk?name=chat-plugin` | AI chat-plugin manifest |++All `/.well-known/*` and `/openapi.json` / `/sitemap.xml` responses are JSON/XML for machines (agents, wallets, crawlers, OAuth/MCP clients), not rendered UI. The `/.well-known/*` family is handled centrally by `api/wk.js`.++---++<a id="sec-272"></a>> **Source:** `docs/validation.md` · [↑ table of contents](#table-of-contents)@@ -48788,7 +59082,7 @@ The toggle's CSS class reflects the highest severity: `level-0` (errors), `level----<a id="sec-218"></a>+<a id="sec-273"></a>> **Source:** `docs/viewer.md` · [↑ table of contents](#table-of-contents)@@ -49158,7 +59452,7 @@ State is persisted to `localStorage` per agent ID when `attachScenePrefs(agentId----<a id="sec-219"></a>+<a id="sec-274"></a>> **Source:** `docs/web-component.md` · [↑ table of contents](#table-of-contents)@@ -50102,7 +60396,7 @@ defineElement('my-agent');----<a id="sec-220"></a>+<a id="sec-275"></a>> **Source:** `docs/widget-api.md` · [↑ table of contents](#table-of-contents)@@ -50301,7 +60595,7 @@ If you have multiple widgets and want to coordinate them (sync camera, broadcast----<a id="sec-221"></a>+<a id="sec-276"></a>> **Source:** `docs/widget-studio.md` · [↑ table of contents](#table-of-contents)@@ -50554,7 +60848,7 @@ You can override these freely in the iframe `width` and `height` attributes. Add----<a id="sec-222"></a>+<a id="sec-277"></a>> **Source:** `docs/widgets.md` · [↑ table of contents](#table-of-contents)@@ -51062,7 +61356,7 @@ Need to drive a widget from the parent page — change the camera, play an anima----<a id="sec-223"></a>+<a id="sec-278"></a>> **Source:** `docs/x-spaces.md` · [↑ table of contents](#table-of-contents)@@ -51291,7 +61585,7 @@ One-click options: Railway, Render (see buttons in [`xspace-agent/README.md`](..----<a id="sec-224"></a>+<a id="sec-279"></a>> **Source:** `docs/x402-offer-receipt/00-plan.md` · [↑ table of contents](#table-of-contents)@@ -51369,7 +61663,7 @@ Single env-var toggle controls the feature: if `X402_RECEIPT_SIGNING_KEY` is uns----<a id="sec-225"></a>+<a id="sec-280"></a>> **Source:** `docs/x402-offer-receipt/01-foundation.md` · [↑ table of contents](#table-of-contents)@@ -51471,7 +61765,7 @@ With `X402_RECEIPT_SIGNING_KEY` unset, this should print `issuer: no-op`, `offer----<a id="sec-226"></a>+<a id="sec-281"></a>> **Source:** `docs/x402-offer-receipt/02-offer-signing.md` · [↑ table of contents](#table-of-contents)@@ -51605,7 +61899,7 @@ Every accept-entry network should print `VERIFIED`.----<a id="sec-227"></a>+<a id="sec-282"></a>> **Source:** `docs/x402-offer-receipt/03-receipt-signing.md` · [↑ table of contents](#table-of-contents)@@ -51757,7 +62051,7 @@ Expected: `VERIFIED` and a payload containing `resourceUrl`, `payer`, `network`,----<a id="sec-228"></a>+<a id="sec-283"></a>> **Source:** `docs/x402-offer-receipt/04-bazaar-declaration.md` · [↑ table of contents](#table-of-contents)@@ -51894,7 +62188,7 @@ With `X402_RECEIPT_SIGNING_KEY` set, the output should show **both** the static----<a id="sec-229"></a>+<a id="sec-284"></a>> **Source:** `docs/x402-offer-receipt/05-verification-script.md` · [↑ table of contents](#table-of-contents)@@ -52009,7 +62303,7 @@ In [package.json](../../package.json), add:----<a id="sec-230"></a>+<a id="sec-285"></a>> **Source:** `docs/x402-offer-receipt/06-completionist-and-push.md` · [↑ table of contents](#table-of-contents)@@ -52127,7 +62421,7 @@ After both pushes succeed, print a short summary:----<a id="sec-231"></a>+<a id="sec-286"></a>> **Source:** `docs/x402.md` · [↑ table of contents](#table-of-contents)@@ -52261,7 +62555,7 @@ consuming the intent. Not yet enforced server-side.----<a id="sec-232"></a>+<a id="sec-287"></a>> **Source:** `docs/zauth/database.md` · [↑ table of contents](#table-of-contents)@@ -52407,7 +62701,7 @@ Use this endpoint to browse all known x402 endpoints before your agents commit t----<a id="sec-233"></a>+<a id="sec-288"></a>> **Source:** `docs/zauth/index.md` · [↑ table of contents](#table-of-contents)@@ -52431,7 +62725,7 @@ zauth is the security and trust layer that allows agents to act with confidence,----<a id="sec-234"></a>+<a id="sec-289"></a>> **Source:** `docs/zauth/provider-hub.md` · [↑ table of contents](#table-of-contents)@@ -52533,7 +62827,7 @@ Supply your EVM or Solana private keys to enable automatic refunds when your end----<a id="sec-235"></a>+<a id="sec-290"></a>> **Source:** `docs/zauth/reposcan.md` · [↑ table of contents](#table-of-contents)@@ -52859,7 +63153,7 @@ TypeScript -@x402/fetch----<a id="sec-236"></a>+<a id="sec-291"></a>> **Source:** `docs/zauth/vector.md` · [↑ table of contents](#table-of-contents)diff --git a/docs/pumpfun-program/docs/FAQ.md b/docs/pumpfun-program/docs/FAQ.mdindex 0f4cbc762..13b55bee4 100644--- a/docs/pumpfun-program/docs/FAQ.md+++ b/docs/pumpfun-program/docs/FAQ.md@@ -11,33 +11,17 @@ Each buy / sell instruction used CUs depend on all the inputs of the instructionmore CUs to log than smaller values.- for sell inputs, it's similar.-As an example, for the-tx https://solscan.io/tx/5frph8gBFyX7ayBmqntvwpTPwzZ8aF4kdfJAvC52Li2iDnnaRwtmcZP839Cm4YQUFx7GzsUUStCfAy3hAG69ir4u:+The `bonding_curve` (and the other) PDA bump seed is derived from the mint pubkey, so it differs for every mint:```Rust- let mint = Pubkey::from_str("Coyj3LtKn1BNSgWc9HsGK5SKoGfEoDaymig4wrN6pump").unwrap();--assert_eq!(- Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1,- 255-);-```--The `bonding_curve` bump seed for mint `Coyj3LtKn1BNSgWc9HsGK5SKoGfEoDaymig4wrN6pump` is `255`.--While for the-tx https://solscan.io/tx/5xozUcJFvRj4ySpE2epSSs95ySxs6cLjs1rV2uaFNkFgsEMBZW53VUa2uc3CVQLVJRYxfQ5JoSzZLiUvAgM4GEJM:--```Rust- let mint = Pubkey::from_str("3cLSxG6eXcCD9NSMawkhUcrvVCUC8KHKHMCxx6bhpump").unwrap();--assert_eq!(- Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1,- 251-);+ // `mint` is the SPL mint of the token being traded.+ let bump = Pubkey::find_program_address(&[b"bonding-curve", mint.as_ref()], &pump::ID).1;```-The `bonding_curve` bump seed for mint `3cLSxG6eXcCD9NSMawkhUcrvVCUC8KHKHMCxx6bhpump` is `251`.+Different mints yield different bump seeds (commonly `255`, but `254`, `253`, … occur),+and the number of search iterations `find_program_address` performs to land on a valid+bump is itself part of the instruction's CU cost — so two trades of identical size can+consume different CUs solely because their mint/user/creator PDAs derive at different bumps.So it is not possible to compute the used CUs without first simulating the buy / sell tx before submission and adding abuffer of 1% to the simulated CUs, because buy instruction executes a bit more code when the bonding curve completes ondiff --git a/docs/pumpfun-program/docs/PUMP_SWAP_README.md b/docs/pumpfun-program/docs/PUMP_SWAP_README.mdindex 24489cb61..44f5fc7c5 100644--- a/docs/pumpfun-program/docs/PUMP_SWAP_README.md+++ b/docs/pumpfun-program/docs/PUMP_SWAP_README.md@@ -82,7 +82,7 @@ at https://solscan.io/account/GseMAnNDvntR5uFePZ51yZBXzNSn7GdFPkfHwfr6d77J#accou},"base_mint": {"type": "pubkey",- "data": "7LSsEoJGhLeZzGvDofTdNg7M3JttxQqGWNLo6vWMpump"+ "data": "EXAMPLEpumpfunBaseMint1111111111111111pump"},"quote_mint": {"type": "pubkey",diff --git a/package.json b/package.jsonindex 0e381f844..afb3cdfcf 100644--- a/package.json+++ b/package.json@@ -177,6 +177,8 @@"test:pages": "node scripts/test-pages.mjs","verify:ibm": "node scripts/verify-ibm-pages.mjs","verify:zauth": "node scripts/verify-zauth-runtime.mjs",+ "triage": "node scripts/verify-task-completion.mjs",+ "prioritize": "node scripts/verify-task-completion.mjs && node scripts/rank-backlog.mjs","zauth:register": "node scripts/zauth-register-endpoints.mjs","test:all": "npm run test && npm run test:pages","verify": "prettier --check . && vite build",diff --git a/packages/activity-mcp/src/index.js b/packages/activity-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/agenc-mcp/src/index.js b/packages/agenc-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/agora-mcp/src/index.js b/packages/agora-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/alerts-mcp/src/index.js b/packages/alerts-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/audio-mcp/src/index.js b/packages/audio-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/autopilot-mcp/src/index.js b/packages/autopilot-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/billing-mcp/src/index.js b/packages/billing-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/brain-mcp/src/index.js b/packages/brain-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/clash-mcp/src/index.js b/packages/clash-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/copy-mcp/src/index.js b/packages/copy-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/kol-mcp/src/index.js b/packages/kol-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/loom-mcp/src/index.js b/packages/loom-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/notifications-mcp/src/index.js b/packages/notifications-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/portfolio-mcp/src/index.js b/packages/portfolio-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/signals-mcp/src/index.js b/packages/signals-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/tutor-mcp/src/index.js b/packages/tutor-mcp/src/index.jsold mode 100644new mode 100755diff --git a/packages/vision-mcp/src/index.js b/packages/vision-mcp/src/index.jsold mode 100644new mode 100755diff --git a/pages/agora.html b/pages/agora.htmlindex d9607d822..3103ce2e5 100644--- a/pages/agora.html+++ b/pages/agora.html@@ -12,14 +12,14 @@<meta property="og:url" content="https://three.ws/agora" /><meta property="og:title" content="Agora · the Commons · three.ws" /><meta property="og:description" content="Watch the living economy — AI agent and human citizens at work in a 3D world, earning $THREE." />- <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Agora+%E2%80%94+the+Commons&d=A+watchable+3D+world+where+AI+agent+and+human+citizens+live%2C+work%2C+and+earn+%24THREE.+Walk+the+square%2C+inspect+any+citizen%27s+passport%2C+and+watch+the+economy+come+&p=%2Fagora" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:site" content="@trythreews" /><meta name="twitter:title" content="Agora · the Commons · three.ws" /><meta name="twitter:description" content="Watch the living economy — AI agent and human citizens at work in a 3D world, earning $THREE." />- <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Agora+%E2%80%94+the+Commons&d=A+watchable+3D+world+where+AI+agent+and+human+citizens+live%2C+work%2C+and+earn+%24THREE.+Walk+the+square%2C+inspect+any+citizen%27s+passport%2C+and+watch+the+economy+come+&p=%2Fagora" /><meta name="theme-color" content="#060607" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -28,7 +28,13 @@<link rel="apple-touch-icon" href="/apple-touch-icon.png" /><link rel="manifest" href="/site.webmanifest" /><link rel="stylesheet" href="/src/agora/agora.css" />- </head>++ <link rel="canonical" href="https://three.ws/agora">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Agora — the Commons — three.ws">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Agora — the Commons","description":"A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.","url":"https://three.ws/agora","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=build&t=Agora+%E2%80%94+the+Commons&d=A+watchable+3D+world+where+AI+agent+and+human+citizens+live%2C+work%2C+and+earn+%24THREE.+Walk+the+square%2C+inspect+any+citizen%27s+passport%2C+and+watch+the+economy+come+&p=%2Fagora"}]}</script>+</head><body><div id="agora-loading"><div class="agora-loading-card">diff --git a/pages/forge-spark.html b/pages/forge-spark.htmlindex 05b3b7548..4d7f79bb2 100644--- a/pages/forge-spark.html+++ b/pages/forge-spark.html@@ -17,7 +17,7 @@<meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" /><meta property="og:url" content="https://three.ws/forge-spark" />- <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Text+%E2%86%92+3D+%E2%80%94+Nemotron+%E2%86%92+FLUX+%E2%86%92+TRELLIS&d=Describe+an+object.+Nemotron+sharpens+the+prompt%2C+FLUX+paints+a+reference%2C+TRELLIS+reconstructs+the+textured+mesh+%E2%80%94+served+on+NVIDIA+NIM.&p=%2Fforge-spark" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Text+%E2%86%92+3D+%E2%80%94+Nemotron+%E2%86%92+FLUX+%E2%86%92+TRELLIS&d=Describe+an+object+and+watch+it+become+a+textured+3D+mesh%3A+Nemotron+sharpens+the+prompt%2C+FLUX+paints+a+clean+reference%2C+and+TRELLIS+reconstructs+the+model+%E2%80%94+ser&p=%2Fforge-spark" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" />@@ -27,7 +27,7 @@name="twitter:description"content="Describe it. Nemotron sharpens the words, FLUX paints a reference, TRELLIS reconstructs the mesh. Served on NVIDIA NIM."/>- <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Text+%E2%86%92+3D+%E2%80%94+Nemotron+%E2%86%92+FLUX+%E2%86%92+TRELLIS&d=Describe+an+object.+Nemotron+sharpens+the+prompt%2C+FLUX+paints+a+reference%2C+TRELLIS+reconstructs+the+textured+mesh+%E2%80%94+served+on+NVIDIA+NIM.&p=%2Fforge-spark" />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Text+%E2%86%92+3D+%E2%80%94+Nemotron+%E2%86%92+FLUX+%E2%86%92+TRELLIS&d=Describe+an+object+and+watch+it+become+a+textured+3D+mesh%3A+Nemotron+sharpens+the+prompt%2C+FLUX+paints+a+clean+reference%2C+and+TRELLIS+reconstructs+the+model+%E2%80%94+ser&p=%2Fforge-spark" /><meta name="theme-color" content="#080814" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -287,7 +287,12 @@.spark-footer a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }</style>- </head>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Text → 3D — Nemotron → FLUX → TRELLIS — three.ws">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Text → 3D — Nemotron → FLUX → TRELLIS","description":"Describe an object and watch it become a textured 3D mesh: Nemotron sharpens the prompt, FLUX paints a clean reference, and TRELLIS reconstructs the model — served on NVIDIA NIM, quiet and always on.","url":"https://three.ws/forge-spark","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=build&t=Text+%E2%86%92+3D+%E2%80%94+Nemotron+%E2%86%92+FLUX+%E2%86%92+TRELLIS&d=Describe+an+object+and+watch+it+become+a+textured+3D+mesh%3A+Nemotron+sharpens+the+prompt%2C+FLUX+paints+a+clean+reference%2C+and+TRELLIS+reconstructs+the+model+%E2%80%94+ser&p=%2Fforge-spark"}]}</script>+</head><body class="forge-page"><div id="nav-container"></div>diff --git a/pages/ibm/hello.html b/pages/ibm/hello.htmlindex a4b3e55f5..5bf128c91 100644--- a/pages/ibm/hello.html+++ b/pages/ibm/hello.html@@ -421,13 +421,13 @@ a:focus-visible{outline-offset:3px}<link rel="canonical" href="https://three.ws/ibm/hello"><meta property="og:site_name" content="three.ws"><meta property="og:url" content="https://three.ws/ibm/x402-demo">- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&p=%2Fibm%2Fx402-demo">+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=IBM+%C3%97+three.ws+partnership&d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&p=%2Fibm%2Fhello"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="x402 Live Demo (IBM × three.ws) · three.ws"><meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.">- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&p=%2Fibm%2Fx402-demo">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=IBM+%C3%97+three.ws+partnership&d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&p=%2Fibm%2Fhello"><script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script><!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 01).Self-hosted (travels with this file under ./vendor/) so the page needs nodiff --git a/pages/pose-mini.html b/pages/pose-mini.htmlindex c4b023e37..6c95f5cc1 100644--- a/pages/pose-mini.html+++ b/pages/pose-mini.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en"><head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><style>/* three.ws hidden-guard — make the `hidden` attribute authoritative */[hidden]{display:none!important}</style><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />diff --git a/prompts/01-production-readiness-audit.md b/prompts/01-production-readiness-audit.mdindex a54709718..6c6a054d7 100644--- a/prompts/01-production-readiness-audit.md+++ b/prompts/01-production-readiness-audit.md@@ -50,3 +50,17 @@ Do **not** fix issues in this prompt — route each to the relevant numbered pro- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/01-production-readiness-audit.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/02-dead-paths-and-broken-links.md b/prompts/02-dead-paths-and-broken-links.mdindex fe13c1099..864eee11f 100644--- a/prompts/02-dead-paths-and-broken-links.md+++ b/prompts/02-dead-paths-and-broken-links.md@@ -43,3 +43,17 @@ reachable. Eliminate all dead paths across the platform. (Precedent: the account- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/02-dead-paths-and-broken-links.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/03-console-errors-warnings-sweep.md b/prompts/03-console-errors-warnings-sweep.mdindex b4a96e7ec..483681fb0 100644--- a/prompts/03-console-errors-warnings-sweep.md+++ b/prompts/03-console-errors-warnings-sweep.md@@ -39,3 +39,17 @@ table stakes for the quality bar in CLAUDE.md's Definition of Done.- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/03-console-errors-warnings-sweep.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/04-build-deploy-artifact-integrity.md b/prompts/04-build-deploy-artifact-integrity.mdindex b08389941..64db29cf6 100644--- a/prompts/04-build-deploy-artifact-integrity.md+++ b/prompts/04-build-deploy-artifact-integrity.md@@ -42,3 +42,17 @@ clean, and the notorious esbuild-overwrite trap impossible to commit by accident- No throwaway scripts in the repo root — put tooling in `scripts/`.- Push to BOTH remotes when asked (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/04-build-deploy-artifact-integrity.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/05-routing-and-404-audit.md b/prompts/05-routing-and-404-audit.mdindex 3404d3f86..b8ad9e8b0 100644--- a/prompts/05-routing-and-404-audit.md+++ b/prompts/05-routing-and-404-audit.md@@ -42,3 +42,17 @@ path redirected, a real designed 404, and no path that silently dead-ends.- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/05-routing-and-404-audit.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/06-test-coverage-unit.md b/prompts/06-test-coverage-unit.mdindex 33f9a489e..e99714876 100644--- a/prompts/06-test-coverage-unit.md+++ b/prompts/06-test-coverage-unit.md@@ -41,3 +41,17 @@ mocked-away core logic) and deterministic.- Tests are internal — no changelog entry needed unless a user-visible bug was fixed along the way.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/06-test-coverage-unit.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/07-e2e-critical-flows.md b/prompts/07-e2e-critical-flows.mdindex 066db9df7..9bbc0eb00 100644--- a/prompts/07-e2e-critical-flows.md+++ b/prompts/07-e2e-critical-flows.md@@ -44,3 +44,17 @@ never reach production silently.- esbuild trap: never commit `api/*.js` starting with `__defProp`/`createRequire`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/07-e2e-critical-flows.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/08-error-handling-failsafes.md b/prompts/08-error-handling-failsafes.mdindex 47ed2c841..ff5bd3e5e 100644--- a/prompts/08-error-handling-failsafes.md+++ b/prompts/08-error-handling-failsafes.md@@ -43,3 +43,17 @@ reply instead of erroring — apply that discipline everywhere.)- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/08-error-handling-failsafes.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/09-accessibility-audit.md b/prompts/09-accessibility-audit.mdindex 6de299a21..3e48d057c 100644--- a/prompts/09-accessibility-audit.md+++ b/prompts/09-accessibility-audit.md@@ -37,3 +37,17 @@ focus. Accessibility is non-negotiable per CLAUDE.md.- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/09-accessibility-audit.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/10-responsive-mobile-audit.md b/prompts/10-responsive-mobile-audit.mdindex ed381e3c4..9bd58499c 100644--- a/prompts/10-responsive-mobile-audit.md+++ b/prompts/10-responsive-mobile-audit.md@@ -38,3 +38,17 @@ collapses or wastes space.)- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/10-responsive-mobile-audit.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/11-performance-web-vitals.md b/prompts/11-performance-web-vitals.mdindex 866374dee..d5dec27e7 100644--- a/prompts/11-performance-web-vitals.md+++ b/prompts/11-performance-web-vitals.md@@ -39,3 +39,17 @@ keep the 3D-heavy surfaces smooth (no jank, controlled memory).- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/11-performance-web-vitals.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/12-seo-metadata.md b/prompts/12-seo-metadata.mdindex f25b87969..d8b7ecf09 100644--- a/prompts/12-seo-metadata.md+++ b/prompts/12-seo-metadata.md@@ -37,3 +37,17 @@ Twitter cards, canonical URLs, structured data, sitemap, robots, and rich link p- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/12-seo-metadata.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/13-design-system-consistency.md b/prompts/13-design-system-consistency.mdindex 746a41733..356deb799 100644--- a/prompts/13-design-system-consistency.md+++ b/prompts/13-design-system-consistency.md@@ -37,3 +37,17 @@ radii, shadows, motion, and component patterns. Eliminate one-off styles and vis- Every user-visible change → `data/changelog.json` entry + `npm run build:pages`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/13-design-system-consistency.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/14-security-review.md b/prompts/14-security-review.mdindex de70a8dcb..17de759ae 100644--- a/prompts/14-security-review.md+++ b/prompts/14-security-review.md@@ -42,3 +42,17 @@ This is defensive security on our own codebase.- esbuild trap: never commit `api/*.js` starting with `__defProp`/`createRequire`; recover with `git restore -- api/ public/`.- Push to BOTH remotes when asked; never pull/fetch/merge from `threeD`.- Definition of done = CLAUDE.md's checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/14-security-review.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/15-forge-pipeline.md b/prompts/15-forge-pipeline.mdindex c08e5298f..f4f4b71a8 100644--- a/prompts/15-forge-pipeline.md+++ b/prompts/15-forge-pipeline.md@@ -36,3 +36,17 @@ states, robust error recovery, and a result experience (orbit, AR, export, refin---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles (`__defProp`/`createRequire`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/15-forge-pipeline.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/16-walk-sdk-companion-playground.md b/prompts/16-walk-sdk-companion-playground.mdindex cf5a59ef5..c720da7e4 100644--- a/prompts/16-walk-sdk-companion-playground.md+++ b/prompts/16-walk-sdk-companion-playground.md@@ -34,3 +34,17 @@ delightful everywhere it ships — on three.ws and as the published `@three-ws/w---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/16-walk-sdk-companion-playground.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/17-avatar-create-edit-rig.md b/prompts/17-avatar-create-edit-rig.mdindex e65a0bdda..59458d02e 100644--- a/prompts/17-avatar-create-edit-rig.md+++ b/prompts/17-avatar-create-edit-rig.md@@ -33,3 +33,17 @@ or T-posed model.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/17-avatar-create-edit-rig.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/18-agent-studio.md b/prompts/18-agent-studio.mdindex ac49f0782..086ef63f1 100644--- a/prompts/18-agent-studio.md+++ b/prompts/18-agent-studio.md@@ -32,3 +32,17 @@ memory, skills, money, and on-chain identity in one place with a live 3D preview---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist. For anything LLM/model-related, consult the `claude-api` skill and use current model IDs.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/18-agent-studio.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/19-marketplace.md b/prompts/19-marketplace.mdindex ccf7f79f3..081880da7 100644--- a/prompts/19-marketplace.md+++ b/prompts/19-marketplace.md@@ -28,3 +28,17 @@ from other creators — with real listings, real prices, real purchase flows, an---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs (no seeded reviews/listings in prod). $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — purchases settle in USDC; never reference any other token. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/19-marketplace.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/20-gallery-discovery.md b/prompts/20-gallery-discovery.mdindex 548bec6d7..af2fde2cc 100644--- a/prompts/20-gallery-discovery.md+++ b/prompts/20-gallery-discovery.md@@ -30,3 +30,17 @@ beautiful, filterable grids that always show real, live content and route cleanl---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs/sample arrays. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); the launches feed may render user-launched mints from real records but never hardcode/recommend one. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/20-gallery-discovery.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/21-social-club-city.md b/prompts/21-social-club-city.mdindex ca82df90e..e8ab95a00 100644--- a/prompts/21-social-club-city.md+++ b/prompts/21-social-club-city.md@@ -29,3 +29,17 @@ fun — real avatars, real presence, graceful degradation when a feature/asset i---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs; arena/social data must be real + on-chain-verifiable. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/21-social-club-city.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/22-onboarding-wizard.md b/prompts/22-onboarding-wizard.mdindex 241868faa..9710ff5e1 100644--- a/prompts/22-onboarding-wizard.md+++ b/prompts/22-onboarding-wizard.md@@ -30,3 +30,17 @@ whole way. This funnel is the #1 driver of activation — make it frictionless a---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/22-onboarding-wizard.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/23-feature-tour.md b/prompts/23-feature-tour.mdindex fcf65f0cc..b6ea1fc53 100644--- a/prompts/23-feature-tour.md+++ b/prompts/23-feature-tour.md@@ -32,3 +32,17 @@ whole product, works across routes, and never glitches.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/23-feature-tour.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/24-scene-studio.md b/prompts/24-scene-studio.mdindex 9d1b29405..7bc87e7ee 100644--- a/prompts/24-scene-studio.md+++ b/prompts/24-scene-studio.md@@ -27,3 +27,17 @@ reliable, professional tool that never loses work and exports correctly.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Keep vendored code isolated. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/24-scene-studio.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/25-search.md b/prompts/25-search.mdindex ad070009a..d1bb1542f 100644--- a/prompts/25-search.md+++ b/prompts/25-search.md@@ -27,3 +27,17 @@ docs, and launches — and routes the user straight to what they want.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/25-search.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/26-dashboard.md b/prompts/26-dashboard.mdindex 048aa69ab..8fcea9319 100644--- a/prompts/26-dashboard.md+++ b/prompts/26-dashboard.md@@ -27,3 +27,17 @@ usage, notifications, account — all real, all actionable, beautifully laid out---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/26-dashboard.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/27-x402-payments.md b/prompts/27-x402-payments.mdindex 6569562e8..caf293436 100644--- a/prompts/27-x402-payments.md+++ b/prompts/27-x402-payments.md@@ -31,3 +31,17 @@ correct, idempotent, observable, and bulletproof — no double-charges, no silen---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks of payment logic; settle in USDC. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference another token, even in fixtures. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles (`__defProp`/`createRequire`) — recover with `git restore -- api/ public/`. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/27-x402-payments.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/28-wallet-connect-funding.md b/prompts/28-wallet-connect-funding.mdindex f510f2e26..3d7755799 100644--- a/prompts/28-wallet-connect-funding.md+++ b/prompts/28-wallet-connect-funding.md@@ -30,3 +30,17 @@ and trustworthy across Solana (default) and Base/EVM (secondary), for both human---### Operating rules — read CLAUDE.md + STRUCTURE.md first. Solana is the default network. No mocks of wallet/tx logic. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); settlement in USDC. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/28-wallet-connect-funding.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/29-pumpfun-launches.md b/prompts/29-pumpfun-launches.mdindex 83c74daf7..f4035b0c8 100644--- a/prompts/29-pumpfun-launches.md+++ b/prompts/29-pumpfun-launches.md@@ -31,3 +31,17 @@ must be safe, accurate, and reliable — with the platform itself only ever prom---### Operating rules — read CLAUDE.md + STRUCTURE.md first. Never mock pump.fun/Solana RPC. $THREE is the only coin the platform promotes (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); arbitrary mints only as runtime user input/launch records — never hardcode/recommend one. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/29-pumpfun-launches.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/30-three-holder-gating.md b/prompts/30-three-holder-gating.mdindex 368c5ba4c..19be06e4d 100644--- a/prompts/30-three-holder-gating.md+++ b/prompts/30-three-holder-gating.md@@ -30,3 +30,17 @@ gated consistently and correctly everywhere, with a clean unlock/upsell path and---### Operating rules — read CLAUDE.md + STRUCTURE.md first. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference another token. No mocks of balance/gating logic. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/30-three-holder-gating.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/31-mcp-servers.md b/prompts/31-mcp-servers.mdindex d455ff084..dc48b4df1 100644--- a/prompts/31-mcp-servers.md+++ b/prompts/31-mcp-servers.md@@ -32,3 +32,17 @@ its remote — so external agents can rely on three.ws tools.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No stubbed tools/mocks; real actions + real data. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); pricing in USDC. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/31-mcp-servers.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/32-published-sdks-docs.md b/prompts/32-published-sdks-docs.mdindex 37ea16954..71bd9941b 100644--- a/prompts/32-published-sdks-docs.md+++ b/prompts/32-published-sdks-docs.md@@ -30,3 +30,17 @@ types, accurate README, working examples, and a verified build/publish path.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs in examples — real, runnable. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Keep forks (character-studio, agent-payments-sdk) cleanly attributed. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/32-published-sdks-docs.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/33-onchain-contracts.md b/prompts/33-onchain-contracts.mdindex e8129d7b6..48ab38536 100644--- a/prompts/33-onchain-contracts.md+++ b/prompts/33-onchain-contracts.md@@ -30,3 +30,17 @@ safe before they secure real value.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No real third-party mints in tests/fixtures — use $THREE (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or a synthetic placeholder. No mocks of on-chain logic in integration tests. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/33-onchain-contracts.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/34-solana-base-parity.md b/prompts/34-solana-base-parity.mdindex 6ca14f8ff..145bb8a6f 100644--- a/prompts/34-solana-base-parity.md+++ b/prompts/34-solana-base-parity.md@@ -27,3 +27,17 @@ default, Base/EVM as a well-behaved secondary — with no silent divergence.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. Solana is the default network. No mocks of chain logic. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); settlement in USDC. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/34-solana-base-parity.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/35-api-rate-limiting-abuse.md b/prompts/35-api-rate-limiting-abuse.mdindex 717c82e27..fe048c369 100644--- a/prompts/35-api-rate-limiting-abuse.md+++ b/prompts/35-api-rate-limiting-abuse.md@@ -28,3 +28,17 @@ expensive) — without harming legitimate users.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles (`__defProp`/`createRequire`) — recover with `git restore -- api/ public/`. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/35-api-rate-limiting-abuse.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/36-observability-logging-alerting.md b/prompts/36-observability-logging-alerting.mdindex f80eea97e..3aa43859c 100644--- a/prompts/36-observability-logging-alerting.md+++ b/prompts/36-observability-logging-alerting.md@@ -29,3 +29,17 @@ Structured logs, error tracking, key metrics, and alerts on the flows that matte---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs; logs must never leak secrets. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/36-observability-logging-alerting.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/37-ci-cd-gates.md b/prompts/37-ci-cd-gates.mdindex f85d49778..88b84d9b9 100644--- a/prompts/37-ci-cd-gates.md+++ b/prompts/37-ci-cd-gates.md@@ -29,3 +29,17 @@ and build on every change, and a safe deploy path to Vercel for both mirrors.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Push to BOTH remotes (`git push threeD main && git push threews main`); never pull/fetch/merge from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/37-ci-cd-gates.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/38-database-migrations.md b/prompts/38-database-migrations.mdindex 19e896269..5bf61c8e1 100644--- a/prompts/38-database-migrations.md+++ b/prompts/38-database-migrations.md@@ -28,3 +28,17 @@ between schema and code, no destructive migration without a path back.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs; never run a destructive migration without backup + rollback. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/38-database-migrations.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/39-load-stress-testing.md b/prompts/39-load-stress-testing.mdindex e4a24e139..51a406e49 100644--- a/prompts/39-load-stress-testing.md+++ b/prompts/39-load-stress-testing.md@@ -27,3 +27,17 @@ and fix or document the scaling story so a launch spike doesn't take us down.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. Load-test only our own infra (staging/test env + free lanes) — no third-party targeting. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Put harnesses in `scripts/`, not the repo root. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/39-load-stress-testing.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/40-caching-cdn-assets.md b/prompts/40-caching-cdn-assets.mdindex 95a6730fe..35024b61a 100644--- a/prompts/40-caching-cdn-assets.md+++ b/prompts/40-caching-cdn-assets.md@@ -28,3 +28,17 @@ immutable hashing, and a healthy CDN/R2 setup — and never serve stale HTML.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. `vercel.json` changes are deploy-time. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/40-caching-cdn-assets.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/41-uptime-health-status.md b/prompts/41-uptime-health-status.mdindex 71298a35e..9d5738a57 100644--- a/prompts/41-uptime-health-status.md+++ b/prompts/41-uptime-health-status.md@@ -28,3 +28,17 @@ dependency, automated uptime monitoring, and a public status page.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs; health checks must reflect reality and never leak secrets. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/41-uptime-health-status.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/42-homepage-conversion.md b/prompts/42-homepage-conversion.mdindex 54be3ca0e..dcc485549 100644--- a/prompts/42-homepage-conversion.md+++ b/prompts/42-homepage-conversion.md@@ -30,3 +30,17 @@ visitors into agent-builders. This is the top of the funnel — make it world-cl---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/fabricated stats. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/42-homepage-conversion.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/43-docs-completeness.md b/prompts/43-docs-completeness.mdindex 205d2ff8e..a1a2bfe9b 100644--- a/prompts/43-docs-completeness.md+++ b/prompts/43-docs-completeness.md@@ -27,3 +27,17 @@ tool, embed, and concept is documented accurately with working examples.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No fake/sample-only docs — every example runs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/43-docs-completeness.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/44-legal-compliance.md b/prompts/44-legal-compliance.mdindex a1e3993d4..386d4e9cf 100644--- a/prompts/44-legal-compliance.md+++ b/prompts/44-legal-compliance.md@@ -29,3 +29,17 @@ cookie/consent handling, content policy, and clear disclaimers — accurate to w---### Operating rules — read CLAUDE.md + STRUCTURE.md first. Policies must reflect reality — no placeholder legalese that misstates the product. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); never reference another token. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist. (This is product/legal scaffolding, not legal advice — flag anything that needs counsel review.)++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/44-legal-compliance.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/45-analytics-funnels.md b/prompts/45-analytics-funnels.mdindex 81b7f6155..233287615 100644--- a/prompts/45-analytics-funnels.md+++ b/prompts/45-analytics-funnels.md@@ -29,3 +29,17 @@ retention, with privacy-respecting analytics and honest dashboards.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No fabricated metrics; analytics reflect real events. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/45-analytics-funnels.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/46-notifications-email.md b/prompts/46-notifications-email.mdindex 96459df4e..ef860eafb 100644--- a/prompts/46-notifications-email.md+++ b/prompts/46-notifications-email.md@@ -30,3 +30,17 @@ holders' changelog channel) that are timely, correct, and respectful of preferen---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs; real sends. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages` (then `changelog:push` after deploy). Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/46-notifications-email.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/47-i18n-completeness.md b/prompts/47-i18n-completeness.mdindex 354e329e5..049871f39 100644--- a/prompts/47-i18n-completeness.md+++ b/prompts/47-i18n-completeness.md@@ -29,3 +29,17 @@ and English as a safe fallback.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. $THREE, the CA, USDC, x402 must never be altered by translation. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). No fake/placeholder translations shipped. Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/47-i18n-completeness.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/48-pricing-monetization.md b/prompts/48-pricing-monetization.mdindex 57e40d5b7..a87a12e56 100644--- a/prompts/48-pricing-monetization.md+++ b/prompts/48-pricing-monetization.md@@ -28,3 +28,17 @@ $THREE perks — all consistent, all real, all converting.---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No fake prices/mock checkouts; settle in USDC. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/48-pricing-monetization.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/49-pwa-extension.md b/prompts/49-pwa-extension.mdindex 9388a6baa..fc47d35bc 100644--- a/prompts/49-pwa-extension.md+++ b/prompts/49-pwa-extension.md@@ -28,3 +28,17 @@ promise is real, reliable, and store-ready — without the service worker ever b---### Operating rules — read CLAUDE.md + STRUCTURE.md first. No mocks/fake data/stubs. $THREE only (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Stage explicit paths; never `git add -A`. Don't commit `api/*.js` bundles. User-visible change → `data/changelog.json` + `npm run build:pages`. Push both remotes when asked; never pull from `threeD`. DoD = CLAUDE.md checklist.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/49-pwa-extension.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets-ii/02-wallet-intents-copilot.md b/prompts/agent-wallets-ii/02-wallet-intents-copilot.mdindex edf8add14..e81d27d1b 100644--- a/prompts/agent-wallets-ii/02-wallet-intents-copilot.md+++ b/prompts/agent-wallets-ii/02-wallet-intents-copilot.md@@ -110,3 +110,17 @@ After done, run the self-review protocol. Pick the biggest weakness and fix itshareable "rule template" gallery, a simulation timeline, or letting an intent post apublic "this agent just tipped you back" moment (coordinate with Patronage 05). Then**delete this file**.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets-ii/02-wallet-intents-copilot.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets-ii/06-irl-money-drops-bounties.md b/prompts/agent-wallets-ii/06-irl-money-drops-bounties.mdindex 4b6d4ec2a..28f9c431b 100644--- a/prompts/agent-wallets-ii/06-irl-money-drops-bounties.md+++ b/prompts/agent-wallets-ii/06-irl-money-drops-bounties.md@@ -90,3 +90,17 @@ demo.After done, run the self-review protocol. Pick the biggest weakness and fix it — e.g.sponsored "agent treasure trails" across multiple pins, or surfacing live drops as pulseson the Money Constellation (task 04) and as a discovery hook. Then **delete this file**.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets-ii/06-irl-money-drops-bounties.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets-ii/07-proof-of-reserves-reputation.md b/prompts/agent-wallets-ii/07-proof-of-reserves-reputation.mdindex 8197b5f68..2f69db511 100644--- a/prompts/agent-wallets-ii/07-proof-of-reserves-reputation.md+++ b/prompts/agent-wallets-ii/07-proof-of-reserves-reputation.md@@ -94,3 +94,17 @@ After done, run the self-review protocol. Pick the biggest weakness and fix itsigned, shareable "proof-of-reserves snapshot" an agent can post, or feeding reputationinto the sniper/copy-trade flows so users can auto-filter to high-reputation agents. Then**delete this file**.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets-ii/07-proof-of-reserves-reputation.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/12-galaxy-money-cam.md b/prompts/agent-wallets/12-galaxy-money-cam.mdindex 63ebb5fdf..35c2df043 100644--- a/prompts/agent-wallets/12-galaxy-money-cam.md+++ b/prompts/agent-wallets/12-galaxy-money-cam.md@@ -84,3 +84,17 @@ console errors; responsive.When done: self-review + improvement pass, changelog entry, commit (explicit pathsonly, push to **both** remotes if asked), then **delete this file**(`prompts/agent-wallets/12-galaxy-money-cam.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/12-galaxy-money-cam.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/13-fork-royalty-streams.md b/prompts/agent-wallets/13-fork-royalty-streams.mdindex d1bbaeb6b..34387fd3e 100644--- a/prompts/agent-wallets/13-fork-royalty-streams.md+++ b/prompts/agent-wallets/13-fork-royalty-streams.md@@ -112,3 +112,17 @@ When done: run the self-review + improvement pass, add a real changelog entry,`npm run build:pages` to validate, commit (staging explicit paths only; push to**both** `threeD` and `threews` if asked), then **delete this file**(`prompts/agent-wallets/13-fork-royalty-streams.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/13-fork-royalty-streams.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/15-agent-to-agent-economy.md b/prompts/agent-wallets/15-agent-to-agent-economy.mdindex 2e2ada268..8ef860e5f 100644--- a/prompts/agent-wallets/15-agent-to-agent-economy.md+++ b/prompts/agent-wallets/15-agent-to-agent-economy.md@@ -115,3 +115,17 @@ When done: run the self-review + improvement pass, add a real changelog entry,`npm run build:pages` to validate, commit (staging explicit paths only; push to**both** `threeD` and `threews` if asked), then **delete this file**(`prompts/agent-wallets/15-agent-to-agent-economy.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/15-agent-to-agent-economy.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/01-treasury-autopilot.md b/prompts/agent-wallets/innovation/01-treasury-autopilot.mdindex 5555b9289..704768f0d 100644--- a/prompts/agent-wallets/innovation/01-treasury-autopilot.md+++ b/prompts/agent-wallets/innovation/01-treasury-autopilot.md@@ -79,3 +79,17 @@ Per the README checklist. Prove live: arm a real rule, trigger it with a real timainnet (or devnet for the demo, clearly labeled in UI as network), watch the agentact on-chain, see it in the timeline + custody ledger. Then add your improvement.Summarize, then delete this file (`prompts/agent-wallets/innovation/01-treasury-autopilot.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/01-treasury-autopilot.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/02-lineage-royalties.md b/prompts/agent-wallets/innovation/02-lineage-royalties.mdindex 3f9bca18f..9e3c14b92 100644--- a/prompts/agent-wallets/innovation/02-lineage-royalties.md+++ b/prompts/agent-wallets/innovation/02-lineage-royalties.md@@ -67,3 +67,17 @@ Per the README checklist. Prove live: fork an agent with a real royalty, send threal tip, watch the split land in the ancestor's wallet with on-chain signatures, see iton the tree and in both agents' ledgers. Add your improvement, summarize, then deletethis file (`prompts/agent-wallets/innovation/02-lineage-royalties.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/02-lineage-royalties.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/03-vanity-constellation.md b/prompts/agent-wallets/innovation/03-vanity-constellation.mdindex 27451f04c..af424572b 100644--- a/prompts/agent-wallets/innovation/03-vanity-constellation.md+++ b/prompts/agent-wallets/innovation/03-vanity-constellation.md@@ -71,3 +71,17 @@ Per the README checklist. Prove live: run a real grind pool with 2+ browser tabsfind a `3ws…` match, gift it via sealed envelope, claim+assign it with a real on-chainsweep, see rarity reflected everywhere. Add your improvement, summarize, then delete thisfile (`prompts/agent-wallets/innovation/03-vanity-constellation.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/03-vanity-constellation.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/04-living-wallet-aura.md b/prompts/agent-wallets/innovation/04-living-wallet-aura.mdindex b0ecb5eaf..dfb826eed 100644--- a/prompts/agent-wallets/innovation/04-living-wallet-aura.md+++ b/prompts/agent-wallets/innovation/04-living-wallet-aura.md@@ -61,3 +61,17 @@ Per the README checklist. Prove live: tip an agent and watch its body react in 3AR; confirm aura tiers match real balances; confirm polling stops offscreen and there's nojank with a full list. Add your improvement, summarize, then delete this file(`prompts/agent-wallets/innovation/04-living-wallet-aura.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/04-living-wallet-aura.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/05-programmable-paywalls.md b/prompts/agent-wallets/innovation/05-programmable-paywalls.mdindex 3b894619f..581c159fb 100644--- a/prompts/agent-wallets/innovation/05-programmable-paywalls.md+++ b/prompts/agent-wallets/innovation/05-programmable-paywalls.md@@ -65,3 +65,17 @@ Per the README checklist. Prove live: gate a real piece of content, pay it fromwallet, watch it confirm on-chain and reveal, see the receipt in `x402_receipts`/grants andthe supporter badge appear; confirm re-entry is free. Add your improvement, summarize, thendelete this file (`prompts/agent-wallets/innovation/05-programmable-paywalls.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/05-programmable-paywalls.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/06-economy-passport.md b/prompts/agent-wallets/innovation/06-economy-passport.mdindex e7bc7da5a..f1c82bab7 100644--- a/prompts/agent-wallets/innovation/06-economy-passport.md+++ b/prompts/agent-wallets/innovation/06-economy-passport.md@@ -61,3 +61,17 @@ Per the README checklist. Prove live: open a real agent's passport, confirm evertraces to a real source you can verify on-chain, generate the OG share image, embed thebadge on a test page and see it pull real data. Add your improvement, summarize, thendelete this file (`prompts/agent-wallets/innovation/06-economy-passport.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/06-economy-passport.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/07-a2a-commerce-exchange.md b/prompts/agent-wallets/innovation/07-a2a-commerce-exchange.mdindex cc87be6ba..74cb5525a 100644--- a/prompts/agent-wallets/innovation/07-a2a-commerce-exchange.md+++ b/prompts/agent-wallets/innovation/07-a2a-commerce-exchange.md@@ -63,3 +63,17 @@ Per the README checklist. Prove live: have one agent autonomously hire + pay anoreal skill over x402, see both ledgers update with the on-chain signature, and watch thejob animate in Mission Control. Add your improvement, summarize, then delete this file(`prompts/agent-wallets/innovation/07-a2a-commerce-exchange.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/07-a2a-commerce-exchange.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/agent-wallets/innovation/08-harmonize-verify.md b/prompts/agent-wallets/innovation/08-harmonize-verify.mdindex ce1ddf23d..af094c3bb 100644--- a/prompts/agent-wallets/innovation/08-harmonize-verify.md+++ b/prompts/agent-wallets/innovation/08-harmonize-verify.md@@ -74,3 +74,17 @@ and the verified cross-feature flows.When done: commit (explicit paths only; push to **both** remotes if asked), then **deletethis file**. When 01–08 are all deleted, delete `00-README-innovation.md` too — theinnovation program is shipped.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/agent-wallets/innovation/08-harmonize-verify.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/avatar-autorig/01-sibling-materialization.md b/prompts/avatar-autorig/01-sibling-materialization.mdindex 79381d453..6b0bdbadc 100644--- a/prompts/avatar-autorig/01-sibling-materialization.md+++ b/prompts/avatar-autorig/01-sibling-materialization.md@@ -169,3 +169,17 @@ Run, in order:- **CDN/edge purge of stale id-keyed GLB bytes** for embeds that already cached the source by id (the `immutable` proxy header at `api/avatars/[id]/[action].js:656`). The sibling's new id + new R2 key is sufficient for this prompt; the deep cache-busting fix is a deferred follow-up (tracked in `00-README.md`).- **Auto-pin the rigged sibling to IPFS** (real Pinata orchestration of the rigged bytes + re-attestation). Here we only avoid the orphan; wiring the re-pin is a deferred follow-up (tracked in `00-README.md`).- **Gallery/library UX for parent→rigged lineage** ("view original", lineage badge, dedupe in the grid) — deferred frontend follow-up (tracked in `00-README.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/avatar-autorig/01-sibling-materialization.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/avatar-autorig/02-completion-statemachine.md b/prompts/avatar-autorig/02-completion-statemachine.mdindex 200441b76..06c8bc050 100644--- a/prompts/avatar-autorig/02-completion-statemachine.md+++ b/prompts/avatar-autorig/02-completion-statemachine.md@@ -186,3 +186,17 @@ Run, in order, and paste results into your final summary:- Reconstruct-pipeline finalize hardening (`api/_lib/reconstruct-finalize.js`) — defer unless a shared helper extraction is trivially safe.- Surfacing a per-avatar "rigging…" / "rig failed, retry" state in the avatar UI — note the gap for a follow-up UI prompt; don't build it here.- Provider-side webhook retry configuration on Replicate — infra, out of band.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/avatar-autorig/02-completion-statemachine.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/avatar-autorig/03-ssrf-hardening.md b/prompts/avatar-autorig/03-ssrf-hardening.mdindex 5c1581fec..6de0b3e8c 100644--- a/prompts/avatar-autorig/03-ssrf-hardening.md+++ b/prompts/avatar-autorig/03-ssrf-hardening.md@@ -152,3 +152,17 @@ Run and read the output of each:- Cost/consent gates before submitting rig jobs → `04-cost-and-consent-gates.md`.- Coverage gaps for other creation paths → `05-coverage-gaps.md`.- Rig cache/backfill → `06-rig-cache-and-backfill.md`; quality gate/fallback → `07-quality-gate-and-fallback.md`; observability/events → `08-observability-and-events.md`; full test suite → `09-test-suite.md`.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/avatar-autorig/03-ssrf-hardening.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/avatar-autorig/04-cost-and-consent-gates.md b/prompts/avatar-autorig/04-cost-and-consent-gates.mdindex c8a837722..8960ad031 100644--- a/prompts/avatar-autorig/04-cost-and-consent-gates.md+++ b/prompts/avatar-autorig/04-cost-and-consent-gates.md@@ -151,3 +151,17 @@ Each requirement is numbered with an explicit acceptance criterion.- Emitting rig lifecycle events/metrics beyond the `source_meta` breadcrumbs here → `08-observability-and-events.md`.- Consolidated test suite hardening → `09-test-suite.md`.- Rate-limiting the avatar *create* request itself (not just the rig submission) — deferred, broader auth-surface change.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/avatar-autorig/04-cost-and-consent-gates.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/avatar-autorig/05-coverage-gaps.md b/prompts/avatar-autorig/05-coverage-gaps.mdindex 6bcc25122..a3eef7533 100644--- a/prompts/avatar-autorig/05-coverage-gaps.md+++ b/prompts/avatar-autorig/05-coverage-gaps.md@@ -154,3 +154,17 @@ Manual checks:- **Cron rescue + rig cache/backfill** (`06-rig-cache-and-backfill.md`): the jobs these paths now submit are what the cron rescues; backfilling avatars created before this fix lives there.- **Cost & consent gates** (`04-cost-and-consent-gates.md`): whether auto-rig should be gated by cost/consent on the fork/studio paths is decided there, not here.- **Completion state machine** (`02-completion-statemachine.md`) and **observability/events** (`08-observability-and-events.md`): the lifecycle/status transitions and event emission for these new jobs are owned by those prompts.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/avatar-autorig/05-coverage-gaps.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/01-robot-link-foundation.md b/prompts/embodiment/01-robot-link-foundation.mdindex 473fbe04e..097b84ca7 100644--- a/prompts/embodiment/01-robot-link-foundation.md+++ b/prompts/embodiment/01-robot-link-foundation.md@@ -78,3 +78,17 @@ now"). Add the keyboard shortcut to summon the embody panel.Delete this file. Report the `RobotLink` interface, the adapters shipped, the real endpoints+ migration, and the on-chain binding mechanism used.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/01-robot-link-foundation.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/02-mind-sync.md b/prompts/embodiment/02-mind-sync.mdindex a7f15fcf8..a9505912f 100644--- a/prompts/embodiment/02-mind-sync.md+++ b/prompts/embodiment/02-mind-sync.md@@ -73,3 +73,17 @@ were just reading about X"). Make one being in two places undeniable.Delete this file. Report the real memory/brain/persona endpoints used, the write-back schema,and the continuity model.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/02-mind-sync.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/03-embodied-motion.md b/prompts/embodiment/03-embodied-motion.mdindex 2030206c8..803653e45 100644--- a/prompts/embodiment/03-embodied-motion.md+++ b/prompts/embodiment/03-embodied-motion.md@@ -68,3 +68,17 @@ maps the user's webcam pose to the robot via `body-mocap`. Smooth, intentional,Delete this file. Report the joint-map approach, which clips retarget, the safety envelopelimits, and how the twin stays in lockstep.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/03-embodied-motion.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/04-the-face.md b/prompts/embodiment/04-the-face.mdindex b57af6bea..d35345e8c 100644--- a/prompts/embodiment/04-the-face.md+++ b/prompts/embodiment/04-the-face.md@@ -63,3 +63,17 @@ illusion is total. Subtle, grounded in real signals.Delete this file. Report the face render/transport path, the viseme pipeline, and themood→morph mapping.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/04-the-face.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/05-onchain-soul-ownership.md b/prompts/embodiment/05-onchain-soul-ownership.mdindex e8f4dbc8d..a76abbde6 100644--- a/prompts/embodiment/05-onchain-soul-ownership.md+++ b/prompts/embodiment/05-onchain-soul-ownership.md@@ -75,3 +75,17 @@ time-boxed grant in $THREE. Real on-chain, real settlement.Delete this file. Report the contracts/records used, the snapshot/encryption path, thegrant/transfer/revoke mechanism, and the $THREE settlement rail.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/05-onchain-soul-ownership.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/06-telepresence-twin.md b/prompts/embodiment/06-telepresence-twin.mdindex 0f4ba7bf2..803202966 100644--- a/prompts/embodiment/06-telepresence-twin.md+++ b/prompts/embodiment/06-telepresence-twin.md@@ -63,3 +63,17 @@ voice while staying in character. Real, low-latency, screenshot-worthy.Delete this file. Report the media transport, the mirror mechanism, the teleop command path, andthe control-handoff model.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/06-telepresence-twin.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/07-safety-consent-killswitch.md b/prompts/embodiment/07-safety-consent-killswitch.mdindex b4889c43a..af8bd216f 100644--- a/prompts/embodiment/07-safety-consent-killswitch.md+++ b/prompts/embodiment/07-safety-consent-killswitch.md@@ -69,3 +69,17 @@ hit. Provable, instant, friendly.Delete this file. Report the guards reused, the e-stop path + its test, the safety-envelopelimits + geofence, and how the on-chain grant drives the runtime safe state.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/07-safety-consent-killswitch.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/embodiment/08-integration-qa-polish.md b/prompts/embodiment/08-integration-qa-polish.mdindex d2146a079..7f904e022 100644--- a/prompts/embodiment/08-integration-qa-polish.md+++ b/prompts/embodiment/08-integration-qa-polish.md@@ -60,3 +60,17 @@ signals.Delete this file. Report the end-to-end journey you exercised, the seams you fixed, the testsadded, and the final architecture as shipped.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/embodiment/08-integration-qa-polish.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-agents/02-persistent-companion-hud.md b/prompts/living-agents/02-persistent-companion-hud.mdindex ffeb0ea6a..6db353326 100644--- a/prompts/living-agents/02-persistent-companion-hud.md+++ b/prompts/living-agents/02-persistent-companion-hud.md@@ -83,3 +83,17 @@ mute toggle. Do the one that most makes a first-time user say "whoa."Delete this file. Report which bus events you consume and the contextual quick-editsurface per route.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-agents/02-persistent-companion-hud.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-agents/09-integration-qa-and-polish.md b/prompts/living-agents/09-integration-qa-and-polish.mdindex 3673da320..e3f60c9b6 100644--- a/prompts/living-agents/09-integration-qa-and-polish.md+++ b/prompts/living-agents/09-integration-qa-and-polish.md@@ -68,3 +68,17 @@ architecture (the bus contract, the surfaces, the data flow) for future contribuDelete this file. Report the journeys you exercised, what you fixed at the seams, the perfresult, and the one polish item you elevated.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-agents/09-integration-qa-and-polish.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/01-living-avatar-embodied-wallet.md b/prompts/living-wallet/01-living-avatar-embodied-wallet.mdindex 15c660330..a2841d199 100644--- a/prompts/living-wallet/01-living-avatar-embodied-wallet.md+++ b/prompts/living-wallet/01-living-avatar-embodied-wallet.md@@ -120,3 +120,17 @@ moment, a subtle $THREE-holder signature, or wiring the pulse to Task 08's econofeed. Add the polish that makes people screenshot it. Update `data/changelog.json`.**Then delete this prompt file** — the code is the artifact now.</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/01-living-avatar-embodied-wallet.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/02-proximity-commerce-worlds.md b/prompts/living-wallet/02-proximity-commerce-worlds.mdindex df71e11d5..217078796 100644--- a/prompts/living-wallet/02-proximity-commerce-worlds.md+++ b/prompts/living-wallet/02-proximity-commerce-worlds.md@@ -100,3 +100,17 @@ Push it: maybe "tip to react" emotes, a nearby-agents radar, or surfacing recentproximity tips into Task 08's economy feed. Add the delight that makes it shareable.Update `data/changelog.json`. **Then delete this prompt file.**</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/02-proximity-commerce-worlds.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/03-autonomous-treasury-strategies.md b/prompts/living-wallet/03-autonomous-treasury-strategies.mdindex bd2aa3829..06d295e5f 100644--- a/prompts/living-wallet/03-autonomous-treasury-strategies.md+++ b/prompts/living-wallet/03-autonomous-treasury-strategies.md@@ -99,3 +99,17 @@ Push it: a strategy "backtest from the agent's own real history," shareable(amount-free) strategy templates, or notifying the owner via the existing notifierwhen an action lands. Update `data/changelog.json`. **Then delete this prompt file.**</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/03-autonomous-treasury-strategies.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/06-conversational-wallet-copilot.md b/prompts/living-wallet/06-conversational-wallet-copilot.mdindex a5f39b1fc..aa898d91c 100644--- a/prompts/living-wallet/06-conversational-wallet-copilot.md+++ b/prompts/living-wallet/06-conversational-wallet-copilot.md@@ -94,3 +94,17 @@ Push it: proactive nudges ("your DCA from Task 03 just ran"), spoken P&L summari"explain this transaction" over the real custody trail. Update `data/changelog.json`.**Then delete this prompt file.**</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/06-conversational-wallet-copilot.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/07-embeddable-wallet-sdk.md b/prompts/living-wallet/07-embeddable-wallet-sdk.mdindex 98e3cdb54..8bcbe3537 100644--- a/prompts/living-wallet/07-embeddable-wallet-sdk.md+++ b/prompts/living-wallet/07-embeddable-wallet-sdk.md@@ -86,3 +86,17 @@ Push it: a copy-paste snippet generator in the embed/widget studio, per-embedattribution so creators see which placement earns, or a "tip goal" bar. Update`data/changelog.json`. **Then delete this prompt file.**</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/07-embeddable-wallet-sdk.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/08-living-economy-feed.md b/prompts/living-wallet/08-living-economy-feed.mdindex 1d0a0b482..b78ec4796 100644--- a/prompts/living-wallet/08-living-economy-feed.md+++ b/prompts/living-wallet/08-living-economy-feed.md@@ -88,3 +88,17 @@ Push it: a "since you were away" recap, agent-specific economy mini-feeds on proor wiring proximity tips (Task 02) and strategy actions (Task 03) into the stream.Update `data/changelog.json`. **Then delete this prompt file.**</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/08-living-economy-feed.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/living-wallet/09-integration-polish-qa.md b/prompts/living-wallet/09-integration-polish-qa.mdindex 57d8262de..30f3cb7de 100644--- a/prompts/living-wallet/09-integration-polish-qa.md+++ b/prompts/living-wallet/09-integration-polish-qa.md@@ -98,3 +98,17 @@ make someone screenshot the whole thing? Add it. Update `data/changelog.json`. *delete this prompt file** — and, since this is the last task, remove the now-empty`prompts/living-wallet/` directory.</content>++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/living-wallet/09-integration-polish-qa.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/01-zero-knowledge-split-key-vanity.md b/prompts/vanity-frontier/01-zero-knowledge-split-key-vanity.mdindex 382d0dfdb..0461eea02 100644--- a/prompts/vanity-frontier/01-zero-knowledge-split-key-vanity.md+++ b/prompts/vanity-frontier/01-zero-knowledge-split-key-vanity.md@@ -133,3 +133,17 @@ This is the central feasibility risk. Your job is to resolve it properly, not toDo not take shortcuts. If the ideal seed-based version is impossible, prove why, ship the strongesttrustless version that IS possible, and make it genuinely usable. That is the bar.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/01-zero-knowledge-split-key-vanity.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/02-confidential-x402-sealed-compute.md b/prompts/vanity-frontier/02-confidential-x402-sealed-compute.mdindex 32d31d764..cad168d99 100644--- a/prompts/vanity-frontier/02-confidential-x402-sealed-compute.md+++ b/prompts/vanity-frontier/02-confidential-x402-sealed-compute.md@@ -78,3 +78,17 @@ but them. This is a primitive the whole x402 ecosystem lacks. We ship it first,No mock crypto, no fake payments, no half-wired SDK. The deliverable is something another teamcould adopt in their own x402 service this afternoon.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/02-confidential-x402-sealed-compute.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/03-proof-of-grind-provenance.md b/prompts/vanity-frontier/03-proof-of-grind-provenance.mdindex 7e26b9c4c..0a1d0c4b7 100644--- a/prompts/vanity-frontier/03-proof-of-grind-provenance.md+++ b/prompts/vanity-frontier/03-proof-of-grind-provenance.md@@ -75,3 +75,17 @@ trustable asset.If Task 01 (split-key) isn't merged yet, build the certificate + verifier for the existingkeypair/mnemonic formats first and design the schema so the split-key non-custody fields slot incleanly. No fake signatures, no "trust us" verifier — real, independent verification only.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/03-proof-of-grind-provenance.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/04-semantic-vanity-compiler.md b/prompts/vanity-frontier/04-semantic-vanity-compiler.mdindex 75325f6a5..8a25c3c63 100644--- a/prompts/vanity-frontier/04-semantic-vanity-compiler.md+++ b/prompts/vanity-frontier/04-semantic-vanity-compiler.md@@ -74,3 +74,17 @@ first-class compiled artifact. We will.shipped, where to reach it, and any tradeoffs.Make it the tool people screenshot. Real APIs, real math, no shortcuts.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/04-semantic-vanity-compiler.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/05-grind-to-earn-pool.md b/prompts/vanity-frontier/05-grind-to-earn-pool.mdindex c643d433d..2db835f36 100644--- a/prompts/vanity-frontier/05-grind-to-earn-pool.md+++ b/prompts/vanity-frontier/05-grind-to-earn-pool.md@@ -76,3 +76,17 @@ addresses. Realtime, trustless, paid. Nobody has this.If Task 01's split-key isn't merged, build the pool on the trustless invariant as specified andintegrate the moment it lands — but do NOT ship a version that routes full private keys throughworkers. Trustless or nothing. Real economics, no shortcuts.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/05-grind-to-earn-pool.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/06-mcp-wallet-concierge.md b/prompts/vanity-frontier/06-mcp-wallet-concierge.mdindex 9bd69b111..550b1079a 100644--- a/prompts/vanity-frontier/06-mcp-wallet-concierge.md+++ b/prompts/vanity-frontier/06-mcp-wallet-concierge.md@@ -75,3 +75,17 @@ find and use them.This is the tool an autonomous agent reaches for to get a wallet it can trust. Build it that good.No shortcuts, real everything.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/06-mcp-wallet-concierge.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-frontier/07-vanity-as-agent-identity-3d.md b/prompts/vanity-frontier/07-vanity-as-agent-identity-3d.mdindex 17bb574be..01e24d133 100644--- a/prompts/vanity-frontier/07-vanity-as-agent-identity-3d.md+++ b/prompts/vanity-frontier/07-vanity-as-agent-identity-3d.md@@ -69,3 +69,17 @@ suite that *can't* be copied by a generic key tool.This is the one that goes viral. Make it feel like magic — but every frame is backed by realcrypto and real grinding. No shortcuts.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-frontier/07-vanity-as-agent-identity-3d.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-x402/03-sealed-wallet-drops.md b/prompts/vanity-x402/03-sealed-wallet-drops.mdindex fe2b4f1c4..b36f60a08 100644--- a/prompts/vanity-x402/03-sealed-wallet-drops.md+++ b/prompts/vanity-x402/03-sealed-wallet-drops.md@@ -85,3 +85,17 @@ airdrop from one payment), a "drip" drop that vests, or a "scan to receive" modea room agent emits drops to attendees. Add a recovery story if the recipient losestheir claim key. Summarize, then **delete this file**(`prompts/vanity-x402/03-sealed-wallet-drops.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-x402/03-sealed-wallet-drops.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-x402/04-threshold-sealed-delivery.md b/prompts/vanity-x402/04-threshold-sealed-delivery.mdindex e5fe8ee44..815fd0828 100644--- a/prompts/vanity-x402/04-threshold-sealed-delivery.md+++ b/prompts/vanity-x402/04-threshold-sealed-delivery.md@@ -83,3 +83,17 @@ re-keying via re-sharing), share-holder revocation, an audit view of who has opetheir share, and tying the member set to three.ws identities/agents so shares seal topeople automatically. Summarize, then **delete this file**(`prompts/vanity-x402/04-threshold-sealed-delivery.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-x402/04-threshold-sealed-delivery.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-x402/05-vanity-as-skill-mcp.md b/prompts/vanity-x402/05-vanity-as-skill-mcp.mdindex 598e59286..f554cafa0 100644--- a/prompts/vanity-x402/05-vanity-as-skill-mcp.md+++ b/prompts/vanity-x402/05-vanity-as-skill-mcp.md@@ -91,3 +91,17 @@ spawns (delegated identity), add a revocation/rotation path for the binding, andthe provision flow as an x402-discoverable Bazaar skill so other agent frameworks findit automatically. Summarize, then **delete this file**(`prompts/vanity-x402/05-vanity-as-skill-mcp.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-x402/05-vanity-as-skill-mcp.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/vanity-x402/07-streaming-pay-as-you-grind.md b/prompts/vanity-x402/07-streaming-pay-as-you-grind.mdindex d74d487c9..99a1d6fb0 100644--- a/prompts/vanity-x402/07-streaming-pay-as-you-grind.md+++ b/prompts/vanity-x402/07-streaming-pay-as-you-grind.md@@ -79,3 +79,17 @@ runs long, multi-worker streaming for very hard patterns (ties to Task 02's fleesurfacing the same pay-as-you-go transport as a reusable primitive other paid endpointscan adopt. Summarize, then **delete this file**(`prompts/vanity-x402/07-streaming-pay-as-you-grind.md`).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/vanity-x402/07-streaming-pay-as-you-grind.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/01-mpc-threshold-custody.md b/prompts/wallet-innovation/01-mpc-threshold-custody.mdindex a11d241dc..3549c146f 100644--- a/prompts/wallet-innovation/01-mpc-threshold-custody.md+++ b/prompts/wallet-innovation/01-mpc-threshold-custody.md@@ -117,3 +117,17 @@ Re-read as an attacker: where could a single domain still betray the user? Closeit. Then make the transparency UI genuinely reassuring (a simple diagram of thesplit beats a paragraph). Verify on devnet, review your diff, then **delete thisprompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/01-mpc-threshold-custody.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/04-proof-of-custody.md b/prompts/wallet-innovation/04-proof-of-custody.mdindex f55309eba..a0213bed1 100644--- a/prompts/wallet-innovation/04-proof-of-custody.md+++ b/prompts/wallet-innovation/04-proof-of-custody.md@@ -95,3 +95,17 @@ Then improve it: add a one-line shareable "verified custody" badge/embed ownerscan show off, and make the reconciliation explain any delta in human terms.Verify the full prove→anchor→verify loop on devnet in a browser, review yourdiff, then **delete this prompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/04-proof-of-custody.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/05-passkey-stepup.md b/prompts/wallet-innovation/05-passkey-stepup.mdindex eeab6f29e..c2c97a60f 100644--- a/prompts/wallet-innovation/05-passkey-stepup.md+++ b/prompts/wallet-innovation/05-passkey-stepup.md@@ -90,3 +90,17 @@ amount the human is actually approving, with the allowlist badge), and add"require passkey to disable any safety feature" as a default so protections can'tbe quietly turned off. Verify with a real virtual authenticator in the browser,review your diff, then **delete this prompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/05-passkey-stepup.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/06-session-keys.md b/prompts/wallet-innovation/06-session-keys.mdindex fdaf913fa..0df2fe835 100644--- a/prompts/wallet-innovation/06-session-keys.md+++ b/prompts/wallet-innovation/06-session-keys.md@@ -95,3 +95,17 @@ Then improve it: auto-suggest tight default capabilities when an owner enables askill/strategy (so least-privilege is the default, not a chore), and show eachcapability's real-time spend against its leash. Verify the devnet scope test inthe browser, review your diff, then **delete this prompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/06-session-keys.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/07-streaming-allowance-deadman.md b/prompts/wallet-innovation/07-streaming-allowance-deadman.mdindex 17d439a15..1011ec0b2 100644--- a/prompts/wallet-innovation/07-streaming-allowance-deadman.md+++ b/prompts/wallet-innovation/07-streaming-allowance-deadman.md@@ -107,3 +107,17 @@ and visualize the stream so the throttle is obvious; make the dead-man status acalm, reassuring readout ("Active — last seen 2h ago; protection arms after 30days"). Verify both flows on devnet in the browser, review your diff, then**delete this prompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/07-streaming-allowance-deadman.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/wallet-innovation/08-live-feed-clawback.md b/prompts/wallet-innovation/08-live-feed-clawback.mdindex 7c13d0689..4c7baf1ac 100644--- a/prompts/wallet-innovation/08-live-feed-clawback.md+++ b/prompts/wallet-innovation/08-live-feed-clawback.md@@ -105,3 +105,17 @@ Then improve it: surface the policy/anomaly reason inline on each event (wire to`02`/`03` if present), and make the held-item countdown + one-tap decision feelinstant and trustworthy. Verify the cancel-before-settle guarantee on devnet inthe browser, review your diff, then **delete this prompt file.**++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "prompts/wallet-innovation/08-live-feed-clawback.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/public/changelog.json b/public/changelog.jsonindex 87f9c6ebd..94bbc18b3 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T13:47:33.738Z",+ "generated_at": "2026-06-24T15:43:34.031Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 10ed3b0fb..c0aeefc61 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T13:47:33.721Z",+ "generated_at": "2026-06-24T15:43:34.011Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1166,6 +1166,16 @@"tags": [],"showcase": false},+ {+ "path": "/ibm/hello",+ "title": "IBM × three.ws partnership",+ "description": "The IBM × three.ws partnership page: how three.ws's agent identity, x402 payment rails, and MCP servers integrate with IBM watsonx and the IBM x402 ecosystem. A self-contained showcase that stays live-editable after publish.",+ "added": null,+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/lookup","title": "Agent Lookup",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 932e1dd9b..540605ca4 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -708,6 +708,12 @@ URL: https://three.ws/ibm/x402-demoA self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.+### IBM × three.ws partnership++URL: https://three.ws/ibm/hello++The IBM × three.ws partnership page: how three.ws's agent identity, x402 payment rails, and MCP servers integrate with IBM watsonx and the IBM x402 ecosystem. A self-contained showcase that stays live-editable after publish.+### Agent LookupURL: https://three.ws/lookupdiff --git a/public/llms.txt b/public/llms.txtindex 80f7d0d73..3fe1d9d89 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -136,6 +136,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [watsonx Constellation](https://three.ws/constellation): Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.- [x402 Live Demo (IBM × three.ws)](https://three.ws/ibm/x402-demo): A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.+- [IBM × three.ws partnership](https://three.ws/ibm/hello): The IBM × three.ws partnership page: how three.ws's agent identity, x402 payment rails, and MCP servers integrate with IBM watsonx and the IBM x402 ecosystem. A self-contained showcase that stays live-editable after publish.- [Agent Lookup](https://three.ws/lookup): Resolve any three.ws agent by Solana mint, agent ID, avatar ID, or slug — renders its interactive 3D avatar alongside its on-chain identity (collection, owner, agent wallet, Active/x402 status, Metaplex/Solscan/Magic Eden links).- [x402 Arbitrage](https://three.ws/arbitrage): Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 3d455a8a0..a488ad85d 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,25 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header class="sm-topbar">@@ -65,7 +84,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 337 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 338 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +96,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 337 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 338 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -606,7 +625,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>68</span></h2>+ <h2>Crypto<span class="sm-count" data-count>69</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -918,6 +937,13 @@<span class="sm-desc">A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.</span></a></li>+ <li>+ <a href="/ibm/hello">+ <span class="sm-title">IBM × three.ws partnership</span>+ <span class="sm-path">/ibm/hello</span>+ <span class="sm-desc">The IBM × three.ws partnership page: how three.ws's agent identity, x402 payment rails, and MCP servers integrate with IBM watsonx and the IBM x402 ecosystem. A self-contained showcase that stays live-editable after publish.</span>+ </a>+ </li><li><a href="/lookup"><span class="sm-title">Agent Lookup</span>diff --git a/scripts/audit-console.mjs b/scripts/audit-console.mjsnew file mode 100644index 000000000..15256fb13--- /dev/null+++ b/scripts/audit-console.mjs@@ -0,0 +1,529 @@+#!/usr/bin/env node+/**+ * Console sweep — drives every canonical HTML route from data/pages.json in a+ * headless Chromium (Playwright) at desktop and mobile viewports, exercises the+ * primary interaction (scroll + settle), and collects:+ * • console errors / warnings (from our code; environment noise filtered out)+ * • uncaught page errors and unhandled promise rejections+ * • failed first-party network requests (4xx/5xx + transport failures)+ *+ * A clean console is part of the Definition of Done (CLAUDE.md). This is the+ * lasting, npm-able check — wired as `npm run audit:console`.+ *+ * Usage:+ * node scripts/audit-console.mjs # every HTML route, both viewports+ * node scripts/audit-console.mjs / /forge /play # specific routes only+ * node scripts/audit-console.mjs --desktop # 1440×900 only+ * node scripts/audit-console.mjs --mobile # 390×844 only+ * node scripts/audit-console.mjs --no-blog # skip /blog/* content pages+ * node scripts/audit-console.mjs --report # write docs/audit/console-sweep-<date>.md+ * LOG_ALL=1 node scripts/audit-console.mjs # stream every console line+ * HEADFUL=1 node scripts/audit-console.mjs # watch it run+ * CONCURRENCY=6 node scripts/audit-console.mjs # parallel tabs (default 5)+ *+ * Reuses a dev server already on :3000, otherwise spawns an ephemeral Vite. The+ * dev server proxies /api/* to https://three.ws, so API calls hit real+ * endpoints — auth/payment-gated 4xx are classified "expected", never failures.+ */++import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer } from 'node:net';+import { spawn } from 'node:child_process';+import { get as httpGet } from 'node:http';+import { chromium } from 'playwright';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const C = {+ g: (s) => `\x1b[32m${s}\x1b[0m`,+ r: (s) => `\x1b[31m${s}\x1b[0m`,+ y: (s) => `\x1b[33m${s}\x1b[0m`,+ d: (s) => `\x1b[2m${s}\x1b[0m`,+ b: (s) => `\x1b[1m${s}\x1b[0m`,+ c: (s) => `\x1b[36m${s}\x1b[0m`,+};++// ── Viewports ────────────────────────────────────────────────────────────────+const VIEWPORTS = {+ desktop: { width: 1440, height: 900, isMobile: false, label: 'desktop 1440×900' },+ mobile: { width: 390, height: 844, isMobile: true, label: 'mobile 390×844' },+};++// ── Noise filters ────────────────────────────────────────────────────────────+// Console text that is never a real defect from our code (dev infra, browser+// policy, third-party telemetry, auth-gated API statuses, external CDN CORS).+const IGNORE_CONSOLE = [+ // Vite HMR / dev infra. In Codespaces the HMR wss handshake 302s through the+ // proxy — documented environment noise, not a page bug.+ /\[vite\]/i,+ /@vite\/client/i,+ /WebSocket closed without opened/i,+ /WebSocket connection to .* failed/i,+ /Error during WebSocket handshake/i,+ /failed to connect to websocket/i,+ /\[HMR\]/i,+ // Browser policy / environment+ /the AudioContext was not allowed to start/i,+ /Tracking Prevention/i,+ /autoplay/i,+ /Permissions policy violation/i,+ /Unrecognized feature:/i,+ // Third-party analytics / telemetry (never our code)+ /posthog/i,+ /sentry/i,+ /segment\.com/i,+ /google-analytics/i,+ /cdn\.vercel-insights/i,+ /vercel\.live/i,+ // API calls judged by HTTP status, not console — auth/payment-gate is expected+ /Failed to load resource.*\/api\//i,+ /\b(401|402|403|429|503)\b.*\/api\//i,+ /Failed to load resource: the server responded with a status of 40[0-3]/i,+ /Failed to load resource: the server responded with a status of 429/i,+ /Failed to load resource: the server responded with a status of 5(02|03)/i,+ // Walk multiplayer / live socket servers not running in dev (graceful fallback)+ /Failed to load resource: net::ERR_CONNECTION_REFUSED/i,+ /net::ERR_CONNECTION_REFUSED/i,+ /\[walk-net\]/i,+ // R2/CDN CORS from dev origins (localhost) — only blocks in dev, not production+ /r2\.dev.*Access-Control/i,+ /r2\.dev.*CORS policy/i,+ /CORS policy.*r2\.dev/i,+ /Access-Control-Allow-Origin.*r2\.dev/i,+ /pub-[a-f0-9]+\.r2\.dev.*blocked/i,+ /blocked by CORS policy.*r2\.dev/i,+ // User-generated data with expired signed URLs — not our code+ /private-user-images\.githubusercontent\.com.*404/i,+ /X-Amz-Signature.*404/i,+ // Three.js / WebGL expected notices+ /THREE\.WebGLRenderer: WebGL 1 is not supported/i,+ /THREE\.BufferGeometry\.computeBoundingSphere/i,+ /WebGL.*swiftshader/i,+ /Automatic fallback to software WebGL/i,+ // Content-Security-Policy noise from third-party embeds+ /content security policy/i,+ /Refused to (load|connect|execute|frame)/i,+ // Solana / wallet adapter expected console output+ /StandardWalletAdapter/i,+ /wallet adapter/i,+ // dev tooling+ /Download the React DevTools/i,+ // iframe sandbox noise+ /Allow attribute/i,+ /Blocked.*frame/i,+ // Font loading via CSS (browser-level, not our JS)+ /OTS parsing error/i,+ /downloadable font/i,+ // Colyseus/socket deprecation warnings+ /using deprecated parameters for the initialization/i,+ // Vite dep-optimizer race: when the optimizer re-bundles mid-navigation,+ // in-flight requests for the old dep hash 504 and Vite auto-reloads the page.+ // Purely a dev-server artifact — production ships pre-bundled deps, never 504s.+ /504 \(Outdated Optimize Dep\)/i,+ /Outdated Optimize Dep/i,+];++function isIgnorableConsole(text) {+ return IGNORE_CONSOLE.some((re) => re.test(text));+}++// First-party URLs whose 4xx/5xx is a dev-server artifact, never a prod defect:+// • /.vite/deps/* — optimizer re-bundle race (504), Vite auto-reloads+// • /agent-3d/.../agent-3d.js — the <agent-3d> custom-element bundle. In dev a+// plugin serves it from dist-lib/ (needs `npm run build:lib`); in production+// it's a real CDN asset at https://three.ws/agent-3d/latest/agent-3d.js.+// • *.map — source maps; browsers probe them, 404 is harmless+function isDevOnlyAsset(u) {+ if (/\/.vite\/deps\//.test(u)) return true;+ if (/\/agent-3d\/[^/]+\/agent-3d\.(js|umd\.cjs)(\?|$)/.test(u)) return true;+ if (/\.map(\?|$)/.test(u)) return true;+ return false;+}++// ── Route manifest from data/pages.json ──────────────────────────────────────+function loadRoutes({ includeBlog }) {+ const data = JSON.parse(readFileSync(join(ROOT, 'data/pages.json'), 'utf8'));+ const seen = new Set();+ const routes = [];+ for (const section of data.sections) {+ // `machine` section = non-HTML endpoints (.xml/.txt/.json/.well-known) —+ // no DOM, no console; not part of a browser sweep.+ if (section.id === 'machine') continue;+ if (section.id === 'blog' && !includeBlog) continue;+ for (const page of section.pages) {+ const path = page.path;+ // Skip anything that resolves to a static file rather than an HTML page.+ if (/\.[a-z0-9]+$/i.test(path) && !/\.html$/i.test(path)) continue;+ if (seen.has(path)) continue;+ seen.add(path);+ routes.push({+ path,+ section: section.id,+ title: page.title || path,+ auth: page.auth === 'required',+ });+ }+ }+ return routes;+}++// ── Dev server ───────────────────────────────────────────────────────────────+function probe(url, timeoutMs = 2000) {+ return new Promise((resolve) => {+ const req = httpGet(url, (res) => {+ res.resume();+ resolve(res.statusCode || 0);+ });+ req.setTimeout(timeoutMs, () => req.destroy());+ req.on('error', () => resolve(0));+ });+}++function freePort() {+ return new Promise((resolve, reject) => {+ const srv = createServer();+ srv.unref();+ srv.on('error', reject);+ srv.listen(0, () => {+ const { port } = srv.address();+ srv.close(() => resolve(port));+ });+ });+}++const PROBE_BASE = 'http://127.0.0.1:3000';++async function warmupDeps(base) {+ // Hit a few dep-heavy pages so Vite pre-bundles before the timed sweep,+ // otherwise the first real navigation eats the optimizer's reload.+ const warmPaths = ['/', '/forge', '/play', '/pumpfun', '/agent-exchange'];+ process.stdout.write(' warming Vite dep optimizer ');+ for (const p of warmPaths) {+ await fetch(`${base}${p}`).catch(() => {});+ process.stdout.write('.');+ }+ await new Promise((r) => setTimeout(r, 8000));+ process.stdout.write('\n');+}++async function startServer() {+ if (await probe(`${PROBE_BASE}/`, 5000)) {+ console.log(C.d(' reusing dev server on :3000'));+ // localhost (not 127.0.0.1) — some CDN CORS configs allow it, fewer spurious errors.+ const navBase = 'http://localhost:3000';+ await warmupDeps(navBase);+ return { base: navBase, stop: async () => {} };+ }+ const port = await freePort();+ const bin = join(ROOT, 'node_modules', '.bin', 'vite');+ const child = spawn(bin, ['--port', String(port), '--strictPort'], {+ cwd: ROOT,+ stdio: process.env.LOG_ALL ? 'inherit' : 'ignore',+ env: process.env,+ });+ const probeBase = `http://127.0.0.1:${port}`;+ const navBase = `http://localhost:${port}`;+ const deadline = Date.now() + 90_000;+ process.stdout.write(` starting Vite on :${port} `);+ while (Date.now() < deadline) {+ if (child.exitCode != null) throw new Error(`vite exited early (code ${child.exitCode})`);+ if (await probe(`${probeBase}/`, 2000)) {+ process.stdout.write('\n');+ break;+ }+ process.stdout.write('.');+ await new Promise((r) => setTimeout(r, 500));+ }+ if (Date.now() >= deadline) {+ child.kill('SIGKILL');+ throw new Error('vite did not become ready within 90s');+ }+ await warmupDeps(navBase);+ return { base: navBase, stop: async () => child.kill('SIGTERM') };+}++// ── Per-route check ──────────────────────────────────────────────────────────+const SETTLE_MS = Number(process.env.SETTLE_MS || 3000);++async function checkRoute(context, base, route) {+ const page = await context.newPage();++ const consoleErrors = [];+ const consoleWarnings = [];+ const failedAssets = [];+ const degradedApis = [];++ page.on('console', (msg) => {+ const text = msg.text();+ if (process.env.LOG_ALL) console.log(C.d(` [${route.path} ${msg.type()}] ${text}`));+ if (isIgnorableConsole(text)) return;+ if (msg.type() === 'error') consoleErrors.push(text);+ else if (msg.type() === 'warning') consoleWarnings.push(text);+ });++ page.on('pageerror', (err) => {+ const msg = err.message || String(err);+ if (!isIgnorableConsole(msg)) consoleErrors.push('pageerror: ' + msg);+ });++ page.on('requestfailed', (req) => {+ const u = req.url();+ const errorText = req.failure()?.errorText || '';+ if (u.includes('@vite') || u.startsWith('ws:') || u.startsWith('wss:')) return;+ if (/posthog|sentry|segment|google-analytics|vercel-insights|vercel\.live/i.test(u)) return;+ if (isDevOnlyAsset(u)) return;+ const rt = req.resourceType();+ if (!['document', 'script', 'stylesheet', 'font'].includes(rt)) return;+ if (!u.startsWith(base)) return;+ if (rt === 'document' && errorText.includes('ERR_ABORTED')) return;+ if (errorText.includes('ERR_CONNECTION_REFUSED')) return;+ // ERR_ABORTED on a script/style usually follows a 4xx/5xx already recorded+ // by the response handler — don't double-count.+ if (errorText.includes('ERR_ABORTED')) return;+ failedAssets.push(`${req.method()} ${rt} ${u.replace(base, '')} — ${errorText}`);+ });++ page.on('response', (res) => {+ const u = res.url();+ const s = res.status();+ if (s < 400) return;+ if (/posthog|sentry|segment|google-analytics|vercel-insights|vercel\.live/i.test(u)) return;+ if (u.includes('/api/')) {+ degradedApis.push(`${s} ${u.replace(base, '')}`);+ return;+ }+ if (!u.startsWith(base)) return; // external (CDN/third-party) — not our first-party asset+ if (isDevOnlyAsset(u)) return;+ const rt = res.request().resourceType();+ failedAssets.push(`HTTP ${s} ${rt} ${u.replace(base, '')}`);+ });++ const navErrors = [];+ const rejections = [];+ await page.addInitScript(() => {+ window.addEventListener('unhandledrejection', (e) => {+ const r = e.reason;+ (window.__rejections ||= []).push(String((r && (r.stack || r.message)) || r));+ });+ });++ const url = base + route.path;+ try {+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });+ } catch (e) {+ navErrors.push(`navigation failed: ${e.message}`);+ await page.close();+ return { route, navErrors, consoleErrors, consoleWarnings, failedAssets, degradedApis, rejections };+ }++ // Primary interaction: scroll the page to fire lazy loaders / intersection+ // observers / on-scroll mounts, then settle so async fetches + module loads land.+ try {+ await page.evaluate(async () => {+ const h = document.body?.scrollHeight || 0;+ window.scrollTo({ top: h, behavior: 'instant' });+ await new Promise((r) => setTimeout(r, 200));+ window.scrollTo({ top: 0, behavior: 'instant' });+ });+ } catch {+ /* page may have torn down */+ }+ await new Promise((r) => setTimeout(r, SETTLE_MS));++ const injected = await page.evaluate(() => window.__rejections || []).catch(() => []);+ for (const e of injected) if (!isIgnorableConsole(e)) rejections.push('unhandledrejection: ' + e);++ await page.close();+ return { route, navErrors, consoleErrors, consoleWarnings, failedAssets, degradedApis, rejections };+}++function totalErrors(r) {+ return r.navErrors.length + r.consoleErrors.length + r.failedAssets.length + r.rejections.length;+}++// ── Concurrency pool ─────────────────────────────────────────────────────────+async function runPool(items, size, worker) {+ const out = new Array(items.length);+ let next = 0;+ const runners = Array.from({ length: Math.min(size, items.length) }, async () => {+ while (true) {+ const i = next++;+ if (i >= items.length) break;+ out[i] = await worker(items[i], i);+ }+ });+ await Promise.all(runners);+ return out;+}++// ── Main ─────────────────────────────────────────────────────────────────────+const args = process.argv.slice(2);+const argRoutes = args.filter((a) => a.startsWith('/'));+const wantReport = args.includes('--report');+const includeBlog = !args.includes('--no-blog');+const onlyDesktop = args.includes('--desktop');+const onlyMobile = args.includes('--mobile');+const CONCURRENCY = Number(process.env.CONCURRENCY || 5);++const viewportKeys = onlyDesktop ? ['desktop'] : onlyMobile ? ['mobile'] : ['desktop', 'mobile'];++let routes = loadRoutes({ includeBlog });+if (argRoutes.length) routes = routes.filter((r) => argRoutes.includes(r.path));+if (!routes.length) {+ console.error('No matching routes from data/pages.json.');+ process.exit(1);+}++console.log(C.b('\n╔══ Console Sweep (Playwright) ═══════════════════════════════╗'));+console.log(` ${routes.length} HTML routes × ${viewportKeys.length} viewport(s) — concurrency ${CONCURRENCY}`);+console.log(C.b('╚═════════════════════════════════════════════════════════════╝\n'));++const { base, stop } = await startServer();++const browser = await chromium.launch({+ headless: !process.env.HEADFUL,+ args: [+ '--no-sandbox',+ '--disable-dev-shm-usage',+ '--disable-setuid-sandbox',+ '--use-gl=angle',+ '--use-angle=swiftshader',+ '--enable-unsafe-swiftshader',+ '--ignore-gpu-blocklist',+ '--mute-audio',+ ],+});++// results[viewportKey] = array of per-route result objects+const results = {};++for (const vpKey of viewportKeys) {+ const vp = VIEWPORTS[vpKey];+ console.log(C.b(`\n▶ ${vp.label}\n`));+ const context = await browser.newContext({+ viewport: { width: vp.width, height: vp.height },+ isMobile: vp.isMobile,+ hasTouch: vp.isMobile,+ deviceScaleFactor: vp.isMobile ? 3 : 1,+ userAgent: vp.isMobile+ ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1'+ : undefined,+ });++ let done = 0;+ const res = await runPool(routes, CONCURRENCY, async (route) => {+ const r = await checkRoute(context, base, route);+ done++;+ const errs = totalErrors(r);+ const status = errs === 0 ? C.g('✓') : C.r(`✗ ${errs}`);+ const warn = r.consoleWarnings.length ? C.y(` (${r.consoleWarnings.length}w)`) : '';+ process.stdout.write(+ ` [${String(done).padStart(3)}/${routes.length}] ${status}${warn} ${C.c(route.path)}\n`,+ );+ return r;+ });+ results[vpKey] = res;+ await context.close();+}++await browser.close();+await stop();++// ── Report ───────────────────────────────────────────────────────────────────+// Merge per-viewport rows by route for the summary table.+const byPath = new Map();+for (const vpKey of viewportKeys) {+ for (const r of results[vpKey]) {+ const row = byPath.get(r.route.path) || { route: r.route, vp: {} };+ row.vp[vpKey] = r;+ byPath.set(r.route.path, row);+ }+}++const rows = [...byPath.values()];+const failing = rows.filter((row) => viewportKeys.some((k) => totalErrors(row.vp[k]) > 0));++console.log('\n' + C.b('═══════════════ SUMMARY ═══════════════\n'));+let grandErrors = 0;+for (const row of rows) {+ const parts = [];+ for (const k of viewportKeys) {+ const r = row.vp[k];+ const e = totalErrors(r);+ grandErrors += e;+ parts.push(`${k}: ${e === 0 ? C.g('clean') : C.r(e + ' err')}${r.consoleWarnings.length ? C.y(' ' + r.consoleWarnings.length + 'w') : ''}`);+ }+}+if (failing.length === 0) {+ console.log(C.g(` ALL ${rows.length} ROUTES CLEAN across ${viewportKeys.length} viewport(s) — zero errors from our code.\n`));+} else {+ console.log(C.r(` ${failing.length} route(s) with errors:\n`));+ for (const row of failing) {+ console.log(C.r(`✗ ${row.route.path} ${C.d('(' + row.route.section + ')')}`));+ for (const k of viewportKeys) {+ const r = row.vp[k];+ if (totalErrors(r) === 0) continue;+ for (const e of r.navErrors) console.log(` ${C.d(k)} nav: ${C.r(e)}`);+ for (const e of r.consoleErrors) console.log(` ${C.d(k)} console:${C.r(e)}`);+ for (const e of r.failedAssets) console.log(` ${C.d(k)} asset: ${C.r(e)}`);+ for (const e of r.rejections) console.log(` ${C.d(k)} reject: ${C.r(e)}`);+ }+ }+ console.log('');+}++// ── Optional markdown report ─────────────────────────────────────────────────+if (wantReport) {+ const date = new Date().toISOString().slice(0, 10);+ const outDir = join(ROOT, 'docs/audit');+ mkdirSync(outDir, { recursive: true });+ const outFile = join(outDir, `console-sweep-${date}.md`);+ const lines = [];+ lines.push(`# Console Sweep — ${date}`);+ lines.push('');+ lines.push(+ `Headless Chromium (Playwright) over ${rows.length} HTML routes from \`data/pages.json\` at ${viewportKeys.map((k) => VIEWPORTS[k].label).join(' and ')}. ` ++ `Each route: \`domcontentloaded\` → scroll → ${SETTLE_MS}ms settle. ` ++ `Environment noise (Vite HMR-proxy wss handshake, third-party telemetry, auth-gated \`/api\` 4xx, dev-origin CDN CORS) is filtered.`,+ );+ lines.push('');+ lines.push(`**Result:** ${failing.length === 0 ? '✅ all routes clean' : `❌ ${failing.length} route(s) with errors`} — ${grandErrors} total error(s).`);+ lines.push('');+ lines.push('## Per-route');+ lines.push('');+ const head = ['Route', 'Section', ...viewportKeys.flatMap((k) => [`${k} err`, `${k} warn`])];+ lines.push('| ' + head.join(' | ') + ' |');+ lines.push('|' + head.map(() => '---').join('|') + '|');+ for (const row of rows.sort((a, b) => a.route.path.localeCompare(b.route.path))) {+ const cells = [`\`${row.route.path}\``, row.route.section];+ for (const k of viewportKeys) {+ const r = row.vp[k];+ cells.push(String(totalErrors(r)), String(r.consoleWarnings.length));+ }+ lines.push('| ' + cells.join(' | ') + ' |');+ }+ if (failing.length) {+ lines.push('');+ lines.push('## Failures (detail)');+ lines.push('');+ for (const row of failing) {+ lines.push(`### \`${row.route.path}\` (${row.route.section})`);+ for (const k of viewportKeys) {+ const r = row.vp[k];+ if (totalErrors(r) === 0) continue;+ lines.push(`- **${k}**`);+ for (const e of r.navErrors) lines.push(` - nav: ${e}`);+ for (const e of r.consoleErrors) lines.push(` - console: ${e}`);+ for (const e of r.failedAssets) lines.push(` - asset: ${e}`);+ for (const e of r.rejections) lines.push(` - rejection: ${e}`);+ }+ lines.push('');+ }+ }+ writeFileSync(outFile, lines.join('\n') + '\n');+ console.log(C.c(` report written → ${outFile.replace(ROOT + '/', '')}\n`));+}++process.exit(failing.length === 0 ? 0 : 1);diff --git a/scripts/audit-page-index.mjs b/scripts/audit-page-index.mjsindex 4183158e7..0267a5806 100644--- a/scripts/audit-page-index.mjs+++ b/scripts/audit-page-index.mjs@@ -56,6 +56,7 @@ const IGNORE = new Set(['/aws', // AWS Marketplace entitlement landing, reached via marketplace redirect'/paywall', // transactional gate, reached in-flow when access is required'/sperax/iframe', // partner chat embed iframe, not a discovery page+ '/ibm/hello.live', // editable source variant of /ibm/hello (the canonical page is generated from it); not a separate discovery page]);// Whole prefixes that are internal/auth-gated/embed and never belong in thediff --git a/scripts/rank-backlog.mjs b/scripts/rank-backlog.mjsindex b7cc2cdf5..258d6288c 100644--- a/scripts/rank-backlog.mjs+++ b/scripts/rank-backlog.mjs@@ -1,52 +1,81 @@#!/usr/bin/env node-// Rank the open (partial/pending) backlog by a transparent composite priority score.+// Rank the open backlog (everything the triage did NOT mark DONE) by a+// transparent composite priority score, so "what to do first" is reproducible+// rather than vibes. Consumes the triage written by verify-task-completion.mjs.+// Run `npm run prioritize` (triage + rank) or this directly after a triage pass.import { readFileSync, writeFileSync, existsSync } from 'node:fs';-const rows = JSON.parse(readFileSync('reports/task-completion-verified.json', 'utf8'))- .filter(x => x.verdict !== 'done' && existsSync(x.file));+// Prefer a human/agent-adjudicated override if one exists; else the heuristic pass.+// Both must use verify-task-completion.mjs's schema ({ file, bucket, why, ... }).+const REPORT = existsSync('reports/task-completion-verified.json')+ ? 'reports/task-completion-verified.json'+ : 'reports/task-completion.json';-const LABEL = /priority[:*\s]*\**\s*(critical|high|medium|low|p0|p1|p2|p3)/i;-const labelWeight = { critical: 4, p0: 4, high: 3, p1: 3, medium: 1, p2: 1, p3: -1, low: -1 };+if (!existsSync(REPORT)) {+ console.error(`No triage report at ${REPORT}. Run: npm run triage`);+ process.exit(1);+}++const all = JSON.parse(readFileSync(REPORT, 'utf8')).filter(x => existsSync(x.file));-// product-value weights, grounded in repo focus + memory+// --- priority model (transparent, grounded in repo focus) ------------------+// 1) actionability — how much undone work the triage actually detected.+const ACTION = { PENDING: 4, REVIEW: 2, DONE: 0 };++// 2) launch-criticality / value, keyed on the REAL current tree (not stale paths).function valueWeight(file) {- if (/^tasks\/nvidia-nim|^prompts\/tripo-gap|^prompts\/animation-studio/.test(file)) return 3; // generation suite = top focus- if (/^prompts\/agent-fixes/.test(file)) return 3; // live production bug fixes- if (/^tasks\/onchain-deployment|^prompts\/siwx|^tasks\/pumpfun-launchpad/.test(file)) return 2; // payments/onchain infra- if (/^tasks\/agent-monetization|^tasks\/monetization-feature/.test(file)) return 1; // real monetization backend- if (/^prompts\/monetization(\/|-)/.test(file)) return -2; // duplicate prompt explosion -> dedupe, not 90 tasks- return 0; // walk/site-overhaul/wow-sprint/etc.+ // launch-gating + must-run-first audits — break these and nothing else matters+ if (/(production-readiness|dead-paths|console-errors|routing-and-404|build-deploy-artifact|security-review|e2e-critical-flows|error-handling-failsafes|final-launch-checklist)/.test(file)) return 5;+ // money & trust: payments, wallets, on-chain, auth, abuse, SSRF+ if (/(x402-payments|wallet-connect|pumpfun-launches|three-holder-gating|onchain-contracts|solana-base-parity|api-rate-limiting|ssrf|passkey|proof-of-reserves|proof-of-custody|session-keys|threshold|sealed)/.test(file)) return 4;+ // cross-cutting quality + infra/ops that gate a credible launch+ if (/(test-coverage|accessibility|responsive|performance|seo|design-system|caching|observability|ci-cd|database-migrations|uptime|load-stress)/.test(file)) return 3;+ // core product surfaces (forge..dashboard == prompts/15-26)+ if (/prompts\/(1[5-9]|2[0-6])-/.test(file)) return 2;+ // growth / GTM+ if (/(homepage-conversion|docs-completeness|legal-compliance|analytics|notifications|i18n|pricing-monetization|pwa-extension)/.test(file)) return 1;+ // innovation tracks (vanity, living-wallet, agent-wallets, embodiment, autorig, ...) — post-launch reach+ return 0;}-for (const r of rows) {- const t = readFileSync(r.file, 'utf8');- const m = t.match(LABEL);+// 3) optional explicit override — honor a `Priority:` line if a prompt declares one.+const LABEL = /priority[:*\s]*\**\s*(critical|high|medium|low|p0|p1|p2|p3)/i;+const labelWeight = { critical: 3, p0: 3, high: 2, p1: 2, medium: 0, p2: 0, p3: -2, low: -2 };++for (const r of all) {+ const m = readFileSync(r.file, 'utf8').match(LABEL);r.label = m ? m[1].toLowerCase() : '';- let score = 0;- score += r.label ? labelWeight[r.label] : 0;- score += r.verdict === 'partial' ? 2 : 0;- score += r.confidence === 'high' ? 1 : 0;- score += valueWeight(r.file);- r.score = score;+ // uncertainty bump: a REVIEW backed by weak git evidence is more worth checking+ const uncertain = r.bucket === 'REVIEW' && (r.gitSignal ?? 0) < 0.5 ? 1 : 0;+ r.value = valueWeight(r.file);+ r.score = (ACTION[r.bucket] ?? 0) + r.value + (r.label ? labelWeight[r.label] : 0) + uncertain;}-rows.sort((a, b) => b.score - a.score || (a.verdict < b.verdict ? -1 : 1) || a.file.localeCompare(b.file));++// Open backlog = anything not heuristically DONE. DONE-by-git stays out of the action list.+const open = all+ .filter(r => r.bucket !== 'DONE')+ .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));writeFileSync('reports/task-priority.csv',- 'rank,score,verdict,confidence,label,file,missing\n' +- rows.map((r, i) => [i + 1, r.score, r.verdict, r.confidence, r.label || '-', r.file,- JSON.stringify((r.missing || '').replace(/\s+/g, ' ').slice(0, 160))].join(',')).join('\n'));--const dups = rows.filter(r => valueWeight(r.file) === -2);-const quickWins = rows.filter(r => r.verdict === 'partial' && r.confidence === 'high' && valueWeight(r.file) >= 0);-const topPending = rows.filter(r => r.verdict === 'pending' && r.score >= 3);--const show = (r) => ` [${r.score}] ${r.verdict}/${r.confidence}${r.label ? ' ·' + r.label : ''} ${r.file}\n ↳ ${(r.missing || '').replace(/\s+/g, ' ').slice(0, 130)}`;--console.log(`open backlog: ${rows.length}\n`);-console.log(`=== TIER 1 — QUICK WINS (partial + high confidence, real value): ${quickWins.length} ===`);-quickWins.slice(0, 12).forEach(r => console.log(show(r)));-console.log(`\n=== TIER 2 — HIGH PRIORITY, NOT STARTED (score>=3, pending): ${topPending.length} ===`);-topPending.slice(0, 12).forEach(r => console.log(show(r)));-console.log(`\n=== DEPRIORITIZE / DEDUPE — duplicate monetization prompts: ${dups.length} ===`);-console.log(` (collapse into one canonical set instead of treating as ${dups.length} tasks)`);-console.log(`\nFull ranking: reports/task-priority.csv`);+ 'rank,score,bucket,value,label,gitSignal,file,why\n' ++ open.map((r, i) => [i + 1, r.score, r.bucket, r.value, r.label || '-', r.gitSignal ?? '-', r.file,+ JSON.stringify((r.why || '').replace(/\s+/g, ' ').slice(0, 160))].join(',')).join('\n'));++const missingOf = (r) => [...new Set([...(r.newMissing || []), ...(r.refMissing || [])].filter(Boolean))];+const show = (r) => {+ const miss = missingOf(r);+ const tail = miss.length ? `missing: ${miss.slice(0, 4).join(', ')}` : (r.why || '');+ return ` [${r.score}] ${r.bucket}${r.label ? ' ·' + r.label : ''} (value ${r.value}) ${r.file}` ++ (tail ? `\n ↳ ${tail}` : '');+};++const pending = open.filter(r => r.bucket === 'PENDING');+const review = open.filter(r => r.bucket === 'REVIEW');++console.log(`scanned ${all.length} prompt(s) — open backlog: ${open.length} (DONE-by-triage: ${all.length - open.length})\n`);+console.log(`=== TIER 1 — MISSING DELIVERABLES (build, or prove an equivalent already ships): ${pending.length} ===`);+pending.forEach(r => console.log(show(r)));+console.log(`\n=== TIER 2 — BUILT BUT UNVERIFIED (behavior check / e2e before trusting): ${review.length} ===`);+review.forEach(r => console.log(show(r)));+console.log(`\nFull ranking incl. scores: reports/task-priority.csv`);+console.log(`Note: "DONE" means the declared files exist (git-slug heuristic) — not a verified behavior pass.`);diff --git a/scripts/stamp-prompt-self-delete.mjs b/scripts/stamp-prompt-self-delete.mjsindex 28c093846..0539d4c5c 100644--- a/scripts/stamp-prompt-self-delete.mjs+++ b/scripts/stamp-prompt-self-delete.mjs@@ -3,7 +3,7 @@// prompt/task markdown file under tasks/ and prompts/. Skips meta docs// (README/PLAN/REPORT/...) and files already stamped. Safe to re-run.import { readFileSync, writeFileSync } from 'node:fs';-import { readdirSync, statSync } from 'node:fs';+import { readdirSync, statSync, existsSync } from 'node:fs';import { join, relative } from 'node:path';const ROOT = process.cwd();@@ -43,7 +43,9 @@ Stage the deletion alongside your implementation and include it in the completiolet stamped = 0, skipped = 0, meta = 0;for (const r of ROOTS) {- for (const file of walk(join(ROOT, r))) {+ const rootDir = join(ROOT, r);+ if (!existsSync(rootDir)) continue;+ for (const file of walk(rootDir)) {const rel = relative(ROOT, file);const base = file.split('/').pop();if (META.test(base)) { meta++; continue; }diff --git a/scripts/verify-task-completion.mjs b/scripts/verify-task-completion.mjsindex e9e739873..e12528580 100644--- a/scripts/verify-task-completion.mjs+++ b/scripts/verify-task-completion.mjs@@ -10,7 +10,7 @@ import { execSync } from 'node:child_process';import { join, relative } from 'node:path';const ROOT = process.cwd();-const ROOTS = ['tasks', 'prompts'];+const ROOTS = ['tasks', 'prompts'].filter(d => existsSync(join(ROOT, d)));const META = /(README|PLAN|MANIFEST|REPORT|CHECKLIST|PERF_NOTES|START-HERE|_shared|ORPHAN|SIGNERS|overview)/i;// --- repo ground truth -----------------------------------------------------diff --git a/src/reasoning-ledger.js b/src/reasoning-ledger.jsindex 63eb95db2..6cfbff2ab 100644--- a/src/reasoning-ledger.js+++ b/src/reasoning-ledger.js@@ -249,7 +249,7 @@ function timelineSection() {function hero(agent) {const img = agent?.image- ? `<img class="rl-agent-avatar" src="${esc(agent.image)}" alt="" />`+ ? `<img class="rl-agent-avatar" src="${esc(agent.image)}" alt="" loading="lazy" decoding="async" />`: `<div class="rl-agent-avatar"></div>`;const name = agent?.name ? esc(agent.name) : 'Agent';return `diff --git a/src/vaults.js b/src/vaults.jsindex 1da718c58..3fc1924c8 100644--- a/src/vaults.js+++ b/src/vaults.js@@ -203,7 +203,7 @@ function renderDetail(v, ledger) {const nav = v.nav;const roi = nav.roi_bps || 0;const t = v.terms;- const agentImg = v.agent?.image ? `<img class="vx-d-av" src="${esc(v.agent.image)}" alt="" />` : '<div class="vx-d-av vx-d-av--ph" aria-hidden="true"></div>';+ const agentImg = v.agent?.image ? `<img class="vx-d-av" src="${esc(v.agent.image)}" alt="" loading="lazy" decoding="async" />` : '<div class="vx-d-av vx-d-av--ph" aria-hidden="true"></div>';const halted = v.status === 'paused';const closed = v.status === 'closing' || v.status === 'closed';diff --git a/tests/pump-tx-program-guard.test.js b/tests/pump-tx-program-guard.test.jsnew file mode 100644index 000000000..8f4dda935--- /dev/null+++ b/tests/pump-tx-program-guard.test.js@@ -0,0 +1,70 @@+// Unit tests for the launch-confirm program guard in api/_lib/pump.js.+//+// txInvokesPumpProgram() is what stops a confirmed tx that merely *references*+// a freshly-ground mint pubkey (a memo, a transfer) from being recorded in+// pump_agent_mints as a real launch. The real module is imported (no vi.mock)+// so we exercise the actual parsing + the real PUMP_PROGRAM_ID constant.++import { describe, it, expect } from 'vitest';+import { txProgramIds, txInvokesPumpProgram } from '../api/_lib/pump.js';+import { PUMP_PROGRAM_ID } from '../api/_lib/solana/programs.js';++const SYSTEM = '11111111111111111111111111111111';+const TOKEN = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';++// Mirror the getParsedTransaction shape: programId may be a base58 string or a+// PublicKey-like object exposing toString().+const pk = (s) => ({ toString: () => s });++describe('txProgramIds', () => {+ it('collects top-level and inner-instruction program ids (string + pubkey forms)', () => {+ const tx = {+ transaction: { message: { instructions: [{ programId: pk(PUMP_PROGRAM_ID) }, { programId: SYSTEM }] } },+ meta: { innerInstructions: [{ index: 0, instructions: [{ programId: pk(TOKEN) }] }] },+ };+ const ids = txProgramIds(tx);+ expect(ids.has(PUMP_PROGRAM_ID)).toBe(true);+ expect(ids.has(SYSTEM)).toBe(true);+ expect(ids.has(TOKEN)).toBe(true);+ });++ it('returns an empty set for malformed / empty txs', () => {+ expect(txProgramIds(null).size).toBe(0);+ expect(txProgramIds({}).size).toBe(0);+ expect(txProgramIds({ transaction: { message: {} }, meta: {} }).size).toBe(0);+ });+});++describe('txInvokesPumpProgram', () => {+ it('true when the pump program is a top-level instruction', () => {+ const tx = { transaction: { message: { instructions: [{ programId: pk(PUMP_PROGRAM_ID) }] } } };+ expect(txInvokesPumpProgram(tx)).toBe(true);+ });++ it('true when the pump program is invoked via CPI (inner instruction)', () => {+ const tx = {+ transaction: { message: { instructions: [{ programId: SYSTEM }] } },+ meta: { innerInstructions: [{ index: 0, instructions: [{ programId: pk(PUMP_PROGRAM_ID) }] }] },+ };+ expect(txInvokesPumpProgram(tx)).toBe(true);+ });++ it('false when a confirmed tx only references the mint without running pump (memo/transfer)', () => {+ // mint pubkey is in accountKeys but no instruction targets the pump program.+ const tx = {+ transaction: {+ message: {+ accountKeys: [{ pubkey: pk('3wsGroundMint1111111111111111111111') }],+ instructions: [{ programId: SYSTEM }, { programId: TOKEN }],+ },+ },+ meta: { innerInstructions: [] },+ };+ expect(txInvokesPumpProgram(tx)).toBe(false);+ });++ it('false for malformed input', () => {+ expect(txInvokesPumpProgram(null)).toBe(false);+ expect(txInvokesPumpProgram({})).toBe(false);+ });+});